flow-lang-value 0.1.0-rc.5

The Flow runtime value model: data values, their equality, order and text, and the operations std's built-in types declare.
Documentation
//! `Duration` and `Instant` (`data.md`, *Duration and Instant*).
//!
//! Both are an exact [`Decimal`] number of seconds: a duration is a length,
//! of either sign, and an instant is a signed offset from
//! 1970-01-01T00:00:00Z on the proleptic Gregorian calendar with no leap
//! seconds. Nothing here reads a clock. Exact seconds carry whatever
//! fraction an ISO 8601 text gives, so no instant or duration is rounded to a
//! resolution of this crate's choosing.

use std::fmt;

use num_bigint::BigInt;
use num_integer::Integer;
use num_traits::ToPrimitive;

use crate::decimal::Decimal;
use crate::error::Fault;
use crate::int::Int;

/// A length of time, ordered by length.
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
pub struct Duration(Decimal);

impl Duration {
    /// Returns the duration of `seconds` seconds.
    pub fn from_seconds(seconds: Decimal) -> Self {
        Duration(seconds)
    }

    /// Returns the duration of `count` milliseconds (`duration.millis`).
    ///
    /// # Panics
    ///
    /// Never: normalizing a count scaled by `10^-3` only raises its exponent
    /// towards zero, which cannot pass `i64::MAX`.
    pub fn from_millis(count: &Int) -> Self {
        Duration(
            Decimal::new(count.as_bigint().clone(), -3)
                .expect("normalizing a count of milliseconds only raises its exponent towards 0"),
        )
    }

    /// Returns the length in seconds.
    pub fn seconds(&self) -> &Decimal {
        &self.0
    }
}

/// The text form: `PT`, the seconds as a `Decimal`'s text, then `S`, as
/// `abi.md`'s canonical ISO 8601 form writes it: `PT90S`, `PT0.25S`, `PT-5S`.
impl fmt::Display for Duration {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "PT{}S", self.0)
    }
}

/// A point in time, ordered chronologically.
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
pub struct Instant(Decimal);

impl Instant {
    /// Returns the instant `seconds` after 1970-01-01T00:00:00Z.
    pub fn from_unix_seconds(seconds: Decimal) -> Self {
        Instant(seconds)
    }

    /// Returns the offset in seconds from 1970-01-01T00:00:00Z.
    pub fn unix_seconds(&self) -> &Decimal {
        &self.0
    }

    /// Returns the instant `span` after this one (`time.add`).
    ///
    /// # Errors
    ///
    /// [`Fault::Limit`] when the sum's exponent would leave the `i64` range.
    pub fn add(&self, span: &Duration) -> Result<Instant, Fault> {
        Ok(Instant(self.0.add(&span.0)?))
    }

    /// Returns the duration from `earlier` to this instant, negative when
    /// `earlier` is later (`time.between`).
    ///
    /// # Errors
    ///
    /// [`Fault::Limit`] when the difference's exponent would leave the `i64`
    /// range.
    pub fn since(&self, earlier: &Instant) -> Result<Duration, Fault> {
        Ok(Duration(self.0.sub(&earlier.0)?))
    }
}

const SECONDS_PER_DAY: i64 = 86_400;

/// The text form: `abi.md`'s canonical ISO 8601 form, in UTC with the `Z`
/// suffix and the fewest fractional-second digits that are exact, such as
/// `2026-03-21T09:30:00.25Z`. A year outside `0000` to `9999` carries a sign
/// and at least four digits: `+10000-01-01T00:00:00Z`, `-0001-12-31T00:00:00Z`.
impl fmt::Display for Instant {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let whole = self.0.floor();
        let fraction = self
            .0
            .sub(&Decimal::from(&whole))
            .expect("an exact difference of numbers that share their low digits");
        let (days, second_of_day) = whole
            .as_bigint()
            .div_mod_floor(&BigInt::from(SECONDS_PER_DAY));
        let second_of_day = second_of_day.to_i64().expect("a remainder below 86400");
        let (year, month, day) = civil_from_days(&days);

        let year = if year < BigInt::from(0) {
            format!("-{:04}", -year)
        } else if year > BigInt::from(9999) {
            format!("+{year}")
        } else {
            format!("{year:04}")
        };
        // The fraction is in [0, 1), so its text is `0` or `0.` followed by
        // the fewest digits that are exact.
        let fraction = fraction.to_string();
        write!(
            f,
            "{year}-{month:02}-{day:02}T{:02}:{:02}:{:02}{}Z",
            second_of_day / 3600,
            second_of_day / 60 % 60,
            second_of_day % 60,
            fraction.strip_prefix('0').unwrap_or(&fraction),
        )
    }
}

/// Returns the proleptic Gregorian `(year, month, day)` of the day `days`
/// after 1970-01-01.
///
/// This is Howard Hinnant's `civil_from_days`, over 400-year eras of 146097
/// days so that only the era count needs more than 64 bits.
fn civil_from_days(days: &BigInt) -> (BigInt, i64, i64) {
    let shifted: BigInt = days + 719_468;
    let (era, day_of_era) = shifted.div_mod_floor(&BigInt::from(146_097));
    let day_of_era = day_of_era.to_i64().expect("a remainder below 146097");
    let year_of_era =
        (day_of_era - day_of_era / 1460 + day_of_era / 36524 - day_of_era / 146_096) / 365;
    let day_of_year = day_of_era - (365 * year_of_era + year_of_era / 4 - year_of_era / 100);
    let shifted_month = (5 * day_of_year + 2) / 153;
    let day = day_of_year - (153 * shifted_month + 2) / 5 + 1;
    let month = if shifted_month < 10 {
        shifted_month + 3
    } else {
        shifted_month - 9
    };
    let year = era * 400 + year_of_era + i64::from(month <= 2);
    (year, month, day)
}