with-cell

Crates.iowith-cell
lib.rswith-cell
version0.1.0
created_at2025-11-12 19:47:53.680504+00
updated_at2025-11-12 19:47:53.680504+00
descriptionMore convenient Cell for non-Copy types
homepage
repositoryhttps://github.com/Demindiro/with-cell-rs
max_upload_size
id1929849
size7,179
David Hoppenbrouwers (Demindiro)

documentation

https://docs.rs/with-cell

README

with-cell

A cell-like wrapper which provides a with and map method.

It makes it more convenient to use mutable data structures in a shared manner without the overhead of RefCell.

Why?

Ever written code like this?

use core::cell::RefCell;

let vec = RefCell::new(vec![1, 2, 3]);
if let Some(x) = vec.borrow_mut().pop() {
    vec.borrow_mut().push(x); // ¡ay caramba!
}

Annoying, isn't it? Easy enough to work around but also easy to forget.

Example

use with_cell::WithCell;

let vec = WithCell::new(vec![]);
vec.with(|v| v.push(1337));

How it works

The API is:

impl<T> WithCell<T>
where
    T: Default,
{
    pub fn with<F, R>(&self, f: F) -> R
    where
        F: FnOnce(&mut T) -> R;

    pub fn map<F>(&self, f: F)
    where
        F: FnOnce(T) -> T;
}

When with is called, the original value is replaced with a stub Default value. After the closure finishes, it is replaced with the original value again.

This does require two extra memory copies in the worst case, which might be suboptimal for large structures. The copy might be avoided if the compiler can prove the function does not panic.

map is very similar to [Cell::update], except it replaces the inner value with a stub.

Care must be taken when dealing with panics: the stub will remain in place!

Commit count: 0

cargo fmt