wdxtools 0.4.2

Everyday formatting tools for the command line
Documentation
use std::fmt::Write as _;

/// Powers of 10 for precision lookups. Avoids `powi` for the common case.
const POW10: [f64; 11] = [1.0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10];

/// Integer powers of 10 for the fixed-point fast path.
const IPOW10: [i64; 16] = [
    1,
    1e1 as i64,
    1e2 as i64,
    1e3 as i64,
    1e4 as i64,
    1e5 as i64,
    1e6 as i64,
    1e7 as i64,
    1e8 as i64,
    1e9 as i64,
    1e10 as i64,
    1e11 as i64,
    1e12 as i64,
    1e13 as i64,
    1e14 as i64,
    1e15 as i64,
];

/// `summarize` only ever feeds `append_number` values in [0, 1000), so scaling
/// by 10^p fits comfortably in i64 for p <= 15. Larger precision falls back to
/// `core::fmt`, which is off the hot path.
const FAST_MAX_PRECISION: i32 = 15;

#[inline]
pub(crate) fn pow10_factor(n: i32) -> f64 {
    if n >= 0 && (n as usize) < POW10.len() {
        POW10[n as usize]
    } else {
        10f64.powi(n)
    }
}

/// Appends `number` with the given precision and maxPrecision.
///
/// `precision` is the minimum number of decimal places; `max_precision` the
/// maximum (trailing zeros trimmed), or negative when unset.
///
/// Rounding is half-away-from-zero (`f64::round`) for PHP parity, then digits
/// are emitted from a scaled integer rather than through the shortest-
/// representation machinery of `core::fmt`.
pub(crate) fn append_number(out: &mut String, number: f64, precision: i32, max_precision: i32) {
    if max_precision >= 0 {
        append_with_max_precision(out, number, precision, max_precision)
    } else {
        append_with_precision(out, number, precision)
    }
}

fn append_with_precision(out: &mut String, number: f64, precision: i32) {
    if precision <= 0 {
        append_i64(out, number.round() as i64);
        return;
    }
    if precision > FAST_MAX_PRECISION {
        let factor = pow10_factor(precision);
        let rounded = (number * factor).round() / factor;
        let _ = write!(out, "{:.*}", precision as usize, rounded);
        return;
    }
    let scaled = (number * pow10_factor(precision)).round() as i64;
    append_fixed(out, scaled, precision as u32);
}

fn append_with_max_precision(out: &mut String, number: f64, precision: i32, max_precision: i32) {
    if max_precision > FAST_MAX_PRECISION {
        return append_with_max_precision_slow(out, number, precision, max_precision);
    }

    let mut scaled = (number * pow10_factor(max_precision)).round() as i64;
    let mut p = max_precision;

    // Trim trailing zeros arithmetically, keeping at least `precision` decimals.
    let floor = precision.max(0);
    while p > floor && scaled % 10 == 0 {
        scaled /= 10;
        p -= 1;
    }

    if p <= 0 {
        append_i64(out, scaled);
    } else {
        append_fixed(out, scaled, p as u32);
    }
}

fn append_with_max_precision_slow(
    out: &mut String,
    number: f64,
    precision: i32,
    max_precision: i32,
) {
    let factor = pow10_factor(max_precision);
    let rounded = (number * factor).round() / factor;

    let start = out.len();
    let _ = write!(out, "{:.*}", max_precision as usize, rounded);

    let Some(dot) = out.as_bytes()[start..]
        .iter()
        .position(|&c| c == b'.')
        .map(|i| i + start)
    else {
        return;
    };

    let min_len = if precision <= 0 {
        dot
    } else {
        dot + 1 + precision as usize
    };

    let mut end = out.len();
    while end > min_len && out.as_bytes()[end - 1] == b'0' {
        end -= 1;
    }
    if end > 0 && out.as_bytes()[end - 1] == b'.' && precision <= 0 {
        end -= 1;
    }
    out.truncate(end);
}

/// Appends `scaled / 10^decimals` in fixed-point notation: `(48994, 2)` → `"489.94"`.
fn append_fixed(out: &mut String, scaled: i64, decimals: u32) {
    debug_assert!(scaled >= 0 && decimals >= 1);
    let pow = IPOW10[decimals as usize];
    let (int, mut frac) = (scaled / pow, scaled % pow);

    append_i64(out, int);
    out.push('.');

    let mut buf = [b'0'; 16];
    let mut i = buf.len();
    for _ in 0..decimals {
        i -= 1;
        buf[i] = b'0' + (frac % 10) as u8;
        frac /= 10;
    }
    out.push_str(unsafe { std::str::from_utf8_unchecked(&buf[i..]) });
}

/// Manual i64 formatting; the counterpart of Go's `strconv.AppendInt`.
pub(crate) fn append_i64(out: &mut String, mut v: i64) {
    if v == 0 {
        out.push('0');
        return;
    }
    if v < 0 {
        out.push('-');
        v = -v;
    }
    let mut buf = [0u8; 20];
    let mut i = buf.len();
    while v > 0 {
        i -= 1;
        buf[i] = b'0' + (v % 10) as u8;
        v /= 10;
    }
    out.push_str(unsafe { std::str::from_utf8_unchecked(&buf[i..]) });
}