heapless/
vec.rs

1use core::{
2    cmp::Ordering, convert::TryFrom, fmt, hash, iter::FromIterator, mem::MaybeUninit, ops, ptr,
3    slice,
4};
5use hash32;
6
7/// A fixed capacity [`Vec`](https://doc.rust-lang.org/std/vec/struct.Vec.html)
8///
9/// # Examples
10///
11/// ```
12/// use heapless::Vec;
13///
14///
15/// // A vector with a fixed capacity of 8 elements allocated on the stack
16/// let mut vec = Vec::<_, 8>::new();
17/// vec.push(1);
18/// vec.push(2);
19///
20/// assert_eq!(vec.len(), 2);
21/// assert_eq!(vec[0], 1);
22///
23/// assert_eq!(vec.pop(), Some(2));
24/// assert_eq!(vec.len(), 1);
25///
26/// vec[0] = 7;
27/// assert_eq!(vec[0], 7);
28///
29/// vec.extend([1, 2, 3].iter().cloned());
30///
31/// for x in &vec {
32///     println!("{}", x);
33/// }
34/// assert_eq!(*vec, [7, 1, 2, 3]);
35/// ```
36pub struct Vec<T, const N: usize> {
37    // NOTE order is important for optimizations. the `len` first layout lets the compiler optimize
38    // `new` to: reserve stack space and zero the first word. With the fields in the reverse order
39    // the compiler optimizes `new` to `memclr`-ing the *entire* stack space, including the `buffer`
40    // field which should be left uninitialized. Optimizations were last checked with Rust 1.60
41    len: usize,
42
43    buffer: [MaybeUninit<T>; N],
44}
45
46impl<T, const N: usize> Vec<T, N> {
47    const ELEM: MaybeUninit<T> = MaybeUninit::uninit();
48    const INIT: [MaybeUninit<T>; N] = [Self::ELEM; N]; // important for optimization of `new`
49
50    /// Constructs a new, empty vector with a fixed capacity of `N`
51    ///
52    /// # Examples
53    ///
54    /// ```
55    /// use heapless::Vec;
56    ///
57    /// // allocate the vector on the stack
58    /// let mut x: Vec<u8, 16> = Vec::new();
59    ///
60    /// // allocate the vector in a static variable
61    /// static mut X: Vec<u8, 16> = Vec::new();
62    /// ```
63    /// `Vec` `const` constructor; wrap the returned value in [`Vec`](../struct.Vec.html)
64    pub const fn new() -> Self {
65        // Const assert N >= 0
66        crate::sealed::greater_than_eq_0::<N>();
67
68        Self {
69            len: 0,
70            buffer: Self::INIT,
71        }
72    }
73
74    /// Constructs a new vector with a fixed capacity of `N` and fills it
75    /// with the provided slice.
76    ///
77    /// This is equivalent to the following code:
78    ///
79    /// ```
80    /// use heapless::Vec;
81    ///
82    /// let mut v: Vec<u8, 16> = Vec::new();
83    /// v.extend_from_slice(&[1, 2, 3]).unwrap();
84    /// ```
85    #[inline]
86    pub fn from_slice(other: &[T]) -> Result<Self, ()>
87    where
88        T: Clone,
89    {
90        let mut v = Vec::new();
91        v.extend_from_slice(other)?;
92        Ok(v)
93    }
94
95    /// Clones a vec into a new vec
96    pub(crate) fn clone(&self) -> Self
97    where
98        T: Clone,
99    {
100        let mut new = Self::new();
101        // avoid `extend_from_slice` as that introduces a runtime check / panicking branch
102        for elem in self {
103            unsafe {
104                new.push_unchecked(elem.clone());
105            }
106        }
107        new
108    }
109
110    /// Returns a raw pointer to the vector’s buffer.
111    pub fn as_ptr(&self) -> *const T {
112        self.buffer.as_ptr() as *const T
113    }
114
115    /// Returns a raw pointer to the vector’s buffer, which may be mutated through.
116    pub fn as_mut_ptr(&mut self) -> *mut T {
117        self.buffer.as_mut_ptr() as *mut T
118    }
119
120    /// Extracts a slice containing the entire vector.
121    ///
122    /// Equivalent to `&s[..]`.
123    ///
124    /// # Examples
125    ///
126    /// ```
127    /// use heapless::Vec;
128    /// let buffer: Vec<u8, 5> = Vec::from_slice(&[1, 2, 3, 5, 8]).unwrap();
129    /// assert_eq!(buffer.as_slice(), &[1, 2, 3, 5, 8]);
130    /// ```
131    pub fn as_slice(&self) -> &[T] {
132        // NOTE(unsafe) avoid bound checks in the slicing operation
133        // &buffer[..self.len]
134        unsafe { slice::from_raw_parts(self.buffer.as_ptr() as *const T, self.len) }
135    }
136
137    /// Returns the contents of the vector as an array of length `M` if the length
138    /// of the vector is exactly `M`, otherwise returns `Err(self)`.
139    ///
140    /// # Examples
141    ///
142    /// ```
143    /// use heapless::Vec;
144    /// let buffer: Vec<u8, 42> = Vec::from_slice(&[1, 2, 3, 5, 8]).unwrap();
145    /// let array: [u8; 5] = buffer.into_array().unwrap();
146    /// assert_eq!(array, [1, 2, 3, 5, 8]);
147    /// ```
148    pub fn into_array<const M: usize>(self) -> Result<[T; M], Self> {
149        if self.len() == M {
150            // This is how the unstable `MaybeUninit::array_assume_init` method does it
151            let array = unsafe { (&self.buffer as *const _ as *const [T; M]).read() };
152
153            // We don't want `self`'s destructor to be called because that would drop all the
154            // items in the array
155            core::mem::forget(self);
156
157            Ok(array)
158        } else {
159            Err(self)
160        }
161    }
162
163    /// Extracts a mutable slice containing the entire vector.
164    ///
165    /// Equivalent to `&s[..]`.
166    ///
167    /// # Examples
168    ///
169    /// ```
170    /// use heapless::Vec;
171    /// let mut buffer: Vec<u8, 5> = Vec::from_slice(&[1, 2, 3, 5, 8]).unwrap();
172    /// buffer[0] = 9;
173    /// assert_eq!(buffer.as_slice(), &[9, 2, 3, 5, 8]);
174    /// ```
175    pub(crate) fn as_mut_slice(&mut self) -> &mut [T] {
176        // NOTE(unsafe) avoid bound checks in the slicing operation
177        // &mut buffer[..self.len]
178        unsafe { slice::from_raw_parts_mut(self.buffer.as_mut_ptr() as *mut T, self.len) }
179    }
180
181    /// Returns the maximum number of elements the vector can hold.
182    pub const fn capacity(&self) -> usize {
183        N
184    }
185
186    /// Clears the vector, removing all values.
187    pub fn clear(&mut self) {
188        self.truncate(0);
189    }
190
191    /// Extends the vec from an iterator.
192    ///
193    /// # Panic
194    ///
195    /// Panics if the vec cannot hold all elements of the iterator.
196    pub fn extend<I>(&mut self, iter: I)
197    where
198        I: IntoIterator<Item = T>,
199    {
200        for elem in iter {
201            self.push(elem).ok().unwrap()
202        }
203    }
204
205    /// Clones and appends all elements in a slice to the `Vec`.
206    ///
207    /// Iterates over the slice `other`, clones each element, and then appends
208    /// it to this `Vec`. The `other` vector is traversed in-order.
209    ///
210    /// # Examples
211    ///
212    /// ```
213    /// use heapless::Vec;
214    ///
215    /// let mut vec = Vec::<u8, 8>::new();
216    /// vec.push(1).unwrap();
217    /// vec.extend_from_slice(&[2, 3, 4]).unwrap();
218    /// assert_eq!(*vec, [1, 2, 3, 4]);
219    /// ```
220    pub fn extend_from_slice(&mut self, other: &[T]) -> Result<(), ()>
221    where
222        T: Clone,
223    {
224        if self.len + other.len() > self.capacity() {
225            // won't fit in the `Vec`; don't modify anything and return an error
226            Err(())
227        } else {
228            for elem in other {
229                unsafe {
230                    self.push_unchecked(elem.clone());
231                }
232            }
233            Ok(())
234        }
235    }
236
237    /// Removes the last element from a vector and returns it, or `None` if it's empty
238    pub fn pop(&mut self) -> Option<T> {
239        if self.len != 0 {
240            Some(unsafe { self.pop_unchecked() })
241        } else {
242            None
243        }
244    }
245
246    /// Appends an `item` to the back of the collection
247    ///
248    /// Returns back the `item` if the vector is full
249    pub fn push(&mut self, item: T) -> Result<(), T> {
250        if self.len < self.capacity() {
251            unsafe { self.push_unchecked(item) }
252            Ok(())
253        } else {
254            Err(item)
255        }
256    }
257
258    /// Removes the last element from a vector and returns it
259    ///
260    /// # Safety
261    ///
262    /// This assumes the vec to have at least one element.
263    pub unsafe fn pop_unchecked(&mut self) -> T {
264        debug_assert!(!self.is_empty());
265
266        self.len -= 1;
267        (self.buffer.get_unchecked_mut(self.len).as_ptr() as *const T).read()
268    }
269
270    /// Appends an `item` to the back of the collection
271    ///
272    /// # Safety
273    ///
274    /// This assumes the vec is not full.
275    pub unsafe fn push_unchecked(&mut self, item: T) {
276        // NOTE(ptr::write) the memory slot that we are about to write to is uninitialized. We
277        // use `ptr::write` to avoid running `T`'s destructor on the uninitialized memory
278        debug_assert!(!self.is_full());
279
280        *self.buffer.get_unchecked_mut(self.len) = MaybeUninit::new(item);
281
282        self.len += 1;
283    }
284
285    /// Shortens the vector, keeping the first `len` elements and dropping the rest.
286    pub fn truncate(&mut self, len: usize) {
287        // This is safe because:
288        //
289        // * the slice passed to `drop_in_place` is valid; the `len > self.len`
290        //   case avoids creating an invalid slice, and
291        // * the `len` of the vector is shrunk before calling `drop_in_place`,
292        //   such that no value will be dropped twice in case `drop_in_place`
293        //   were to panic once (if it panics twice, the program aborts).
294        unsafe {
295            // Note: It's intentional that this is `>` and not `>=`.
296            //       Changing it to `>=` has negative performance
297            //       implications in some cases. See rust-lang/rust#78884 for more.
298            if len > self.len {
299                return;
300            }
301            let remaining_len = self.len - len;
302            let s = ptr::slice_from_raw_parts_mut(self.as_mut_ptr().add(len), remaining_len);
303            self.len = len;
304            ptr::drop_in_place(s);
305        }
306    }
307
308    /// Resizes the Vec in-place so that len is equal to new_len.
309    ///
310    /// If new_len is greater than len, the Vec is extended by the
311    /// difference, with each additional slot filled with value. If
312    /// new_len is less than len, the Vec is simply truncated.
313    ///
314    /// See also [`resize_default`](struct.Vec.html#method.resize_default).
315    pub fn resize(&mut self, new_len: usize, value: T) -> Result<(), ()>
316    where
317        T: Clone,
318    {
319        if new_len > self.capacity() {
320            return Err(());
321        }
322
323        if new_len > self.len {
324            while self.len < new_len {
325                self.push(value.clone()).ok();
326            }
327        } else {
328            self.truncate(new_len);
329        }
330
331        Ok(())
332    }
333
334    /// Resizes the `Vec` in-place so that `len` is equal to `new_len`.
335    ///
336    /// If `new_len` is greater than `len`, the `Vec` is extended by the
337    /// difference, with each additional slot filled with `Default::default()`.
338    /// If `new_len` is less than `len`, the `Vec` is simply truncated.
339    ///
340    /// See also [`resize`](struct.Vec.html#method.resize).
341    pub fn resize_default(&mut self, new_len: usize) -> Result<(), ()>
342    where
343        T: Clone + Default,
344    {
345        self.resize(new_len, T::default())
346    }
347
348    /// Forces the length of the vector to `new_len`.
349    ///
350    /// This is a low-level operation that maintains none of the normal
351    /// invariants of the type. Normally changing the length of a vector
352    /// is done using one of the safe operations instead, such as
353    /// [`truncate`], [`resize`], [`extend`], or [`clear`].
354    ///
355    /// [`truncate`]: #method.truncate
356    /// [`resize`]: #method.resize
357    /// [`extend`]: https://doc.rust-lang.org/stable/core/iter/trait.Extend.html#tymethod.extend
358    /// [`clear`]: #method.clear
359    ///
360    /// # Safety
361    ///
362    /// - `new_len` must be less than or equal to [`capacity()`].
363    /// - The elements at `old_len..new_len` must be initialized.
364    ///
365    /// [`capacity()`]: #method.capacity
366    ///
367    /// # Examples
368    ///
369    /// This method can be useful for situations in which the vector
370    /// is serving as a buffer for other code, particularly over FFI:
371    ///
372    /// ```no_run
373    /// # #![allow(dead_code)]
374    /// use heapless::Vec;
375    ///
376    /// # // This is just a minimal skeleton for the doc example;
377    /// # // don't use this as a starting point for a real library.
378    /// # pub struct StreamWrapper { strm: *mut core::ffi::c_void }
379    /// # const Z_OK: i32 = 0;
380    /// # extern "C" {
381    /// #     fn deflateGetDictionary(
382    /// #         strm: *mut core::ffi::c_void,
383    /// #         dictionary: *mut u8,
384    /// #         dictLength: *mut usize,
385    /// #     ) -> i32;
386    /// # }
387    /// # impl StreamWrapper {
388    /// pub fn get_dictionary(&self) -> Option<Vec<u8, 32768>> {
389    ///     // Per the FFI method's docs, "32768 bytes is always enough".
390    ///     let mut dict = Vec::new();
391    ///     let mut dict_length = 0;
392    ///     // SAFETY: When `deflateGetDictionary` returns `Z_OK`, it holds that:
393    ///     // 1. `dict_length` elements were initialized.
394    ///     // 2. `dict_length` <= the capacity (32_768)
395    ///     // which makes `set_len` safe to call.
396    ///     unsafe {
397    ///         // Make the FFI call...
398    ///         let r = deflateGetDictionary(self.strm, dict.as_mut_ptr(), &mut dict_length);
399    ///         if r == Z_OK {
400    ///             // ...and update the length to what was initialized.
401    ///             dict.set_len(dict_length);
402    ///             Some(dict)
403    ///         } else {
404    ///             None
405    ///         }
406    ///     }
407    /// }
408    /// # }
409    /// ```
410    ///
411    /// While the following example is sound, there is a memory leak since
412    /// the inner vectors were not freed prior to the `set_len` call:
413    ///
414    /// ```
415    /// use core::iter::FromIterator;
416    /// use heapless::Vec;
417    ///
418    /// let mut vec = Vec::<Vec<u8, 3>, 3>::from_iter(
419    ///     [
420    ///         Vec::from_iter([1, 0, 0].iter().cloned()),
421    ///         Vec::from_iter([0, 1, 0].iter().cloned()),
422    ///         Vec::from_iter([0, 0, 1].iter().cloned()),
423    ///     ]
424    ///     .iter()
425    ///     .cloned()
426    /// );
427    /// // SAFETY:
428    /// // 1. `old_len..0` is empty so no elements need to be initialized.
429    /// // 2. `0 <= capacity` always holds whatever `capacity` is.
430    /// unsafe {
431    ///     vec.set_len(0);
432    /// }
433    /// ```
434    ///
435    /// Normally, here, one would use [`clear`] instead to correctly drop
436    /// the contents and thus not leak memory.
437    pub unsafe fn set_len(&mut self, new_len: usize) {
438        debug_assert!(new_len <= self.capacity());
439
440        self.len = new_len
441    }
442
443    /// Removes an element from the vector and returns it.
444    ///
445    /// The removed element is replaced by the last element of the vector.
446    ///
447    /// This does not preserve ordering, but is O(1).
448    ///
449    /// # Panics
450    ///
451    /// Panics if `index` is out of bounds.
452    ///
453    /// # Examples
454    ///
455    /// ```
456    /// use heapless::Vec;
457    ///// use heapless::consts::*;
458    ///
459    /// let mut v: Vec<_, 8> = Vec::new();
460    /// v.push("foo").unwrap();
461    /// v.push("bar").unwrap();
462    /// v.push("baz").unwrap();
463    /// v.push("qux").unwrap();
464    ///
465    /// assert_eq!(v.swap_remove(1), "bar");
466    /// assert_eq!(&*v, ["foo", "qux", "baz"]);
467    ///
468    /// assert_eq!(v.swap_remove(0), "foo");
469    /// assert_eq!(&*v, ["baz", "qux"]);
470    /// ```
471    pub fn swap_remove(&mut self, index: usize) -> T {
472        assert!(index < self.len);
473        unsafe { self.swap_remove_unchecked(index) }
474    }
475
476    /// Removes an element from the vector and returns it.
477    ///
478    /// The removed element is replaced by the last element of the vector.
479    ///
480    /// This does not preserve ordering, but is O(1).
481    ///
482    /// # Safety
483    ///
484    ///  Assumes `index` within bounds.
485    ///
486    /// # Examples
487    ///
488    /// ```
489    /// use heapless::Vec;
490    ///
491    /// let mut v: Vec<_, 8> = Vec::new();
492    /// v.push("foo").unwrap();
493    /// v.push("bar").unwrap();
494    /// v.push("baz").unwrap();
495    /// v.push("qux").unwrap();
496    ///
497    /// assert_eq!(unsafe { v.swap_remove_unchecked(1) }, "bar");
498    /// assert_eq!(&*v, ["foo", "qux", "baz"]);
499    ///
500    /// assert_eq!(unsafe { v.swap_remove_unchecked(0) }, "foo");
501    /// assert_eq!(&*v, ["baz", "qux"]);
502    /// ```
503    pub unsafe fn swap_remove_unchecked(&mut self, index: usize) -> T {
504        let length = self.len();
505        debug_assert!(index < length);
506        let value = ptr::read(self.as_ptr().add(index));
507        let base_ptr = self.as_mut_ptr();
508        ptr::copy(base_ptr.add(length - 1), base_ptr.add(index), 1);
509        self.len -= 1;
510        value
511    }
512
513    /// Returns true if the vec is full
514    #[inline]
515    pub fn is_full(&self) -> bool {
516        self.len == self.capacity()
517    }
518
519    /// Returns true if the vec is empty
520    #[inline]
521    pub fn is_empty(&self) -> bool {
522        self.len == 0
523    }
524
525    /// Returns `true` if `needle` is a prefix of the Vec.
526    ///
527    /// Always returns `true` if `needle` is an empty slice.
528    ///
529    /// # Examples
530    ///
531    /// ```
532    /// use heapless::Vec;
533    ///
534    /// let v: Vec<_, 8> = Vec::from_slice(b"abc").unwrap();
535    /// assert_eq!(v.starts_with(b""), true);
536    /// assert_eq!(v.starts_with(b"ab"), true);
537    /// assert_eq!(v.starts_with(b"bc"), false);
538    /// ```
539    #[inline]
540    pub fn starts_with(&self, needle: &[T]) -> bool
541    where
542        T: PartialEq,
543    {
544        let n = needle.len();
545        self.len >= n && needle == &self[..n]
546    }
547
548    /// Returns `true` if `needle` is a suffix of the Vec.
549    ///
550    /// Always returns `true` if `needle` is an empty slice.
551    ///
552    /// # Examples
553    ///
554    /// ```
555    /// use heapless::Vec;
556    ///
557    /// let v: Vec<_, 8> = Vec::from_slice(b"abc").unwrap();
558    /// assert_eq!(v.ends_with(b""), true);
559    /// assert_eq!(v.ends_with(b"ab"), false);
560    /// assert_eq!(v.ends_with(b"bc"), true);
561    /// ```
562    #[inline]
563    pub fn ends_with(&self, needle: &[T]) -> bool
564    where
565        T: PartialEq,
566    {
567        let (v, n) = (self.len(), needle.len());
568        v >= n && needle == &self[v - n..]
569    }
570
571    /// Inserts an element at position `index` within the vector, shifting all
572    /// elements after it to the right.
573    ///
574    /// Returns back the `element` if the vector is full.
575    ///
576    /// # Panics
577    ///
578    /// Panics if `index > len`.
579    ///
580    /// # Examples
581    ///
582    /// ```
583    /// use heapless::Vec;
584    ///
585    /// let mut vec: Vec<_, 8> = Vec::from_slice(&[1, 2, 3]).unwrap();
586    /// vec.insert(1, 4);
587    /// assert_eq!(vec, [1, 4, 2, 3]);
588    /// vec.insert(4, 5);
589    /// assert_eq!(vec, [1, 4, 2, 3, 5]);
590    /// ```
591    pub fn insert(&mut self, index: usize, element: T) -> Result<(), T> {
592        let len = self.len();
593        if index > len {
594            panic!(
595                "insertion index (is {}) should be <= len (is {})",
596                index, len
597            );
598        }
599
600        // check there's space for the new element
601        if self.is_full() {
602            return Err(element);
603        }
604
605        unsafe {
606            // infallible
607            // The spot to put the new value
608            {
609                let p = self.as_mut_ptr().add(index);
610                // Shift everything over to make space. (Duplicating the
611                // `index`th element into two consecutive places.)
612                ptr::copy(p, p.offset(1), len - index);
613                // Write it in, overwriting the first copy of the `index`th
614                // element.
615                ptr::write(p, element);
616            }
617            self.set_len(len + 1);
618        }
619
620        Ok(())
621    }
622
623    /// Removes and returns the element at position `index` within the vector,
624    /// shifting all elements after it to the left.
625    ///
626    /// Note: Because this shifts over the remaining elements, it has a
627    /// worst-case performance of *O*(*n*). If you don't need the order of
628    /// elements to be preserved, use [`swap_remove`] instead. If you'd like to
629    /// remove elements from the beginning of the `Vec`, consider using
630    /// [`Deque::pop_front`] instead.
631    ///
632    /// [`swap_remove`]: Vec::swap_remove
633    /// [`Deque::pop_front`]: crate::Deque::pop_front
634    ///
635    /// # Panics
636    ///
637    /// Panics if `index` is out of bounds.
638    ///
639    /// # Examples
640    ///
641    /// ```
642    /// use heapless::Vec;
643    ///
644    /// let mut v: Vec<_, 8> = Vec::from_slice(&[1, 2, 3]).unwrap();
645    /// assert_eq!(v.remove(1), 2);
646    /// assert_eq!(v, [1, 3]);
647    /// ```
648    pub fn remove(&mut self, index: usize) -> T {
649        let len = self.len();
650        if index >= len {
651            panic!("removal index (is {}) should be < len (is {})", index, len);
652        }
653        unsafe {
654            // infallible
655            let ret;
656            {
657                // the place we are taking from.
658                let ptr = self.as_mut_ptr().add(index);
659                // copy it out, unsafely having a copy of the value on
660                // the stack and in the vector at the same time.
661                ret = ptr::read(ptr);
662
663                // Shift everything down to fill in that spot.
664                ptr::copy(ptr.offset(1), ptr, len - index - 1);
665            }
666            self.set_len(len - 1);
667            ret
668        }
669    }
670
671    /// Retains only the elements specified by the predicate.
672    ///
673    /// In other words, remove all elements `e` for which `f(&e)` returns `false`.
674    /// This method operates in place, visiting each element exactly once in the
675    /// original order, and preserves the order of the retained elements.
676    ///
677    /// # Examples
678    ///
679    /// ```
680    /// use heapless::Vec;
681    ///
682    /// let mut vec: Vec<_, 8> = Vec::from_slice(&[1, 2, 3, 4]).unwrap();
683    /// vec.retain(|&x| x % 2 == 0);
684    /// assert_eq!(vec, [2, 4]);
685    /// ```
686    ///
687    /// Because the elements are visited exactly once in the original order,
688    /// external state may be used to decide which elements to keep.
689    ///
690    /// ```
691    /// use heapless::Vec;
692    ///
693    /// let mut vec: Vec<_, 8> = Vec::from_slice(&[1, 2, 3, 4, 5]).unwrap();
694    /// let keep = [false, true, true, false, true];
695    /// let mut iter = keep.iter();
696    /// vec.retain(|_| *iter.next().unwrap());
697    /// assert_eq!(vec, [2, 3, 5]);
698    /// ```
699    pub fn retain<F>(&mut self, mut f: F)
700    where
701        F: FnMut(&T) -> bool,
702    {
703        self.retain_mut(|elem| f(elem));
704    }
705
706    /// Retains only the elements specified by the predicate, passing a mutable reference to it.
707    ///
708    /// In other words, remove all elements `e` such that `f(&mut e)` returns `false`.
709    /// This method operates in place, visiting each element exactly once in the
710    /// original order, and preserves the order of the retained elements.
711    ///
712    /// # Examples
713    ///
714    /// ```
715    /// use heapless::Vec;
716    ///
717    /// let mut vec: Vec<_, 8> = Vec::from_slice(&[1, 2, 3, 4]).unwrap();
718    /// vec.retain_mut(|x| if *x <= 3 {
719    ///     *x += 1;
720    ///     true
721    /// } else {
722    ///     false
723    /// });
724    /// assert_eq!(vec, [2, 3, 4]);
725    /// ```
726    pub fn retain_mut<F>(&mut self, mut f: F)
727    where
728        F: FnMut(&mut T) -> bool,
729    {
730        let original_len = self.len();
731        // Avoid double drop if the drop guard is not executed,
732        // since we may make some holes during the process.
733        unsafe { self.set_len(0) };
734
735        // Vec: [Kept, Kept, Hole, Hole, Hole, Hole, Unchecked, Unchecked]
736        //      |<-              processed len   ->| ^- next to check
737        //                  |<-  deleted cnt     ->|
738        //      |<-              original_len                          ->|
739        // Kept: Elements which predicate returns true on.
740        // Hole: Moved or dropped element slot.
741        // Unchecked: Unchecked valid elements.
742        //
743        // This drop guard will be invoked when predicate or `drop` of element panicked.
744        // It shifts unchecked elements to cover holes and `set_len` to the correct length.
745        // In cases when predicate and `drop` never panick, it will be optimized out.
746        struct BackshiftOnDrop<'a, T, const N: usize> {
747            v: &'a mut Vec<T, N>,
748            processed_len: usize,
749            deleted_cnt: usize,
750            original_len: usize,
751        }
752
753        impl<T, const N: usize> Drop for BackshiftOnDrop<'_, T, N> {
754            fn drop(&mut self) {
755                if self.deleted_cnt > 0 {
756                    // SAFETY: Trailing unchecked items must be valid since we never touch them.
757                    unsafe {
758                        ptr::copy(
759                            self.v.as_ptr().add(self.processed_len),
760                            self.v
761                                .as_mut_ptr()
762                                .add(self.processed_len - self.deleted_cnt),
763                            self.original_len - self.processed_len,
764                        );
765                    }
766                }
767                // SAFETY: After filling holes, all items are in contiguous memory.
768                unsafe {
769                    self.v.set_len(self.original_len - self.deleted_cnt);
770                }
771            }
772        }
773
774        let mut g = BackshiftOnDrop {
775            v: self,
776            processed_len: 0,
777            deleted_cnt: 0,
778            original_len,
779        };
780
781        fn process_loop<F, T, const N: usize, const DELETED: bool>(
782            original_len: usize,
783            f: &mut F,
784            g: &mut BackshiftOnDrop<'_, T, N>,
785        ) where
786            F: FnMut(&mut T) -> bool,
787        {
788            while g.processed_len != original_len {
789                let p = g.v.as_mut_ptr();
790                // SAFETY: Unchecked element must be valid.
791                let cur = unsafe { &mut *p.add(g.processed_len) };
792                if !f(cur) {
793                    // Advance early to avoid double drop if `drop_in_place` panicked.
794                    g.processed_len += 1;
795                    g.deleted_cnt += 1;
796                    // SAFETY: We never touch this element again after dropped.
797                    unsafe { ptr::drop_in_place(cur) };
798                    // We already advanced the counter.
799                    if DELETED {
800                        continue;
801                    } else {
802                        break;
803                    }
804                }
805                if DELETED {
806                    // SAFETY: `deleted_cnt` > 0, so the hole slot must not overlap with current element.
807                    // We use copy for move, and never touch this element again.
808                    unsafe {
809                        let hole_slot = p.add(g.processed_len - g.deleted_cnt);
810                        ptr::copy_nonoverlapping(cur, hole_slot, 1);
811                    }
812                }
813                g.processed_len += 1;
814            }
815        }
816
817        // Stage 1: Nothing was deleted.
818        process_loop::<F, T, N, false>(original_len, &mut f, &mut g);
819
820        // Stage 2: Some elements were deleted.
821        process_loop::<F, T, N, true>(original_len, &mut f, &mut g);
822
823        // All item are processed. This can be optimized to `set_len` by LLVM.
824        drop(g);
825    }
826}
827
828// Trait implementations
829
830impl<T, const N: usize> Default for Vec<T, N> {
831    fn default() -> Self {
832        Self::new()
833    }
834}
835
836impl<T, const N: usize> fmt::Debug for Vec<T, N>
837where
838    T: fmt::Debug,
839{
840    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
841        <[T] as fmt::Debug>::fmt(self, f)
842    }
843}
844
845impl<const N: usize> fmt::Write for Vec<u8, N> {
846    fn write_str(&mut self, s: &str) -> fmt::Result {
847        match self.extend_from_slice(s.as_bytes()) {
848            Ok(()) => Ok(()),
849            Err(_) => Err(fmt::Error),
850        }
851    }
852}
853
854impl<T, const N: usize> Drop for Vec<T, N> {
855    fn drop(&mut self) {
856        // We drop each element used in the vector by turning into a &mut[T]
857        unsafe {
858            ptr::drop_in_place(self.as_mut_slice());
859        }
860    }
861}
862
863impl<'a, T: Clone, const N: usize> TryFrom<&'a [T]> for Vec<T, N> {
864    type Error = ();
865
866    fn try_from(slice: &'a [T]) -> Result<Self, Self::Error> {
867        Vec::from_slice(slice)
868    }
869}
870
871impl<T, const N: usize> Extend<T> for Vec<T, N> {
872    fn extend<I>(&mut self, iter: I)
873    where
874        I: IntoIterator<Item = T>,
875    {
876        self.extend(iter)
877    }
878}
879
880impl<'a, T, const N: usize> Extend<&'a T> for Vec<T, N>
881where
882    T: 'a + Copy,
883{
884    fn extend<I>(&mut self, iter: I)
885    where
886        I: IntoIterator<Item = &'a T>,
887    {
888        self.extend(iter.into_iter().cloned())
889    }
890}
891
892impl<T, const N: usize> hash::Hash for Vec<T, N>
893where
894    T: core::hash::Hash,
895{
896    fn hash<H: hash::Hasher>(&self, state: &mut H) {
897        <[T] as hash::Hash>::hash(self, state)
898    }
899}
900
901impl<T, const N: usize> hash32::Hash for Vec<T, N>
902where
903    T: hash32::Hash,
904{
905    fn hash<H: hash32::Hasher>(&self, state: &mut H) {
906        <[T] as hash32::Hash>::hash(self, state)
907    }
908}
909
910impl<'a, T, const N: usize> IntoIterator for &'a Vec<T, N> {
911    type Item = &'a T;
912    type IntoIter = slice::Iter<'a, T>;
913
914    fn into_iter(self) -> Self::IntoIter {
915        self.iter()
916    }
917}
918
919impl<'a, T, const N: usize> IntoIterator for &'a mut Vec<T, N> {
920    type Item = &'a mut T;
921    type IntoIter = slice::IterMut<'a, T>;
922
923    fn into_iter(self) -> Self::IntoIter {
924        self.iter_mut()
925    }
926}
927
928impl<T, const N: usize> FromIterator<T> for Vec<T, N> {
929    fn from_iter<I>(iter: I) -> Self
930    where
931        I: IntoIterator<Item = T>,
932    {
933        let mut vec = Vec::new();
934        for i in iter {
935            vec.push(i).ok().expect("Vec::from_iter overflow");
936        }
937        vec
938    }
939}
940
941/// An iterator that moves out of an [`Vec`][`Vec`].
942///
943/// This struct is created by calling the `into_iter` method on [`Vec`][`Vec`].
944///
945/// [`Vec`]: (https://doc.rust-lang.org/std/vec/struct.Vec.html)
946///
947pub struct IntoIter<T, const N: usize> {
948    vec: Vec<T, N>,
949    next: usize,
950}
951
952impl<T, const N: usize> Iterator for IntoIter<T, N> {
953    type Item = T;
954    fn next(&mut self) -> Option<Self::Item> {
955        if self.next < self.vec.len() {
956            let item = unsafe {
957                (self.vec.buffer.get_unchecked_mut(self.next).as_ptr() as *const T).read()
958            };
959            self.next += 1;
960            Some(item)
961        } else {
962            None
963        }
964    }
965}
966
967impl<T, const N: usize> Clone for IntoIter<T, N>
968where
969    T: Clone,
970{
971    fn clone(&self) -> Self {
972        let mut vec = Vec::new();
973
974        if self.next < self.vec.len() {
975            let s = unsafe {
976                slice::from_raw_parts(
977                    (self.vec.buffer.as_ptr() as *const T).add(self.next),
978                    self.vec.len() - self.next,
979                )
980            };
981            vec.extend_from_slice(s).ok();
982        }
983
984        Self { vec, next: 0 }
985    }
986}
987
988impl<T, const N: usize> Drop for IntoIter<T, N> {
989    fn drop(&mut self) {
990        unsafe {
991            // Drop all the elements that have not been moved out of vec
992            ptr::drop_in_place(&mut self.vec.as_mut_slice()[self.next..]);
993            // Prevent dropping of other elements
994            self.vec.len = 0;
995        }
996    }
997}
998
999impl<T, const N: usize> IntoIterator for Vec<T, N> {
1000    type Item = T;
1001    type IntoIter = IntoIter<T, N>;
1002
1003    fn into_iter(self) -> Self::IntoIter {
1004        IntoIter { vec: self, next: 0 }
1005    }
1006}
1007
1008impl<A, B, const N1: usize, const N2: usize> PartialEq<Vec<B, N2>> for Vec<A, N1>
1009where
1010    A: PartialEq<B>,
1011{
1012    fn eq(&self, other: &Vec<B, N2>) -> bool {
1013        <[A]>::eq(self, &**other)
1014    }
1015}
1016
1017// Vec<A, N> == [B]
1018impl<A, B, const N: usize> PartialEq<[B]> for Vec<A, N>
1019where
1020    A: PartialEq<B>,
1021{
1022    fn eq(&self, other: &[B]) -> bool {
1023        <[A]>::eq(self, &other[..])
1024    }
1025}
1026
1027// [B] == Vec<A, N>
1028impl<A, B, const N: usize> PartialEq<Vec<A, N>> for [B]
1029where
1030    A: PartialEq<B>,
1031{
1032    fn eq(&self, other: &Vec<A, N>) -> bool {
1033        <[A]>::eq(other, &self[..])
1034    }
1035}
1036
1037// Vec<A, N> == &[B]
1038impl<A, B, const N: usize> PartialEq<&[B]> for Vec<A, N>
1039where
1040    A: PartialEq<B>,
1041{
1042    fn eq(&self, other: &&[B]) -> bool {
1043        <[A]>::eq(self, &other[..])
1044    }
1045}
1046
1047// &[B] == Vec<A, N>
1048impl<A, B, const N: usize> PartialEq<Vec<A, N>> for &[B]
1049where
1050    A: PartialEq<B>,
1051{
1052    fn eq(&self, other: &Vec<A, N>) -> bool {
1053        <[A]>::eq(other, &self[..])
1054    }
1055}
1056
1057// Vec<A, N> == &mut [B]
1058impl<A, B, const N: usize> PartialEq<&mut [B]> for Vec<A, N>
1059where
1060    A: PartialEq<B>,
1061{
1062    fn eq(&self, other: &&mut [B]) -> bool {
1063        <[A]>::eq(self, &other[..])
1064    }
1065}
1066
1067// &mut [B] == Vec<A, N>
1068impl<A, B, const N: usize> PartialEq<Vec<A, N>> for &mut [B]
1069where
1070    A: PartialEq<B>,
1071{
1072    fn eq(&self, other: &Vec<A, N>) -> bool {
1073        <[A]>::eq(other, &self[..])
1074    }
1075}
1076
1077// Vec<A, N> == [B; M]
1078// Equality does not require equal capacity
1079impl<A, B, const N: usize, const M: usize> PartialEq<[B; M]> for Vec<A, N>
1080where
1081    A: PartialEq<B>,
1082{
1083    fn eq(&self, other: &[B; M]) -> bool {
1084        <[A]>::eq(self, &other[..])
1085    }
1086}
1087
1088// [B; M] == Vec<A, N>
1089// Equality does not require equal capacity
1090impl<A, B, const N: usize, const M: usize> PartialEq<Vec<A, N>> for [B; M]
1091where
1092    A: PartialEq<B>,
1093{
1094    fn eq(&self, other: &Vec<A, N>) -> bool {
1095        <[A]>::eq(other, &self[..])
1096    }
1097}
1098
1099// Vec<A, N> == &[B; M]
1100// Equality does not require equal capacity
1101impl<A, B, const N: usize, const M: usize> PartialEq<&[B; M]> for Vec<A, N>
1102where
1103    A: PartialEq<B>,
1104{
1105    fn eq(&self, other: &&[B; M]) -> bool {
1106        <[A]>::eq(self, &other[..])
1107    }
1108}
1109
1110// &[B; M] == Vec<A, N>
1111// Equality does not require equal capacity
1112impl<A, B, const N: usize, const M: usize> PartialEq<Vec<A, N>> for &[B; M]
1113where
1114    A: PartialEq<B>,
1115{
1116    fn eq(&self, other: &Vec<A, N>) -> bool {
1117        <[A]>::eq(other, &self[..])
1118    }
1119}
1120
1121// Implements Eq if underlying data is Eq
1122impl<T, const N: usize> Eq for Vec<T, N> where T: Eq {}
1123
1124impl<T, const N1: usize, const N2: usize> PartialOrd<Vec<T, N2>> for Vec<T, N1>
1125where
1126    T: PartialOrd,
1127{
1128    fn partial_cmp(&self, other: &Vec<T, N2>) -> Option<Ordering> {
1129        PartialOrd::partial_cmp(&**self, &**other)
1130    }
1131}
1132
1133impl<T, const N: usize> Ord for Vec<T, N>
1134where
1135    T: Ord,
1136{
1137    #[inline]
1138    fn cmp(&self, other: &Self) -> Ordering {
1139        Ord::cmp(&**self, &**other)
1140    }
1141}
1142
1143impl<T, const N: usize> ops::Deref for Vec<T, N> {
1144    type Target = [T];
1145
1146    fn deref(&self) -> &[T] {
1147        self.as_slice()
1148    }
1149}
1150
1151impl<T, const N: usize> ops::DerefMut for Vec<T, N> {
1152    fn deref_mut(&mut self) -> &mut [T] {
1153        self.as_mut_slice()
1154    }
1155}
1156
1157impl<T, const N: usize> AsRef<Vec<T, N>> for Vec<T, N> {
1158    #[inline]
1159    fn as_ref(&self) -> &Self {
1160        self
1161    }
1162}
1163
1164impl<T, const N: usize> AsMut<Vec<T, N>> for Vec<T, N> {
1165    #[inline]
1166    fn as_mut(&mut self) -> &mut Self {
1167        self
1168    }
1169}
1170
1171impl<T, const N: usize> AsRef<[T]> for Vec<T, N> {
1172    #[inline]
1173    fn as_ref(&self) -> &[T] {
1174        self
1175    }
1176}
1177
1178impl<T, const N: usize> AsMut<[T]> for Vec<T, N> {
1179    #[inline]
1180    fn as_mut(&mut self) -> &mut [T] {
1181        self
1182    }
1183}
1184
1185impl<T, const N: usize> Clone for Vec<T, N>
1186where
1187    T: Clone,
1188{
1189    fn clone(&self) -> Self {
1190        self.clone()
1191    }
1192}
1193
1194#[cfg(test)]
1195mod tests {
1196    use crate::Vec;
1197    use core::fmt::Write;
1198
1199    #[test]
1200    fn static_new() {
1201        static mut _V: Vec<i32, 4> = Vec::new();
1202    }
1203
1204    #[test]
1205    fn stack_new() {
1206        let mut _v: Vec<i32, 4> = Vec::new();
1207    }
1208
1209    #[test]
1210    fn is_full_empty() {
1211        let mut v: Vec<i32, 4> = Vec::new();
1212
1213        assert!(v.is_empty());
1214        assert!(!v.is_full());
1215
1216        v.push(1).unwrap();
1217        assert!(!v.is_empty());
1218        assert!(!v.is_full());
1219
1220        v.push(1).unwrap();
1221        assert!(!v.is_empty());
1222        assert!(!v.is_full());
1223
1224        v.push(1).unwrap();
1225        assert!(!v.is_empty());
1226        assert!(!v.is_full());
1227
1228        v.push(1).unwrap();
1229        assert!(!v.is_empty());
1230        assert!(v.is_full());
1231    }
1232
1233    #[test]
1234    fn drop() {
1235        droppable!();
1236
1237        {
1238            let mut v: Vec<Droppable, 2> = Vec::new();
1239            v.push(Droppable::new()).ok().unwrap();
1240            v.push(Droppable::new()).ok().unwrap();
1241            v.pop().unwrap();
1242        }
1243
1244        assert_eq!(Droppable::count(), 0);
1245
1246        {
1247            let mut v: Vec<Droppable, 2> = Vec::new();
1248            v.push(Droppable::new()).ok().unwrap();
1249            v.push(Droppable::new()).ok().unwrap();
1250        }
1251
1252        assert_eq!(Droppable::count(), 0);
1253    }
1254
1255    #[test]
1256    fn eq() {
1257        let mut xs: Vec<i32, 4> = Vec::new();
1258        let mut ys: Vec<i32, 8> = Vec::new();
1259
1260        assert_eq!(xs, ys);
1261
1262        xs.push(1).unwrap();
1263        ys.push(1).unwrap();
1264
1265        assert_eq!(xs, ys);
1266    }
1267
1268    #[test]
1269    fn cmp() {
1270        let mut xs: Vec<i32, 4> = Vec::new();
1271        let mut ys: Vec<i32, 4> = Vec::new();
1272
1273        assert_eq!(xs, ys);
1274
1275        xs.push(1).unwrap();
1276        ys.push(2).unwrap();
1277
1278        assert!(xs < ys);
1279    }
1280
1281    #[test]
1282    fn cmp_heterogenous_size() {
1283        let mut xs: Vec<i32, 4> = Vec::new();
1284        let mut ys: Vec<i32, 8> = Vec::new();
1285
1286        assert_eq!(xs, ys);
1287
1288        xs.push(1).unwrap();
1289        ys.push(2).unwrap();
1290
1291        assert!(xs < ys);
1292    }
1293
1294    #[test]
1295    fn cmp_with_arrays_and_slices() {
1296        let mut xs: Vec<i32, 12> = Vec::new();
1297        xs.push(1).unwrap();
1298
1299        let array = [1];
1300
1301        assert_eq!(xs, array);
1302        assert_eq!(array, xs);
1303
1304        assert_eq!(xs, array.as_slice());
1305        assert_eq!(array.as_slice(), xs);
1306
1307        assert_eq!(xs, &array);
1308        assert_eq!(&array, xs);
1309
1310        let longer_array = [1; 20];
1311
1312        assert_ne!(xs, longer_array);
1313        assert_ne!(longer_array, xs);
1314    }
1315
1316    #[test]
1317    fn full() {
1318        let mut v: Vec<i32, 4> = Vec::new();
1319
1320        v.push(0).unwrap();
1321        v.push(1).unwrap();
1322        v.push(2).unwrap();
1323        v.push(3).unwrap();
1324
1325        assert!(v.push(4).is_err());
1326    }
1327
1328    #[test]
1329    fn iter() {
1330        let mut v: Vec<i32, 4> = Vec::new();
1331
1332        v.push(0).unwrap();
1333        v.push(1).unwrap();
1334        v.push(2).unwrap();
1335        v.push(3).unwrap();
1336
1337        let mut items = v.iter();
1338
1339        assert_eq!(items.next(), Some(&0));
1340        assert_eq!(items.next(), Some(&1));
1341        assert_eq!(items.next(), Some(&2));
1342        assert_eq!(items.next(), Some(&3));
1343        assert_eq!(items.next(), None);
1344    }
1345
1346    #[test]
1347    fn iter_mut() {
1348        let mut v: Vec<i32, 4> = Vec::new();
1349
1350        v.push(0).unwrap();
1351        v.push(1).unwrap();
1352        v.push(2).unwrap();
1353        v.push(3).unwrap();
1354
1355        let mut items = v.iter_mut();
1356
1357        assert_eq!(items.next(), Some(&mut 0));
1358        assert_eq!(items.next(), Some(&mut 1));
1359        assert_eq!(items.next(), Some(&mut 2));
1360        assert_eq!(items.next(), Some(&mut 3));
1361        assert_eq!(items.next(), None);
1362    }
1363
1364    #[test]
1365    fn collect_from_iter() {
1366        let slice = &[1, 2, 3];
1367        let vec: Vec<i32, 4> = slice.iter().cloned().collect();
1368        assert_eq!(&vec, slice);
1369    }
1370
1371    #[test]
1372    #[should_panic]
1373    fn collect_from_iter_overfull() {
1374        let slice = &[1, 2, 3];
1375        let _vec = slice.iter().cloned().collect::<Vec<_, 2>>();
1376    }
1377
1378    #[test]
1379    fn iter_move() {
1380        let mut v: Vec<i32, 4> = Vec::new();
1381        v.push(0).unwrap();
1382        v.push(1).unwrap();
1383        v.push(2).unwrap();
1384        v.push(3).unwrap();
1385
1386        let mut items = v.into_iter();
1387
1388        assert_eq!(items.next(), Some(0));
1389        assert_eq!(items.next(), Some(1));
1390        assert_eq!(items.next(), Some(2));
1391        assert_eq!(items.next(), Some(3));
1392        assert_eq!(items.next(), None);
1393    }
1394
1395    #[test]
1396    fn iter_move_drop() {
1397        droppable!();
1398
1399        {
1400            let mut vec: Vec<Droppable, 2> = Vec::new();
1401            vec.push(Droppable::new()).ok().unwrap();
1402            vec.push(Droppable::new()).ok().unwrap();
1403            let mut items = vec.into_iter();
1404            // Move all
1405            let _ = items.next();
1406            let _ = items.next();
1407        }
1408
1409        assert_eq!(Droppable::count(), 0);
1410
1411        {
1412            let mut vec: Vec<Droppable, 2> = Vec::new();
1413            vec.push(Droppable::new()).ok().unwrap();
1414            vec.push(Droppable::new()).ok().unwrap();
1415            let _items = vec.into_iter();
1416            // Move none
1417        }
1418
1419        assert_eq!(Droppable::count(), 0);
1420
1421        {
1422            let mut vec: Vec<Droppable, 2> = Vec::new();
1423            vec.push(Droppable::new()).ok().unwrap();
1424            vec.push(Droppable::new()).ok().unwrap();
1425            let mut items = vec.into_iter();
1426            let _ = items.next(); // Move partly
1427        }
1428
1429        assert_eq!(Droppable::count(), 0);
1430    }
1431
1432    #[test]
1433    fn push_and_pop() {
1434        let mut v: Vec<i32, 4> = Vec::new();
1435        assert_eq!(v.len(), 0);
1436
1437        assert_eq!(v.pop(), None);
1438        assert_eq!(v.len(), 0);
1439
1440        v.push(0).unwrap();
1441        assert_eq!(v.len(), 1);
1442
1443        assert_eq!(v.pop(), Some(0));
1444        assert_eq!(v.len(), 0);
1445
1446        assert_eq!(v.pop(), None);
1447        assert_eq!(v.len(), 0);
1448    }
1449
1450    #[test]
1451    fn resize_size_limit() {
1452        let mut v: Vec<u8, 4> = Vec::new();
1453
1454        v.resize(0, 0).unwrap();
1455        v.resize(4, 0).unwrap();
1456        v.resize(5, 0).err().expect("full");
1457    }
1458
1459    #[test]
1460    fn resize_length_cases() {
1461        let mut v: Vec<u8, 4> = Vec::new();
1462
1463        assert_eq!(v.len(), 0);
1464
1465        // Grow by 1
1466        v.resize(1, 0).unwrap();
1467        assert_eq!(v.len(), 1);
1468
1469        // Grow by 2
1470        v.resize(3, 0).unwrap();
1471        assert_eq!(v.len(), 3);
1472
1473        // Resize to current size
1474        v.resize(3, 0).unwrap();
1475        assert_eq!(v.len(), 3);
1476
1477        // Shrink by 1
1478        v.resize(2, 0).unwrap();
1479        assert_eq!(v.len(), 2);
1480
1481        // Shrink by 2
1482        v.resize(0, 0).unwrap();
1483        assert_eq!(v.len(), 0);
1484    }
1485
1486    #[test]
1487    fn resize_contents() {
1488        let mut v: Vec<u8, 4> = Vec::new();
1489
1490        // New entries take supplied value when growing
1491        v.resize(1, 17).unwrap();
1492        assert_eq!(v[0], 17);
1493
1494        // Old values aren't changed when growing
1495        v.resize(2, 18).unwrap();
1496        assert_eq!(v[0], 17);
1497        assert_eq!(v[1], 18);
1498
1499        // Old values aren't changed when length unchanged
1500        v.resize(2, 0).unwrap();
1501        assert_eq!(v[0], 17);
1502        assert_eq!(v[1], 18);
1503
1504        // Old values aren't changed when shrinking
1505        v.resize(1, 0).unwrap();
1506        assert_eq!(v[0], 17);
1507    }
1508
1509    #[test]
1510    fn resize_default() {
1511        let mut v: Vec<u8, 4> = Vec::new();
1512
1513        // resize_default is implemented using resize, so just check the
1514        // correct value is being written.
1515        v.resize_default(1).unwrap();
1516        assert_eq!(v[0], 0);
1517    }
1518
1519    #[test]
1520    fn write() {
1521        let mut v: Vec<u8, 4> = Vec::new();
1522        write!(v, "{:x}", 1234).unwrap();
1523        assert_eq!(&v[..], b"4d2");
1524    }
1525
1526    #[test]
1527    fn extend_from_slice() {
1528        let mut v: Vec<u8, 4> = Vec::new();
1529        assert_eq!(v.len(), 0);
1530        v.extend_from_slice(&[1, 2]).unwrap();
1531        assert_eq!(v.len(), 2);
1532        assert_eq!(v.as_slice(), &[1, 2]);
1533        v.extend_from_slice(&[3]).unwrap();
1534        assert_eq!(v.len(), 3);
1535        assert_eq!(v.as_slice(), &[1, 2, 3]);
1536        assert!(v.extend_from_slice(&[4, 5]).is_err());
1537        assert_eq!(v.len(), 3);
1538        assert_eq!(v.as_slice(), &[1, 2, 3]);
1539    }
1540
1541    #[test]
1542    fn from_slice() {
1543        // Successful construction
1544        let v: Vec<u8, 4> = Vec::from_slice(&[1, 2, 3]).unwrap();
1545        assert_eq!(v.len(), 3);
1546        assert_eq!(v.as_slice(), &[1, 2, 3]);
1547
1548        // Slice too large
1549        assert!(Vec::<u8, 2>::from_slice(&[1, 2, 3]).is_err());
1550    }
1551
1552    #[test]
1553    fn starts_with() {
1554        let v: Vec<_, 8> = Vec::from_slice(b"ab").unwrap();
1555        assert!(v.starts_with(&[]));
1556        assert!(v.starts_with(b""));
1557        assert!(v.starts_with(b"a"));
1558        assert!(v.starts_with(b"ab"));
1559        assert!(!v.starts_with(b"abc"));
1560        assert!(!v.starts_with(b"ba"));
1561        assert!(!v.starts_with(b"b"));
1562    }
1563
1564    #[test]
1565    fn ends_with() {
1566        let v: Vec<_, 8> = Vec::from_slice(b"ab").unwrap();
1567        assert!(v.ends_with(&[]));
1568        assert!(v.ends_with(b""));
1569        assert!(v.ends_with(b"b"));
1570        assert!(v.ends_with(b"ab"));
1571        assert!(!v.ends_with(b"abc"));
1572        assert!(!v.ends_with(b"ba"));
1573        assert!(!v.ends_with(b"a"));
1574    }
1575
1576    #[test]
1577    fn zero_capacity() {
1578        let mut v: Vec<u8, 0> = Vec::new();
1579        // Validate capacity
1580        assert_eq!(v.capacity(), 0);
1581
1582        // Make sure there is no capacity
1583        assert!(v.push(1).is_err());
1584
1585        // Validate length
1586        assert_eq!(v.len(), 0);
1587
1588        // Validate pop
1589        assert_eq!(v.pop(), None);
1590
1591        // Validate slice
1592        assert_eq!(v.as_slice(), &[]);
1593
1594        // Validate empty
1595        assert!(v.is_empty());
1596
1597        // Validate full
1598        assert!(v.is_full());
1599    }
1600}