Zero Copy Chunk Reads With fill_buf

Read a BufReader in zero-copy chunks with fill_buf and consume, bounding each read to the buffer capacity instead of allocating a Vec per segment.

RustData Integrity

Code

rustsnippet
22 lines
use std::io::{BufRead, BufReader, Cursor};

fn main() {
    // 8 字节容量的缓冲:fill_buf 每次最多给 8 字节
    let mut reader = BufReader::with_capacity(8, Cursor::new(b"chunk-a|chunk-b|c".to_vec()));

    // zero-copy chunk loop:fill_buf 借出内部缓冲,consume 推进读位置
    let mut total = 0;
    loop {
        let chunk = match reader.fill_buf() {
            Ok(chunk) if !chunk.is_empty() => chunk,
            Ok(_) => break, // 空切片表示 EOF
            Err(_) => break,
        };
        let n = chunk.len();
        let text = String::from_utf8_lossy(chunk).into_owned();
        println!("read {}: {}", n, text);
        reader.consume(n);
        total += n;
    }
    println!("total consumed: {}", total);
}

How it works

Zero Copy Chunk Reads With fill_buf reduces to the function main.

A match spells out every case; omit one and the code does not compile.

What to watch for

  • Runs with what the toolchain already gives you — nothing extra.

Putting it to use

Entry signature: fn main()

Look for the read, total consumed: prefixes when the file runs; they tie each line to its step.

Core lines

Ok(_) => break, // 空切片表示 EOF
Err(_) => break,
};

Interactive Tools for This Topic

FAQ

What does Zero Copy Chunk Reads With fill_buf print when run?
The script runs standalone; its 2 labeled outputs include `read`, `total consumed:`.