jia_pipe_viewer 0.1.2

This was made for cruise but you can give it short
Documentation
//! The module contains the stats loop 
//!
//!
//! # Some eader 
//! More discussion!
mod timer;
use crossbeam::channel::Receiver;
use crossterm::{
    cursor, execute,
    style::{self, Color, PrintStyledContent},
    terminal::{Clear, ClearType},
};
use std::io::{self, Result, Stderr, Write};
use std::time::Instant;
use timer::Timer;

pub fn stats_loop(silent: bool, stats_rx: Receiver<usize>) -> Result<()> {
    let mut total_bytes = 0;
    let start = Instant::now();
    let mut timer = Timer::new();
    let mut stderr = io::stderr();

    loop {
        //recive bytes
        let num_bytes = stats_rx.recv().unwrap();
        timer.update();
        let rate_per_second = num_bytes as f64 / timer.delta.as_secs_f64();
        total_bytes += num_bytes;
        if !silent && timer.ready {
            timer.ready = false;
            output_progress(
                &mut stderr,
                total_bytes,
                start.elapsed().as_secs().as_time(),
                rate_per_second,
            );
        }

        if num_bytes == 0 {
            break;
        }
    }
    if !silent {
        eprintln!(
        );
    }
    Ok(())
}

fn output_progress(stderr: &mut Stderr, bytes: usize, elapsed: String, rate: f64) {
    let bytes = style::style(format!("Bytes: {} ", bytes)).with(Color::Red);
    let elapsed = style::style(elapsed).with(Color::Green);
    let rate = style::style(format!("Rate: [{:.0}b/s] ", rate)).with(Color::Blue);
    let _ = execute!(
        stderr,
        cursor::MoveToColumn(0),
        Clear(ClearType::CurrentLine),
        PrintStyledContent(bytes),
        PrintStyledContent(elapsed),
        PrintStyledContent(rate)
    );

    let _ = stderr.flush();
}

/// The TimeOutput trait a `.as_time()` method to `u64`
///
/// #Example 
/// Here is an example of how to use it.
/// ```rust
/// use jia_pipe_viewer::stats::TimeOutput;
/// assert_eq!(65_u64.as_time(), String::from("Time: 0:01:05 "))
/// ```  
pub trait TimeOutput {
    fn as_time(&self) -> String;
}

impl TimeOutput for u64 {
    /// Renders the u64 into a time String
    
    fn as_time(&self) -> String {
        let (hours, left) = (*self / 3600, *self % 3600);
        let (minutes, seconds) = (left / 60, left % 60);
        format!("Time: {}:{:02}:{:02} ", hours, minutes, seconds)
    }
}

#[cfg(test)]
mod tests {

    use super::TimeOutput;

    #[test]
    fn as_time_format(){
        let pairs = vec![
            (5_u64, "Time: 0:00:05 "),
            (60_u64, "Time: 0:01:00 "),
            (3603_u64, "Time: 1:00:03 "),
            (154_u64, "Time: 0:02:34 "),
        ];
        for (input, output) in pairs {
            assert_eq!(input.as_time().as_str(), output);
        }
    }

}