#interior-mutability #const #mutability #cell #pure #interior

no-std pure_cell

Alternative to GhostCell that provides safe interior mutability via const expressions

2 unstable releases

0.2.0 Mar 28, 2022
0.1.0 Mar 12, 2022

#2775 in Rust patterns

Apache-2.0 OR MIT OR BSL-1.0

7KB
82 lines

pure_cell

Alternative to GhostCell that provides safe interior mutability via const expressions.


lib.rs:

Alternative to GhostCell that provides safe interior mutability via const expressions.

Advantages

  • Simple, with no cell keys
  • Works better with thread local global state.

Disadvantages

  • Const closures/fn pointers don't exist (yet), so this crate depends on macro magic to sort-of-polyfill them
  • Might not always optimize well (TODO)

Once const contexts support mutable references, this crate will be able to remove the second disadvantage. Additionally, once const function pointers stabilize, this crate will be able to remove the first disadvantage.

Getting Started

use pure_cell::{PureCell, pure_cell};

let mut cell = PureCell::new(15);
pure_cell!(cell, (), |state: u32, _args: ()| {
    state += 1;
});
let got = cell.get();
assert_eq!(*got, 16);
use pure_cell::{PureCell, pure_cell};

let cell = PureCell::new(15);
let amount = 2;
let state = pure_cell!(cell, amount, |state: u32, amount: u32| -> u32 {
    state += amount;
    state
});
assert_eq!(state, 17);

No runtime deps