Skip to content

Commit b6b12e5

Browse files
committed
Merge pull request #31 from blaenk/or_insert
implement or_insert API
2 parents 4c18439 + 7e74af6 commit b6b12e5

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

src/lib.rs

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -182,6 +182,28 @@ pub enum Entry<'a, K, A: ?Sized + UnsafeAnyExt + 'a = UnsafeAny> {
182182
Vacant(VacantEntry<'a, K, A>)
183183
}
184184

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+
185207
/// A view onto an occupied entry in a TypeMap.
186208
pub struct OccupiedEntry<'a, K, A: ?Sized + UnsafeAnyExt + 'a = UnsafeAny> {
187209
data: hash_map::OccupiedEntry<'a, TypeId, Box<A>>,
@@ -296,6 +318,16 @@ mod test {
296318
assert!(map.contains::<KeyType>());
297319
}
298320

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+
299331
#[test] fn test_custom_bounds() {
300332
let mut map: SendMap = TypeMap::custom();
301333
map.insert::<KeyType>(Value(10));

0 commit comments

Comments
 (0)