Shared Container
A unified abstraction for shared data access in both multi-threaded and single-threaded environments.
Overview
shared-container provides a unified abstraction over different container types used for shared data access with interior mutability in different contexts. It abstracts over the differences between:
- Thread-safe
Arc<RwLock<T>>used in multi-threaded environments Rc<RefCell<T>>used in single-threaded environments like WebAssembly
This allows code using these containers to be written once but work efficiently in both contexts.
Features
- Platform-aware implementation: Automatically uses the most efficient implementation based on the target platform
- Unified API: Same API for both multi-threaded and single-threaded environments
- Read/Write access: Provides both read-only and read-write access to the contained data
- Weak references: Supports weak references to prevent reference cycles
- Clone support: Containers can be cloned to create multiple references to the same data
- Transparent access: Uses Rust's deref mechanism for ergonomic access to the contained data
Usage
Add this to your Cargo.toml:
[]
= "0.1.0"
Basic Example
use SharedContainer;
// Create a new container with a value
let container = new;
// Read access
if let Some = container.read
// Write access
if let Some = container.write
// Clone the container (both point to the same data)
let container2 = container.clone;
// Changes through one container are visible through the other
if let Some = container2.read
// Create a weak reference
let weak = container.downgrade;
// Upgrade weak reference to strong reference
if let Some = weak.upgrade
Working with Custom Types
use SharedContainer;
use Debug;
let user = User ;
let container = new;
// Get a clone of the contained value
if let Some = container.get_cloned
// Modify the user
if let Some = container.write
Platform-specific Behavior
- On native platforms,
SharedContainer<T>usesArc<RwLock<T>>internally - On WebAssembly (
wasm32target), it usesRc<RefCell<T>>internally - The API remains the same, but the behavior differs slightly:
- On native platforms, read/write operations can fail if the lock is poisoned
- On WebAssembly, read/write operations can fail if there's already a borrow
License
This project is licensed under the MIT License - see the LICENSE file for details.