@@ -21,12 +21,42 @@ impl<T, V> ArenaMap<Idx<T>, V> {
2121 Self { v : Vec :: with_capacity ( capacity) , _ty : PhantomData }
2222 }
2323
24+ /// Reserves capacity for at least additional more elements to be inserted in the map.
25+ pub fn reserve ( & mut self , additional : usize ) {
26+ self . v . reserve ( additional) ;
27+ }
28+
29+ /// Clears the map, removing all elements.
30+ pub fn clear ( & mut self ) {
31+ self . v . clear ( ) ;
32+ }
33+
34+ /// Shrinks the capacity of the map as much as possible.
35+ pub fn shrink_to_fit ( & mut self ) {
36+ let min_len = self . v . iter ( ) . rposition ( |slot| slot. is_some ( ) ) . map_or ( 0 , |i| i + 1 ) ;
37+ self . v . truncate ( min_len) ;
38+ self . v . shrink_to_fit ( ) ;
39+ }
40+
41+ /// Returns whether the map contains a value for the specified index.
42+ pub fn contains_idx ( & self , idx : Idx < T > ) -> bool {
43+ matches ! ( self . v. get( Self :: to_idx( idx) ) , Some ( Some ( _) ) )
44+ }
45+
46+ /// Removes an index from the map, returning the value at the index if the index was previously in the map.
47+ pub fn remove ( & mut self , idx : Idx < T > ) -> Option < V > {
48+ self . v . get_mut ( Self :: to_idx ( idx) ) ?. take ( )
49+ }
50+
2451 /// Inserts a value associated with a given arena index into the map.
25- pub fn insert ( & mut self , idx : Idx < T > , t : V ) {
52+ ///
53+ /// If the map did not have this index present, None is returned.
54+ /// Otherwise, the value is updated, and the old value is returned.
55+ pub fn insert ( & mut self , idx : Idx < T > , t : V ) -> Option < V > {
2656 let idx = Self :: to_idx ( idx) ;
2757
2858 self . v . resize_with ( ( idx + 1 ) . max ( self . v . len ( ) ) , || None ) ;
29- self . v [ idx] = Some ( t) ;
59+ self . v [ idx] . replace ( t)
3060 }
3161
3262 /// Returns a reference to the value associated with the provided index
@@ -94,6 +124,22 @@ impl<T, V> Default for ArenaMap<Idx<V>, T> {
94124 }
95125}
96126
127+ impl < T , V > Extend < ( Idx < V > , T ) > for ArenaMap < Idx < V > , T > {
128+ fn extend < I : IntoIterator < Item = ( Idx < V > , T ) > > ( & mut self , iter : I ) {
129+ iter. into_iter ( ) . for_each ( move |( k, v) | {
130+ self . insert ( k, v) ;
131+ } ) ;
132+ }
133+ }
134+
135+ impl < T , V > FromIterator < ( Idx < V > , T ) > for ArenaMap < Idx < V > , T > {
136+ fn from_iter < I : IntoIterator < Item = ( Idx < V > , T ) > > ( iter : I ) -> Self {
137+ let mut this = Self :: new ( ) ;
138+ this. extend ( iter) ;
139+ this
140+ }
141+ }
142+
97143/// A view into a single entry in a map, which may either be vacant or occupied.
98144///
99145/// This `enum` is constructed from the [`entry`] method on [`ArenaMap`].
0 commit comments