humanize_proper 0.1.0

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
//! Number formatting with decimal (1000-wise) and binary (1024-wise) 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.

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 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"];

/// The step between two neighboring unit prefixes.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Base {
    /// Steps of 1024, as used for memory sizes.
    Bin,
    /// Steps of 1000, as used by the 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,
}

impl NumFmt {
    /// Binary prefixes in steps of 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,
        }
    }

    /// SI prefixes in steps of 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,
        }
    }

    /// 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
    }

    /// 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)
    }

    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,
        }
    }
}

/// 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: usize },
    Plain { mantissa: f64, idx: usize },
}

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 < TABLE_LEN - 1 && 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 < TABLE_LEN - 1 && 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`].
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 < TABLE_LEN - 1 && mantissa >= base_f {
        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 < TABLE_LEN - 1 && 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: usize, out: &mut dyn Write) -> fmt::Result {
    let prefix = cfg.table()[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 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***");
    }
}