humanize_proper 0.1.2

Dependency-free, no_std formatting of numbers with SI/binary unit prefixes and of durations
Documentation
//! A fixed size stack string used to buffer rendered output so that
//! [`core::fmt::Formatter::pad`] can apply width, alignment and fill.

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

/// Capacity of the buffer both formatters render into. Comfortably above the longest output they
/// can produce, which is a duration with 18 fraction digits and separators.
const RENDER_CAPACITY: usize = 128;

/// Write target with a compile time capacity. Writes beyond the capacity are dropped and recorded
/// in the overflow flag instead of failing, so that rendering is total.
pub(crate) struct StackStr<const N: usize> {
    buf: [u8; N],
    len: usize,
    overflow: bool,
}

impl<const N: usize> StackStr<N> {
    pub(crate) const fn new() -> Self {
        Self { buf: [0; N], len: 0, overflow: false }
    }

    pub(crate) fn as_str(&self) -> &str {
        core::str::from_utf8(&self.buf[..self.len]).unwrap_or("")
    }

    pub(crate) const fn overflowed(&self) -> bool {
        self.overflow
    }
}

impl<const N: usize> Write for StackStr<N> {
    fn write_str(&mut self, s: &str) -> fmt::Result {
        let bytes = s.as_bytes();
        if self.len + bytes.len() > N {
            self.overflow = true;
            return Ok(());
        }
        self.buf[self.len..self.len + bytes.len()].copy_from_slice(bytes);
        self.len += bytes.len();
        Ok(())
    }
}

/// Renders through a stack buffer and emits the result with [`Formatter::pad`], so that width,
/// alignment and fill of the format specifier are honored. If the output does not fit the buffer,
/// it is written straight to the formatter, giving up the padding rather than the output.
pub(crate) fn pad_rendered(
    f: &mut Formatter<'_>,
    render: impl Fn(&mut dyn Write) -> fmt::Result,
) -> fmt::Result {
    let mut buf = StackStr::<RENDER_CAPACITY>::new();
    render(&mut buf)?;
    if buf.overflowed() {
        render(f)
    } else {
        f.pad(buf.as_str())
    }
}

/// Powers of ten as `u128`, indexed by the exponent.
pub(crate) const POW10: [u128; 39] = {
    let mut table = [1u128; 39];
    let mut i = 1;
    while i < 39 {
        table[i] = table[i - 1] * 10;
        i += 1;
    }
    table
};

/// Number of decimal digits of `n`, at least 1.
pub(crate) const fn digits_of(mut n: u128) -> u32 {
    let mut d = 1;
    while n >= 10 {
        n /= 10;
        d += 1;
    }
    d
}

/// Writes `value` right aligned in `width` columns, padded with zeros.
pub(crate) fn write_zero_padded(out: &mut dyn Write, value: u128, width: usize) -> fmt::Result {
    write!(out, "{value:0width$}")
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn buffer_reports_overflow_instead_of_failing() {
        let mut buf = StackStr::<4>::new();
        assert!(write!(buf, "ab").is_ok());
        assert!(write!(buf, "cde").is_ok());
        assert!(buf.overflowed());
        assert_eq!(buf.as_str(), "ab");
    }

    #[test]
    fn pow10_and_digits_agree() {
        assert_eq!(POW10[0], 1);
        assert_eq!(POW10[18], 1_000_000_000_000_000_000);
        assert_eq!(digits_of(0), 1);
        assert_eq!(digits_of(9), 1);
        assert_eq!(digits_of(10), 2);
        assert_eq!(digits_of(u128::MAX), 39);
    }
}