From 9e5f7d5631b8f4009ac1c693e585d4b7108d4275 Mon Sep 17 00:00:00 2001 From: mark Date: Thu, 27 Aug 2020 22:58:48 -0500 Subject: mv compiler to compiler/ --- compiler/rustc_data_structures/src/thin_vec.rs | 82 ++++++++++++++++++++++++++ 1 file changed, 82 insertions(+) create mode 100644 compiler/rustc_data_structures/src/thin_vec.rs (limited to 'compiler/rustc_data_structures/src/thin_vec.rs') diff --git a/compiler/rustc_data_structures/src/thin_vec.rs b/compiler/rustc_data_structures/src/thin_vec.rs new file mode 100644 index 00000000000..4d673fd5cf9 --- /dev/null +++ b/compiler/rustc_data_structures/src/thin_vec.rs @@ -0,0 +1,82 @@ +use crate::stable_hasher::{HashStable, StableHasher}; + +/// A vector type optimized for cases where this size is usually 0 (cf. `SmallVector`). +/// The `Option>` wrapping allows us to represent a zero sized vector with `None`, +/// which uses only a single (null) pointer. +#[derive(Clone, Encodable, Decodable, Debug)] +pub struct ThinVec(Option>>); + +impl ThinVec { + pub fn new() -> Self { + ThinVec(None) + } +} + +impl From> for ThinVec { + fn from(vec: Vec) -> Self { + if vec.is_empty() { ThinVec(None) } else { ThinVec(Some(Box::new(vec))) } + } +} + +impl Into> for ThinVec { + fn into(self) -> Vec { + match self { + ThinVec(None) => Vec::new(), + ThinVec(Some(vec)) => *vec, + } + } +} + +impl ::std::ops::Deref for ThinVec { + type Target = [T]; + fn deref(&self) -> &[T] { + match *self { + ThinVec(None) => &[], + ThinVec(Some(ref vec)) => vec, + } + } +} + +impl ::std::ops::DerefMut for ThinVec { + fn deref_mut(&mut self) -> &mut [T] { + match *self { + ThinVec(None) => &mut [], + ThinVec(Some(ref mut vec)) => vec, + } + } +} + +impl Extend for ThinVec { + fn extend>(&mut self, iter: I) { + match *self { + ThinVec(Some(ref mut vec)) => vec.extend(iter), + ThinVec(None) => *self = iter.into_iter().collect::>().into(), + } + } + + fn extend_one(&mut self, item: T) { + match *self { + ThinVec(Some(ref mut vec)) => vec.push(item), + ThinVec(None) => *self = vec![item].into(), + } + } + + fn extend_reserve(&mut self, additional: usize) { + match *self { + ThinVec(Some(ref mut vec)) => vec.reserve(additional), + ThinVec(None) => *self = Vec::with_capacity(additional).into(), + } + } +} + +impl, CTX> HashStable for ThinVec { + fn hash_stable(&self, hcx: &mut CTX, hasher: &mut StableHasher) { + (**self).hash_stable(hcx, hasher) + } +} + +impl Default for ThinVec { + fn default() -> Self { + Self(None) + } +} -- cgit 1.4.1-3-g733a5