| Crates.io | with-cell |
| lib.rs | with-cell |
| version | 0.1.0 |
| created_at | 2025-11-12 19:47:53.680504+00 |
| updated_at | 2025-11-12 19:47:53.680504+00 |
| description | More convenient Cell for non-Copy types |
| homepage | |
| repository | https://github.com/Demindiro/with-cell-rs |
| max_upload_size | |
| id | 1929849 |
| size | 7,179 |
with-cellA 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.
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.
use with_cell::WithCell;
let vec = WithCell::new(vec![]);
vec.with(|v| v.push(1337));
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!