Pair
Safe API for generic self-referential pairs of owner and dependent.
You define how to construct a dependent type from a reference to an owning type,
and Pair will carefully bundle them together in a safe and freely movable
self-referential struct.
Example Usage
A typical use case might look something like this:
use ;
// Let's say you have some buffer type that contains a string
// And you have some borrowing "parsed" representation, containing string slices
// And you have some expensive parsing function you only want to run once
// You would then implement HasDependent and Owner for MyBuffer:
// Defines the owner/dependent relationship between MyBuffer and Parsed<'_>
// Define how to make a Parsed<'_> from a &MyBuffer
// You can now use MyBuffer in a Pair:
How it Works
Note: the implementation details described in this section are not part of the crate's public API, and are subject to change.
Under the hood, Pair moves the owner onto the heap, giving it a stable
memory address. It is then borrowed and used to construct the dependent, which
is also moved onto the heap. The dependent is type-erased, so that its
inexpressible self-referential lifetime goes away. All exposed APIs are careful
to ensure type and aliasing rules are upheld, regardless of anything safe user
code could do. When the owner needs to be dropped or recovered, the dependent
will first be recovered and dropped, ending the borrow of the owner. At that
point, the owner can safely be recovered and the Pair deconstructed.
Related Projects
| Crate | Macro free | No alloc |
Maintained | Soundness |
|---|---|---|---|---|
pair |
✅ | ❌ | ✅ | No known issues |
ouroboros |
❌ | ❌ | ✅ | ⚠️ Unsound ⚠️ |
self_cell |
❌ | ❌ | ✅ | No known issues |
yoke |
❌ | ✅ | ✅ | ⚠️ Unsound ⚠️ |
selfie |
✅ | ✅ | ❌ | ⚠️ Unsound ⚠️ |
nolife |
❌ | ❌ | ✅ | No known issues |
owning_ref |
✅ | ✅ | ❌ | ⚠️ Unsound ⚠️ |
rental |
❌ | ✅ | ❌ | ⚠️ Unsound ⚠️ |
fortify |
❌ | ❌ | ✅ | No known issues |
loaned |
❌ | ✅ | ✅ | No known issues |
selfref |
❌ | ✅ | ✅ | No known issues |
self-reference |
❌ | ✅ | ❌ | ⚠️ Unsound ⚠️ |
zc |
❌ | ✅ | ✅ | No known issues |
License
Licensed under either of:
- Apache License, Version 2.0 (LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0)
- MIT license (LICENSE-MIT or http://opensource.org/licenses/MIT)
at your option.
Contribution
Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.