prettier-bytes 0.2.1

A blazingly fast and safe, zero-allocation, `no_std`-compatible byte formatter.
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
#![doc = include_str!("../README.md")]
#![no_std]
#![deny(clippy::pedantic)]
#![deny(clippy::nursery)]
#![forbid(clippy::indexing_slicing)]
#![forbid(clippy::panic)]
#![forbid(clippy::unwrap_used)]
#![forbid(clippy::expect_used)]
#![forbid(clippy::unreachable)]
#![forbid(clippy::todo)]
#![forbid(clippy::unimplemented)]
#![forbid(clippy::alloc_instead_of_core)]
#![forbid(clippy::float_arithmetic)]
#![forbid(clippy::cast_possible_wrap)]
#![forbid(clippy::cast_possible_truncation)]
#![forbid(unsafe_code)]

use core::fmt;

/// A configurable formatter for byte sizes.
///
/// # Examples
///
/// ```
/// use prettier_bytes::{ByteFormatter, Standard};
///
/// let fmt = ByteFormatter::new().standard(Standard::SI);
/// assert_eq!(fmt.format(2500).as_str().unwrap(), "2.50 kB");
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ByteFormatter {
    unit: Unit,
    standard: Standard,
    space: bool,
}

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

impl ByteFormatter {
    /// Creates a new `ByteFormatter` with sensible defaults:
    /// Binary standard (Base 1024), Bytes, and a space between the number and unit.
    #[must_use]
    pub const fn new() -> Self {
        Self {
            unit: Unit::Bytes,
            standard: Standard::Binary,
            space: true,
        }
    }

    /// Sets the formatting standard (e.g., SI vs Binary).
    #[must_use]
    pub const fn standard(mut self, standard: Standard) -> Self {
        self.standard = standard;
        self
    }

    /// Sets the base unit (e.g., Bytes vs Bits).
    #[must_use]
    pub const fn unit(mut self, unit: Unit) -> Self {
        self.unit = unit;
        self
    }

    /// Determines whether a space is placed between the number and the unit.
    ///
    /// Defaults to `true` (e.g., `"1.50 MB"`). If set to `false`, the space is omitted
    /// (e.g., `"1.50MB"`).
    ///
    /// # Examples
    ///
    /// ```
    /// use prettier_bytes::ByteFormatter;
    ///
    /// let fmt_spaced = ByteFormatter::new().space(true);
    /// assert_eq!(fmt_spaced.format(1024).as_str().unwrap(), "1.00 KiB");
    ///
    /// let fmt_compact = ByteFormatter::new().space(false);
    /// assert_eq!(fmt_compact.format(1024).as_str().unwrap(), "1.00KiB");
    /// ```
    #[must_use]
    pub const fn space(mut self, space: bool) -> Self {
        self.space = space;
        self
    }

    /// Formats the given value and returns a stack-allocated buffer.
    #[must_use]
    pub fn format(self, val: u64) -> FormattedBytes {
        FormattedBytes::from_formatter(val, self.unit, self.standard, self.space)
    }
}

/// Represents the base unit to format against.
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum Unit {
    /// Formats with a trailing 'B' (e.g., MB, GiB).
    Bytes,
    /// Formats with a trailing 'b' (e.g., Mb, Mib, Gib).
    Bits,
}

/// Represents the mathematical standard for calculating magnitudes.
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum Standard {
    /// Base 1000 (SI standard). Produces kB, MB, GB, etc.
    SI,
    /// Base 1024 (IEC/Binary standard). Produces KiB, MiB, GiB, etc.
    Binary,
}

/// A stack-allocated buffer containing the formatted byte string.
///
/// `FormattedBytes` calculates the formatting upon instantiation and stores
/// the result internally. It can be cheaply converted to a `&str` or `&[u8]`.
#[derive(Clone, Copy)]
pub struct FormattedBytes {
    buf: [u8; 16],
    len: usize,
}

impl FormattedBytes {
    pub(crate) fn from_formatter(val: u64, unit: Unit, standard: Standard, space: bool) -> Self {
        // Determine the magnitude (0=Base, 1=Kilo, 2=Mega, etc.)
        let mag = if val == 0 {
            0
        } else {
            match standard {
                Standard::SI => (val.ilog10() / 3) as usize,
                Standard::Binary => (val.ilog2() / 10) as usize,
            }
        };

        // Cap magnitude at 6 (Exabytes), the physical limit of a u64.
        let mag = mag.min(6);

        // We calculate both the whole number AND the fraction simultaneously
        // such that LLVM never emits a dynamic CPU `div` instruction.
        let (mut whole, mut frac) = if mag == 0 {
            (val, 0)
        } else {
            match standard {
                Standard::Binary => {
                    // Base 1024: Pure bitwise operations (1 clock cycle)
                    let shift = mag * 10;
                    let divisor = 1_u64 << shift;
                    let whole = val >> shift;
                    let rem = val & (divisor - 1);

                    // To prevent u64 overflow on Exbibytes (mag 6), we shift down by 7.
                    let (scaled_rem, final_shift) = if mag == 6 {
                        (rem >> 7, shift - 7)
                    } else {
                        (rem, shift)
                    };

                    // Rounding: Add half of the divisor before shifting to round to nearest integer
                    let rounder = 1_u64 << (final_shift - 1);
                    let f = ((scaled_rem * 100) + rounder) >> final_shift;

                    (whole, f)
                }
                Standard::SI => {
                    // Base 1000: We use a local macro to force LLVM to calculate the
                    // fraction while the divisor is a hardcoded literal
                    // This triggers reciprocal multiplication, bypassing CPU division
                    macro_rules! calc_si {
                        ($div:expr) => {{
                            let w = val / $div;
                            let r = val % $div;
                            let (sr, sd) = if mag == 6 {
                                (r >> 7, $div >> 7)
                            } else {
                                (r, $div)
                            };
                            let f = (sr * 100 + (sd / 2)) / sd;
                            (w, f)
                        }};
                    }

                    match mag {
                        1 => calc_si!(1_000_u64),
                        2 => calc_si!(1_000_000_u64),
                        3 => calc_si!(1_000_000_000_u64),
                        4 => calc_si!(1_000_000_000_000_u64),
                        5 => calc_si!(1_000_000_000_000_000_u64),
                        _ => calc_si!(1_000_000_000_000_000_000_u64),
                    }
                }
            }
        };

        // Carry over if rounding pushed the fraction to 100
        if frac >= 100 {
            frac = 0;
            whole += 1;
        }

        // String assembly
        let mut buf = [0u8; 16];
        let mut iter = buf.iter_mut();

        // Safe iterator pushing
        let mut push = |b: u8| {
            if let Some(slot) = iter.next() {
                *slot = b;
            }
        };

        let (num_buf, num_len) = format_small_num(whole);

        // Push whole number
        for b in num_buf.into_iter().take(num_len) {
            push(b);
        }

        // Push decimals
        if mag != 0 {
            push(b'.');
            push(b'0' + u8::try_from(frac / 10).unwrap_or(0));
            push(b'0' + u8::try_from(frac % 10).unwrap_or(0));
        }

        // Push space
        if space {
            push(b' ');
        }

        // Push prefixes
        if mag != 0 {
            let prefix = match (mag, standard) {
                (1, Standard::SI) => b'k',
                (1, Standard::Binary) => b'K',
                (2, _) => b'M',
                (3, _) => b'G',
                (4, _) => b'T',
                (5, _) => b'P',
                _ => b'E',
            };
            push(prefix);

            if standard == Standard::Binary {
                push(b'i');
            }
        }

        // Push unit
        push(match unit {
            Unit::Bytes => b'B',
            Unit::Bits => b'b',
        });

        // Calculate final length mathematically
        let len = 16 - iter.len();

        Self { buf, len }
    }

    /// Returns the formatted output as a raw byte slice.
    /// Useful for direct `std::io::Write` usage.
    #[inline]
    #[must_use]
    pub fn as_bytes(&self) -> &[u8] {
        self.buf.get(..self.len).unwrap_or(&self.buf)
    }

    /// Returns the formatted output as a UTF-8 string slice.
    ///
    /// # Errors
    ///
    /// Returns a `core::str::Utf8Error` if the internal buffer contains
    /// invalid UTF-8 bytes. (Note: The format method only writes valid
    /// ASCII characters, so this is guaranteed to succeed in practice).
    #[inline]
    pub fn as_str(&self) -> Result<&str, core::str::Utf8Error> {
        let bytes = self.buf.get(..self.len).unwrap_or(&self.buf);
        core::str::from_utf8(bytes)
    }
}

/// Allows `FormattedBytes` to be used in standard Rust formatting macros
/// (e.g., `format!()`, `println!()`, `write!()`).
impl fmt::Display for FormattedBytes {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str().map_err(|_| fmt::Error)?)
    }
}

/// Inlines formatting for numbers strictly < 1024.
///
/// Avoids the heavy loop/modulo cost of general `itoa` routines.
#[inline]
fn format_small_num(n: u64) -> ([u8; 4], usize) {
    if n < 10 {
        ([b'0' + u8::try_from(n).unwrap_or(0), 0, 0, 0], 1)
    } else if n < 100 {
        (
            [
                b'0' + u8::try_from(n / 10).unwrap_or(0),
                b'0' + u8::try_from(n % 10).unwrap_or(0),
                0,
                0,
            ],
            2,
        )
    } else if n < 1000 {
        (
            [
                b'0' + u8::try_from(n / 100).unwrap_or(0),
                b'0' + u8::try_from((n / 10) % 10).unwrap_or(0),
                b'0' + u8::try_from(n % 10).unwrap_or(0),
                0,
            ],
            3,
        )
    } else {
        (
            [
                b'0' + u8::try_from(n / 1000).unwrap_or(0),
                b'0' + u8::try_from((n / 100) % 10).unwrap_or(0),
                b'0' + u8::try_from((n / 10) % 10).unwrap_or(0),
                b'0' + u8::try_from(n % 10).unwrap_or(0),
            ],
            4,
        )
    }
}

/// Allow `FormattedBytes` to be logged seamlessly in resource-constrained
/// embedded environments using the `defmt` framework.
#[cfg(feature = "defmt")]
impl defmt::Format for FormattedBytes {
    fn format(&self, fmt: defmt::Formatter) {
        // We use `.as_str()` because we want to log the human-readable text.
        // The "{=str}" syntax is specific to `defmt` for safely transmitting string slices.
        if let Ok(text) = self.as_str() {
            defmt::write!(fmt, "{=str}", text);
        } else {
            // Fallback in case of a highly improbable UTF-8 failure,
            // ensuring we never panic the embedded device.
            defmt::write!(fmt, "<prettier-bytes: invalid utf-8>");
        }
    }
}

#[cfg(test)]
mod tests {
    extern crate alloc;

    use alloc::format;

    use super::*;

    macro_rules! assert_fmt {
        ($val:expr, $unit:path, $std:path, $space:expr, $expected:expr) => {
            let fmt = ByteFormatter::new()
                .unit($unit)
                .standard($std)
                .space($space)
                .format($val);
            assert_eq!(fmt.as_str().unwrap(), $expected);
        };
    }

    #[test]
    fn test_zero() {
        assert_fmt!(0, Unit::Bytes, Standard::SI, true, "0 B");
        assert_fmt!(0, Unit::Bits, Standard::SI, true, "0 b");
        assert_fmt!(0, Unit::Bytes, Standard::Binary, false, "0B");
        assert_fmt!(0, Unit::Bits, Standard::Binary, false, "0b");
    }

    #[test]
    fn test_base_units_under_1000() {
        // Values < 1000 should format as raw bytes with no decimals in either standard.
        assert_fmt!(1, Unit::Bytes, Standard::SI, true, "1 B");
        assert_fmt!(12, Unit::Bytes, Standard::Binary, true, "12 B");
        assert_fmt!(345, Unit::Bytes, Standard::SI, false, "345B");
        assert_fmt!(999, Unit::Bytes, Standard::SI, true, "999 B");
        assert_fmt!(999, Unit::Bytes, Standard::Binary, true, "999 B");
    }

    #[test]
    fn test_si_exact_magnitudes() {
        // Tests exactly hitting the boundary of SI prefixes (Base 1000)
        assert_fmt!(1_000, Unit::Bytes, Standard::SI, true, "1.00 kB");
        assert_fmt!(1_000_000, Unit::Bytes, Standard::SI, true, "1.00 MB");
        assert_fmt!(1_000_000_000, Unit::Bytes, Standard::SI, true, "1.00 GB");
        assert_fmt!(
            1_000_000_000_000,
            Unit::Bytes,
            Standard::SI,
            true,
            "1.00 TB"
        );
        assert_fmt!(
            1_000_000_000_000_000,
            Unit::Bytes,
            Standard::SI,
            true,
            "1.00 PB"
        );
        assert_fmt!(
            1_000_000_000_000_000_000,
            Unit::Bytes,
            Standard::SI,
            true,
            "1.00 EB"
        );
    }

    #[test]
    fn test_binary_exact_magnitudes() {
        // Tests exactly hitting the boundary of Binary prefixes (Base 1024)
        assert_fmt!(1_024, Unit::Bytes, Standard::Binary, true, "1.00 KiB");
        assert_fmt!(1_048_576, Unit::Bytes, Standard::Binary, true, "1.00 MiB");
        assert_fmt!(
            1_073_741_824,
            Unit::Bytes,
            Standard::Binary,
            true,
            "1.00 GiB"
        );
        assert_fmt!(
            1_099_511_627_776,
            Unit::Bytes,
            Standard::Binary,
            true,
            "1.00 TiB"
        );
        assert_fmt!(
            1_125_899_906_842_624,
            Unit::Bytes,
            Standard::Binary,
            true,
            "1.00 PiB"
        );
        assert_fmt!(
            1_152_921_504_606_846_976,
            Unit::Bytes,
            Standard::Binary,
            true,
            "1.00 EiB"
        );
    }

    #[test]
    fn test_si_vs_binary_difference() {
        // 1,000 bytes is 1.00 kB in SI, but still 1000 B in Binary (since it's < 1024)
        assert_fmt!(1_000, Unit::Bytes, Standard::SI, true, "1.00 kB");
        assert_fmt!(1_000, Unit::Bytes, Standard::Binary, true, "1000 B");

        // 1,023 bytes
        assert_fmt!(1_023, Unit::Bytes, Standard::SI, true, "1.02 kB");
        assert_fmt!(1_023, Unit::Bytes, Standard::Binary, true, "1023 B");
    }

    #[test]
    fn test_rounding_and_decimals() {
        // 1,500 bytes = 1.50 kB
        assert_fmt!(1_500, Unit::Bytes, Standard::SI, true, "1.50 kB");

        // 1,536 bytes = 1.50 KiB (1024 + 512)
        assert_fmt!(1_536, Unit::Bytes, Standard::Binary, true, "1.50 KiB");

        // Rounding down: 1,004 bytes -> 1.00 kB
        assert_fmt!(1_004, Unit::Bytes, Standard::SI, true, "1.00 kB");

        // Rounding up: 1,005 bytes -> 1.01 kB
        assert_fmt!(1_005, Unit::Bytes, Standard::SI, true, "1.01 kB");

        // 1.23 MB
        assert_fmt!(1_230_000, Unit::Bytes, Standard::SI, true, "1.23 MB");
    }

    #[test]
    fn test_carry_over_rounding() {
        // If a value is right on the edge of the next decimal, it should round the whole number up.
        // 999,999 bytes in SI is 999.999 kB. Rounding to 2 digits makes it 1000.00 kB.
        assert_fmt!(999_999, Unit::Bytes, Standard::SI, true, "1000.00 kB");

        // Binary equivalent: 1,048,575 bytes is 1 byte shy of 1 MiB.
        // In KiB, it's 1023.999... which rounds up to 1024.00 KiB.
        assert_fmt!(
            1_048_575,
            Unit::Bytes,
            Standard::Binary,
            true,
            "1024.00 KiB"
        );
    }

    #[test]
    fn test_formatting_variations() {
        let val = 2_500_000;

        // Bytes vs Bits
        assert_fmt!(val, Unit::Bytes, Standard::SI, true, "2.50 MB");
        assert_fmt!(val, Unit::Bits, Standard::SI, true, "2.50 Mb");

        // SI vs Binary
        assert_fmt!(val, Unit::Bytes, Standard::SI, true, "2.50 MB");
        assert_fmt!(val, Unit::Bytes, Standard::Binary, true, "2.38 MiB");

        // Spacing vs No Spacing
        assert_fmt!(val, Unit::Bytes, Standard::SI, true, "2.50 MB");
        assert_fmt!(val, Unit::Bytes, Standard::SI, false, "2.50MB");
    }

    #[test]
    fn test_extreme_values() {
        // u64::MAX is 18_446_744_073_709_551_615

        // In SI (Base 1000): ~18.45 Exabytes
        assert_fmt!(u64::MAX, Unit::Bytes, Standard::SI, true, "18.45 EB");

        // In Binary (Base 1024):
        // u64::MAX is just 1 byte shy of 16 Exbibytes (16.00 EiB after rounding)
        assert_fmt!(u64::MAX, Unit::Bytes, Standard::Binary, true, "16.00 EiB");
    }

    #[test]
    fn test_as_bytes() {
        // Ensure the raw byte slice matches the string representation exactly
        let fmt = ByteFormatter::new()
            .unit(Unit::Bytes)
            .standard(Standard::SI)
            .space(false)
            .format(1500);
        assert_eq!(fmt.as_bytes(), b"1.50kB");
    }

    #[test]
    fn test_number_boundaries() {
        // Tests the transition points inside the `format_small_num` logic
        assert_fmt!(9, Unit::Bytes, Standard::SI, true, "9 B"); // 1 digit max
        assert_fmt!(10, Unit::Bytes, Standard::SI, true, "10 B"); // 2 digits min
        assert_fmt!(99, Unit::Bytes, Standard::SI, true, "99 B"); // 2 digits max
        assert_fmt!(100, Unit::Bytes, Standard::SI, true, "100 B"); // 3 digits min
        assert_fmt!(999, Unit::Bytes, Standard::SI, true, "999 B"); // 3 digits max
    }

    #[test]
    fn test_display_trait() {
        let fmt = ByteFormatter::new()
            .unit(Unit::Bytes)
            .standard(Standard::Binary)
            .space(true)
            .format(1_048_576);

        // This implicitly calls the `Display` trait implementation!
        let output = format!("{fmt}");

        assert_eq!(output, "1.00 MiB");
    }
}