humanize_proper 0.1.2

Dependency-free, no_std formatting of numbers with SI/binary unit prefixes and of durations
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
//! Number formatting with decimal (metric, factor 1000) and binary (factor 1024) unit prefixes.
//!
//! Integer inputs are scaled exactly. The prefix index comes from repeated integer division, then
//! the value is scaled to a `u128` with half-up rounding. Splitting it into `v / base^idx` and
//! `v % base^idx` before applying the scale keeps that overflow-free up to `u128::MAX`; if it would
//! overflow anyway, the float path takes over. Rounding that reaches the base bumps the prefix and
//! repeats, which is what turns 999999 into 1MB. Floats join the same rendering path by scaling to
//! the same integer, and magnitudes too large to scale print their mantissa plainly.
//!
//! The prefix index is signed: 0 is the bare unit, positive indices are the multiples, negative
//! ones the SI submultiples down to `q`. Only the float path can reach the negative half, since an
//! integer magnitude is either zero or at least 1.

use core::fmt::{self, Display, Formatter, Write};

use crate::buf::{digits_of, pad_rendered, write_zero_padded, POW10};
use crate::value::{ToValue, Value};

const TABLE_LEN: usize = 11;
const SUB_LEN: usize = 10;

const SI: [&str; TABLE_LEN] = ["", "k", "M", "G", "T", "P", "E", "Z", "Y", "R", "Q"];
const IEC: [&str; TABLE_LEN] = ["", "Ki", "Mi", "Gi", "Ti", "Pi", "Ei", "Zi", "Yi", "Ri", "Qi"];
const JEDEC: [&str; TABLE_LEN] = ["", "K", "M", "G", "T", "P", "E", "Z", "Y", "R", "Q"];

/// SI submultiple prefixes, `SUB[0]` being 10^-3. Only used with [`Base::Dec`], since the binary
/// prefixes have no counterpart below 1.
const SUB: [&str; SUB_LEN] = ["m", "µ", "n", "p", "f", "a", "z", "y", "r", "q"];

/// Prefix index of `µ`, the one submultiple that is not an ASCII letter.
const MICRO_IDX: i32 = -2;

/// Prefix index of `Q`, the largest multiple.
const MAX_IDX: i32 = TABLE_LEN as i32 - 1;
/// Prefix index of `q`, the smallest submultiple. Negative indices count downward from `m` at -1.
const MIN_IDX: i32 = -(SUB_LEN as i32);

/// The factor between two neighboring unit prefixes.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Base {
    /// Factor 1024, as used for file sizes and memory.
    Bin,
    /// Factor 1000, as used by the metric (SI) prefixes.
    Dec,
}

impl Base {
    const fn factor(self) -> u128 {
        match self {
            Self::Bin => 1024,
            Self::Dec => 1000,
        }
    }
}

/// The spelling of the binary prefixes.
///
/// Only relevant for [`Base::Bin`]. [`Base::Dec`] always uses the SI prefixes.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Prefixes {
    /// `Ki`, `Mi`, `Gi`, ... as standardized by the IEC.
    Iec,
    /// `K`, `M`, `G`, ... as traditionally used by JEDEC.
    Jedec,
}

/// Configuration of the number formatter.
///
/// The type is `Copy` and all builder methods are `const`, so configurations can be constants:
///
/// ```
/// use humanize_proper::NumFmt;
///
/// const CFG: NumFmt = NumFmt::bin().space(true).jedec();
/// assert_eq!(CFG.fmt(1536).to_string(), "1.5 KB");
/// ```
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[must_use]
pub struct NumFmt {
    base: Base,
    prefixes: Prefixes,
    unit: &'static str,
    space: bool,
    sig: u8,
    trim: bool,
    small: bool,
    ascii_micro: bool,
}

impl NumFmt {
    /// Binary prefixes (factor 1024), IEC spelling, unit `B`, no space.
    ///
    /// ```
    /// # use humanize_proper::NumFmt;
    /// assert_eq!(NumFmt::bin().fmt(1536).to_string(), "1.5KiB");
    /// ```
    pub const fn bin() -> Self {
        Self {
            base: Base::Bin,
            prefixes: Prefixes::Iec,
            unit: "B",
            space: false,
            sig: 3,
            trim: true,
            small: false,
            ascii_micro: false,
        }
    }

    /// Decimal prefixes (metric, factor 1000), unit `B`, no space.
    ///
    /// ```
    /// # use humanize_proper::NumFmt;
    /// assert_eq!(NumFmt::dec().fmt(1500).to_string(), "1.5kB");
    /// ```
    pub const fn dec() -> Self {
        Self {
            base: Base::Dec,
            prefixes: Prefixes::Iec,
            unit: "B",
            space: false,
            sig: 3,
            trim: true,
            small: false,
            ascii_micro: false,
        }
    }

    /// Switches the base while keeping all other settings.
    pub const fn base(mut self, base: Base) -> Self {
        self.base = base;
        self
    }

    /// Inserts a space between the number and the prefix.
    ///
    /// ```
    /// # use humanize_proper::NumFmt;
    /// assert_eq!(NumFmt::bin().space(true).fmt(1536).to_string(), "1.5 KiB");
    /// ```
    pub const fn space(mut self, space: bool) -> Self {
        self.space = space;
        self
    }

    /// Sets the unit appended after the prefix.
    ///
    /// ```
    /// # use humanize_proper::NumFmt;
    /// assert_eq!(NumFmt::dec().unit("Hz").fmt(1_500_000).to_string(), "1.5MHz");
    /// ```
    pub const fn unit(mut self, unit: &'static str) -> Self {
        self.unit = unit;
        self
    }

    /// Formats without any unit.
    ///
    /// ```
    /// # use humanize_proper::NumFmt;
    /// assert_eq!(NumFmt::bin().no_unit().fmt(1536).to_string(), "1.5Ki");
    /// ```
    pub const fn no_unit(self) -> Self {
        self.unit("")
    }

    /// Selects the spelling of the binary prefixes.
    pub const fn prefixes(mut self, prefixes: Prefixes) -> Self {
        self.prefixes = prefixes;
        self
    }

    /// Shorthand for [`Prefixes::Iec`], giving `KiB`, `MiB`, ...
    pub const fn iec(self) -> Self {
        self.prefixes(Prefixes::Iec)
    }

    /// Shorthand for [`Prefixes::Jedec`], giving `KB`, `MB`, ... for base 1024.
    ///
    /// ```
    /// # use humanize_proper::NumFmt;
    /// assert_eq!(NumFmt::bin().jedec().fmt(1048576).to_string(), "1MB");
    /// ```
    pub const fn jedec(self) -> Self {
        self.prefixes(Prefixes::Jedec)
    }

    /// Sets the number of significant digits, clamped to `1..=15`.
    ///
    /// ```
    /// # use humanize_proper::NumFmt;
    /// assert_eq!(NumFmt::bin().sig_digits(5).fmt(1536).to_string(), "1.5KiB");
    /// assert_eq!(NumFmt::bin().sig_digits(1).fmt(1536).to_string(), "2KiB");
    /// ```
    pub const fn sig_digits(mut self, sig: u8) -> Self {
        self.sig = if sig < 1 {
            1
        } else if sig > 15 {
            15
        } else {
            sig
        };
        self
    }

    /// Controls whether trailing zeros of the fraction are dropped.
    ///
    /// ```
    /// # use humanize_proper::NumFmt;
    /// assert_eq!(NumFmt::dec().trim_zeros(false).fmt(1000).to_string(), "1.00kB");
    /// ```
    pub const fn trim_zeros(mut self, trim: bool) -> Self {
        self.trim = trim;
        self
    }

    /// Scales values below 1 with the SI submultiple prefixes `m`, `µ`, `n`, `p`, `f`, `a`, `z`,
    /// `y`, `r`, `q`, instead of printing them as a fraction of the unit.
    ///
    /// Off by default, since a byte count never needs it. Only [`Base::Dec`] is affected: the
    /// binary prefixes have no counterpart below 1, so the setting is ignored for [`Base::Bin`].
    ///
    /// ```
    /// # use humanize_proper::NumFmt;
    /// const V: NumFmt = NumFmt::dec().unit("V").small_prefixes(true);
    /// assert_eq!(V.fmt(0.0125).to_string(), "12.5mV");
    /// assert_eq!(V.fmt(0.000_000_47).to_string(), "470nV");
    /// ```
    pub const fn small_prefixes(mut self, small: bool) -> Self {
        self.small = small;
        self
    }

    /// Spells the micro prefix as the ASCII letter `u` instead of `µ`, for output that has to stay
    /// ASCII. Affects nothing else, since `µ` is the only prefix outside ASCII.
    ///
    /// ```
    /// # use humanize_proper::NumFmt;
    /// const S: NumFmt = NumFmt::dec().unit("s").small_prefixes(true);
    /// assert_eq!(S.fmt(0.000_002_5).to_string(), "2.5µs");
    /// assert_eq!(S.ascii_micro(true).fmt(0.000_002_5).to_string(), "2.5us");
    /// ```
    pub const fn ascii_micro(mut self, ascii: bool) -> Self {
        self.ascii_micro = ascii;
        self
    }

    /// Binds this configuration to a value. The result implements [`Display`].
    pub fn fmt<V: ToValue>(self, value: V) -> Num {
        Num { cfg: self, val: value.to_value() }
    }

    /// Fraction digits left for a mantissa whose integer part has the given number of digits.
    const fn decimals_for(&self, integer_digits: u32) -> u32 {
        (self.sig as u32).saturating_sub(integer_digits)
    }

    /// Whether values below 1 are scaled down into the submultiple prefixes.
    const fn scales_down(&self) -> bool {
        self.small && matches!(self.base, Base::Dec)
    }

    const fn table(&self) -> &'static [&'static str; TABLE_LEN] {
        match (self.base, self.prefixes) {
            (Base::Dec, _) => &SI,
            (Base::Bin, Prefixes::Iec) => &IEC,
            (Base::Bin, Prefixes::Jedec) => &JEDEC,
        }
    }

    /// The prefix for a signed prefix index, negative indices being the submultiples.
    const fn prefix(&self, idx: i32) -> &'static str {
        if idx == MICRO_IDX && self.ascii_micro {
            "u"
        } else if idx < 0 {
            SUB[(-idx - 1) as usize]
        } else {
            self.table()[idx as usize]
        }
    }
}

/// A number bound to a [`NumFmt`], ready to be displayed.
#[derive(Clone, Copy, Debug)]
#[must_use]
pub struct Num {
    cfg: NumFmt,
    val: Value,
}

impl Display for Num {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        pad_rendered(f, |out| render(&self.cfg, self.val, out))
    }
}

/// The magnitude of a value, split off from its sign.
#[derive(Clone, Copy)]
enum Magnitude {
    Int(u128),
    Float(f64),
}

/// A magnitude prepared for output: either scaled to an integer with a known number of fraction
/// digits, or, for magnitudes beyond the prefix table, the plain mantissa.
#[derive(Clone, Copy)]
enum Layout {
    Scaled { scaled: u128, decimals: u32, idx: i32 },
    Plain { mantissa: f64, idx: i32 },
}

fn render(cfg: &NumFmt, val: Value, out: &mut dyn Write) -> fmt::Result {
    let (neg, magnitude) = match val {
        Value::Uint(v) => (false, Magnitude::Int(v)),
        Value::Int(v) => (v < 0, Magnitude::Int(v.unsigned_abs())),
        Value::Float(v) => {
            if v.is_nan() {
                return out.write_str("NaN");
            }
            let neg = v < 0.0;
            let a = if neg { -v } else { v };
            if a.is_infinite() {
                return out.write_str(if neg { "-inf" } else { "inf" });
            }
            (neg, Magnitude::of(a))
        }
    };
    if neg {
        out.write_char('-')?;
    }
    match layout(cfg, magnitude) {
        Layout::Scaled { scaled, decimals, idx } => {
            write_scaled(cfg, scaled, decimals, out)?;
            write_suffix(cfg, idx, out)
        }
        Layout::Plain { mantissa, idx } => {
            write!(out, "{mantissa}")?;
            write_suffix(cfg, idx, out)
        }
    }
}

impl Magnitude {
    /// Routes floats with an exact integer value to the exact integer path.
    fn of(a: f64) -> Self {
        if a < u128::MAX as f64 && (a as u128) as f64 == a {
            Self::Int(a as u128)
        } else {
            Self::Float(a)
        }
    }
}

fn layout(cfg: &NumFmt, magnitude: Magnitude) -> Layout {
    match magnitude {
        Magnitude::Int(v) => layout_int(cfg, v).unwrap_or_else(|| layout_float(cfg, v as f64)),
        Magnitude::Float(a) => layout_float(cfg, a),
    }
}

/// Scales an integer magnitude exactly. Returns `None` if the exact computation would overflow, in
/// which case the float path takes over.
fn layout_int(cfg: &NumFmt, v: u128) -> Option<Layout> {
    let base = cfg.base.factor();
    let mut idx = 0;
    let mut div = 1u128;
    while idx < MAX_IDX && v / div >= base {
        div *= base;
        idx += 1;
    }
    loop {
        let decimals = cfg.decimals_for(digits_of(v / div));
        let scaled = scale_int(v, div, decimals)?;
        if idx < MAX_IDX && rolls_over(scaled, base, decimals) {
            div *= base;
            idx += 1;
            continue;
        }
        return Some(Layout::Scaled { scaled, decimals, idx });
    }
}

fn scale_int(v: u128, div: u128, decimals: u32) -> Option<u128> {
    let pow = POW10[decimals as usize];
    let quot = (v / div).checked_mul(pow)?;
    let rest = (v % div).checked_mul(pow)?.checked_add(div / 2)? / div;
    quot.checked_add(rest)
}

/// Same as [`layout_int`], for magnitudes that are not exact integers. Magnitudes that exceed the
/// prefix table and cannot be scaled into a `u128` end up as [`Layout::Plain`]. Magnitudes below 1
/// are scaled up into the submultiple prefixes, if those are enabled.
fn layout_float(cfg: &NumFmt, a: f64) -> Layout {
    let base = cfg.base.factor();
    let base_f = base as f64;
    let mut idx = 0;
    let mut mantissa = a;
    while idx < MAX_IDX && mantissa >= base_f {
        mantissa /= base_f;
        idx += 1;
    }
    if cfg.scales_down() {
        while idx > MIN_IDX && mantissa > 0.0 && mantissa < 1.0 {
            mantissa *= base_f;
            idx -= 1;
        }
    }
    loop {
        let decimals = cfg.decimals_for(digits_of(mantissa as u128));
        let shifted = mantissa * (POW10[decimals as usize] as f64);
        if shifted >= u128::MAX as f64 {
            return Layout::Plain { mantissa, idx };
        }
        let truncated = shifted as u128;
        let scaled = if shifted - (truncated as f64) >= 0.5 { truncated + 1 } else { truncated };
        if idx < MAX_IDX && rolls_over(scaled, base, decimals) {
            mantissa /= base_f;
            idx += 1;
            continue;
        }
        return Layout::Scaled { scaled, decimals, idx };
    }
}

/// Whether rounding pushed the value up into the next prefix, e.g. 999999 to 1MB.
fn rolls_over(scaled: u128, base: u128, decimals: u32) -> bool {
    base.checked_mul(POW10[decimals as usize]).is_some_and(|limit| scaled >= limit)
}

fn write_suffix(cfg: &NumFmt, idx: i32, out: &mut dyn Write) -> fmt::Result {
    let prefix = cfg.prefix(idx);
    if cfg.space && !(prefix.is_empty() && cfg.unit.is_empty()) {
        out.write_char(' ')?;
    }
    out.write_str(prefix)?;
    out.write_str(cfg.unit)
}

fn write_scaled(cfg: &NumFmt, scaled: u128, decimals: u32, out: &mut dyn Write) -> fmt::Result {
    let pow = POW10[decimals as usize];
    let mut frac = scaled % pow;
    let mut width = decimals as usize;
    if cfg.trim {
        while width > 0 && frac % 10 == 0 {
            frac /= 10;
            width -= 1;
        }
    }
    write!(out, "{}", scaled / pow)?;
    if width > 0 {
        out.write_char('.')?;
        write_zero_padded(out, frac, width)?;
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    extern crate std;
    use std::string::ToString;

    #[test]
    fn spec_table() {
        let cases: [(u64, &str, &str); 7] = [
            (1000, "1000B", "1kB"),
            (1024, "1KiB", "1.02kB"),
            (1536, "1.5KiB", "1.54kB"),
            (15872, "15.5KiB", "15.9kB"),
            (999_999, "977KiB", "1MB"),
            (1_048_576, "1MiB", "1.05MB"),
            (u64::MAX, "16EiB", "18.4EB"),
        ];
        for (input, bin, dec) in cases {
            assert_eq!(NumFmt::bin().fmt(input).to_string(), bin, "bin({input})");
            assert_eq!(NumFmt::dec().fmt(input).to_string(), dec, "dec({input})");
        }
    }

    #[test]
    fn rounding_rolls_over_into_the_next_prefix() {
        assert_eq!(NumFmt::dec().fmt(999_999u64).to_string(), "1MB");
        assert_eq!(NumFmt::dec().fmt(999_499u64).to_string(), "999kB");
        assert_eq!(NumFmt::bin().fmt(1_048_575u64).to_string(), "1MiB");
        assert_eq!(NumFmt::dec().sig_digits(1).fmt(999_999u64).to_string(), "1MB");
    }

    #[test]
    fn sig_digits_never_shorten_the_integer_part() {
        assert_eq!(NumFmt::dec().sig_digits(1).fmt(999u64).to_string(), "999B");
        assert_eq!(NumFmt::dec().sig_digits(15).fmt(1_048_576u64).to_string(), "1.048576MB");
    }

    #[test]
    fn negative_values_keep_their_sign() {
        assert_eq!(NumFmt::bin().fmt(-1536i64).to_string(), "-1.5KiB");
        assert_eq!(NumFmt::dec().fmt(-0.5f64).to_string(), "-0.5B");
    }

    #[test]
    fn floats_and_integers_agree_on_exact_values() {
        assert_eq!(
            NumFmt::bin().fmt(1536.0f64).to_string(),
            NumFmt::bin().fmt(1536u32).to_string()
        );
        assert_eq!(NumFmt::dec().fmt(1.5e9f64).to_string(), "1.5GB");
        assert_eq!(NumFmt::dec().fmt(0.125f64).to_string(), "0.13B");
    }

    #[test]
    fn non_finite_values_are_named() {
        assert_eq!(NumFmt::bin().fmt(f64::NAN).to_string(), "NaN");
        assert_eq!(NumFmt::bin().fmt(f64::INFINITY).to_string(), "inf");
        assert_eq!(NumFmt::bin().fmt(f64::NEG_INFINITY).to_string(), "-inf");
    }

    #[test]
    fn extreme_magnitudes_stay_in_the_table() {
        assert_eq!(NumFmt::dec().fmt(u128::MAX).to_string(), "340282367QB");
        assert_eq!(NumFmt::bin().fmt(u128::MAX).to_string(), "268435456QiB");
        let beyond_the_table = NumFmt::dec().fmt(1e300f64).to_string();
        assert!(beyond_the_table.starts_with("1000000000000000"), "{beyond_the_table}");
        assert!(beyond_the_table.ends_with("QB"), "{beyond_the_table}");
        assert_eq!(beyond_the_table.len(), 273);
    }

    #[test]
    fn small_prefixes_scale_values_below_one() {
        const V: NumFmt = NumFmt::dec().unit("V").small_prefixes(true);
        let cases: [(f64, &str); 12] = [
            (1.0, "1V"),
            (0.5, "500mV"),
            (0.0125, "12.5mV"),
            (1e-3, "1mV"),
            (9.99e-4, "999µV"),
            (4.7e-7, "470nV"),
            (1e-12, "1pV"),
            (1e-15, "1fV"),
            (1e-18, "1aV"),
            (1e-21, "1zV"),
            (1e-24, "1yV"),
            (1e-30, "1qV"),
        ];
        for (input, expected) in cases {
            assert_eq!(V.fmt(input).to_string(), expected, "{input:e}");
        }
        assert_eq!(V.fmt(-0.0125).to_string(), "-12.5mV");
        assert_eq!(V.fmt(0.0).to_string(), "0V");
    }

    #[test]
    fn small_prefixes_roll_over_upward_when_rounding_reaches_the_next_one() {
        const V: NumFmt = NumFmt::dec().unit("V").small_prefixes(true);
        assert_eq!(V.fmt(9.999e-4).to_string(), "1mV");
        assert_eq!(V.fmt(0.9999).to_string(), "1V");
    }

    #[test]
    fn magnitudes_below_the_smallest_submultiple_round_to_zero() {
        const V: NumFmt = NumFmt::dec().unit("V").small_prefixes(true);
        assert_eq!(V.fmt(1e-31).to_string(), "0.1qV");
        assert_eq!(V.fmt(1e-40).to_string(), "0qV");
        assert_eq!(V.fmt(f64::MIN_POSITIVE).to_string(), "0qV");
    }

    #[test]
    fn ascii_micro_replaces_only_the_micro_prefix() {
        const S: NumFmt = NumFmt::dec().unit("s").small_prefixes(true).ascii_micro(true);
        assert_eq!(S.fmt(2.5e-6).to_string(), "2.5us");
        assert_eq!(S.fmt(2.5e-3).to_string(), "2.5ms");
        assert_eq!(S.fmt(2.5e-9).to_string(), "2.5ns");
        assert_eq!(S.fmt(2.5e6).to_string(), "2.5Ms");
        let rendered = S.fmt(2.5e-6).to_string();
        assert!(rendered.is_ascii(), "{rendered}");
    }

    #[test]
    fn small_prefixes_are_opt_in_and_decimal_only() {
        assert_eq!(NumFmt::dec().fmt(0.0125).to_string(), "0.01B");
        assert_eq!(NumFmt::bin().small_prefixes(true).fmt(0.0125).to_string(), "0.01B");
        assert_eq!(NumFmt::dec().small_prefixes(true).fmt(0.0125).to_string(), "12.5mB");
    }

    #[test]
    fn zero_is_prefix_free() {
        assert_eq!(NumFmt::bin().fmt(0u8).to_string(), "0B");
        assert_eq!(NumFmt::dec().space(true).no_unit().fmt(0u8).to_string(), "0");
    }

    #[test]
    fn display_padding_is_honored() {
        assert_eq!(std::format!("{:>10}", NumFmt::bin().fmt(1536)), "    1.5KiB");
        assert_eq!(std::format!("{:*<8}", NumFmt::dec().fmt(1500)), "1.5kB***");
    }
}