#unsafe #slice #unsafecell

unsafe_cell_slice

A microlibrary for creating multiple mutable subslices of a slice

2 unstable releases

0.2.0 Oct 3, 2024
0.1.0 Sep 1, 2024

#1007 in Rust patterns

Download history 397/week @ 2024-08-31 51/week @ 2024-09-07 144/week @ 2024-09-14 133/week @ 2024-09-21 297/week @ 2024-09-28 90/week @ 2024-10-05 98/week @ 2024-10-12

623 downloads per month
Used in 9 crates (2 directly)

MIT/Apache

10KB

unsafe_cell_slice

Latest Version unsafe_cell_slice documentation msrv build

A Rust microlibrary for creating multiple mutable subslices of a slice.

Motivation

The rust borrow checker forbids creating multiple mutable references of a slice. For example, this fails to compile with cannot borrow `data` as mutable more than once at a time:

let mut data = vec![0u8; 2];
let data_a: &mut [u8] = &mut data[0..1];
let data_b: &mut [u8] = &mut data[1..2];
data_a[0] = 0;
data_b[1] = 1;

There are use cases for acquiring multiple mutable subslices of a slice, such as for writing independent elements in parallel. A safe approach is to borrow non-overlapping slices via slice::split_at_mut, slice::chunks_mut, etc. However, such approaches may not be applicable in complicated use cases, such as writing to interleaved elements.

UnsafeCellSlice

An UnsafeCellSlice can be created from a mutable slice or the spare capacity in a Vec. It has an unsafe index_mut method that permits creating multiple mutable subslices.

let mut data = vec![0u8; 2];
{
    let data = UnsafeCellSlice::new(&mut data);
    let data_a: &mut [u8] = unsafe { data.index_mut(0..1) };
    let data_b: &mut [u8] = unsafe { data.index_mut(1..2) };
    data_a[0] = 0;
    data_b[0] = 1;
}
assert_eq!(data[0], 0);
assert_eq!(data[1], 1);

Note that this is very unsafe and bypasses Rust's safety guarantees! It is the responsibility of the caller of UnsafeCellSlice::index_mut() to avoid data races and undefined behavior by not requesting overlapping subslices.

Under the hood, UnsafeCellSlice is a reference to a std::cell::UnsafeCell slice, hence the name of the crate.

Licence

unsafe_cell_slice is licensed under either of

Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.

No runtime deps