]> git.lizzy.rs Git - rust.git/blob - src/librustc_data_structures/thin_vec.rs
Rollup merge of #68233 - danielframpton:update-compiler-builtins, r=alexcrichton
[rust.git] / src / librustc_data_structures / thin_vec.rs
1 use crate::stable_hasher::{HashStable, StableHasher};
2
3 /// A vector type optimized for cases where this size is usually 0 (cf. `SmallVector`).
4 /// The `Option<Box<..>>` wrapping allows us to represent a zero sized vector with `None`,
5 /// which uses only a single (null) pointer.
6 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
7 pub struct ThinVec<T>(Option<Box<Vec<T>>>);
8
9 impl<T> ThinVec<T> {
10     pub fn new() -> Self {
11         ThinVec(None)
12     }
13 }
14
15 impl<T> From<Vec<T>> for ThinVec<T> {
16     fn from(vec: Vec<T>) -> Self {
17         if vec.is_empty() { ThinVec(None) } else { ThinVec(Some(Box::new(vec))) }
18     }
19 }
20
21 impl<T> Into<Vec<T>> for ThinVec<T> {
22     fn into(self) -> Vec<T> {
23         match self {
24             ThinVec(None) => Vec::new(),
25             ThinVec(Some(vec)) => *vec,
26         }
27     }
28 }
29
30 impl<T> ::std::ops::Deref for ThinVec<T> {
31     type Target = [T];
32     fn deref(&self) -> &[T] {
33         match *self {
34             ThinVec(None) => &[],
35             ThinVec(Some(ref vec)) => vec,
36         }
37     }
38 }
39
40 impl<T> ::std::ops::DerefMut for ThinVec<T> {
41     fn deref_mut(&mut self) -> &mut [T] {
42         match *self {
43             ThinVec(None) => &mut [],
44             ThinVec(Some(ref mut vec)) => vec,
45         }
46     }
47 }
48
49 impl<T> Extend<T> for ThinVec<T> {
50     fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
51         match *self {
52             ThinVec(Some(ref mut vec)) => vec.extend(iter),
53             ThinVec(None) => *self = iter.into_iter().collect::<Vec<_>>().into(),
54         }
55     }
56 }
57
58 impl<T: HashStable<CTX>, CTX> HashStable<CTX> for ThinVec<T> {
59     fn hash_stable(&self, hcx: &mut CTX, hasher: &mut StableHasher) {
60         (**self).hash_stable(hcx, hasher)
61     }
62 }
63
64 impl<T> Default for ThinVec<T> {
65     fn default() -> Self {
66         Self(None)
67     }
68 }