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 associated 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 is_array(&self) -> bool {
57 pub fn with_capacity(cap: usize) -> Self {
58 let mut vec = SmallVec::new();
63 pub fn one(el: A::Element) -> Self {
64 SmallVec(AccumulateVec::one(el))
67 pub fn many<I: IntoIterator<Item=A::Element>>(els: I) -> Self {
68 SmallVec(AccumulateVec::many(els))
71 pub fn expect_one(self, err: &'static str) -> A::Element {
72 assert!(self.len() == 1, err);
74 AccumulateVec::Array(arr) => arr.into_iter().next().unwrap(),
75 AccumulateVec::Heap(vec) => vec.into_iter().next().unwrap(),
79 /// Will reallocate onto the heap if needed.
80 pub fn push(&mut self, el: A::Element) {
83 AccumulateVec::Array(ref mut array) => array.push(el),
84 AccumulateVec::Heap(ref mut vec) => vec.push(el),
88 pub fn reserve(&mut self, n: usize) {
90 AccumulateVec::Array(_) => {
91 if self.len() + n > A::LEN {
93 let array = mem::replace(&mut self.0,
94 AccumulateVec::Heap(Vec::with_capacity(len + n)));
95 if let AccumulateVec::Array(array) = array {
97 AccumulateVec::Heap(ref mut vec) => vec.extend(array),
103 AccumulateVec::Heap(ref mut vec) => vec.reserve(n)
107 pub unsafe fn set_len(&mut self, len: usize) {
109 AccumulateVec::Array(ref mut arr) => arr.set_len(len),
110 AccumulateVec::Heap(ref mut vec) => vec.set_len(len),
114 pub fn insert(&mut self, index: usize, element: A::Element) {
115 let len = self.len();
117 // Reserve space for shifting elements to the right
120 assert!(index <= len);
124 // The spot to put the new value
126 let p = self.as_mut_ptr().offset(index as isize);
127 // Shift everything over to make space. (Duplicating the
128 // `index`th element into two consecutive places.)
129 ptr::copy(p, p.offset(1), len - index);
130 // Write it in, overwriting the first copy of the `index`th
132 ptr::write(p, element);
134 self.set_len(len + 1);
138 pub fn truncate(&mut self, len: usize) {
140 while len < self.len() {
141 // Decrement len before the drop_in_place(), so a panic on Drop
142 // doesn't re-drop the just-failed value.
143 let newlen = self.len() - 1;
144 self.set_len(newlen);
145 ::std::ptr::drop_in_place(self.get_unchecked_mut(newlen));
151 impl<A: Array> Deref for SmallVec<A> {
152 type Target = AccumulateVec<A>;
153 fn deref(&self) -> &Self::Target {
158 impl<A: Array> DerefMut for SmallVec<A> {
159 fn deref_mut(&mut self) -> &mut AccumulateVec<A> {
164 impl<A: Array> FromIterator<A::Element> for SmallVec<A> {
165 fn from_iter<I>(iter: I) -> Self where I: IntoIterator<Item=A::Element> {
166 SmallVec(iter.into_iter().collect())
170 impl<A: Array> Extend<A::Element> for SmallVec<A> {
171 fn extend<I: IntoIterator<Item=A::Element>>(&mut self, iter: I) {
172 let iter = iter.into_iter();
173 self.reserve(iter.size_hint().0);
175 AccumulateVec::Heap(ref mut vec) => vec.extend(iter),
176 _ => iter.for_each(|el| self.push(el))
181 impl<A: Array> IntoIterator for SmallVec<A> {
182 type Item = A::Element;
183 type IntoIter = IntoIter<A>;
184 fn into_iter(self) -> Self::IntoIter {
189 impl<A: Array> Default for SmallVec<A> {
190 fn default() -> SmallVec<A> {
195 impl<A> Encodable for SmallVec<A>
197 A::Element: Encodable {
198 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
199 s.emit_seq(self.len(), |s| {
200 for (i, e) in self.iter().enumerate() {
201 s.emit_seq_elt(i, |s| e.encode(s))?;
208 impl<A> Decodable for SmallVec<A>
210 A::Element: Decodable {
211 fn decode<D: Decoder>(d: &mut D) -> Result<SmallVec<A>, D::Error> {
212 d.read_seq(|d, len| {
213 (0..len).map(|i| d.read_seq_elt(i, |d| Decodable::decode(d))).collect()
221 use self::test::Bencher;
226 fn fill_small_vec_1_10_with_cap(b: &mut Bencher) {
228 let mut sv: SmallVec<[usize; 1]> = SmallVec::with_capacity(10);
235 fn fill_small_vec_1_10_wo_cap(b: &mut Bencher) {
237 let mut sv: SmallVec<[usize; 1]> = SmallVec::new();
244 fn fill_small_vec_8_10_with_cap(b: &mut Bencher) {
246 let mut sv: SmallVec<[usize; 8]> = SmallVec::with_capacity(10);
253 fn fill_small_vec_8_10_wo_cap(b: &mut Bencher) {
255 let mut sv: SmallVec<[usize; 8]> = SmallVec::new();
262 fn fill_small_vec_32_10_with_cap(b: &mut Bencher) {
264 let mut sv: SmallVec<[usize; 32]> = SmallVec::with_capacity(10);
271 fn fill_small_vec_32_10_wo_cap(b: &mut Bencher) {
273 let mut sv: SmallVec<[usize; 32]> = SmallVec::new();
280 fn fill_small_vec_1_50_with_cap(b: &mut Bencher) {
282 let mut sv: SmallVec<[usize; 1]> = SmallVec::with_capacity(50);
289 fn fill_small_vec_1_50_wo_cap(b: &mut Bencher) {
291 let mut sv: SmallVec<[usize; 1]> = SmallVec::new();
298 fn fill_small_vec_8_50_with_cap(b: &mut Bencher) {
300 let mut sv: SmallVec<[usize; 8]> = SmallVec::with_capacity(50);
307 fn fill_small_vec_8_50_wo_cap(b: &mut Bencher) {
309 let mut sv: SmallVec<[usize; 8]> = SmallVec::new();
316 fn fill_small_vec_32_50_with_cap(b: &mut Bencher) {
318 let mut sv: SmallVec<[usize; 32]> = SmallVec::with_capacity(50);
325 fn fill_small_vec_32_50_wo_cap(b: &mut Bencher) {
327 let mut sv: SmallVec<[usize; 32]> = SmallVec::new();