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;
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
pub struct Duration(Decimal);
impl Duration {
pub fn from_seconds(seconds: Decimal) -> Self {
Duration(seconds)
}
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"),
)
}
pub fn seconds(&self) -> &Decimal {
&self.0
}
}
impl fmt::Display for Duration {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "PT{}S", self.0)
}
}
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
pub struct Instant(Decimal);
impl Instant {
pub fn from_unix_seconds(seconds: Decimal) -> Self {
Instant(seconds)
}
pub fn unix_seconds(&self) -> &Decimal {
&self.0
}
pub fn add(&self, span: &Duration) -> Result<Instant, Fault> {
Ok(Instant(self.0.add(&span.0)?))
}
}
const SECONDS_PER_DAY: i64 = 86_400;
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}")
};
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),
)
}
}
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)
}