smallvec_stableunion/
lib.rs

1// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
2// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
3// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
4// option. This file may not be copied, modified, or distributed
5// except according to those terms.
6
7//! Small vectors in various sizes. These store a certain number of elements inline, and fall back
8//! to the heap for larger allocations.  This can be a useful optimization for improving cache
9//! locality and reducing allocator traffic for workloads that fit within the inline buffer.
10//!
11//! ## no_std support
12//!
13//! By default, `smallvec` depends on `libstd`. However, it can be configured to use the unstable
14//! `liballoc` API instead, for use on platforms that have `liballoc` but not `libstd`.  This
15//! configuration is currently unstable and is not guaranteed to work on all versions of Rust.
16//!
17//! To depend on `smallvec` without `libstd`, use `default-features = false` in the `smallvec`
18//! section of Cargo.toml to disable its `"std"` feature.
19//!
20//! ## `union` feature
21//!
22//! When the `union` feature is enabled `smallvec` will track its state (inline or spilled)
23//! without the use of an enum tag, reducing the size of the `smallvec` by one machine word.
24//! This means that there is potentially no space overhead compared to `Vec`.
25//! Note that `smallvec` can still be larger than `Vec` if the inline buffer is larger than two
26//! machine words.
27//!
28//! To use this feature add `features = ["union"]` in the `smallvec` section of Cargo.toml.
29//! Note that this feature requires a nightly compiler (for now).
30
31#![cfg_attr(not(feature = "std"), no_std)]
32// #![cfg_attr(feature = "union", feature(untagged_unions))]
33#![cfg_attr(feature = "specialization", feature(specialization))]
34#![cfg_attr(feature = "may_dangle", feature(dropck_eyepatch))]
35#![deny(missing_docs)]
36
37
38#[cfg(not(feature = "std"))]
39#[macro_use]
40extern crate alloc;
41
42#[cfg(not(feature = "std"))]
43use alloc::vec::Vec;
44
45#[cfg(feature = "serde")]
46extern crate serde;
47
48#[cfg(not(feature = "std"))]
49mod std {
50    pub use core::*;
51}
52
53use std::borrow::{Borrow, BorrowMut};
54use std::cmp;
55use std::fmt;
56use std::hash::{Hash, Hasher};
57use std::iter::{IntoIterator, FromIterator, repeat};
58use std::mem;
59use std::mem::ManuallyDrop;
60use std::ops;
61use std::ptr;
62use std::slice;
63#[cfg(feature = "std")]
64use std::io;
65#[cfg(feature = "serde")]
66use serde::ser::{Serialize, Serializer, SerializeSeq};
67#[cfg(feature = "serde")]
68use serde::de::{Deserialize, Deserializer, SeqAccess, Visitor};
69#[cfg(feature = "serde")]
70use std::marker::PhantomData;
71
72/// Creates a [`SmallVec`] containing the arguments.
73///
74/// `smallvec!` allows `SmallVec`s to be defined with the same syntax as array expressions.
75/// There are two forms of this macro:
76///
77/// - Create a [`SmallVec`] containing a given list of elements:
78///
79/// ```
80/// # #[macro_use] extern crate smallvec;
81/// # use smallvec::SmallVec;
82/// # fn main() {
83/// let v: SmallVec<[_; 128]> = smallvec![1, 2, 3];
84/// assert_eq!(v[0], 1);
85/// assert_eq!(v[1], 2);
86/// assert_eq!(v[2], 3);
87/// # }
88/// ```
89///
90/// - Create a [`SmallVec`] from a given element and size:
91///
92/// ```
93/// # #[macro_use] extern crate smallvec;
94/// # use smallvec::SmallVec;
95/// # fn main() {
96/// let v: SmallVec<[_; 0x8000]> = smallvec![1; 3];
97/// assert_eq!(v, SmallVec::from_buf([1, 1, 1]));
98/// # }
99/// ```
100///
101/// Note that unlike array expressions this syntax supports all elements
102/// which implement [`Clone`] and the number of elements doesn't have to be
103/// a constant.
104///
105/// This will use `clone` to duplicate an expression, so one should be careful
106/// using this with types having a nonstandard `Clone` implementation. For
107/// example, `smallvec![Rc::new(1); 5]` will create a vector of five references
108/// to the same boxed integer value, not five references pointing to independently
109/// boxed integers.
110
111#[macro_export]
112macro_rules! smallvec {
113    // count helper: transform any expression into 1
114    (@one $x:expr) => (1usize);
115    ($elem:expr; $n:expr) => ({
116        $crate::SmallVec::from_elem($elem, $n)
117    });
118    ($($x:expr),*$(,)*) => ({
119        let count = 0usize $(+ smallvec!(@one $x))*;
120        let mut vec = $crate::SmallVec::new();
121        if count <= vec.inline_size() {
122            $(vec.push($x);)*
123            vec
124        } else {
125            $crate::SmallVec::from_vec(vec![$($x,)*])
126        }
127    });
128}
129
130/// Hint to the optimizer that any code path which calls this function is
131/// statically unreachable and can be removed.
132///
133/// Equivalent to `std::hint::unreachable_unchecked` but works in older versions of Rust.
134#[inline]
135pub unsafe fn unreachable() -> ! {
136    enum Void {}
137    let x: &Void = mem::transmute(1usize);
138    match *x {}
139}
140
141/// `panic!()` in debug builds, optimization hint in release.
142
143/// Common operations implemented by both `Vec` and `SmallVec`.
144///
145/// This can be used to write generic code that works with both `Vec` and `SmallVec`.
146///
147/// ## Example
148///
149/// ```rust
150/// use smallvec::{VecLike, SmallVec};
151///
152/// fn initialize<V: VecLike<u8>>(v: &mut V) {
153///     for i in 0..5 {
154///         v.push(i);
155///     }
156/// }
157///
158/// let mut vec = Vec::new();
159/// initialize(&mut vec);
160///
161/// let mut small_vec = SmallVec::<[u8; 8]>::new();
162/// initialize(&mut small_vec);
163/// ```
164#[deprecated(note = "Use `Extend` and `Deref<[T]>` instead")]
165pub trait VecLike<T>:
166        ops::Index<usize, Output=T> +
167        ops::IndexMut<usize> +
168        ops::Index<ops::Range<usize>, Output=[T]> +
169        ops::IndexMut<ops::Range<usize>> +
170        ops::Index<ops::RangeFrom<usize>, Output=[T]> +
171        ops::IndexMut<ops::RangeFrom<usize>> +
172        ops::Index<ops::RangeTo<usize>, Output=[T]> +
173        ops::IndexMut<ops::RangeTo<usize>> +
174        ops::Index<ops::RangeFull, Output=[T]> +
175        ops::IndexMut<ops::RangeFull> +
176        ops::DerefMut<Target = [T]> +
177        Extend<T> {
178
179    /// Append an element to the vector.
180    fn push(&mut self, value: T);
181}
182
183#[allow(deprecated)]
184impl<T> VecLike<T> for Vec<T> {
185    #[inline]
186    fn push(&mut self, value: T) {
187        Vec::push(self, value);
188    }
189}
190
191/// Trait to be implemented by a collection that can be extended from a slice
192///
193/// ## Example
194///
195/// ```rust
196/// use smallvec::{ExtendFromSlice, SmallVec};
197///
198/// fn initialize<V: ExtendFromSlice<u8>>(v: &mut V) {
199///     v.extend_from_slice(b"Test!");
200/// }
201///
202/// let mut vec = Vec::new();
203/// initialize(&mut vec);
204/// assert_eq!(&vec, b"Test!");
205///
206/// let mut small_vec = SmallVec::<[u8; 8]>::new();
207/// initialize(&mut small_vec);
208/// assert_eq!(&small_vec as &[_], b"Test!");
209/// ```
210pub trait ExtendFromSlice<T> {
211    /// Extends a collection from a slice of its element type
212    fn extend_from_slice(&mut self, other: &[T]);
213}
214
215impl<T: Clone> ExtendFromSlice<T> for Vec<T> {
216    fn extend_from_slice(&mut self, other: &[T]) {
217        Vec::extend_from_slice(self, other)
218    }
219}
220
221unsafe fn deallocate<T>(ptr: *mut T, capacity: usize) {
222    let _vec: Vec<T> = Vec::from_raw_parts(ptr, 0, capacity);
223    // Let it drop.
224}
225
226/// An iterator that removes the items from a `SmallVec` and yields them by value.
227///
228/// Returned from [`SmallVec::drain`][1].
229///
230/// [1]: struct.SmallVec.html#method.drain
231pub struct Drain<'a, T: 'a> {
232    iter: slice::IterMut<'a,T>,
233}
234
235impl<'a, T: 'a> Iterator for Drain<'a,T> {
236    type Item = T;
237
238    #[inline]
239    fn next(&mut self) -> Option<T> {
240        self.iter.next().map(|reference| unsafe { ptr::read(reference) })
241    }
242
243    #[inline]
244    fn size_hint(&self) -> (usize, Option<usize>) {
245        self.iter.size_hint()
246    }
247}
248
249impl<'a, T: 'a> DoubleEndedIterator for Drain<'a, T> {
250    #[inline]
251    fn next_back(&mut self) -> Option<T> {
252        self.iter.next_back().map(|reference| unsafe { ptr::read(reference) })
253    }
254}
255
256impl<'a, T> ExactSizeIterator for Drain<'a, T> { }
257
258impl<'a, T: 'a> Drop for Drain<'a,T> {
259    fn drop(&mut self) {
260        // Destroy the remaining elements.
261        for _ in self.by_ref() {}
262    }
263}
264
265union SmallVecData<A: Array + Copy> {
266    inline: ManuallyDrop<A>,
267    heap: (*mut A::Item, usize),
268}
269
270impl<A: Array + Copy> SmallVecData<A> {
271    #[inline]
272    unsafe fn inline(&self) -> &A {
273        &self.inline
274    }
275    #[inline]
276    unsafe fn inline_mut(&mut self) -> &mut A {
277        &mut self.inline
278    }
279    #[inline]
280    fn from_inline(inline: A) -> SmallVecData<A> {
281        SmallVecData { inline: ManuallyDrop::new(inline) }
282    }
283    #[inline]
284    unsafe fn into_inline(self) -> A { ManuallyDrop::into_inner(self.inline) }
285    #[inline]
286    unsafe fn heap(&self) -> (*mut A::Item, usize) {
287        self.heap
288    }
289    #[inline]
290    unsafe fn heap_mut(&mut self) -> &mut (*mut A::Item, usize) {
291        &mut self.heap
292    }
293    #[inline]
294    fn from_heap(ptr: *mut A::Item, len: usize) -> SmallVecData<A> {
295        SmallVecData { heap: (ptr, len) }
296    }
297}
298
299
300unsafe impl<A: Array + Send + Copy> Send for SmallVecData<A> {}
301unsafe impl<A: Array + Sync + Copy> Sync for SmallVecData<A> {}
302
303/// A `Vec`-like container that can store a small number of elements inline.
304///
305/// `SmallVec` acts like a vector, but can store a limited amount of data inline within the
306/// `SmallVec` struct rather than in a separate allocation.  If the data exceeds this limit, the
307/// `SmallVec` will "spill" its data onto the heap, allocating a new buffer to hold it.
308///
309/// The amount of data that a `SmallVec` can store inline depends on its backing store. The backing
310/// store can be any type that implements the `Array` trait; usually it is a small fixed-sized
311/// array.  For example a `SmallVec<[u64; 8]>` can hold up to eight 64-bit integers inline.
312///
313/// ## Example
314///
315/// ```rust
316/// use smallvec::SmallVec;
317/// let mut v = SmallVec::<[u8; 4]>::new(); // initialize an empty vector
318///
319/// // The vector can hold up to 4 items without spilling onto the heap.
320/// v.extend(0..4);
321/// assert_eq!(v.len(), 4);
322/// assert!(!v.spilled());
323///
324/// // Pushing another element will force the buffer to spill:
325/// v.push(4);
326/// assert_eq!(v.len(), 5);
327/// assert!(v.spilled());
328/// ```
329pub struct SmallVec<A: Array + Copy> {
330    // The capacity field is used to determine which of the storage variants is active:
331    // If capacity <= A::size() then the inline variant is used and capacity holds the current length of the vector (number of elements actually in use).
332    // If capacity > A::size() then the heap variant is used and capacity holds the size of the memory allocation.
333    capacity: usize,
334    data: SmallVecData<A>,
335}
336
337impl<A: Array + Copy> SmallVec<A> {
338    /// Construct an empty vector
339    #[inline]
340    pub fn new() -> SmallVec<A> {
341        unsafe {
342            SmallVec {
343                capacity: 0,
344                data: SmallVecData::from_inline(mem::uninitialized()),
345            }
346        }
347    }
348
349    /// Construct an empty vector with enough capacity pre-allocated to store at least `n`
350    /// elements.
351    ///
352    /// Will create a heap allocation only if `n` is larger than the inline capacity.
353    ///
354    /// ```
355    /// # use smallvec::SmallVec;
356    ///
357    /// let v: SmallVec<[u8; 3]> = SmallVec::with_capacity(100);
358    ///
359    /// assert!(v.is_empty());
360    /// assert!(v.capacity() >= 100);
361    /// ```
362    #[inline]
363    pub fn with_capacity(n: usize) -> Self {
364        let mut v = SmallVec::new();
365        v.reserve_exact(n);
366        v
367    }
368
369    /// Construct a new `SmallVec` from a `Vec<A::Item>`.
370    ///
371    /// Elements will be copied to the inline buffer if vec.capacity() <= A::size().
372    ///
373    /// ```rust
374    /// use smallvec::SmallVec;
375    ///
376    /// let vec = vec![1, 2, 3, 4, 5];
377    /// let small_vec: SmallVec<[_; 3]> = SmallVec::from_vec(vec);
378    ///
379    /// assert_eq!(&*small_vec, &[1, 2, 3, 4, 5]);
380    /// ```
381    #[inline]
382    pub fn from_vec(mut vec: Vec<A::Item>) -> SmallVec<A> {
383        if vec.capacity() <= A::size() {
384            unsafe {
385                let mut data = SmallVecData::<A>::from_inline(mem::uninitialized());
386                let len = vec.len();
387                vec.set_len(0);
388                ptr::copy_nonoverlapping(vec.as_ptr(), data.inline_mut().ptr_mut(), len);
389
390                SmallVec {
391                    capacity: len,
392                    data,
393                }
394            }
395        } else {
396            let (ptr, cap, len) = (vec.as_mut_ptr(), vec.capacity(), vec.len());
397            mem::forget(vec);
398
399            SmallVec {
400                capacity: cap,
401                data: SmallVecData::from_heap(ptr, len),
402            }
403        }
404    }
405
406    /// Constructs a new `SmallVec` on the stack from an `A` without
407    /// copying elements.
408    ///
409    /// ```rust
410    /// use smallvec::SmallVec;
411    ///
412    /// let buf = [1, 2, 3, 4, 5];
413    /// let small_vec: SmallVec<_> = SmallVec::from_buf(buf);
414    ///
415    /// assert_eq!(&*small_vec, &[1, 2, 3, 4, 5]);
416    /// ```
417    #[inline]
418    pub fn from_buf(buf: A) -> SmallVec<A> {
419        SmallVec {
420            capacity: A::size(),
421            data: SmallVecData::from_inline(buf),
422        }
423    }
424
425    /// Constructs a new `SmallVec` on the stack from an `A` without
426    /// copying elements. Also sets the length, which must be less or
427    /// equal to the size of `buf`.
428    ///
429    /// ```rust
430    /// use smallvec::SmallVec;
431    ///
432    /// let buf = [1, 2, 3, 4, 5, 0, 0, 0];
433    /// let small_vec: SmallVec<_> = SmallVec::from_buf_and_len(buf, 5);
434    ///
435    /// assert_eq!(&*small_vec, &[1, 2, 3, 4, 5]);
436    /// ```
437    #[inline]
438    pub fn from_buf_and_len(buf: A, len: usize) -> SmallVec<A> {
439        assert!(len <= A::size());
440        unsafe { SmallVec::from_buf_and_len_unchecked(buf, len) }
441    }
442
443    /// Constructs a new `SmallVec` on the stack from an `A` without
444    /// copying elements. Also sets the length. The user is responsible
445    /// for ensuring that `len <= A::size()`.
446    ///
447    /// ```rust
448    /// use smallvec::SmallVec;
449    ///
450    /// let buf = [1, 2, 3, 4, 5, 0, 0, 0];
451    /// let small_vec: SmallVec<_> = unsafe {
452    ///     SmallVec::from_buf_and_len_unchecked(buf, 5)
453    /// };
454    ///
455    /// assert_eq!(&*small_vec, &[1, 2, 3, 4, 5]);
456    /// ```
457    #[inline]
458    pub unsafe fn from_buf_and_len_unchecked(buf: A, len: usize) -> SmallVec<A> {
459        SmallVec {
460            capacity: len,
461            data: SmallVecData::from_inline(buf),
462        }
463    }
464
465
466    /// Sets the length of a vector.
467    ///
468    /// This will explicitly set the size of the vector, without actually
469    /// modifying its buffers, so it is up to the caller to ensure that the
470    /// vector is actually the specified size.
471    pub unsafe fn set_len(&mut self, new_len: usize) {
472        let (_, len_ptr, _) = self.triple_mut();
473        *len_ptr = new_len;
474    }
475
476    /// The maximum number of elements this vector can hold inline
477    #[inline]
478    pub fn inline_size(&self) -> usize {
479        A::size()
480    }
481
482    /// The number of elements stored in the vector
483    #[inline]
484    pub fn len(&self) -> usize {
485        self.triple().1
486    }
487
488    /// Returns `true` if the vector is empty
489    #[inline]
490    pub fn is_empty(&self) -> bool {
491        self.len() == 0
492    }
493
494    /// The number of items the vector can hold without reallocating
495    #[inline]
496    pub fn capacity(&self) -> usize {
497        self.triple().2
498    }
499
500    /// Returns a tuple with (data ptr, len, capacity)
501    /// Useful to get all SmallVec properties with a single check of the current storage variant.
502    #[inline]
503    fn triple(&self) -> (*const A::Item, usize, usize) {
504        unsafe {
505            if self.spilled() {
506                let (ptr, len) = self.data.heap();
507                (ptr, len, self.capacity)
508            } else {
509                (self.data.inline().ptr(), self.capacity, A::size())
510            }
511        }
512    }
513
514    /// Returns a tuple with (data ptr, len ptr, capacity)
515    #[inline]
516    fn triple_mut(&mut self) -> (*mut A::Item, &mut usize, usize) {
517        unsafe {
518            if self.spilled() {
519                let &mut (ptr, ref mut len_ptr) = self.data.heap_mut();
520                (ptr, len_ptr, self.capacity)
521            } else {
522                (self.data.inline_mut().ptr_mut(), &mut self.capacity, A::size())
523            }
524        }
525    }
526
527    /// Returns `true` if the data has spilled into a separate heap-allocated buffer.
528    #[inline]
529    pub fn spilled(&self) -> bool {
530        self.capacity > A::size()
531    }
532
533    /// Empty the vector and return an iterator over its former contents.
534    pub fn drain(&mut self) -> Drain<A::Item> {
535        unsafe {
536            let ptr = self.as_mut_ptr();
537
538            let current_len = self.len();
539            self.set_len(0);
540
541            let slice = slice::from_raw_parts_mut(ptr, current_len);
542
543            Drain {
544                iter: slice.iter_mut(),
545            }
546        }
547    }
548
549    /// Append an item to the vector.
550    #[inline]
551    pub fn push(&mut self, value: A::Item) {
552        unsafe {
553            let (_, &mut len, cap) = self.triple_mut();
554            if len == cap {
555                self.reserve(1);
556            }
557            let (ptr, len_ptr, _) = self.triple_mut();
558            *len_ptr = len + 1;
559            ptr::write(ptr.offset(len as isize), value);
560        }
561    }
562
563    /// Remove an item from the end of the vector and return it, or None if empty.
564    #[inline]
565    pub fn pop(&mut self) -> Option<A::Item> {
566        unsafe {
567            let (ptr, len_ptr, _) = self.triple_mut();
568            if *len_ptr == 0 {
569                return None;
570            }
571            let last_index = *len_ptr - 1;
572            *len_ptr = last_index;
573            Some(ptr::read(ptr.offset(last_index as isize)))
574        }
575    }
576
577    /// Re-allocate to set the capacity to `max(new_cap, inline_size())`.
578    ///
579    /// Panics if `new_cap` is less than the vector's length.
580    pub fn grow(&mut self, new_cap: usize) {
581        unsafe {
582            let (ptr, &mut len, cap) = self.triple_mut();
583            let unspilled = !self.spilled();
584            assert!(new_cap >= len);
585            if new_cap <= self.inline_size() {
586                if unspilled {
587                    return;
588                }
589                self.data = SmallVecData::from_inline(mem::uninitialized());
590                ptr::copy_nonoverlapping(ptr, self.data.inline_mut().ptr_mut(), len);
591                self.capacity = len;
592            } else if new_cap != cap {
593                let mut vec = Vec::with_capacity(new_cap);
594                let new_alloc = vec.as_mut_ptr();
595                mem::forget(vec);
596                ptr::copy_nonoverlapping(ptr, new_alloc, len);
597                self.data = SmallVecData::from_heap(new_alloc, len);
598                self.capacity = new_cap;
599                if unspilled {
600                    return;
601                }
602            } else {
603                return;
604            }
605            deallocate(ptr, cap);
606        }
607    }
608
609    /// Reserve capacity for `additional` more elements to be inserted.
610    ///
611    /// May reserve more space to avoid frequent reallocations.
612    ///
613    /// If the new capacity would overflow `usize` then it will be set to `usize::max_value()`
614    /// instead. (This means that inserting `additional` new elements is not guaranteed to be
615    /// possible after calling this function.)
616    #[inline]
617    pub fn reserve(&mut self, additional: usize) {
618        // prefer triple_mut() even if triple() would work
619        // so that the optimizer removes duplicated calls to it
620        // from callers like insert()
621        let (_, &mut len, cap) = self.triple_mut();
622        if cap - len < additional {
623            let new_cap = len.checked_add(additional).
624                and_then(usize::checked_next_power_of_two).
625                unwrap_or(usize::max_value());
626            self.grow(new_cap);
627        }
628    }
629
630    /// Reserve the minimum capacity for `additional` more elements to be inserted.
631    ///
632    /// Panics if the new capacity overflows `usize`.
633    pub fn reserve_exact(&mut self, additional: usize) {
634        let (_, &mut len, cap) = self.triple_mut();
635        if cap - len < additional {
636            match len.checked_add(additional) {
637                Some(cap) => self.grow(cap),
638                None => panic!("reserve_exact overflow"),
639            }
640        }
641    }
642
643    /// Shrink the capacity of the vector as much as possible.
644    ///
645    /// When possible, this will move data from an external heap buffer to the vector's inline
646    /// storage.
647    pub fn shrink_to_fit(&mut self) {
648        if !self.spilled() {
649            return;
650        }
651        let len = self.len();
652        if self.inline_size() >= len {
653            unsafe {
654                let (ptr, len) = self.data.heap();
655                self.data = SmallVecData::from_inline(mem::uninitialized());
656                ptr::copy_nonoverlapping(ptr, self.data.inline_mut().ptr_mut(), len);
657                deallocate(ptr, self.capacity);
658                self.capacity = len;
659            }
660        } else if self.capacity() > len {
661            self.grow(len);
662        }
663    }
664
665    /// Shorten the vector, keeping the first `len` elements and dropping the rest.
666    ///
667    /// If `len` is greater than or equal to the vector's current length, this has no
668    /// effect.
669    ///
670    /// This does not re-allocate.  If you want the vector's capacity to shrink, call
671    /// `shrink_to_fit` after truncating.
672    pub fn truncate(&mut self, len: usize) {
673        unsafe {
674            let (ptr, len_ptr, _) = self.triple_mut();
675            while len < *len_ptr {
676                let last_index = *len_ptr - 1;
677                *len_ptr = last_index;
678                ptr::drop_in_place(ptr.offset(last_index as isize));
679            }
680        }
681    }
682
683    /// Extracts a slice containing the entire vector.
684    ///
685    /// Equivalent to `&s[..]`.
686    pub fn as_slice(&self) -> &[A::Item] {
687        self
688    }
689
690    /// Extracts a mutable slice of the entire vector.
691    ///
692    /// Equivalent to `&mut s[..]`.
693    pub fn as_mut_slice(&mut self) -> &mut [A::Item] {
694        self
695    }
696
697    /// Remove the element at position `index`, replacing it with the last element.
698    ///
699    /// This does not preserve ordering, but is O(1).
700    ///
701    /// Panics if `index` is out of bounds.
702    #[inline]
703    pub fn swap_remove(&mut self, index: usize) -> A::Item {
704        let len = self.len();
705        self.swap(len - 1, index);
706        self.pop().unwrap_or_else(|| unsafe { unreachable() })
707    }
708
709    /// Remove all elements from the vector.
710    #[inline]
711    pub fn clear(&mut self) {
712        self.truncate(0);
713    }
714
715    /// Remove and return the element at position `index`, shifting all elements after it to the
716    /// left.
717    ///
718    /// Panics if `index` is out of bounds.
719    pub fn remove(&mut self, index: usize) -> A::Item {
720        unsafe {
721            let (mut ptr, len_ptr, _) = self.triple_mut();
722            let len = *len_ptr;
723            assert!(index < len);
724            *len_ptr = len - 1;
725            ptr = ptr.offset(index as isize);
726            let item = ptr::read(ptr);
727            ptr::copy(ptr.offset(1), ptr, len - index - 1);
728            item
729        }
730    }
731
732    /// Insert an element at position `index`, shifting all elements after it to the right.
733    ///
734    /// Panics if `index` is out of bounds.
735    pub fn insert(&mut self, index: usize, element: A::Item) {
736        self.reserve(1);
737
738        unsafe {
739            let (mut ptr, len_ptr, _) = self.triple_mut();
740            let len = *len_ptr;
741            assert!(index <= len);
742            *len_ptr = len + 1;
743            ptr = ptr.offset(index as isize);
744            ptr::copy(ptr, ptr.offset(1), len - index);
745            ptr::write(ptr, element);
746        }
747    }
748
749    /// Insert multiple elements at position `index`, shifting all following elements toward the
750    /// back.
751    pub fn insert_many<I: IntoIterator<Item=A::Item>>(&mut self, index: usize, iterable: I) {
752        let iter = iterable.into_iter();
753        if index == self.len() {
754            return self.extend(iter);
755        }
756
757        let (lower_size_bound, _) = iter.size_hint();
758        assert!(lower_size_bound <= std::isize::MAX as usize);  // Ensure offset is indexable
759        assert!(index + lower_size_bound >= index);  // Protect against overflow
760        self.reserve(lower_size_bound);
761
762        unsafe {
763            let old_len = self.len();
764            assert!(index <= old_len);
765            let mut ptr = self.as_mut_ptr().offset(index as isize);
766
767            // Move the trailing elements.
768            ptr::copy(ptr, ptr.offset(lower_size_bound as isize), old_len - index);
769
770            // In case the iterator panics, don't double-drop the items we just copied above.
771            self.set_len(index);
772
773            let mut num_added = 0;
774            for element in iter {
775                let mut cur = ptr.offset(num_added as isize);
776                if num_added >= lower_size_bound {
777                    // Iterator provided more elements than the hint.  Move trailing items again.
778                    self.reserve(1);
779                    ptr = self.as_mut_ptr().offset(index as isize);
780                    cur = ptr.offset(num_added as isize);
781                    ptr::copy(cur, cur.offset(1), old_len - index);
782                }
783                ptr::write(cur, element);
784                num_added += 1;
785            }
786            if num_added < lower_size_bound {
787                // Iterator provided fewer elements than the hint
788                ptr::copy(ptr.offset(lower_size_bound as isize), ptr.offset(num_added as isize), old_len - index);
789            }
790
791            self.set_len(old_len + num_added);
792        }
793    }
794
795    /// Convert a SmallVec to a Vec, without reallocating if the SmallVec has already spilled onto
796    /// the heap.
797    pub fn into_vec(self) -> Vec<A::Item> {
798        if self.spilled() {
799            unsafe {
800                let (ptr, len) = self.data.heap();
801                let v = Vec::from_raw_parts(ptr, len, self.capacity);
802                mem::forget(self);
803                v
804            }
805        } else {
806            self.into_iter().collect()
807        }
808    }
809
810    /// Convert the SmallVec into an `A` if possible. Otherwise return `Err(Self)`.
811    ///
812    /// This method returns `Err(Self)` if the SmallVec is too short (and the `A` contains uninitialized elements),
813    /// or if the SmallVec is too long (and all the elements were spilled to the heap).
814    pub fn into_inner(self) -> Result<A, Self> {
815        if self.spilled() || self.len() != A::size() {
816            Err(self)
817        } else {
818            unsafe {
819                let data = ptr::read(&self.data);
820                mem::forget(self);
821                Ok(data.into_inline())
822            }
823        }
824    }
825
826    /// Retains only the elements specified by the predicate.
827    ///
828    /// In other words, remove all elements `e` such that `f(&e)` returns `false`.
829    /// This method operates in place and preserves the order of the retained
830    /// elements.
831    pub fn retain<F: FnMut(&mut A::Item) -> bool>(&mut self, mut f: F) {
832        let mut del = 0;
833        let len = self.len();
834        for i in 0..len {
835            if !f(&mut self[i]) {
836                del += 1;
837            } else if del > 0 {
838                self.swap(i - del, i);
839            }
840        }
841        self.truncate(len - del);
842    }
843
844    /// Removes consecutive duplicate elements.
845    pub fn dedup(&mut self) where A::Item: PartialEq<A::Item> {
846        self.dedup_by(|a, b| a == b);
847    }
848
849    /// Removes consecutive duplicate elements using the given equality relation.
850    pub fn dedup_by<F>(&mut self, mut same_bucket: F)
851        where F: FnMut(&mut A::Item, &mut A::Item) -> bool
852    {
853        // See the implementation of Vec::dedup_by in the
854        // standard library for an explanation of this algorithm.
855        let len = self.len();
856        if len <= 1 {
857            return;
858        }
859
860        let ptr = self.as_mut_ptr();
861        let mut w: usize = 1;
862
863        unsafe {
864            for r in 1..len {
865                let p_r = ptr.offset(r as isize);
866                let p_wm1 = ptr.offset((w - 1) as isize);
867                if !same_bucket(&mut *p_r, &mut *p_wm1) {
868                    if r != w {
869                        let p_w = p_wm1.offset(1);
870                        mem::swap(&mut *p_r, &mut *p_w);
871                    }
872                    w += 1;
873                }
874            }
875        }
876
877        self.truncate(w);
878    }
879
880    /// Removes consecutive elements that map to the same key.
881    pub fn dedup_by_key<F, K>(&mut self, mut key: F)
882        where F: FnMut(&mut A::Item) -> K,
883              K: PartialEq<K>
884    {
885        self.dedup_by(|a, b| key(a) == key(b));
886    }
887
888    /// Creates a `SmallVec` directly from the raw components of another
889    /// `SmallVec`.
890    ///
891    /// # Safety
892    ///
893    /// This is highly unsafe, due to the number of invariants that aren't
894    /// checked:
895    ///
896    /// * `ptr` needs to have been previously allocated via `SmallVec` for its
897    ///   spilled storage (at least, it's highly likely to be incorrect if it
898    ///   wasn't).
899    /// * `ptr`'s `A::Item` type needs to be the same size and alignment that
900    ///   it was allocated with
901    /// * `length` needs to be less than or equal to `capacity`.
902    /// * `capacity` needs to be the capacity that the pointer was allocated
903    ///   with.
904    ///
905    /// Violating these may cause problems like corrupting the allocator's
906    /// internal data structures.
907    ///
908    /// Additionally, `capacity` must be greater than the amount of inline
909    /// storage `A` has; that is, the new `SmallVec` must need to spill over
910    /// into heap allocated storage. This condition is asserted against.
911    ///
912    /// The ownership of `ptr` is effectively transferred to the
913    /// `SmallVec` which may then deallocate, reallocate or change the
914    /// contents of memory pointed to by the pointer at will. Ensure
915    /// that nothing else uses the pointer after calling this
916    /// function.
917    ///
918    /// # Examples
919    ///
920    /// ```
921    /// # #[macro_use] extern crate smallvec;
922    /// # use smallvec::SmallVec;
923    /// use std::mem;
924    /// use std::ptr;
925    ///
926    /// fn main() {
927    ///     let mut v: SmallVec<[_; 1]> = smallvec![1, 2, 3];
928    ///
929    ///     // Pull out the important parts of `v`.
930    ///     let p = v.as_mut_ptr();
931    ///     let len = v.len();
932    ///     let cap = v.capacity();
933    ///     let spilled = v.spilled();
934    ///
935    ///     unsafe {
936    ///         // Forget all about `v`. The heap allocation that stored the
937    ///         // three values won't be deallocated.
938    ///         mem::forget(v);
939    ///
940    ///         // Overwrite memory with [4, 5, 6].
941    ///         //
942    ///         // This is only safe if `spilled` is true! Otherwise, we are
943    ///         // writing into the old `SmallVec`'s inline storage on the
944    ///         // stack.
945    ///         assert!(spilled);
946    ///         for i in 0..len as isize {
947    ///             ptr::write(p.offset(i), 4 + i);
948    ///         }
949    ///
950    ///         // Put everything back together into a SmallVec with a different
951    ///         // amount of inline storage, but which is still less than `cap`.
952    ///         let rebuilt = SmallVec::<[_; 2]>::from_raw_parts(p, len, cap);
953    ///         assert_eq!(&*rebuilt, &[4, 5, 6]);
954    ///     }
955    /// }
956    pub unsafe fn from_raw_parts(
957        ptr: *mut A::Item,
958        length: usize,
959        capacity: usize,
960    ) -> SmallVec<A> {
961        assert!(capacity > A::size());
962        SmallVec {
963            capacity,
964            data: SmallVecData::from_heap(ptr, length),
965        }
966    }
967}
968
969impl<A: Array + Copy> SmallVec<A> where A::Item: Copy {
970    /// Copy the elements from a slice into a new `SmallVec`.
971    ///
972    /// For slices of `Copy` types, this is more efficient than `SmallVec::from(slice)`.
973    pub fn from_slice(slice: &[A::Item]) -> Self {
974        let len = slice.len();
975        if len <= A::size() {
976            SmallVec {
977                capacity: len,
978                data: SmallVecData::from_inline(unsafe {
979                    let mut data: A = mem::uninitialized();
980                    ptr::copy_nonoverlapping(slice.as_ptr(), data.ptr_mut(), len);
981                    data
982                })
983            }
984        } else {
985            let mut b = slice.to_vec();
986            let (ptr, cap) = (b.as_mut_ptr(), b.capacity());
987            mem::forget(b);
988            SmallVec {
989                capacity: cap,
990                data: SmallVecData::from_heap(ptr, len),
991            }
992        }
993    }
994
995    /// Copy elements from a slice into the vector at position `index`, shifting any following
996    /// elements toward the back.
997    ///
998    /// For slices of `Copy` types, this is more efficient than `insert`.
999    pub fn insert_from_slice(&mut self, index: usize, slice: &[A::Item]) {
1000        self.reserve(slice.len());
1001
1002        let len = self.len();
1003        assert!(index <= len);
1004
1005        unsafe {
1006            let slice_ptr = slice.as_ptr();
1007            let ptr = self.as_mut_ptr().offset(index as isize);
1008            ptr::copy(ptr, ptr.offset(slice.len() as isize), len - index);
1009            ptr::copy_nonoverlapping(slice_ptr, ptr, slice.len());
1010            self.set_len(len + slice.len());
1011        }
1012    }
1013
1014    /// Copy elements from a slice and append them to the vector.
1015    ///
1016    /// For slices of `Copy` types, this is more efficient than `extend`.
1017    #[inline]
1018    pub fn extend_from_slice(&mut self, slice: &[A::Item]) {
1019        let len = self.len();
1020        self.insert_from_slice(len, slice);
1021    }
1022}
1023
1024impl<A: Array + Copy> SmallVec<A> where A::Item: Clone {
1025    /// Resizes the vector so that its length is equal to `len`.
1026    ///
1027    /// If `len` is less than the current length, the vector simply truncated.
1028    ///
1029    /// If `len` is greater than the current length, `value` is appended to the
1030    /// vector until its length equals `len`.
1031    pub fn resize(&mut self, len: usize, value: A::Item) {
1032        let old_len = self.len();
1033
1034        if len > old_len {
1035            self.extend(repeat(value).take(len - old_len));
1036        } else {
1037            self.truncate(len);
1038        }
1039    }
1040
1041    /// Creates a `SmallVec` with `n` copies of `elem`.
1042    /// ```
1043    /// use smallvec::SmallVec;
1044    ///
1045    /// let v = SmallVec::<[char; 128]>::from_elem('d', 2);
1046    /// assert_eq!(v, SmallVec::from_buf(['d', 'd']));
1047    /// ```
1048    pub fn from_elem(elem: A::Item, n: usize) -> Self {
1049        if n > A::size() {
1050            vec![elem; n].into()
1051        } else {
1052            let mut v = SmallVec::<A>::new();
1053            unsafe {
1054                let (ptr, len_ptr, _) = v.triple_mut();
1055                let mut local_len = SetLenOnDrop::new(len_ptr);
1056
1057                for i in 0..n as isize {
1058                    ::std::ptr::write(ptr.offset(i), elem.clone());
1059                    local_len.increment_len(1);
1060                }
1061            }
1062            v
1063        }
1064    }
1065}
1066
1067impl<A: Array + Copy> ops::Deref for SmallVec<A> {
1068    type Target = [A::Item];
1069    #[inline]
1070    fn deref(&self) -> &[A::Item] {
1071        unsafe {
1072            let (ptr, len, _) = self.triple();
1073            slice::from_raw_parts(ptr, len)
1074        }
1075    }
1076}
1077
1078impl<A: Array + Copy> ops::DerefMut for SmallVec<A> {
1079    #[inline]
1080    fn deref_mut(&mut self) -> &mut [A::Item] {
1081        unsafe {
1082            let (ptr, &mut len, _) = self.triple_mut();
1083            slice::from_raw_parts_mut(ptr, len)
1084        }
1085    }
1086}
1087
1088impl<A: Array + Copy> AsRef<[A::Item]> for SmallVec<A> {
1089    #[inline]
1090    fn as_ref(&self) -> &[A::Item] {
1091        self
1092    }
1093}
1094
1095impl<A: Array + Copy> AsMut<[A::Item]> for SmallVec<A> {
1096    #[inline]
1097    fn as_mut(&mut self) -> &mut [A::Item] {
1098        self
1099    }
1100}
1101
1102impl<A: Array + Copy> Borrow<[A::Item]> for SmallVec<A> {
1103    #[inline]
1104    fn borrow(&self) -> &[A::Item] {
1105        self
1106    }
1107}
1108
1109impl<A: Array + Copy> BorrowMut<[A::Item]> for SmallVec<A> {
1110    #[inline]
1111    fn borrow_mut(&mut self) -> &mut [A::Item] {
1112        self
1113    }
1114}
1115
1116#[cfg(feature = "std")]
1117impl<A: Array<Item = u8> + Copy> io::Write for SmallVec<A> {
1118    #[inline]
1119    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
1120        self.extend_from_slice(buf);
1121        Ok(buf.len())
1122    }
1123
1124    #[inline]
1125    fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
1126        self.extend_from_slice(buf);
1127        Ok(())
1128    }
1129
1130    #[inline]
1131    fn flush(&mut self) -> io::Result<()> {
1132        Ok(())
1133    }
1134}
1135
1136#[cfg(feature = "serde")]
1137impl<A: Array + Copy> Serialize for SmallVec<A> where A::Item: Serialize {
1138    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
1139        let mut state = serializer.serialize_seq(Some(self.len()))?;
1140        for item in self {
1141            state.serialize_element(&item)?;
1142        }
1143        state.end()
1144    }
1145}
1146
1147#[cfg(feature = "serde")]
1148impl<'de, A: Array + Copy> Deserialize<'de> for SmallVec<A> where A::Item: Deserialize<'de> {
1149    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
1150        deserializer.deserialize_seq(SmallVecVisitor{phantom: PhantomData})
1151    }
1152}
1153
1154#[cfg(feature = "serde")]
1155struct SmallVecVisitor<A> {
1156    phantom: PhantomData<A>
1157}
1158
1159#[cfg(feature = "serde")]
1160impl<'de, A: Array> Visitor<'de> for SmallVecVisitor<A>
1161where A::Item: Deserialize<'de>,
1162{
1163    type Value = SmallVec<A>;
1164
1165    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1166        formatter.write_str("a sequence")
1167    }
1168
1169    fn visit_seq<B>(self, mut seq: B) -> Result<Self::Value, B::Error>
1170        where
1171            B: SeqAccess<'de>,
1172    {
1173        let len = seq.size_hint().unwrap_or(0);
1174        let mut values = SmallVec::with_capacity(len);
1175
1176        while let Some(value) = seq.next_element()? {
1177            values.push(value);
1178        }
1179
1180        Ok(values)
1181    }
1182}
1183
1184
1185#[cfg(feature = "specialization")]
1186trait SpecFrom<A: Array, S> {
1187    fn spec_from(slice: S) -> SmallVec<A>;
1188}
1189
1190#[cfg(feature = "specialization")]
1191mod specialization;
1192
1193#[cfg(feature = "specialization")]
1194impl<'a, A: Array> SpecFrom<A, &'a [A::Item]> for SmallVec<A> where A::Item: Copy {
1195    #[inline]
1196    fn spec_from(slice: &'a [A::Item]) -> SmallVec<A> {
1197        SmallVec::from_slice(slice)
1198    }
1199}
1200
1201impl<'a, A: Array + Copy> From<&'a [A::Item]> for SmallVec<A> where A::Item: Clone {
1202    #[cfg(not(feature = "specialization"))]
1203    #[inline]
1204    fn from(slice: &'a [A::Item]) -> SmallVec<A> {
1205        slice.into_iter().cloned().collect()
1206    }
1207
1208    #[cfg(feature = "specialization")]
1209    #[inline]
1210    fn from(slice: &'a [A::Item]) -> SmallVec<A> {
1211        SmallVec::spec_from(slice)
1212    }
1213}
1214
1215impl<A: Array + Copy> From<Vec<A::Item>> for SmallVec<A> {
1216    #[inline]
1217    fn from(vec: Vec<A::Item>) -> SmallVec<A> {
1218        SmallVec::from_vec(vec)
1219    }
1220}
1221
1222impl<A: Array + Copy> From<A> for SmallVec<A> {
1223    #[inline]
1224    fn from(array: A) -> SmallVec<A> {
1225        SmallVec::from_buf(array)
1226    }
1227}
1228
1229macro_rules! impl_index {
1230    ($index_type: ty, $output_type: ty) => {
1231        impl<A: Array + Copy> ops::Index<$index_type> for SmallVec<A> {
1232            type Output = $output_type;
1233            #[inline]
1234            fn index(&self, index: $index_type) -> &$output_type {
1235                &(&**self)[index]
1236            }
1237        }
1238
1239        impl<A: Array + Copy> ops::IndexMut<$index_type> for SmallVec<A> {
1240            #[inline]
1241            fn index_mut(&mut self, index: $index_type) -> &mut $output_type {
1242                &mut (&mut **self)[index]
1243            }
1244        }
1245    }
1246}
1247
1248impl_index!(usize, A::Item);
1249impl_index!(ops::Range<usize>, [A::Item]);
1250impl_index!(ops::RangeFrom<usize>, [A::Item]);
1251impl_index!(ops::RangeTo<usize>, [A::Item]);
1252impl_index!(ops::RangeFull, [A::Item]);
1253
1254impl<A: Array + Copy> ExtendFromSlice<A::Item> for SmallVec<A> where A::Item: Copy {
1255    fn extend_from_slice(&mut self, other: &[A::Item]) {
1256        SmallVec::extend_from_slice(self, other)
1257    }
1258}
1259
1260#[allow(deprecated)]
1261impl<A: Array + Copy> VecLike<A::Item> for SmallVec<A> {
1262    #[inline]
1263    fn push(&mut self, value: A::Item) {
1264        SmallVec::push(self, value);
1265    }
1266}
1267
1268impl<A: Array + Copy> FromIterator<A::Item> for SmallVec<A> {
1269    fn from_iter<I: IntoIterator<Item=A::Item>>(iterable: I) -> SmallVec<A> {
1270        let mut v = SmallVec::new();
1271        v.extend(iterable);
1272        v
1273    }
1274}
1275
1276impl<A: Array + Copy> Extend<A::Item> for SmallVec<A> {
1277    fn extend<I: IntoIterator<Item=A::Item>>(&mut self, iterable: I) {
1278        let mut iter = iterable.into_iter();
1279        let (lower_size_bound, _) = iter.size_hint();
1280        self.reserve(lower_size_bound);
1281
1282        unsafe {
1283            let (ptr, len_ptr, cap) = self.triple_mut();
1284            let mut len = SetLenOnDrop::new(len_ptr);
1285            while len.get() < cap {
1286                if let Some(out) = iter.next() {
1287                    ptr::write(ptr.offset(len.get() as isize), out);
1288                    len.increment_len(1);
1289                } else {
1290                    return;
1291                }
1292            }
1293        }
1294
1295        for elem in iter {
1296            self.push(elem);
1297        }
1298    }
1299}
1300
1301impl<A: Array + Copy> fmt::Debug for SmallVec<A> where A::Item: fmt::Debug {
1302    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1303        f.debug_list().entries(self.iter()).finish()
1304    }
1305}
1306
1307impl<A: Array + Copy> Default for SmallVec<A> {
1308    #[inline]
1309    fn default() -> SmallVec<A> {
1310        SmallVec::new()
1311    }
1312}
1313
1314#[cfg(feature = "may_dangle")]
1315unsafe impl<#[may_dangle] A: Array + Copy> Drop for SmallVec<A> {
1316    fn drop(&mut self) {
1317        unsafe {
1318            if self.spilled() {
1319                let (ptr, len) = self.data.heap();
1320                Vec::from_raw_parts(ptr, len, self.capacity);
1321            } else {
1322                ptr::drop_in_place(&mut self[..]);
1323            }
1324        }
1325    }
1326}
1327
1328#[cfg(not(feature = "may_dangle"))]
1329impl<A: Array + Copy> Drop for SmallVec<A> {
1330    fn drop(&mut self) {
1331        unsafe {
1332            if self.spilled() {
1333                let (ptr, len) = self.data.heap();
1334                Vec::from_raw_parts(ptr, len, self.capacity);
1335            } else {
1336                ptr::drop_in_place(&mut self[..]);
1337            }
1338        }
1339    }
1340}
1341
1342impl<A: Array + Copy> Clone for SmallVec<A> where A::Item: Clone {
1343    fn clone(&self) -> SmallVec<A> {
1344        let mut new_vector = SmallVec::with_capacity(self.len());
1345        for element in self.iter() {
1346            new_vector.push((*element).clone())
1347        }
1348        new_vector
1349    }
1350}
1351
1352impl<A: Array + Copy, B: Array + Copy> PartialEq<SmallVec<B>> for SmallVec<A>
1353    where A::Item: PartialEq<B::Item> {
1354    #[inline]
1355    fn eq(&self, other: &SmallVec<B>) -> bool { self[..] == other[..] }
1356    #[inline]
1357    fn ne(&self, other: &SmallVec<B>) -> bool { self[..] != other[..] }
1358}
1359
1360impl<A: Array + Copy> Eq for SmallVec<A> where A::Item: Eq {}
1361
1362impl<A: Array + Copy> PartialOrd for SmallVec<A> where A::Item: PartialOrd {
1363    #[inline]
1364    fn partial_cmp(&self, other: &SmallVec<A>) -> Option<cmp::Ordering> {
1365        PartialOrd::partial_cmp(&**self, &**other)
1366    }
1367}
1368
1369impl<A: Array + Copy> Ord for SmallVec<A> where A::Item: Ord {
1370    #[inline]
1371    fn cmp(&self, other: &SmallVec<A>) -> cmp::Ordering {
1372        Ord::cmp(&**self, &**other)
1373    }
1374}
1375
1376impl<A: Array + Copy> Hash for SmallVec<A> where A::Item: Hash {
1377    fn hash<H: Hasher>(&self, state: &mut H) {
1378        (**self).hash(state)
1379    }
1380}
1381
1382unsafe impl<A: Array + Copy> Send for SmallVec<A> where A::Item: Send {}
1383
1384/// An iterator that consumes a `SmallVec` and yields its items by value.
1385///
1386/// Returned from [`SmallVec::into_iter`][1].
1387///
1388/// [1]: struct.SmallVec.html#method.into_iter
1389pub struct IntoIter<A: Array + Copy> {
1390    data: SmallVec<A>,
1391    current: usize,
1392    end: usize,
1393}
1394
1395impl<A: Array + Copy> Drop for IntoIter<A> {
1396    fn drop(&mut self) {
1397        for _ in self { }
1398    }
1399}
1400
1401impl<A: Array + Copy> Iterator for IntoIter<A> {
1402    type Item = A::Item;
1403
1404    #[inline]
1405    fn next(&mut self) -> Option<A::Item> {
1406        if self.current == self.end {
1407            None
1408        }
1409        else {
1410            unsafe {
1411                let current = self.current as isize;
1412                self.current += 1;
1413                Some(ptr::read(self.data.as_ptr().offset(current)))
1414            }
1415        }
1416    }
1417
1418    #[inline]
1419    fn size_hint(&self) -> (usize, Option<usize>) {
1420        let size = self.end - self.current;
1421        (size, Some(size))
1422    }
1423}
1424
1425impl<A: Array + Copy> DoubleEndedIterator for IntoIter<A> {
1426    #[inline]
1427    fn next_back(&mut self) -> Option<A::Item> {
1428        if self.current == self.end {
1429            None
1430        }
1431        else {
1432            unsafe {
1433                self.end -= 1;
1434                Some(ptr::read(self.data.as_ptr().offset(self.end as isize)))
1435            }
1436        }
1437    }
1438}
1439
1440impl<A: Array + Copy> ExactSizeIterator for IntoIter<A> { }
1441
1442impl<A: Array + Copy> IntoIterator for SmallVec<A> {
1443    type IntoIter = IntoIter<A>;
1444    type Item = A::Item;
1445    fn into_iter(mut self) -> Self::IntoIter {
1446        unsafe {
1447            // Set SmallVec len to zero as `IntoIter` drop handles dropping of the elements
1448            let len = self.len();
1449            self.set_len(0);
1450            IntoIter {
1451                data: self,
1452                current: 0,
1453                end: len,
1454            }
1455        }
1456    }
1457}
1458
1459impl<'a, A: Array + Copy> IntoIterator for &'a SmallVec<A> {
1460    type IntoIter = slice::Iter<'a, A::Item>;
1461    type Item = &'a A::Item;
1462    fn into_iter(self) -> Self::IntoIter {
1463        self.iter()
1464    }
1465}
1466
1467impl<'a, A: Array + Copy> IntoIterator for &'a mut SmallVec<A> {
1468    type IntoIter = slice::IterMut<'a, A::Item>;
1469    type Item = &'a mut A::Item;
1470    fn into_iter(self) -> Self::IntoIter {
1471        self.iter_mut()
1472    }
1473}
1474
1475/// Types that can be used as the backing store for a SmallVec
1476pub unsafe trait Array {
1477    /// The type of the array's elements.
1478    type Item;
1479    /// Returns the number of items the array can hold.
1480    fn size() -> usize;
1481    /// Returns a pointer to the first element of the array.
1482    fn ptr(&self) -> *const Self::Item;
1483    /// Returns a mutable pointer to the first element of the array.
1484    fn ptr_mut(&mut self) -> *mut Self::Item;
1485}
1486
1487/// Set the length of the vec when the `SetLenOnDrop` value goes out of scope.
1488///
1489/// Copied from https://github.com/rust-lang/rust/pull/36355
1490struct SetLenOnDrop<'a> {
1491    len: &'a mut usize,
1492    local_len: usize,
1493}
1494
1495impl<'a> SetLenOnDrop<'a> {
1496    #[inline]
1497    fn new(len: &'a mut usize) -> Self {
1498        SetLenOnDrop { local_len: *len, len: len }
1499    }
1500
1501    #[inline]
1502    fn get(&self) -> usize {
1503        self.local_len
1504    }
1505
1506    #[inline]
1507    fn increment_len(&mut self, increment: usize) {
1508        self.local_len += increment;
1509    }
1510}
1511
1512impl<'a> Drop for SetLenOnDrop<'a> {
1513    #[inline]
1514    fn drop(&mut self) {
1515        *self.len = self.local_len;
1516    }
1517}
1518
1519macro_rules! impl_array(
1520    ($($size:expr),+) => {
1521        $(
1522            unsafe impl<T> Array for [T; $size] {
1523                type Item = T;
1524                fn size() -> usize { $size }
1525                fn ptr(&self) -> *const T { self.as_ptr() }
1526                fn ptr_mut(&mut self) -> *mut T { self.as_mut_ptr() }
1527            }
1528        )+
1529    }
1530);
1531
1532impl_array!(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 20, 24, 32, 36,
1533            0x40, 0x80, 0x100, 0x200, 0x400, 0x800, 0x1000, 0x2000, 0x4000, 0x8000,
1534            0x10000, 0x20000, 0x40000, 0x80000, 0x100000);
1535
1536#[cfg(test)]
1537mod tests {
1538    use SmallVec;
1539
1540    use std::iter::FromIterator;
1541
1542    #[cfg(feature = "std")]
1543    use std::borrow::ToOwned;
1544    #[cfg(not(feature = "std"))]
1545    use alloc::borrow::ToOwned;
1546    #[cfg(feature = "std")]
1547    use std::rc::Rc;
1548    #[cfg(not(feature = "std"))]
1549    use alloc::rc::Rc;
1550    #[cfg(not(feature = "std"))]
1551    use alloc::boxed::Box;
1552    #[cfg(not(feature = "std"))]
1553    use alloc::vec::Vec;
1554
1555    #[test]
1556    pub fn test_zero() {
1557        let mut v = SmallVec::<[_; 0]>::new();
1558        assert!(!v.spilled());
1559        v.push(0usize);
1560        assert!(v.spilled());
1561        assert_eq!(&*v, &[0]);
1562    }
1563
1564    // We heap allocate all these strings so that double frees will show up under valgrind.
1565
1566    #[test]
1567    pub fn test_inline() {
1568        let mut v = SmallVec::<[_; 16]>::new();
1569        v.push(0.to_owned());
1570        v.push(1.to_owned());
1571        assert_eq!(&*v, &[
1572            0.to_owned(),
1573            1.to_owned(),
1574        ][..]);
1575    }
1576
1577    #[test]
1578    pub fn test_spill() {
1579        let mut v = SmallVec::<[_; 2]>::new();
1580        v.push(0);
1581        assert_eq!(v[0], 0);
1582        v.push(1.to_owned());
1583        v.push(2.to_owned());
1584        assert_eq!(v[0], 0);
1585        v.push(3.to_owned());
1586        assert_eq!(&*v, &[
1587            0.to_owned(),
1588            1.to_owned(),
1589            2.to_owned(),
1590            3.to_owned(),
1591        ][..]);
1592    }
1593
1594    #[test]
1595    pub fn test_double_spill() {
1596        let mut v = SmallVec::<[_; 2]>::new();
1597        v.push(0.to_owned());
1598        v.push(1.to_owned());
1599        v.push(2.to_owned());
1600        v.push(3.to_owned());
1601        v.push(0.to_owned());
1602        v.push(1.to_owned());
1603        v.push(2.to_owned());
1604        v.push(3.to_owned());
1605        assert_eq!(&*v, &[
1606        0.to_owned(),
1607        1.to_owned(),
1608        2.to_owned(),
1609        3.to_owned(),
1610        0.to_owned(),
1611        1.to_owned(),
1612        2.to_owned(),
1613        3.to_owned(),
1614        ][..]);
1615    }
1616
1617
1618    /// https://github.com/servo/rust-smallvec/issues/5
1619    #[test]
1620    fn issue_5() {
1621        assert!(Some(SmallVec::<[&u32; 2]>::new()).is_some());
1622    }
1623
1624    #[test]
1625    fn test_with_capacity() {
1626        let v: SmallVec<[u8; 3]> = SmallVec::with_capacity(1);
1627        assert!(v.is_empty());
1628        assert!(!v.spilled());
1629        assert_eq!(v.capacity(), 3);
1630
1631        let v: SmallVec<[u8; 3]> = SmallVec::with_capacity(10);
1632        assert!(v.is_empty());
1633        assert!(v.spilled());
1634        assert_eq!(v.capacity(), 10);
1635    }
1636
1637    #[test]
1638    fn drain() {
1639        let mut v: SmallVec<[u8; 2]> = SmallVec::new();
1640        v.push(3);
1641        assert_eq!(v.drain().collect::<Vec<_>>(), &[3]);
1642
1643        // spilling the vec
1644        v.push(3);
1645        v.push(4);
1646        v.push(5);
1647        assert_eq!(v.drain().collect::<Vec<_>>(), &[3, 4, 5]);
1648    }
1649
1650    #[test]
1651    fn drain_rev() {
1652        let mut v: SmallVec<[u8; 2]> = SmallVec::new();
1653        v.push(3);
1654        assert_eq!(v.drain().rev().collect::<Vec<_>>(), &[3]);
1655
1656        // spilling the vec
1657        v.push(3);
1658        v.push(4);
1659        v.push(5);
1660        assert_eq!(v.drain().rev().collect::<Vec<_>>(), &[5, 4, 3]);
1661    }
1662
1663    #[test]
1664    fn into_iter() {
1665        let mut v: SmallVec<[u8; 2]> = SmallVec::new();
1666        v.push(3);
1667        assert_eq!(v.into_iter().collect::<Vec<_>>(), &[3]);
1668
1669        // spilling the vec
1670        let mut v: SmallVec<[u8; 2]> = SmallVec::new();
1671        v.push(3);
1672        v.push(4);
1673        v.push(5);
1674        assert_eq!(v.into_iter().collect::<Vec<_>>(), &[3, 4, 5]);
1675    }
1676
1677    #[test]
1678    fn into_iter_rev() {
1679        let mut v: SmallVec<[u8; 2]> = SmallVec::new();
1680        v.push(3);
1681        assert_eq!(v.into_iter().rev().collect::<Vec<_>>(), &[3]);
1682
1683        // spilling the vec
1684        let mut v: SmallVec<[u8; 2]> = SmallVec::new();
1685        v.push(3);
1686        v.push(4);
1687        v.push(5);
1688        assert_eq!(v.into_iter().rev().collect::<Vec<_>>(), &[5, 4, 3]);
1689    }
1690
1691    #[test]
1692    fn test_capacity() {
1693        let mut v: SmallVec<[u8; 2]> = SmallVec::new();
1694        v.reserve(1);
1695        assert_eq!(v.capacity(), 2);
1696        assert!(!v.spilled());
1697
1698        v.reserve_exact(0x100);
1699        assert!(v.capacity() >= 0x100);
1700
1701        v.push(0);
1702        v.push(1);
1703        v.push(2);
1704        v.push(3);
1705
1706        v.shrink_to_fit();
1707        assert!(v.capacity() < 0x100);
1708    }
1709
1710    #[test]
1711    fn test_insert_many() {
1712        let mut v: SmallVec<[u8; 8]> = SmallVec::new();
1713        for x in 0..4 {
1714            v.push(x);
1715        }
1716        assert_eq!(v.len(), 4);
1717        v.insert_many(1, [5, 6].iter().cloned());
1718        assert_eq!(&v.iter().map(|v| *v).collect::<Vec<_>>(), &[0, 5, 6, 1, 2, 3]);
1719    }
1720
1721    struct MockHintIter<T: Iterator>{x: T, hint: usize}
1722    impl<T: Iterator> Iterator for MockHintIter<T> {
1723        type Item = T::Item;
1724        fn next(&mut self) -> Option<Self::Item> {self.x.next()}
1725        fn size_hint(&self) -> (usize, Option<usize>) {(self.hint, None)}
1726    }
1727
1728    #[test]
1729    fn test_insert_many_short_hint() {
1730        let mut v: SmallVec<[u8; 8]> = SmallVec::new();
1731        for x in 0..4 {
1732            v.push(x);
1733        }
1734        assert_eq!(v.len(), 4);
1735        v.insert_many(1, MockHintIter{x: [5, 6].iter().cloned(), hint: 5});
1736        assert_eq!(&v.iter().map(|v| *v).collect::<Vec<_>>(), &[0, 5, 6, 1, 2, 3]);
1737    }
1738
1739    #[test]
1740    fn test_insert_many_long_hint() {
1741        let mut v: SmallVec<[u8; 8]> = SmallVec::new();
1742        for x in 0..4 {
1743            v.push(x);
1744        }
1745        assert_eq!(v.len(), 4);
1746        v.insert_many(1, MockHintIter{x: [5, 6].iter().cloned(), hint: 1});
1747        assert_eq!(&v.iter().map(|v| *v).collect::<Vec<_>>(), &[0, 5, 6, 1, 2, 3]);
1748    }
1749
1750    #[test]
1751    #[should_panic]
1752    fn test_invalid_grow() {
1753        let mut v: SmallVec<[u8; 8]> = SmallVec::new();
1754        v.extend(0..8);
1755        v.grow(5);
1756    }
1757
1758    #[test]
1759    fn test_insert_from_slice() {
1760        let mut v: SmallVec<[u8; 8]> = SmallVec::new();
1761        for x in 0..4 {
1762            v.push(x);
1763        }
1764        assert_eq!(v.len(), 4);
1765        v.insert_from_slice(1, &[5, 6]);
1766        assert_eq!(&v.iter().map(|v| *v).collect::<Vec<_>>(), &[0, 5, 6, 1, 2, 3]);
1767    }
1768
1769    #[test]
1770    fn test_extend_from_slice() {
1771        let mut v: SmallVec<[u8; 8]> = SmallVec::new();
1772        for x in 0..4 {
1773            v.push(x);
1774        }
1775        assert_eq!(v.len(), 4);
1776        v.extend_from_slice(&[5, 6]);
1777        assert_eq!(&v.iter().map(|v| *v).collect::<Vec<_>>(), &[0, 1, 2, 3, 5, 6]);
1778    }
1779
1780    #[test]
1781    fn test_eq() {
1782        let mut a: SmallVec<[u32; 2]> = SmallVec::new();
1783        let mut b: SmallVec<[u32; 2]> = SmallVec::new();
1784        let mut c: SmallVec<[u32; 2]> = SmallVec::new();
1785        // a = [1, 2]
1786        a.push(1);
1787        a.push(2);
1788        // b = [1, 2]
1789        b.push(1);
1790        b.push(2);
1791        // c = [3, 4]
1792        c.push(3);
1793        c.push(4);
1794
1795        assert!(a == b);
1796        assert!(a != c);
1797    }
1798
1799    #[test]
1800    fn test_ord() {
1801        let mut a: SmallVec<[u32; 2]> = SmallVec::new();
1802        let mut b: SmallVec<[u32; 2]> = SmallVec::new();
1803        let mut c: SmallVec<[u32; 2]> = SmallVec::new();
1804        // a = [1]
1805        a.push(1);
1806        // b = [1, 1]
1807        b.push(1);
1808        b.push(1);
1809        // c = [1, 2]
1810        c.push(1);
1811        c.push(2);
1812
1813        assert!(a < b);
1814        assert!(b > a);
1815        assert!(b < c);
1816        assert!(c > b);
1817    }
1818
1819    #[cfg(feature = "std")]
1820    #[test]
1821    fn test_hash() {
1822        use std::hash::Hash;
1823        use std::collections::hash_map::DefaultHasher;
1824
1825        {
1826            let mut a: SmallVec<[u32; 2]> = SmallVec::new();
1827            let b = [1, 2];
1828            a.extend(b.iter().cloned());
1829            let mut hasher = DefaultHasher::new();
1830            assert_eq!(a.hash(&mut hasher), b.hash(&mut hasher));
1831        }
1832        {
1833            let mut a: SmallVec<[u32; 2]> = SmallVec::new();
1834            let b = [1, 2, 11, 12];
1835            a.extend(b.iter().cloned());
1836            let mut hasher = DefaultHasher::new();
1837            assert_eq!(a.hash(&mut hasher), b.hash(&mut hasher));
1838        }
1839    }
1840
1841    #[test]
1842    fn test_as_ref() {
1843        let mut a: SmallVec<[u32; 2]> = SmallVec::new();
1844        a.push(1);
1845        assert_eq!(a.as_ref(), [1]);
1846        a.push(2);
1847        assert_eq!(a.as_ref(), [1, 2]);
1848        a.push(3);
1849        assert_eq!(a.as_ref(), [1, 2, 3]);
1850    }
1851
1852    #[test]
1853    fn test_as_mut() {
1854        let mut a: SmallVec<[u32; 2]> = SmallVec::new();
1855        a.push(1);
1856        assert_eq!(a.as_mut(), [1]);
1857        a.push(2);
1858        assert_eq!(a.as_mut(), [1, 2]);
1859        a.push(3);
1860        assert_eq!(a.as_mut(), [1, 2, 3]);
1861        a.as_mut()[1] = 4;
1862        assert_eq!(a.as_mut(), [1, 4, 3]);
1863    }
1864
1865    #[test]
1866    fn test_borrow() {
1867        use std::borrow::Borrow;
1868
1869        let mut a: SmallVec<[u32; 2]> = SmallVec::new();
1870        a.push(1);
1871        assert_eq!(a.borrow(), [1]);
1872        a.push(2);
1873        assert_eq!(a.borrow(), [1, 2]);
1874        a.push(3);
1875        assert_eq!(a.borrow(), [1, 2, 3]);
1876    }
1877
1878    #[test]
1879    fn test_borrow_mut() {
1880        use std::borrow::BorrowMut;
1881
1882        let mut a: SmallVec<[u32; 2]> = SmallVec::new();
1883        a.push(1);
1884        assert_eq!(a.borrow_mut(), [1]);
1885        a.push(2);
1886        assert_eq!(a.borrow_mut(), [1, 2]);
1887        a.push(3);
1888        assert_eq!(a.borrow_mut(), [1, 2, 3]);
1889        BorrowMut::<[u32]>::borrow_mut(&mut a)[1] = 4;
1890        assert_eq!(a.borrow_mut(), [1, 4, 3]);
1891    }
1892
1893    #[test]
1894    fn test_from() {
1895        assert_eq!(&SmallVec::<[u32; 2]>::from(&[1][..])[..], [1]);
1896        assert_eq!(&SmallVec::<[u32; 2]>::from(&[1, 2, 3][..])[..], [1, 2, 3]);
1897
1898        let vec = vec![];
1899        let small_vec: SmallVec<[u8; 3]> = SmallVec::from(vec);
1900        assert_eq!(&*small_vec, &[]);
1901        drop(small_vec);
1902
1903        let vec = vec![1, 2, 3, 4, 5];
1904        let small_vec: SmallVec<[u8; 3]> = SmallVec::from(vec);
1905        assert_eq!(&*small_vec, &[1, 2, 3, 4, 5]);
1906        drop(small_vec);
1907
1908        let vec = vec![1, 2, 3, 4, 5];
1909        let small_vec: SmallVec<[u8; 1]> = SmallVec::from(vec);
1910        assert_eq!(&*small_vec, &[1, 2, 3, 4, 5]);
1911        drop(small_vec);
1912
1913        let array = [1];
1914        let small_vec: SmallVec<[u8; 1]> = SmallVec::from(array);
1915        assert_eq!(&*small_vec, &[1]);
1916        drop(small_vec);
1917
1918        let array = [99; 128];
1919        let small_vec: SmallVec<[u8; 128]> = SmallVec::from(array);
1920        assert_eq!(&*small_vec, vec![99u8; 128].as_slice());
1921        drop(small_vec);
1922    }
1923
1924    #[test]
1925    fn test_from_slice() {
1926        assert_eq!(&SmallVec::<[u32; 2]>::from_slice(&[1][..])[..], [1]);
1927        assert_eq!(&SmallVec::<[u32; 2]>::from_slice(&[1, 2, 3][..])[..], [1, 2, 3]);
1928    }
1929
1930    #[test]
1931    fn test_exact_size_iterator() {
1932        let mut vec = SmallVec::<[u32; 2]>::from(&[1, 2, 3][..]);
1933        assert_eq!(vec.clone().into_iter().len(), 3);
1934        assert_eq!(vec.drain().len(), 3);
1935    }
1936
1937    #[test]
1938    #[allow(deprecated)]
1939    fn veclike_deref_slice() {
1940        use super::VecLike;
1941
1942        fn test<T: VecLike<i32>>(vec: &mut T) {
1943            assert!(!vec.is_empty());
1944            assert_eq!(vec.len(), 3);
1945
1946            vec.sort();
1947            assert_eq!(&vec[..], [1, 2, 3]);
1948        }
1949
1950        let mut vec = SmallVec::<[i32; 2]>::from(&[3, 1, 2][..]);
1951        test(&mut vec);
1952    }
1953
1954    #[test]
1955    fn shrink_to_fit_unspill() {
1956        let mut vec = SmallVec::<[u8; 2]>::from_iter(0..3);
1957        vec.pop();
1958        assert!(vec.spilled());
1959        vec.shrink_to_fit();
1960        assert!(!vec.spilled(), "shrink_to_fit will un-spill if possible");
1961    }
1962
1963    #[test]
1964    fn test_into_vec() {
1965        let vec = SmallVec::<[u8; 2]>::from_iter(0..2);
1966        assert_eq!(vec.into_vec(), vec![0, 1]);
1967
1968        let vec = SmallVec::<[u8; 2]>::from_iter(0..3);
1969        assert_eq!(vec.into_vec(), vec![0, 1, 2]);
1970    }
1971
1972    #[test]
1973    fn test_into_inner() {
1974        let vec = SmallVec::<[u8; 2]>::from_iter(0..2);
1975        assert_eq!(vec.into_inner(), Ok([0, 1]));
1976
1977        let vec = SmallVec::<[u8; 2]>::from_iter(0..1);
1978        assert_eq!(vec.clone().into_inner(), Err(vec));
1979
1980        let vec = SmallVec::<[u8; 2]>::from_iter(0..3);
1981        assert_eq!(vec.clone().into_inner(), Err(vec));
1982    }
1983
1984    #[test]
1985    fn test_from_vec() {
1986        let vec = vec![];
1987        let small_vec: SmallVec<[u8; 3]> = SmallVec::from_vec(vec);
1988        assert_eq!(&*small_vec, &[]);
1989        drop(small_vec);
1990
1991        let vec = vec![];
1992        let small_vec: SmallVec<[u8; 1]> = SmallVec::from_vec(vec);
1993        assert_eq!(&*small_vec, &[]);
1994        drop(small_vec);
1995
1996        let vec = vec![1];
1997        let small_vec: SmallVec<[u8; 3]> = SmallVec::from_vec(vec);
1998        assert_eq!(&*small_vec, &[1]);
1999        drop(small_vec);
2000
2001        let vec = vec![1, 2, 3];
2002        let small_vec: SmallVec<[u8; 3]> = SmallVec::from_vec(vec);
2003        assert_eq!(&*small_vec, &[1, 2, 3]);
2004        drop(small_vec);
2005
2006        let vec = vec![1, 2, 3, 4, 5];
2007        let small_vec: SmallVec<[u8; 3]> = SmallVec::from_vec(vec);
2008        assert_eq!(&*small_vec, &[1, 2, 3, 4, 5]);
2009        drop(small_vec);
2010
2011        let vec = vec![1, 2, 3, 4, 5];
2012        let small_vec: SmallVec<[u8; 1]> = SmallVec::from_vec(vec);
2013        assert_eq!(&*small_vec, &[1, 2, 3, 4, 5]);
2014        drop(small_vec);
2015    }
2016
2017    #[test]
2018    fn test_retain() {
2019        // Test inline data storate
2020        let mut sv: SmallVec<[i32; 5]> = SmallVec::from_slice(&[1, 2, 3, 3, 4]);
2021        sv.retain(|&mut i| i != 3);
2022        assert_eq!(sv.pop(), Some(4));
2023        assert_eq!(sv.pop(), Some(2));
2024        assert_eq!(sv.pop(), Some(1));
2025        assert_eq!(sv.pop(), None);
2026
2027        // Test spilled data storage
2028        let mut sv: SmallVec<[i32; 3]> = SmallVec::from_slice(&[1, 2, 3, 3, 4]);
2029        sv.retain(|&mut i| i != 3);
2030        assert_eq!(sv.pop(), Some(4));
2031        assert_eq!(sv.pop(), Some(2));
2032        assert_eq!(sv.pop(), Some(1));
2033        assert_eq!(sv.pop(), None);
2034    }
2035
2036    #[test]
2037    fn test_dedup() {
2038        let mut dupes: SmallVec<[i32; 5]> = SmallVec::from_slice(&[1, 1, 2, 3, 3]);
2039        dupes.dedup();
2040        assert_eq!(&*dupes, &[1, 2, 3]);
2041
2042        let mut empty: SmallVec<[i32; 5]> = SmallVec::new();
2043        empty.dedup();
2044        assert!(empty.is_empty());
2045
2046        let mut all_ones: SmallVec<[i32; 5]> = SmallVec::from_slice(&[1, 1, 1, 1, 1]);
2047        all_ones.dedup();
2048        assert_eq!(all_ones.len(), 1);
2049
2050        let mut no_dupes: SmallVec<[i32; 5]> = SmallVec::from_slice(&[1, 2, 3, 4, 5]);
2051        no_dupes.dedup();
2052        assert_eq!(no_dupes.len(), 5);
2053    }
2054
2055    #[test]
2056    fn test_resize() {
2057        let mut v: SmallVec<[i32; 8]> = SmallVec::new();
2058        v.push(1);
2059        v.resize(5, 0);
2060        assert_eq!(v[..], [1, 0, 0, 0, 0][..]);
2061
2062        v.resize(2, -1);
2063        assert_eq!(v[..], [1, 0][..]);
2064    }
2065
2066    #[cfg(feature = "std")]
2067    #[test]
2068    fn test_write() {
2069        use io::Write;
2070
2071        let data = [1, 2, 3, 4, 5];
2072
2073        let mut small_vec: SmallVec<[u8; 2]> = SmallVec::new();
2074        let len = small_vec.write(&data[..]).unwrap();
2075        assert_eq!(len, 5);
2076        assert_eq!(small_vec.as_ref(), data.as_ref());
2077
2078        let mut small_vec: SmallVec<[u8; 2]> = SmallVec::new();
2079        small_vec.write_all(&data[..]).unwrap();
2080        assert_eq!(small_vec.as_ref(), data.as_ref());
2081    }
2082
2083    #[cfg(feature = "serde")]
2084    extern crate bincode;
2085
2086    #[cfg(feature = "serde")]
2087    #[test]
2088    fn test_serde() {
2089        use self::bincode::{config, deserialize};
2090        let mut small_vec: SmallVec<[i32; 2]> = SmallVec::new();
2091        small_vec.push(1);
2092        let encoded = config().limit(100).serialize(&small_vec).unwrap();
2093        let decoded: SmallVec<[i32; 2]> = deserialize(&encoded).unwrap();
2094        assert_eq!(small_vec, decoded);
2095        small_vec.push(2);
2096        // Spill the vec
2097        small_vec.push(3);
2098        small_vec.push(4);
2099        // Check again after spilling.
2100        let encoded = config().limit(100).serialize(&small_vec).unwrap();
2101        let decoded: SmallVec<[i32; 2]> = deserialize(&encoded).unwrap();
2102        assert_eq!(small_vec, decoded);
2103    }
2104
2105    #[test]
2106    fn grow_to_shrink() {
2107        let mut v: SmallVec<[u8; 2]> = SmallVec::new();
2108        v.push(1);
2109        v.push(2);
2110        v.push(3);
2111        assert!(v.spilled());
2112        v.clear();
2113        // Shrink to inline.
2114        v.grow(2);
2115        assert!(!v.spilled());
2116        assert_eq!(v.capacity(), 2);
2117        assert_eq!(v.len(), 0);
2118        v.push(4);
2119        assert_eq!(v[..], [4]);
2120    }
2121
2122    #[test]
2123    fn resumable_extend() {
2124        let s = "a b c";
2125        // This iterator yields: (Some('a'), None, Some('b'), None, Some('c')), None
2126        let it = s
2127            .chars()
2128            .scan(0, |_, ch| if ch.is_whitespace() { None } else { Some(ch) });
2129        let mut v: SmallVec<[char; 4]> = SmallVec::new();
2130        v.extend(it);
2131        assert_eq!(v[..], ['a']);
2132    }
2133
2134    #[test]
2135    fn grow_spilled_same_size() {
2136        let mut v: SmallVec<[u8; 2]> = SmallVec::new();
2137        v.push(0);
2138        v.push(1);
2139        v.push(2);
2140        assert!(v.spilled());
2141        assert_eq!(v.capacity(), 4);
2142        // grow with the same capacity
2143        v.grow(4);
2144        assert_eq!(v.capacity(), 4);
2145        assert_eq!(v[..], [0, 1, 2]);
2146    }
2147}