humanize_proper 0.1.2

Dependency-free, no_std formatting of numbers with SI/binary unit prefixes and of durations
Documentation
//! Tests of the public API as a user of the crate sees it.

use std::fmt::Write as _;
use std::panic::RefUnwindSafe;
use std::time::Duration;

use humanize_proper::{
    bin, bin_no_unit, dec, dec_no_unit, dur, Base, Dur, DurFmt, FmtDur, Frac, Num, NumFmt,
    Prefixes, TimeUnit, Zeros,
};

const BYTES: NumFmt = NumFmt::bin().space(true);
const UPTIME: DurFmt = DurFmt::new().zeros(Zeros::TrimLargest).smallest(TimeUnit::Min);

#[test]
fn configurations_can_be_constants() {
    assert_eq!(BYTES.fmt(1536).to_string(), "1.5 KiB");
    assert_eq!(UPTIME.fmt(3665u64).to_string(), "1h01m");
}

#[test]
fn free_functions_cover_the_common_cases() {
    assert_eq!(bin(1536).to_string(), "1.5KiB");
    assert_eq!(dec(1500).to_string(), "1.5kB");
    assert_eq!(bin_no_unit(1536).to_string(), "1.5Ki");
    assert_eq!(dec_no_unit(1500).to_string(), "1.5k");
    assert_eq!(dur(90).to_string(), "01m30s");
}

#[test]
fn every_prefix_of_both_tables_is_reachable() {
    let dec_expected = ["1B", "1kB", "1MB", "1GB", "1TB", "1PB", "1EB", "1ZB", "1YB", "1RB", "1QB"];
    let bin_expected =
        ["1B", "1KiB", "1MiB", "1GiB", "1TiB", "1PiB", "1EiB", "1ZiB", "1YiB", "1RiB", "1QiB"];
    let mut dec_value = 1u128;
    let mut bin_value = 1u128;
    for i in 0..11 {
        assert_eq!(dec(dec_value).to_string(), dec_expected[i], "1000^{i}");
        assert_eq!(bin(bin_value).to_string(), bin_expected[i], "1024^{i}");
        dec_value *= 1000;
        bin_value *= 1024;
    }
}

#[test]
fn jedec_spells_binary_prefixes_like_decimal_ones() {
    assert_eq!(NumFmt::bin().jedec().fmt(1_048_576).to_string(), "1MB");
    assert_eq!(NumFmt::bin().iec().fmt(1_048_576).to_string(), "1MiB");
    assert_eq!(NumFmt::dec().prefixes(Prefixes::Jedec).fmt(1_000_000).to_string(), "1MB");
}

#[test]
fn base_can_be_switched_on_an_existing_config() {
    let cfg = NumFmt::dec().unit("Hz").space(true);
    assert_eq!(cfg.fmt(1_500_000).to_string(), "1.5 MHz");
    assert_eq!(cfg.base(Base::Bin).fmt(1_572_864).to_string(), "1.5 MiHz");
}

#[test]
fn all_integer_types_are_accepted() {
    assert_eq!(bin(1536u16).to_string(), "1.5KiB");
    assert_eq!(bin(1536i32).to_string(), "1.5KiB");
    assert_eq!(bin(1536u64).to_string(), "1.5KiB");
    assert_eq!(bin(1536i128).to_string(), "1.5KiB");
    assert_eq!(bin(1536usize).to_string(), "1.5KiB");
    assert_eq!(bin(1536.0f32).to_string(), "1.5KiB");
    assert_eq!(bin(1536.0f64).to_string(), "1.5KiB");
}

#[test]
fn durations_accept_std_and_own_types() {
    assert_eq!(dur(Duration::from_secs(90)).to_string(), "01m30s");
    assert_eq!(dur(Dur::from_millis(90_500)).to_string(), "01m30s");
    assert_eq!(dur(90u32).to_string(), "01m30s");
    assert_eq!(dur(-90i64).to_string(), "-01m30s");
    assert_eq!(dur(90.5f64).to_string(), "01m30s");
}

#[test]
fn sub_nanosecond_precision_survives_formatting() {
    let cfg = DurFmt::new().frac(Frac::Attos);
    assert_eq!(cfg.fmt(Dur::from_attos(1)).to_string(), "00.000000000000000001s");
    assert_eq!(cfg.fmt(Dur::from_femtos(1)).to_string(), "00.000000000000001000s");
    assert_eq!(cfg.fmt(Dur::from_picos(1)).to_string(), "00.000000000001000000s");
    assert_eq!(
        cfg.frac_sep(Some("_")).fmt(Dur::from_picos(1)).to_string(),
        "00.000_000_000_001_000_000s"
    );
}

#[test]
fn writing_into_a_buffer_needs_no_intermediate_string() {
    let mut line = String::new();
    write!(line, "{:>10} in {:>12}", bin(1_073_741_824u64), dur(1_000_000_000u64)).unwrap();
    assert_eq!(line, "      1GiB in 31y251d_13h21m28s");
}

/// The formatters hold plain data and keep no state across a `Display` call, so a configuration can
/// be shared. These bounds are auto traits, so a cached field or an interior mutability escape
/// hatch sneaking into any of these types would fail the build here.
fn assert_shareable<T: Send + Sync + Copy + RefUnwindSafe + 'static>() {}

#[test]
fn every_public_type_is_shareable_across_threads() {
    assert_shareable::<NumFmt>();
    assert_shareable::<DurFmt>();
    assert_shareable::<Num>();
    assert_shareable::<FmtDur>();
    assert_shareable::<Dur>();
    assert_shareable::<Base>();
    assert_shareable::<Prefixes>();
    assert_shareable::<TimeUnit>();
    assert_shareable::<Zeros>();
    assert_shareable::<Frac>();
}

#[test]
fn one_shared_config_formats_identically_from_many_threads() {
    let expected: Vec<String> =
        (0..2_000).map(|i| BYTES.fmt(i * 1_048_576u64).to_string()).collect();
    let workers: Vec<_> = (0..8)
        .map(|_| {
            std::thread::spawn(|| {
                (0..2_000).map(|i| BYTES.fmt(i * 1_048_576u64).to_string()).collect::<Vec<_>>()
            })
        })
        .collect();
    for worker in workers {
        assert_eq!(worker.join().unwrap(), expected);
    }
}

#[test]
fn small_prefixes_extend_the_table_below_one() {
    const OHM: NumFmt = NumFmt::dec().unit("Ω").small_prefixes(true).space(true);
    assert_eq!(OHM.fmt(0.047).to_string(), "47 mΩ");
    assert_eq!(format!("{:>8}", OHM.fmt(0.000_002_2)), "  2.2 µΩ");

    let expected = ["1V", "1mV", "1µV", "1nV", "1pV", "1fV", "1aV", "1zV", "1yV", "1rV", "1qV"];
    let cfg = NumFmt::dec().unit("V").small_prefixes(true);
    let mut value = 1.0f64;
    for (i, want) in expected.iter().enumerate() {
        assert_eq!(cfg.fmt(value).to_string(), *want, "1000^-{i}");
        value /= 1000.0;
    }
}

#[test]
fn a_table_lines_up() {
    let sizes = [0u64, 999, 1024, 1_048_576, u64::MAX];
    let rendered: Vec<String> = sizes.iter().map(|s| format!("{:>9}", bin(*s))).collect();
    assert_eq!(rendered, ["       0B", "     999B", "     1KiB", "     1MiB", "    16EiB"]);
}