grippo 0.2.1

Parse, match and scrub data faster and more efficiently.
Documentation
// Project:   grippo
// File:      src/time/render.rs
// Purpose:   Instants written out: RFC 3339, epoch numbers, a date, strftime, Java-style patterns
// Language:  Rust
//
// License:   Apache-2.0
// Copyright: (c) 2026 HYPERI PTY LIMITED

use jiff::Timestamp;
use jiff::civil::Date;
use jiff::fmt::strtime::BrokenDownTime;
use jiff::tz::{Offset, TimeZone};

use super::{JavaPattern, StrptimeDialect, TimeError, TimeFormat};

/// How many fraction digits [`RenderFormat::Rfc3339`] writes.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum Fraction {
    /// Exactly this many, cut rather than rounded: 0 writes none and 3
    /// milliseconds. Past 9 writes 9.
    Digits(u8),
    /// Trailing zeros dropped, keeping at least this many: with 3, `.000`,
    /// `.120` and `.123456`.
    Trimmed(u8),
    /// The fewest of 0, 3, 6 or 9 digits that hold the fraction, and at least
    /// this many: with 3, `.000`, `.120` and `.123456`, with 0 none for a
    /// whole second.
    Groups(u8),
}

/// How [`render`] writes an instant.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum RenderFormat {
    /// RFC 3339 in the zone's offset, with `Z` where it is zero:
    /// `2026-11-30T10:00:00.000+10:00`. An offset's seconds aren't written.
    Rfc3339(Fraction),
    /// Seconds since 1970-01-01 UTC, with the fraction the instant has and no
    /// trailing zeros: `1764496800`, `1764496800.25`, and `-0.5` half a
    /// second before 1970.
    EpochSeconds,
    /// Whole milliseconds since 1970, rounded down.
    EpochMillis,
    /// Whole microseconds since 1970, rounded down.
    EpochMicros,
    /// Nanoseconds since 1970.
    EpochNanos,
    /// The date in the zone: `2026-11-30`.
    Date,
    /// A strftime format in jiff's dialect, such as `%Y-%m-%d %H:%M:%S%.f %:z`.
    Strftime(String),
    /// A Java-style date pattern, printed as Java prints it.
    Java(JavaPattern),
}

impl RenderFormat {
    /// A [`RenderFormat::Strftime`] from `format` written in `dialect`,
    /// translated as [`TimeFormat::strptime`] translates it, or a
    /// [`RenderFormat::Java`] for [`StrptimeDialect::Java`]. The format writes
    /// one instant here, so a directive that can't be written fails now and
    /// not per record.
    ///
    /// # Errors
    ///
    /// [`TimeError::Directive`] for a directive jiff can't write, and
    /// [`TimeError::Pattern`] for a Java-style pattern that doesn't build.
    pub fn strftime(dialect: StrptimeDialect, format: &str) -> Result<Self, TimeError> {
        let built = match TimeFormat::strptime(dialect, format)? {
            TimeFormat::Java(pattern) => return Ok(Self::Java(pattern)),
            TimeFormat::Strptime(translated) => translated,
            _ => return Err(TimeError::Directive(format.to_owned())),
        };
        let mut out = String::new();
        BrokenDownTime::from(&Timestamp::UNIX_EPOCH.to_zoned_datetime(TimeZone::UTC))
            .format(built.as_bytes(), &mut out)
            .map_err(|_| TimeError::Directive(format.to_owned()))?;
        Ok(Self::Strftime(built))
    }
}

/// Write `ts` in `zone` as `format` writes it.
///
/// # Errors
///
/// [`TimeError::Range`] when a strftime format can't write the instant.
pub fn render(ts: Timestamp, format: &RenderFormat, zone: &TimeZone) -> Result<String, TimeError> {
    let mut out = String::with_capacity(32);
    render_into(ts, format, zone, &mut out)?;
    Ok(out)
}

/// [`render`], appending to `out`.
///
/// # Errors
///
/// As [`render`].
pub fn render_into(
    ts: Timestamp,
    format: &RenderFormat,
    zone: &TimeZone,
    out: &mut String,
) -> Result<(), TimeError> {
    let ns = ts.as_nanosecond();
    match format {
        RenderFormat::Rfc3339(fraction) => rfc3339(ts, zone.to_offset(ts), *fraction, out),
        RenderFormat::EpochSeconds => epoch_seconds(ns, out),
        RenderFormat::EpochMillis => number(out, ns.div_euclid(1_000_000), 0),
        RenderFormat::EpochMicros => number(out, ns.div_euclid(1_000), 0),
        RenderFormat::EpochNanos => number(out, ns, 0),
        RenderFormat::Date => date(zone.to_offset(ts).to_datetime(ts).date(), out),
        RenderFormat::Strftime(fmt) => {
            BrokenDownTime::from(&ts.to_zoned_datetime(zone.clone()))
                .format(fmt.as_bytes(), out)?;
        }
        RenderFormat::Java(pattern) => pattern.print(ts, zone, out),
    }
    Ok(())
}

/// `value` with its sign, zero-padded to `width` digits.
fn number(out: &mut String, value: i128, width: usize) {
    if value < 0 {
        out.push('-');
    }
    let mut digits = [0_u8; 40];
    let mut v = value.unsigned_abs();
    let mut len = 0;
    while v > 0 || len == 0 {
        digits[len] = u8::try_from(v % 10).unwrap_or(0);
        v /= 10;
        len += 1;
    }
    for _ in len..width {
        out.push('0');
    }
    for &d in digits[..len].iter().rev() {
        out.push(char::from(b'0' + d));
    }
}

/// `YYYY-MM-DD`, with a sign and five places for a year before 0.
fn date(d: Date, out: &mut String) {
    let year = i128::from(d.year());
    if year < 0 {
        out.push('-');
        number(out, -year, 4);
    } else {
        number(out, year, 4);
    }
    out.push('-');
    number(out, d.month().into(), 2);
    out.push('-');
    number(out, d.day().into(), 2);
}

fn rfc3339(ts: Timestamp, offset: Offset, fraction: Fraction, out: &mut String) {
    let dt = offset.to_datetime(ts);
    date(dt.date(), out);
    out.push('T');
    let t = dt.time();
    number(out, t.hour().into(), 2);
    out.push(':');
    number(out, t.minute().into(), 2);
    out.push(':');
    number(out, t.second().into(), 2);
    write_fraction(t.subsec_nanosecond(), fraction, out);
    if offset == Offset::UTC {
        out.push('Z');
        return;
    }
    let secs = offset.seconds();
    out.push(if secs < 0 { '-' } else { '+' });
    let minutes = i128::from(secs.unsigned_abs() / 60);
    number(out, minutes / 60, 2);
    out.push(':');
    number(out, minutes % 60, 2);
}

/// The digits of `nanos` the rule keeps, after a `.`, or nothing.
fn write_fraction(nanos: i32, rule: Fraction, out: &mut String) {
    let mut digits = [b'0'; 9];
    let mut v = nanos.unsigned_abs();
    for slot in digits.iter_mut().rev() {
        *slot = b'0' + u8::try_from(v % 10).unwrap_or(0);
        v /= 10;
    }
    let significant = 9 - digits.iter().rev().take_while(|&&d| d == b'0').count();
    let len = match rule {
        Fraction::Digits(n) => usize::from(n.min(9)),
        Fraction::Trimmed(min) => significant.max(usize::from(min.min(9))),
        Fraction::Groups(min) => significant.max(usize::from(min.min(9))).next_multiple_of(3),
    };
    if len > 0 {
        out.push('.');
        out.extend(digits[..len].iter().map(|&d| char::from(d)));
    }
}

/// Whole seconds and the fraction's significant digits, the sign on the
/// whole instant, so half a second before 1970 is `-0.5`.
fn epoch_seconds(ns: i128, out: &mut String) {
    if ns < 0 {
        out.push('-');
    }
    let abs = ns.unsigned_abs();
    number(out, i128::try_from(abs / 1_000_000_000).unwrap_or(0), 0);
    let nanos = i32::try_from(abs % 1_000_000_000).unwrap_or(0);
    write_fraction(nanos, Fraction::Trimmed(0), out);
}