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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
use std::cell::UnsafeCell;
use std::sync::Mutex;
pub struct LazyOnce<T> {
cell: Mutex<UnsafeCell<Option<T>>>,
}
impl<T> LazyOnce<T> {
pub fn new() -> Self {
Self {
cell: Mutex::new(UnsafeCell::new(None)),
}
}
pub fn get(&self, f: impl FnOnce() -> T) -> &T {
let cell = self.cell.lock().unwrap();
unsafe {
(*cell.get()).get_or_insert_with(f)
}
}
#[must_use]
pub fn try_get(&self) -> Option<&T> {
let cell = self.cell.lock().unwrap();
unsafe {
(*cell.get()).as_ref()
}
}
pub fn get_mut(&mut self, f: impl FnOnce() -> T) -> &mut T {
let cell = self.cell.lock().unwrap();
unsafe {
(*cell.get()).get_or_insert_with(f)
}
}
pub fn expect(&self, s: &str) -> &T {
let cell = self.cell.lock().unwrap();
unsafe {
(*cell.get()).as_ref().expect(s)
}
}
pub fn into_inner(self) -> Option<T> {
let cell = self.cell.lock().unwrap();
unsafe {
(*cell.get()).take()
}
}
}
#[test]
fn test_get() {
let l = LazyOnce::new();
assert_eq!(None, l.try_get());
assert_eq!(1, *l.get(|| 1u8));
assert_eq!(1, *l.get(|| 2u8));
assert_eq!(1, *l.try_get().unwrap());
assert_eq!(1, *l.get(|| 3u8));
assert_eq!(1, *l.expect("set"));
}
#[test]
fn test_mut() {
let mut l = LazyOnce::new();
assert_eq!(1, *l.get_mut(|| 1u8));
assert_eq!(1, *l.get(|| 2u8));
assert_eq!(1, *l.get_mut(|| 3u8));
*l.get_mut(|| 3u8) = 4;
assert_eq!(4, *l.get_mut(|| 3u8));
assert_eq!(4, *l.try_get().unwrap());
assert_eq!(4, *l.expect("set"));
assert_eq!(4, l.into_inner().unwrap());
}
#[test]
fn test_send_and_sync() {
let l = LazyOnce::new();
::std::thread::spawn(move || {
let _ = l.get(|| "hi");
});
fn is_sync<T: Sync>(_: T) {}
is_sync(&LazyOnce::<u8>::new());
}