Skip to main content

bbm/compare/
threshold.rs

1// Copyright (c) 2023-2026 Tim Oliver Rabl
2//
3// Permission is hereby granted, free of charge, to any person obtaining a copy
4// of this software and associated documentation files (the "Software"), to deal
5// in the Software without restriction, including without limitation the rights
6// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7// copies of the Software, and to permit persons to whom the Software is
8// furnished to do so, subject to the following conditions:
9//
10// The above copyright notice and this permission notice shall be included in
11// all copies or substantial portions of the Software.
12//
13// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
19// SOFTWARE.
20
21use serde::Serialize;
22
23/// Format kbit/s as human-readable Mbit/s.
24fn fmt_mbps(kbps: f64) -> String {
25    format!("{:.1} Mbit/s", kbps / 1000.0)
26}
27
28#[derive(Debug, Clone, Serialize)]
29pub struct ThresholdResult {
30    pub check: String,
31    pub threshold_kbps: Option<f64>,
32    pub threshold_display: Option<String>,
33    pub measured_kbps: f64,
34    pub measured_display: String,
35    pub met: bool,
36    pub percent: f64,
37}
38
39impl ThresholdResult {
40    /// Compare a measured value against an optional threshold.
41    pub fn check(label: &str, measured: f64, threshold: Option<f64>) -> Self {
42        match threshold {
43            Some(t) => {
44                let met = measured >= t;
45                let pct = if t > 0.0 {
46                    (measured / t * 100.0).round()
47                } else {
48                    100.0
49                };
50                Self {
51                    check: label.into(),
52                    threshold_kbps: Some(t),
53                    threshold_display: Some(fmt_mbps(t)),
54                    measured_kbps: measured,
55                    measured_display: fmt_mbps(measured),
56                    met,
57                    percent: pct,
58                }
59            }
60            None => Self {
61                check: label.into(),
62                threshold_kbps: None,
63                threshold_display: None,
64                measured_kbps: measured,
65                measured_display: fmt_mbps(measured),
66                met: true,
67                percent: 0.0,
68            },
69        }
70    }
71}