pipeviewer_exercise/
stats.rs

1//! The stats module contains the stats loop
2//!
3//! # Some header
4//! More discussion!
5
6mod timer;
7
8use crossbeam::channel::Receiver;
9use crossterm::{
10    cursor, execute,
11    style::{self, Color, PrintStyledContent, Stylize},
12    terminal::{Clear, ClearType},
13};
14use std::io::{self, Result, Stderr, Write};
15use std::time::Instant;
16use timer::Timer;
17
18pub fn stats_loop(silent: bool, stats_rx: Receiver<usize>) -> Result<()> {
19    let mut total_bytes = 0;
20    let start = Instant::now();
21    let mut timer = Timer::new();
22    let mut stderr = io::stderr();
23
24    loop {
25        let num_bytes = stats_rx.recv().unwrap();
26        timer.update();
27        let rate_per_second = num_bytes as f64 / timer.delta.as_secs_f64();
28
29        total_bytes += num_bytes;
30
31        if !silent && timer.ready {
32            timer.ready = false;
33            output_progress(
34                &mut stderr,
35                total_bytes,
36                start.elapsed().as_secs().as_time(),
37                rate_per_second,
38            );
39        }
40        if num_bytes == 0 {
41            break;
42        }
43    }
44    if !silent {
45        eprintln!();
46    }
47    Ok(())
48}
49
50fn output_progress(stderr: &mut Stderr, bytes: usize, elapsed: String, rate: f64) {
51    let bytes = style::style(format!("{} ", bytes)).with(Color::Red);
52    let elapsed = style::style(elapsed).with(Color::Green);
53    let rate = style::style(format!(" [{:.0}b/s]", rate)).with(Color::Blue);
54    let _ = execute!(
55        stderr,
56        cursor::MoveToColumn(0),
57        Clear(ClearType::CurrentLine),
58        PrintStyledContent(bytes),
59        PrintStyledContent(elapsed),
60        PrintStyledContent(rate),
61    );
62    let _ = stderr.flush();
63}
64
65/// The TimeOutput trait adds a `.as_time()` method to `u64`
66///
67/// # Example
68///
69/// ```rust
70/// use pipeviewer_exercise::stats::TimeOutput;
71/// assert_eq!(65_u64.as_time(), String::from("0:01:05"))
72/// ```
73pub trait TimeOutput {
74    fn as_time(&self) -> String;
75}
76
77impl TimeOutput for u64 {
78    /// Renders the u64 into a time string
79    fn as_time(&self) -> String {
80        let (hours, left) = (*self / 3600, *self % 3600);
81        let (minutes, seconds) = (left / 60, left % 60);
82        format!("{}:{:02}:{:02}", hours, minutes, seconds)
83    }
84}
85
86#[cfg(test)]
87mod tests {
88    use super::TimeOutput;
89
90    #[test]
91    fn as_time_format() {
92        let pairs = vec![
93            (5_u64, "0:00:05"),
94            (60_u64, "0:01:00"),
95            (154_u64, "0:02:34"),
96            (3603_u64, "1:00:03"),
97        ];
98        for (input, output) in pairs {
99            assert_eq!(input.as_time().as_str(), output);
100        }
101    }
102}