Expand description
A Box
with weak references.
A RefBox
is a smart pointer that owns the data, just like a standard
Box
. Similarly, a RefBox cannot be cloned cheaply, and when it is
dropped, the data it points to is dropped as well. However, a RefBox may
have many Ref
pointers to the same data. These pointers don’t own the
data and are reference counted, comparable to the standard library’s
Weak
. Which means, as long as the RefBox is alive, Refs can be used to
access the data from multiple places without lifetime parameters.
A RefBox could be seen as a lighter alternative to the standard library’s
Rc
, Weak
and RefCell
combination, in cases where there is one
Rc with many Weaks to the same data.
A RefBox does not differentiate between strong and weak pointers and immutable and mutable borrows. There is always a single strong pointer, zero, one or many weak pointers and all borrows are mutable. This means there can only be one borrow active at any given time. But in return, RefBox uses less memory, is faster to borrow from, and a Ref does not need to be upgraded to a RefBox in order to access the data.
Note: this crate is currently experimental.
Rc<RefCell> vs RefBox
Rc<RefCell<T>> | RefBox<T> | |
---|---|---|
Pointer kinds | Many strong pointers and many weak pointers | One strong owner and many weak pointers |
Clonable | Both Rc and Weak are cheap to clone | Only Ref can be cheaply cloned |
Up-/Downgrading | Rc is downgradable, Weak is upgradable | No up- or downgrading, but RefBox::create_ref |
Data access | RefCell::try_borrow_mut | RefBox::try_borrow_mut |
Weak data access | 1. Weak::upgrade 2. RefCell::try_borrow_mut 3. Rc::drop | Ref::try_borrow_mut |
Active borrows | One mutable or many immutable | One (mutable or immutable) |
T::drop | When all Rc s are dropped | When owner RefBox is dropped |
Max no. Weak s | usize::MAX | u32::MAX |
Heap overhead | 64-bit: 24 bytes 32-bit: 12 bytes | 8 bytes |
Performance | Cloning is fast, mutating is slow | Cloning is a tiny bit slower, mutating is much faster |
Examples
use refbox::RefBox;
fn main() {
// Create a RefBox.
let owner = RefBox::new(100);
// Create a weak reference.
let weak = owner.create_ref();
// Access the data.
let borrow = weak.try_borrow_mut().unwrap();
assert_eq!(*borrow, 100);
}
Optional Features
- cyclic: Enables the
RefBox::new_cyclic()
method. This allows you to create data structures that contain weak references to (parts of) themselves in one go. Requires the Nightly feature layout_for_ptr.
Macros
Coerces a RefBox<T>
into a RefBox<dyn Trait>
on stable Rust.
Coerces a Ref<T>
into a Ref<dyn Trait>
on stable Rust.
Structs
A smart pointer with many reference-counted weak references.