Skip to main content

sys_lib/
units.rs

1//! Value types: [`Bytes`] and [`Percent`].
2//!
3//! Both print themselves ("125.6 GiB", "32.8%") and expose exact values
4//! (`raw()`, `value()`). Formatting is deterministic, allocation-free, and for
5//! `Bytes` done entirely in integer arithmetic, so the output never depends on
6//! floating-point printing.
7
8use core::{
9    cmp::Ordering,
10    fmt::{self, Write as _},
11    hash::{Hash, Hasher},
12};
13
14use crate::fmt::{StackBuf, pad};
15
16/// A byte count: an exact `u64` inside, with a `Display` that picks the unit.
17///
18/// `{}` prints binary values with IEC labels (`125.6 GiB`), `{:#}` decimal
19/// values with SI labels (`134.9 GB`), and [`jedec`](Bytes::jedec) binary
20/// values with JEDEC labels (`125.6 GB`, what Windows Explorer shows). One
21/// decimal place by default with a trailing `.0` dropped; `{:.0}` to `{:.9}`
22/// are honoured, as are width, fill, and alignment. Values under 1 KiB print
23/// as integers. Rounding is half away from zero, and a value that rounds up to
24/// 1024 of a unit prints as 1 of the next.
25///
26/// # Examples
27///
28/// ```
29/// use sys_lib::Bytes;
30///
31/// let ram = Bytes::new(134_876_545_024);
32/// assert_eq!(ram.to_string(), "125.6 GiB");
33/// assert_eq!(format!("{ram:#}"), "134.9 GB");
34/// assert_eq!(ram.jedec().to_string(), "125.6 GB");
35/// assert_eq!(format!("{ram:.2}"), "125.61 GiB");
36/// assert_eq!(ram.raw(), 134_876_545_024);
37///
38/// assert_eq!(Bytes::new(512).to_string(), "512 B");
39/// assert_eq!(Bytes::from_gib(128).to_string(), "128 GiB");
40/// assert_eq!(Bytes::new(1_048_575).to_string(), "1 MiB");
41/// assert_eq!(Bytes::MAX.to_string(), "16 EiB");
42/// ```
43#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
44pub struct Bytes(u64);
45
46/// Which unit system [`Bytes::display`] uses.
47#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
48#[non_exhaustive]
49pub enum Units {
50    /// 1024-based, IEC labels: `KiB`, `MiB`, `GiB`.
51    Binary,
52    /// 1000-based, SI labels: `kB`, `MB`, `GB`.
53    Decimal,
54    /// 1024-based, JEDEC labels: `KB`, `MB`, `GB`.
55    Jedec,
56}
57
58const BINARY: [&str; 7] = ["B", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB"];
59const DECIMAL: [&str; 7] = ["B", "kB", "MB", "GB", "TB", "PB", "EB"];
60const JEDEC: [&str; 7] = ["B", "KB", "MB", "GB", "TB", "PB", "EB"];
61const MAX_PRECISION: usize = 9;
62
63impl Units {
64    const fn base(self) -> u128 {
65        match self {
66            Self::Decimal => 1000,
67            Self::Binary | Self::Jedec => 1024,
68        }
69    }
70
71    const fn labels(self) -> &'static [&'static str; 7] {
72        match self {
73            Self::Binary => &BINARY,
74            Self::Decimal => &DECIMAL,
75            Self::Jedec => &JEDEC,
76        }
77    }
78}
79
80impl Bytes {
81    /// Zero bytes.
82    pub const ZERO: Bytes = Bytes(0);
83    /// The largest count, `u64::MAX` bytes.
84    pub const MAX: Bytes = Bytes(u64::MAX);
85
86    /// A count of `bytes`.
87    #[must_use]
88    pub const fn new(bytes: u64) -> Bytes {
89        Bytes(bytes)
90    }
91
92    /// The exact number of bytes.
93    #[must_use]
94    pub const fn raw(self) -> u64 {
95        self.0
96    }
97
98    /// `n` KiB (1024 bytes each), saturating at [`Bytes::MAX`].
99    #[must_use]
100    pub const fn from_kib(n: u64) -> Bytes {
101        Bytes(n.saturating_mul(1 << 10))
102    }
103
104    /// `n` MiB, saturating at [`Bytes::MAX`].
105    #[must_use]
106    pub const fn from_mib(n: u64) -> Bytes {
107        Bytes(n.saturating_mul(1 << 20))
108    }
109
110    /// `n` GiB, saturating at [`Bytes::MAX`].
111    ///
112    /// ```
113    /// use sys_lib::Bytes;
114    /// assert_eq!(Bytes::from_gib(2).raw(), 2 * 1024 * 1024 * 1024);
115    /// assert_eq!(Bytes::from_gib(u64::MAX), Bytes::MAX);
116    /// ```
117    #[must_use]
118    pub const fn from_gib(n: u64) -> Bytes {
119        Bytes(n.saturating_mul(1 << 30))
120    }
121
122    /// `self + other`, saturating at [`Bytes::MAX`].
123    #[must_use]
124    pub const fn saturating_add(self, other: Bytes) -> Bytes {
125        Bytes(self.0.saturating_add(other.0))
126    }
127
128    /// `self - other`, saturating at zero.
129    #[must_use]
130    pub const fn saturating_sub(self, other: Bytes) -> Bytes {
131        Bytes(self.0.saturating_sub(other.0))
132    }
133
134    /// `self + other`, or `None` on overflow.
135    #[must_use]
136    pub const fn checked_add(self, other: Bytes) -> Option<Bytes> {
137        match self.0.checked_add(other.0) {
138            Some(v) => Some(Bytes(v)),
139            None => None,
140        }
141    }
142
143    /// `self - other`, or `None` when `other` is larger.
144    ///
145    /// ```
146    /// use sys_lib::Bytes;
147    /// assert_eq!(Bytes::new(5).checked_sub(Bytes::new(3)), Some(Bytes::new(2)));
148    /// assert_eq!(Bytes::new(3).checked_sub(Bytes::new(5)), None);
149    /// ```
150    #[must_use]
151    pub const fn checked_sub(self, other: Bytes) -> Option<Bytes> {
152        match self.0.checked_sub(other.0) {
153            Some(v) => Some(Bytes(v)),
154            None => None,
155        }
156    }
157
158    /// The share of `total` this is: 0% when `total` is zero, at most 100%.
159    ///
160    /// ```
161    /// use sys_lib::Bytes;
162    /// assert_eq!(Bytes::new(41).percent_of(Bytes::new(125)).to_string(), "32.8%");
163    /// ```
164    #[must_use]
165    pub fn percent_of(self, total: Bytes) -> Percent {
166        Percent::from_ratio(self.0, total.0)
167    }
168
169    /// Formats in the given unit system.
170    ///
171    /// ```
172    /// use sys_lib::{Bytes, Units};
173    /// assert_eq!(Bytes::new(1_500_000).display(Units::Decimal).to_string(), "1.5 MB");
174    /// ```
175    pub fn display(self, units: Units) -> impl fmt::Display {
176        Formatted { bytes: self, units }
177    }
178
179    /// Formats with binary values and IEC labels: `125.6 GiB`.
180    pub fn binary(self) -> impl fmt::Display {
181        self.display(Units::Binary)
182    }
183
184    /// Formats with decimal values and SI labels: `134.9 GB`.
185    pub fn decimal(self) -> impl fmt::Display {
186        self.display(Units::Decimal)
187    }
188
189    /// Formats with binary values and JEDEC labels: `125.6 GB`.
190    pub fn jedec(self) -> impl fmt::Display {
191        self.display(Units::Jedec)
192    }
193}
194
195impl From<u64> for Bytes {
196    fn from(bytes: u64) -> Self {
197        Bytes(bytes)
198    }
199}
200
201impl From<Bytes> for u64 {
202    fn from(bytes: Bytes) -> Self {
203        bytes.0
204    }
205}
206
207impl fmt::Display for Bytes {
208    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
209        let units = if f.alternate() {
210            Units::Decimal
211        } else {
212            Units::Binary
213        };
214        write_bytes(f, self.0, units)
215    }
216}
217
218impl fmt::Debug for Bytes {
219    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
220        write!(f, "Bytes({})", self.0)
221    }
222}
223
224struct Formatted {
225    bytes: Bytes,
226    units: Units,
227}
228
229impl fmt::Display for Formatted {
230    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
231        write_bytes(f, self.bytes.0, self.units)
232    }
233}
234
235/// The byte-count formatter, in integer arithmetic.
236fn write_bytes(f: &mut fmt::Formatter<'_>, value: u64, units: Units) -> fmt::Result {
237    let mut buf = StackBuf::<48>::new();
238    render_bytes(&mut buf, value, units, f.precision())?;
239    pad(f, buf.as_str())
240}
241
242pub(crate) fn render_bytes(
243    out: &mut impl fmt::Write,
244    value: u64,
245    units: Units,
246    precision: Option<usize>,
247) -> fmt::Result {
248    let base = units.base();
249    let labels = units.labels();
250    let v = u128::from(value);
251    if v < base {
252        return write!(out, "{value} {}", labels[0]);
253    }
254    let digits = precision.unwrap_or(1).min(MAX_PRECISION);
255    let scale = 10u128.pow(digits as u32);
256
257    // The largest unit for which the value is at least 1.
258    let mut index = 0;
259    let mut divisor = 1u128;
260    while index < labels.len() - 1 && v >= divisor * base {
261        divisor *= base;
262        index += 1;
263    }
264    let mut scaled = round_div(v * scale, divisor);
265    // A value that rounds up to `base` of a unit carries into the next unit.
266    if scaled >= base * scale && index < labels.len() - 1 {
267        divisor *= base;
268        index += 1;
269        scaled = round_div(v * scale, divisor);
270    }
271    let whole = scaled / scale;
272    let fraction = scaled % scale;
273    write!(out, "{whole}")?;
274    let keep_fraction = digits > 0 && (precision.is_some() || fraction != 0);
275    if keep_fraction {
276        write!(out, ".{fraction:0width$}", width = digits)?;
277    }
278    write!(out, " {}", labels[index])
279}
280
281/// `numerator / divisor`, rounded half away from zero (both are non-negative).
282const fn round_div(numerator: u128, divisor: u128) -> u128 {
283    (numerator + divisor / 2) / divisor
284}
285
286/// A share between 0 and 100 percent, never NaN.
287///
288/// Because the value is never NaN, `Percent` is `Eq`, `Ord`, and `Hash`, so it
289/// sorts and compares without surprises. `Display` prints one decimal place
290/// (`32.8%`) and honours a precision (`{:.0}` gives `33%`).
291///
292/// # Examples
293///
294/// ```
295/// use sys_lib::Percent;
296///
297/// let p = Percent::from_ratio(41, 125);
298/// assert_eq!(p.to_string(), "32.8%");
299/// assert_eq!(format!("{p:.0}"), "33%");
300/// assert_eq!(p.complement().to_string(), "67.2%");
301/// assert_eq!(Percent::from_ratio(5, 0), Percent::ZERO);
302/// assert_eq!(Percent::from_ratio(9, 4), Percent::FULL);
303/// assert_eq!(Percent::from_value(f32::NAN), Percent::ZERO);
304/// assert!(Percent::FULL > p);
305/// ```
306#[derive(Clone, Copy, Default)]
307pub struct Percent(f32);
308
309impl Percent {
310    /// 0%.
311    pub const ZERO: Percent = Percent(0.0);
312    /// 100%.
313    pub const FULL: Percent = Percent(100.0);
314
315    /// `part` as a share of `whole`, exact to 0.1%: clamped to 100%, and 0% when
316    /// `whole` is zero.
317    #[must_use]
318    pub fn from_ratio(part: u64, whole: u64) -> Percent {
319        if whole == 0 {
320            return Percent::ZERO;
321        }
322        let tenths = round_div(u128::from(part) * 1000, u128::from(whole)).min(1000);
323        // At most 1000, so the conversion is exact.
324        Percent(tenths as f32 / 10.0)
325    }
326
327    /// `value` percent, clamped to 0..=100; NaN gives 0%.
328    #[must_use]
329    pub fn from_value(value: f32) -> Percent {
330        if value.is_nan() {
331            Percent::ZERO
332        } else {
333            // `+ 0.0` turns -0.0 into 0.0, so equal values have equal bits.
334            Percent(value.clamp(0.0, 100.0) + 0.0)
335        }
336    }
337
338    /// The value, 0.0 to 100.0.
339    #[must_use]
340    pub fn value(self) -> f32 {
341        self.0
342    }
343
344    /// The value as a fraction, 0.0 to 1.0.
345    #[must_use]
346    pub fn fraction(self) -> f32 {
347        self.0 / 100.0
348    }
349
350    /// 100% minus this.
351    #[must_use]
352    pub fn complement(self) -> Percent {
353        Percent::from_value(100.0 - self.0)
354    }
355}
356
357impl PartialEq for Percent {
358    fn eq(&self, other: &Self) -> bool {
359        self.0.to_bits() == other.0.to_bits()
360    }
361}
362
363impl Eq for Percent {}
364
365impl PartialOrd for Percent {
366    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
367        Some(self.cmp(other))
368    }
369}
370
371impl Ord for Percent {
372    fn cmp(&self, other: &Self) -> Ordering {
373        self.0.total_cmp(&other.0)
374    }
375}
376
377impl Hash for Percent {
378    fn hash<H: Hasher>(&self, state: &mut H) {
379        self.0.to_bits().hash(state);
380    }
381}
382
383impl fmt::Display for Percent {
384    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
385        let digits = f.precision().unwrap_or(1).min(MAX_PRECISION);
386        let mut buf = StackBuf::<24>::new();
387        write!(buf, "{:.*}%", digits, self.0)?;
388        pad(f, buf.as_str())
389    }
390}
391
392impl fmt::Debug for Percent {
393    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
394        write!(f, "Percent({})", self.0)
395    }
396}
397
398#[cfg(test)]
399mod tests {
400    use proptest::prelude::*;
401
402    use super::*;
403
404    #[test]
405    fn test_bytes_display_examples_from_the_api() {
406        let ram = Bytes::new(134_876_545_024);
407        assert_eq!(ram.to_string(), "125.6 GiB");
408        assert_eq!(format!("{ram:#}"), "134.9 GB");
409        assert_eq!(ram.jedec().to_string(), "125.6 GB");
410        assert_eq!(format!("{ram:.2}"), "125.61 GiB");
411        assert_eq!(format!("{ram:.0}"), "126 GiB");
412    }
413
414    #[test]
415    fn test_bytes_display_under_one_kib_is_an_integer() {
416        assert_eq!(Bytes::new(0).to_string(), "0 B");
417        assert_eq!(Bytes::new(1).to_string(), "1 B");
418        assert_eq!(Bytes::new(1023).to_string(), "1023 B");
419        assert_eq!(format!("{:.3}", Bytes::new(512)), "512 B");
420        assert_eq!(format!("{:#}", Bytes::new(999)), "999 B");
421    }
422
423    #[test]
424    fn test_bytes_display_unit_boundaries() {
425        assert_eq!(Bytes::new(1024).to_string(), "1 KiB");
426        assert_eq!(Bytes::new(1536).to_string(), "1.5 KiB");
427        assert_eq!(format!("{:#}", Bytes::new(1000)), "1 kB");
428        assert_eq!(Bytes::from_mib(1).to_string(), "1 MiB");
429        assert_eq!(Bytes::from_gib(128).to_string(), "128 GiB");
430        assert_eq!(Bytes::new(137_331_519_488).to_string(), "127.9 GiB");
431    }
432
433    #[test]
434    fn test_bytes_display_1023_99_kib_carries_to_1_mib() {
435        assert_eq!(Bytes::new(1_048_575).to_string(), "1 MiB");
436        assert_eq!(Bytes::new(1_048_524).to_string(), "1023.9 KiB");
437        assert_eq!(format!("{:.2}", Bytes::new(1_048_575)), "1.00 MiB");
438    }
439
440    #[test]
441    fn test_bytes_display_maximum() {
442        assert_eq!(Bytes::MAX.to_string(), "16 EiB");
443        assert_eq!(format!("{:#}", Bytes::MAX), "18.4 EB");
444        assert_eq!(format!("{:.9}", Bytes::MAX), "16.000000000 EiB");
445    }
446
447    #[test]
448    fn test_bytes_display_precision_capped_at_nine() {
449        assert_eq!(format!("{:.30}", Bytes::from_kib(1)), "1.000000000 KiB");
450    }
451
452    #[test]
453    fn test_bytes_display_width_and_alignment() {
454        assert_eq!(format!("{:>10}|", Bytes::from_kib(2)), "     2 KiB|");
455        assert_eq!(format!("{:<10}|", Bytes::from_kib(2)), "2 KiB     |");
456        assert_eq!(format!("{:^9}|", Bytes::new(5)), "   5 B   |");
457    }
458
459    #[test]
460    fn test_bytes_debug_is_exact() {
461        assert_eq!(
462            format!("{:?}", Bytes::new(134_876_545_024)),
463            "Bytes(134876545024)"
464        );
465    }
466
467    #[test]
468    fn test_bytes_arithmetic_saturates_and_checks() {
469        assert_eq!(Bytes::MAX.saturating_add(Bytes::new(1)), Bytes::MAX);
470        assert_eq!(Bytes::ZERO.saturating_sub(Bytes::new(1)), Bytes::ZERO);
471        assert_eq!(Bytes::MAX.checked_add(Bytes::new(1)), None);
472        assert_eq!(Bytes::from_kib(u64::MAX), Bytes::MAX);
473        assert_eq!(Bytes::from_mib(u64::MAX), Bytes::MAX);
474        assert_eq!(u64::from(Bytes::from(7_u64)), 7);
475    }
476
477    #[test]
478    fn test_percent_from_ratio_examples() {
479        assert_eq!(Percent::from_ratio(41, 125).to_string(), "32.8%");
480        assert_eq!(Percent::from_ratio(0, 7).to_string(), "0.0%");
481        assert_eq!(Percent::from_ratio(7, 7), Percent::FULL);
482        assert_eq!(Percent::from_ratio(1, 3).to_string(), "33.3%");
483        assert_eq!(Percent::from_ratio(2, 3).to_string(), "66.7%");
484        assert_eq!(Percent::from_ratio(u64::MAX, u64::MAX), Percent::FULL);
485        assert_eq!(Percent::from_ratio(u64::MAX, 1), Percent::FULL);
486        assert_eq!(Percent::from_ratio(1, 0), Percent::ZERO);
487    }
488
489    #[test]
490    fn test_percent_from_value_clamps_and_rejects_nan() {
491        assert_eq!(Percent::from_value(-5.0), Percent::ZERO);
492        assert_eq!(Percent::from_value(250.0), Percent::FULL);
493        assert_eq!(Percent::from_value(f32::NAN), Percent::ZERO);
494        assert_eq!(Percent::from_value(f32::INFINITY), Percent::FULL);
495        assert_eq!(Percent::from_value(-0.0), Percent::ZERO);
496    }
497
498    #[test]
499    fn test_percent_display_precision_and_padding() {
500        let p = Percent::from_ratio(41, 125);
501        assert_eq!(format!("{p:.0}"), "33%");
502        assert_eq!(format!("{p:.2}"), "32.80%");
503        assert_eq!(format!("{p:>7}"), "  32.8%");
504        assert_eq!(format!("{p:?}"), "Percent(32.8)");
505        assert!((p.fraction() - 0.328).abs() < 1e-6);
506        assert_eq!(p.complement().to_string(), "67.2%");
507    }
508
509    /// Parses the number in front of the unit of a formatted `Bytes`.
510    fn parse_display(s: &str) -> (f64, &str) {
511        let (num, unit) = s.split_once(' ').unwrap();
512        (num.parse().unwrap(), unit)
513    }
514
515    proptest! {
516        #[test]
517        fn prop_bytes_display_round_trips_within_rounding(v in any::<u64>()) {
518            for (units, base) in [(Units::Binary, 1024f64), (Units::Decimal, 1000f64)] {
519                let s = Bytes::new(v).display(units).to_string();
520                let (num, unit) = parse_display(&s);
521                let index = units.labels().iter().position(|&l| l == unit).unwrap();
522                prop_assert!(num < base || index == 6, "{s} should have carried");
523                let back = num * base.powi(index as i32);
524                // One decimal place: within half a tenth of the unit.
525                let tolerance = 0.05 * base.powi(index as i32) + 0.5;
526                prop_assert!((back - v as f64).abs() <= tolerance, "{v} -> {s}");
527            }
528        }
529
530        #[test]
531        fn prop_bytes_order_matches_raw(a in any::<u64>(), b in any::<u64>()) {
532            prop_assert_eq!(Bytes::new(a).cmp(&Bytes::new(b)), a.cmp(&b));
533        }
534
535        #[test]
536        fn prop_percent_always_in_range(part in any::<u64>(), whole in any::<u64>(), v in any::<f32>()) {
537            for p in [Percent::from_ratio(part, whole), Percent::from_value(v)] {
538                prop_assert!(!p.value().is_nan());
539                prop_assert!((0.0..=100.0).contains(&p.value()));
540                prop_assert!((0.0..=100.0).contains(&p.complement().value()));
541            }
542        }
543
544        #[test]
545        fn prop_percent_eq_matches_hash(a in any::<f32>(), b in any::<f32>()) {
546            use std::collections::hash_map::DefaultHasher;
547            let (pa, pb) = (Percent::from_value(a), Percent::from_value(b));
548            let hash = |p: Percent| { let mut h = DefaultHasher::new(); p.hash(&mut h); h.finish() };
549            if pa == pb { prop_assert_eq!(hash(pa), hash(pb)); }
550            prop_assert_eq!(pa == pb, pa.cmp(&pb) == Ordering::Equal);
551        }
552    }
553}