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