diff options
| author | oxalica <oxalicc@pm.me> | 2022-08-07 04:17:04 +0800 |
|---|---|---|
| committer | oxalica <oxalicc@pm.me> | 2022-08-07 04:52:49 +0800 |
| commit | 1a94193602e65c99344ba313c71d4298b0d4c0cc (patch) | |
| tree | 9508194a2e9639cd04674e5b5d447392803d0e0b | |
| parent | d9e462fd97fe56a63da62d11bb5c4d2132e4c74a (diff) | |
| download | rust-1a94193602e65c99344ba313c71d4298b0d4c0cc.tar.gz rust-1a94193602e65c99344ba313c71d4298b0d4c0cc.zip | |
Impl more methods and traits for la_arena::ArenaMap
| -rw-r--r-- | lib/la-arena/src/map.rs | 43 |
1 files changed, 43 insertions, 0 deletions
diff --git a/lib/la-arena/src/map.rs b/lib/la-arena/src/map.rs index f74ec5d97cb..3034e33a788 100644 --- a/lib/la-arena/src/map.rs +++ b/lib/la-arena/src/map.rs @@ -21,6 +21,33 @@ impl<T, V> ArenaMap<Idx<T>, V> { Self { v: Vec::with_capacity(capacity), _ty: PhantomData } } + /// Reserves capacity for at least additional more elements to be inserted in the map. + pub fn reserve(&mut self, additional: usize) { + self.v.reserve(additional); + } + + /// Clears the map, removing all elements. + pub fn clear(&mut self) { + self.v.clear(); + } + + /// Shrinks the capacity of the map as much as possible. + pub fn shrink_to_fit(&mut self) { + let min_len = self.v.iter().rposition(|slot| slot.is_some()).map_or(0, |i| i + 1); + self.v.truncate(min_len); + self.v.shrink_to_fit(); + } + + /// Returns whether the map contains a value for the specified index. + pub fn contains_idx(&self, idx: Idx<T>) -> bool { + matches!(self.v.get(Self::to_idx(idx)), Some(Some(_))) + } + + /// Removes an index from the map, returning the value at the index if the index was previously in the map. + pub fn remove(&mut self, idx: Idx<T>) -> Option<V> { + self.v.get_mut(Self::to_idx(idx))?.take() + } + /// Inserts a value associated with a given arena index into the map. pub fn insert(&mut self, idx: Idx<T>, t: V) { let idx = Self::to_idx(idx); @@ -94,6 +121,22 @@ impl<T, V> Default for ArenaMap<Idx<V>, T> { } } +impl<T, V> Extend<(Idx<V>, T)> for ArenaMap<Idx<V>, T> { + fn extend<I: IntoIterator<Item = (Idx<V>, T)>>(&mut self, iter: I) { + iter.into_iter().for_each(move |(k, v)| { + self.insert(k, v); + }); + } +} + +impl<T, V> FromIterator<(Idx<V>, T)> for ArenaMap<Idx<V>, T> { + fn from_iter<I: IntoIterator<Item = (Idx<V>, T)>>(iter: I) -> Self { + let mut this = Self::new(); + this.extend(iter); + this + } +} + /// A view into a single entry in a map, which may either be vacant or occupied. /// /// This `enum` is constructed from the [`entry`] method on [`ArenaMap`]. |
