25.10 Example: Splitting a Mutable Slice (split_at_mut)

A classic example in the standard library is the split_at_mut function, which splits a mutable slice into two non-overlapping mutable slices. Safe Rust does not allow creating two mutable slices from one slice, because the compiler cannot prove that the slices do not overlap. The example below uses unsafe functions (like std::slice::from_raw_parts_mut) and pointer arithmetic to provide this functionality:

fn my_split_at_mut(slice: &mut [u8], mid: usize) -> (&mut [u8], &mut [u8]) {
    let len = slice.len();
    assert!(mid <= len);
    let ptr = slice.as_mut_ptr();
    unsafe {
        (
            std::slice::from_raw_parts_mut(ptr, mid),
            std::slice::from_raw_parts_mut(ptr.add(mid), len - mid),
        )
    }
}

fn main() {
    let mut data = [1, 2, 3, 4, 5];
    let (left, right) = my_split_at_mut(&mut data, 2);
    left[0] = 42;
    right[0] = 99;
    println!("{:?}", data); // Outputs: [42, 2, 99, 4, 5]
}

By carefully ensuring that the two returned slices do not overlap, the function safely exposes low-level pointer arithmetic in a high-level, safe API.