//! How numbers, durations and times are written on the page. use sccache_dash_api::Range; /// How a comparison with the period before is worded, from the range's own /// label: "previous 24 hours". pub fn previous_label(range: Range) -> String { let label = range.label(); format!("previous {}", label.strip_prefix("last ").unwrap_or(label)) } /// Whole-number percentages of `parts` that add up to exactly 100, giving the /// leftovers of rounding to the largest shares. All zero when nothing is counted. pub fn shares(parts: &[u64]) -> Vec { let total: u64 = parts.iter().sum(); if total == 0 { return vec![0; parts.len()]; } let exact: Vec = parts .iter() .map(|part| 100.0 * *part as f64 / total as f64) .collect(); let mut whole: Vec = exact.iter().map(|value| value.floor() as u64).collect(); let mut left = 100 - whole.iter().sum::(); let mut by_fraction: Vec = (0..parts.len()).collect(); by_fraction.sort_by(|a, b| exact[*b].fract().total_cmp(&exact[*a].fract())); for index in by_fraction { if left == 0 { break; } whole[index] += 1; left -= 1; } whole } /// How the refresh control names an interval: "Every 10 s", or "Off". pub fn refresh_label(secs: u64) -> String { if secs == 0 { "Off".into() } else { format!("Every {secs} s") } } /// A count with thousands separators: 2815 becomes "2,815". pub fn count(n: u64) -> String { let digits = n.to_string(); let first = (digits.len() - 1) % 3 + 1; let mut out = String::with_capacity(digits.len() + digits.len() / 3); out.push_str(&digits[..first]); for (index, digit) in digits[first..].chars().enumerate() { if index % 3 == 0 { out.push(','); } out.push(digit); } out } /// A ratio as whole percent: 0.456 becomes "46%"; "—" when there is no ratio. pub fn percent(ratio: Option) -> String { ratio.map_or_else(|| "—".into(), |ratio| format!("{:.0}%", ratio * 100.0)) } /// `part` of `whole` as whole percent; "—" when `whole` is zero. pub fn share(part: u64, whole: u64) -> String { percent((whole > 0).then(|| part as f64 / whole as f64)) } /// Seconds the short way: "0.7 ms", "8.1 s", "3m 05s", "3h 05m", "2d 3h". pub fn duration(seconds: f64) -> String { if !seconds.is_finite() { return "—".into(); } let seconds = seconds.max(0.0); if seconds < 1.0 { return format!("{:.1} ms", seconds * 1000.0); } let tenths = (seconds * 10.0).round() as u64; let (whole, tenth) = (tenths / 10, tenths % 10); if whole < 60 { return format!("{whole}.{tenth} s"); } let (minutes, second) = (whole / 60, whole % 60); if minutes < 60 { return format!("{minutes}m {second:02}s"); } let (hours, minute) = (minutes / 60, minutes % 60); if hours < 24 { return format!("{hours}h {minute:02}m"); } let (days, hour) = (hours / 24, hours % 24); format!("{days}d {hour}h") } /// A multiple in round numbers: 11432.7 becomes "11,000", 7.42 becomes "7.4". pub fn round_number(n: f64) -> String { if !n.is_finite() || n <= 0.0 { return "—".into(); } if n < 10.0 { return format!("{n:.1}"); } let round_to = if n >= 1000.0 { 100.0 } else if n >= 100.0 { 10.0 } else { 1.0 }; count((n / round_to).round() as u64 * round_to as u64) } /// A size in bytes the way file managers show it: "10.0 GB". pub fn bytes(n: u64) -> String { const K: f64 = 1024.0; let (value, unit) = match n as f64 { value if value < K => return format!("{n} B"), value if value < K * K => (value / K, "KB"), value if value < K * K * K => (value / (K * K), "MB"), value if value < K * K * K * K => (value / (K * K * K), "GB"), value => (value / (K * K * K * K), "TB"), }; format!("{value:.1} {unit}") } /// Seconds to add to a Unix time to get the clock time of this computer. /// The browser knows its time zone; a native window would need to find it another way. pub fn local_offset() -> i64 { #[cfg(target_arch = "wasm32")] { // `get_timezone_offset` is minutes to add to local time to get UTC. -(js_sys::Date::new_0().get_timezone_offset() as i64) * 60 } #[cfg(not(target_arch = "wasm32"))] { 0 } } /// A moment as month, day and clock time. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct Moment { pub month: u32, pub day: u32, pub hour: u32, pub minute: u32, } /// The moment `unix` seconds after 1 January 1970. pub fn moment(unix: i64) -> Moment { let days = unix.div_euclid(86_400); let secs_of_day = unix.rem_euclid(86_400); // Howard Hinnant's civil-from-days. let z = days + 719_468; let day_of_era = z.rem_euclid(146_097); let year_of_era = (day_of_era - day_of_era / 1460 + day_of_era / 36_524 - day_of_era / 146_096) / 365; let day_of_year = day_of_era - (365 * year_of_era + year_of_era / 4 - year_of_era / 100); let mp = (5 * day_of_year + 2) / 153; let day = day_of_year - (153 * mp + 2) / 5 + 1; let month = if mp < 10 { mp + 3 } else { mp - 9 }; Moment { month: month as u32, day: day as u32, hour: (secs_of_day / 3600) as u32, minute: (secs_of_day % 3600 / 60) as u32, } } impl Moment { /// "14:05" pub fn clock(self) -> String { format!("{:02}:{:02}", self.hour, self.minute) } /// "Nov 12" pub fn date(self) -> String { const MONTHS: [&str; 12] = [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", ]; let month = MONTHS[(self.month.clamp(1, 12) - 1) as usize]; format!("{month} {}", self.day) } } /// "Nov 12, 14:05" for a moment given in Unix seconds. pub fn moment_text(unix: i64) -> String { let moment = moment(unix); format!("{}, {}", moment.date(), moment.clock()) } /// Spacing of the ticks on a time axis that long, in seconds: whole minutes, /// hours or days, giving about four to eight ticks. pub fn tick_step(span_secs: f64) -> i64 { const STEPS: [i64; 14] = [ 60, 120, 300, 600, 900, 1800, 3600, 7200, 10_800, 21_600, 43_200, 86_400, 172_800, 604_800, ]; STEPS .into_iter() .find(|step| span_secs / *step as f64 <= 7.5) .unwrap_or(604_800) } /// The label for one tick of a time axis: the clock time, or the date for /// ticks that fall on midnight or are a day or more apart. pub fn tick_label(unix: i64, step: i64) -> String { let moment = moment(unix); if step >= 86_400 || unix.rem_euclid(86_400) == 0 { moment.date() } else { moment.clock() } } /// What is hidden after the "All languages" box changes: ticked shows every /// language, cleared hides them all. pub fn hidden_after_all<'a>(ticked: bool, languages: impl Iterator) -> Vec { if ticked { Vec::new() } else { languages.map(str::to_owned).collect() } } #[cfg(test)] mod tests { use super::*; #[test] fn counts_have_thousands_separators() { assert_eq!(count(0), "0"); assert_eq!(count(325), "325"); assert_eq!(count(2815), "2,815"); assert_eq!(count(123_456), "123,456"); assert_eq!(count(1_234_567_890), "1,234,567,890"); } #[test] fn durations_are_short_and_round_cleanly() { assert_eq!(duration(0.0007), "0.7 ms"); assert_eq!(duration(0.0), "0.0 ms"); assert_eq!(duration(8.14), "8.1 s"); assert_eq!(duration(59.96), "1m 00s"); assert_eq!(duration(185.0), "3m 05s"); assert_eq!(duration(11_100.0), "3h 05m"); assert_eq!(duration(183_600.0), "2d 3h"); assert_eq!(duration(f64::NAN), "—"); } #[test] fn moments_match_the_calendar() { assert_eq!( moment(0), Moment { month: 1, day: 1, hour: 0, minute: 0 } ); // 1,700,000,000 is 14 November 2023, 22:13:20 UTC. assert_eq!(moment_text(1_700_000_000), "Nov 14, 22:13"); // Day 95 after the epoch is 6 April 1970. assert_eq!(moment_text(95 * 86_400 + 12 * 3600), "Apr 6, 12:00"); } #[test] fn numbers_are_round_and_ticked() { assert_eq!(round_number(11_432.7), "11,400"); assert_eq!(round_number(7.42), "7.4"); assert_eq!(bytes(10 * 1024 * 1024 * 1024), "10.0 GB"); assert_eq!(tick_step(3660.0), 600); assert_eq!(tick_step(86_640.0), 21_600); assert_eq!(tick_label(43_200, 600), "12:00"); assert_eq!(tick_label(86_400, 600), "Jan 2"); } #[test] fn shares_add_up_to_one_hundred() { assert_eq!(shares(&[50, 33, 17]), [50, 33, 17]); assert_eq!(shares(&[1, 1, 1]), [34, 33, 33]); assert_eq!(shares(&[7351, 0, 0, 0, 0]), [100, 0, 0, 0, 0]); assert_eq!(shares(&[0, 0]), [0, 0]); let parts = [3254, 3256, 829, 14, 13]; assert_eq!(shares(&parts).iter().sum::(), 100); } #[test] fn all_languages_box_turns_them_back_on() { let names = ["Rust", "C/C++"]; assert_eq!(hidden_after_all(true, names.into_iter()), Vec::::new()); assert_eq!(hidden_after_all(false, names.into_iter()), vec!["Rust", "C/C++"]); } }