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.
Code
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
RAG Document Chunk VisualizerSplit long documents into RAG chunks by character or word count with configurable overlap, boundary alignment, token stats, and highlighted overlaps.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.