Coverage Report

Created: 2026-12-01 08:10

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/rust/registry/src/index.crates.io-1949cf8c6b5b557f/arrayvec-0.7.9/src/array_string.rs
Line
Count
Source
1
use std::borrow::{Borrow, BorrowMut};
2
use std::cmp;
3
use std::convert::TryFrom;
4
use std::fmt;
5
use std::hash::{Hash, Hasher};
6
use std::mem::MaybeUninit;
7
use std::ops::{Deref, DerefMut};
8
#[cfg(feature="std")]
9
use std::path::Path;
10
use std::ptr;
11
use std::slice;
12
use std::str;
13
use std::str::FromStr;
14
use std::str::Utf8Error;
15
16
use crate::CapacityError;
17
use crate::LenUint;
18
use crate::char::encode_utf8;
19
use crate::utils::MakeMaybeUninit;
20
21
#[cfg(feature="serde")]
22
use serde::{Serialize, Deserialize, Serializer, Deserializer};
23
24
25
/// A string with a fixed capacity.
26
///
27
/// The `ArrayString` is a string backed by a fixed size array. It keeps track
28
/// of its length, and is parameterized by `CAP` for the maximum capacity.
29
///
30
/// `CAP` is of type `usize` but is range limited to `u32::MAX` (or `u16` on 16-bit targets);
31
/// attempting to create larger arrayvecs with larger capacity will panic.
32
///
33
/// The string is a contiguous value that you can store directly on the stack
34
/// if needed.
35
#[derive(Copy)]
36
#[repr(C)]
37
pub struct ArrayString<const CAP: usize> {
38
    // the `len` first elements of the array are initialized
39
    len: LenUint,
40
    xs: [MaybeUninit<u8>; CAP],
41
}
42
43
impl<const CAP: usize> Default for ArrayString<CAP>
44
{
45
    /// Return an empty `ArrayString`
46
0
    fn default() -> ArrayString<CAP> {
47
0
        ArrayString::new()
48
0
    }
49
}
50
51
impl<const CAP: usize> ArrayString<CAP>
52
{
53
    /// Create a new empty `ArrayString`.
54
    ///
55
    /// Capacity is inferred from the type parameter.
56
    ///
57
    /// ```
58
    /// use arrayvec::ArrayString;
59
    ///
60
    /// let mut string = ArrayString::<16>::new();
61
    /// string.push_str("foo");
62
    /// assert_eq!(&string[..], "foo");
63
    /// assert_eq!(string.capacity(), 16);
64
    /// ```
65
0
    pub fn new() -> ArrayString<CAP> {
66
0
        assert_capacity_limit!(CAP);
67
        unsafe {
68
0
            ArrayString { xs: MaybeUninit::uninit().assume_init(), len: 0 }
69
        }
70
0
    }
71
72
    /// Create a new empty `ArrayString` (const fn).
73
    ///
74
    /// Capacity is inferred from the type parameter.
75
    ///
76
    /// ```
77
    /// use arrayvec::ArrayString;
78
    ///
79
    /// static ARRAY: ArrayString<1024> = ArrayString::new_const();
80
    /// ```
81
0
    pub const fn new_const() -> ArrayString<CAP> {
82
0
        assert_capacity_limit_const!(CAP);
83
0
        ArrayString { xs: MakeMaybeUninit::ARRAY, len: 0 }
84
0
    }
85
86
    /// Return the length of the string.
87
    #[inline]
88
0
    pub const fn len(&self) -> usize { self.len as usize }
89
90
    /// Returns whether the string is empty.
91
    #[inline]
92
0
    pub const fn is_empty(&self) -> bool { self.len() == 0 }
93
94
    /// Create a new `ArrayString` from a `str`.
95
    ///
96
    /// Capacity is inferred from the type parameter.
97
    ///
98
    /// **Errors** if the backing array is not large enough to fit the string.
99
    ///
100
    /// ```
101
    /// use arrayvec::ArrayString;
102
    ///
103
    /// let mut string = ArrayString::<3>::from("foo").unwrap();
104
    /// assert_eq!(&string[..], "foo");
105
    /// assert_eq!(string.len(), 3);
106
    /// assert_eq!(string.capacity(), 3);
107
    /// ```
108
0
    pub fn from(s: &str) -> Result<Self, CapacityError<&str>> {
109
0
        let mut arraystr = Self::new();
110
0
        arraystr.try_push_str(s)?;
111
0
        Ok(arraystr)
112
0
    }
113
114
    /// Create a new `ArrayString` from a byte string literal.
115
    ///
116
    /// **Errors** if the byte string literal is not valid UTF-8.
117
    ///
118
    /// ```
119
    /// use arrayvec::ArrayString;
120
    ///
121
    /// let string = ArrayString::from_byte_string(b"hello world").unwrap();
122
    /// ```
123
0
    pub fn from_byte_string(b: &[u8; CAP]) -> Result<Self, Utf8Error> {
124
0
        let len = str::from_utf8(b)?.len();
125
0
        debug_assert_eq!(len, CAP);
126
0
        let mut vec = Self::new();
127
0
        unsafe {
128
0
            (b as *const [u8; CAP] as *const [MaybeUninit<u8>; CAP])
129
0
                .copy_to_nonoverlapping(&mut vec.xs as *mut [MaybeUninit<u8>; CAP], 1);
130
0
            vec.set_len(CAP);
131
0
        }
132
0
        Ok(vec)
133
0
    }
134
135
    /// Create a new `ArrayString` value fully filled with ASCII NULL characters (`\0`). Useful
136
    /// to be used as a buffer to collect external data or as a buffer for intermediate processing.
137
    ///
138
    /// ```
139
    /// use arrayvec::ArrayString;
140
    ///
141
    /// let string = ArrayString::<16>::zero_filled();
142
    /// assert_eq!(string.len(), 16);
143
    /// ```
144
    #[inline]
145
0
    pub fn zero_filled() -> Self {
146
0
        assert_capacity_limit!(CAP);
147
        // SAFETY: `assert_capacity_limit` asserts that `len` won't overflow and
148
        // `zeroed` fully fills the array with nulls.
149
        unsafe {
150
0
            ArrayString {
151
0
                xs: MaybeUninit::zeroed().assume_init(),
152
0
                len: CAP as _
153
0
            }
154
        }
155
0
    }
156
157
    /// Return the capacity of the `ArrayString`.
158
    ///
159
    /// ```
160
    /// use arrayvec::ArrayString;
161
    ///
162
    /// let string = ArrayString::<3>::new();
163
    /// assert_eq!(string.capacity(), 3);
164
    /// ```
165
    #[inline(always)]
166
0
    pub const fn capacity(&self) -> usize { CAP }
167
168
    /// Return if the `ArrayString` is completely filled.
169
    ///
170
    /// ```
171
    /// use arrayvec::ArrayString;
172
    ///
173
    /// let mut string = ArrayString::<1>::new();
174
    /// assert!(!string.is_full());
175
    /// string.push_str("A");
176
    /// assert!(string.is_full());
177
    /// ```
178
0
    pub const fn is_full(&self) -> bool { self.len() == self.capacity() }
179
180
    /// Returns the capacity left in the `ArrayString`.
181
    ///
182
    /// ```
183
    /// use arrayvec::ArrayString;
184
    ///
185
    /// let mut string = ArrayString::<3>::from("abc").unwrap();
186
    /// string.pop();
187
    /// assert_eq!(string.remaining_capacity(), 1);
188
    /// ```
189
0
    pub const fn remaining_capacity(&self) -> usize {
190
0
        self.capacity() - self.len()
191
0
    }
192
193
    /// Adds the given char to the end of the string.
194
    ///
195
    /// ***Panics*** if the backing array is not large enough to fit the additional char.
196
    ///
197
    /// ```
198
    /// use arrayvec::ArrayString;
199
    ///
200
    /// let mut string = ArrayString::<2>::new();
201
    ///
202
    /// string.push('a');
203
    /// string.push('b');
204
    ///
205
    /// assert_eq!(&string[..], "ab");
206
    /// ```
207
    #[track_caller]
208
0
    pub fn push(&mut self, c: char) {
209
0
        self.try_push(c).unwrap();
210
0
    }
211
212
    /// Adds the given char to the end of the string.
213
    ///
214
    /// Returns `Ok` if the push succeeds.
215
    ///
216
    /// **Errors** if the backing array is not large enough to fit the additional char.
217
    ///
218
    /// ```
219
    /// use arrayvec::ArrayString;
220
    ///
221
    /// let mut string = ArrayString::<2>::new();
222
    ///
223
    /// string.try_push('a').unwrap();
224
    /// string.try_push('b').unwrap();
225
    /// let overflow = string.try_push('c');
226
    ///
227
    /// assert_eq!(&string[..], "ab");
228
    /// assert_eq!(overflow.unwrap_err().element(), 'c');
229
    /// ```
230
0
    pub fn try_push(&mut self, c: char) -> Result<(), CapacityError<char>> {
231
0
        let len = self.len();
232
        unsafe {
233
0
            let ptr = self.as_mut_ptr().add(len);
234
0
            let remaining_cap = self.capacity() - len;
235
0
            match encode_utf8(c, ptr, remaining_cap) {
236
0
                Ok(n) => {
237
0
                    self.set_len(len + n);
238
0
                    Ok(())
239
                }
240
0
                Err(_) => Err(CapacityError::new(c)),
241
            }
242
        }
243
0
    }
244
245
    /// Adds the given string slice to the end of the string.
246
    ///
247
    /// ***Panics*** if the backing array is not large enough to fit the string.
248
    ///
249
    /// ```
250
    /// use arrayvec::ArrayString;
251
    ///
252
    /// let mut string = ArrayString::<2>::new();
253
    ///
254
    /// string.push_str("a");
255
    /// string.push_str("d");
256
    ///
257
    /// assert_eq!(&string[..], "ad");
258
    /// ```
259
    #[track_caller]
260
0
    pub fn push_str(&mut self, s: &str) {
261
0
        self.try_push_str(s).unwrap()
262
0
    }
263
264
    /// Adds the given string slice to the end of the string.
265
    ///
266
    /// Returns `Ok` if the push succeeds.
267
    ///
268
    /// **Errors** if the backing array is not large enough to fit the string.
269
    ///
270
    /// ```
271
    /// use arrayvec::ArrayString;
272
    ///
273
    /// let mut string = ArrayString::<2>::new();
274
    ///
275
    /// string.try_push_str("a").unwrap();
276
    /// let overflow1 = string.try_push_str("bc");
277
    /// string.try_push_str("d").unwrap();
278
    /// let overflow2 = string.try_push_str("ef");
279
    ///
280
    /// assert_eq!(&string[..], "ad");
281
    /// assert_eq!(overflow1.unwrap_err().element(), "bc");
282
    /// assert_eq!(overflow2.unwrap_err().element(), "ef");
283
    /// ```
284
0
    pub fn try_push_str<'a>(&mut self, s: &'a str) -> Result<(), CapacityError<&'a str>> {
285
0
        if s.len() > self.capacity() - self.len() {
286
0
            return Err(CapacityError::new(s));
287
0
        }
288
0
        unsafe {
289
0
            let dst = self.as_mut_ptr().add(self.len());
290
0
            let src = s.as_ptr();
291
0
            ptr::copy_nonoverlapping(src, dst, s.len());
292
0
            let newl = self.len() + s.len();
293
0
            self.set_len(newl);
294
0
        }
295
0
        Ok(())
296
0
    }
297
298
    /// Removes the last character from the string and returns it.
299
    ///
300
    /// Returns `None` if this `ArrayString` is empty.
301
    ///
302
    /// ```
303
    /// use arrayvec::ArrayString;
304
    /// 
305
    /// let mut s = ArrayString::<3>::from("foo").unwrap();
306
    ///
307
    /// assert_eq!(s.pop(), Some('o'));
308
    /// assert_eq!(s.pop(), Some('o'));
309
    /// assert_eq!(s.pop(), Some('f'));
310
    ///
311
    /// assert_eq!(s.pop(), None);
312
    /// ```
313
0
    pub fn pop(&mut self) -> Option<char> {
314
0
        let ch = self.chars().next_back()?;
315
0
        let new_len = self.len() - ch.len_utf8();
316
0
        unsafe {
317
0
            self.set_len(new_len);
318
0
        }
319
0
        Some(ch)
320
0
    }
321
322
    /// Shortens this `ArrayString` to the specified length.
323
    ///
324
    /// If `new_len` is greater than the string’s current length, this has no
325
    /// effect.
326
    ///
327
    /// ***Panics*** if `new_len` does not lie on a `char` boundary.
328
    ///
329
    /// ```
330
    /// use arrayvec::ArrayString;
331
    ///
332
    /// let mut string = ArrayString::<6>::from("foobar").unwrap();
333
    /// string.truncate(3);
334
    /// assert_eq!(&string[..], "foo");
335
    /// string.truncate(4);
336
    /// assert_eq!(&string[..], "foo");
337
    /// ```
338
0
    pub fn truncate(&mut self, new_len: usize) {
339
0
        if new_len <= self.len() {
340
0
            assert!(self.is_char_boundary(new_len));
341
0
            unsafe { 
342
0
                // In libstd truncate is called on the underlying vector,
343
0
                // which in turns drops each element.
344
0
                // As we know we don't have to worry about Drop,
345
0
                // we can just set the length (a la clear.)
346
0
                self.set_len(new_len);
347
0
            }
348
0
        }
349
0
    }
350
351
    /// Removes a `char` from this `ArrayString` at a byte position and returns it.
352
    ///
353
    /// This is an `O(n)` operation, as it requires copying every element in the
354
    /// array.
355
    ///
356
    /// ***Panics*** if `idx` is larger than or equal to the `ArrayString`’s length,
357
    /// or if it does not lie on a `char` boundary.
358
    ///
359
    /// ```
360
    /// use arrayvec::ArrayString;
361
    /// 
362
    /// let mut s = ArrayString::<3>::from("foo").unwrap();
363
    ///
364
    /// assert_eq!(s.remove(0), 'f');
365
    /// assert_eq!(s.remove(1), 'o');
366
    /// assert_eq!(s.remove(0), 'o');
367
    /// ```
368
0
    pub fn remove(&mut self, idx: usize) -> char {
369
0
        let ch = match self[idx..].chars().next() {
370
0
            Some(ch) => ch,
371
0
            None => panic!("cannot remove a char from the end of a string"),
372
        };
373
374
0
        let next = idx + ch.len_utf8();
375
0
        let len = self.len();
376
0
        let ptr = self.as_mut_ptr();
377
0
        unsafe {
378
0
            ptr::copy(
379
0
                ptr.add(next),
380
0
                ptr.add(idx),
381
0
                len - next);
382
0
            self.set_len(len - (next - idx));
383
0
        }
384
0
        ch
385
0
    }
386
387
    /// Make the string empty.
388
0
    pub fn clear(&mut self) {
389
0
        unsafe {
390
0
            self.set_len(0);
391
0
        }
392
0
    }
393
394
    /// Set the strings’s length.
395
    ///
396
    /// This function is `unsafe` because it changes the notion of the
397
    /// number of “valid” bytes in the string. Use with care.
398
    ///
399
    /// This method uses *debug assertions* to check the validity of `length`
400
    /// and may use other debug assertions.
401
0
    pub unsafe fn set_len(&mut self, length: usize) {
402
        // type invariant that capacity always fits in LenUint
403
0
        debug_assert!(length <= self.capacity());
404
0
        self.len = length as LenUint;
405
0
    }
406
407
    /// Return a string slice of the whole `ArrayString`.
408
0
    pub fn as_str(&self) -> &str {
409
0
        self
410
0
    }
411
412
    /// Return a mutable string slice of the whole `ArrayString`.
413
0
    pub fn as_mut_str(&mut self) -> &mut str {
414
0
        self
415
0
    }
416
417
    /// Return a raw pointer to the string's buffer.
418
0
    pub fn as_ptr(&self) -> *const u8 {
419
0
        self.xs.as_ptr() as *const u8
420
0
    }
421
422
    /// Return a raw mutable pointer to the string's buffer.
423
0
    pub fn as_mut_ptr(&mut self) -> *mut u8 {
424
0
        self.xs.as_mut_ptr() as *mut u8
425
0
    }
426
}
427
428
impl<const CAP: usize> Deref for ArrayString<CAP>
429
{
430
    type Target = str;
431
    #[inline]
432
0
    fn deref(&self) -> &str {
433
        unsafe {
434
0
            let sl = slice::from_raw_parts(self.as_ptr(), self.len());
435
0
            str::from_utf8_unchecked(sl)
436
        }
437
0
    }
438
}
439
440
impl<const CAP: usize> DerefMut for ArrayString<CAP>
441
{
442
    #[inline]
443
0
    fn deref_mut(&mut self) -> &mut str {
444
0
        unsafe {
445
0
            let len = self.len();
446
0
            let sl = slice::from_raw_parts_mut(self.as_mut_ptr(), len);
447
0
            str::from_utf8_unchecked_mut(sl)
448
0
        }
449
0
    }
450
}
451
452
impl<const CAP: usize> PartialEq for ArrayString<CAP>
453
{
454
0
    fn eq(&self, rhs: &Self) -> bool {
455
0
        **self == **rhs
456
0
    }
457
}
458
459
impl<const CAP: usize> PartialEq<str> for ArrayString<CAP>
460
{
461
0
    fn eq(&self, rhs: &str) -> bool {
462
0
        &**self == rhs
463
0
    }
464
}
465
466
impl<const CAP: usize> PartialEq<ArrayString<CAP>> for str
467
{
468
0
    fn eq(&self, rhs: &ArrayString<CAP>) -> bool {
469
0
        self == &**rhs
470
0
    }
471
}
472
473
impl<const CAP: usize> Eq for ArrayString<CAP> 
474
{ }
475
476
impl<const CAP: usize> Hash for ArrayString<CAP>
477
{
478
0
    fn hash<H: Hasher>(&self, h: &mut H) {
479
0
        (**self).hash(h)
480
0
    }
481
}
482
483
impl<const CAP: usize> Borrow<str> for ArrayString<CAP>
484
{
485
0
    fn borrow(&self) -> &str { self }
486
}
487
488
impl<const CAP: usize> BorrowMut<str> for ArrayString<CAP>
489
{
490
0
    fn borrow_mut(&mut self) -> &mut str { self }
491
}
492
493
impl<const CAP: usize> AsRef<str> for ArrayString<CAP>
494
{
495
0
    fn as_ref(&self) -> &str { self }
496
}
497
498
impl<const CAP: usize> fmt::Debug for ArrayString<CAP>
499
{
500
0
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { (**self).fmt(f) }
501
}
502
503
#[cfg(feature="std")]
504
impl<const CAP: usize> AsRef<Path> for ArrayString<CAP> {
505
0
    fn as_ref(&self) -> &Path {
506
0
        self.as_str().as_ref()
507
0
    }
508
}
509
510
impl<const CAP: usize> fmt::Display for ArrayString<CAP>
511
{
512
0
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { (**self).fmt(f) }
513
}
514
515
/// `Write` appends written data to the end of the string.
516
impl<const CAP: usize> fmt::Write for ArrayString<CAP>
517
{
518
0
    fn write_char(&mut self, c: char) -> fmt::Result {
519
0
        self.try_push(c).map_err(|_| fmt::Error)
520
0
    }
521
522
0
    fn write_str(&mut self, s: &str) -> fmt::Result {
523
0
        self.try_push_str(s).map_err(|_| fmt::Error)
524
0
    }
525
}
526
527
impl<const CAP: usize> Clone for ArrayString<CAP>
528
{
529
0
    fn clone(&self) -> ArrayString<CAP> {
530
0
        *self
531
0
    }
532
0
    fn clone_from(&mut self, rhs: &Self) {
533
        // guaranteed to fit due to types matching.
534
0
        self.clear();
535
0
        self.try_push_str(rhs).ok();
536
0
    }
537
}
538
539
impl<const CAP: usize> PartialOrd for ArrayString<CAP>
540
{
541
0
    fn partial_cmp(&self, rhs: &Self) -> Option<cmp::Ordering> {
542
0
        (**self).partial_cmp(&**rhs)
543
0
    }
544
0
    fn lt(&self, rhs: &Self) -> bool { **self < **rhs }
545
0
    fn le(&self, rhs: &Self) -> bool { **self <= **rhs }
546
0
    fn gt(&self, rhs: &Self) -> bool { **self > **rhs }
547
0
    fn ge(&self, rhs: &Self) -> bool { **self >= **rhs }
548
}
549
550
impl<const CAP: usize> PartialOrd<str> for ArrayString<CAP>
551
{
552
0
    fn partial_cmp(&self, rhs: &str) -> Option<cmp::Ordering> {
553
0
        (**self).partial_cmp(rhs)
554
0
    }
555
0
    fn lt(&self, rhs: &str) -> bool { &**self < rhs }
556
0
    fn le(&self, rhs: &str) -> bool { &**self <= rhs }
557
0
    fn gt(&self, rhs: &str) -> bool { &**self > rhs }
558
0
    fn ge(&self, rhs: &str) -> bool { &**self >= rhs }
559
}
560
561
impl<const CAP: usize> PartialOrd<ArrayString<CAP>> for str
562
{
563
0
    fn partial_cmp(&self, rhs: &ArrayString<CAP>) -> Option<cmp::Ordering> {
564
0
        self.partial_cmp(&**rhs)
565
0
    }
566
0
    fn lt(&self, rhs: &ArrayString<CAP>) -> bool { self < &**rhs }
567
0
    fn le(&self, rhs: &ArrayString<CAP>) -> bool { self <= &**rhs }
568
0
    fn gt(&self, rhs: &ArrayString<CAP>) -> bool { self > &**rhs }
569
0
    fn ge(&self, rhs: &ArrayString<CAP>) -> bool { self >= &**rhs }
570
}
571
572
impl<const CAP: usize> Ord for ArrayString<CAP>
573
{
574
0
    fn cmp(&self, rhs: &Self) -> cmp::Ordering {
575
0
        (**self).cmp(&**rhs)
576
0
    }
577
}
578
579
impl<const CAP: usize> FromStr for ArrayString<CAP>
580
{
581
    type Err = CapacityError;
582
583
0
    fn from_str(s: &str) -> Result<Self, Self::Err> {
584
0
        Self::from(s).map_err(CapacityError::simplify)
585
0
    }
586
}
587
588
#[cfg(feature="serde")]
589
/// Requires crate feature `"serde"`
590
impl<const CAP: usize> Serialize for ArrayString<CAP>
591
{
592
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
593
        where S: Serializer
594
    {
595
        serializer.serialize_str(&*self)
596
    }
597
}
598
599
#[cfg(feature="serde")]
600
/// Requires crate feature `"serde"`
601
impl<'de, const CAP: usize> Deserialize<'de> for ArrayString<CAP> 
602
{
603
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
604
        where D: Deserializer<'de>
605
    {
606
        use serde::de::{self, Visitor};
607
        use std::marker::PhantomData;
608
609
        struct ArrayStringVisitor<const CAP: usize>(PhantomData<[u8; CAP]>);
610
611
        impl<'de, const CAP: usize> Visitor<'de> for ArrayStringVisitor<CAP> {
612
            type Value = ArrayString<CAP>;
613
614
            fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
615
                write!(formatter, "a string no more than {} bytes long", CAP)
616
            }
617
618
            fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
619
                where E: de::Error,
620
            {
621
                ArrayString::from(v).map_err(|_| E::invalid_length(v.len(), &self))
622
            }
623
624
            fn visit_bytes<E>(self, v: &[u8]) -> Result<Self::Value, E>
625
                where E: de::Error,
626
            {
627
                let s = str::from_utf8(v).map_err(|_| E::invalid_value(de::Unexpected::Bytes(v), &self))?;
628
629
                ArrayString::from(s).map_err(|_| E::invalid_length(s.len(), &self))
630
            }
631
        }
632
633
        deserializer.deserialize_str(ArrayStringVisitor(PhantomData))
634
    }
635
}
636
637
#[cfg(feature = "borsh")]
638
/// Requires crate feature `"borsh"`
639
impl<const CAP: usize> borsh::BorshSerialize for ArrayString<CAP> {
640
    fn serialize<W: borsh::io::Write>(&self, writer: &mut W) -> borsh::io::Result<()> {
641
        <str as borsh::BorshSerialize>::serialize(&*self, writer)
642
    }
643
}
644
645
#[cfg(feature = "borsh")]
646
/// Requires crate feature `"borsh"`
647
impl<const CAP: usize> borsh::BorshDeserialize for ArrayString<CAP> {
648
    fn deserialize_reader<R: borsh::io::Read>(reader: &mut R) -> borsh::io::Result<Self> {
649
        let len = <u32 as borsh::BorshDeserialize>::deserialize_reader(reader)? as usize;
650
        if len > CAP {
651
            return Err(borsh::io::Error::new(
652
                borsh::io::ErrorKind::InvalidData,
653
                format!("Expected a string no more than {} bytes long", CAP),
654
            ))
655
        }
656
657
        let mut buf = [0u8; CAP];
658
        let buf = &mut buf[..len];
659
        reader.read_exact(buf)?;
660
661
        let s = str::from_utf8(&buf).map_err(|err| {
662
            borsh::io::Error::new(borsh::io::ErrorKind::InvalidData, err.to_string())
663
        })?;
664
        Ok(Self::from(s).unwrap())
665
    }
666
}
667
668
impl<'a, const CAP: usize> TryFrom<&'a str> for ArrayString<CAP>
669
{
670
    type Error = CapacityError<&'a str>;
671
672
0
    fn try_from(f: &'a str) -> Result<Self, Self::Error> {
673
0
        let mut v = Self::new();
674
0
        v.try_push_str(f)?;
675
0
        Ok(v)
676
0
    }
677
}
678
679
impl<'a, const CAP: usize> TryFrom<fmt::Arguments<'a>> for ArrayString<CAP>
680
{
681
    type Error = CapacityError<fmt::Error>;
682
683
0
    fn try_from(f: fmt::Arguments<'a>) -> Result<Self, Self::Error> {
684
        use fmt::Write;
685
0
        let mut v = Self::new();
686
0
        v.write_fmt(f).map_err(CapacityError::new)?;
687
0
        Ok(v)
688
0
    }
689
}
690
691
#[cfg(feature = "zeroize")]
692
/// "Best efforts" zeroing of the `ArrayString`'s buffer when the `zeroize` feature is enabled.
693
///
694
/// The length is set to 0, and the buffer is dropped and zeroized.
695
/// Cannot ensure that previous moves of the `ArrayString` did not leave values on the stack.
696
///
697
/// ```
698
/// use arrayvec::ArrayString;
699
/// use zeroize::Zeroize;
700
/// let mut string = ArrayString::<6>::from("foobar").unwrap();
701
/// string.zeroize();
702
/// assert_eq!(string.len(), 0);
703
/// unsafe { string.set_len(string.capacity()) };
704
/// assert_eq!(&*string, "\0\0\0\0\0\0");
705
/// ```
706
impl<const CAP: usize> zeroize::Zeroize for ArrayString<CAP> {
707
    fn zeroize(&mut self) {
708
        // There are no elements to drop
709
        self.clear();
710
        // Zeroize the backing array.
711
        self.xs.zeroize();
712
    }
713
}