Skip to content

Commit

Permalink
Allow shared access to SyncCell for types that are already Sync (b…
Browse files Browse the repository at this point in the history
…evyengine#7718)

# Objective

The type `SyncCell<T>` (added in bevyengine#5483) is used to force any wrapped type to be `Sync`, by only allowing exclusive access to the wrapped value. This restriction is unnecessary for types which are already `Sync`.

---

## Changelog

+ Added the method `read` to `SyncCell`, which allows shared access to values that already implement the `Sync` trait.
  • Loading branch information
JoJoJet authored and myreprise1 committed Feb 18, 2023
1 parent 2ba9101 commit ce3068a
Showing 1 changed file with 10 additions and 2 deletions.
12 changes: 10 additions & 2 deletions crates/bevy_utils/src/synccell.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,14 @@ impl<T: ?Sized> SyncCell<T> {
&mut self.inner
}

/// For types that implement [`Sync`], get shared access to this `SyncCell`'s inner value.
pub fn read(&self) -> &T
where
T: Sync,
{
&self.inner
}

/// Build a mutable reference to a `SyncCell` from a mutable reference
/// to its inner value, to skip constructing with [`new()`](SyncCell::new()).
pub fn from_mut(r: &'_ mut T) -> &'_ mut SyncCell<T> {
Expand All @@ -38,6 +46,6 @@ impl<T: ?Sized> SyncCell<T> {
}

// SAFETY: `Sync` only allows multithreaded access via immutable reference.
// As `SyncCell` requires an exclusive reference to access the wrapped value,
// marking this type as `Sync` does not actually allow threaded access to the inner value.
// As `SyncCell` requires an exclusive reference to access the wrapped value for `!Sync` types,
// marking this type as `Sync` does not actually allow unsychronized access to the inner value.
unsafe impl<T: ?Sized> Sync for SyncCell<T> {}

0 comments on commit ce3068a

Please sign in to comment.