gnostr_asyncgit/
progress.rs

1//!
2
3use std::cmp;
4
5use easy_cast::{Conv, ConvFloat};
6
7///
8#[derive(Clone, Copy, Default, Debug, PartialEq, Eq)]
9pub struct ProgressPercent {
10    /// percent 0..100
11    pub progress: u8,
12}
13
14impl ProgressPercent {
15    ///
16    pub fn new(current: usize, total: usize) -> Self {
17        let total = f64::conv(cmp::max(current, total));
18        let progress = f64::conv(current) / total * 100.0;
19        let progress = u8::try_conv_nearest(progress).unwrap_or(100);
20        Self { progress }
21    }
22    ///
23    pub const fn empty() -> Self {
24        Self { progress: 0 }
25    }
26    ///
27    pub const fn full() -> Self {
28        Self { progress: 100 }
29    }
30}
31
32#[cfg(test)]
33mod tests {
34    use super::*;
35
36    #[test]
37    fn test_progress_zero_total() {
38        let prog = ProgressPercent::new(1, 0);
39
40        assert_eq!(prog.progress, 100);
41    }
42
43    #[test]
44    fn test_progress_zero_all() {
45        let prog = ProgressPercent::new(0, 0);
46        assert_eq!(prog.progress, 100);
47    }
48
49    #[test]
50    fn test_progress_rounding() {
51        let prog = ProgressPercent::new(2, 10);
52
53        assert_eq!(prog.progress, 20);
54    }
55}