#refcell #interior-mutability #safe #reborrow #unborrow

no-std better-refcell

A drop-in replacement for RefCell with safe unborrow and reborrow capabilities

3 releases

Uses new Rust 2024

new 0.1.1 May 24, 2025
0.1.0 May 23, 2025
0.1.0-beta.1 May 20, 2025

#829 in Rust patterns

Download history 76/week @ 2025-05-16

76 downloads per month

MIT/Apache

17KB
307 lines

BetterRefCell

License Version Docs.rs CI

A drop-in replacement for RefCell with safe unborrow and reborrow capabilities.

Features

  • Allows putting back a borrowed value and reborrowing it within a closure.
  • Fully compatible with the RefCell interface of the stable Rust standard library.
  • Zero dependencies.

Usage

use better_refcell::BetterRefCell;
use std::cell::*;

let cell = BetterRefCell::new(42);

let mut guard: RefMut<i32> = cell.borrow_mut();
let mut_reference: &mut i32 = &mut *guard;

let ret = cell.unborrow(mut_reference, || {
    let mut guard = cell.borrow_mut();
    assert_eq!(*guard, 42);
    *guard += 1;
    format!("Returns {guard}")
});

assert_eq!(*guard, 43);
assert_eq!(ret, "Returns 43");

License

This project is dual-licensed under either the MIT or Apache-2.0 license, at your option.

No runtime deps