skip to content

How does Rust's standard library implement the safe `<[T]>::split_at_mut`, and which checks keep its `unsafe` body sound?

level: seniorimportance: should knowfreq 45%

answer

  1. one raw pointer, two slices
  2. the mid <= len check
  3. from_raw_parts_mut twice
  4. lifetimes tied by the signature

basics

~20 s

It checks mid <= len, panicking with "mid > len" otherwise, takes one raw pointer from as_mut_ptr, and builds from_raw_parts_mut(ptr, mid) and from_raw_parts_mut(ptr.add(mid), len - mid). The ranges cannot overlap and both borrow from the input.

solid answer

~40 s

Safe code cannot return two `&mut` into one slice, so std uses `unsafe` and proves the result itself. `split_at_mut` calls `split_at_mut_checked`, which returns `None` unless `mid <= self.len()`, and then panics with `"mid > len"` on that `None`. Inside `split_at_mut_unchecked` it takes **one** raw pointer with `as_mut_ptr` and builds the halves with `slice::from_raw_parts_mut(ptr, mid)` and `from_raw_parts_mut(ptr.add(mid), len - mid)`. Soundness rests on four facts: the bounds check, the two ranges being disjoint, both coming from the same pointer, and the signature tying both outputs to the input `&mut self`, so the original slice stays frozen while the halves live. Drop the check and a safe caller can reach out-of-bounds memory.

code

rust · 23 lines
rust
use std::slice;

pub fn split_at_mut<T>(s: &mut [T], mid: usize) -> (&mut [T], &mut [T]) {
    let len = s.len();
    assert!(mid <= len, "mid > len"); // without this check the fn is unsound
    let ptr = s.as_mut_ptr();
    // SAFETY: ptr is valid for len elements; [0, mid) and [mid, len) do not
    // overlap, and both borrows live no longer than the &mut s they came from.
    unsafe {
        (
            slice::from_raw_parts_mut(ptr, mid),
            slice::from_raw_parts_mut(ptr.add(mid), len - mid),
        )
    }
}

fn main() {
    let mut pixels = [1, 2, 3, 4, 5, 6];
    let (left, right) = split_at_mut(&mut pixels, 2);
    left[0] = 10;
    right[0] = 30;
    println!("{pixels:?}");
}

go deeper

for a junior

Recall that split_at_mut returns two mutable halves of one slice, that it panics when mid exceeds the length, and that std implements it with unsafe code.

for a middle

Walk through the body: one raw pointer from as_mut_ptr, two calls to slice::from_raw_parts_mut, and the mid <= len check before them.

for a senior

List the proof obligations: bounds, disjointness, one origin pointer and lifetimes bounded by the signature. Explain why dropping the check is unsound and why two whole-slice reborrows fail under Stacked Borrows.

for a principal

Use split_at_mut as the template for reviewing any container's unsafe accessors: a checked safe entry point, an unchecked core with documented preconditions, and lifetimes tied by the signature.

## Why the safe version cannot be written The borrow checker reasons about a slice as one place: `&mut s[..mid]` borrows all of `s` mutably, so a second `&mut s[mid..]` is rejected even though the ranges are disjoint (the borrow-checker material covers that error). Splitting a slice into two independently mutable halves is therefore something only `unsafe` code can do, and `split_at_mut` is the canonical example of a **safe abstraction** whose unsafe body carries its own proof. ## The implementation in std In the 1.99.1 library source the safe method delegates through a checked variant to an unchecked one: 1. `split_at_mut(&mut self, mid)` calls `split_at_mut_checked(mid)` and panics with `"mid > len"` when that returns `None`. 2. `split_at_mut_checked` tests `mid <= self.len()` and only then calls the unsafe `split_at_mut_unchecked`. 3. `split_at_mut_unchecked` reads `len` and `ptr = self.as_mut_ptr()`, and returns `(from_raw_parts_mut(ptr, mid), from_raw_parts_mut(ptr.add(mid), len - mid))` under the comment that the two ranges "are not overlapping, so returning a mutable reference is fine". It also has an internal `assert_unsafe_precondition!` that catches misuse in builds with UB checks enabled. A hand-written version has the same shape: ```rust pub fn split_at_mut<T>(s: &mut [T], mid: usize) -> (&mut [T], &mut [T]) { let len = s.len(); assert!(mid <= len, "mid > len"); let ptr = s.as_mut_ptr(); // SAFETY: [0, mid) and [mid, len) are disjoint and inside s. unsafe { (slice::from_raw_parts_mut(ptr, mid), slice::from_raw_parts_mut(ptr.add(mid), len - mid)) } } ``` ## The proof obligations Each line answers a requirement in the docs of the unsafe functions it calls: - **In bounds.** `ptr.add(mid)` must stay within the allocation (one past the end is allowed), and `from_raw_parts_mut` needs `len` initialised elements behind its pointer. The `mid <= len` check gives both; without it, a release build computes `len - mid` with wrapping arithmetic and builds a slice of enormous length. - **No overlap.** Two live `&mut` to the same element would be undefined behaviour; `[0, mid)` and `[mid, len)` share no element. - **One provenance.** Both halves come from the same raw pointer, taken once. - **Bounded lifetimes.** `from_raw_parts_mut` returns a slice whose lifetime "is inferred from its usage", so nothing inside the function limits it. The signature does: with one input reference, elision gives both outputs the input's lifetime, so the caller's `&mut` stays frozen until the halves are gone. | Step | What it guarantees | |---|---| | `assert!(mid <= len)` | Both ranges lie inside the slice | | `as_mut_ptr()` once | Both halves share one origin pointer | | `from_raw_parts_mut(ptr, mid)` | Left half covers `[0, mid)` | | `from_raw_parts_mut(ptr.add(mid), len - mid)` | Right half covers `[mid, len)` | | Elided signature | Halves cannot outlive the borrowed input | ## A tempting variant that Miri rejects A shorter version casts the slice to `*mut [T]` and indexes twice: `(&mut (&mut *p)[..mid], &mut (&mut *p)[mid..])`. It compiles (rustc's deny-by-default `dangerous_implicit_autorefs` lint rejects the form without the explicit `&mut *p`) and prints the right output, but each `&mut *p` creates a fresh mutable reference to the **whole** slice. Miri's default Stacked Borrows model reports undefined behaviour when the second whole-slice borrow invalidates the first half; the experimental Tree Borrows model accepts the same program. The std shape, two slices built from one raw pointer, is clean under both, which is why it is the one to copy. ## What the unsafe functions do not check `slice::from_raw_parts_mut` has its own debug-time precondition check, but in the 1.99.1 source it covers only that the pointer is aligned and non-null and that the total size does not exceed `isize::MAX`. It knows nothing about the allocation's real length, and nothing about whether another `&mut` already covers those elements. Bounds and disjointness are entirely the caller's proof, which is why the `assert!` and the arithmetic deserve the closest reading in review. ## Reusing the pattern The same reasoning sits behind `chunks_mut`, `iter_mut` and `split_first_mut`, and behind a container's own splitting methods. For a custom type, wrap the raw-pointer arithmetic in one small function, check every index against the length first, return references whose lifetimes the signature ties to `&mut self`, and document the disjointness argument in a `// SAFETY:` comment. Often no new unsafe code is needed at all. A stack vector that already exposes a sound `as_mut_slice` can offer its own split as `self.as_mut_slice().split_at_mut(mid)`, reusing std's proof instead of writing a second one; that is the cheapest abstraction to audit.

  • What goes wrong if a hand-written `split_at_mut` leaves out the `mid <= len` check?
    A safe caller can pass `mid > len`. `ptr.add(mid)` then points beyond the memory the slice covers, which is undefined behaviour once it leaves the allocation, and in a release build `len - mid` wraps to a huge length, so the right half covers memory the slice does not own. A debug build may panic on the `len - mid` overflow, but that is not a guarantee to rely on. Either way, safe code reaches UB, so the function is unsound.
  • Where do the returned halves get their lifetime from?
    From the signature. `slice::from_raw_parts_mut` returns a slice whose lifetime is inferred from use, so it is unbounded inside the function. Because the function has one input reference, elision gives both outputs that input's lifetime: the caller's `&mut` slice stays mutably borrowed until both halves are dropped. A signature declaring `'static` outputs, with a `T: 'static` bound, would also compile and would be unsound.

  • split_at_mut uses mem::transmute to duplicate the mutable slice reference.
  • The mid <= len check is a convenience; the function is sound without it.
  • slice::from_raw_parts_mut checks the length against the allocation at run time.
  • Taking two &mut (*p)[..] borrows through one raw pointer is the same as std's version.
  • The borrow checker already knows that [..mid] and [mid..] are disjoint.