moka/
ops.rs

1//! Cache operations.
2
3/// Operations used by the `and_compute_with` and similar methods.
4pub mod compute {
5    use std::sync::Arc;
6
7    use crate::Entry;
8
9    /// Instructs the `and_compute_with` and similar methods how to modify the cached
10    /// entry.
11    #[derive(Debug, Clone, PartialEq, Eq)]
12    pub enum Op<V> {
13        /// No-operation. Do not modify the cached entry.
14        Nop,
15        /// Insert or update the value of the cached entry.
16        Put(V),
17        /// Remove the cached entry.
18        Remove,
19    }
20
21    /// The result of the `and_compute_with` and similar methods.
22    #[derive(Debug)]
23    pub enum CompResult<K, V> {
24        /// The entry did not exist and still does not exist.
25        StillNone(Arc<K>),
26        /// The entry already existed and was not modified. The returned entry
27        /// contains the existing value.
28        Unchanged(Entry<K, V>),
29        /// The entry did not exist and was inserted. The returned entry contains
30        /// the inserted value.
31        Inserted(Entry<K, V>),
32        /// The entry already existed and its value was replaced with a new one. The
33        /// returned entry contains the new value (not the replaced value).
34        ReplacedWith(Entry<K, V>),
35        /// The entry already existed and was removed. The returned entry contains
36        /// the removed value.
37        ///
38        /// Note: `StillNone` is returned instead of `Removed` if `Op::Remove` was
39        /// requested but the entry did not exist.
40        Removed(Entry<K, V>),
41    }
42
43    impl<K, V> CompResult<K, V> {
44        /// Returns the contained `Some(Entry)` if any. Otherwise returns `None`.
45        /// Consumes the `self` value.
46        pub fn into_entry(self) -> Option<Entry<K, V>> {
47            match self {
48                CompResult::StillNone(_) => None,
49                CompResult::Unchanged(entry) => Some(entry),
50                CompResult::Inserted(entry) => Some(entry),
51                CompResult::ReplacedWith(entry) => Some(entry),
52                CompResult::Removed(entry) => Some(entry),
53            }
54        }
55
56        /// Unwraps the contained `Entry`, consuming the `self` value.
57        ///
58        /// # Panics
59        ///
60        /// Panics if the `self` value is `StillNone`.
61        pub fn unwrap(self) -> Entry<K, V> {
62            match self {
63                CompResult::StillNone(_) => panic!("`CompResult::unwrap` called on `StillNone`"),
64                CompResult::Unchanged(entry) => entry,
65                CompResult::Inserted(entry) => entry,
66                CompResult::ReplacedWith(entry) => entry,
67                CompResult::Removed(entry) => entry,
68            }
69        }
70    }
71}