parallel_disk_usage/visualizer/
proportion_bar.rs

1use super::BarAlignment;
2use derive_more::{AsRef, Deref, Display, From, Into};
3use fmt_iter::repeat;
4use std::fmt::{Display, Error, Formatter};
5
6/// Block of proportion bar.
7#[derive(Debug, Clone, Copy, PartialEq, Eq, AsRef, Deref, Display, Into)]
8pub struct ProportionBarBlock(char);
9
10macro_rules! make_const {
11    ($name:ident = $content:literal) => {
12        pub const $name: ProportionBarBlock = ProportionBarBlock($content);
13    };
14}
15
16make_const!(LEVEL0_BLOCK = '█');
17make_const!(LEVEL1_BLOCK = '▓');
18make_const!(LEVEL2_BLOCK = '▒');
19make_const!(LEVEL3_BLOCK = '░');
20make_const!(LEVEL4_BLOCK = ' ');
21
22/// Proportion bar.
23#[derive(Debug, Clone, Copy, PartialEq, Eq, From, Into)]
24pub struct ProportionBar {
25    pub level0: usize,
26    pub level1: usize,
27    pub level2: usize,
28    pub level3: usize,
29    pub level4: usize,
30}
31
32impl ProportionBar {
33    #[inline]
34    fn display_level0(self) -> impl Display {
35        repeat(LEVEL0_BLOCK, self.level0)
36    }
37
38    #[inline]
39    fn display_level1(self) -> impl Display {
40        repeat(LEVEL1_BLOCK, self.level1)
41    }
42
43    #[inline]
44    fn display_level2(self) -> impl Display {
45        repeat(LEVEL2_BLOCK, self.level2)
46    }
47
48    #[inline]
49    fn display_level3(self) -> impl Display {
50        repeat(LEVEL3_BLOCK, self.level3)
51    }
52
53    #[inline]
54    fn display_level4(self) -> impl Display {
55        repeat(LEVEL4_BLOCK, self.level4)
56    }
57
58    /// Create a [displayable](Display) value.
59    #[inline]
60    pub fn display(self, align: BarAlignment) -> ProportionBarDisplay {
61        ProportionBarDisplay { bar: self, align }
62    }
63}
64
65/// Result of [`ProportionBar::display`].
66#[derive(Debug, Clone, Copy, PartialEq, Eq)]
67pub struct ProportionBarDisplay {
68    pub bar: ProportionBar,
69    pub align: BarAlignment,
70}
71
72impl Display for ProportionBarDisplay {
73    fn fmt(&self, formatter: &mut Formatter<'_>) -> Result<(), Error> {
74        let ProportionBarDisplay { bar, align } = self;
75        macro_rules! fmt {
76            ($pattern:literal) => {
77                write!(
78                    formatter,
79                    $pattern,
80                    level0 = bar.display_level0(),
81                    level1 = bar.display_level1(),
82                    level2 = bar.display_level2(),
83                    level3 = bar.display_level3(),
84                    level4 = bar.display_level4(),
85                )
86            };
87        }
88        match align {
89            BarAlignment::Left => fmt!("{level0}{level1}{level2}{level3}{level4}"),
90            BarAlignment::Right => fmt!("{level4}{level3}{level2}{level1}{level0}"),
91        }
92    }
93}