cryo
Extend the lifetime of a reference. Safely.
Requires Rust 1.25.0 or later.
This crate provides a cell-like type Cryo that is similar to RefCell
except that it constrains the lifetime of its borrowed value
through a runtime check mechanism, erasing the compile-time lifetime
information. The lock guard CryoRef created from Cryo is
'static and therefore can be used in various situations that require
'static types, including:
- Store
CryoReftemporarily in astd::any::Any-compatible container. - Capture a reference to create a Objective-C block.
This works by, when a Cryo is dropped, blocking the current thread until
all references to the contained value are dropped so that none of them can
outlive the cell.
The constructor of Cryo is marked as unsafe because it's easy to
break various assumptions essential to memory safety if Cryo values are
not handled properly. Utility functions with_cryo and
with_cryo_mut ensure safety by providing access to Cryo values in a
controlled way.
Examples
with_cryo and Cryo:
use spawn;
let cell: usize = 42;
with_cryo;
with_cryo_mut and CryoMut:
with_cryo_mut;
assert_eq!;
Don't do this:
// The following statement will deadlock because it attempts to drop
// `Cryo` while a `CryoRef` is still referencing it
let borrow = with_cryo;
Caveats
- While it's capable of extending the effective lifetime of a reference,
it does not apply to nested references. For example, when
&'a NonStaticType<'b>is supplied to theCryo's constructor, the borrowed type isCryoRef<NonStaticType<'b>>, which is still partially bound to the original lifetime.
Details
Feature flags
parking_lot— Specifies to useparking_lotinstead ofstd::sync.
Overhead
Cryo<T> incurs moderate overhead due to the uses of Mutex and
Condvar. This can be alleviated somewhat by using the parking_lot
feature flag.
Nomenclature
From cryopreservation.
License: MIT/Apache-2.0