1 // Copyright 2016 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! A vector type intended to be used for collecting from iterators onto the stack.
13 //! Space for up to N elements is provided on the stack. If more elements are collected, Vec is
14 //! used to store the values on the heap. SmallVec is similar to AccumulateVec, but adds
15 //! the ability to push elements.
17 //! The N above is determined by Array's implementor, by way of an associatated constant.
19 use std::ops::{Deref, DerefMut};
20 use std::iter::{IntoIterator, FromIterator};
21 use std::fmt::{self, Debug};
25 use rustc_serialize::{Encodable, Encoder, Decodable, Decoder};
27 use accumulate_vec::{IntoIter, AccumulateVec};
30 pub struct SmallVec<A: Array>(AccumulateVec<A>);
32 impl<A> Clone for SmallVec<A>
35 fn clone(&self) -> Self {
36 SmallVec(self.0.clone())
40 impl<A> Debug for SmallVec<A>
41 where A: Array + Debug,
43 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
44 f.debug_tuple("SmallVec").field(&self.0).finish()
48 impl<A: Array> SmallVec<A> {
49 pub fn new() -> Self {
50 SmallVec(AccumulateVec::new())
53 pub fn with_capacity(cap: usize) -> Self {
54 let mut vec = SmallVec::new();
59 pub fn one(el: A::Element) -> Self {
60 SmallVec(AccumulateVec::one(el))
63 pub fn many<I: IntoIterator<Item=A::Element>>(els: I) -> Self {
64 SmallVec(AccumulateVec::many(els))
67 pub fn expect_one(self, err: &'static str) -> A::Element {
68 assert!(self.len() == 1, err);
70 AccumulateVec::Array(arr) => arr.into_iter().next().unwrap(),
71 AccumulateVec::Heap(vec) => vec.into_iter().next().unwrap(),
75 /// Will reallocate onto the heap if needed.
76 pub fn push(&mut self, el: A::Element) {
79 AccumulateVec::Array(ref mut array) => array.push(el),
80 AccumulateVec::Heap(ref mut vec) => vec.push(el),
84 pub fn reserve(&mut self, n: usize) {
86 AccumulateVec::Array(_) => {
87 if self.len() + n > A::LEN {
89 let array = mem::replace(&mut self.0,
90 AccumulateVec::Heap(Vec::with_capacity(len + n)));
91 if let AccumulateVec::Array(array) = array {
93 AccumulateVec::Heap(ref mut vec) => vec.extend(array),
99 AccumulateVec::Heap(ref mut vec) => vec.reserve(n)
103 pub unsafe fn set_len(&mut self, len: usize) {
105 AccumulateVec::Array(ref mut arr) => arr.set_len(len),
106 AccumulateVec::Heap(ref mut vec) => vec.set_len(len),
110 pub fn insert(&mut self, index: usize, element: A::Element) {
111 let len = self.len();
113 // Reserve space for shifting elements to the right
116 assert!(index <= len);
120 // The spot to put the new value
122 let p = self.as_mut_ptr().offset(index as isize);
123 // Shift everything over to make space. (Duplicating the
124 // `index`th element into two consecutive places.)
125 ptr::copy(p, p.offset(1), len - index);
126 // Write it in, overwriting the first copy of the `index`th
128 ptr::write(p, element);
130 self.set_len(len + 1);
134 pub fn truncate(&mut self, len: usize) {
136 while len < self.len() {
137 // Decrement len before the drop_in_place(), so a panic on Drop
138 // doesn't re-drop the just-failed value.
139 let newlen = self.len() - 1;
140 self.set_len(newlen);
141 ::std::ptr::drop_in_place(self.get_unchecked_mut(newlen));
147 impl<A: Array> Deref for SmallVec<A> {
148 type Target = AccumulateVec<A>;
149 fn deref(&self) -> &Self::Target {
154 impl<A: Array> DerefMut for SmallVec<A> {
155 fn deref_mut(&mut self) -> &mut AccumulateVec<A> {
160 impl<A: Array> FromIterator<A::Element> for SmallVec<A> {
161 fn from_iter<I>(iter: I) -> Self where I: IntoIterator<Item=A::Element> {
162 SmallVec(iter.into_iter().collect())
166 impl<A: Array> Extend<A::Element> for SmallVec<A> {
167 fn extend<I: IntoIterator<Item=A::Element>>(&mut self, iter: I) {
168 let iter = iter.into_iter();
169 self.reserve(iter.size_hint().0);
176 impl<A: Array> IntoIterator for SmallVec<A> {
177 type Item = A::Element;
178 type IntoIter = IntoIter<A>;
179 fn into_iter(self) -> Self::IntoIter {
184 impl<A: Array> Default for SmallVec<A> {
185 fn default() -> SmallVec<A> {
190 impl<A> Encodable for SmallVec<A>
192 A::Element: Encodable {
193 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
194 s.emit_seq(self.len(), |s| {
195 for (i, e) in self.iter().enumerate() {
196 try!(s.emit_seq_elt(i, |s| e.encode(s)));
203 impl<A> Decodable for SmallVec<A>
205 A::Element: Decodable {
206 fn decode<D: Decoder>(d: &mut D) -> Result<SmallVec<A>, D::Error> {
207 d.read_seq(|d, len| {
208 let mut vec = SmallVec::with_capacity(len);
210 vec.push(try!(d.read_seq_elt(i, |d| Decodable::decode(d))));