Skip to content
Myr

counter.rs

This file

Path

crates/printer/src/counter.rs

97 lines · 2.2 KiB · Rust

Last changed by

Not known.

History of this file

Take it

1use std::io::{self, Write};23use termcolor::{ColorSpec, HyperlinkSpec, WriteColor};45/// A writer that counts the number of bytes that have been successfully6/// written.7#[derive(Clone, Debug)]8pub(crate) struct CounterWriter<W> {9    wtr: W,10    count: u64,11    total_count: u64,12}1314impl<W: Write> CounterWriter<W> {15    pub(crate) fn new(wtr: W) -> CounterWriter<W> {16        CounterWriter { wtr, count: 0, total_count: 0 }17    }18}1920impl<W> CounterWriter<W> {21    /// Returns the total number of bytes written since construction or the22    /// last time `reset` was called.23    #[inline]24    pub(crate) fn count(&self) -> u64 {25        self.count26    }2728    /// Returns the total number of bytes written since construction.29    #[inline]30    pub(crate) fn total_count(&self) -> u64 {31        self.total_count + self.count32    }3334    /// Resets the number of bytes written to `0`.35    #[inline]36    pub(crate) fn reset_count(&mut self) {37        self.total_count += self.count;38        self.count = 0;39    }4041    #[inline]42    pub(crate) fn get_mut(&mut self) -> &mut W {43        &mut self.wtr44    }4546    #[inline]47    pub(crate) fn into_inner(self) -> W {48        self.wtr49    }50}5152impl<W: Write> Write for CounterWriter<W> {53    // A high match count ad hoc benchmark flagged this as a hot spot.54    #[inline(always)]55    fn write(&mut self, buf: &[u8]) -> Result<usize, io::Error> {56        let n = self.wtr.write(buf)?;57        self.count += n as u64;58        Ok(n)59    }6061    #[inline]62    fn flush(&mut self) -> Result<(), io::Error> {63        self.wtr.flush()64    }65}6667impl<W: WriteColor> WriteColor for CounterWriter<W> {68    #[inline]69    fn supports_color(&self) -> bool {70        self.wtr.supports_color()71    }7273    #[inline]74    fn supports_hyperlinks(&self) -> bool {75        self.wtr.supports_hyperlinks()76    }7778    #[inline]79    fn set_color(&mut self, spec: &ColorSpec) -> io::Result<()> {80        self.wtr.set_color(spec)81    }8283    #[inline]84    fn set_hyperlink(&mut self, link: &HyperlinkSpec) -> io::Result<()> {85        self.wtr.set_hyperlink(link)86    }8788    #[inline]89    fn reset(&mut self) -> io::Result<()> {90        self.wtr.reset()91    }9293    #[inline]94    fn is_synchronous(&self) -> bool {95        self.wtr.is_synchronous()96    }97}