Skip to content

get_or_default #33

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 8 additions & 2 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,7 @@ use std::marker::PhantomData;

use Entry::{Occupied, Vacant};

pub use internals::{CloneAny, DebugAny};
use internals::Implements;
pub use internals::{CloneAny, DebugAny, Implements};

/// A map keyed by types.
///
Expand Down Expand Up @@ -139,6 +138,13 @@ impl<A: UnsafeAnyExt + ?Sized> TypeMap<A> {
})
}

/// Find a value in the map and get a reference to it if it exists, or
/// insert a default value first.
pub fn get_or_default<K: Key>(&mut self) -> &mut K::Value
where K::Value: Any + Implements<A> + Default {
self.entry::<K>().or_insert_with(Default::default)
}

/// Get the given key's corresponding entry in the map for in-place manipulation.
pub fn entry<'a, K: Key>(&'a mut self) -> Entry<'a, K, A>
where K::Value: Any + Implements<A> {
Expand Down