]> git.lizzy.rs Git - rust.git/blob - src/librustc_data_structures/thin_vec.rs
546686b46b8db4c92f2474b4f64ee354938cbe5a
[rust.git] / src / librustc_data_structures / thin_vec.rs
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.
4 //
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.
10
11 /// A vector type optimized for cases where this size is usually 0 (c.f. `SmallVector`).
12 /// The `Option<Box<..>>` wrapping allows us to represent a zero sized vector with `None`,
13 /// which uses only a single (null) pointer.
14 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
15 pub struct ThinVec<T>(Option<Box<Vec<T>>>);
16
17 impl<T> ThinVec<T> {
18     pub fn new() -> Self {
19         ThinVec(None)
20     }
21 }
22
23 impl<T> From<Vec<T>> for ThinVec<T> {
24     fn from(vec: Vec<T>) -> Self {
25         if vec.is_empty() {
26             ThinVec(None)
27         } else {
28             ThinVec(Some(Box::new(vec)))
29         }
30     }
31 }
32
33 impl<T> Into<Vec<T>> for ThinVec<T> {
34     fn into(self) -> Vec<T> {
35         match self {
36             ThinVec(None) => Vec::new(),
37             ThinVec(Some(vec)) => *vec,
38         }
39     }
40 }
41
42 impl<T> ::std::ops::Deref for ThinVec<T> {
43     type Target = [T];
44     fn deref(&self) -> &[T] {
45         match *self {
46             ThinVec(None) => &[],
47             ThinVec(Some(ref vec)) => vec,
48         }
49     }
50 }
51
52 impl<T> Extend<T> for ThinVec<T> {
53     fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
54         match *self {
55             ThinVec(Some(ref mut vec)) => vec.extend(iter),
56             ThinVec(None) => *self = iter.into_iter().collect::<Vec<_>>().into(),
57         }
58     }
59 }