pub struct SharedContainer<T> { /* private fields */ }Expand description
A unified container for shared data that works in both multi-threaded and single-threaded environments.
This struct provides an abstraction over different container types:
Arc<std::sync::RwLock<T>>(used in standard multi-threaded environments)Arc<tokio::sync::RwLock<T>>(used for async/await support)Rc<RefCell<T>>(used in single-threaded environments like WebAssembly)
It allows code to be written once but compile to the most efficient implementation based on the environment where it will run and the features enabled.
Implementations§
Sourcepub fn get_cloned(&self) -> Option<T>
pub fn get_cloned(&self) -> Option<T>
Gets a clone of the contained value.
This method acquires a read lock, clones the value, and releases the lock.
§Returns
Some(T): A clone of the contained valueNone: If the lock couldn’t be acquired
§Note
When using the tokio-sync feature, this method will try to acquire the lock
in a blocking manner, which may not be ideal for async code. Consider using
get_cloned_async() instead.
Sourcepub async fn get_cloned_async(&self) -> Twhere
T: Clone,
Available on crate feature tokio-sync only.
pub async fn get_cloned_async(&self) -> Twhere
T: Clone,
tokio-sync only.Sourcepub fn read(&self) -> Option<SharedReadGuard<'_, T>>
pub fn read(&self) -> Option<SharedReadGuard<'_, T>>
Sourcepub fn write(&self) -> Option<SharedWriteGuard<'_, T>>
pub fn write(&self) -> Option<SharedWriteGuard<'_, T>>
Sourcepub fn downgrade(&self) -> WeakSharedContainer<T>
pub fn downgrade(&self) -> WeakSharedContainer<T>
Creates a weak reference to this container.
A weak reference doesn’t prevent the value from being dropped when no strong references remain, which helps break reference cycles that could cause memory leaks.
§Returns
A WeakSharedContainer that points to the same data
Sourcepub async fn read_async(&self) -> SharedReadGuard<'_, T>
Available on crate feature tokio-sync only.
pub async fn read_async(&self) -> SharedReadGuard<'_, T>
tokio-sync only.Asynchronously gets a read-only access guard to the contained value.
This method is only available when the tokio-sync feature is enabled.
§Returns
A guard allowing read-only access to the value
§Examples
let container = SharedContainer::new(42);
let guard = container.read_async().await;
assert_eq!(*guard, 42);Sourcepub async fn write_async(&self) -> SharedWriteGuard<'_, T>
Available on crate feature tokio-sync only.
pub async fn write_async(&self) -> SharedWriteGuard<'_, T>
tokio-sync only.Asynchronously gets a writable access guard to the contained value.
This method is only available when the tokio-sync feature is enabled.
§Returns
A guard allowing read-write access to the value
§Examples
let container = SharedContainer::new(42);
let mut guard = container.write_async().await;
*guard = 100;