bevy_utils/
synccell.rs

1//! A reimplementation of the currently unstable [`std::sync::Exclusive`]
2//!
3//! [`std::sync::Exclusive`]: https://doc.rust-lang.org/nightly/std/sync/struct.Exclusive.html
4
5use core::ptr;
6
7/// See [`Exclusive`](https://github.com/rust-lang/rust/issues/98407) for stdlib's upcoming implementation,
8/// which should replace this one entirely.
9///
10/// Provides a wrapper that allows making any type unconditionally [`Sync`] by only providing mutable access.
11#[repr(transparent)]
12pub struct SyncCell<T: ?Sized> {
13    inner: T,
14}
15
16impl<T: Sized> SyncCell<T> {
17    /// Construct a new instance of a `SyncCell` from the given value.
18    pub fn new(inner: T) -> Self {
19        Self { inner }
20    }
21
22    /// Deconstruct this `SyncCell` into its inner value.
23    pub fn to_inner(Self { inner }: Self) -> T {
24        inner
25    }
26}
27
28impl<T: ?Sized> SyncCell<T> {
29    /// Get a reference to this `SyncCell`'s inner value.
30    pub fn get(&mut self) -> &mut T {
31        &mut self.inner
32    }
33
34    /// For types that implement [`Sync`], get shared access to this `SyncCell`'s inner value.
35    pub fn read(&self) -> &T
36    where
37        T: Sync,
38    {
39        &self.inner
40    }
41
42    /// Build a mutable reference to a `SyncCell` from a mutable reference
43    /// to its inner value, to skip constructing with [`new()`](SyncCell::new()).
44    pub fn from_mut(r: &'_ mut T) -> &'_ mut SyncCell<T> {
45        // SAFETY: repr is transparent, so refs have the same layout; and `SyncCell` properties are `&mut`-agnostic
46        unsafe { &mut *(ptr::from_mut(r) as *mut SyncCell<T>) }
47    }
48}
49
50// SAFETY: `Sync` only allows multithreaded access via immutable reference.
51// As `SyncCell` requires an exclusive reference to access the wrapped value for `!Sync` types,
52// marking this type as `Sync` does not actually allow unsynchronized access to the inner value.
53unsafe impl<T: ?Sized> Sync for SyncCell<T> {}