Requires Rust 1.34.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:
- Storing
CryoRef
temporarily in astd::any::Any
-compatible container. - Capturing a reference to create a Objective-C block.
This works by, when a Cryo
is dropped, not letting the current thread's
execution move forward (at least¹) until all references to the expiring
Cryo
are dropped so that none of them can outlive the Cryo
.
This is implemented by readers-writer locks under the hood.
¹ SyncLock
blocks the current thread's execution on lock failure.
LocalLock
, on the other hand, panics because it's designed for
single-thread use cases and would deadlock otherwise.
Examples
cryo!
, Cryo
, and LocalLock
(single-thread lock
implementation, used by default):
use ;
let cell: usize = 42;
cryo!
, Cryo
, and SyncLock
(thread-safe lock implementation):
use ;
let cell: usize = 42;
cryo!
, CryoMut
, and SyncLock
:
assert_eq!;
Don't do these:
// The following statement will DEADLOCK because it attempts to drop
// `Cryo` while a `CryoRef` is still referencing it, and `Cryo`'s
// destructor will wait for the `CryoRef` to be dropped first (which
// will never happen)
let borrow = ;
// The following statement will ABORT because it attempts to drop
// `Cryo` while a `CryoRef` is still referencing it, and `Cryo`'s
// destructor will panic, knowing no amount of waiting would cause
// the `CryoRef` to be dropped
let borrow = ;
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 toCryo
's constructor, the borrowed type isCryoRef<NonStaticType<'b>>
, which is still partially bound to the original lifetime.
Details
Feature flags
-
std
(enabled by default) enablesSyncLock
. -
lock_api
enables the blanket implementation ofLock
on all types implementinglock_api::RawRwLock
, such asspin::RawRwLock
andparking_lot::RawRwLock
.
spin::RawRwLock
: https://docs.rs/spin/0.9.0/spin/type.RwLock.html
parking_lot::RawRwLock
: https://docs.rs/parking_lot/0.11.1/parking_lot/struct.RawRwLock.html
Overhead
Cryo<T, SyncLock>
's creation, destruction, borrowing, and unborrowing
each take one or two atomic operations in the best cases.
Neither of SyncLock
and LocalLock
require dynamic memory allocation.
Nomenclature
From cryopreservation.
License: MIT/Apache-2.0