get_trait/entry.rs
1//! Entry API for maps.
2use get::GetMut;
3
4/// A trait for getting an entry at a given key.
5pub trait GetEntry<'a>: GetMut {
6 /// The type of an occupied entry.
7 type Occupied: OccupiedEntry<'a, Self>;
8
9 /// The type of a vacant entry.
10 type Vacant: VacantEntry<'a, Self>;
11
12 /// Gets the entry.
13 fn entry(&'a mut self, key: Self::Key) -> Entry<'a, Self>;
14}
15
16/// An entry at a given key.
17pub enum Entry<'a, T: ?Sized + GetEntry<'a>> {
18 /// An entry with a value.
19 Occupied(T::Occupied),
20
21 /// An entry without a value.
22 Vacant(T::Vacant),
23}
24impl<'a, T: ?Sized + GetEntry<'a>> Entry<'a, T> {
25 /// Gets this entry's value, inserting the given default value if the entry is empty.
26 pub fn or_insert(self, default: T::Value) -> &'a mut T::Value {
27 match self {
28 Entry::Occupied(entry) => entry.into_mut(),
29 Entry::Vacant(entry) => entry.insert(default),
30 }
31 }
32 /// Similar to `or_insert`, using a closure to create the value if necessary.
33 pub fn or_insert_with<F: FnOnce() -> T::Value>(self, default: F) -> &'a mut T::Value {
34 match self {
35 Entry::Occupied(entry) => entry.into_mut(),
36 Entry::Vacant(entry) => entry.insert(default()),
37 }
38 }
39}
40
41/// A trait for an entry with a value.
42pub trait OccupiedEntry<'a, T: ?Sized + GetEntry<'a>> {
43 /// Gets a reference to the key at this entry.
44 fn key(&self) -> &T::Key;
45
46 /// Gets a reference to the value at this entry.
47 fn get(&self) -> &T::Value;
48
49 /// Gets a mutable reference to the value at this entry.
50 fn get_mut(&mut self) -> &mut T::Value;
51
52 /// Inserts the given value into this entry, returning the old value.
53 fn insert(&mut self, value: T::Value) -> T::Value;
54
55 /// Consumes this entry handle, yielding a mutable reference to its value.
56 fn into_mut(self) -> &'a mut T::Value;
57
58 /// Removes this entry, returning both its key and value.
59 fn remove_entry(self) -> (T::Key, T::Value);
60}
61
62/// A trait for an entry without a value.
63pub trait VacantEntry<'a, T: ?Sized + GetEntry<'a>> {
64 /// Gets a reference to the key at this entry.
65 fn key(&self) -> &T::Key;
66
67 /// Consumes this entry, yielding back the key instead of inserting.
68 fn into_key(self) -> T::Key;
69
70 /// Inserts a value into this entry, yielding a mutable reference to its value.
71 fn insert(self, value: T::Value) -> &'a mut T::Value;
72}