Skip to main content

oomtop_core/
measured.rs

1//! Helpers for [`Measured<T>`] and [`Quality`] (SPEC ยง5: every number carries source + quality).
2
3use crate::model::{Measured, Quality};
4
5impl Quality {
6    /// Severity order used when combining values: exact < estimate < unavailable.
7    pub fn rank(&self) -> u8 {
8        match self {
9            Quality::Exact => 0,
10            Quality::Estimate => 1,
11            Quality::Unavailable(_) => 2,
12        }
13    }
14
15    pub fn is_available(&self) -> bool {
16        !matches!(self, Quality::Unavailable(_))
17    }
18
19    /// The weaker of two qualities (estimate beats exact; unavailable beats both).
20    pub fn worst(self, other: Quality) -> Quality {
21        if other.rank() > self.rank() {
22            other
23        } else {
24            self
25        }
26    }
27
28    /// Short label for UI/exports: "exact", "est.", "n/a".
29    pub fn short_label(&self) -> &'static str {
30        match self {
31            Quality::Exact => "exact",
32            Quality::Estimate => "est.",
33            Quality::Unavailable(_) => "n/a",
34        }
35    }
36}
37
38impl<T> Measured<T> {
39    pub fn exact(value: T, source: impl Into<String>) -> Self {
40        Measured {
41            value: Some(value),
42            source: source.into(),
43            quality: Quality::Exact,
44        }
45    }
46
47    pub fn estimate(value: T, source: impl Into<String>) -> Self {
48        Measured {
49            value: Some(value),
50            source: source.into(),
51            quality: Quality::Estimate,
52        }
53    }
54
55    pub fn unavailable(source: impl Into<String>, reason: impl Into<String>) -> Self {
56        Measured {
57            value: None,
58            source: source.into(),
59            quality: Quality::Unavailable(reason.into()),
60        }
61    }
62
63    /// Value, if available.
64    pub fn get(&self) -> Option<&T> {
65        self.value.as_ref()
66    }
67
68    pub fn is_available(&self) -> bool {
69        self.value.is_some() && self.quality.is_available()
70    }
71
72    pub fn map<U>(self, f: impl FnOnce(T) -> U) -> Measured<U> {
73        Measured {
74            value: self.value.map(f),
75            source: self.source,
76            quality: self.quality,
77        }
78    }
79
80    /// Downgrades quality to `Estimate` (keeps `Unavailable`).
81    pub fn into_estimate(mut self) -> Self {
82        if self.quality == Quality::Exact {
83            self.quality = Quality::Estimate;
84        }
85        self
86    }
87
88    /// Reason text when unavailable.
89    pub fn unavailable_reason(&self) -> Option<&str> {
90        match &self.quality {
91            Quality::Unavailable(r) => Some(r.as_str()),
92            _ => None,
93        }
94    }
95}
96
97impl<T: Copy> Measured<T> {
98    pub fn value_or(&self, default: T) -> T {
99        self.value.unwrap_or(default)
100    }
101
102    /// The value only when the quality is not `Unavailable` (guards against inconsistent inputs such as
103    /// `value: Some(_)` with `quality: unavailable`, which must never be used as a number).
104    pub fn usable(&self) -> Option<T> {
105        self.value.filter(|_| self.quality.is_available())
106    }
107}
108
109/// Sums byte values. The result is available if at least one input is; quality is the worst of the
110/// available inputs, and becomes `Estimate` if some inputs were unavailable (partial sum).
111pub fn sum_bytes<'a>(items: impl IntoIterator<Item = &'a Measured<u64>>, source: &str) -> Measured<u64> {
112    let mut total: u64 = 0;
113    let mut any = false;
114    let mut missing = false;
115    let mut quality = Quality::Exact;
116    let mut reason = String::from("no inputs");
117    for m in items {
118        match (&m.value, &m.quality) {
119            (Some(v), q) if q.is_available() => {
120                total = total.saturating_add(*v);
121                any = true;
122                quality = quality.worst(q.clone());
123            }
124            (_, Quality::Unavailable(r)) => {
125                missing = true;
126                reason = r.clone();
127            }
128            _ => missing = true,
129        }
130    }
131    if !any {
132        return Measured::unavailable(source, reason);
133    }
134    if missing {
135        quality = quality.worst(Quality::Estimate);
136    }
137    Measured {
138        value: Some(total),
139        source: source.to_string(),
140        quality,
141    }
142}
143
144/// Sums f64 values with the same rules as [`sum_bytes`].
145pub fn sum_f64<'a>(items: impl IntoIterator<Item = &'a Measured<f64>>, source: &str) -> Measured<f64> {
146    let mut total = 0.0;
147    let mut any = false;
148    let mut missing = false;
149    let mut quality = Quality::Exact;
150    for m in items {
151        match m.value {
152            Some(v) if m.quality.is_available() => {
153                total += v;
154                any = true;
155                quality = quality.worst(m.quality.clone());
156            }
157            _ => missing = true,
158        }
159    }
160    if !any {
161        return Measured::unavailable(source, "no inputs");
162    }
163    if missing {
164        quality = quality.worst(Quality::Estimate);
165    }
166    Measured {
167        value: Some(total),
168        source: source.to_string(),
169        quality,
170    }
171}
172
173#[cfg(test)]
174mod tests {
175    use super::*;
176
177    #[test]
178    fn sum_quality_rules() {
179        let a = Measured::exact(10u64, "a");
180        let b = Measured::estimate(5u64, "b");
181        let c: Measured<u64> = Measured::unavailable("c", "needs root");
182        let s = sum_bytes([&a, &b], "sum");
183        assert_eq!(s.value, Some(15));
184        assert_eq!(s.quality, Quality::Estimate);
185        let s = sum_bytes([&a, &c], "sum");
186        assert_eq!(s.value, Some(10));
187        assert_eq!(s.quality, Quality::Estimate);
188        let s = sum_bytes([&c], "sum");
189        assert_eq!(s.value, None);
190        assert_eq!(s.unavailable_reason(), Some("needs root"));
191        let s = sum_bytes([&a, &a], "sum");
192        assert_eq!(s.quality, Quality::Exact);
193    }
194
195    #[test]
196    fn usable_requires_available_quality() {
197        assert_eq!(Measured::exact(3u64, "a").usable(), Some(3));
198        let inconsistent = Measured {
199            value: Some(3u64),
200            source: "x".into(),
201            quality: Quality::Unavailable("stale".into()),
202        };
203        assert_eq!(inconsistent.usable(), None);
204        assert!(!inconsistent.is_available());
205        assert_eq!(Measured::estimate(1.5f64, "b").map(|v| v * 2.0).value, Some(3.0));
206        assert_eq!(
207            Measured::exact(1u8, "c").into_estimate().quality,
208            Quality::Estimate
209        );
210        let u: Measured<u8> = Measured::unavailable("d", "needs root");
211        assert_eq!(u.into_estimate().unavailable_reason(), Some("needs root"));
212    }
213
214    #[test]
215    fn worst_quality() {
216        assert_eq!(Quality::Exact.worst(Quality::Estimate), Quality::Estimate);
217        assert_eq!(Quality::Estimate.worst(Quality::Exact), Quality::Estimate);
218    }
219}