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
use core::cell::Cell;
use core::marker::Copy;
pub struct OptionalCell<T: Copy> {
value: Cell<Option<T>>,
}
impl<T: Copy> OptionalCell<T> {
pub const fn new(val: T) -> OptionalCell<T> {
OptionalCell {
value: Cell::new(Some(val)),
}
}
pub const fn empty() -> OptionalCell<T> {
OptionalCell {
value: Cell::new(None),
}
}
pub fn is_none(&self) -> bool {
self.value.get().is_none()
}
pub fn is_some(&self) -> bool {
self.value.get().is_some()
}
pub fn set(&self, val: T) {
self.value.set(Some(val));
}
pub fn clear(&self) {
self.value.set(None);
}
pub fn take(&self) -> Option<T> {
self.value.take()
}
pub fn map<F, R>(&self, closure: F) -> Option<R>
where
F: FnOnce(&mut T) -> R,
{
self.value.get().map(|mut val| closure(&mut val))
}
pub fn map_or<F, R>(&self, default: R, closure: F) -> R
where
F: FnOnce(&mut T) -> R,
{
self.value
.get()
.map_or(default, |mut val| closure(&mut val))
}
pub fn map_or_else<U, D, F>(&self, default: D, closure: F) -> U
where
D: FnOnce() -> U,
F: FnOnce(&mut T) -> U,
{
self.value
.get()
.map_or_else(default, |mut val| closure(&mut val))
}
}