stackvector/
lib.rs

1//! Vector-like class allocated entirely on the stack.
2//!
3//! Shallow wrapper around an underlying `Array`, which panics if the
4//! array bounds are exceeded.
5//!
6//! # no_std support
7//!
8//! By default, `smallvec` depends on `libstd`. However, it can be configured to use the unstable
9//! `liballoc` API instead, for use on platforms that have `liballoc` but not `libstd`.  This
10//! configuration is currently unstable and is not guaranteed to work on all versions of Rust.
11//!
12//! To depend on `smallvec` without `libstd`, use `default-features = false` in the `smallvec`
13//! section of Cargo.toml to disable its `"std"` feature.
14//!
15//! Adapted from Servo's smallvec:
16//!     https://github.com/servo/rust-smallve
17//!
18//! StackVec is distributed under the same terms as the smallvec and
19//! lexical, that is, it is dual licensed under either the MIT or Apache
20//! 2.0 license.
21
22#![cfg_attr(not(feature = "std"), no_std)]
23
24#[cfg(all(test, not(feature = "std")))]
25#[macro_use]
26extern crate alloc;
27
28#[cfg(all(not(test), not(feature = "std")))]
29extern crate alloc;
30
31#[cfg(not(feature = "std"))]
32use alloc::vec::Vec;
33
34extern crate unreachable;
35use unreachable::UncheckedOptionExt;
36
37/// Facade around the core features for name mangling.
38pub(crate) mod lib {
39    #[cfg(feature = "std")]
40    pub(crate) use std::*;
41
42    #[cfg(not(feature = "std"))]
43    pub(crate) use core::*;
44
45    #[cfg(all(test, not(feature = "std")))]
46    pub(crate) use alloc::{borrow, boxed, rc};
47}
48
49use lib::borrow::{Borrow, BorrowMut};
50use lib::{cmp, fmt, hash, iter, mem, ops, ptr, slice};
51
52#[cfg(feature = "std")]
53use lib::io;
54
55// POINTER METHODS
56
57// Certain pointer methods aren't implemented below Rustc versions 1.26.
58// We implement a dummy version here.
59
60trait PointerMethods {
61    // Add to the pointer (use padd to avoid conflict with ptr::add).
62    unsafe fn padd(self, count: usize) -> Self;
63}
64
65impl<T> PointerMethods for *const T {
66    #[inline(always)]
67    unsafe fn padd(self, count: usize) -> Self {
68        #[cfg(has_pointer_methods)]
69        return self.add(count);
70
71        #[cfg(not(has_pointer_methods))]
72        return self.offset(count as isize);
73    }
74}
75
76impl<T> PointerMethods for *mut T {
77    #[inline(always)]
78    unsafe fn padd(self, count: usize) -> Self {
79        #[cfg(has_pointer_methods)]
80        return self.add(count);
81
82        #[cfg(not(has_pointer_methods))]
83        return self.offset(count as isize);
84    }
85}
86
87// ARRAY
88
89/// Types that can be used as the backing store for a StackVec
90pub unsafe trait Array {
91    /// The type of the array's elements.
92    type Item;
93    /// Returns the number of items the array can hold.
94    fn size() -> usize;
95    /// Returns a pointer to the first element of the array.
96    fn ptr(&self) -> *const Self::Item;
97    /// Returns a mutable pointer to the first element of the array.
98    fn ptr_mut(&mut self) -> *mut Self::Item;
99}
100
101macro_rules! impl_array(
102    ($($size:expr),+) => {
103        $(
104            unsafe impl<T> Array for [T; $size] {
105                type Item = T;
106                fn size() -> usize { $size }
107                fn ptr(&self) -> *const T { self.as_ptr() }
108                fn ptr_mut(&mut self) -> *mut T { self.as_mut_ptr() }
109            }
110        )+
111    }
112);
113
114impl_array! { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 20, 24, 32, 36, 0x40, 0x80, 0x100, 0x200, 0x400, 0x800, 0x1000, 0x2000, 0x4000, 0x8000, 0x10000, 0x20000, 0x40000, 0x80000, 0x100000 }
115
116// VEC LIKE
117
118/// Common operations implemented by both `Vec` and `StackVec`.
119///
120/// This can be used to write generic code that works with both `Vec` and `StackVec`.
121///
122/// ## Example
123///
124/// ```rust
125/// use stackvector::{VecLike, StackVec};
126///
127/// fn initialize<V: VecLike<u8>>(v: &mut V) {
128///     for i in 0..5 {
129///         v.push(i);
130///     }
131/// }
132///
133/// let mut vec = Vec::new();
134/// initialize(&mut vec);
135///
136/// let mut stack_vec = StackVec::<[u8; 8]>::new();
137/// initialize(&mut stack_vec);
138/// ```
139pub trait VecLike<T>:
140    ops::Index<usize, Output = T>
141    + ops::IndexMut<usize>
142    + ops::Index<ops::Range<usize>, Output = [T]>
143    + ops::IndexMut<ops::Range<usize>>
144    + ops::Index<ops::RangeFrom<usize>, Output = [T]>
145    + ops::IndexMut<ops::RangeFrom<usize>>
146    + ops::Index<ops::RangeTo<usize>, Output = [T]>
147    + ops::IndexMut<ops::RangeTo<usize>>
148    + ops::Index<ops::RangeFull, Output = [T]>
149    + ops::IndexMut<ops::RangeFull>
150    + ops::DerefMut<Target = [T]>
151    + Extend<T>
152{
153    /// Append an element to the vector.
154    fn push(&mut self, value: T);
155
156    /// Pop an element from the end of the vector.
157    fn pop(&mut self) -> Option<T>;
158}
159
160#[allow(deprecated)]
161impl<T> VecLike<T> for Vec<T> {
162    #[inline]
163    fn push(&mut self, value: T) {
164        Vec::push(self, value);
165    }
166
167    #[inline]
168    fn pop(&mut self) -> Option<T> {
169        Vec::pop(self)
170    }
171}
172
173// EXTEND FROM SLICE
174
175/// Trait to be implemented by a collection that can be extended from a slice
176///
177/// ## Example
178///
179/// ```rust
180/// use stackvector::{ExtendFromSlice, StackVec};
181///
182/// fn initialize<V: ExtendFromSlice<u8>>(v: &mut V) {
183///     v.extend_from_slice(b"Test!");
184/// }
185///
186/// let mut vec = Vec::new();
187/// initialize(&mut vec);
188/// assert_eq!(&vec, b"Test!");
189///
190/// let mut stack_vec = StackVec::<[u8; 8]>::new();
191/// initialize(&mut stack_vec);
192/// assert_eq!(&stack_vec as &[_], b"Test!");
193/// ```
194pub trait ExtendFromSlice<T> {
195    /// Extends a collection from a slice of its element type
196    fn extend_from_slice(&mut self, other: &[T]);
197}
198
199impl<T: Clone> ExtendFromSlice<T> for Vec<T> {
200    fn extend_from_slice(&mut self, other: &[T]) {
201        Vec::extend_from_slice(self, other)
202    }
203}
204
205// DRAIN
206
207/// An iterator that removes the items from a `StackVec` and yields them by value.
208///
209/// Returned from [`StackVec::drain`][1].
210///
211/// [1]: struct.StackVec.html#method.drain
212pub struct Drain<'a, T: 'a> {
213    iter: slice::IterMut<'a, T>,
214}
215
216impl<'a, T: 'a> Iterator for Drain<'a, T> {
217    type Item = T;
218
219    #[inline]
220    fn next(&mut self) -> Option<T> {
221        self.iter
222            .next()
223            .map(|reference| unsafe { ptr::read(reference) })
224    }
225
226    #[inline]
227    fn size_hint(&self) -> (usize, Option<usize>) {
228        self.iter.size_hint()
229    }
230}
231
232impl<'a, T: 'a> DoubleEndedIterator for Drain<'a, T> {
233    #[inline]
234    fn next_back(&mut self) -> Option<T> {
235        self.iter
236            .next_back()
237            .map(|reference| unsafe { ptr::read(reference) })
238    }
239}
240
241impl<'a, T> ExactSizeIterator for Drain<'a, T> {}
242
243impl<'a, T: 'a> Drop for Drain<'a, T> {
244    fn drop(&mut self) {
245        // Destroy the remaining elements.
246        for _ in self.by_ref() {}
247    }
248}
249
250// SET LEN ON DROP
251
252/// Set the length of the vec when the `SetLenOnDrop` value goes out of scope.
253///
254/// Copied from https://github.com/rust-lang/rust/pull/36355
255struct SetLenOnDrop<'a> {
256    len: &'a mut usize,
257    local_len: usize,
258}
259
260impl<'a> SetLenOnDrop<'a> {
261    #[inline]
262    fn new(len: &'a mut usize) -> Self {
263        SetLenOnDrop {
264            local_len: *len,
265            len: len,
266        }
267    }
268
269    #[inline]
270    fn increment_len(&mut self, increment: usize) {
271        self.local_len += increment;
272    }
273}
274
275impl<'a> Drop for SetLenOnDrop<'a> {
276    #[inline]
277    fn drop(&mut self) {
278        *self.len = self.local_len;
279    }
280}
281
282struct DropOnPanic<T> {
283    start: *mut T,
284    skip: ops::Range<usize>,
285    len: usize,
286}
287
288impl<T> Drop for DropOnPanic<T> {
289    fn drop(&mut self) {
290        for i in 0..self.len {
291            if !self.skip.contains(&i) {
292                unsafe {
293                    ptr::drop_in_place(self.start.add(i));
294                }
295            }
296        }
297    }
298}
299
300// STACKVEC
301
302/// A `Vec`-like container that stores elements on the stack.
303///
304/// The amount of data that a `StackVec` can store inline depends on its backing store. The backing
305/// store can be any type that implements the `Array` trait; usually it is a small fixed-sized
306/// array.  For example a `StackVec<[u64; 8]>` can hold up to eight 64-bit integers inline.
307///
308/// ## Example
309///
310/// ```rust,should_panic
311/// use stackvector::StackVec;
312/// let mut v = StackVec::<[u8; 4]>::new(); // initialize an empty vector
313///
314/// // The vector can hold up to 4 items without spilling onto the heap.
315/// v.extend(0..4);
316/// assert_eq!(v.len(), 4);
317///
318/// // Pushing another element will force the buffer to spill and panic:
319/// v.push(4);
320/// ```
321pub struct StackVec<A: Array> {
322    // The capacity field is used for iteration and other optimizations.
323    // Publicly expose the fields, so they may be used in constant
324    // initialization.
325    pub data: mem::MaybeUninit<A>,
326    pub length: usize,
327}
328
329impl<A: Array> StackVec<A> {
330    /// Construct an empty vector
331    #[inline]
332    pub fn new() -> StackVec<A> {
333        StackVec {
334            length: 0,
335            data: mem::MaybeUninit::uninit(),
336        }
337    }
338
339    /// Construct a new `StackVec` from a `Vec<A::Item>`.
340    ///
341    /// Elements will be copied to the inline buffer if vec.len() <= A::size().
342    ///
343    /// ```rust
344    /// use stackvector::StackVec;
345    ///
346    /// let vec = vec![1, 2, 3, 4, 5];
347    /// let stack_vec: StackVec<[_; 5]> = StackVec::from_vec(vec);
348    ///
349    /// assert_eq!(&*stack_vec, &[1, 2, 3, 4, 5]);
350    /// ```
351    #[inline]
352    pub fn from_vec(vec: Vec<A::Item>) -> StackVec<A> {
353        assert!(vec.len() <= A::size());
354        unsafe { Self::from_vec_unchecked(vec) }
355    }
356
357    /// Construct a new `StackVec` from a `Vec<A::Item>` without bounds checking.
358    #[allow(deprecated)]
359    pub unsafe fn from_vec_unchecked(mut vec: Vec<A::Item>) -> StackVec<A> {
360        let mut data: A = mem::uninitialized();
361        let len = vec.len();
362        vec.set_len(0);
363        ptr::copy_nonoverlapping(vec.as_ptr(), data.ptr_mut(), len);
364
365        StackVec {
366            length: len,
367            data: mem::MaybeUninit::new(data),
368        }
369    }
370
371    /// Constructs a new `StackVec` on the stack from an `A` without
372    /// copying elements.
373    ///
374    /// ```rust
375    /// use stackvector::StackVec;
376    ///
377    /// let buf = [1, 2, 3, 4, 5];
378    /// let stack_vec: StackVec<_> = StackVec::from_buf(buf);
379    ///
380    /// assert_eq!(&*stack_vec, &[1, 2, 3, 4, 5]);
381    /// ```
382    #[inline]
383    pub fn from_buf(buf: A) -> StackVec<A> {
384        StackVec {
385            length: A::size(),
386            data: mem::MaybeUninit::new(buf),
387        }
388    }
389
390    /// Constructs a new `StackVec` on the stack from an `A` without
391    /// copying elements. Also sets the length, which must be less or
392    /// equal to the size of `buf`.
393    ///
394    /// ```rust
395    /// use stackvector::StackVec;
396    ///
397    /// let buf = [1, 2, 3, 4, 5, 0, 0, 0];
398    /// let stack_vec: StackVec<_> = StackVec::from_buf_and_len(buf, 5);
399    ///
400    /// assert_eq!(&*stack_vec, &[1, 2, 3, 4, 5]);
401    /// ```
402    #[inline]
403    pub fn from_buf_and_len(buf: A, len: usize) -> StackVec<A> {
404        assert!(len <= A::size());
405        unsafe { StackVec::from_buf_and_len_unchecked(buf, len) }
406    }
407
408    /// Constructs a new `StackVec` on the stack from an `A` without
409    /// copying elements. Also sets the length. The user is responsible
410    /// for ensuring that `len <= A::size()`.
411    ///
412    /// ```rust
413    /// use stackvector::StackVec;
414    ///
415    /// let buf = [1, 2, 3, 4, 5, 0, 0, 0];
416    /// let stack_vec: StackVec<_> = unsafe {
417    ///     StackVec::from_buf_and_len_unchecked(buf, 5)
418    /// };
419    ///
420    /// assert_eq!(&*stack_vec, &[1, 2, 3, 4, 5]);
421    /// ```
422    #[inline]
423    pub unsafe fn from_buf_and_len_unchecked(buf: A, len: usize) -> StackVec<A> {
424        StackVec {
425            length: len,
426            data: mem::MaybeUninit::new(buf),
427        }
428    }
429
430    /// Sets the length of a vector.
431    ///
432    /// This will explicitly set the size of the vector, without actually
433    /// modifying its buffers, so it is up to the caller to ensure that the
434    /// vector is actually the specified size.
435    #[inline]
436    pub unsafe fn set_len(&mut self, new_len: usize) {
437        self.length = new_len;
438    }
439
440    /// The number of elements stored in the vector.
441    #[inline]
442    pub fn len(&self) -> usize {
443        self.length
444    }
445
446    /// If the vector is empty.
447    #[inline]
448    pub fn is_empty(&self) -> bool {
449        self.len() == 0
450    }
451
452    /// The number of items the vector can hold.
453    #[inline]
454    pub fn capacity(&self) -> usize {
455        A::size()
456    }
457
458    /// Empty the vector and return an iterator over its former contents.
459    pub fn drain(&mut self) -> Drain<A::Item> {
460        unsafe {
461            let slice = slice::from_raw_parts_mut(self.as_mut_ptr(), self.len());
462            self.set_len(0);
463
464            Drain {
465                iter: slice.iter_mut(),
466            }
467        }
468    }
469
470    /// Append an item to the vector.
471    #[inline]
472    pub fn push(&mut self, value: A::Item) {
473        assert!(self.len() < self.capacity());
474        unsafe {
475            ptr::write(self.as_mut_ptr().padd(self.length), value);
476            self.length += 1;
477        }
478    }
479
480    /// Remove an item from the end of the vector and return it, or None if empty.
481    #[inline]
482    pub fn pop(&mut self) -> Option<A::Item> {
483        unsafe {
484            if self.len() == 0 {
485                None
486            } else {
487                self.length -= 1;
488                Some(ptr::read(self.as_mut_ptr().padd(self.length)))
489            }
490        }
491    }
492
493    /// Shorten the vector, keeping the first `len` elements and dropping the rest.
494    ///
495    /// If `len` is greater than or equal to the vector's current length, this has no
496    /// effect.
497    /// `shrink_to_fit` after truncating.
498    pub fn truncate(&mut self, len: usize) {
499        unsafe {
500            while len < self.length {
501                self.length -= 1;
502                ptr::drop_in_place(self.as_mut_ptr().padd(self.length));
503            }
504        }
505    }
506
507    /// Extracts a slice containing the entire vector.
508    ///
509    /// Equivalent to `&s[..]`.
510    #[inline]
511    pub fn as_slice(&self) -> &[A::Item] {
512        self
513    }
514
515    /// Extracts a mutable slice of the entire vector.
516    ///
517    /// Equivalent to `&mut s[..]`.
518    #[inline]
519    pub fn as_mut_slice(&mut self) -> &mut [A::Item] {
520        self
521    }
522
523    /// Remove the element at position `index`, replacing it with the last element.
524    ///
525    /// This does not preserve ordering, but is O(1).
526    ///
527    /// Panics if `index` is out of bounds.
528    #[inline]
529    pub fn swap_remove(&mut self, index: usize) -> A::Item {
530        let len = self.len();
531        self.swap(len - 1, index);
532        unsafe { self.pop().unchecked_unwrap() }
533    }
534
535    /// Remove all elements from the vector.
536    #[inline]
537    pub fn clear(&mut self) {
538        self.truncate(0);
539    }
540
541    /// Remove and return the element at position `index`, shifting all elements after it to the
542    /// left.
543    ///
544    /// Panics if `index` is out of bounds.
545    pub fn remove(&mut self, index: usize) -> A::Item {
546        assert!(index < self.len());
547        unsafe {
548            self.length -= 1;
549            let ptr = self.as_mut_ptr().padd(index);
550            let item = ptr::read(ptr);
551            ptr::copy(ptr.offset(1), ptr, self.length - index);
552            item
553        }
554    }
555
556    /// Insert an element at position `index`, shifting all elements after it to the right.
557    ///
558    /// Panics if `index` is out of bounds.
559    pub fn insert(&mut self, index: usize, element: A::Item) {
560        assert!(index < self.len() && self.len() < self.capacity());
561        unsafe {
562            let ptr = self.as_mut_ptr().padd(index);
563            ptr::copy(ptr, ptr.offset(1), self.length - index);
564            ptr::write(ptr, element);
565            self.length += 1;
566        }
567    }
568
569    /// Insert multiple elements at position `index`, shifting all following elements toward the
570    /// back.
571    pub fn insert_many<I: iter::IntoIterator<Item = A::Item>>(
572        &mut self,
573        index: usize,
574        iterable: I,
575    ) {
576        let mut iter = iterable.into_iter();
577        if index == self.len() {
578            return self.extend(iter);
579        }
580
581        let (lower_size_bound, _) = iter.size_hint();
582        assert!(lower_size_bound <= lib::isize::MAX as usize); // Ensure offset is indexable
583        assert!(index + lower_size_bound >= index); // Protect against overflow
584        assert!(self.len() + lower_size_bound <= self.capacity());
585
586        let mut num_added = 0;
587        let old_len = self.len();
588        assert!(index <= old_len);
589
590
591        unsafe {
592            let start = self.as_mut_ptr();
593            let ptr = start.add(index);
594
595            // Move the trailing elements.
596            ptr::copy(ptr, ptr.padd(lower_size_bound), old_len - index);
597
598            // In case the iterator panics, don't double-drop the items we just copied above.
599            self.set_len(0);
600            let mut guard = DropOnPanic {
601                start,
602                skip: index..(index + lower_size_bound),
603                len: old_len + lower_size_bound,
604            };
605
606            while num_added < lower_size_bound {
607                let element = match iter.next() {
608                    Some(x) => x,
609                    None => break,
610                };
611                let cur = ptr.add(num_added);
612                ptr::write(cur, element);
613                guard.skip.start += 1;
614                num_added += 1;
615            }
616
617            if num_added < lower_size_bound {
618                // Iterator provided fewer elements than the hint. Move the tail backward.
619                ptr::copy(
620                    ptr.add(lower_size_bound),
621                    ptr.add(num_added),
622                    old_len - index,
623                );
624            }
625            // There are no more duplicate or uninitialized slots, so the guard is not needed.
626            self.set_len(old_len + num_added);
627            mem::forget(guard);
628
629            // Insert any remaining elements one-by-one.
630            for element in iter {
631                self.insert(index + num_added, element);
632                num_added += 1;
633            }
634        }
635    }
636
637    /// Convert a StackVec to a Vec.
638    pub fn into_vec(self) -> Vec<A::Item> {
639        self.into_iter().collect()
640    }
641
642    /// Convert the StackVec into an `A`.
643    pub fn into_inner(self) -> Result<A, Self> {
644        if self.len() != A::size() {
645            Err(self)
646        } else {
647            unsafe {
648                let this = mem::ManuallyDrop::new(self);
649                let array = ptr::read(this.as_ptr() as *const A);
650                Ok(array)
651            }
652        }
653    }
654
655    /// Retains only the elements specified by the predicate.
656    ///
657    /// In other words, remove all elements `e` such that `f(&e)` returns `false`.
658    /// This method operates in place and preserves the order of the retained
659    /// elements.
660    pub fn retain<F: FnMut(&mut A::Item) -> bool>(&mut self, mut f: F) {
661        let mut del = 0;
662        let len = self.len();
663        for i in 0..len {
664            if !f(&mut self[i]) {
665                del += 1;
666            } else if del > 0 {
667                self.swap(i - del, i);
668            }
669        }
670        self.truncate(len - del);
671    }
672
673    /// Removes consecutive duplicate elements.
674    pub fn dedup(&mut self)
675    where
676        A::Item: PartialEq<A::Item>,
677    {
678        self.dedup_by(|a, b| a == b);
679    }
680
681    /// Removes consecutive duplicate elements using the given equality relation.
682    pub fn dedup_by<F>(&mut self, mut same_bucket: F)
683    where
684        F: FnMut(&mut A::Item, &mut A::Item) -> bool,
685    {
686        // See the implementation of Vec::dedup_by in the
687        // standard library for an explanation of this algorithm.
688        let len = self.len();
689        if len <= 1 {
690            return;
691        }
692
693        let ptr = self.as_mut_ptr();
694        let mut w: usize = 1;
695
696        unsafe {
697            for r in 1..len {
698                let p_r = ptr.offset(r as isize);
699                let p_wm1 = ptr.offset((w - 1) as isize);
700                if !same_bucket(&mut *p_r, &mut *p_wm1) {
701                    if r != w {
702                        let p_w = p_wm1.offset(1);
703                        mem::swap(&mut *p_r, &mut *p_w);
704                    }
705                    w += 1;
706                }
707            }
708        }
709
710        self.truncate(w);
711    }
712
713    /// Removes consecutive elements that map to the same key.
714    pub fn dedup_by_key<F, K>(&mut self, mut key: F)
715    where
716        F: FnMut(&mut A::Item) -> K,
717        K: PartialEq<K>,
718    {
719        self.dedup_by(|a, b| key(a) == key(b));
720    }
721}
722
723impl<A: Array> StackVec<A>
724where
725    A::Item: Copy,
726{
727    /// Copy the elements from a slice into a new `StackVec`.
728    ///
729    /// For slices of `Copy` types, this is more efficient than `StackVec::from(slice)`.
730    pub fn from_slice(slice: &[A::Item]) -> Self {
731        assert!(slice.len() <= A::size());
732        StackVec {
733            length: slice.len(),
734            data: unsafe {
735                let mut data: mem::MaybeUninit<A> = mem::MaybeUninit::uninit();
736                let ptr = data.as_mut_ptr() as *mut A::Item;
737                ptr::copy_nonoverlapping(slice.as_ptr(), ptr, slice.len());
738                data
739            },
740        }
741    }
742
743    /// Copy elements from a slice into the vector at position `index`, shifting any following
744    /// elements toward the back.
745    ///
746    /// For slices of `Copy` types, this is more efficient than `insert`.
747    pub fn insert_from_slice(&mut self, index: usize, slice: &[A::Item]) {
748        assert!(index <= self.len() && self.len() + slice.len() <= self.capacity());
749        unsafe {
750            let len = self.len();
751            let slice_ptr = slice.as_ptr();
752            let ptr = self.as_mut_ptr().padd(index);
753            ptr::copy(ptr, ptr.padd(slice.len()), len - index);
754            ptr::copy_nonoverlapping(slice_ptr, ptr, slice.len());
755            self.set_len(len + slice.len());
756        }
757    }
758
759    /// Copy elements from a slice and append them to the vector.
760    ///
761    /// For slices of `Copy` types, this is more efficient than `extend`.
762    #[inline]
763    pub fn extend_from_slice(&mut self, slice: &[A::Item]) {
764        let len = self.len();
765        self.insert_from_slice(len, slice);
766    }
767}
768
769impl<A: Array> StackVec<A>
770where
771    A::Item: Clone,
772{
773    /// Resizes the vector so that its length is equal to `len`.
774    ///
775    /// If `len` is less than the current length, the vector simply truncated.
776    ///
777    /// If `len` is greater than the current length, `value` is appended to the
778    /// vector until its length equals `len`.
779    pub fn resize(&mut self, len: usize, value: A::Item) {
780        assert!(len <= self.capacity());
781        let old_len = self.len();
782        if len > old_len {
783            self.extend(iter::repeat(value).take(len - old_len));
784        } else {
785            self.truncate(len);
786        }
787    }
788
789    /// Creates a `StackVec` with `n` copies of `elem`.
790    /// ```
791    /// use stackvector::StackVec;
792    ///
793    /// let v = StackVec::<[char; 128]>::from_elem('d', 2);
794    /// assert_eq!(v, StackVec::from_buf(['d', 'd']));
795    /// ```
796    pub fn from_elem(elem: A::Item, n: usize) -> Self {
797        assert!(n <= A::size());
798        let mut v = StackVec::<A>::new();
799        unsafe {
800            let ptr = v.as_mut_ptr();
801            let mut local_len = SetLenOnDrop::new(&mut v.length);
802            for i in 0..n as isize {
803                ptr::write(ptr.offset(i), elem.clone());
804                local_len.increment_len(1);
805            }
806        }
807        v
808    }
809}
810
811impl<A: Array> ops::Deref for StackVec<A> {
812    type Target = [A::Item];
813    #[inline]
814    fn deref(&self) -> &[A::Item] {
815        unsafe {
816            let ptr = self.data.as_ptr() as *const A::Item;
817            slice::from_raw_parts(ptr, self.len())
818        }
819    }
820}
821
822impl<A: Array> ops::DerefMut for StackVec<A> {
823    #[inline]
824    fn deref_mut(&mut self) -> &mut [A::Item] {
825        unsafe {
826            let ptr = self.data.as_mut_ptr() as *mut A::Item;
827            slice::from_raw_parts_mut(ptr, self.len())
828        }
829    }
830}
831
832impl<A: Array> AsRef<[A::Item]> for StackVec<A> {
833    #[inline]
834    fn as_ref(&self) -> &[A::Item] {
835        self
836    }
837}
838
839impl<A: Array> AsMut<[A::Item]> for StackVec<A> {
840    #[inline]
841    fn as_mut(&mut self) -> &mut [A::Item] {
842        self
843    }
844}
845
846impl<A: Array> Borrow<[A::Item]> for StackVec<A> {
847    #[inline]
848    fn borrow(&self) -> &[A::Item] {
849        self
850    }
851}
852
853impl<A: Array> BorrowMut<[A::Item]> for StackVec<A> {
854    #[inline]
855    fn borrow_mut(&mut self) -> &mut [A::Item] {
856        self
857    }
858}
859
860#[cfg(feature = "std")]
861impl<A: Array<Item = u8>> io::Write for StackVec<A> {
862    #[inline]
863    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
864        self.extend_from_slice(buf);
865        Ok(buf.len())
866    }
867
868    #[inline]
869    fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
870        self.extend_from_slice(buf);
871        Ok(())
872    }
873
874    #[inline]
875    fn flush(&mut self) -> io::Result<()> {
876        Ok(())
877    }
878}
879
880impl<'a, A: Array> From<&'a [A::Item]> for StackVec<A>
881where
882    A::Item: Clone,
883{
884    #[inline]
885    fn from(slice: &'a [A::Item]) -> StackVec<A> {
886        slice.into_iter().cloned().collect()
887    }
888}
889
890impl<A: Array> From<Vec<A::Item>> for StackVec<A> {
891    #[inline]
892    fn from(vec: Vec<A::Item>) -> StackVec<A> {
893        StackVec::from_vec(vec)
894    }
895}
896
897impl<A: Array> From<A> for StackVec<A> {
898    #[inline]
899    fn from(array: A) -> StackVec<A> {
900        StackVec::from_buf(array)
901    }
902}
903
904macro_rules! impl_index {
905    ($index_type: ty, $output_type: ty) => {
906        impl<A: Array> ops::Index<$index_type> for StackVec<A> {
907            type Output = $output_type;
908            #[inline]
909            fn index(&self, index: $index_type) -> &$output_type {
910                &(&**self)[index]
911            }
912        }
913
914        impl<A: Array> ops::IndexMut<$index_type> for StackVec<A> {
915            #[inline]
916            fn index_mut(&mut self, index: $index_type) -> &mut $output_type {
917                &mut (&mut **self)[index]
918            }
919        }
920    };
921}
922
923impl_index!(usize, A::Item);
924impl_index!(ops::Range<usize>, [A::Item]);
925impl_index!(ops::RangeFrom<usize>, [A::Item]);
926impl_index!(ops::RangeFull, [A::Item]);
927impl_index!(ops::RangeTo<usize>, [A::Item]);
928
929#[cfg(has_range_inclusive)]
930impl_index!(ops::RangeInclusive<usize>, [A::Item]);
931
932#[cfg(has_range_inclusive)]
933impl_index!(ops::RangeToInclusive<usize>, [A::Item]);
934
935impl<A: Array> ExtendFromSlice<A::Item> for StackVec<A>
936where
937    A::Item: Copy,
938{
939    fn extend_from_slice(&mut self, other: &[A::Item]) {
940        StackVec::extend_from_slice(self, other)
941    }
942}
943
944impl<A: Array> VecLike<A::Item> for StackVec<A> {
945    #[inline]
946    fn push(&mut self, value: A::Item) {
947        StackVec::push(self, value);
948    }
949
950    #[inline]
951    fn pop(&mut self) -> Option<A::Item> {
952        StackVec::pop(self)
953    }
954}
955
956impl<A: Array> iter::FromIterator<A::Item> for StackVec<A> {
957    fn from_iter<I: iter::IntoIterator<Item = A::Item>>(iterable: I) -> StackVec<A> {
958        let mut v = StackVec::new();
959        v.extend(iterable);
960        v
961    }
962}
963
964impl<A: Array> Extend<A::Item> for StackVec<A> {
965    fn extend<I: iter::IntoIterator<Item = A::Item>>(&mut self, iterable: I) {
966        // size_hint() has no safety guarantees, and TrustedLen
967        // is nightly only, so we can't do any optimizations with
968        // size_hint.
969        for elem in iterable.into_iter() {
970            self.push(elem);
971        }
972    }
973}
974
975impl<A: Array> fmt::Debug for StackVec<A>
976where
977    A::Item: fmt::Debug,
978{
979    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
980        f.debug_list().entries(self.iter()).finish()
981    }
982}
983
984impl<A: Array> Default for StackVec<A> {
985    #[inline]
986    fn default() -> StackVec<A> {
987        StackVec::new()
988    }
989}
990
991impl<A: Array> Drop for StackVec<A> {
992    fn drop(&mut self) {
993        unsafe {
994            ptr::drop_in_place(&mut self[..]);
995        }
996    }
997}
998
999impl<A: Array> Clone for StackVec<A>
1000where
1001    A::Item: Clone,
1002{
1003    fn clone(&self) -> StackVec<A> {
1004        let mut new_vector = StackVec::new();
1005        for element in self.iter() {
1006            new_vector.push(element.clone())
1007        }
1008        new_vector
1009    }
1010}
1011
1012impl<A: Array, B: Array> PartialEq<StackVec<B>> for StackVec<A>
1013where
1014    A::Item: PartialEq<B::Item>,
1015{
1016    #[inline]
1017    fn eq(&self, other: &StackVec<B>) -> bool {
1018        self[..] == other[..]
1019    }
1020
1021    #[inline]
1022    fn ne(&self, other: &StackVec<B>) -> bool {
1023        self[..] != other[..]
1024    }
1025}
1026
1027impl<A: Array> Eq for StackVec<A> where A::Item: Eq {}
1028
1029impl<A: Array> PartialOrd for StackVec<A>
1030where
1031    A::Item: PartialOrd,
1032{
1033    #[inline]
1034    fn partial_cmp(&self, other: &StackVec<A>) -> Option<cmp::Ordering> {
1035        PartialOrd::partial_cmp(&**self, &**other)
1036    }
1037}
1038
1039impl<A: Array> Ord for StackVec<A>
1040where
1041    A::Item: Ord,
1042{
1043    #[inline]
1044    fn cmp(&self, other: &StackVec<A>) -> cmp::Ordering {
1045        Ord::cmp(&**self, &**other)
1046    }
1047}
1048
1049impl<A: Array> hash::Hash for StackVec<A>
1050where
1051    A::Item: hash::Hash,
1052{
1053    fn hash<H: hash::Hasher>(&self, state: &mut H) {
1054        (**self).hash(state)
1055    }
1056}
1057
1058unsafe impl<A: Array> Send for StackVec<A> where A::Item: Send {}
1059
1060/// An iterator that consumes a `StackVec` and yields its items by value.
1061///
1062/// Returned from [`StackVec::into_iter`][1].
1063///
1064/// [1]: struct.StackVec.html#method.into_iter
1065pub struct IntoIter<A: Array> {
1066    data: StackVec<A>,
1067    current: usize,
1068    end: usize,
1069}
1070
1071impl<A: Array> Drop for IntoIter<A> {
1072    fn drop(&mut self) {
1073        for _ in self {}
1074    }
1075}
1076
1077impl<A: Array> Iterator for IntoIter<A> {
1078    type Item = A::Item;
1079
1080    #[inline]
1081    fn next(&mut self) -> Option<A::Item> {
1082        if self.current == self.end {
1083            None
1084        } else {
1085            unsafe {
1086                let current = self.current;
1087                self.current += 1;
1088                Some(ptr::read(self.data.as_ptr().padd(current)))
1089            }
1090        }
1091    }
1092
1093    #[inline]
1094    fn size_hint(&self) -> (usize, Option<usize>) {
1095        let size = self.end - self.current;
1096        (size, Some(size))
1097    }
1098}
1099
1100impl<A: Array> DoubleEndedIterator for IntoIter<A> {
1101    #[inline]
1102    fn next_back(&mut self) -> Option<A::Item> {
1103        if self.current == self.end {
1104            None
1105        } else {
1106            unsafe {
1107                self.end -= 1;
1108                Some(ptr::read(self.data.as_ptr().padd(self.end)))
1109            }
1110        }
1111    }
1112}
1113
1114impl<A: Array> ExactSizeIterator for IntoIter<A> {}
1115
1116impl<A: Array> IntoIterator for StackVec<A> {
1117    type IntoIter = IntoIter<A>;
1118    type Item = A::Item;
1119    fn into_iter(mut self) -> Self::IntoIter {
1120        unsafe {
1121            // Set StackVec len to zero as `IntoIter` drop handles dropping of the elements
1122            let len = self.len();
1123            self.set_len(0);
1124            IntoIter {
1125                data: self,
1126                current: 0,
1127                end: len,
1128            }
1129        }
1130    }
1131}
1132
1133impl<'a, A: Array> IntoIterator for &'a StackVec<A> {
1134    type IntoIter = slice::Iter<'a, A::Item>;
1135    type Item = &'a A::Item;
1136    fn into_iter(self) -> Self::IntoIter {
1137        self.iter()
1138    }
1139}
1140
1141impl<'a, A: Array> IntoIterator for &'a mut StackVec<A> {
1142    type IntoIter = slice::IterMut<'a, A::Item>;
1143    type Item = &'a mut A::Item;
1144    fn into_iter(self) -> Self::IntoIter {
1145        self.iter_mut()
1146    }
1147}
1148
1149// STACKVEC MACRO
1150
1151/// Creates a [`StackVec`] containing the arguments.
1152///
1153/// `stackvec!` allows `StackVec`s to be defined with the same syntax as array expressions.
1154/// There are two forms of this macro:
1155///
1156/// - Create a [`StackVec`] containing a given list of elements:
1157///
1158/// ```
1159/// # #[macro_use] extern crate stackvector;
1160/// # use stackvector::StackVec;
1161/// # fn main() {
1162/// let v: StackVec<[_; 128]> = stackvec![1, 2, 3];
1163/// assert_eq!(v[0], 1);
1164/// assert_eq!(v[1], 2);
1165/// assert_eq!(v[2], 3);
1166/// # }
1167/// ```
1168///
1169/// - Create a [`StackVec`] from a given element and size:
1170///
1171/// ```
1172/// # #[macro_use] extern crate stackvector;
1173/// # use stackvector::StackVec;
1174/// # fn main() {
1175/// let v: StackVec<[_; 0x8000]> = stackvec![1; 3];
1176/// assert_eq!(v, StackVec::from_buf([1, 1, 1]));
1177/// # }
1178/// ```
1179///
1180/// Note that unlike array expressions this syntax supports all elements
1181/// which implement [`Clone`] and the number of elements doesn't have to be
1182/// a constant.
1183///
1184/// This will use `clone` to duplicate an expression, so one should be careful
1185/// using this with types having a nonstandard `Clone` implementation. For
1186/// example, `stackvec![Rc::new(1); 5]` will create a vector of five references
1187/// to the same boxed integer value, not five references pointing to independently
1188/// boxed integers.
1189#[macro_export]
1190macro_rules! stackvec {
1191    // count helper: transform any expression into 1
1192    (@one $x:expr) => (1usize);
1193    ($elem:expr; $n:expr) => ({
1194        $crate::StackVec::from_elem($elem, $n)
1195    });
1196    ($($x:expr),*$(,)*) => ({
1197        // Allow an unused mut variable, since if the sequence is empty,
1198        // the vec will never be mutated.
1199        #[allow(unused_mut)] {
1200            let mut vec = $crate::StackVec::new();
1201            $(vec.push($x);)*
1202            vec
1203        }
1204    });
1205}
1206
1207// TESTS
1208// -----
1209
1210#[cfg(test)]
1211mod test {
1212    use super::*;
1213    use crate::lib::borrow::ToOwned;
1214    use crate::lib::boxed::Box;
1215    use crate::lib::iter::FromIterator;
1216    use crate::lib::rc::Rc;
1217
1218    struct BadBoundsIterator1(u8);
1219
1220    impl BadBoundsIterator1 {
1221        pub fn new() -> Self {
1222            BadBoundsIterator1(0)
1223        }
1224    }
1225
1226    impl Iterator for BadBoundsIterator1 {
1227        type Item = u8;
1228
1229        fn next(&mut self) -> Option<Self::Item> {
1230            self.0 += 1;
1231            if self.0 >= 10 {
1232                None
1233            } else {
1234                Some(0x41)
1235            }
1236        }
1237
1238        fn size_hint(&self) -> (usize, Option<usize>) {
1239            let lower_bound = 20;
1240            let upper_bound = Some(0);
1241            (lower_bound, upper_bound)
1242        }
1243    }
1244
1245    struct BadBoundsIterator2(u8);
1246
1247    impl BadBoundsIterator2 {
1248        pub fn new() -> Self {
1249            BadBoundsIterator2(0)
1250        }
1251    }
1252
1253    impl Iterator for BadBoundsIterator2 {
1254        type Item = u8;
1255
1256        fn next(&mut self) -> Option<Self::Item> {
1257            self.0 += 1;
1258            if self.0 >= 30 {
1259                None
1260            } else {
1261                Some(0x41)
1262            }
1263        }
1264
1265        fn size_hint(&self) -> (usize, Option<usize>) {
1266            let lower_bound = 0;
1267            let upper_bound = Some(0);
1268            (lower_bound, upper_bound)
1269        }
1270    }
1271
1272    struct BadSizeHint(u8);
1273
1274    impl BadSizeHint {
1275        pub fn new(start: u8) -> Self {
1276            BadSizeHint(start)
1277        }
1278    }
1279
1280    impl Iterator for BadSizeHint {
1281        type Item = u8;
1282
1283        fn next(&mut self) -> Option<Self::Item> {
1284            self.0 += 1;
1285            if self.0 >= 30 {
1286                None
1287            } else {
1288                Some(0x41)
1289            }
1290        }
1291
1292        fn size_hint(&self) -> (usize, Option<usize>) {
1293            let lower_bound = 0;
1294            let upper_bound = None;
1295            (lower_bound, upper_bound)
1296        }
1297    }
1298
1299    #[test]
1300    pub fn test_zero() {
1301        let v = StackVec::<[usize; 0]>::new();
1302        assert_eq!(v.len(), 0);
1303    }
1304
1305    #[test]
1306    #[should_panic]
1307    pub fn test_panic() {
1308        let mut v = StackVec::<[usize; 0]>::new();
1309        v.push(0);
1310    }
1311
1312    // We heap allocate all these strings so that double frees will show up under valgrind.
1313
1314    #[test]
1315    pub fn test_inline() {
1316        let mut v = StackVec::<[_; 16]>::new();
1317        v.push("hello".to_owned());
1318        v.push("there".to_owned());
1319        assert_eq!(&*v, &["hello".to_owned(), "there".to_owned(),][..]);
1320    }
1321
1322    #[test]
1323    #[should_panic]
1324    pub fn test_spill() {
1325        let mut v = StackVec::<[_; 2]>::new();
1326        v.push("hello".to_owned());
1327        assert_eq!(v[0], "hello");
1328        v.push("there".to_owned());
1329        v.push("burma".to_owned());
1330        assert_eq!(v[0], "hello");
1331        v.push("shave".to_owned());
1332        assert_eq!(
1333            &*v,
1334            &[
1335                "hello".to_owned(),
1336                "there".to_owned(),
1337                "burma".to_owned(),
1338                "shave".to_owned(),
1339            ][..]
1340        );
1341    }
1342
1343    #[test]
1344    #[should_panic]
1345    pub fn test_double_spill() {
1346        let mut v = StackVec::<[_; 2]>::new();
1347        v.push("hello".to_owned());
1348        v.push("there".to_owned());
1349        v.push("burma".to_owned());
1350        v.push("shave".to_owned());
1351        v.push("hello".to_owned());
1352        v.push("there".to_owned());
1353        v.push("burma".to_owned());
1354        v.push("shave".to_owned());
1355        assert_eq!(
1356            &*v,
1357            &[
1358                "hello".to_owned(),
1359                "there".to_owned(),
1360                "burma".to_owned(),
1361                "shave".to_owned(),
1362                "hello".to_owned(),
1363                "there".to_owned(),
1364                "burma".to_owned(),
1365                "shave".to_owned(),
1366            ][..]
1367        );
1368    }
1369
1370    /// https://github.com/servo/rust-smallvec/issues/4
1371    #[test]
1372    fn issue_4() {
1373        StackVec::<[Box<u32>; 2]>::new();
1374    }
1375
1376    /// https://github.com/servo/rust-smallvec/issues/5
1377    #[test]
1378    fn issue_5() {
1379        assert!(Some(StackVec::<[&u32; 2]>::new()).is_some());
1380    }
1381
1382    #[test]
1383    fn drain_test() {
1384        let mut v: StackVec<[u8; 2]> = StackVec::new();
1385        v.push(3);
1386        assert_eq!(v.drain().collect::<Vec<_>>(), &[3]);
1387    }
1388
1389    #[test]
1390    fn drain_rev_test() {
1391        let mut v: StackVec<[u8; 2]> = StackVec::new();
1392        v.push(3);
1393        assert_eq!(v.drain().rev().collect::<Vec<_>>(), &[3]);
1394    }
1395
1396    #[test]
1397    fn into_iter() {
1398        let mut v: StackVec<[u8; 2]> = StackVec::new();
1399        v.push(3);
1400        assert_eq!(v.into_iter().collect::<Vec<_>>(), &[3]);
1401    }
1402
1403    #[test]
1404    fn into_iter_rev() {
1405        let mut v: StackVec<[u8; 2]> = StackVec::new();
1406        v.push(3);
1407        assert_eq!(v.into_iter().rev().collect::<Vec<_>>(), &[3]);
1408    }
1409
1410    #[test]
1411    fn into_iter_drop() {
1412        use lib::cell::Cell;
1413
1414        struct DropCounter<'a>(&'a Cell<i32>);
1415
1416        impl<'a> Drop for DropCounter<'a> {
1417            fn drop(&mut self) {
1418                self.0.set(self.0.get() + 1);
1419            }
1420        }
1421
1422        {
1423            let cell = Cell::new(0);
1424            let mut v: StackVec<[DropCounter; 2]> = StackVec::new();
1425            v.push(DropCounter(&cell));
1426            v.into_iter();
1427            assert_eq!(cell.get(), 1);
1428        }
1429
1430        {
1431            let cell = Cell::new(0);
1432            let mut v: StackVec<[DropCounter; 2]> = StackVec::new();
1433            v.push(DropCounter(&cell));
1434            v.push(DropCounter(&cell));
1435            assert!(v.into_iter().next().is_some());
1436            assert_eq!(cell.get(), 2);
1437        }
1438    }
1439
1440    #[test]
1441    fn test_capacity() {
1442        let v: StackVec<[u8; 2]> = StackVec::new();
1443        assert_eq!(v.capacity(), 2);
1444    }
1445
1446    #[test]
1447    fn test_truncate() {
1448        let mut v: StackVec<[Box<u8>; 8]> = StackVec::new();
1449
1450        for x in 0..8 {
1451            v.push(Box::new(x));
1452        }
1453        v.truncate(4);
1454
1455        assert_eq!(v.len(), 4);
1456
1457        assert_eq!(*v.swap_remove(1), 1);
1458        assert_eq!(*v.remove(1), 3);
1459        v.insert(1, Box::new(3));
1460
1461        assert_eq!(&v.iter().map(|v| **v).collect::<Vec<_>>(), &[0, 3, 2]);
1462    }
1463
1464    #[test]
1465    fn test_insert_many() {
1466        let mut v: StackVec<[u8; 8]> = StackVec::new();
1467        for x in 0..4 {
1468            v.push(x);
1469        }
1470        assert_eq!(v.len(), 4);
1471        v.insert_many(1, [5, 6].iter().cloned());
1472        assert_eq!(
1473            &v.iter().map(|v| *v).collect::<Vec<_>>(),
1474            &[0, 5, 6, 1, 2, 3]
1475        );
1476    }
1477
1478    #[test]
1479    fn test_insert_many_buggy_iterator() {
1480        let mut v: StackVec<[u8; 64]> = StackVec::new();
1481        for x in 0..4 {
1482            v.push(x);
1483        }
1484        v.insert_many(1, BadBoundsIterator1::new());
1485        assert_eq!(
1486            &v.iter().map(|v| *v).collect::<Vec<_>>(),
1487            &[0, 65, 65, 65, 65, 65, 65, 65, 65, 65, 1, 2, 3]
1488        );
1489
1490        let mut v: StackVec<[u8; 64]> = StackVec::new();
1491        for x in 0..4 {
1492            v.push(x);
1493        }
1494        v.insert_many(1, BadBoundsIterator2::new());
1495        assert_eq!(v.len(), 33);
1496
1497        let mut v: StackVec<[u8; 64]> = StackVec::new();
1498        for x in 0..4 {
1499            v.push(x);
1500        }
1501        v.insert_many(1, BadSizeHint::new(1));
1502        assert_eq!(v.len(), 32);
1503    }
1504
1505    #[should_panic]
1506    #[test]
1507    fn test_insert_many_panic_buggy_iterator() {
1508        let mut v: StackVec<[u8; 8]> = StackVec::new();
1509        for x in 0..4 {
1510            v.push(x);
1511        }
1512        v.insert_many(1, BadBoundsIterator2::new());
1513    }
1514
1515    #[test]
1516    fn test_insert_from_slice() {
1517        let mut v: StackVec<[u8; 8]> = StackVec::new();
1518        for x in 0..4 {
1519            v.push(x);
1520        }
1521        assert_eq!(v.len(), 4);
1522        v.insert_from_slice(1, &[5, 6]);
1523        assert_eq!(
1524            &v.iter().map(|v| *v).collect::<Vec<_>>(),
1525            &[0, 5, 6, 1, 2, 3]
1526        );
1527    }
1528
1529    #[test]
1530    fn test_extend_from_slice() {
1531        let mut v: StackVec<[u8; 8]> = StackVec::new();
1532        for x in 0..4 {
1533            v.push(x);
1534        }
1535        assert_eq!(v.len(), 4);
1536        v.extend_from_slice(&[5, 6]);
1537        assert_eq!(
1538            &v.iter().map(|v| *v).collect::<Vec<_>>(),
1539            &[0, 1, 2, 3, 5, 6]
1540        );
1541    }
1542
1543    #[test]
1544    #[should_panic]
1545    fn test_drop_panic_smallvec() {
1546        // This test should only panic once, and not double panic,
1547        // which would mean a double drop
1548        struct DropPanic;
1549
1550        impl Drop for DropPanic {
1551            fn drop(&mut self) {
1552                panic!("drop");
1553            }
1554        }
1555
1556        let mut v = StackVec::<[_; 1]>::new();
1557        v.push(DropPanic);
1558    }
1559
1560    #[test]
1561    fn test_eq() {
1562        let mut a: StackVec<[u32; 2]> = StackVec::new();
1563        let mut b: StackVec<[u32; 2]> = StackVec::new();
1564        let mut c: StackVec<[u32; 2]> = StackVec::new();
1565        // a = [1, 2]
1566        a.push(1);
1567        a.push(2);
1568        // b = [1, 2]
1569        b.push(1);
1570        b.push(2);
1571        // c = [3, 4]
1572        c.push(3);
1573        c.push(4);
1574
1575        assert!(a == b);
1576        assert!(a != c);
1577    }
1578
1579    #[test]
1580    fn test_ord() {
1581        let mut a: StackVec<[u32; 2]> = StackVec::new();
1582        let mut b: StackVec<[u32; 2]> = StackVec::new();
1583        let mut c: StackVec<[u32; 2]> = StackVec::new();
1584        // a = [1]
1585        a.push(1);
1586        // b = [1, 1]
1587        b.push(1);
1588        b.push(1);
1589        // c = [1, 2]
1590        c.push(1);
1591        c.push(2);
1592
1593        assert!(a < b);
1594        assert!(b > a);
1595        assert!(b < c);
1596        assert!(c > b);
1597    }
1598
1599    #[cfg(feature = "std")]
1600    #[test]
1601    fn test_hash() {
1602        use std::collections::hash_map::DefaultHasher;
1603        use std::hash::Hash;
1604
1605        {
1606            let mut a: StackVec<[u32; 2]> = StackVec::new();
1607            let b = [1, 2];
1608            a.extend(b.iter().cloned());
1609            let mut hasher = DefaultHasher::new();
1610            assert_eq!(a.hash(&mut hasher), b.hash(&mut hasher));
1611        }
1612        {
1613            let mut a: StackVec<[u32; 4]> = StackVec::new();
1614            let b = [1, 2, 11, 12];
1615            a.extend(b.iter().cloned());
1616            let mut hasher = DefaultHasher::new();
1617            assert_eq!(a.hash(&mut hasher), b.hash(&mut hasher));
1618        }
1619    }
1620
1621    #[test]
1622    fn test_as_ref() {
1623        let mut a: StackVec<[u32; 3]> = StackVec::new();
1624        a.push(1);
1625        assert_eq!(a.as_ref(), [1]);
1626        a.push(2);
1627        assert_eq!(a.as_ref(), [1, 2]);
1628        a.push(3);
1629        assert_eq!(a.as_ref(), [1, 2, 3]);
1630    }
1631
1632    #[test]
1633    fn test_as_mut() {
1634        let mut a: StackVec<[u32; 3]> = StackVec::new();
1635        a.push(1);
1636        assert_eq!(a.as_mut(), [1]);
1637        a.push(2);
1638        assert_eq!(a.as_mut(), [1, 2]);
1639        a.push(3);
1640        assert_eq!(a.as_mut(), [1, 2, 3]);
1641        a.as_mut()[1] = 4;
1642        assert_eq!(a.as_mut(), [1, 4, 3]);
1643    }
1644
1645    #[test]
1646    fn test_borrow() {
1647        use lib::borrow::Borrow;
1648
1649        let mut a: StackVec<[u32; 3]> = StackVec::new();
1650        a.push(1);
1651        assert_eq!(a.borrow(), [1]);
1652        a.push(2);
1653        assert_eq!(a.borrow(), [1, 2]);
1654        a.push(3);
1655        assert_eq!(a.borrow(), [1, 2, 3]);
1656    }
1657
1658    #[test]
1659    fn test_borrow_mut() {
1660        use lib::borrow::BorrowMut;
1661
1662        let mut a: StackVec<[u32; 3]> = StackVec::new();
1663        a.push(1);
1664        assert_eq!(a.borrow_mut(), [1]);
1665        a.push(2);
1666        assert_eq!(a.borrow_mut(), [1, 2]);
1667        a.push(3);
1668        assert_eq!(a.borrow_mut(), [1, 2, 3]);
1669        BorrowMut::<[u32]>::borrow_mut(&mut a)[1] = 4;
1670        assert_eq!(a.borrow_mut(), [1, 4, 3]);
1671    }
1672
1673    #[test]
1674    fn test_from() {
1675        assert_eq!(&StackVec::<[u32; 2]>::from(&[1][..])[..], [1]);
1676        assert_eq!(&StackVec::<[u32; 3]>::from(&[1, 2, 3][..])[..], [1, 2, 3]);
1677
1678        let vec = vec![];
1679        let stack_vec: StackVec<[u8; 3]> = StackVec::from(vec);
1680        assert_eq!(&*stack_vec, &[]);
1681        drop(stack_vec);
1682
1683        let vec = vec![1, 2, 3, 4, 5];
1684        let stack_vec: StackVec<[u8; 5]> = StackVec::from(vec);
1685        assert_eq!(&*stack_vec, &[1, 2, 3, 4, 5]);
1686        drop(stack_vec);
1687
1688        let vec = vec![1, 2, 3, 4, 5];
1689        let stack_vec: StackVec<[u8; 5]> = StackVec::from(vec);
1690        assert_eq!(&*stack_vec, &[1, 2, 3, 4, 5]);
1691        drop(stack_vec);
1692
1693        let array = [1];
1694        let stack_vec: StackVec<[u8; 1]> = StackVec::from(array);
1695        assert_eq!(&*stack_vec, &[1]);
1696        drop(stack_vec);
1697
1698        let array = [99; 128];
1699        let stack_vec: StackVec<[u8; 128]> = StackVec::from(array);
1700        assert_eq!(&*stack_vec, vec![99u8; 128].as_slice());
1701        drop(stack_vec);
1702    }
1703
1704    #[test]
1705    fn test_from_slice() {
1706        assert_eq!(&StackVec::<[u32; 2]>::from_slice(&[1][..])[..], [1]);
1707        assert_eq!(
1708            &StackVec::<[u32; 3]>::from_slice(&[1, 2, 3][..])[..],
1709            [1, 2, 3]
1710        );
1711    }
1712
1713    #[test]
1714    fn test_exact_size_iterator() {
1715        let mut vec = StackVec::<[u32; 3]>::from(&[1, 2, 3][..]);
1716        assert_eq!(vec.clone().into_iter().len(), 3);
1717        assert_eq!(vec.drain().len(), 3);
1718    }
1719
1720    #[test]
1721    fn veclike_deref_slice() {
1722        use super::VecLike;
1723
1724        fn test<T: VecLike<i32>>(vec: &mut T) {
1725            assert!(!vec.is_empty());
1726            assert_eq!(vec.len(), 3);
1727
1728            vec.sort();
1729            assert_eq!(&vec[..], [1, 2, 3]);
1730        }
1731
1732        let mut vec = StackVec::<[i32; 3]>::from(&[3, 1, 2][..]);
1733        test(&mut vec);
1734    }
1735
1736    #[test]
1737    fn test_into_vec() {
1738        let vec = StackVec::<[u8; 2]>::from_iter(0..2);
1739        assert_eq!(vec.into_vec(), vec![0, 1]);
1740
1741        let vec = StackVec::<[u8; 3]>::from_iter(0..3);
1742        assert_eq!(vec.into_vec(), vec![0, 1, 2]);
1743    }
1744
1745    #[test]
1746    fn test_into_inner() {
1747        let vec = StackVec::<[u8; 2]>::from_iter(0..2);
1748        assert_eq!(vec.into_inner(), Ok([0, 1]));
1749
1750        let vec = StackVec::<[u8; 2]>::from_iter(0..1);
1751        assert_eq!(vec.clone().into_inner(), Err(vec));
1752
1753        let vec = StackVec::<[u8; 3]>::from_iter(0..3);
1754        assert_eq!(vec.clone().into_inner(), Ok([0, 1, 2]));
1755
1756        let vec = StackVec::<[u8; 4]>::from_iter(0..3);
1757        assert_eq!(vec.clone().into_inner(), Err(vec));
1758    }
1759
1760    #[test]
1761    fn test_from_vec() {
1762        let vec = vec![];
1763        let stack_vec: StackVec<[u8; 3]> = StackVec::from_vec(vec);
1764        assert_eq!(&*stack_vec, &[]);
1765        drop(stack_vec);
1766
1767        let vec = vec![];
1768        let stack_vec: StackVec<[u8; 1]> = StackVec::from_vec(vec);
1769        assert_eq!(&*stack_vec, &[]);
1770        drop(stack_vec);
1771
1772        let vec = vec![1];
1773        let stack_vec: StackVec<[u8; 3]> = StackVec::from_vec(vec);
1774        assert_eq!(&*stack_vec, &[1]);
1775        drop(stack_vec);
1776
1777        let vec = vec![1, 2, 3];
1778        let stack_vec: StackVec<[u8; 3]> = StackVec::from_vec(vec);
1779        assert_eq!(&*stack_vec, &[1, 2, 3]);
1780        drop(stack_vec);
1781
1782        let vec = vec![1, 2, 3, 4, 5];
1783        let stack_vec: StackVec<[u8; 5]> = StackVec::from_vec(vec);
1784        assert_eq!(&*stack_vec, &[1, 2, 3, 4, 5]);
1785        drop(stack_vec);
1786    }
1787
1788    #[test]
1789    fn test_retain() {
1790        let mut sv: StackVec<[i32; 5]> = StackVec::from_slice(&[1, 2, 3, 3, 4]);
1791        sv.retain(|&mut i| i != 3);
1792        assert_eq!(sv.pop(), Some(4));
1793        assert_eq!(sv.pop(), Some(2));
1794        assert_eq!(sv.pop(), Some(1));
1795        assert_eq!(sv.pop(), None);
1796
1797        // Test that drop implementations are called for inline.
1798        let one = Rc::new(1);
1799        let mut sv: StackVec<[Rc<i32>; 3]> = StackVec::new();
1800        sv.push(Rc::clone(&one));
1801        assert_eq!(Rc::strong_count(&one), 2);
1802        sv.retain(|_| false);
1803        assert_eq!(Rc::strong_count(&one), 1);
1804    }
1805
1806    #[test]
1807    fn test_dedup() {
1808        let mut dupes: StackVec<[i32; 5]> = StackVec::from_slice(&[1, 1, 2, 3, 3]);
1809        dupes.dedup();
1810        assert_eq!(&*dupes, &[1, 2, 3]);
1811
1812        let mut empty: StackVec<[i32; 5]> = StackVec::new();
1813        empty.dedup();
1814        assert!(empty.is_empty());
1815
1816        let mut all_ones: StackVec<[i32; 5]> = StackVec::from_slice(&[1, 1, 1, 1, 1]);
1817        all_ones.dedup();
1818        assert_eq!(all_ones.len(), 1);
1819
1820        let mut no_dupes: StackVec<[i32; 5]> = StackVec::from_slice(&[1, 2, 3, 4, 5]);
1821        no_dupes.dedup();
1822        assert_eq!(no_dupes.len(), 5);
1823    }
1824
1825    #[test]
1826    fn test_resize() {
1827        let mut v: StackVec<[i32; 8]> = StackVec::new();
1828        v.push(1);
1829        v.resize(5, 0);
1830        assert_eq!(v[..], [1, 0, 0, 0, 0][..]);
1831
1832        v.resize(2, -1);
1833        assert_eq!(v[..], [1, 0][..]);
1834    }
1835
1836    #[cfg(feature = "std")]
1837    #[test]
1838    fn test_write() {
1839        use io::Write;
1840
1841        let data = [1, 2, 3, 4, 5];
1842
1843        let mut small_vec: StackVec<[u8; 5]> = StackVec::new();
1844        let len = small_vec.write(&data[..]).unwrap();
1845        assert_eq!(len, 5);
1846        assert_eq!(small_vec.as_ref(), data.as_ref());
1847
1848        let mut small_vec: StackVec<[u8; 5]> = StackVec::new();
1849        small_vec.write_all(&data[..]).unwrap();
1850        assert_eq!(small_vec.as_ref(), data.as_ref());
1851    }
1852}