humanize_proper 0.1.2

Dependency-free, no_std formatting of numbers with SI/binary unit prefixes and of durations
Documentation
//! Human readable formatting of numbers and durations. No dependencies, `no_std`, no allocation,
//! no `unsafe`.
//!
//! ```
//! # use humanize_proper::{bin, dur};
//! println!("downloaded {} in {}", bin(4_823_512), dur(93));
//! // downloaded 4.6MiB in 01m33s
//! # assert_eq!(bin(4_823_512).to_string(), "4.6MiB");
//! # assert_eq!(dur(93).to_string(), "01m33s");
//! ```
//!
//! # Numbers
//!
//! A large number is scaled down until it fits into a few digits, and a unit prefix carries the
//! rest of the magnitude. Which prefix system is the right one depends on what is being counted, so
//! both are available and neither is a global setting:
//!
//! - decimal (metric, factor 1000) with the prefixes `k M G T P E Z Y R Q`, for disk capacities,
//!   data rates, frequencies and everything else the SI touches: [`dec`], [`NumFmt::dec`].
//! - binary (factor 1024) with the prefixes `Ki Mi Gi Ti Pi Ei Zi Yi Ri Qi`, for file sizes, memory
//!   and everything a computer counts in powers of two: [`bin`], [`NumFmt::bin`].
//!
//! ```
//! # use humanize_proper::{bin, dec};
//! // A file on disk, the way `ls -lh` shows it.
//! println!("archive.tar.zst  {}", bin(4_823_512));
//! // archive.tar.zst  4.6MiB
//!
//! // A disk's capacity, the way the vendor prints it on the box.
//! println!("capacity: {}", dec(2_000_398_934_016u64));
//! // capacity: 2TB
//! # assert_eq!(bin(4_823_512).to_string(), "4.6MiB");
//! # assert_eq!(dec(2_000_398_934_016u64).to_string(), "2TB");
//! ```
//!
//! Byte formatting is the default. [`bin_no_unit`] and [`dec_no_unit`] drop the trailing `B`, and
//! [`NumFmt::unit`] replaces it with something else:
//!
//! ```
//! # use humanize_proper::{dec_no_unit, NumFmt};
//! println!("{} rows imported", dec_no_unit(18_500_000));
//! // 18.5M rows imported
//!
//! println!("clock: {}", NumFmt::dec().unit("Hz").fmt(4_700_000_000u64));
//! // clock: 4.7GHz
//! # assert_eq!(dec_no_unit(18_500_000).to_string(), "18.5M");
//! # assert_eq!(NumFmt::dec().unit("Hz").fmt(4_700_000_000u64).to_string(), "4.7GHz");
//! ```
//!
//! [`NumFmt`] is `Copy` and all of its builder methods are `const`, so a format used in several
//! places can live in a constant:
//!
//! ```
//! # use humanize_proper::NumFmt;
//! const RATE: NumFmt = NumFmt::dec().unit("B/s").space(true);
//!
//! println!("throughput: {}", RATE.fmt(2_411_756));
//! // throughput: 2.41 MB/s
//! # assert_eq!(RATE.fmt(2_411_756).to_string(), "2.41 MB/s");
//! ```
//!
//! Values below 1 print as a fraction of the unit, which is what a byte count wants. For measured
//! quantities, [`NumFmt::small_prefixes`] switches them to the SI submultiples
//! `m ยต n p f a z y r q`:
//!
//! ```
//! # use humanize_proper::NumFmt;
//! const VOLT: NumFmt = NumFmt::dec().unit("V").small_prefixes(true);
//!
//! println!("offset: {}", VOLT.fmt(0.0125));
//! // offset: 12.5mV
//!
//! println!("noise floor: {}", VOLT.fmt(0.000_000_47));
//! // noise floor: 470nV
//! # assert_eq!(VOLT.fmt(0.0125).to_string(), "12.5mV");
//! # assert_eq!(VOLT.fmt(0.000_000_47).to_string(), "470nV");
//! ```
//!
//! Integers are scaled with exact `u128` arithmetic and never take a detour through `f64`, so
//! rounding rolls over into the next prefix where it should, and the extremes stay precise:
//!
//! ```
//! # use humanize_proper::{bin, dec};
//! println!("{} {}", dec(999_999), bin(u64::MAX));
//! // 1MB 16EiB
//! # assert_eq!(format!("{} {}", dec(999_999), bin(u64::MAX)), "1MB 16EiB");
//! ```
//!
//! Every primitive integer type plus `f32` and `f64` is accepted, through [`ToValue`].
//!
//! # Durations
//!
//! The default style is `32y007d_05h01m05s`: years and days, then hours, minutes and seconds, with
//! `_` between the two groups. Leading units that are zero are dropped, so a short duration stays
//! short.
//!
//! ```
//! # use humanize_proper::dur;
//! println!("uptime: {}", dur(3665));
//! // uptime: 01h01m05s
//! # assert_eq!(dur(3665).to_string(), "01h01m05s");
//! ```
//!
//! Zero padding keeps columns aligned, which is what a log or a table wants. In a sentence, trim it
//! away with [`Zeros`], and cut the display off at the unit that carries the message with
//! [`DurFmt::smallest`]:
//!
//! ```
//! # use humanize_proper::{DurFmt, TimeUnit, Zeros};
//! const REMAINING: DurFmt = DurFmt::new().zeros(Zeros::TrimLargest).smallest(TimeUnit::Day);
//!
//! println!("certificate expires in {}", REMAINING.fmt(7_776_000));
//! // certificate expires in 90d
//!
//! println!("took {}", DurFmt::new().zeros(Zeros::TrimAll).fmt(3665));
//! // took 1h1m5s
//! # assert_eq!(REMAINING.fmt(7_776_000).to_string(), "90d");
//! # assert_eq!(DurFmt::new().zeros(Zeros::TrimAll).fmt(3665).to_string(), "1h1m5s");
//! ```
//!
//! For timings, the seconds field takes a fraction, selected with [`Frac`].
//! [`core::time::Duration`] is accepted directly; for anything finer than nanoseconds there is
//! [`Dur`], which resolves down to attoseconds:
//!
//! ```
//! # use core::time::Duration;
//! # use humanize_proper::{dur, Dur, DurFmt, Frac};
//! println!("{}", dur(Duration::from_millis(90_500)));
//! // 01m30s
//!
//! let elapsed = Dur::from_nanos(65_123_456_789);
//!
//! println!("finished in {}", DurFmt::new().frac(Frac::Millis).fmt(elapsed));
//! // finished in 01m05.123s
//!
//! println!("one attosecond is {}", DurFmt::new().frac(Frac::Attos).fmt(Dur::from_attos(1)));
//! // one attosecond is 00.000000000000000001s
//! # assert_eq!(dur(Duration::from_millis(90_500)).to_string(), "01m30s");
//! # assert_eq!(DurFmt::new().frac(Frac::Millis).fmt(elapsed).to_string(), "01m05.123s");
//! # let attos = DurFmt::new().frac(Frac::Attos).fmt(Dur::from_attos(1)).to_string();
//! # assert_eq!(attos, "00.000000000000000001s");
//! ```
//!
//! A year is 365.2425 days, which is exactly `31_556_952` seconds, so day counts run `0..=365` and
//! the arithmetic stays exact at second granularity. Override it with [`DurFmt::secs_per_year`].
//!
//! # Display behavior
//!
//! Both formatters return values implementing [`core::fmt::Display`] that render through
//! [`core::fmt::Formatter::pad`], so width, alignment and fill work as usual and nothing is
//! allocated on the way:
//!
//! ```
//! # use humanize_proper::{bin, dur};
//! for (name, size, age) in [("index.db", 1_048_576, 90), ("wal.log", 6_291_456, 3_600)] {
//!     println!("{name:<10}{:>9}{:>11}", bin(size), dur(age));
//! }
//! // index.db       1MiB     01m30s
//! // wal.log        6MiB  01h00m00s
//! # assert_eq!(format!("{:>9}", bin(1_048_576)), "     1MiB");
//! # assert_eq!(format!("{:>11}", dur(3_600)), "  01h00m00s");
//! ```
//!
//! # Scope
//!
//! Deliberately out of scope: localization such as a decimal comma or grouped integer digits, and
//! parsing, since this library only formats.

#![no_std]
#![forbid(unsafe_code)]
#![warn(missing_docs, missing_debug_implementations)]

mod buf;
mod duration;
mod num;
mod value;

pub use duration::{Dur, DurFmt, FmtDur, Frac, TimeUnit, ToDuration, Zeros, ATTOS_PER_SEC};
pub use num::{Base, Num, NumFmt, Prefixes};
pub use value::{ToValue, Value};

/// Formats a byte count with binary prefixes, e.g. `1.5KiB`.
///
/// ```
/// # use humanize_proper::bin;
/// assert_eq!(bin(1_048_576).to_string(), "1MiB");
/// ```
pub fn bin<V: ToValue>(value: V) -> Num {
    NumFmt::bin().fmt(value)
}

/// Formats a byte count with SI prefixes, e.g. `1.5kB`.
///
/// ```
/// # use humanize_proper::dec;
/// assert_eq!(dec(1_000_000).to_string(), "1MB");
/// ```
pub fn dec<V: ToValue>(value: V) -> Num {
    NumFmt::dec().fmt(value)
}

/// Formats a number with binary prefixes and no unit, e.g. `1.5Ki`.
///
/// ```
/// # use humanize_proper::bin_no_unit;
/// assert_eq!(bin_no_unit(1_048_576).to_string(), "1Mi");
/// ```
pub fn bin_no_unit<V: ToValue>(value: V) -> Num {
    NumFmt::bin().no_unit().fmt(value)
}

/// Formats a number with SI prefixes and no unit, e.g. `1.5k`.
///
/// ```
/// # use humanize_proper::dec_no_unit;
/// assert_eq!(dec_no_unit(1_000_000).to_string(), "1M");
/// ```
pub fn dec_no_unit<V: ToValue>(value: V) -> Num {
    NumFmt::dec().no_unit().fmt(value)
}

/// Formats a duration in the default style, e.g. `32y007d_05h01m05s`.
///
/// ```
/// # use humanize_proper::dur;
/// assert_eq!(dur(90).to_string(), "01m30s");
/// ```
pub fn dur<D: ToDuration>(duration: D) -> FmtDur {
    DurFmt::new().fmt(duration)
}