rsv_lib/utils/
progress.rs

1use std::io;
2use std::io::Write;
3use std::time::Instant;
4
5use super::constants::{GB_F64, KB_F64, MB_F64};
6
7pub struct Progress {
8    pub chunks: usize,
9    pub bytes: usize,
10    pub lines: usize,
11    pub print_count: usize,
12    start_time: Instant,
13}
14
15impl Progress {
16    pub fn new() -> Self {
17        Progress {
18            chunks: 0,
19            bytes: 0,
20            lines: 0,
21            print_count: 0,
22            start_time: Instant::now(),
23        }
24    }
25
26    pub fn add_chunks(&mut self, n: usize) {
27        self.chunks += n;
28    }
29
30    pub fn add_bytes(&mut self, n: usize) {
31        self.bytes += n;
32    }
33
34    pub fn add_lines(&mut self, n: usize) {
35        self.lines += n;
36    }
37
38    pub fn info(&self) -> String {
39        let bytes = self.bytes as f64;
40        if bytes < MB_F64 {
41            format!("{:.2}KB", bytes / KB_F64)
42        } else if bytes < GB_F64 {
43            format!("{:.2}MB", bytes / MB_F64)
44        } else {
45            format!("{:.2}GB", bytes / GB_F64)
46        }
47    }
48
49    pub fn elapsed_time_as_string(&self) -> String {
50        let t = self.start_time.elapsed().as_secs_f64();
51        if t < 60.0 {
52            format!("{} seconds", t as usize)
53        } else {
54            format!("{:.2} minutes", t / 60.0)
55        }
56    }
57
58    pub fn print(&mut self) {
59        // must have the suffix space, otherwise current line cannot be cleaned completely
60        print!(
61            "\rchunk: {}, total processed: {}, elapsed time: {}         ",
62            self.chunks,
63            self.info(),
64            self.elapsed_time_as_string()
65        );
66        io::stdout().flush().unwrap();
67
68        self.print_count += 1;
69    }
70
71    pub fn clear(&mut self) {
72        // must have the suffix space, otherwise current line cannot be cleaned completely
73        print!("\r");
74        print!("{}", " ".repeat(60));
75        print!("\r");
76        io::stdout().flush().unwrap();
77
78        self.print_count += 1;
79    }
80
81    pub fn print_elapsed_time(&mut self) {
82        println!("elapsed time: {}     ", self.elapsed_time_as_string());
83        io::stdout().flush().unwrap();
84
85        self.print_count += 1;
86    }
87}