Skip to main content

flow_value/
time.rs

1//! `Duration` and `Instant` (`data.md`, *Duration and Instant*).
2//!
3//! Both are an exact [`Decimal`] number of seconds: a duration is a length,
4//! of either sign, and an instant is a signed offset from
5//! 1970-01-01T00:00:00Z on the proleptic Gregorian calendar with no leap
6//! seconds. Nothing here reads a clock. Exact seconds carry whatever
7//! fraction an ISO 8601 text gives, so no instant or duration is rounded to a
8//! resolution of this crate's choosing.
9
10use std::fmt;
11
12use num_bigint::BigInt;
13use num_integer::Integer;
14use num_traits::ToPrimitive;
15
16use crate::decimal::Decimal;
17use crate::error::Fault;
18use crate::int::Int;
19
20/// A length of time, ordered by length.
21#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
22pub struct Duration(Decimal);
23
24impl Duration {
25    /// Returns the duration of `seconds` seconds.
26    pub fn from_seconds(seconds: Decimal) -> Self {
27        Duration(seconds)
28    }
29
30    /// Returns the duration of `count` milliseconds (`duration.millis`).
31    pub fn from_millis(count: &Int) -> Self {
32        Duration(
33            Decimal::new(count.as_bigint().clone(), -3)
34                .expect("normalizing a count of milliseconds only raises its exponent towards 0"),
35        )
36    }
37
38    /// Returns the length in seconds.
39    pub fn seconds(&self) -> &Decimal {
40        &self.0
41    }
42}
43
44/// The text form: `PT`, the seconds as a `Decimal`'s text, then `S`, as
45/// `abi.md`'s canonical ISO 8601 form writes it: `PT90S`, `PT0.25S`, `PT-5S`.
46impl fmt::Display for Duration {
47    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
48        write!(f, "PT{}S", self.0)
49    }
50}
51
52/// A point in time, ordered chronologically.
53#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
54pub struct Instant(Decimal);
55
56impl Instant {
57    /// Returns the instant `seconds` after 1970-01-01T00:00:00Z.
58    pub fn from_unix_seconds(seconds: Decimal) -> Self {
59        Instant(seconds)
60    }
61
62    /// Returns the offset in seconds from 1970-01-01T00:00:00Z.
63    pub fn unix_seconds(&self) -> &Decimal {
64        &self.0
65    }
66
67    /// Returns the instant `span` after this one (`time.add`).
68    pub fn add(&self, span: &Duration) -> Result<Instant, Fault> {
69        Ok(Instant(self.0.add(&span.0)?))
70    }
71}
72
73const SECONDS_PER_DAY: i64 = 86_400;
74
75/// The text form: `abi.md`'s canonical ISO 8601 form, in UTC with the `Z`
76/// suffix and the fewest fractional-second digits that are exact, such as
77/// `2026-03-21T09:30:00.25Z`. A year outside `0000` to `9999` carries a sign
78/// and at least four digits: `+10000-01-01T00:00:00Z`, `-0001-12-31T00:00:00Z`.
79impl fmt::Display for Instant {
80    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
81        let whole = self.0.floor();
82        let fraction = self
83            .0
84            .sub(&Decimal::from(&whole))
85            .expect("an exact difference of numbers that share their low digits");
86        let (days, second_of_day) = whole
87            .as_bigint()
88            .div_mod_floor(&BigInt::from(SECONDS_PER_DAY));
89        let second_of_day = second_of_day.to_i64().expect("a remainder below 86400");
90        let (year, month, day) = civil_from_days(&days);
91
92        let year = if year < BigInt::from(0) {
93            format!("-{:04}", -year)
94        } else if year > BigInt::from(9999) {
95            format!("+{year}")
96        } else {
97            format!("{year:04}")
98        };
99        // The fraction is in [0, 1), so its text is `0` or `0.` followed by
100        // the fewest digits that are exact.
101        let fraction = fraction.to_string();
102        write!(
103            f,
104            "{year}-{month:02}-{day:02}T{:02}:{:02}:{:02}{}Z",
105            second_of_day / 3600,
106            second_of_day / 60 % 60,
107            second_of_day % 60,
108            fraction.strip_prefix('0').unwrap_or(&fraction),
109        )
110    }
111}
112
113/// Returns the proleptic Gregorian `(year, month, day)` of the day `days`
114/// after 1970-01-01.
115///
116/// This is Howard Hinnant's `civil_from_days`, over 400-year eras of 146097
117/// days so that only the era count needs more than 64 bits.
118fn civil_from_days(days: &BigInt) -> (BigInt, i64, i64) {
119    let shifted: BigInt = days + 719_468;
120    let (era, day_of_era) = shifted.div_mod_floor(&BigInt::from(146_097));
121    let day_of_era = day_of_era.to_i64().expect("a remainder below 146097");
122    let year_of_era =
123        (day_of_era - day_of_era / 1460 + day_of_era / 36524 - day_of_era / 146_096) / 365;
124    let day_of_year = day_of_era - (365 * year_of_era + year_of_era / 4 - year_of_era / 100);
125    let shifted_month = (5 * day_of_year + 2) / 153;
126    let day = day_of_year - (153 * shifted_month + 2) / 5 + 1;
127    let month = if shifted_month < 10 {
128        shifted_month + 3
129    } else {
130        shifted_month - 9
131    };
132    let year = era * 400 + year_of_era + i64::from(month <= 2);
133    (year, month, day)
134}