Skip to main content

ordinal_map/map/
entry.rs

1/// Reference to the occupied entry in [`OrdinalMap`](crate::map::OrdinalMap)
2/// or [`OrdinalArrayMap`](crate::map::OrdinalArrayMap).
3pub struct OccupiedEntry<'a, K, V> {
4    key: K,
5    /// We know that the entry is `Some`.
6    entry: &'a mut Option<V>,
7}
8
9/// Reference to the vacant entry in [`OrdinalMap`](crate::map::OrdinalMap)
10/// or [`OrdinalArrayMap`](crate::map::OrdinalArrayMap).
11pub struct VacantEntry<'a, K, V> {
12    key: K,
13    /// We know that the entry is `None`.
14    entry: &'a mut Option<V>,
15}
16
17/// Entry API.
18///
19/// Operations with [`OrdinalMap`](crate::map::OrdinalMap)
20/// and [`OrdinalArrayMap`](crate::map::OrdinalArrayMap) are
21/// constant time, and this API is provided for convenience.
22pub enum Entry<'a, K, V> {
23    /// Occupied entry.
24    Occupied(OccupiedEntry<'a, K, V>),
25    /// Vacant entry.
26    Vacant(VacantEntry<'a, K, V>),
27}
28
29impl<'a, K, V> OccupiedEntry<'a, K, V> {
30    /// Get the key of the entry.
31    #[inline]
32    pub fn key(&self) -> &K {
33        &self.key
34    }
35
36    /// Get a reference to the value in the entry.
37    #[inline]
38    pub fn get(&self) -> &V {
39        self.entry.as_ref().unwrap()
40    }
41
42    /// Get a mutable reference to the value in the entry.
43    #[inline]
44    pub fn get_mut(&mut self) -> &mut V {
45        self.entry.as_mut().unwrap()
46    }
47}
48
49impl<'a, K, V> VacantEntry<'a, K, V> {
50    /// Get the key of the entry.
51    #[inline]
52    pub fn key(&self) -> &K {
53        &self.key
54    }
55
56    /// Insert a value into the map.
57    #[inline]
58    pub fn insert(self, value: V) {
59        *self.entry = Some(value);
60    }
61}
62
63impl<'a, K, V> Entry<'a, K, V> {
64    pub(crate) fn new(key: K, entry: &'a mut Option<V>) -> Self {
65        if entry.is_some() {
66            Entry::Occupied(OccupiedEntry { key, entry })
67        } else {
68            Entry::Vacant(VacantEntry { key, entry })
69        }
70    }
71
72    /// Get the key of the entry.
73    #[inline]
74    pub fn key(&self) -> &K {
75        match self {
76            Entry::Occupied(entry) => entry.key(),
77            Entry::Vacant(entry) => entry.key(),
78        }
79    }
80
81    /// Convert the entry to an occupied entry.
82    #[inline]
83    pub fn or_insert(self, value: V) -> &'a mut V {
84        match self {
85            Entry::Occupied(entry) => entry.entry.as_mut().unwrap(),
86            Entry::Vacant(entry) => entry.entry.insert(value),
87        }
88    }
89}