Skip to main content

retroglyph_widgets/widget/
meter.rs

1//! [`Meter`]: a load ratio mapped to a green→yellow→red color.
2use retroglyph_core::Color;
3
4/// A load ratio in `0.0..=1.0`, mapped to a green→yellow→red color ramp.
5///
6/// Low load is green, mid load yellow, high load red. Values outside the
7/// range are clamped. Delegates to [`Color::lerp`] (backed by `gem`) rather
8/// than hand-rolling RGB interpolation.
9///
10/// Not a drawing widget: there's no [`Terminal`](retroglyph_core::Terminal)
11/// involved, just a ratio-to-color mapping, but kept as its own small
12/// struct rather than a free function so [`Gauge`](super::Gauge),
13/// [`StatBar`](super::StatBar), and [`Sparkline`](super::Sparkline) share
14/// one place that owns the ramp.
15///
16/// # Examples
17///
18/// ```
19/// use retroglyph_widgets::Meter;
20///
21/// let meter = Meter::new(0.9);
22/// assert_ne!(meter.color(), Meter::new(0.1).color());
23/// ```
24#[derive(Clone, Copy, Debug, PartialEq)]
25pub struct Meter {
26    ratio: f32,
27}
28
29impl Meter {
30    const GREEN: Color = Color::Rgb {
31        r: 80,
32        g: 200,
33        b: 120,
34    };
35    const YELLOW: Color = Color::Rgb {
36        r: 220,
37        g: 200,
38        b: 90,
39    };
40    const RED: Color = Color::Rgb {
41        r: 220,
42        g: 90,
43        b: 90,
44    };
45
46    /// A meter reading `ratio` (clamped to `0.0..=1.0` when colored).
47    #[must_use]
48    pub const fn new(ratio: f32) -> Self {
49        Self { ratio }
50    }
51
52    /// The ramped color for this meter's ratio.
53    #[must_use]
54    pub fn color(self) -> Color {
55        let t = self.ratio.clamp(0.0, 1.0);
56        if t < 0.5 {
57            Color::lerp(Self::GREEN, Self::YELLOW, t * 2.0)
58        } else {
59            Color::lerp(Self::YELLOW, Self::RED, (t - 0.5) * 2.0)
60        }
61    }
62}
63
64#[cfg(test)]
65mod tests {
66    use super::*;
67
68    #[test]
69    fn low_load_is_green() {
70        assert_eq!(Meter::new(0.0).color(), Meter::GREEN);
71    }
72
73    #[test]
74    fn mid_load_is_yellow() {
75        assert_eq!(Meter::new(0.5).color(), Meter::YELLOW);
76    }
77
78    #[test]
79    fn high_load_is_red() {
80        assert_eq!(Meter::new(1.0).color(), Meter::RED);
81    }
82
83    #[test]
84    fn out_of_range_ratios_are_clamped() {
85        assert_eq!(Meter::new(-1.0).color(), Meter::GREEN);
86        assert_eq!(Meter::new(2.0).color(), Meter::RED);
87    }
88}