wdxtools 0.4.2

Everyday formatting tools for the command line
Documentation
//! Numeric formatting utilities.
//!
//! [`abbreviate`] is a port of Laravel Framework's `Number::abbreviate()`.
//! Original source: <https://github.com/laravel/framework/blob/12.x/src/Illuminate/Support/Number.php>
//! Laravel is created by Taylor Otwell and licensed under the MIT License.

mod format;

use format::append_number;

/// Appends a signed integer without going through `core::fmt`.
/// Shared with [`crate::timediff`], which formats unit counts on its hot path.
pub(crate) use format::append_i64 as format_i64;

/// Formatting configuration for [`abbreviate`] and [`for_humans`].
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Config {
    /// Minimum number of decimal places.
    pub precision: i32,
    /// Maximum number of decimal places; negative means unset. Trailing zeros
    /// between `precision` and `max_precision` are removed.
    pub max_precision: i32,
}

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

impl Config {
    pub const fn new() -> Self {
        Self {
            precision: 0,
            max_precision: -1,
        }
    }

    pub const fn precision(mut self, p: i32) -> Self {
        self.precision = p;
        self
    }

    pub const fn max_precision(mut self, p: i32) -> Self {
        self.max_precision = p;
        self
    }
}

/// Pre-computed powers of 10 for common magnitudes.
const POWERS: [f64; 6] = [1.0, 1e3, 1e6, 1e9, 1e12, 1e15];

/// Suffix tables indexed by `display_exponent / 3` for O(1) lookup.
const SHORT_SUFFIXES: [&str; 6] = ["", "K", "M", "B", "T", "Q"];
const LONG_SUFFIXES: [&str; 6] = [
    "",
    " thousand",
    " million",
    " billion",
    " trillion",
    " quadrillion",
];

/// Formats a number into a short human-readable string.
///
/// ```
/// use wdxtools::number::{abbreviate, Config};
/// assert_eq!(abbreviate(1000.0, Config::new()), "1K");
/// assert_eq!(abbreviate(489939.0, Config::new().max_precision(2)), "489.94K");
/// ```
pub fn abbreviate(number: f64, cfg: Config) -> String {
    let mut s = String::with_capacity(24);
    append_abbreviate(&mut s, number, cfg);
    s
}

/// Formats a number into a long human-readable string.
///
/// ```
/// use wdxtools::number::{for_humans, Config};
/// assert_eq!(for_humans(1000000.0, Config::new()), "1 million");
/// ```
pub fn for_humans(number: f64, cfg: Config) -> String {
    let mut s = String::with_capacity(32);
    append_for_humans(&mut s, number, cfg);
    s
}

/// Allocation-free counterpart of [`abbreviate`] for hot loops.
#[inline]
pub fn append_abbreviate(out: &mut String, number: f64, cfg: Config) {
    append_with(out, number, cfg, &SHORT_SUFFIXES)
}

/// Allocation-free counterpart of [`for_humans`] for hot loops.
#[inline]
pub fn append_for_humans(out: &mut String, number: f64, cfg: Config) {
    append_with(out, number, cfg, &LONG_SUFFIXES)
}

fn append_with(out: &mut String, number: f64, cfg: Config, units: &[&str; 6]) {
    let number = if number < 0.0 {
        out.push('-');
        -number
    } else {
        number
    };
    summarize(out, number, cfg, units)
}

/// Core formatting logic, ported from Laravel's `Number::summarize()`.
///
/// Uses comparison-based exponent detection (no `log10`) and a pre-computed
/// power table (no `powi`) for maximum throughput.
fn summarize(out: &mut String, number: f64, cfg: Config, units: &[&str; 6]) {
    if number == 0.0 {
        return append_number(out, 0.0, cfg.precision, cfg.max_precision);
    }

    // For numbers >= 1Q (1e15), recurse once and append the quadrillion suffix.
    if number >= 1e15 {
        summarize(out, number / 1e15, cfg, units);
        out.push_str(units[5]);
        return;
    }

    // At most 4 float comparisons, exact at IEEE 754 boundaries.
    let idx = if number >= 1e12 {
        4
    } else if number >= 1e9 {
        3
    } else if number >= 1e6 {
        2
    } else if number >= 1e3 {
        1
    } else {
        return append_number(out, number, cfg.precision, cfg.max_precision);
    };

    append_number(out, number / POWERS[idx], cfg.precision, cfg.max_precision);
    out.push_str(units[idx]);
}

/// Formats a bare number with the given precision, bypassing suffix selection.
/// Exposed for benchmarks and differential tests against the reference formatter.
#[doc(hidden)]
pub fn format_number(number: f64, precision: i32, max_precision: i32) -> String {
    let mut s = String::with_capacity(24);
    append_number(&mut s, number, precision, max_precision);
    s
}