size 0.6.0

A crate for expressing, formatting, and interacting with file sizes
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
//! The `fmt` module contains [`SizeFormatter`] and other types pertaining to formatting a size as
//! human-readable text.
//!
//! You will likely not need to interact with this module directly, as the functionality of a
//! [`SizeFormatter`] is exposed by simply calling [`Size::format()`]. However, a new
//! [`SizeFormatter`] can be instantiated directly if you would like a standalone pretty-printer for
//! raw byte sizes.
//!
//! The formatting-related enums in this module ([`Base`] and [`Style`]) are re-exported at the
//! crate level as `size::Base` and `size::Style`.

use super::*;
use core::fmt;

/// An enumeration of supported bases to use for generating textual descriptions of sizes.
///
/// [`Base::Base10`] is the "usual" units like "kilobyte" and "exabyte", while [`Base::Base2`] is
/// the SI/memory units like "mebibyte" and "tebibyte", (more often referred to as "MiB" and "TiB",
/// respectively).
#[non_exhaustive]
#[derive(Copy, Clone, Debug)]
pub enum Base {
    /// Base-2 units like "kibibyte" and "mebibyte", more often referred to via their abbreviations
    /// ("KiB" and "MiB", respectively). Each unit is 1024 times greater than the preceding one.
    Base2,
    /// Base-10 units like "kilobyte" and "megabyte". Each unit is 1000 times greater than the
    /// preceding one.
    Base10,
}

/// A collection of units used to refer to sizes, for all supported bases.
enum Unit {
    /// The basic "byte" unit, used by both base-2 and base-10 styles.
    Byte,
    /// The base-2 "kibibyte" unit, equal to 1024 bytes.
    Kibibyte,
    /// The base-10 "kilobyte" unit, equal to 1000 bytes.
    Kilobyte,
    /// The base-2 "mebibyte" unit, equal to 1024 kibibytes.
    Mebibyte,
    /// The base-10 "megabyte" unit, equal to 1000 kilobytes.
    Megabyte,
    /// The base-2 "gibibyte" unit, equal to 1024 mebibytes.
    Gibibyte,
    /// The base-10 "gigabyte" unit, equal to 1000 megabytes.
    Gigabyte,
    /// The base-2 "tebibyte" unit, equal to 1024 gibibytes.
    Tebibyte,
    /// The base-10 "terabyte" unit, equal to 1000 gigabytes.
    Terabyte,
    /// The base-2 "pebibyte" unit, equal to 1024 tebibytes.
    Pebibyte,
    /// The base-10 "petabyte" unit, equal to 1000 terabytes.
    Petabyte,
    /// The base-2 "exbibyte" unit, equal to 1024 pebibytes.
    Exbibyte,
    /// The base-10 "exabyte" unit, equal to 1000 petabytes.
    Exabyte,
}

impl Unit {
    #[rustfmt::skip]
    const fn text(&self) -> (&'static str, &'static str, &'static str, &'static str) {
        use self::Unit::*;

        match self {
            Byte => ("byte", "Byte", "b", "B"),

            Kilobyte => ("kilobyte", "Kilobyte", "kb", "KB"),
            Megabyte => ("megabyte", "Megabyte", "mb", "MB"),
            Gigabyte => ("gigabyte", "Gigabyte", "gb", "GB"),
            Terabyte => ("terabyte", "Terabyte", "tb", "TB"),
            Petabyte => ("petabyte", "Petabyte", "pb", "PB"),
            Exabyte  => ("exabyte",  "Exabyte",  "eb", "EB"),

            Kibibyte => ("kibibyte", "Kibibyte", "kib", "KiB"),
            Mebibyte => ("mebibyte", "Mebibyte", "mib", "MiB"),
            Gibibyte => ("gibibyte", "Gibibyte", "gib", "GiB"),
            Pebibyte => ("pebibyte", "Pebibyte", "pib", "PiB"),
            Tebibyte => ("tebibyte", "Tebibyte", "tib", "TiB"),
            Exbibyte => ("exbibyte", "Exbibyte", "eib", "EiB"),
        }
    }

    fn format(&self, fmt: &mut fmt::Formatter, bytes: u64, style: &Style) -> fmt::Result {
        match (&style, bytes) {
            (&Style::Default, _) => match &self {
                &Unit::Byte => self.format(fmt, bytes, &Style::FullLowercase),
                _ => self.format(fmt, bytes, &Style::Abbreviated),
            },

            (&Style::FullLowercase, 1) => write!(fmt, " {}", self.text().0),
            (&Style::Full, 1) => write!(fmt, " {}", self.text().1),
            (&Style::AbbreviatedLowercase, 1) => write!(fmt, " {}", self.text().2),
            (&Style::Abbreviated, 1) => write!(fmt, " {}", self.text().3),

            (&Style::FullLowercase, _) => write!(fmt, " {}s", self.text().0),
            (&Style::Full, _) => write!(fmt, " {}s", self.text().1),
            (&Style::AbbreviatedLowercase, _) => write!(fmt, " {}", self.text().2),
            (&Style::Abbreviated, _) => write!(fmt, " {}", self.text().3),
        }
    }
}

/// An enumeration of supported styles to be used when formatting/printing a [`Size`] type,
/// specifying how the unit should be spelled out.
#[non_exhaustive]
#[derive(Copy, Clone, Debug)]
pub enum Style {
    /// The default "smart" style, currently equal to [`Style::FullLowercase`] when the final unit
    /// is in bytes or [`Style::Abbreviated`] otherwise, e.g. "1024 bytes" and "1.29 GiB"
    Default,
    /// Abbreviated style, e.g. "1024 KB" and "1.29 GiB"
    Abbreviated,
    /// Abbreviated, lowercase style, e.g. "1024 kb" and "1.29 gib"
    AbbreviatedLowercase,
    /// Full unit name style, e.g. "1024 Kilobytes" and "1.29 Gibibytes"
    Full,
    /// Full, lowercase unit name style, e.g. "1024 kilobytes" and "1.29 gibibytes"
    FullLowercase,
}

// Backwards-compatibility associated constants to mimic `Style` variants to enable compilation of
// older code. They are all hidden from the docs.
impl Style {
    #[doc(hidden)]
    #[allow(non_upper_case_globals)]
    #[deprecated(since = "0.3.0", note = "Use Style::Default instead")]
    /// A backwards-compatible alias for [`Style::Default`]
    pub const Smart: Style = Style::Default;

    #[doc(hidden)]
    #[allow(non_upper_case_globals)]
    #[deprecated(since = "0.3.0", note = "Use Style::AbbreviatedLowercase instead")]
    /// A backwards-compatible alias for [`Style::AbbreviatedLowercase`]
    pub const AbbreviatedLowerCase: Style = Style::AbbreviatedLowercase;

    #[doc(hidden)]
    #[allow(non_upper_case_globals)]
    #[deprecated(since = "0.3.0", note = "Use Style::FullLowercase instead")]
    /// A backwards-compatible alias for [`Style::FullLowercase`]
    pub const FullLowerCase: Style = Style::FullLowercase;
}

impl fmt::Display for Size {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        write!(fmt, "{}", self.format())
    }
}

mod sealed {
    pub trait FormatterSize {}

    impl FormatterSize for () {}
    impl<'a> FormatterSize for &'a crate::Size {}
}

/// A standalone size formatter that is configured via the builder pattern (via the various `.with_`
/// methods) which can then be used to format an integral byte value as a pretty printed `String` in
/// accordance with the configured properties.
///
/// Use of the strongly typed [`Size`] to hold and display sizes is strongly preferred over this
/// approach, but it may come in handy when you have many sizes and all need to be formatted in an
/// identical and manually-specified fashion.
///
#[cfg_attr(not(feature = "std"), doc = "```ignore")]
#[cfg_attr(feature = "std", doc = "```")]
/// use size::{Base, Size, SizeFormatter, Style};
///
/// let formatter = SizeFormatter::new()
///     // Use base-10 units like MB and KB, not MiB and KiB
///     .with_base(Base::Base10)
///     // Use abbreviated unit names (e.g. MB and not megabyte)
///     .with_style(Style::Abbreviated)
///     // Print sizes with two digits after the decimal point (e.g. 2.00 KiB, not 2 KiB)
///     .with_scale(Some(2));
///
/// # let mut sizes: Vec<String> = Vec::new();
/// for raw_size in [ 1024, 2048, 4096 ]
/// #   // Work around limitation in earlier rustc versions (e.g. 1.50)
/// #   .iter()
/// {
/// #   // Work around limitation in earlier rustc versions (e.g. 1.50)
/// #   let raw_size = *raw_size;
///     let formatted = formatter.format(raw_size);
///     println!("{}", &formatted);
/// #   sizes.push(formatted);
/// }
///
/// // Prints:
/// // 1.02 KB
/// // 2.05 KB
/// // 4.10 KB
///
/// # assert_eq!(sizes[0].as_str(), "1.02 KB");
/// # assert_eq!(sizes[1].as_str(), "2.05 KB");
/// # assert_eq!(sizes[2].as_str(), "4.10 KB");
/// ```
pub struct SizeFormatter<T: sealed::FormatterSize = ()> {
    size: T,
    base: Base,
    style: Style,
    scale: Option<usize>,
}

impl Default for SizeFormatter<()> {
    fn default() -> Self {
        Self::new()
    }
}

impl<T: sealed::FormatterSize> SizeFormatter<T> {
    /// Specify the base of the units to be used when generating the textual description of the
    /// `Size`.
    ///
    /// This lets users choose between "standard" base-10 units like "KB" and "MB" or the improved
    /// SI base-2 units like "KiB" and "MiB". See [`Base`] for more information.
    pub fn with_base(self, base: Base) -> Self {
        Self { base, ..self }
    }

    /// Specify the style used to write the accompanying unit for a formatted file size.
    ///
    /// See [`Style`] for more information.
    pub fn with_style(self, style: Style) -> Self {
        Self { style, ..self }
    }

    /// Specify the scale/precision of the formatted sizes.
    ///
    /// Sets the number of digits after the decimal point for formatted sizes. A value of `Some(0)`
    /// prints whole numbers only while a value of `None` uses the default formatting which uses a
    /// different scale/precision for sizes depending on the chosen unit.
    ///
    /// # Examples
    ///
    #[cfg_attr(not(feature = "std"), doc = "```")]
    #[cfg_attr(feature = "std", doc = "```")]
    /// use size::Size;
    ///
    /// let formatted = Size::from_bytes(42_000)
    ///     .format()
    ///     .with_scale(Some(3))
    ///     .to_string();
    /// assert_eq!(&formatted, "41.016 KiB");
    /// ```
    ///
    /// Sizes that are printed as a whole number of bytes do not have a scale:
    #[cfg_attr(not(feature = "std"), doc = "```ignore")]
    #[cfg_attr(feature = "std", doc = "```")]
    /// use size::SizeFormatter;
    ///
    /// let bytes = SizeFormatter::new()
    ///     .with_scale(Some(2))
    ///     .format(123);
    /// assert_eq!(&bytes, "123 bytes");
    /// ```
    pub fn with_scale(self, scale: Option<usize>) -> Self {
        Self { scale, ..self }
    }

    /// Formats the provided `bytes` value with the configured [`self.base`], [`self.style`], and
    /// [`self.scale`].
    fn inner_fmt(&self, fmt: &mut fmt::Formatter, bytes: i64) -> fmt::Result {
        let bytes = match bytes {
            x @ 0..=i64::MAX => x as u64,
            y => {
                write!(fmt, "-")?;

                // The absolute magnitude of T::MIN for a signed number is one more than
                // that of T::MAX, meaning T::MIN.abs() will panic.
                match y.checked_abs() {
                    Some(abs) => abs as u64,
                    None => i64::MAX as u64,
                }
            }
        };

        let rule = match self.base {
            Base::Base2 => match BASE2_RULES.binary_search_by_key(&bytes, |rule| rule.less_than) {
                Ok(index) => &BASE2_RULES[index + 1],
                Err(index) => &BASE2_RULES[index],
            },
            Base::Base10 => {
                match BASE10_RULES.binary_search_by_key(&bytes, |rule| rule.less_than) {
                    Ok(index) => &BASE10_RULES[index + 1],
                    Err(index) => &BASE10_RULES[index],
                }
            }
        };

        (rule.formatter)(fmt, bytes, self.scale)?;
        rule.unit.format(fmt, bytes, &self.style)?;

        Ok(())
    }
}

impl SizeFormatter<()> {
    /// Create a new `SizeFormatter` that can be used to repeatedly format a number of file sizes
    /// according to its configured options.
    pub const fn new() -> SizeFormatter<()> {
        SizeFormatter {
            size: (),
            base: DEFAULT_BASE,
            style: DEFAULT_STYLE,
            scale: DEFAULT_SCALE,
        }
    }
}

/// Result of [`Size::format()`], allowing customization of size pretty printing.
///
/// This is a specialization of [`SizeFormatter`] that can be used to achieve greater control over
/// how a specific [`Size`] value is formatted as human-readable text, created by calling
/// [`Size::format()`]. The `SizeFormatter` follows the builder model and exposes a chaining API for
/// configuration (via the `.with_` functions).
///
/// After configuration, a `FormattableSize` may be passed directly to the `println!()` or
/// `format!()` macros and their friends because it implements [`Display`](core::fmt::Display), or
/// [`FormattableSize::to_string()`](ToString::to_string) can be used to retrieve a `String`
/// containing the formatted result.
///
/// To configure once and repeatedly print sizes in the same format, create a standalone
/// [`SizeFormatter`] instead of using `Size::format()`.
///
/// Example:
/// ```
/// use size::{Base, Size, Style};
///
/// # #[cfg(feature = "std")]
/// let size = Size::from_mib(1.907349);
/// # #[cfg(not(feature = "std"))]
/// # let size = Size::from_bytes(2000000);
/// let text = size.format()
///     .with_base(Base::Base10) // use base-10 sizes
///     .with_style(Style::Full) // print full unit names
///     .with_scale(Some(2)) // two digits after the decimal
///     .to_string();
///
/// assert_eq!(text.as_str(), "2.00 Megabytes");
/// ```
///
/// The call to `.to_string()` can be omitted if you are passing the `SizeFormatter`/
/// `FormattableSize` to any of the format macros like `println!()` and co.
pub type FormattableSize<'a> = SizeFormatter<&'a Size>;

impl fmt::Display for FormattableSize<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.inner_fmt(f, self.size.bytes())
    }
}

impl Size {
    /// Returns a textual representation of the [`Size`] for display purposes.
    ///
    /// Gives the caller control over the returned value's scale, base (see [`Base::Base2`] and
    /// [`Base::Base10`]), and the style used to express the determined unit (see [`Style`]).
    ///
    /// Example:
    /// ```
    /// use size::{Base, Size, Style};
    ///
    /// # #[cfg(feature = "std")]
    /// let size = Size::from_mib(1.907349);
    /// # #[cfg(not(feature = "std"))]
    /// # let size = Size::from_bytes(2000000);
    /// let text = size.format()
    ///     .with_base(Base::Base10) // use base-10 sizes
    ///     .with_style(Style::Full) // print full unit names
    ///     .with_scale(Some(2)) // two digits after the decimal
    ///     .to_string();
    ///
    /// assert_eq!(text.as_str(), "2.00 Megabytes");
    /// ```
    ///
    /// It is not necessary to call `.to_string()` if you are passing the formatted size to a
    /// `format!()` macro or similar (e.g. `println!` and friends), as the result implements
    /// [`Display`](core::fmt::Display) and will resolve to the same text.
    pub fn format(&self) -> FormattableSize<'_> {
        FormattableSize {
            size: self,
            base: DEFAULT_BASE,
            style: DEFAULT_STYLE,
            scale: DEFAULT_SCALE,
        }
    }
}

struct FormatRule {
    less_than: u64,
    formatter: fn(&mut fmt::Formatter, bytes: u64, scale: Option<usize>) -> fmt::Result,
    unit: Unit,
}

const BASE10_RULES: [FormatRule; 17] = [
    FormatRule {
        less_than: KILOBYTE as u64,
        formatter: |fmt, bytes, _| write!(fmt, "{0:.0}", bytes),
        unit: Unit::Byte,
    },
    FormatRule {
        less_than: 10 * KILOBYTE as u64,
        formatter: |fmt, bytes, scale| {
            write!(fmt, "{0:.1$}", bytes as f64 / (KILOBYTE as f64), scale.unwrap_or(2))
        },
        unit: Unit::Kilobyte,
    },
    FormatRule {
        less_than: 100 * KILOBYTE as u64,
        formatter: |fmt, bytes, scale| {
            write!(fmt, "{0:.1$}", bytes as f64 / (KILOBYTE as f64), scale.unwrap_or(1))
        },
        unit: Unit::Kilobyte,
    },
    FormatRule {
        less_than: MEGABYTE as u64,
        formatter: |fmt, bytes, scale| {
            write!(fmt, "{0:.1$}", bytes as f64 / (KILOBYTE as f64), scale.unwrap_or(0))
        },
        unit: Unit::Kilobyte,
    },
    FormatRule {
        less_than: 10 * MEGABYTE as u64,
        formatter: |fmt, bytes, scale| {
            write!(fmt, "{0:.1$}", bytes as f64 / (MEGABYTE as f64), scale.unwrap_or(2))
        },
        unit: Unit::Megabyte,
    },
    FormatRule {
        less_than: 100 * MEGABYTE as u64,
        formatter: |fmt, bytes, scale| {
            write!(fmt, "{0:.1$}", bytes as f64 / (MEGABYTE as f64), scale.unwrap_or(1))
        },
        unit: Unit::Megabyte,
    },
    FormatRule {
        less_than: GIGABYTE as u64,
        formatter: |fmt, bytes, scale| {
            write!(fmt, "{0:.1$}", bytes as f64 / (MEGABYTE as f64), scale.unwrap_or(0))
        },
        unit: Unit::Megabyte,
    },
    FormatRule {
        less_than: 10 * GIGABYTE as u64,
        formatter: |fmt, bytes, scale| {
            write!(fmt, "{0:.1$}", bytes as f64 / (GIGABYTE as f64), scale.unwrap_or(2))
        },
        unit: Unit::Gigabyte,
    },
    FormatRule {
        less_than: 100 * GIGABYTE as u64,
        formatter: |fmt, bytes, scale| {
            write!(fmt, "{0:.1$}", bytes as f64 / (GIGABYTE as f64), scale.unwrap_or(1))
        },
        unit: Unit::Gigabyte,
    },
    FormatRule {
        less_than: TERABYTE as u64,
        formatter: |fmt, bytes, scale| {
            write!(fmt, "{0:.1$}", bytes as f64 / (GIGABYTE as f64), scale.unwrap_or(0))
        },
        unit: Unit::Gigabyte,
    },
    FormatRule {
        less_than: 10 * TERABYTE as u64,
        formatter: |fmt, bytes, scale| {
            write!(fmt, "{0:.1$}", bytes as f64 / (TERABYTE as f64), scale.unwrap_or(2))
        },
        unit: Unit::Terabyte,
    },
    FormatRule {
        less_than: 100 * TERABYTE as u64,
        formatter: |fmt, bytes, scale| {
            write!(fmt, "{0:.1$}", bytes as f64 / (TERABYTE as f64), scale.unwrap_or(1))
        },
        unit: Unit::Terabyte,
    },
    FormatRule {
        less_than: PETABYTE as u64,
        formatter: |fmt, bytes, scale| {
            write!(fmt, "{0:.1$}", bytes as f64 / (TERABYTE as f64), scale.unwrap_or(0))
        },
        unit: Unit::Terabyte,
    },
    FormatRule {
        less_than: 10 * PETABYTE as u64,
        formatter: |fmt, bytes, scale| {
            write!(fmt, "{0:.1$}", bytes as f64 / (PETABYTE as f64), scale.unwrap_or(2))
        },
        unit: Unit::Petabyte,
    },
    FormatRule {
        less_than: 100 * PETABYTE as u64,
        formatter: |fmt, bytes, scale| {
            write!(fmt, "{0:.1$}", bytes as f64 / (PETABYTE as f64), scale.unwrap_or(1))
        },
        unit: Unit::Petabyte,
    },
    FormatRule {
        less_than: EXABYTE as u64,
        formatter: |fmt, bytes, scale| {
            write!(fmt, "{0:.1$}", bytes as f64 / (PETABYTE as f64), scale.unwrap_or(0))
        },
        unit: Unit::Petabyte,
    },
    FormatRule {
        less_than: u64::MAX,
        formatter: |fmt, bytes, scale| {
            write!(fmt, "{0:.1$}", bytes as f64 / (EXABYTE as f64), scale.unwrap_or(0))
        },
        unit: Unit::Exabyte,
    },
];

const BASE2_RULES: [FormatRule; 17] = [
    FormatRule {
        less_than: KIBIBYTE as u64,
        formatter: |fmt, bytes, _| write!(fmt, "{0:.0}", bytes),
        unit: Unit::Byte,
    },
    FormatRule {
        less_than: 10 * KIBIBYTE as u64,
        formatter: |fmt, bytes, scale| {
            write!(fmt, "{0:.1$}", bytes as f64 / (KIBIBYTE as f64), scale.unwrap_or(2))
        },
        unit: Unit::Kibibyte,
    },
    FormatRule {
        less_than: 100 * KIBIBYTE as u64,
        formatter: |fmt, bytes, scale| {
            write!(fmt, "{0:.1$}", bytes as f64 / (KIBIBYTE as f64), scale.unwrap_or(1))
        },
        unit: Unit::Kibibyte,
    },
    FormatRule {
        less_than: MEBIBYTE as u64,
        formatter: |fmt, bytes, scale| {
            write!(fmt, "{0:.1$}", bytes as f64 / (KIBIBYTE as f64), scale.unwrap_or(0))
        },
        unit: Unit::Kibibyte,
    },
    FormatRule {
        less_than: 10 * MEBIBYTE as u64,
        formatter: |fmt, bytes, scale| {
            write!(fmt, "{0:.1$}", bytes as f64 / (MEBIBYTE as f64), scale.unwrap_or(2))
        },
        unit: Unit::Mebibyte,
    },
    FormatRule {
        less_than: 100 * MEBIBYTE as u64,
        formatter: |fmt, bytes, scale| {
            write!(fmt, "{0:.1$}", bytes as f64 / (MEBIBYTE as f64), scale.unwrap_or(1))
        },
        unit: Unit::Mebibyte,
    },
    FormatRule {
        less_than: GIBIBYTE as u64,
        formatter: |fmt, bytes, scale| {
            write!(fmt, "{0:.1$}", bytes as f64 / (MEBIBYTE as f64), scale.unwrap_or(0))
        },
        unit: Unit::Mebibyte,
    },
    FormatRule {
        less_than: 10 * GIBIBYTE as u64,
        formatter: |fmt, bytes, scale| {
            write!(fmt, "{0:.1$}", bytes as f64 / (GIBIBYTE as f64), scale.unwrap_or(2))
        },
        unit: Unit::Gibibyte,
    },
    FormatRule {
        less_than: 100 * GIBIBYTE as u64,
        formatter: |fmt, bytes, scale| {
            write!(fmt, "{0:.1$}", bytes as f64 / (GIBIBYTE as f64), scale.unwrap_or(1))
        },
        unit: Unit::Gibibyte,
    },
    FormatRule {
        less_than: TEBIBYTE as u64,
        formatter: |fmt, bytes, scale| {
            write!(fmt, "{0:.1$}", bytes as f64 / (GIBIBYTE as f64), scale.unwrap_or(0))
        },
        unit: Unit::Gibibyte,
    },
    FormatRule {
        less_than: 10 * TEBIBYTE as u64,
        formatter: |fmt, bytes, scale| {
            write!(fmt, "{0:.1$}", bytes as f64 / (TEBIBYTE as f64), scale.unwrap_or(2))
        },
        unit: Unit::Tebibyte,
    },
    FormatRule {
        less_than: 100 * TEBIBYTE as u64,
        formatter: |fmt, bytes, scale| {
            write!(fmt, "{0:.1$}", bytes as f64 / (TEBIBYTE as f64), scale.unwrap_or(1))
        },
        unit: Unit::Tebibyte,
    },
    FormatRule {
        less_than: PEBIBYTE as u64,
        formatter: |fmt, bytes, scale| {
            write!(fmt, "{0:.1$}", bytes as f64 / (TEBIBYTE as f64), scale.unwrap_or(0))
        },
        unit: Unit::Tebibyte,
    },
    FormatRule {
        less_than: 10 * PEBIBYTE as u64,
        formatter: |fmt, bytes, scale| {
            write!(fmt, "{0:.1$}", bytes as f64 / (PEBIBYTE as f64), scale.unwrap_or(2))
        },
        unit: Unit::Pebibyte,
    },
    FormatRule {
        less_than: 100 * PEBIBYTE as u64,
        formatter: |fmt, bytes, scale| {
            write!(fmt, "{0:.1$}", bytes as f64 / (PEBIBYTE as f64), scale.unwrap_or(1))
        },
        unit: Unit::Pebibyte,
    },
    FormatRule {
        less_than: EXBIBYTE as u64,
        formatter: |fmt, bytes, scale| {
            write!(fmt, "{0:.1$}", bytes as f64 / (PEBIBYTE as f64), scale.unwrap_or(0))
        },
        unit: Unit::Pebibyte,
    },
    FormatRule {
        less_than: u64::MAX,
        formatter: |fmt, bytes, scale| {
            write!(fmt, "{0:.1$}", bytes as f64 / (EXBIBYTE as f64), scale.unwrap_or(0))
        },
        unit: Unit::Exbibyte,
    },
];

#[cfg(feature = "std")]
mod std {
    use super::*;

    /// Makes it possible to obtain a string from an `fmt(f: &mut Formatter)` function by initializing
    /// this type as a wrapper around said format function, then using `format!("{}", foo)` on the
    /// resulting object.
    struct FmtRenderer<F: Fn(&mut fmt::Formatter) -> fmt::Result> {
        formatter: F,
    }

    impl<F: Fn(&mut fmt::Formatter) -> fmt::Result> FmtRenderer<F> {
        pub fn new(formatter: F) -> Self {
            Self { formatter }
        }
    }

    impl<F: Fn(&mut fmt::Formatter) -> fmt::Result> fmt::Display for FmtRenderer<F> {
        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            (self.formatter)(f)
        }
    }

    impl SizeFormatter<()> {
        /// Formats a provided size in bytes as a string, per the configuration of the current
        /// `SizeFormatter` instance.
        pub fn format(&self, bytes: i64) -> String {
            format!(
                "{}",
                FmtRenderer::new(|fmt: &mut fmt::Formatter| { self.inner_fmt(fmt, bytes) })
            )
        }
    }
}