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
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
use std::cell::UnsafeCell;
use std::fmt::{self, Debug, Formatter};
use std::mem::{self, MaybeUninit};
use std::ptr;
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::thread::{self, Thread};
use scopeguard::defer_on_unwind;
#[cfg(test)]
mod tests;
const STATE_CLEAR: usize = 0;
const STATE_INIT: usize = usize::MAX;
const BUSY_BIT: usize = 1;
#[repr(align(2))]
struct Parked {
wake: AtomicBool,
thread: Thread,
next: *const Parked,
}
impl Parked {
pub unsafe fn park(state: &AtomicUsize, mut guess: usize) {
let mut parked = Self {
wake: AtomicBool::new(false),
thread: thread::current(),
next: ptr::null(),
};
let parked_ptr = &parked as *const Self as usize;
debug_assert!((parked_ptr & BUSY_BIT) == 0);
loop {
parked.next = (guess & !BUSY_BIT) as *const Parked;
match state.compare_exchange_weak(
guess,
parked_ptr | (guess & BUSY_BIT),
Ordering::Release,
Ordering::Relaxed,
) {
Ok(..) => {
break;
}
Err(STATE_INIT) => {
match state.load(Ordering::Acquire) {
STATE_INIT => return,
other => bad_state(other),
}
}
Err(current) => {
guess = current;
}
};
}
loop {
thread::park();
if parked.wake.load(Ordering::Acquire) {
return;
}
}
}
pub unsafe fn unpark_all(mut head: *const Self) {
while !head.is_null() {
head = Self::unpark(head);
}
}
unsafe fn unpark(parked: *const Self) -> *const Self {
let thread = (*parked).thread.clone();
let next = (*parked).next;
assert_eq!((*parked).wake.swap(true, Ordering::Release), false);
thread.unpark();
next
}
}
unsafe impl Sync for Parked {}
pub struct WaitCell<T> {
state: AtomicUsize,
value: UnsafeCell<MaybeUninit<T>>,
}
impl<T> WaitCell<T> {
#[must_use]
pub const fn new() -> Self {
Self {
state: AtomicUsize::new(STATE_CLEAR),
value: UnsafeCell::new(MaybeUninit::uninit()),
}
}
#[must_use]
pub const fn initialized(value: T) -> Self {
Self {
state: AtomicUsize::new(STATE_INIT),
value: UnsafeCell::new(MaybeUninit::new(value)),
}
}
#[must_use]
unsafe fn get_ptr(&self) -> *mut T {
(&mut *self.value.get()).as_mut_ptr()
}
#[must_use]
unsafe fn get_ref(&self) -> &T {
&*self.get_ptr()
}
#[allow(clippy::mut_from_ref)]
#[must_use]
unsafe fn get_mut(&self) -> &mut T {
&mut *self.get_ptr()
}
unsafe fn wake(&self, value: T) -> &T {
ptr::write(self.get_ptr(), value);
let state = self.state.swap(STATE_INIT, Ordering::Release);
debug_assert!((state & BUSY_BIT) != 0);
Parked::unpark_all((state & !BUSY_BIT) as *const Parked);
self.get_ref()
}
unsafe fn wake_with<F: FnOnce() -> T>(&self, func: F) -> &T {
self.wake({
defer_on_unwind! {
self.state.fetch_and(!BUSY_BIT, Ordering::Relaxed);
}
func()
})
}
unsafe fn wait(&self, state: usize) -> &T {
if state != STATE_INIT {
Parked::park(&self.state, state);
}
self.get_ref()
}
pub fn init(&self, value: T) -> &T {
let state = self.state.fetch_or(BUSY_BIT, Ordering::Relaxed);
if (state & BUSY_BIT) == 0 {
unsafe { self.wake(value) }
} else {
bad_state(state);
}
}
pub fn try_init<F: FnOnce() -> T>(&self, func: F) -> bool {
let state = self.state.fetch_or(BUSY_BIT, Ordering::Relaxed);
if (state & BUSY_BIT) != 0 {
return false;
}
unsafe {
self.wake_with(func);
}
true
}
#[must_use]
pub fn get_or_init<F: FnOnce() -> T>(&self, func: F) -> &T {
let state = self.state.fetch_or(BUSY_BIT, Ordering::Acquire);
if (state & BUSY_BIT) == 0 {
unsafe { self.wake_with(func) }
} else {
unsafe { self.wait(state) }
}
}
#[must_use]
pub fn get(&self) -> &T {
unsafe { self.wait(self.state.load(Ordering::Acquire)) }
}
#[must_use]
pub fn try_get(&self) -> Option<&T> {
(self.state.load(Ordering::Acquire) == STATE_INIT).then(|| unsafe { self.get_ref() })
}
pub fn set(&mut self, value: T) -> &mut T {
unsafe {
if self.is_set() {
*self.get_mut() = value;
} else {
ptr::write(self.get_ptr(), value);
*self.state.get_mut() = STATE_INIT;
}
self.get_mut()
}
}
pub fn unset(&mut self) -> bool {
self.is_set()
.then(|| unsafe {
*self.state.get_mut() = STATE_CLEAR;
ptr::drop_in_place(self.get_ptr());
})
.is_some()
}
#[must_use]
pub fn is_set(&mut self) -> bool {
match *self.state.get_mut() {
STATE_INIT => true,
STATE_CLEAR => false,
other => bad_state(other),
}
}
#[must_use]
pub fn as_inner(&mut self) -> Option<&mut T> {
self.is_set().then(move || unsafe { self.get_mut() })
}
#[must_use]
pub fn into_inner(mut self) -> Option<T> {
self.is_set().then(|| unsafe {
let result = ptr::read(self.get_ptr());
mem::forget(self);
result
})
}
#[must_use]
pub fn as_ptr(&self) -> *const T {
unsafe { self.get_ptr() }
}
#[must_use]
pub fn as_mut_ptr(&mut self) -> *mut T {
unsafe { self.get_ptr() }
}
pub unsafe fn set_init(&mut self) {
*self.state.get_mut() = STATE_INIT;
}
pub fn set_uninit(&mut self) {
*self.state.get_mut() = STATE_CLEAR;
}
}
impl<T: Default> WaitCell<T> {
#[must_use]
pub fn with_default() -> Self {
Self::initialized(Default::default())
}
}
impl<T> Drop for WaitCell<T> {
fn drop(&mut self) {
self.is_set().then(|| unsafe {
ptr::drop_in_place(self.get_ptr());
});
}
}
impl<T> Debug for WaitCell<T> {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
let state = self.state.load(Ordering::Relaxed);
if state == STATE_INIT {
f.debug_struct("WaitCell")
.field("state", &"initialized")
.field("has_waiter", &false)
.finish()
} else if (state & BUSY_BIT) == 0 {
f.debug_struct("WaitCell")
.field("state", &"uninitialized")
.field("has_waiter", &((state & !BUSY_BIT) != 0))
.finish()
} else {
f.debug_struct("WaitCell")
.field("state", &"initializing")
.field("has_waiter", &((state & !BUSY_BIT) != 0))
.finish()
}
}
}
impl<T> Default for WaitCell<T> {
fn default() -> Self {
Self::new()
}
}
impl<T> From<T> for WaitCell<T> {
fn from(value: T) -> Self {
Self::initialized(value)
}
}
unsafe impl<T: Sync> Sync for WaitCell<T> {}
#[cold]
fn bad_state(state: usize) -> ! {
panic!("invalid WaitCell state: {:#08x}", state);
}