5 releases (breaking)

0.5.0 Feb 23, 2023
0.4.0 Feb 23, 2023
0.3.0 Feb 23, 2023
0.2.0 Feb 23, 2023
0.1.0 Feb 23, 2023

#706 in Memory management

Unlicense

30KB
619 lines

Highly generic wrapper for shared mutable data in Rust.

See the documentation for more information.


lib.rs:

Description

our provides a highly generic shared mutable data abstraction.

Usage

Shared is a generic wrapper around what is usually a smart pointer to something with interior mutability. It provides a way to construct and access shared mutable data, and also provides a way to compare and hash shared values.

Even though Shared is usually implemented with some kind of interior mutability, Shared's methods that return write guards to the shared value require mutable references to the Shared itself. While this can be easily circumvented by simply cloning the Shared, it is implemented this way to try to prevent at compile-time accidentally trying to acquire two exclusive guards, which would panic for non-thread-safe Shareds and deadlock for thread-safe ones.

Shared has three type parameters:

  • The type of the shared value
  • A ShareKind, which determines how the shared value is constructed and accessed
  • ShareUnsync is a non-thread-safe shared value implemented as Rc<RefCell<T>>
  • ShareSync is a thread-safe shared value implemented as Arc<parking_lot::RwLock<T>>
  • A type which usually implements PartialEqKind, EqKind, PartialOrdKind, OrdKind, and HashKind, which determines how shared values are compared and hashed.
  • ByRef compares and hashes by reference
  • ByVal compares and hashes by value

Type aliases

There are four type aliases for Shared provided for convenience:

Non-thread-safe Thread-safe
Compare by reference UnsyncByRef SyncByRef
Compare by value UnsyncByVal SyncByVal

Example

use our::*;

// `SyncByRef` is a thread-safe shared value with by-reference comparison and hashing.
let mut a = SyncByRef::new(0);
let mut b = a.clone();
std::thread::spawn(move || b.set(1)).join().unwrap();
assert_eq!(a.get(), 1);
let c = SyncByRef::new(1);
assert_ne!(a, c); // Notice that while while `a` and `c` both equal `1`,
// they do not compare equal because they are different
// pointers.

// `UnsyncByVal` is a non-thread-safe shared value with by-value comparison and hashing.
let a = UnsyncByVal::new(5);
let b = UnsyncByVal::new(5);
assert_eq!(a, b); // Notice that `a` and `b` compare equal
// even though they are different pointers.

Dependencies

~0.4–6.5MB
~11K SLoC