tirbofish/dropbear
main / crates / dropbear-utils / src / either.rs · 1981 bytes
crates/dropbear-utils/src/either.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, Default, PartialEq)]
pub struct Dirty<T> {
value: T,
dirty: bool,
}
impl<T> Dirty<T> {
/// Creates a new [`Dirty`] of type [`T`]. Marks clean on initial creation.
pub fn new(value: T) -> Self {
Self {
value,
dirty: false,
}
}
/// Creates a new [`Dirty`] of type [`T`]. Marks dirty on initial creation.
pub fn new_dirty(value: T) -> Self {
Self { value, dirty: true }
}
/// Fetches a reference to the value.
///
/// Does not change the state of the cleanliness
pub fn get(&self) -> &T {
&self.value
}
/// Sets this to a new value, marking dirty in the process.
pub fn set(&mut self, value: T) {
self.value = value;
self.dirty = true;
}
/// Mutates the inner value and marks dirty.
pub fn mutate(&mut self, f: impl FnOnce(&mut T)) {
f(&mut self.value);
self.dirty = true;
}
/// Returns the dirtiness of the value.
pub fn is_dirty(&self) -> bool {
self.dirty
}
/// Marks the value as clean.
pub fn mark_clean(&mut self) {
self.dirty = false;
}
/// Marks the value as dirty.
pub fn mark_dirty(&mut self) {
self.dirty = true;
}
/// Fetches the value and clears the dirty flag if dirty, returning None if clean.
pub fn get_if_dirty(&mut self) -> Option<&T> {
if self.dirty {
self.dirty = false;
Some(&self.value)
} else {
None
}
}
}
impl<T: Clone> Dirty<T> {
pub fn get_clean(&mut self) -> T {
self.dirty = false;
self.value.clone()
}
}
impl<T> std::ops::Deref for Dirty<T> {
type Target = T;
fn deref(&self) -> &T {
&self.value
}
}
impl<T> std::ops::DerefMut for Dirty<T> {
fn deref_mut(&mut self) -> &mut T {
self.dirty = true;
&mut self.value
}
}