Skip to main content

adts/
map.rs

1//! Map traits.
2
3use core::borrow::Borrow;
4
5/// A key-value map.
6pub trait Map {
7    /// Key type
8    type Key;
9
10    /// Value type
11    type Value;
12}
13
14/// Getter for a map.
15pub trait MapGet<K: ?Sized>: Map
16where
17    Self::Key: Borrow<K>,
18{
19    /// Returns a reference to the value corresponding to the `key` if exists.
20    fn get(&self, key: &K) -> Option<&Self::Value>;
21
22    /// Returns `true` if the map contains a value for the `key`.
23    #[inline]
24    fn contains_key(&self, key: &K) -> bool {
25        self.get(key).is_some()
26    }
27}
28
29/// Mutator for a map.
30pub trait MapMut<K: ?Sized>: MapGet<K>
31where
32    Self::Key: Borrow<K>,
33{
34    /// Returns a mutable reference to the value corresponding to the `key` if exists.
35    fn get_mut(&mut self, key: &K) -> Option<&mut Self::Value>;
36
37    /// Removes and returns the element at `key` from the map if exists.
38    fn remove(&mut self, key: &K) -> Option<Self::Value>;
39}
40
41/// Operation to insert into a map.
42pub trait MapInsert: Map {
43    /// Inserts `value` into the map. The existing value in the map is returned.
44    fn insert(&mut self, key: Self::Key, value: Self::Value) -> Option<Self::Value>;
45}