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 std::cell::UnsafeCell;
#[cfg(not(feature = "no-state-check"))]
use std::sync::atomic::{AtomicU8, Ordering::SeqCst};
const UNINITIALIZED: u8 = 0;
const INITIALIZING: u8 = 1;
const INITIALIZED: u8 = 2;
pub struct State<T> {
data: UnsafeCell<Option<T>>,
#[cfg(not(feature = "no-state-check"))]
status: AtomicU8,
}
unsafe impl<T> Sync for State<T> {}
#[macro_export]
macro_rules! set_once {
($state:expr, $f:expr) => {{
use std::sync::Once;
static ONCE: Once = Once::new();
ONCE.call_once(|| {
$state.set_force($f());
});
}};
}
impl<T: Sized> State<T> {
pub const fn new() -> State<T> {
State {
data: UnsafeCell::new(None),
#[cfg(not(feature = "no-state-check"))]
status: AtomicU8::new(UNINITIALIZED),
}
}
pub fn set_force(&self, data: T) {
self.set_inner(data)
}
#[cfg(test)]
pub fn set(&self, _data: T) {
log::info!("測試中,不設定狀態");
}
#[cfg(not(test))]
pub fn set(&self, data: T) {
self.set_inner(data)
}
fn set_inner(&self, data: T) {
#[cfg(not(feature = "no-state-check"))]
{
let status = self
.status
.compare_exchange(UNINITIALIZED, INITIALIZING, SeqCst, SeqCst);
log::debug!("設定前的狀態:{:?}", status);
if status.is_err() {
panic!("多次設定狀態");
}
}
let ptr = self.data.get();
unsafe {
*ptr = Some(data);
}
#[cfg(not(feature = "no-state-check"))]
self.status.store(INITIALIZED, SeqCst);
}
pub fn get(&self) -> &T {
#[cfg(not(feature = "no-state-check"))]
match self.status.load(SeqCst) {
UNINITIALIZED => {
panic!("還沒設定就取狀態");
}
INITIALIZING => {
while self.status.load(SeqCst) == INITIALIZING {
std::hint::spin_loop();
}
}
_ => (),
}
let ptr = self.data.get();
unsafe { (&*ptr).as_ref().unwrap() }
}
}