How to track how many bytes are written using "std :: io :: Write"?

When writing to a binary file format, it is useful to be able to check how many bytes have been written (for example, for alignment) or simply so that the nested functions write the correct amount of data.

Is there a way to check std::io::Writeto see how much has been written? If not, what would be a good approach for wrapping a writer so that he can keep track of how many bytes were written?

+6
source share
2 answers

Writehas two required methods: Writeand flush. Since it Writealready returns the number of bytes written, you simply keep track of this:

use std::io::{self, Write};

struct ByteCounter<W> {
    inner: W,
    count: usize,
}

impl<W> ByteCounter<W>
    where W: Write
{
    fn new(inner: W) -> Self {
        ByteCounter {
            inner: inner,
            count: 0,
        }
    }

    fn into_inner(self) -> W {
        self.inner
    }

    fn bytes_written(&self) -> usize {
        self.count
    }
}

impl<W> Write for ByteCounter<W>
    where W: Write
{
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
        let res = self.inner.write(buf);
        if let Ok(size) = res {
            self.count += size
        }
        res
    }

    fn flush(&mut self) -> io::Result<()> {
        self.inner.flush()
    }
}

fn main() {
    let out = std::io::stdout();
    let mut out = ByteCounter::new(out);
    writeln!(&mut out, "Hello, world! {}", 42).unwrap();
    println!("Wrote {} bytes", out.bytes_written());
}

write_all write_fmt, . .

+7

, , std::io::Seek, seek :

pos = f.seek(SeekFrom::Current(0))?;

seek std::fs::File ( std::io::BufWriter, wrapped type seek ).


, :

use ::std::io::{Write, Seek, SeekFrom, Error};

fn my_write<W: Write>(f: &mut W) -> Result<(), Error> { ... }

seek:

fn my_write<W: Write + Seek>(f: &mut W) -> Result<(), Error> { ... }
+5

Source: https://habr.com/ru/post/1014919/


All Articles