@@ -182,6 +182,28 @@ pub enum Entry<'a, K, A: ?Sized + UnsafeAnyExt + 'a = UnsafeAny> {
182
182
Vacant ( VacantEntry < ' a , K , A > )
183
183
}
184
184
185
+ impl < ' a , K : Key , A : ?Sized + UnsafeAnyExt + ' a = UnsafeAny > Entry < ' a , K , A > {
186
+ /// Ensures a value is in the entry by inserting the default if empty, and returns
187
+ /// a mutable reference to the value in the entry.
188
+ pub fn or_insert ( self , default : K :: Value ) -> & ' a mut K :: Value
189
+ where K :: Value : Any + Implements < A > {
190
+ match self {
191
+ Entry :: Occupied ( inner) => inner. into_mut ( ) ,
192
+ Entry :: Vacant ( inner) => inner. insert ( default) ,
193
+ }
194
+ }
195
+
196
+ /// Ensures a value is in the entry by inserting the result of the default function if empty,
197
+ /// and returns a mutable reference to the value in the entry.
198
+ pub fn or_insert_with < F : FnOnce ( ) -> K :: Value > ( self , default : F ) -> & ' a mut K :: Value
199
+ where K :: Value : Any + Implements < A > {
200
+ match self {
201
+ Entry :: Occupied ( inner) => inner. into_mut ( ) ,
202
+ Entry :: Vacant ( inner) => inner. insert ( default ( ) ) ,
203
+ }
204
+ }
205
+ }
206
+
185
207
/// A view onto an occupied entry in a TypeMap.
186
208
pub struct OccupiedEntry < ' a , K , A : ?Sized + UnsafeAnyExt + ' a = UnsafeAny > {
187
209
data : hash_map:: OccupiedEntry < ' a , TypeId , Box < A > > ,
@@ -296,6 +318,16 @@ mod test {
296
318
assert ! ( map. contains:: <KeyType >( ) ) ;
297
319
}
298
320
321
+ #[ test] fn test_entry_or_insert ( ) {
322
+ let mut map = TypeMap :: new ( ) ;
323
+ map. entry :: < KeyType > ( ) . or_insert ( Value ( 20 ) ) . 0 += 1 ;
324
+ assert_eq ! ( map. get:: <KeyType >( ) . unwrap( ) , & Value ( 21 ) ) ;
325
+
326
+ // on existing value
327
+ map. entry :: < KeyType > ( ) . or_insert ( Value ( 100 ) ) . 0 += 1 ;
328
+ assert_eq ! ( map. get:: <KeyType >( ) . unwrap( ) , & Value ( 22 ) ) ;
329
+ }
330
+
299
331
#[ test] fn test_custom_bounds ( ) {
300
332
let mut map: SendMap = TypeMap :: custom ( ) ;
301
333
map. insert :: < KeyType > ( Value ( 10 ) ) ;
0 commit comments