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 SUB_LEN: usize = 10;
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"];
const SUB: [&str; SUB_LEN] = ["m", "µ", "n", "p", "f", "a", "z", "y", "r", "q"];
const MICRO_IDX: i32 = -2;
const MAX_IDX: i32 = TABLE_LEN as i32 - 1;
const MIN_IDX: i32 = -(SUB_LEN as i32);
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Base {
Bin,
Dec,
}
impl Base {
const fn factor(self) -> u128 {
match self {
Self::Bin => 1024,
Self::Dec => 1000,
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Prefixes {
Iec,
Jedec,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[must_use]
pub struct NumFmt {
base: Base,
prefixes: Prefixes,
unit: &'static str,
space: bool,
sig: u8,
trim: bool,
small: bool,
ascii_micro: bool,
}
impl NumFmt {
pub const fn bin() -> Self {
Self {
base: Base::Bin,
prefixes: Prefixes::Iec,
unit: "B",
space: false,
sig: 3,
trim: true,
small: false,
ascii_micro: false,
}
}
pub const fn dec() -> Self {
Self {
base: Base::Dec,
prefixes: Prefixes::Iec,
unit: "B",
space: false,
sig: 3,
trim: true,
small: false,
ascii_micro: false,
}
}
pub const fn base(mut self, base: Base) -> Self {
self.base = base;
self
}
pub const fn space(mut self, space: bool) -> Self {
self.space = space;
self
}
pub const fn unit(mut self, unit: &'static str) -> Self {
self.unit = unit;
self
}
pub const fn no_unit(self) -> Self {
self.unit("")
}
pub const fn prefixes(mut self, prefixes: Prefixes) -> Self {
self.prefixes = prefixes;
self
}
pub const fn iec(self) -> Self {
self.prefixes(Prefixes::Iec)
}
pub const fn jedec(self) -> Self {
self.prefixes(Prefixes::Jedec)
}
pub const fn sig_digits(mut self, sig: u8) -> Self {
self.sig = if sig < 1 {
1
} else if sig > 15 {
15
} else {
sig
};
self
}
pub const fn trim_zeros(mut self, trim: bool) -> Self {
self.trim = trim;
self
}
pub const fn small_prefixes(mut self, small: bool) -> Self {
self.small = small;
self
}
pub const fn ascii_micro(mut self, ascii: bool) -> Self {
self.ascii_micro = ascii;
self
}
pub fn fmt<V: ToValue>(self, value: V) -> Num {
Num { cfg: self, val: value.to_value() }
}
const fn decimals_for(&self, integer_digits: u32) -> u32 {
(self.sig as u32).saturating_sub(integer_digits)
}
const fn scales_down(&self) -> bool {
self.small && matches!(self.base, Base::Dec)
}
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,
}
}
const fn prefix(&self, idx: i32) -> &'static str {
if idx == MICRO_IDX && self.ascii_micro {
"u"
} else if idx < 0 {
SUB[(-idx - 1) as usize]
} else {
self.table()[idx as usize]
}
}
}
#[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))
}
}
#[derive(Clone, Copy)]
enum Magnitude {
Int(u128),
Float(f64),
}
#[derive(Clone, Copy)]
enum Layout {
Scaled { scaled: u128, decimals: u32, idx: i32 },
Plain { mantissa: f64, idx: i32 },
}
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 {
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),
}
}
fn layout_int(cfg: &NumFmt, v: u128) -> Option<Layout> {
let base = cfg.base.factor();
let mut idx = 0;
let mut div = 1u128;
while idx < MAX_IDX && 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 < MAX_IDX && 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)
}
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 < MAX_IDX && mantissa >= base_f {
mantissa /= base_f;
idx += 1;
}
if cfg.scales_down() {
while idx > MIN_IDX && mantissa > 0.0 && mantissa < 1.0 {
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 < MAX_IDX && rolls_over(scaled, base, decimals) {
mantissa /= base_f;
idx += 1;
continue;
}
return Layout::Scaled { scaled, decimals, idx };
}
}
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: i32, out: &mut dyn Write) -> fmt::Result {
let prefix = cfg.prefix(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 small_prefixes_scale_values_below_one() {
const V: NumFmt = NumFmt::dec().unit("V").small_prefixes(true);
let cases: [(f64, &str); 12] = [
(1.0, "1V"),
(0.5, "500mV"),
(0.0125, "12.5mV"),
(1e-3, "1mV"),
(9.99e-4, "999µV"),
(4.7e-7, "470nV"),
(1e-12, "1pV"),
(1e-15, "1fV"),
(1e-18, "1aV"),
(1e-21, "1zV"),
(1e-24, "1yV"),
(1e-30, "1qV"),
];
for (input, expected) in cases {
assert_eq!(V.fmt(input).to_string(), expected, "{input:e}");
}
assert_eq!(V.fmt(-0.0125).to_string(), "-12.5mV");
assert_eq!(V.fmt(0.0).to_string(), "0V");
}
#[test]
fn small_prefixes_roll_over_upward_when_rounding_reaches_the_next_one() {
const V: NumFmt = NumFmt::dec().unit("V").small_prefixes(true);
assert_eq!(V.fmt(9.999e-4).to_string(), "1mV");
assert_eq!(V.fmt(0.9999).to_string(), "1V");
}
#[test]
fn magnitudes_below_the_smallest_submultiple_round_to_zero() {
const V: NumFmt = NumFmt::dec().unit("V").small_prefixes(true);
assert_eq!(V.fmt(1e-31).to_string(), "0.1qV");
assert_eq!(V.fmt(1e-40).to_string(), "0qV");
assert_eq!(V.fmt(f64::MIN_POSITIVE).to_string(), "0qV");
}
#[test]
fn ascii_micro_replaces_only_the_micro_prefix() {
const S: NumFmt = NumFmt::dec().unit("s").small_prefixes(true).ascii_micro(true);
assert_eq!(S.fmt(2.5e-6).to_string(), "2.5us");
assert_eq!(S.fmt(2.5e-3).to_string(), "2.5ms");
assert_eq!(S.fmt(2.5e-9).to_string(), "2.5ns");
assert_eq!(S.fmt(2.5e6).to_string(), "2.5Ms");
let rendered = S.fmt(2.5e-6).to_string();
assert!(rendered.is_ascii(), "{rendered}");
}
#[test]
fn small_prefixes_are_opt_in_and_decimal_only() {
assert_eq!(NumFmt::dec().fmt(0.0125).to_string(), "0.01B");
assert_eq!(NumFmt::bin().small_prefixes(true).fmt(0.0125).to_string(), "0.01B");
assert_eq!(NumFmt::dec().small_prefixes(true).fmt(0.0125).to_string(), "12.5mB");
}
#[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***");
}
}