Skip to main content

sys_lib/
units.rs

1//! Value types: [`Bytes`], [`Percent`], [`Rate`], and [`Mhz`].
2//!
3//! Each prints itself ("125.6 GiB", "32.8%", "12.5 MiB/s", "5.7 GHz") and
4//! exposes its exact value (`raw()`, `value()`, `bytes_per_sec()`). Formatting
5//! is deterministic, allocation-free, and for `Bytes`, `Rate`, and `Mhz` done
6//! entirely in integer arithmetic, so the output never depends on
7//! floating-point printing.
8
9use core::{
10    cmp::Ordering,
11    fmt::{self, Write as _},
12    hash::{Hash, Hasher},
13    time::Duration,
14};
15
16use crate::fmt::{StackBuf, pad};
17
18/// A byte count: an exact `u64` inside, with a `Display` that picks the unit.
19///
20/// `{}` prints binary values with IEC labels (`125.6 GiB`), `{:#}` decimal
21/// values with SI labels (`134.9 GB`), and [`jedec`](Bytes::jedec) binary
22/// values with JEDEC labels (`125.6 GB`, what Windows Explorer shows). One
23/// decimal place by default with a trailing `.0` dropped; `{:.0}` to `{:.9}`
24/// are honoured, as are width, fill, and alignment. Values under 1 KiB print
25/// as integers. Rounding is half away from zero, and a value that rounds up to
26/// 1024 of a unit prints as 1 of the next.
27///
28/// # Examples
29///
30/// ```
31/// use sys_lib::Bytes;
32///
33/// let ram = Bytes::new(134_876_545_024);
34/// assert_eq!(ram.to_string(), "125.6 GiB");
35/// assert_eq!(format!("{ram:#}"), "134.9 GB");
36/// assert_eq!(ram.jedec().to_string(), "125.6 GB");
37/// assert_eq!(format!("{ram:.2}"), "125.61 GiB");
38/// assert_eq!(ram.raw(), 134_876_545_024);
39///
40/// assert_eq!(Bytes::new(512).to_string(), "512 B");
41/// assert_eq!(Bytes::from_gib(128).to_string(), "128 GiB");
42/// assert_eq!(Bytes::new(1_048_575).to_string(), "1 MiB");
43/// assert_eq!(Bytes::MAX.to_string(), "16 EiB");
44/// ```
45#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
46pub struct Bytes(u64);
47
48/// Which unit system [`Bytes::display`] uses.
49#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
50#[non_exhaustive]
51pub enum Units {
52    /// 1024-based, IEC labels: `KiB`, `MiB`, `GiB`.
53    Binary,
54    /// 1000-based, SI labels: `kB`, `MB`, `GB`.
55    Decimal,
56    /// 1024-based, JEDEC labels: `KB`, `MB`, `GB`.
57    Jedec,
58}
59
60const BINARY: [&str; 7] = ["B", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB"];
61const DECIMAL: [&str; 7] = ["B", "kB", "MB", "GB", "TB", "PB", "EB"];
62const JEDEC: [&str; 7] = ["B", "KB", "MB", "GB", "TB", "PB", "EB"];
63const BITS: [&str; 7] = ["bit", "kbit", "Mbit", "Gbit", "Tbit", "Pbit", "Ebit"];
64const MAX_PRECISION: usize = 9;
65
66impl Units {
67    const fn base(self) -> u128 {
68        match self {
69            Self::Decimal => 1000,
70            Self::Binary | Self::Jedec => 1024,
71        }
72    }
73
74    const fn labels(self) -> &'static [&'static str; 7] {
75        match self {
76            Self::Binary => &BINARY,
77            Self::Decimal => &DECIMAL,
78            Self::Jedec => &JEDEC,
79        }
80    }
81}
82
83impl Bytes {
84    /// Zero bytes.
85    pub const ZERO: Bytes = Bytes(0);
86    /// The largest count, `u64::MAX` bytes.
87    pub const MAX: Bytes = Bytes(u64::MAX);
88
89    /// A count of `bytes`.
90    #[must_use]
91    pub const fn new(bytes: u64) -> Bytes {
92        Bytes(bytes)
93    }
94
95    /// The exact number of bytes.
96    #[must_use]
97    pub const fn raw(self) -> u64 {
98        self.0
99    }
100
101    /// `n` KiB (1024 bytes each), saturating at [`Bytes::MAX`].
102    #[must_use]
103    pub const fn from_kib(n: u64) -> Bytes {
104        Bytes(n.saturating_mul(1 << 10))
105    }
106
107    /// `n` MiB, saturating at [`Bytes::MAX`].
108    #[must_use]
109    pub const fn from_mib(n: u64) -> Bytes {
110        Bytes(n.saturating_mul(1 << 20))
111    }
112
113    /// `n` GiB, saturating at [`Bytes::MAX`].
114    ///
115    /// ```
116    /// use sys_lib::Bytes;
117    /// assert_eq!(Bytes::from_gib(2).raw(), 2 * 1024 * 1024 * 1024);
118    /// assert_eq!(Bytes::from_gib(u64::MAX), Bytes::MAX);
119    /// ```
120    #[must_use]
121    pub const fn from_gib(n: u64) -> Bytes {
122        Bytes(n.saturating_mul(1 << 30))
123    }
124
125    /// `self + other`, saturating at [`Bytes::MAX`].
126    #[must_use]
127    pub const fn saturating_add(self, other: Bytes) -> Bytes {
128        Bytes(self.0.saturating_add(other.0))
129    }
130
131    /// `self - other`, saturating at zero.
132    #[must_use]
133    pub const fn saturating_sub(self, other: Bytes) -> Bytes {
134        Bytes(self.0.saturating_sub(other.0))
135    }
136
137    /// `self + other`, or `None` on overflow.
138    #[must_use]
139    pub const fn checked_add(self, other: Bytes) -> Option<Bytes> {
140        match self.0.checked_add(other.0) {
141            Some(v) => Some(Bytes(v)),
142            None => None,
143        }
144    }
145
146    /// `self - other`, or `None` when `other` is larger.
147    ///
148    /// ```
149    /// use sys_lib::Bytes;
150    /// assert_eq!(Bytes::new(5).checked_sub(Bytes::new(3)), Some(Bytes::new(2)));
151    /// assert_eq!(Bytes::new(3).checked_sub(Bytes::new(5)), None);
152    /// ```
153    #[must_use]
154    pub const fn checked_sub(self, other: Bytes) -> Option<Bytes> {
155        match self.0.checked_sub(other.0) {
156            Some(v) => Some(Bytes(v)),
157            None => None,
158        }
159    }
160
161    /// The share of `total` this is: 0% when `total` is zero, at most 100%.
162    ///
163    /// ```
164    /// use sys_lib::Bytes;
165    /// assert_eq!(Bytes::new(41).percent_of(Bytes::new(125)).to_string(), "32.8%");
166    /// ```
167    #[must_use]
168    pub fn percent_of(self, total: Bytes) -> Percent {
169        Percent::from_ratio(self.0, total.0)
170    }
171
172    /// Formats in the given unit system.
173    ///
174    /// ```
175    /// use sys_lib::{Bytes, Units};
176    /// assert_eq!(Bytes::new(1_500_000).display(Units::Decimal).to_string(), "1.5 MB");
177    /// ```
178    pub fn display(self, units: Units) -> impl fmt::Display {
179        Formatted { bytes: self, units }
180    }
181
182    /// Formats with binary values and IEC labels: `125.6 GiB`.
183    pub fn binary(self) -> impl fmt::Display {
184        self.display(Units::Binary)
185    }
186
187    /// Formats with decimal values and SI labels: `134.9 GB`.
188    pub fn decimal(self) -> impl fmt::Display {
189        self.display(Units::Decimal)
190    }
191
192    /// Formats with binary values and JEDEC labels: `125.6 GB`.
193    pub fn jedec(self) -> impl fmt::Display {
194        self.display(Units::Jedec)
195    }
196}
197
198impl From<u64> for Bytes {
199    fn from(bytes: u64) -> Self {
200        Bytes(bytes)
201    }
202}
203
204impl From<Bytes> for u64 {
205    fn from(bytes: Bytes) -> Self {
206        bytes.0
207    }
208}
209
210impl fmt::Display for Bytes {
211    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
212        let units = if f.alternate() {
213            Units::Decimal
214        } else {
215            Units::Binary
216        };
217        write_bytes(f, self.0, units)
218    }
219}
220
221impl fmt::Debug for Bytes {
222    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
223        write!(f, "Bytes({})", self.0)
224    }
225}
226
227struct Formatted {
228    bytes: Bytes,
229    units: Units,
230}
231
232impl fmt::Display for Formatted {
233    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
234        write_bytes(f, self.bytes.0, self.units)
235    }
236}
237
238/// The byte-count formatter, in integer arithmetic.
239fn write_bytes(f: &mut fmt::Formatter<'_>, value: u64, units: Units) -> fmt::Result {
240    let mut buf = StackBuf::<48>::new();
241    render_bytes(&mut buf, value, units, f.precision())?;
242    pad(f, buf.as_str())
243}
244
245pub(crate) fn render_bytes(
246    out: &mut impl fmt::Write,
247    value: u64,
248    units: Units,
249    precision: Option<usize>,
250) -> fmt::Result {
251    render_scaled(out, value, units.base(), units.labels(), precision, "")
252}
253
254/// `value` in the largest of `labels` (each `base` times the last) for which
255/// it is at least 1, with `suffix` after the label.
256fn render_scaled(
257    out: &mut impl fmt::Write,
258    value: u64,
259    base: u128,
260    labels: &[&str; 7],
261    precision: Option<usize>,
262    suffix: &str,
263) -> fmt::Result {
264    let v = u128::from(value);
265    if v < base {
266        return write!(out, "{value} {}{suffix}", labels[0]);
267    }
268    let digits = precision.unwrap_or(1).min(MAX_PRECISION);
269    let scale = 10u128.pow(digits as u32);
270
271    // The largest unit for which the value is at least 1.
272    let mut index = 0;
273    let mut divisor = 1u128;
274    while index < labels.len() - 1 && v >= divisor * base {
275        divisor *= base;
276        index += 1;
277    }
278    let mut scaled = round_div(v * scale, divisor);
279    // A value that rounds up to `base` of a unit carries into the next unit.
280    if scaled >= base * scale && index < labels.len() - 1 {
281        divisor *= base;
282        index += 1;
283        scaled = round_div(v * scale, divisor);
284    }
285    let whole = scaled / scale;
286    let fraction = scaled % scale;
287    write!(out, "{whole}")?;
288    let keep_fraction = digits > 0 && (precision.is_some() || fraction != 0);
289    if keep_fraction {
290        write!(out, ".{fraction:0width$}", width = digits)?;
291    }
292    write!(out, " {}{suffix}", labels[index])
293}
294
295/// A transfer rate in bytes per second, for network download and upload and
296/// disk read and write.
297///
298/// `{}` prints like [`Bytes`] with `/s` (`12.5 MiB/s`), `{:#}` in decimal
299/// units (`13.1 MB/s`), and [`bits`](Rate::bits) the bit rate network links
300/// are sold in (`104.9 Mbit/s`). The same precision, width, and rounding rules
301/// as `Bytes` apply.
302///
303/// ```
304/// use sys_lib::Rate;
305///
306/// let r = Rate::from_bytes_per_sec(13_107_200);
307/// assert_eq!(r.to_string(), "12.5 MiB/s");
308/// assert_eq!(format!("{r:#}"), "13.1 MB/s");
309/// assert_eq!(r.bits().to_string(), "104.9 Mbit/s");
310/// assert_eq!(Rate::ZERO.to_string(), "0 B/s");
311/// ```
312#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
313pub struct Rate(u64);
314
315impl Rate {
316    /// Nothing moving.
317    pub const ZERO: Rate = Rate(0);
318
319    /// `n` bytes per second.
320    #[must_use]
321    pub const fn from_bytes_per_sec(n: u64) -> Rate {
322        Rate(n)
323    }
324
325    /// The rate in bytes per second.
326    #[must_use]
327    pub const fn bytes_per_sec(self) -> u64 {
328        self.0
329    }
330
331    /// The rate in bits per second, saturating at `u64::MAX`.
332    #[must_use]
333    pub const fn bits_per_sec(self) -> u64 {
334        self.0.saturating_mul(8)
335    }
336
337    /// `bytes` moved over `interval`, rounded to the nearest byte per second;
338    /// zero for an empty interval, saturating at `u64::MAX`.
339    ///
340    /// ```
341    /// use std::time::Duration;
342    /// use sys_lib::{Bytes, Rate};
343    ///
344    /// let r = Rate::per(Bytes::from_mib(25), Duration::from_secs(2));
345    /// assert_eq!(r.to_string(), "12.5 MiB/s");
346    /// assert_eq!(Rate::per(Bytes::new(5), Duration::ZERO), Rate::ZERO);
347    /// ```
348    #[must_use]
349    pub fn per(bytes: Bytes, interval: Duration) -> Rate {
350        Rate::from_delta(bytes.raw(), interval)
351    }
352
353    /// `delta` bytes over `interval`, in integer arithmetic.
354    pub(crate) fn from_delta(delta: u64, interval: Duration) -> Rate {
355        let nanos = interval.as_nanos();
356        if nanos == 0 {
357            return Rate::ZERO;
358        }
359        let per_sec = round_div(u128::from(delta) * 1_000_000_000, nanos);
360        Rate(u64::try_from(per_sec).unwrap_or(u64::MAX))
361    }
362
363    /// Formats the bit rate with SI labels: `104.9 Mbit/s`.
364    pub fn bits(self) -> impl fmt::Display {
365        RateBits(self)
366    }
367}
368
369impl fmt::Display for Rate {
370    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
371        let units = if f.alternate() {
372            Units::Decimal
373        } else {
374            Units::Binary
375        };
376        let mut buf = StackBuf::<48>::new();
377        render_scaled(
378            &mut buf,
379            self.0,
380            units.base(),
381            units.labels(),
382            f.precision(),
383            "/s",
384        )?;
385        pad(f, buf.as_str())
386    }
387}
388
389impl fmt::Debug for Rate {
390    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
391        write!(f, "Rate({}/s)", self.0)
392    }
393}
394
395struct RateBits(Rate);
396
397impl fmt::Display for RateBits {
398    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
399        let mut buf = StackBuf::<48>::new();
400        render_scaled(
401            &mut buf,
402            self.0.bits_per_sec(),
403            1000,
404            &BITS,
405            f.precision(),
406            "/s",
407        )?;
408        pad(f, buf.as_str())
409    }
410}
411
412/// A clock frequency in megahertz.
413///
414/// Prints `GHz` with one decimal place at or above 1000 MHz (`5.7 GHz`,
415/// `3.0 GHz`) and whole `MHz` below (`800 MHz`).
416///
417/// ```
418/// use sys_lib::Mhz;
419///
420/// assert_eq!(Mhz(5_700).to_string(), "5.7 GHz");
421/// assert_eq!(Mhz(3_000).to_string(), "3.0 GHz");
422/// assert_eq!(Mhz(800).to_string(), "800 MHz");
423/// ```
424#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
425pub struct Mhz(pub u32);
426
427impl fmt::Display for Mhz {
428    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
429        let mut buf = StackBuf::<24>::new();
430        if self.0 >= 1000 {
431            let tenths = (u64::from(self.0) + 50) / 100;
432            write!(buf, "{}.{} GHz", tenths / 10, tenths % 10)?;
433        } else {
434            write!(buf, "{} MHz", self.0)?;
435        }
436        pad(f, buf.as_str())
437    }
438}
439
440/// `numerator / divisor`, rounded half away from zero (both are non-negative).
441const fn round_div(numerator: u128, divisor: u128) -> u128 {
442    (numerator + divisor / 2) / divisor
443}
444
445/// A share between 0 and 100 percent, never NaN.
446///
447/// Because the value is never NaN, `Percent` is `Eq`, `Ord`, and `Hash`, so it
448/// sorts and compares without surprises. `Display` prints one decimal place
449/// (`32.8%`) and honours a precision (`{:.0}` gives `33%`).
450///
451/// # Examples
452///
453/// ```
454/// use sys_lib::Percent;
455///
456/// let p = Percent::from_ratio(41, 125);
457/// assert_eq!(p.to_string(), "32.8%");
458/// assert_eq!(format!("{p:.0}"), "33%");
459/// assert_eq!(p.complement().to_string(), "67.2%");
460/// assert_eq!(Percent::from_ratio(5, 0), Percent::ZERO);
461/// assert_eq!(Percent::from_ratio(9, 4), Percent::FULL);
462/// assert_eq!(Percent::from_value(f32::NAN), Percent::ZERO);
463/// assert!(Percent::FULL > p);
464/// ```
465#[derive(Clone, Copy, Default)]
466pub struct Percent(f32);
467
468impl Percent {
469    /// 0%.
470    pub const ZERO: Percent = Percent(0.0);
471    /// 100%.
472    pub const FULL: Percent = Percent(100.0);
473
474    /// `part` as a share of `whole`, exact to 0.1%: clamped to 100%, and 0% when
475    /// `whole` is zero.
476    #[must_use]
477    pub fn from_ratio(part: u64, whole: u64) -> Percent {
478        if whole == 0 {
479            return Percent::ZERO;
480        }
481        let tenths = round_div(u128::from(part) * 1000, u128::from(whole)).min(1000);
482        // At most 1000, so the conversion is exact.
483        Percent(tenths as f32 / 10.0)
484    }
485
486    /// `part` of `whole` for wide counters (nanoseconds of CPU time).
487    pub(crate) fn from_ratio_u128(part: u128, whole: u128) -> Percent {
488        if whole == 0 {
489            return Percent::ZERO;
490        }
491        let tenths = round_div(part.saturating_mul(1000), whole).min(1000);
492        Percent(tenths as f32 / 10.0)
493    }
494
495    /// `value` percent, clamped to 0..=100; NaN gives 0%.
496    #[must_use]
497    pub fn from_value(value: f32) -> Percent {
498        if value.is_nan() {
499            Percent::ZERO
500        } else {
501            // `+ 0.0` turns -0.0 into 0.0, so equal values have equal bits.
502            Percent(value.clamp(0.0, 100.0) + 0.0)
503        }
504    }
505
506    /// The value, 0.0 to 100.0.
507    #[must_use]
508    pub fn value(self) -> f32 {
509        self.0
510    }
511
512    /// The value as a fraction, 0.0 to 1.0.
513    #[must_use]
514    pub fn fraction(self) -> f32 {
515        self.0 / 100.0
516    }
517
518    /// 100% minus this.
519    #[must_use]
520    pub fn complement(self) -> Percent {
521        Percent::from_value(100.0 - self.0)
522    }
523}
524
525impl PartialEq for Percent {
526    fn eq(&self, other: &Self) -> bool {
527        self.0.to_bits() == other.0.to_bits()
528    }
529}
530
531impl Eq for Percent {}
532
533impl PartialOrd for Percent {
534    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
535        Some(self.cmp(other))
536    }
537}
538
539impl Ord for Percent {
540    fn cmp(&self, other: &Self) -> Ordering {
541        self.0.total_cmp(&other.0)
542    }
543}
544
545impl Hash for Percent {
546    fn hash<H: Hasher>(&self, state: &mut H) {
547        self.0.to_bits().hash(state);
548    }
549}
550
551impl fmt::Display for Percent {
552    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
553        let digits = f.precision().unwrap_or(1).min(MAX_PRECISION);
554        let mut buf = StackBuf::<24>::new();
555        write!(buf, "{:.*}%", digits, self.0)?;
556        pad(f, buf.as_str())
557    }
558}
559
560impl fmt::Debug for Percent {
561    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
562        write!(f, "Percent({})", self.0)
563    }
564}
565
566#[cfg(test)]
567mod tests {
568    use proptest::prelude::*;
569
570    use super::*;
571
572    #[test]
573    fn test_rate_display_and_bits() {
574        let r = Rate::from_bytes_per_sec(13_107_200);
575        assert_eq!(r.to_string(), "12.5 MiB/s");
576        assert_eq!(format!("{r:#}"), "13.1 MB/s");
577        assert_eq!(r.bits().to_string(), "104.9 Mbit/s");
578        assert_eq!(format!("{:.2}", r.bits()), "104.86 Mbit/s");
579        assert_eq!(format!("{r:?}"), "Rate(13107200/s)");
580        assert_eq!(
581            Rate::from_bytes_per_sec(100).bits().to_string(),
582            "800 bit/s"
583        );
584        assert_eq!(Rate::from_bytes_per_sec(u64::MAX).bits_per_sec(), u64::MAX);
585        assert_eq!(format!("{:>12}", Rate::ZERO), "       0 B/s");
586    }
587
588    #[test]
589    fn test_rate_from_delta_rounds_and_saturates() {
590        assert_eq!(
591            Rate::from_delta(1000, Duration::from_millis(500)).bytes_per_sec(),
592            2000
593        );
594        assert_eq!(
595            Rate::from_delta(1, Duration::from_secs(3)).bytes_per_sec(),
596            0
597        );
598        assert_eq!(
599            Rate::from_delta(2, Duration::from_secs(3)).bytes_per_sec(),
600            1
601        );
602        assert_eq!(
603            Rate::from_delta(u64::MAX, Duration::from_nanos(1)),
604            Rate(u64::MAX)
605        );
606        assert_eq!(Rate::from_delta(7, Duration::ZERO), Rate::ZERO);
607    }
608
609    #[test]
610    fn test_mhz_display() {
611        assert_eq!(Mhz(5_700).to_string(), "5.7 GHz");
612        assert_eq!(Mhz(999).to_string(), "999 MHz");
613        assert_eq!(Mhz(1_000).to_string(), "1.0 GHz");
614        assert_eq!(Mhz(2_449).to_string(), "2.4 GHz");
615        assert_eq!(Mhz(2_450).to_string(), "2.5 GHz");
616        assert_eq!(Mhz(u32::MAX).to_string(), "4294967.3 GHz");
617        assert_eq!(Mhz(0).to_string(), "0 MHz");
618    }
619
620    #[test]
621    fn test_bytes_display_examples_from_the_api() {
622        let ram = Bytes::new(134_876_545_024);
623        assert_eq!(ram.to_string(), "125.6 GiB");
624        assert_eq!(format!("{ram:#}"), "134.9 GB");
625        assert_eq!(ram.jedec().to_string(), "125.6 GB");
626        assert_eq!(format!("{ram:.2}"), "125.61 GiB");
627        assert_eq!(format!("{ram:.0}"), "126 GiB");
628    }
629
630    #[test]
631    fn test_bytes_display_under_one_kib_is_an_integer() {
632        assert_eq!(Bytes::new(0).to_string(), "0 B");
633        assert_eq!(Bytes::new(1).to_string(), "1 B");
634        assert_eq!(Bytes::new(1023).to_string(), "1023 B");
635        assert_eq!(format!("{:.3}", Bytes::new(512)), "512 B");
636        assert_eq!(format!("{:#}", Bytes::new(999)), "999 B");
637    }
638
639    #[test]
640    fn test_bytes_display_unit_boundaries() {
641        assert_eq!(Bytes::new(1024).to_string(), "1 KiB");
642        assert_eq!(Bytes::new(1536).to_string(), "1.5 KiB");
643        assert_eq!(format!("{:#}", Bytes::new(1000)), "1 kB");
644        assert_eq!(Bytes::from_mib(1).to_string(), "1 MiB");
645        assert_eq!(Bytes::from_gib(128).to_string(), "128 GiB");
646        assert_eq!(Bytes::new(137_331_519_488).to_string(), "127.9 GiB");
647    }
648
649    #[test]
650    fn test_bytes_display_1023_99_kib_carries_to_1_mib() {
651        assert_eq!(Bytes::new(1_048_575).to_string(), "1 MiB");
652        assert_eq!(Bytes::new(1_048_524).to_string(), "1023.9 KiB");
653        assert_eq!(format!("{:.2}", Bytes::new(1_048_575)), "1.00 MiB");
654    }
655
656    #[test]
657    fn test_bytes_display_maximum() {
658        assert_eq!(Bytes::MAX.to_string(), "16 EiB");
659        assert_eq!(format!("{:#}", Bytes::MAX), "18.4 EB");
660        assert_eq!(format!("{:.9}", Bytes::MAX), "16.000000000 EiB");
661    }
662
663    #[test]
664    fn test_bytes_display_precision_capped_at_nine() {
665        assert_eq!(format!("{:.30}", Bytes::from_kib(1)), "1.000000000 KiB");
666    }
667
668    #[test]
669    fn test_bytes_display_width_and_alignment() {
670        assert_eq!(format!("{:>10}|", Bytes::from_kib(2)), "     2 KiB|");
671        assert_eq!(format!("{:<10}|", Bytes::from_kib(2)), "2 KiB     |");
672        assert_eq!(format!("{:^9}|", Bytes::new(5)), "   5 B   |");
673    }
674
675    #[test]
676    fn test_bytes_debug_is_exact() {
677        assert_eq!(
678            format!("{:?}", Bytes::new(134_876_545_024)),
679            "Bytes(134876545024)"
680        );
681    }
682
683    #[test]
684    fn test_bytes_arithmetic_saturates_and_checks() {
685        assert_eq!(Bytes::MAX.saturating_add(Bytes::new(1)), Bytes::MAX);
686        assert_eq!(Bytes::ZERO.saturating_sub(Bytes::new(1)), Bytes::ZERO);
687        assert_eq!(Bytes::MAX.checked_add(Bytes::new(1)), None);
688        assert_eq!(Bytes::from_kib(u64::MAX), Bytes::MAX);
689        assert_eq!(Bytes::from_mib(u64::MAX), Bytes::MAX);
690        assert_eq!(u64::from(Bytes::from(7_u64)), 7);
691    }
692
693    #[test]
694    fn test_percent_from_ratio_examples() {
695        assert_eq!(Percent::from_ratio(41, 125).to_string(), "32.8%");
696        assert_eq!(Percent::from_ratio(0, 7).to_string(), "0.0%");
697        assert_eq!(Percent::from_ratio(7, 7), Percent::FULL);
698        assert_eq!(Percent::from_ratio(1, 3).to_string(), "33.3%");
699        assert_eq!(Percent::from_ratio(2, 3).to_string(), "66.7%");
700        assert_eq!(Percent::from_ratio(u64::MAX, u64::MAX), Percent::FULL);
701        assert_eq!(Percent::from_ratio(u64::MAX, 1), Percent::FULL);
702        assert_eq!(Percent::from_ratio(1, 0), Percent::ZERO);
703    }
704
705    #[test]
706    fn test_percent_from_value_clamps_and_rejects_nan() {
707        assert_eq!(Percent::from_value(-5.0), Percent::ZERO);
708        assert_eq!(Percent::from_value(250.0), Percent::FULL);
709        assert_eq!(Percent::from_value(f32::NAN), Percent::ZERO);
710        assert_eq!(Percent::from_value(f32::INFINITY), Percent::FULL);
711        assert_eq!(Percent::from_value(-0.0), Percent::ZERO);
712    }
713
714    #[test]
715    fn test_percent_display_precision_and_padding() {
716        let p = Percent::from_ratio(41, 125);
717        assert_eq!(format!("{p:.0}"), "33%");
718        assert_eq!(format!("{p:.2}"), "32.80%");
719        assert_eq!(format!("{p:>7}"), "  32.8%");
720        assert_eq!(format!("{p:?}"), "Percent(32.8)");
721        assert!((p.fraction() - 0.328).abs() < 1e-6);
722        assert_eq!(p.complement().to_string(), "67.2%");
723    }
724
725    /// Parses the number in front of the unit of a formatted `Bytes`.
726    fn parse_display(s: &str) -> (f64, &str) {
727        let (num, unit) = s.split_once(' ').unwrap();
728        (num.parse().unwrap(), unit)
729    }
730
731    proptest! {
732        #[test]
733        fn prop_bytes_display_round_trips_within_rounding(v in any::<u64>()) {
734            for (units, base) in [(Units::Binary, 1024f64), (Units::Decimal, 1000f64)] {
735                let s = Bytes::new(v).display(units).to_string();
736                let (num, unit) = parse_display(&s);
737                let index = units.labels().iter().position(|&l| l == unit).unwrap();
738                prop_assert!(num < base || index == 6, "{s} should have carried");
739                let back = num * base.powi(index as i32);
740                // One decimal place: within half a tenth of the unit.
741                let tolerance = 0.05 * base.powi(index as i32) + 0.5;
742                prop_assert!((back - v as f64).abs() <= tolerance, "{v} -> {s}");
743            }
744        }
745
746        #[test]
747        fn prop_bytes_order_matches_raw(a in any::<u64>(), b in any::<u64>()) {
748            prop_assert_eq!(Bytes::new(a).cmp(&Bytes::new(b)), a.cmp(&b));
749        }
750
751        #[test]
752        fn prop_percent_always_in_range(part in any::<u64>(), whole in any::<u64>(), v in any::<f32>()) {
753            for p in [Percent::from_ratio(part, whole), Percent::from_value(v)] {
754                prop_assert!(!p.value().is_nan());
755                prop_assert!((0.0..=100.0).contains(&p.value()));
756                prop_assert!((0.0..=100.0).contains(&p.complement().value()));
757            }
758        }
759
760        #[test]
761        fn prop_percent_eq_matches_hash(a in any::<f32>(), b in any::<f32>()) {
762            use std::collections::hash_map::DefaultHasher;
763            let (pa, pb) = (Percent::from_value(a), Percent::from_value(b));
764            let hash = |p: Percent| { let mut h = DefaultHasher::new(); p.hash(&mut h); h.finish() };
765            if pa == pb { prop_assert_eq!(hash(pa), hash(pb)); }
766            prop_assert_eq!(pa == pb, pa.cmp(&pb) == Ordering::Equal);
767        }
768    }
769}