use core::fmt::{self, Display, Formatter, Write};
use crate::buf::{pad_rendered, write_zero_padded, StackStr, POW10};
pub const ATTOS_PER_SEC: u64 = 1_000_000_000_000_000_000;
const SECS_PER_GREGORIAN_YEAR: u64 = 31_556_952;
const UNIT_COUNT: usize = 5;
const LETTERS: [char; UNIT_COUNT] = ['y', 'd', 'h', 'm', 's'];
const WIDTHS: [usize; UNIT_COUNT] = [1, 3, 2, 2, 2];
const SECS_PER_UNIT: [u64; UNIT_COUNT - 1] = [86_400, 3_600, 60, 1];
const TIME_GROUP: usize = TimeUnit::Hour.index();
const SEC: usize = TimeUnit::Sec.index();
const MAX_FRAC_DIGITS: u8 = Frac::Attos.digits();
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[must_use]
pub struct Dur {
neg: bool,
secs: u64,
attos: u64,
}
const fn saturate(v: u128) -> u64 {
if v > u64::MAX as u128 {
u64::MAX
} else {
v as u64
}
}
impl Dur {
pub const ZERO: Self = Self { neg: false, secs: 0, attos: 0 };
pub const fn from_parts(neg: bool, secs: u64, attos: u64) -> Self {
Self { neg, secs: secs.saturating_add(attos / ATTOS_PER_SEC), attos: attos % ATTOS_PER_SEC }
.normalized()
}
const fn normalized(mut self) -> Self {
self.neg = self.neg && !self.is_zero();
self
}
pub const fn from_secs(secs: u64) -> Self {
Self { neg: false, secs, attos: 0 }
}
pub const fn from_millis(millis: u64) -> Self {
Self::from_subsec(millis as u128, 1_000)
}
pub const fn from_micros(micros: u64) -> Self {
Self::from_subsec(micros as u128, 1_000_000)
}
pub const fn from_nanos(nanos: u64) -> Self {
Self::from_subsec(nanos as u128, 1_000_000_000)
}
pub const fn from_picos(picos: u128) -> Self {
Self::from_subsec(picos, 1_000_000_000_000)
}
pub const fn from_femtos(femtos: u128) -> Self {
Self::from_subsec(femtos, 1_000_000_000_000_000)
}
pub const fn from_attos(attos: u128) -> Self {
Self::from_subsec(attos, ATTOS_PER_SEC as u128)
}
const fn from_subsec(value: u128, per_sec: u128) -> Self {
Self {
neg: false,
secs: saturate(value / per_sec),
attos: (value % per_sec) as u64 * (ATTOS_PER_SEC / per_sec as u64),
}
}
pub fn from_secs_f64(secs: f64) -> Self {
if secs.is_nan() {
return Self::ZERO;
}
let neg = secs < 0.0;
let a = if neg { -secs } else { secs };
let whole = a as u64;
let frac = (a - whole as f64) * ATTOS_PER_SEC as f64;
Self { neg, secs: whole, attos: (frac as u64).min(ATTOS_PER_SEC - 1) }.normalized()
}
pub const fn neg(mut self) -> Self {
self.neg = !self.neg;
self.normalized()
}
pub const fn is_zero(&self) -> bool {
self.secs == 0 && self.attos == 0
}
}
pub trait ToDuration {
fn to_duration(self) -> Dur;
}
impl ToDuration for Dur {
fn to_duration(self) -> Dur {
self
}
}
impl ToDuration for core::time::Duration {
fn to_duration(self) -> Dur {
Dur { neg: false, secs: self.as_secs(), attos: self.subsec_nanos() as u64 * 1_000_000_000 }
}
}
macro_rules! impl_unsigned_secs {
($($t:ty),*) => {$(
impl ToDuration for $t {
fn to_duration(self) -> Dur {
Dur::from_secs(self as u64)
}
}
)*};
}
macro_rules! impl_signed_secs {
($($t:ty),*) => {$(
impl ToDuration for $t {
fn to_duration(self) -> Dur {
Dur { neg: self < 0, secs: (self as i64).unsigned_abs(), attos: 0 }
}
}
)*};
}
impl_unsigned_secs!(u32, u64);
impl_signed_secs!(i32, i64);
impl ToDuration for f64 {
fn to_duration(self) -> Dur {
Dur::from_secs_f64(self)
}
}
impl ToDuration for f32 {
fn to_duration(self) -> Dur {
Dur::from_secs_f64(self as f64)
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum TimeUnit {
Year,
Day,
Hour,
Min,
Sec,
}
impl TimeUnit {
const fn index(self) -> usize {
match self {
Self::Year => 0,
Self::Day => 1,
Self::Hour => 2,
Self::Min => 3,
Self::Sec => 4,
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Zeros {
Pad,
TrimAll,
TrimLargest,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Frac {
Secs,
Millis,
Micros,
Nanos,
Picos,
Femtos,
Attos,
}
impl Frac {
pub const fn digits(self) -> u8 {
match self {
Self::Secs => 0,
Self::Millis => 3,
Self::Micros => 6,
Self::Nanos => 9,
Self::Picos => 12,
Self::Femtos => 15,
Self::Attos => 18,
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[must_use]
pub struct DurFmt {
zeros: Zeros,
frac_digits: u8,
frac_sep: Option<&'static str>,
sep: &'static str,
smallest: TimeUnit,
secs_per_year: u64,
}
impl Default for DurFmt {
fn default() -> Self {
Self::new()
}
}
impl DurFmt {
pub const fn new() -> Self {
Self {
zeros: Zeros::Pad,
frac_digits: 0,
frac_sep: None,
sep: "_",
smallest: TimeUnit::Sec,
secs_per_year: SECS_PER_GREGORIAN_YEAR,
}
}
pub const fn zeros(mut self, zeros: Zeros) -> Self {
self.zeros = zeros;
self
}
pub const fn frac(self, frac: Frac) -> Self {
self.frac_digits(frac.digits())
}
pub const fn frac_digits(mut self, digits: u8) -> Self {
self.frac_digits = if digits > MAX_FRAC_DIGITS { MAX_FRAC_DIGITS } else { digits };
self
}
pub const fn frac_sep(mut self, sep: Option<&'static str>) -> Self {
self.frac_sep = sep;
self
}
pub const fn sep(mut self, sep: &'static str) -> Self {
self.sep = sep;
self
}
pub const fn no_sep(self) -> Self {
self.sep("")
}
pub const fn smallest(mut self, unit: TimeUnit) -> Self {
self.smallest = unit;
self
}
pub const fn secs_per_year(mut self, secs: u64) -> Self {
self.secs_per_year = if secs == 0 { 1 } else { secs };
self
}
pub fn fmt<D: ToDuration>(self, duration: D) -> FmtDur {
FmtDur { cfg: self, dur: duration.to_duration() }
}
}
#[derive(Clone, Copy, Debug)]
#[must_use]
pub struct FmtDur {
cfg: DurFmt,
dur: Dur,
}
impl Display for FmtDur {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
pad_rendered(f, |out| render(&self.cfg, self.dur, out))
}
}
fn split(cfg: &DurFmt, secs: u64) -> [u64; UNIT_COUNT] {
let mut values = [0u64; UNIT_COUNT];
let mut rest = secs;
for (i, per_unit) in core::iter::once(cfg.secs_per_year).chain(SECS_PER_UNIT).enumerate() {
values[i] = rest / per_unit;
rest %= per_unit;
}
values
}
fn render(cfg: &DurFmt, d: Dur, out: &mut dyn Write) -> fmt::Result {
let values = split(cfg, d.secs);
let last = cfg.smallest.index();
let first = values[..=last].iter().position(|value| *value != 0).unwrap_or(last);
if d.neg && !d.is_zero() {
out.write_char('-')?;
}
for i in first..=last {
if i == TIME_GROUP && first < TIME_GROUP {
out.write_str(cfg.sep)?;
}
let width = match cfg.zeros {
Zeros::TrimAll => 1,
Zeros::TrimLargest if i == first => 1,
_ => WIDTHS[i],
};
write_zero_padded(out, values[i] as u128, width)?;
if i == SEC {
write_frac(cfg, d.attos, out)?;
}
out.write_char(LETTERS[i])?;
}
Ok(())
}
fn write_frac(cfg: &DurFmt, attos: u64, out: &mut dyn Write) -> fmt::Result {
let digits = cfg.frac_digits as usize;
if digits == 0 {
return Ok(());
}
out.write_char('.')?;
let value = attos as u128 / POW10[MAX_FRAC_DIGITS as usize - digits];
let mut buf = StackStr::<{ MAX_FRAC_DIGITS as usize }>::new();
write_zero_padded(&mut buf, value, digits)?;
match cfg.frac_sep {
None => out.write_str(buf.as_str()),
Some(sep) => {
for (i, group) in buf.as_str().as_bytes().chunks(3).enumerate() {
if i > 0 {
out.write_str(sep)?;
}
out.write_str(core::str::from_utf8(group).unwrap_or(""))?;
}
Ok(())
}
}
}
#[cfg(test)]
mod tests {
use super::*;
extern crate std;
use std::string::ToString;
fn f(secs: u64) -> std::string::String {
DurFmt::new().fmt(secs).to_string()
}
#[test]
fn default_style() {
assert_eq!(f(1_000_000_000), "31y251d_13h21m28s");
assert_eq!(f(0), "00s");
assert_eq!(f(5), "05s");
assert_eq!(f(90), "01m30s");
assert_eq!(f(3665), "01h01m05s");
assert_eq!(f(86_400), "001d_00h00m00s");
assert_eq!(f(SECS_PER_GREGORIAN_YEAR), "1y000d_00h00m00s");
assert_eq!(f(SECS_PER_GREGORIAN_YEAR - 1), "365d_05h49m11s");
}
#[test]
fn unit_boundaries() {
assert_eq!(f(59), "59s");
assert_eq!(f(60), "01m00s");
assert_eq!(f(3_599), "59m59s");
assert_eq!(f(3_600), "01h00m00s");
assert_eq!(f(86_399), "23h59m59s");
}
#[test]
fn zero_modes() {
let d = 5 * 3600 + 65;
assert_eq!(DurFmt::new().zeros(Zeros::Pad).fmt(d as u64).to_string(), "05h01m05s");
assert_eq!(DurFmt::new().zeros(Zeros::TrimAll).fmt(d as u64).to_string(), "5h1m5s");
assert_eq!(DurFmt::new().zeros(Zeros::TrimLargest).fmt(d as u64).to_string(), "5h01m05s");
assert_eq!(DurFmt::new().zeros(Zeros::TrimAll).fmt(86_400u64).to_string(), "1d_0h0m0s");
assert_eq!(DurFmt::new().zeros(Zeros::TrimLargest).fmt(0u64).to_string(), "0s");
}
#[test]
fn all_frac_precisions() {
let d = Dur::from_parts(false, 65, 123_456_789_012_345_678);
let cases = [
(Frac::Secs, "01m05s"),
(Frac::Millis, "01m05.123s"),
(Frac::Micros, "01m05.123456s"),
(Frac::Nanos, "01m05.123456789s"),
(Frac::Picos, "01m05.123456789012s"),
(Frac::Femtos, "01m05.123456789012345s"),
(Frac::Attos, "01m05.123456789012345678s"),
];
for (frac, expected) in cases {
assert_eq!(DurFmt::new().frac(frac).fmt(d).to_string(), expected, "{frac:?}");
}
}
#[test]
fn frac_constructors_are_exact() {
assert_eq!(Dur::from_millis(1_500), Dur::from_parts(false, 1, 500_000_000_000_000_000));
assert_eq!(Dur::from_micros(1_500_000), Dur::from_millis(1_500));
assert_eq!(Dur::from_nanos(1_500_000_000), Dur::from_millis(1_500));
assert_eq!(Dur::from_picos(1_500_000_000_000), Dur::from_millis(1_500));
assert_eq!(Dur::from_femtos(1_500_000_000_000_000), Dur::from_millis(1_500));
assert_eq!(Dur::from_attos(1_500_000_000_000_000_000), Dur::from_millis(1_500));
assert_eq!(Dur::from_secs_f64(1.5), Dur::from_millis(1_500));
}
#[test]
fn frac_is_truncated_not_rounded() {
let d = Dur::from_millis(1_999);
assert_eq!(DurFmt::new().frac_digits(1).fmt(d).to_string(), "01.9s");
assert_eq!(DurFmt::new().fmt(d).to_string(), "01s");
}
#[test]
fn frac_is_ignored_above_seconds() {
let cfg = DurFmt::new().frac(Frac::Millis).smallest(TimeUnit::Min);
assert_eq!(cfg.fmt(Dur::from_millis(90_500)).to_string(), "01m");
}
#[test]
fn smallest_unit_truncates() {
assert_eq!(DurFmt::new().smallest(TimeUnit::Min).fmt(3_665u64).to_string(), "01h01m");
assert_eq!(DurFmt::new().smallest(TimeUnit::Hour).fmt(3_665u64).to_string(), "01h");
assert_eq!(DurFmt::new().smallest(TimeUnit::Day).fmt(3_665u64).to_string(), "000d");
assert_eq!(DurFmt::new().smallest(TimeUnit::Year).fmt(3_665u64).to_string(), "0y");
}
#[test]
fn zero_has_no_sign() {
assert_eq!(Dur::ZERO.neg(), Dur::ZERO);
assert_eq!(Dur::from_parts(true, 0, 0), Dur::ZERO);
assert_eq!(Dur::from_secs_f64(-0.0), Dur::ZERO);
assert_eq!(DurFmt::new().fmt(Dur::from_parts(true, 0, 0)).to_string(), "00s");
}
#[test]
fn signs() {
assert_eq!(DurFmt::new().fmt(-90i64).to_string(), "-01m30s");
assert_eq!(DurFmt::new().fmt(Dur::ZERO.neg()).to_string(), "00s");
assert_eq!(DurFmt::new().fmt(-1.5f64).to_string(), "-01s");
}
#[test]
fn separator_is_configurable() {
assert_eq!(DurFmt::new().no_sep().fmt(86_400u64).to_string(), "001d00h00m00s");
assert_eq!(DurFmt::new().sep(" ").fmt(86_400u64).to_string(), "001d 00h00m00s");
assert_eq!(DurFmt::new().sep(" ").fmt(3_600u64).to_string(), "01h00m00s");
}
#[test]
fn year_length_is_configurable() {
let cfg = DurFmt::new().secs_per_year(365 * 86_400);
assert_eq!(cfg.fmt(365 * 86_400u64).to_string(), "1y000d_00h00m00s");
assert_eq!(cfg.fmt(364 * 86_400u64).to_string(), "364d_00h00m00s");
}
#[test]
fn display_padding_is_honored() {
assert_eq!(std::format!("{:>10}", DurFmt::new().fmt(90u64)), " 01m30s");
}
#[test]
fn std_duration_is_accepted() {
let d = core::time::Duration::from_millis(90_500);
assert_eq!(DurFmt::new().frac(Frac::Millis).fmt(d).to_string(), "01m30.500s");
}
}