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
/// Represents the operational state of an element that can be either active or inactive.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum State<T = ()> {
/// The element is currently active and operational.
Active(T),
/// The element is currently inactive and not operational.
Inactive(T),
}
#[allow(dead_code)]
impl<T> State<T> {
/// Returns `true` if the state is active.
pub fn is_active(&self) -> bool {
matches!(self, State::Active(_))
}
/// Returns `true` if the state is inactive.
pub fn is_inactive(&self) -> bool {
matches!(self, State::Inactive(_))
}
/// Transitions an active state to inactive while preserving the contained value.
///
/// # Panics
///
/// Panics if the state is already inactive.
pub fn shutdown(&mut self) {
assert!(
self.is_active(),
"Tried to shut an already inactive element"
);
unsafe {
let value = match std::ptr::read(self) {
State::Active(v) => v,
State::Inactive(_) => unreachable!(),
};
std::ptr::write(self, State::Inactive(value));
}
}
/// Returns the contained value, consuming the state.
///
/// # Panics
///
/// Panics if the state is inactive.
pub fn unwrap_active(self) -> T {
match self {
State::Active(t) => t,
State::Inactive(_) => panic!("Tried top unwrap_active an inactive state"),
}
}
/// Returns the contained value, consuming the state.
///
/// # Panics
///
/// Panics if the state is active.
pub fn unwrap_inactive(self) -> T {
match self {
State::Active(t) => t,
State::Inactive(_) => panic!("Tried top unwrap_active an inactive state"),
}
}
/// Converts the state to contain references to the contained value instead of owned values.
pub fn as_ref(&self) -> State<&T> {
match self {
State::Active(v) => State::Active(&v),
State::Inactive(v) => State::Inactive(&v),
}
}
/// Converts the state to contain mutable references to the contained value instead of owned
/// values.
pub fn as_mut_ref(&mut self) -> State<&mut T> {
match self {
State::Active(v) => State::Active(v),
State::Inactive(v) => State::Inactive(v),
}
}
}