Checked Splits With split_at_checked

Cut a slice into halves with split_at_checked, which returns None past the end instead of panicking, so length checks fold into one match arm.

RustData Integrity

Code

rustsnippet
22 lines
fn frame<'a>(payload: &'a [u8], header_len: usize) -> Option<(&'a [u8], &'a [u8])> {
    // 越界返回 None,而不是像 split_at 那样 panic
    let (head, body) = payload.split_at_checked(header_len)?;
    if head.first() != Some(&0xAA) {
        return None;
    }
    Some((head, body))
}

fn main() {
    let packet = [0xAA, 0x01, 0x02, 0x03, 0x04];

    println!("ok: {:?}", frame(&packet, 1).map(|(h, b)| (h.len(), b.len())));
    println!("past end: {:?}", frame(&packet, 9));
    println!("empty header: {:?}", frame(&packet, 0));

    // 边界值 0 与 len 都合法,越界一位就是 None
    let empty: [u8; 0] = [];
    println!("empty at 0: {:?}", empty.split_at_checked(0).is_some());
    println!("at len: {:?}", packet.split_at_checked(packet.len()).is_some());
    println!("beyond len: {:?}", packet.split_at_checked(packet.len() + 1).is_some());
}

How it works

Structurally, expect the functions frame and main and nothing else.

What to watch for

  • The toolchain alone is enough — no dependency resolution happens.

Using it

The file announces its steps in the output: ok:, past end:, empty header:.

The entry point wires frame together — run it once and the whole demo flows.

Key statements

fn frame<'a>(payload: &'a [u8], header_len: usize) -> Option<(&'a [u8], &'a [u8])> {
// 越界返回 None,而不是像 split_at 那样 panic
let (head, body) = payload.split_at_checked(header_len)?;
if head.first() != Some(&0xAA) {
return None;
}
Some((head, body))
}

Interactive Tools for This Topic

FAQ

What does Checked Splits With split_at_checked print when run?
No setup needed: run the file and look for labeled lines like `ok:`, `past end:`, `empty header:` in the output.