tinylfu_cached/cache/store/
key_value_ref.rs

1use std::hash::Hash;
2
3use dashmap::mapref::one::Ref;
4
5/// KeyValueRef contains DashMap's Ref [`dashmap::mapref::one::Ref`] which internally holds
6/// a `RwLockReadGuard` for the shard. It is returned as a response to `get_ref` method of [`crate::cache::cached::CacheD`].
7///
8/// Any time `get_ref` method is invoked, the `Store` returns `Option<KeyValueRef<'_, Key, StoredValue<Value>>>`.
9///
10/// If the key is present in the `Store`, `get_ref` will return `Some<KeyValueRef<'_, Key, StoredValue<Value>>>`.
11///
12/// Hence, the invocation of `get_ref` will hold a lock against the shard that contains the key (within the scope of its usage).
13pub struct KeyValueRef<'a, Key, Value>
14    where Key: Eq + Hash {
15    key_value_ref: Ref<'a, Key, Value>,
16}
17
18impl<'a, Key, Value> KeyValueRef<'a, Key, Value>
19    where Key: Eq + Hash {
20    pub(crate) fn new(key_value_ref: Ref<'a, Key, Value>) -> Self <> {
21        KeyValueRef {
22            key_value_ref
23        }
24    }
25
26    /// Returns the reference of the key present in the Store
27    pub fn key(&self) -> &Key {
28        self.key_value_ref.key()
29    }
30
31    /// Returns the reference of the value present in the Store
32    pub fn value(&self) -> &Value {
33        self.key_value_ref.value()
34    }
35}
36
37#[cfg(test)]
38mod tests {
39    use dashmap::DashMap;
40    use crate::cache::store::key_value_ref::KeyValueRef;
41
42    #[test]
43    fn get_key() {
44        let key_values = DashMap::new();
45        key_values.insert("topic", "microservices");
46        let value_ref = key_values.get(&"topic").unwrap();
47
48        let key_value_ref = KeyValueRef::new(value_ref);
49        assert_eq!(&"topic", key_value_ref.key());
50    }
51
52    #[test]
53    fn get_value() {
54        let key_values = DashMap::new();
55        key_values.insert("topic", "microservices");
56        let value_ref = key_values.get(&"topic").unwrap();
57
58        let key_value_ref = KeyValueRef::new(value_ref);
59        assert_eq!(&"microservices", key_value_ref.value());
60    }
61}