use super::super::model::byte_size;
use serde_json::{Number, Value};
fn is_bytes(unit: Option<&str>) -> bool {
unit.map(str::trim).is_some_and(|u| {
u == "B" || u.eq_ignore_ascii_case("byte") || u.eq_ignore_ascii_case("bytes")
})
}
fn label(n: &Number) -> String {
if let Some(bytes) = n.as_u64() {
return byte_size(bytes);
}
if let Some(bytes) = n.as_i64() {
return format!("-{}", byte_size(bytes.unsigned_abs()));
}
let v = n.as_f64().expect("finite JSON number");
if v.abs() < 1_000.0 && v.fract() != 0.0 {
return format!("{n} B");
}
if v.abs() < u64::MAX as f64 {
let sign = if v < 0.0 { "-" } else { "" };
return format!("{sign}{}", byte_size(v.abs() as u64));
}
let mut scaled = v / 1e18;
let mut unit = "EB";
for next in ["ZB", "YB", "RB", "QB"] {
if scaled.abs() < 999.5 {
break;
}
scaled /= 1_000.0;
unit = next;
}
if scaled.abs() >= 1_000.0 {
return format!("{scaled:.2e} {unit}");
}
let precision = 10_f64.powi(2 - scaled.abs().log10().floor() as i32);
format!("{} {unit}", (scaled * precision).round() / precision)
}
pub(super) fn value(unit: Option<&str>, value: &Value) -> Option<String> {
if !is_bytes(unit) {
return None;
}
value.as_number().map(label)
}
pub(super) fn range<'a>(
unit: Option<&str>,
values: impl Iterator<Item = &'a Value> + Clone,
) -> Option<String> {
if !is_bytes(unit) {
return None;
}
let numbers = values.filter_map(Value::as_number);
let compare = |a: &&Number, b: &&Number| {
let x = a.as_f64().expect("finite JSON number");
let y = b.as_f64().expect("finite JSON number");
x.total_cmp(&y).then_with(|| {
a.as_i128()
.unwrap_or(x as i128)
.cmp(&b.as_i128().unwrap_or(y as i128))
})
};
let lo = numbers.clone().min_by(compare)?;
let hi = numbers.max_by(compare)?;
Some(format!("{} to {}", label(lo), label(hi)))
}