expression
Bounded streaming: count bytes with a fixed buffer
Process only the bytes actually read. A short read is not necessarily EOF. This fixture is a finite regular file; real untrusted streams require explicit resource limits. Use a fresh disposable working directory exclusively controlled by this program. Expected stdout (not executed): 7 Common mistake: Processing the full buffer after a short read.
Formal Syntax & Structure
rust syntaxrust
loop { let n = reader.read(&mut buf)?; /* process buf[..n] */ }Working Example
Example Snippetrust
fn main() { use std::fs::{self, File}; use std::io::{Read, Write}; fs::create_dir("bm-fixture").expect("fresh working directory required"); let p = std::path::Path::new("bm-fixture").join("note.txt"); File::create_new(&p).unwrap().write_all(b"abcdefg").unwrap(); let mut f = File::open(p).unwrap(); let mut buf = [0u8; 3]; let mut total = 0; loop { let n = f.read(&mut buf).unwrap(); if n == 0 { break; } total += n; } println!("{total}");}