#experimental #cell #aliasing

no-std toast-cell

Zero-cost type-branded cell with no runtime checks

1 unstable release

0.3.0 Jan 2, 2024
0.2.1 Dec 30, 2023
0.2.0 Dec 30, 2023
0.1.1 Dec 29, 2023
0.1.0 Dec 29, 2023

#483 in Memory management

Unlicense

10KB
129 lines

toast-cell

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

Many thanks to the GhostCell project for pioneering this pattern and to matthieu-m for creating the ghost-cell crate.


lib.rs:

toast_cell

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.

Safety

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

Usage

The interface of this crate is very similar to that of GhostCell. The main difference is that Tokens require a type brand from type-factory instead of a generated lifetime brand.

use toast_cell::{type_factory, Cell, Token};

// 1. Create a brand type.
type_factory::with(|brand| {
    // 2. Make a unique `Token` out of it.
    //    The brand is consumed, so it cannot be used by any other token.
    let mut token = Token::new(brand);

    // 3. Use it with some `Cell`s.
    let cell = Cell::new(0);
    let references = [&cell, &cell, &cell];
    for cell in references {
        *cell.borrow_mut(&mut token) += 1;
    }

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

As the impl [Unique] brand types generated cannot be copied and are consumed, each Token is guaranteed to be unique from any other.

The brand types also guarantee that Cells used with one token are incompatible with other tokens.

type_factory::with(|initial| {
    let (brand, other_brand) = type_factory::split(initial);
    let mut token = Token::new(brand);

    let cell = Cell::new(41);
    *cell.borrow_mut(&mut token) += 1;       //

    let mut other_token = Token::new(other_brand);
    *cell.borrow_mut(&mut other_token) -= 1; //
});

How does it work?

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

Minimum supported Rust version

The MSRV is currently 1.61.

This may change between minor releases.

License

I release this crate into the public domain using the Unlicense.

Dependencies

~7KB