cosmic_text/
cached.rs

1use core::fmt::Debug;
2use core::mem;
3
4/// Helper for caching a value when the value is optionally present in the 'unused' state.
5#[derive(Clone, Debug)]
6pub enum Cached<T: Clone + Debug> {
7    Empty,
8    Unused(T),
9    Used(T),
10}
11
12impl<T: Clone + Debug> Cached<T> {
13    /// Gets the value if in state `Self::Used`.
14    pub fn get(&self) -> Option<&T> {
15        match self {
16            Self::Empty | Self::Unused(_) => None,
17            Self::Used(t) => Some(t),
18        }
19    }
20
21    /// Gets the value mutably if in state `Self::Used`.
22    pub fn get_mut(&mut self) -> Option<&mut T> {
23        match self {
24            Self::Empty | Self::Unused(_) => None,
25            Self::Used(t) => Some(t),
26        }
27    }
28
29    /// Checks if the value is empty or unused.
30    pub fn is_unused(&self) -> bool {
31        match self {
32            Self::Empty | Self::Unused(_) => true,
33            Self::Used(_) => false,
34        }
35    }
36
37    /// Checks if the value is used (i.e. cached for access).
38    pub fn is_used(&self) -> bool {
39        match self {
40            Self::Empty | Self::Unused(_) => false,
41            Self::Used(_) => true,
42        }
43    }
44
45    /// Takes the buffered value if in state `Self::Unused`.
46    pub fn take_unused(&mut self) -> Option<T> {
47        if matches!(*self, Self::Unused(_)) {
48            let Self::Unused(val) = mem::replace(self, Self::Empty) else {
49                unreachable!()
50            };
51            Some(val)
52        } else {
53            None
54        }
55    }
56
57    /// Takes the cached value if in state `Self::Used`.
58    pub fn take_used(&mut self) -> Option<T> {
59        if matches!(*self, Self::Used(_)) {
60            let Self::Used(val) = mem::replace(self, Self::Empty) else {
61                unreachable!()
62            };
63            Some(val)
64        } else {
65            None
66        }
67    }
68
69    /// Moves the value from `Self::Used` to `Self::Unused`.
70    #[allow(clippy::missing_panics_doc)]
71    pub fn set_unused(&mut self) {
72        if matches!(*self, Self::Used(_)) {
73            *self = Self::Unused(self.take_used().expect("cached value should be used"));
74        }
75    }
76
77    /// Sets the value to `Self::Used`.
78    pub fn set_used(&mut self, val: T) {
79        *self = Self::Used(val);
80    }
81}