1 | use std::cell::UnsafeCell; |
2 | use std::fmt; |
3 | use std::ops::Deref; |
4 | use std::panic; |
5 | |
6 | /// `AtomicU32` providing an additional `unsync_load` function. |
7 | pub(crate) struct AtomicU32 { |
8 | inner: UnsafeCell<std::sync::atomic::AtomicU32>, |
9 | } |
10 | |
11 | unsafe impl Send for AtomicU32 {} |
12 | unsafe impl Sync for AtomicU32 {} |
13 | impl panic::RefUnwindSafe for AtomicU32 {} |
14 | impl panic::UnwindSafe for AtomicU32 {} |
15 | |
16 | impl AtomicU32 { |
17 | pub(crate) const fn new(val: u32) -> AtomicU32 { |
18 | let inner: UnsafeCell = UnsafeCell::new(std::sync::atomic::AtomicU32::new(val)); |
19 | AtomicU32 { inner } |
20 | } |
21 | |
22 | /// Performs an unsynchronized load. |
23 | /// |
24 | /// # Safety |
25 | /// |
26 | /// All mutations must have happened before the unsynchronized load. |
27 | /// Additionally, there must be no concurrent mutations. |
28 | pub(crate) unsafe fn unsync_load(&self) -> u32 { |
29 | core::ptr::read(self.inner.get() as *const u32) |
30 | } |
31 | } |
32 | |
33 | impl Deref for AtomicU32 { |
34 | type Target = std::sync::atomic::AtomicU32; |
35 | |
36 | fn deref(&self) -> &Self::Target { |
37 | // safety: it is always safe to access `&self` fns on the inner value as |
38 | // we never perform unsafe mutations. |
39 | unsafe { &*self.inner.get() } |
40 | } |
41 | } |
42 | |
43 | impl fmt::Debug for AtomicU32 { |
44 | fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { |
45 | self.deref().fmt(fmt) |
46 | } |
47 | } |
48 | |