Fixed Frames With next_chunk

Read fixed-size frames from any iterator with next_chunk, which returns [T; N] on success or the remaining iterator when fewer items are left.

RustData Integrity

Code

rustsnippet
19 lines
fn main() {
    // 遥测字节流:每 4 个字节为一帧,共 10 个字节
    let mut frames = [10u8, 20, 30, 40, 50, 60, 70, 80, 90, 100].into_iter();

    // next_chunk::<N>() 一次取出 [T; N],恰好取满是 Ok
    match frames.next_chunk::<4>() {
        Ok(frame) => println!("frame 1: {frame:?}"),
        Err(rest) => println!("short read: {} bytes left", rest.count()),
    }
    match frames.next_chunk::<4>() {
        Ok(frame) => println!("frame 2: {frame:?}"),
        Err(rest) => println!("short read: {} bytes left", rest.count()),
    }
    // 只剩 2 个字节:取不满 4 个,剩余迭代器原样返回
    match frames.next_chunk::<4>() {
        Ok(frame) => println!("frame 3: {frame:?}"),
        Err(rest) => println!("short read: {} bytes left", rest.count()),
    }
}

How each part fits

The snippet is organized around the function main.

The match expression is exhaustive — the compiler enforces that no case is missing.

What to watch for

  • Nothing beyond the existing toolchain is required to run this file as-is.

Applying it

Entry signature: fn main()

Expect labeled output — frame 1:, short read:, frame 2: — when the file runs.

Statements that matter

match frames.next_chunk::<4>() {
    Ok(frame) => println!("frame 1: {frame:?}"),
    Err(rest) => println!("short read: {} bytes left", rest.count()),
}
match frames.next_chunk::<4>() {
    Ok(frame) => println!("frame 2: {frame:?}"),
    Err(rest) => println!("short read: {} bytes left", rest.count()),
}
match frames.next_chunk::<4>() {
    Ok(frame) => println!("frame 3: {frame:?}"),
    Err(rest) => println!("short read: {} bytes left", rest.count()),
}

Interactive Tools for This Topic

FAQ

What does Fixed Frames With next_chunk print when run?
Invoke the file as-is — the `frame 1:`, `short read:`, `frame 2:` prefixes identify which step printed each line.