1use 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#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
46pub struct Bytes(u64);
47
48#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
50#[non_exhaustive]
51pub enum Units {
52 Binary,
54 Decimal,
56 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 pub const ZERO: Bytes = Bytes(0);
86 pub const MAX: Bytes = Bytes(u64::MAX);
88
89 #[must_use]
91 pub const fn new(bytes: u64) -> Bytes {
92 Bytes(bytes)
93 }
94
95 #[must_use]
97 pub const fn raw(self) -> u64 {
98 self.0
99 }
100
101 #[must_use]
103 pub const fn from_kib(n: u64) -> Bytes {
104 Bytes(n.saturating_mul(1 << 10))
105 }
106
107 #[must_use]
109 pub const fn from_mib(n: u64) -> Bytes {
110 Bytes(n.saturating_mul(1 << 20))
111 }
112
113 #[must_use]
121 pub const fn from_gib(n: u64) -> Bytes {
122 Bytes(n.saturating_mul(1 << 30))
123 }
124
125 #[must_use]
127 pub const fn saturating_add(self, other: Bytes) -> Bytes {
128 Bytes(self.0.saturating_add(other.0))
129 }
130
131 #[must_use]
133 pub const fn saturating_sub(self, other: Bytes) -> Bytes {
134 Bytes(self.0.saturating_sub(other.0))
135 }
136
137 #[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 #[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 #[must_use]
168 pub fn percent_of(self, total: Bytes) -> Percent {
169 Percent::from_ratio(self.0, total.0)
170 }
171
172 pub fn display(self, units: Units) -> impl fmt::Display {
179 Formatted { bytes: self, units }
180 }
181
182 pub fn binary(self) -> impl fmt::Display {
184 self.display(Units::Binary)
185 }
186
187 pub fn decimal(self) -> impl fmt::Display {
189 self.display(Units::Decimal)
190 }
191
192 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
238fn 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
254fn 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 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 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#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
313pub struct Rate(u64);
314
315impl Rate {
316 pub const ZERO: Rate = Rate(0);
318
319 #[must_use]
321 pub const fn from_bytes_per_sec(n: u64) -> Rate {
322 Rate(n)
323 }
324
325 #[must_use]
327 pub const fn bytes_per_sec(self) -> u64 {
328 self.0
329 }
330
331 #[must_use]
333 pub const fn bits_per_sec(self) -> u64 {
334 self.0.saturating_mul(8)
335 }
336
337 #[must_use]
349 pub fn per(bytes: Bytes, interval: Duration) -> Rate {
350 Rate::from_delta(bytes.raw(), interval)
351 }
352
353 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 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#[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
440const fn round_div(numerator: u128, divisor: u128) -> u128 {
442 (numerator + divisor / 2) / divisor
443}
444
445#[derive(Clone, Copy, Default)]
466pub struct Percent(f32);
467
468impl Percent {
469 pub const ZERO: Percent = Percent(0.0);
471 pub const FULL: Percent = Percent(100.0);
473
474 #[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 Percent(tenths as f32 / 10.0)
484 }
485
486 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 #[must_use]
497 pub fn from_value(value: f32) -> Percent {
498 if value.is_nan() {
499 Percent::ZERO
500 } else {
501 Percent(value.clamp(0.0, 100.0) + 0.0)
503 }
504 }
505
506 #[must_use]
508 pub fn value(self) -> f32 {
509 self.0
510 }
511
512 #[must_use]
514 pub fn fraction(self) -> f32 {
515 self.0 / 100.0
516 }
517
518 #[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 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 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}