c_map/
encapsulate.rs

1use super::*;
2
3use std::collections::hash_map::Entry;
4
5macro_rules! readable {
6    () => {
7        /// Returns a reference to the value corresponding to the key.
8        pub fn get(&self) -> Option<&V> {
9            self.map.get(&self.key)
10        }
11        /// Returns the key-value pair corresponding to the supplied key.
12        pub fn get_key_value(&self) -> Option<(&K, &V)> {
13            self.map.get_key_value(&self.key)
14        }
15        /// Returns `true` if the map contains a value for the specified key.
16        pub fn contains_key(&self) -> bool {
17            self.map.contains_key(&self.key)
18        }
19    };
20}
21
22/// RAII structure used to release the shared read access, when dropped.
23#[derive(Debug)]
24pub struct Readable<'a, K, V, S> {
25    pub(super) key: &'a K,
26    pub(super) map: RwLockReadGuard<'a, Map<K, V, S>>,
27}
28
29impl<K: Eq + Hash, V, S: BuildHasher> Readable<'_, K, V, S> {
30    readable!();
31}
32
33/// RAII structure used to release the exclusive write access, when dropped.
34#[derive(Debug)]
35pub struct Writeable<'a, K, V, S> {
36    pub(super) key: K,
37    pub(super) map: RwLockWriteGuard<'a, Map<K, V, S>>,
38}
39
40impl<K: Eq + Hash, V, S: BuildHasher> Writeable<'_, K, V, S> {
41    readable!();
42
43    /// Returns a mutable reference to the value corresponding to the key.
44    pub fn get_mut(&mut self) -> Option<&mut V> {
45        self.map.get_mut(&self.key)
46    }
47
48    /// Inserts a key-value pair into the map.
49    ///
50    /// If the map did not have this key present, [`None`] is returned.
51    ///
52    /// If the map did have this key present, the value is updated, and the old
53    /// value is returned. The key is not updated, though; this matters for
54    /// types that can be `==` without being identical.
55    pub fn insert(mut self, value: V) -> Option<V> {
56        self.map.insert(self.key, value)
57    }
58
59    /// Removes a key from the map, returning the value at the key if the key
60    /// was previously in the map.
61    pub fn remove(&mut self) -> Option<V> {
62        self.map.remove(&self.key)
63    }
64
65    /// Gets the given key's corresponding entry in the map for in-place manipulation.
66    pub fn entry(&mut self) -> Entry<'_, K, V>
67    where
68        K: Clone,
69    {
70        self.map.entry(self.key.clone())
71    }
72
73    /// Removes a key from the map, returning the stored key and value if the
74    /// key was previously in the map.
75    pub fn remove_entry(&mut self) -> Option<(K, V)> {
76        self.map.remove_entry(&self.key)
77    }
78}