Struct rust_examples::brands::BrandedVec [−][src]
pub struct BrandedVec<'id, T> { /* fields omitted */ }Expand description
Thin wrapper for Vec which can only be accessed via an associated BrandedIndex
Implementations
Public API of the BrandedVec as presented in the GhostCell paper.
Summary
This implementation defines a vector which
- has static bounds check (i.e. no additional index check in
getandget_mut) - is monotonic (i.e. can only be appened to via
push) - iterior pointers can only be accessed via associated BrandedIndex
- is a zero-cost abstraction over a Vec
Example 1
use rust_examples::brands::BrandedVec;
let vec1 = vec![10, 11];
let vec2 = vec![20, 21];
BrandedVec::make(vec1, move |mut bvec1| {
bvec1.push(12);
let i1 = bvec1.push(13);
BrandedVec::make(vec2, move |mut bvec2| {
let i2 = bvec2.push(22);
*bvec2.get_mut(i2) -= 1;
assert_eq!(bvec1.get(i1), &13);
assert_eq!(bvec2.get(i2), &21);
});
});Example 2
This example demonstrates that BrandedIndex is always bound to the BrandedVec for which it was originally created and as such cannot be used for another BrandedVec.
use rust_examples::brands::BrandedVec;
let vec1 = vec![10, 11];
let vec2 = vec![20, 21];
BrandedVec::make(vec1, move |mut bvec1| {
let i1 = bvec1.push(12);
BrandedVec::make(vec2, move |mut bvec2| {
// Can't use index that was branded for `bvec1`
bvec2.get(i1)
});
});
Example 3
Finally, BrandedVec is a zero-cost abstraction for ordinary Vec.
use std::mem::size_of;
use rust_examples::brands::BrandedVec;
assert_eq!(size_of::<BrandedVec<'_, u8>>(), size_of::<Vec<u8>>());Construct new BrandedVec from given Vec and run a closure f with it.
for<'a> here is an example of rank-2 polymorphism, meaning that the closure given
by f must be valid for any choice of 'a, not just 'id.
So make here is allowed to “pick” a fresh lifetime 'id for each new BrandedVec but
the closure f, when it receives this branded vector, must treat the 'id brand opaquely.
Appends given value to this BrandedVec and returns BrandedIndex of this item which is
bound to self. Since BrandedVec can only be appended to, this BrandedIndex is
guaranteed to always be within bounds.
Method which associates (brands) given idx with this BrandedVec if it is within bounds
- i.e. performs the bounds check which
Vec::getdoes.
Get shared reference to the interior value at given BrandedIndex without performing a bounds check.
Get mutable reference to the interior value at given BrandedIndex without performing a bounds check.
