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
123
124
125
126
#![allow(clippy::mutex_atomic)]
use crate::Executor;
use std::{
cell::Cell,
fmt::{Debug, Error, Formatter},
mem::MaybeUninit,
sync::{
atomic::{AtomicBool, Ordering},
Condvar, Mutex, Once,
},
};
#[derive(Debug)]
struct CvarExecInternal {
mutex: Mutex<()>,
cvar: Condvar,
}
impl Debug for CvarExec {
fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> {
write!(f, "CvarExec")
}
}
pub struct CvarExec {
once: Once,
internal: Cell<MaybeUninit<CvarExecInternal>>,
state: AtomicBool,
}
#[allow(unsafe_code)]
unsafe impl Sync for CvarExec {}
impl CvarExec {
#[inline]
pub const fn new() -> Self {
CvarExec {
once: Once::new(),
internal: Cell::new(MaybeUninit::uninit()),
state: AtomicBool::new(true),
}
}
}
impl Drop for CvarExec {
#[inline]
#[allow(unsafe_code)]
fn drop(&mut self) {
if self.is_used() {
let internal = Cell::new(MaybeUninit::uninit());
self.internal.swap(&internal);
let _ = unsafe { internal.into_inner().assume_init() };
}
}
}
#[allow(unsafe_code)]
impl Executor for CvarExec {
#[inline]
unsafe fn trigger_event(&self) {
if !self.state.compare_and_swap(false, true, Ordering::SeqCst) {
(*(*self.internal.as_ptr()).as_ptr()).cvar.notify_one();
}
}
#[inline]
unsafe fn wait_for_event(&self) {
self.once.call_once(|| {
self.internal.set(MaybeUninit::new(CvarExecInternal {
mutex: Mutex::new(()),
cvar: Condvar::new(),
}));
});
let internal = (*self.internal.as_ptr()).as_ptr();
let mut guard = (*internal).mutex.lock().unwrap();
while !self.state.compare_and_swap(true, false, Ordering::SeqCst) {
guard = (*internal).cvar.wait(guard).unwrap();
}
}
#[inline]
fn is_used(&self) -> bool {
self.once.is_completed()
}
}