First Chunk And Last Chunk Windows

Borrow fixed-size windows with first_chunk and last_chunk, getting Option<&[u8; N]> views instead of panicking copies or manual index math.

RustData Integrity

Code

rustsnippet
18 lines
fn main() {
    let frame: [u8; 6] = [0x1f, 0x8b, 0x08, 7, 0x9c, 0x42];

    // first_chunk::<N>():借走开头 N 字节成 &[u8; N] 固定窗口
    let magic: Option<&[u8; 2]> = frame.first_chunk();
    if let Some([a, b]) = magic {
        println!("magic: {a:#04x} {b:#04x}");
    }

    // last_chunk:从尾部借固定 window,常用于尾嵌校验和字段
    if let Some(checksum) = frame.last_chunk::<4>() {
        println!("checksum: {}", u32::from_le_bytes(*checksum));
    }

    // 长度不足 N 时拿到 None:不会 panic,也不需要手写下标判断
    let tiny = [1u8, 2];
    println!("tiny first4: {:?}", tiny.first_chunk::<4>());
}

How the code behaves

First Chunk And Last Chunk Windows comes down to the function main.

What to watch for

  • Nothing resolves through a package manager — calls land on built-in APIs.

Putting it to use

Signature: fn main()

The run emits 3 labeled sections — magic:, checksum:, tiny first4: — one per step.

Core lines

if let Some(checksum) = frame.last_chunk::<4>() {
    println!("checksum: {}", u32::from_le_bytes(*checksum));
}
if let Some([a, b]) = magic {
    println!("magic: {a:#04x} {b:#04x}");
}

Interactive Tools for This Topic

FAQ

What does First Chunk And Last Chunk Windows print when run?
No setup needed: run the file and look for labeled lines like `magic:`, `checksum:`, `tiny first4:` in the output.