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, Text};
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<Text>) -> 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<Text>) -> 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<Text>, reason: impl Into<Text>) -> Self {
56        Measured {
57            value: None,
58            source: source.into(),
59            quality: Quality::Unavailable(reason.into()),
60        }
61    }
62
63    /// The unavailability reason as shared text (no copy for a literal), or `fallback` when the value is
64    /// available or has no reason: for carrying a reason into a derived value.
65    pub fn reason_or(&self, fallback: &'static str) -> Text {
66        match &self.quality {
67            Quality::Unavailable(r) => r.clone(),
68            _ => fallback.into(),
69        }
70    }
71
72    /// Value, if available.
73    pub fn get(&self) -> Option<&T> {
74        self.value.as_ref()
75    }
76
77    pub fn is_available(&self) -> bool {
78        self.value.is_some() && self.quality.is_available()
79    }
80
81    pub fn map<U>(self, f: impl FnOnce(T) -> U) -> Measured<U> {
82        Measured {
83            value: self.value.map(f),
84            source: self.source,
85            quality: self.quality,
86        }
87    }
88
89    /// Downgrades quality to `Estimate` (keeps `Unavailable`).
90    pub fn into_estimate(mut self) -> Self {
91        if self.quality == Quality::Exact {
92            self.quality = Quality::Estimate;
93        }
94        self
95    }
96
97    /// Reason text when unavailable.
98    pub fn unavailable_reason(&self) -> Option<&str> {
99        match &self.quality {
100            Quality::Unavailable(r) => Some(r),
101            _ => None,
102        }
103    }
104}
105
106impl<T: Copy> Measured<T> {
107    pub fn value_or(&self, default: T) -> T {
108        self.value.unwrap_or(default)
109    }
110
111    /// The value only when the quality is not `Unavailable` (guards against inconsistent inputs such as
112    /// `value: Some(_)` with `quality: unavailable`, which must never be used as a number).
113    pub fn usable(&self) -> Option<T> {
114        self.value.filter(|_| self.quality.is_available())
115    }
116}
117
118/// Sums byte values. The result is available if at least one input is; quality is the worst of the
119/// available inputs, and becomes `Estimate` if some inputs were unavailable (partial sum).
120pub fn sum_bytes<'a>(
121    items: impl IntoIterator<Item = &'a Measured<u64>>,
122    source: &'static str,
123) -> Measured<u64> {
124    let mut total: u64 = 0;
125    let mut any = false;
126    let mut missing = false;
127    let mut quality = Quality::Exact;
128    let mut reason: Text = "no inputs".into();
129    for m in items {
130        match (&m.value, &m.quality) {
131            (Some(v), q) if q.is_available() => {
132                total = total.saturating_add(*v);
133                any = true;
134                quality = quality.worst(q.clone());
135            }
136            (_, Quality::Unavailable(r)) => {
137                missing = true;
138                reason = r.clone();
139            }
140            _ => missing = true,
141        }
142    }
143    if !any {
144        return Measured::unavailable(source, reason);
145    }
146    if missing {
147        quality = quality.worst(Quality::Estimate);
148    }
149    Measured {
150        value: Some(total),
151        source: source.into(),
152        quality,
153    }
154}
155
156/// Sums f64 values with the same rules as [`sum_bytes`].
157pub fn sum_f64<'a>(
158    items: impl IntoIterator<Item = &'a Measured<f64>>,
159    source: &'static str,
160) -> Measured<f64> {
161    let mut total = 0.0;
162    let mut any = false;
163    let mut missing = false;
164    let mut quality = Quality::Exact;
165    for m in items {
166        match m.value {
167            Some(v) if m.quality.is_available() => {
168                total += v;
169                any = true;
170                quality = quality.worst(m.quality.clone());
171            }
172            _ => missing = true,
173        }
174    }
175    if !any {
176        return Measured::unavailable(source, "no inputs");
177    }
178    if missing {
179        quality = quality.worst(Quality::Estimate);
180    }
181    Measured {
182        value: Some(total),
183        source: source.into(),
184        quality,
185    }
186}
187
188#[cfg(test)]
189mod tests {
190    use super::*;
191
192    #[test]
193    fn sum_quality_rules() {
194        let a = Measured::exact(10u64, "a");
195        let b = Measured::estimate(5u64, "b");
196        let c: Measured<u64> = Measured::unavailable("c", "needs root");
197        let s = sum_bytes([&a, &b], "sum");
198        assert_eq!(s.value, Some(15));
199        assert_eq!(s.quality, Quality::Estimate);
200        let s = sum_bytes([&a, &c], "sum");
201        assert_eq!(s.value, Some(10));
202        assert_eq!(s.quality, Quality::Estimate);
203        let s = sum_bytes([&c], "sum");
204        assert_eq!(s.value, None);
205        assert_eq!(s.unavailable_reason(), Some("needs root"));
206        let s = sum_bytes([&a, &a], "sum");
207        assert_eq!(s.quality, Quality::Exact);
208    }
209
210    #[test]
211    fn usable_requires_available_quality() {
212        assert_eq!(Measured::exact(3u64, "a").usable(), Some(3));
213        let inconsistent = Measured {
214            value: Some(3u64),
215            source: "x".into(),
216            quality: Quality::Unavailable("stale".into()),
217        };
218        assert_eq!(inconsistent.usable(), None);
219        assert!(!inconsistent.is_available());
220        assert_eq!(Measured::estimate(1.5f64, "b").map(|v| v * 2.0).value, Some(3.0));
221        assert_eq!(
222            Measured::exact(1u8, "c").into_estimate().quality,
223            Quality::Estimate
224        );
225        let u: Measured<u8> = Measured::unavailable("d", "needs root");
226        assert_eq!(u.into_estimate().unavailable_reason(), Some("needs root"));
227    }
228
229    #[test]
230    fn worst_quality() {
231        assert_eq!(Quality::Exact.worst(Quality::Estimate), Quality::Estimate);
232        assert_eq!(Quality::Estimate.worst(Quality::Exact), Quality::Estimate);
233    }
234}