Skip to main content

asyncgit/
progress.rs

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