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
use std::mem;
pub enum Eventually<T> {
Initialized(T),
Uninitialized,
}
pub trait HasChanged {
type Criteria: Eq;
fn has_changed(&self, criteria: &Self::Criteria) -> bool;
}
impl<T> HasChanged for Option<T>
where
T: HasChanged,
{
type Criteria = T::Criteria;
fn has_changed(&self, criteria: &Self::Criteria) -> bool {
match self {
None => true,
Some(value) => value.has_changed(criteria),
}
}
}
impl<'a, T> Eventually<T>
where
T: HasChanged,
{
#[tracing::instrument(name = "reinitialize", skip_all)]
pub fn reinitialize(&mut self, f: impl FnOnce() -> T, criteria: &T::Criteria) {
let should_replace = match &self {
Eventually::Initialized(current) => current.has_changed(criteria),
Eventually::Uninitialized => true,
};
if should_replace {
*self = Eventually::Initialized(f());
}
}
}
impl<T> Eventually<T> {
#[tracing::instrument(name = "initialize", skip_all)]
pub fn initialize(&mut self, f: impl FnOnce() -> T) {
if let Eventually::Uninitialized = self {
*self = Eventually::Initialized(f());
}
}
pub fn take(&mut self) -> Eventually<T> {
mem::replace(self, Eventually::Uninitialized)
}
}
impl<T> Default for Eventually<T> {
fn default() -> Self {
Eventually::Uninitialized
}
}