pub struct Ref<T> { /* private fields */ }Expand description
A reference to data stored in a garbage collector.
Unlike a Root<T>, this type is not guaranteed to have access to its
underlying data. If no Collectable reachable via all active Roots
marks this allocation, it will be collected.
Because of this, direct access to the data is not provided. To obtain a
reference, call Ref::load().
§Loading a reference
Ref::load() is used to provide a reference to data stored in the garbage
collector.
use refuse::{CollectionGuard, Ref};
let guard = CollectionGuard::acquire();
let data = Ref::new(42, &guard);
assert_eq!(data.load(&guard), Some(&42));References returned from Ref::load() are tied to the lifetime of the
guard. This ensures that a reference to data can only be held between
moments when the garbage collector can be run. For example these usages are
prevented by the compiler:
let guard = CollectionGuard::acquire();
let data = Ref::new(42, &guard);
let reference = data.load(&guard).unwrap();
drop(guard);
// error[E0505]: cannot move out of `guard` because it is borrowed
assert_eq!(reference, &42);let mut guard = CollectionGuard::acquire();
let data = Ref::new(42, &guard);
let reference = data.load(&guard).unwrap();
guard.yield_to_collector();
// error[E0502]: cannot borrow `guard` as mutable because it is also borrowed as immutable
assert_eq!(reference, &42);Implementations§
Source§impl<T> Ref<T>where
T: Collectable,
impl<T> Ref<T>where
T: Collectable,
Sourcepub fn new<'a>(value: T, guard: &impl AsRef<CollectionGuard<'a>>) -> Self
pub fn new<'a>(value: T, guard: &impl AsRef<CollectionGuard<'a>>) -> Self
Stores value in the garbage collector, returning a “weak” reference to
it.
Sourcepub fn load<'guard>(
&self,
guard: &'guard CollectionGuard<'_>,
) -> Option<&'guard T>
pub fn load<'guard>( &self, guard: &'guard CollectionGuard<'_>, ) -> Option<&'guard T>
Loads a reference to the underlying data. Returns None if the data has
been collected and is no longer available.
Sourcepub fn as_root(&self, guard: &CollectionGuard<'_>) -> Option<Root<T>>
pub fn as_root(&self, guard: &CollectionGuard<'_>) -> Option<Root<T>>
Loads a root reference to the underlying data. Returns None if the
data has been collected and is no longer available.