nafcodec/encoder/
counter.rs

1use std::io::Error as IoError;
2use std::io::Write;
3
4/// A wrapper type to count the number of bytes written to a writer.
5#[derive(Debug, Clone)]
6pub struct WriteCounter<W: Write> {
7    w: W,
8    n: usize,
9}
10
11impl<W: Write> WriteCounter<W> {
12    pub fn new(w: W) -> Self {
13        Self { w, n: 0 }
14    }
15
16    pub fn len(&self) -> usize {
17        self.n
18    }
19
20    pub fn into_inner(self) -> W {
21        self.w
22    }
23}
24
25impl<W: Write> Write for WriteCounter<W> {
26    fn write(&mut self, buf: &[u8]) -> Result<usize, IoError> {
27        match self.w.write(buf) {
28            Err(e) => Err(e),
29            Ok(n) => {
30                self.n += n;
31                Ok(n)
32            }
33        }
34    }
35
36    fn flush(&mut self) -> Result<(), IoError> {
37        self.w.flush()
38    }
39}