SyncCell

Struct SyncCell 

Source
pub struct SyncCell<T> { /* private fields */ }
Expand description

A runtime-checked cell that allows sharing non-Sync types between threads.

SyncCell<T> wraps a value of type T (which may not implement Sync) and provides a Sync implementation using a mutex for thread-safe access. Access to the wrapped value is provided through closure-based methods that automatically manage the mutex.

Unlike crate::unsafe_sync_cell::UnsafeSyncCell, this provides memory safety by using a real mutex and proper synchronization. The closure-based API prevents common issues like holding guards across await points or forgetting to release locks.

§Examples

Basic usage with a non-Sync type:

use send_cells::SyncCell;
use std::cell::RefCell;
use std::sync::Arc;
use std::thread;

// RefCell<i32> is not Sync, but SyncCell<RefCell<i32>> is
let data = RefCell::new(42);
let cell = Arc::new(SyncCell::new(data));

let cell_clone = Arc::clone(&cell);
let handle = thread::spawn(move || {
    cell_clone.with(|ref_cell| {
        assert_eq!(*ref_cell.borrow(), 42);
    });
});

handle.join().unwrap();

Mutable access:

use send_cells::SyncCell;
use std::collections::HashMap;

let map = HashMap::new();
let cell = SyncCell::new(map);

cell.with_mut(|map| {
    map.insert("key", "value");
});

cell.with(|map| {
    assert_eq!(map.get("key"), Some(&"value"));
});

§Thread Safety

The cell implements both Send and Sync when the wrapped type implements Send. Access is always protected by the internal mutex, ensuring thread safety.

Implementations§

Source§

impl<T> SyncCell<T>

Source

pub fn new(value: T) -> SyncCell<T>

Creates a new SyncCell wrapping the given value.

The value will be protected by an internal mutex, allowing safe shared access from multiple threads through the closure-based access methods.

§Examples
use send_cells::SyncCell;
use std::rc::Rc;

let data = Rc::new("Hello, world!");
let cell = SyncCell::new(data);

cell.with(|rc| {
    println!("{}", rc);
});
Source

pub fn with<R>(&self, f: impl FnOnce(&T) -> R) -> R

Accesses the underlying value through a synchronous closure.

The closure receives a shared reference to the wrapped value and must return synchronously. The internal mutex is automatically acquired before calling the closure and released when the closure returns.

This method provides safe, synchronized access to the wrapped value from any thread.

§Panics

Panics if the mutex is poisoned (i.e., another thread panicked while holding the lock).

§Examples
use send_cells::SyncCell;
use std::collections::HashMap;

let mut map = HashMap::new();
map.insert("key", "value");
let cell = SyncCell::new(map);

let result = cell.with(|map| {
    map.get("key").copied()
});

assert_eq!(result, Some("value"));
Source

pub fn with_mut<R>(&self, f: impl FnOnce(&mut T) -> R) -> R

Accesses the underlying value mutably through a synchronous closure.

The closure receives a mutable reference to the wrapped value and must return synchronously. The internal mutex is automatically acquired before calling the closure and released when the closure returns.

This method provides safe, synchronized mutable access to the wrapped value from any thread.

§Panics

Panics if the mutex is poisoned (i.e., another thread panicked while holding the lock).

§Examples
use send_cells::SyncCell;
use std::collections::HashMap;

let map = HashMap::new();
let cell = SyncCell::new(map);

cell.with_mut(|map| {
    map.insert("key", "value");
});

cell.with(|map| {
    assert_eq!(map.get("key"), Some(&"value"));
});
Source

pub fn into_inner(self) -> T

Consumes the cell and returns the wrapped value.

This method takes ownership of the SyncCell and returns the wrapped value without any synchronization, since the cell is being consumed.

§Examples
use send_cells::SyncCell;
use std::rc::Rc;

let data = Rc::new("Hello, world!");
let cell = SyncCell::new(data);

let recovered_data = cell.into_inner();
assert_eq!(*recovered_data, "Hello, world!");
Source

pub unsafe fn with_unchecked(&self) -> &T

Unsafely accesses the underlying value without acquiring the mutex.

§Safety

The caller must ensure that:

  • No other thread is currently accessing the value
  • The access is properly synchronized through external means
  • The mutex is not poisoned

This method bypasses all synchronization and may lead to data races if used incorrectly.

§Examples
use send_cells::SyncCell;

let cell = SyncCell::new(42);

// SAFETY: We're the only thread accessing this cell
let value = unsafe { cell.with_unchecked() };
assert_eq!(*value, 42);
Source

pub unsafe fn with_mut_unchecked(&self) -> &mut T

Unsafely accesses the underlying value mutably without acquiring the mutex.

§Safety

The caller must ensure that:

  • No other thread is currently accessing the value
  • The access is properly synchronized through external means
  • The mutex is not poisoned
  • No other references (mutable or immutable) to the value exist

This method bypasses all synchronization and may lead to data races if used incorrectly.

§Examples
use send_cells::SyncCell;

let cell = SyncCell::new(42);

// SAFETY: We're the only thread accessing this cell
unsafe {
    *cell.with_mut_unchecked() = 100;
}

cell.with(|value| {
    assert_eq!(*value, 100);
});

Trait Implementations§

Source§

impl<T: Clone> Clone for SyncCell<T>

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl<T: Debug> Debug for SyncCell<T>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<T: Default> Default for SyncCell<T>

Source§

fn default() -> SyncCell<T>

Returns the “default value” for a type. Read more
Source§

impl<T: Display> Display for SyncCell<T>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<T> From<T> for SyncCell<T>

Source§

fn from(value: T) -> Self

Converts to this type from the input type.
Source§

impl<T: Hash> Hash for SyncCell<T>

Source§

fn hash<H: Hasher>(&self, state: &mut H)

Feeds this value into the given Hasher. Read more
1.3.0 · Source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where H: Hasher, Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
Source§

impl<T: Ord> Ord for SyncCell<T>

Source§

fn cmp(&self, other: &Self) -> Ordering

This method returns an Ordering between self and other. Read more
1.21.0 · Source§

fn max(self, other: Self) -> Self
where Self: Sized,

Compares and returns the maximum of two values. Read more
1.21.0 · Source§

fn min(self, other: Self) -> Self
where Self: Sized,

Compares and returns the minimum of two values. Read more
1.50.0 · Source§

fn clamp(self, min: Self, max: Self) -> Self
where Self: Sized,

Restrict a value to a certain interval. Read more
Source§

impl<T: PartialEq> PartialEq for SyncCell<T>

Source§

fn eq(&self, other: &Self) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl<T: PartialOrd> PartialOrd for SyncCell<T>

Source§

fn partial_cmp(&self, other: &Self) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
1.0.0 · Source§

fn lt(&self, other: &Rhs) -> bool

Tests less than (for self and other) and is used by the < operator. Read more
1.0.0 · Source§

fn le(&self, other: &Rhs) -> bool

Tests less than or equal to (for self and other) and is used by the <= operator. Read more
1.0.0 · Source§

fn gt(&self, other: &Rhs) -> bool

Tests greater than (for self and other) and is used by the > operator. Read more
1.0.0 · Source§

fn ge(&self, other: &Rhs) -> bool

Tests greater than or equal to (for self and other) and is used by the >= operator. Read more
Source§

impl<T: Eq> Eq for SyncCell<T>

Source§

impl<T: Send> Send for SyncCell<T>

Source§

impl<T: Send> Sync for SyncCell<T>

Auto Trait Implementations§

§

impl<T> !Freeze for SyncCell<T>

§

impl<T> !RefUnwindSafe for SyncCell<T>

§

impl<T> Unpin for SyncCell<T>
where T: Unpin,

§

impl<T> UnwindSafe for SyncCell<T>
where T: UnwindSafe,

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<!> for T

Source§

fn from(t: !) -> T

Converts to this type from the input type.
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T> ToString for T
where T: Display + ?Sized,

Source§

fn to_string(&self) -> String

Converts the given value to a String. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.