Crate toast_cell

Source
Expand description

A type-branded cell for aliasing checked at compile-time.

It’s based on the prior work of GhostCell, but trades lifetime brands for type brands.

§Usage

The interface of this crate is very similar to that of GhostCell. The main difference is that “tokens” are type brands from type-factory instead of lifetime brands.

use toast_cell::{type_factory, Cell};

// Create a unique token.
type_factory::with(|mut token| {
    let cell = Cell::new(0);

    // These are all references to the same cell, but we can still mutate it safely!
    let references = [&cell, &cell, &cell];
    for cell in references {
        *cell.borrow_mut(&mut token) += 1;
    }

    assert_eq!(cell.into_inner(), 3);
});

As impl Unique brand types cannot be copied and are exclusively borrowed for mutation, Cells of the same brand are guaranteed to never alias.

type_factory::with(|mut token| {
    let cell = Cell::new("Ghost");
    let borrow1 = cell.borrow_mut(&mut token);
    let borrow2 = cell.borrow_mut(&mut token);

    // error: cannot borrow `token` as mutable more than once at a time
    *borrow1 = "Toast";
});

It is also guaranteed that cells used with one brand are incompatible with other brands.

type_factory::with(|token| {
    let (mut token, mut other_token) = type_factory::split(token);

    let cell = Cell::new(41);
    *cell.borrow_mut(&mut token) += 1;       // ✅
    *cell.borrow_mut(&mut other_token) -= 1; // ❌
});

§How does it work?

The documentation of this crate is currently rather sparse. I recommend reading the documentation of ghost-cell for more information on the exact properties of GhostCell.

§Safety

Unlike GhostCell, this crate has not been formally proven. Use at your own risk.

§Minimum supported Rust version

The MSRV is currently 1.83.

This may change between minor releases.

§License

This crate is licensed under the Blue Oak Model License 1.0.0.

Re-exports§

pub use type_factory;

Structs§

Cell