gent-link 0.2.19

Connect Codex and Claude Code chats across machines with the Gent CLI and desktop companion.
//! Format declared byte quantities in legacy widget text, using the original JSON numbers.
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");
    }
    // Above 999 B the shared formatter's rounding thresholds are whole bytes.
    // Truncating a fraction here preserves which side of the threshold it is on.
    if v.abs() < u64::MAX as f64 {
        let sign = if v < 0.0 { "-" } else { "" };
        return format!("{sign}{}", byte_size(v.abs() as u64));
    }

    // Chart values can exceed an integral byte counter. Continue the same SI
    // progression, using scientific notation past the largest SI prefix.
    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;
    }
    // Geometry uses f64. Resolve ties in the source integers so neighboring
    // large byte counts on opposite sides of a display threshold stay distinct.
    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)))
}