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.

RustCli Tooling

Code

rustsnippet
28 lines
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 own match.

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

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:`.