Implement Write For A Counting Sink
Implement the Write trait for a counting sink that tallies bytes and newlines, returning the consumed length that write! and write_all rely on.
Code
use std::io::{self, Write};
struct CountingSink {
bytes: u64,
lines: u64,
}
impl Write for CountingSink {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
self.bytes += buf.len() as u64;
self.lines += buf.iter().filter(|&&b| b == b'\n').count() as u64;
Ok(buf.len()) // 如实报告消费的字节数,write_all 依赖它决定是否重试
}
fn flush(&mut self) -> io::Result<()> {
Ok(())
}
}
fn main() -> io::Result<()> {
let mut sink = CountingSink { bytes: 0, lines: 0 };
write!(sink, "first metric\n")?;
write!(sink, "second {}\n", "metric")?;
sink.write_all(b"tail without newline")?;
println!("bytes: {}", sink.bytes);
println!("lines: {}", sink.lines);
Ok(())
}Inside the snippet
Count the functions write, flush and main as the entire surface area of Implement Write For A Counting Sink.
Fallible operations return Result, and the ? operator short-circuits errors up to the caller.
Watch out for
- Dependency-free by construction — no registry, no lockfile entry.
- Errors travel through
Result; if you drop the?operators while adapting, each call site needs its ownmatch.
Using it
Signature: fn write(&mut self, buf: &[u8]) -> io::Result<usize>
Running the file prints labeled results such as bytes:, lines: — each operation’s effect is visible in the output.
Key statements
self.lines += buf.iter().filter(|&&b| b == b'\n').count() as u64;
sink.write_all(b"tail without newline")?;
fn flush(&mut self) -> io::Result<()> {
Ok(())
}
Interactive Tools for This Topic
Git Conventional Commit BuilderBuild and validate Conventional Commits v1.0.0 messages with type, scope, breaking markers, 72-char subject counter, body, footers, and git CLI command.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.Tar Archive Command BuilderBuild safe tar create, extract, and list commands for gzip, xz, zstd, and bzip2 archives with excludes, target directory (-C), and flag explanations.
FAQ
- How are errors reported?
- Through the type system: failures are `Result` variants the caller must consume.
- What does Implement Write For A Counting Sink print when run?
- Running the file directly is enough — expect labeled output lines such as `bytes:`, `lines:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.