Crates.io | veccell |
lib.rs | veccell |
version | 0.4.0 |
source | src |
created_at | 2022-06-28 23:17:44.440368 |
updated_at | 2022-07-11 15:10:57.308951 |
description | Provides VecCell, a variant of Vec with interior mutability. |
homepage | |
repository | https://github.com/adri326/veccell/ |
max_upload_size | |
id | 615075 |
size | 52,111 |
A variant of Vec
, with interior mutability, where one element may be borrowed mutably and several other elements may be borrowed immutably at the same time.
You would use this crate if:
Vec
with interior mutabilityYou would need something else if:
Vec<T>
instead)RefCell<Vec<T>>
instead)Vec<RefCell<T>>
instead)Vec<Mutex<T>>
or Arc<Vec<Mutex<T>>>
instead)Run cargo add veccell
or add the following in Cargo.toml
:
[dependencies]
veccell = "0.4"
VecCell
allows an element to be borrowed mutably, and other elements to be accessed immutably:
use veccell::VecCell;
let mut arr: VecCell<usize> = VecCell::new();
arr.push(32);
arr.push(48);
arr.push(2);
let mut third = arr.borrow_mut(2).unwrap(); // Borrow the third element mutably
let first = arr.borrow(0).unwrap(); // Borrow the first element immutably
*third *= *first; // Multiply the third element by the first element
println!("{}", third); // Prints 64
std::mem::drop(third); // Drop the mutable borrow
println!("{}", arr.borrow(2).unwrap()); // Also prints 64
However, to prevent aliasing, while an element is borrowed mutably, it cannot be borrowed immutably:
use veccell::VecCell;
let mut arr: VecCell<usize> = VecCell::new();
arr.push(32);
arr.push(48);
arr.push(8);
let mut third = arr.borrow_mut(2).unwrap(); // Borrow the third element mutably
// Here, arr.borrow(2) returns None,
// because the third element is already borrowed mutably.
let third2 = arr.borrow(2);
assert!(third2.is_none());
std::mem::drop(third);
VecCell
only stores two additional pieces of information:
mut_borrow
)borrows
)This has the advantage of putting all of its elements next to each other in memory, if their padding allows it, but has the disadvantage of having more restrictive rules than you'd expect:
To borrow an element mutably, no element must be borrowed mutably or immutably:
use veccell::VecCell;
let mut arr: VecCell<usize> = VecCell::new();
arr.push(32);
arr.push(48);
arr.push(8);
let second = arr.borrow(1).unwrap();
let third = arr.borrow_mut(2);
// VecCell has no way of telling that the existing immutable borrow (`second`)
// isn't borrowing the third element.
assert!(third.is_none());
std::mem::drop(third);
let first = arr.borrow_mut(0);
// VecCell can only allow one mutable borrow at a time
assert!(arr.borrow_mut(1).is_none());
serde
is supported. To use it, enable the serde
feature:
[dependencies]
veccell = { version = "0.4", features = ["serde"] }
This project is dual-licensed under the MIT license and the Apache v2.0 license. You may choose either of those when using this library.
Any contribution to this repository must be made available under both licenses.