1use 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#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
22pub struct Duration(Decimal);
23
24impl Duration {
25 pub fn from_seconds(seconds: Decimal) -> Self {
27 Duration(seconds)
28 }
29
30 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 pub fn seconds(&self) -> &Decimal {
40 &self.0
41 }
42}
43
44impl 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#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
54pub struct Instant(Decimal);
55
56impl Instant {
57 pub fn from_unix_seconds(seconds: Decimal) -> Self {
59 Instant(seconds)
60 }
61
62 pub fn unix_seconds(&self) -> &Decimal {
64 &self.0
65 }
66
67 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
75impl 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 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
113fn 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}