1use core::{
9 cmp::Ordering,
10 fmt::{self, Write as _},
11 hash::{Hash, Hasher},
12};
13
14use crate::fmt::{StackBuf, pad};
15
16#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
44pub struct Bytes(u64);
45
46#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
48#[non_exhaustive]
49pub enum Units {
50 Binary,
52 Decimal,
54 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 pub const ZERO: Bytes = Bytes(0);
83 pub const MAX: Bytes = Bytes(u64::MAX);
85
86 #[must_use]
88 pub const fn new(bytes: u64) -> Bytes {
89 Bytes(bytes)
90 }
91
92 #[must_use]
94 pub const fn raw(self) -> u64 {
95 self.0
96 }
97
98 #[must_use]
100 pub const fn from_kib(n: u64) -> Bytes {
101 Bytes(n.saturating_mul(1 << 10))
102 }
103
104 #[must_use]
106 pub const fn from_mib(n: u64) -> Bytes {
107 Bytes(n.saturating_mul(1 << 20))
108 }
109
110 #[must_use]
118 pub const fn from_gib(n: u64) -> Bytes {
119 Bytes(n.saturating_mul(1 << 30))
120 }
121
122 #[must_use]
124 pub const fn saturating_add(self, other: Bytes) -> Bytes {
125 Bytes(self.0.saturating_add(other.0))
126 }
127
128 #[must_use]
130 pub const fn saturating_sub(self, other: Bytes) -> Bytes {
131 Bytes(self.0.saturating_sub(other.0))
132 }
133
134 #[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 #[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 #[must_use]
165 pub fn percent_of(self, total: Bytes) -> Percent {
166 Percent::from_ratio(self.0, total.0)
167 }
168
169 pub fn display(self, units: Units) -> impl fmt::Display {
176 Formatted { bytes: self, units }
177 }
178
179 pub fn binary(self) -> impl fmt::Display {
181 self.display(Units::Binary)
182 }
183
184 pub fn decimal(self) -> impl fmt::Display {
186 self.display(Units::Decimal)
187 }
188
189 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
235fn 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 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 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
281const fn round_div(numerator: u128, divisor: u128) -> u128 {
283 (numerator + divisor / 2) / divisor
284}
285
286#[derive(Clone, Copy, Default)]
307pub struct Percent(f32);
308
309impl Percent {
310 pub const ZERO: Percent = Percent(0.0);
312 pub const FULL: Percent = Percent(100.0);
314
315 #[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 Percent(tenths as f32 / 10.0)
325 }
326
327 #[must_use]
329 pub fn from_value(value: f32) -> Percent {
330 if value.is_nan() {
331 Percent::ZERO
332 } else {
333 Percent(value.clamp(0.0, 100.0) + 0.0)
335 }
336 }
337
338 #[must_use]
340 pub fn value(self) -> f32 {
341 self.0
342 }
343
344 #[must_use]
346 pub fn fraction(self) -> f32 {
347 self.0 / 100.0
348 }
349
350 #[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 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 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}