use chrono::{Datelike, NaiveDate, NaiveTime, Timelike};
use crate::{Error, Result, Value};
use super::civil_epoch_days;
use super::field::{quarter_of_month, quarter_start_month};
use super::zone::{add_offset, zone_kind, ZoneSpec};
use super::{
format_zone_offset, lookup, split_seconds, Temporal, NANOS_PER_MICRO, NANOS_PER_MILLI,
SECONDS_PER_HOUR, SECONDS_PER_MINUTE,
};
#[derive(Clone, Copy, PartialEq, Eq)]
enum Component {
Year,
Month,
Day,
OrdinalDay,
Quarter,
Week,
WeekYear,
DayOfWeek,
DayOfQuarter,
Hour,
Minute,
Second,
Millisecond,
Microsecond,
Nanosecond,
Timezone,
Offset,
OffsetSeconds,
OffsetMinutes,
EpochSeconds,
EpochMillis,
}
impl Component {
const TABLE: &'static [(&'static str, Component)] = &[
("year", Component::Year),
("month", Component::Month),
("day", Component::Day),
("ordinalday", Component::OrdinalDay),
("quarter", Component::Quarter),
("week", Component::Week),
("weekyear", Component::WeekYear),
("dayofweek", Component::DayOfWeek),
("weekday", Component::DayOfWeek),
("dayofquarter", Component::DayOfQuarter),
("hour", Component::Hour),
("minute", Component::Minute),
("second", Component::Second),
("millisecond", Component::Millisecond),
("microsecond", Component::Microsecond),
("nanosecond", Component::Nanosecond),
("timezone", Component::Timezone),
("offset", Component::Offset),
("offsetseconds", Component::OffsetSeconds),
("offsetminutes", Component::OffsetMinutes),
("epochseconds", Component::EpochSeconds),
("epochmillis", Component::EpochMillis),
];
fn from_name(name: &str) -> Option<Self> {
lookup(Self::TABLE, name)
}
}
#[derive(Clone, Copy)]
enum DurationComponent {
Years,
Quarters,
Months,
Weeks,
Days,
Hours,
Minutes,
Seconds,
Millis,
Micros,
Nanos,
MonthsOfYear,
QuartersOfYear,
MonthsOfQuarter,
DaysOfWeek,
MinutesOfHour,
SecondsOfMinute,
MillisOfSecond,
MicrosOfSecond,
NanosOfSecond,
}
impl DurationComponent {
const TABLE: &'static [(&'static str, DurationComponent)] = &[
("years", DurationComponent::Years),
("quarters", DurationComponent::Quarters),
("months", DurationComponent::Months),
("weeks", DurationComponent::Weeks),
("days", DurationComponent::Days),
("hours", DurationComponent::Hours),
("minutes", DurationComponent::Minutes),
("seconds", DurationComponent::Seconds),
("milliseconds", DurationComponent::Millis),
("microseconds", DurationComponent::Micros),
("nanoseconds", DurationComponent::Nanos),
("monthsofyear", DurationComponent::MonthsOfYear),
("quartersofyear", DurationComponent::QuartersOfYear),
("monthsofquarter", DurationComponent::MonthsOfQuarter),
("daysofweek", DurationComponent::DaysOfWeek),
("minutesofhour", DurationComponent::MinutesOfHour),
("secondsofminute", DurationComponent::SecondsOfMinute),
("millisecondsofsecond", DurationComponent::MillisOfSecond),
("microsecondsofsecond", DurationComponent::MicrosOfSecond),
("nanosecondsofsecond", DurationComponent::NanosOfSecond),
];
fn from_name(name: &str) -> Option<Self> {
lookup(Self::TABLE, name)
}
}
pub(super) fn read(t: &Temporal, key: &str) -> Result<Value> {
let name = key.to_ascii_lowercase();
if let Temporal::Duration {
months,
days,
nanos,
} = t
{
let component =
DurationComponent::from_name(&name).ok_or_else(|| no_component("duration", key))?;
return duration_component(*months, *days, *nanos, component);
}
let kind = t.kind_name();
let component = Component::from_name(&name).ok_or_else(|| no_component(kind, key))?;
component_value(t, component)?.ok_or_else(|| no_component(kind, key))
}
fn no_component(kind: &str, key: &str) -> Error {
Error::ty(format!("no such component '{key}' on a {kind} value"))
}
#[derive(Clone, Copy)]
struct Ymd {
year: i64,
month: u32,
day: u32,
}
impl From<NaiveDate> for Ymd {
fn from(d: NaiveDate) -> Self {
Ymd {
year: i64::from(d.year()),
month: d.month(),
day: d.day(),
}
}
}
struct IsoWeek {
week_year: i64,
week: i64,
}
impl Ymd {
fn epoch_days(self) -> i128 {
civil_epoch_days(self.year, self.month, self.day)
}
fn day_of_week(self) -> i64 {
(self.epoch_days() + 3).rem_euclid(7) as i64 + 1
}
fn ordinal_day(self) -> i64 {
let jan_first = civil_epoch_days(self.year, 1, 1);
(self.epoch_days() - jan_first) as i64 + 1
}
fn quarter(self) -> u32 {
quarter_of_month(self.month)
}
fn day_of_quarter(self) -> i64 {
let quarter_start = civil_epoch_days(self.year, quarter_start_month(self.month), 1);
(self.epoch_days() - quarter_start) as i64 + 1
}
fn iso_week(self) -> IsoWeek {
let week = (self.ordinal_day() - self.day_of_week() + 10) / 7;
if week < 1 {
IsoWeek {
week_year: self.year - 1,
week: iso_weeks_in_year(self.year - 1),
}
} else if week > iso_weeks_in_year(self.year) {
IsoWeek {
week_year: self.year + 1,
week: 1,
}
} else {
IsoWeek {
week_year: self.year,
week,
}
}
}
}
fn iso_weeks_in_year(year: i64) -> i64 {
const THURSDAY: i64 = 4;
let day_of_week = |month, day| Ymd { year, month, day }.day_of_week();
if day_of_week(1, 1) == THURSDAY || day_of_week(12, 31) == THURSDAY {
53
} else {
52
}
}
fn date_part(t: &Temporal) -> Result<Option<Ymd>> {
Ok(match t {
Temporal::Date(d) => Some((*d).into()),
Temporal::LocalDateTime(dt) => Some(dt.date().into()),
Temporal::DateTime { utc, offset, .. } => Some(add_offset(*utc, *offset)?.date().into()),
Temporal::CivilDate { year, month, day }
| Temporal::CivilDateTime {
year, month, day, ..
} => Some(Ymd {
year: *year,
month: *month,
day: *day,
}),
Temporal::CivilZoned(f) => Some(Ymd {
year: f.year,
month: f.month,
day: f.day,
}),
_ => None,
})
}
fn time_part(t: &Temporal) -> Result<Option<NaiveTime>> {
Ok(match t {
Temporal::LocalTime(tm) | Temporal::Time { time: tm, .. } => Some(*tm),
Temporal::LocalDateTime(dt) => Some(dt.time()),
Temporal::DateTime { utc, offset, .. } => Some(add_offset(*utc, *offset)?.time()),
Temporal::CivilDateTime { time, .. } => Some(*time),
Temporal::CivilZoned(f) => Some(f.time),
_ => None,
})
}
fn offset_part(t: &Temporal) -> Option<i32> {
match t {
Temporal::Time { offset, .. } | Temporal::DateTime { offset, .. } => Some(*offset),
Temporal::CivilZoned(f) => Some(f.offset),
_ => None,
}
}
fn timezone_part(t: &Temporal) -> Option<String> {
let offset = offset_part(t)?;
let named_zone = match t {
Temporal::DateTime { zone, .. } => zone.as_deref(),
Temporal::CivilZoned(f) => f.zone.as_deref(),
_ => None,
};
if let Some(zone) = named_zone {
return Some(match zone_kind(zone) {
ZoneSpec::Iana(name) => name.into(),
ZoneSpec::Fixed(_) | ZoneSpec::Other(_) => format_zone_offset(offset),
ZoneSpec::Prefixed(name) => name.into(),
ZoneSpec::Utc => "Z".into(),
});
}
Some(format_zone_offset(offset))
}
fn component_value(t: &Temporal, component: Component) -> Result<Option<Value>> {
let ymd_int = |f: fn(Ymd) -> i64| -> Result<Option<Value>> {
Ok(date_part(t)?.map(|d| Value::Int(f(d))))
};
let time_int = |f: fn(NaiveTime) -> i64| -> Result<Option<Value>> {
Ok(time_part(t)?.map(|tm| Value::Int(f(tm))))
};
match component {
Component::Year => ymd_int(|d| d.year),
Component::Month => ymd_int(|d| i64::from(d.month)),
Component::Day => ymd_int(|d| i64::from(d.day)),
Component::OrdinalDay => ymd_int(Ymd::ordinal_day),
Component::Quarter => ymd_int(|d| i64::from(d.quarter())),
Component::Week => ymd_int(|d| d.iso_week().week),
Component::WeekYear => ymd_int(|d| d.iso_week().week_year),
Component::DayOfWeek => ymd_int(Ymd::day_of_week),
Component::DayOfQuarter => ymd_int(Ymd::day_of_quarter),
Component::Hour => time_int(|tm| i64::from(tm.hour())),
Component::Minute => time_int(|tm| i64::from(tm.minute())),
Component::Second => time_int(|tm| i64::from(tm.second())),
Component::Millisecond => time_int(|tm| i64::from(tm.nanosecond() / 1_000_000)),
Component::Microsecond => time_int(|tm| i64::from(tm.nanosecond() / 1_000)),
Component::Nanosecond => time_int(|tm| i64::from(tm.nanosecond())),
Component::Timezone => Ok(timezone_part(t).map(|z| Value::String(z.into()))),
Component::Offset => {
Ok(offset_part(t).map(|o| Value::String(format_zone_offset(o).into())))
}
Component::OffsetSeconds => Ok(offset_part(t).map(|o| Value::Int(i64::from(o)))),
Component::OffsetMinutes => Ok(offset_part(t).map(|o| Value::Int(i64::from(o / 60)))),
Component::EpochSeconds => Ok(epoch_millis(t)?.map(|ms| Value::Int(ms.div_euclid(1000)))),
Component::EpochMillis => Ok(epoch_millis(t)?.map(Value::Int)),
}
}
fn epoch_millis(t: &Temporal) -> Result<Option<i64>> {
let Some(parts) = t.zoned_parts() else {
return Ok(None);
};
i64::try_from(parts.instant.div_euclid(NANOS_PER_MILLI))
.map(Some)
.map_err(|_| super::range_err())
}
fn duration_component(
months: i64,
days: i64,
nanos: i128,
component: DurationComponent,
) -> Result<Value> {
let (total_seconds, sub_nanos) = split_seconds(nanos);
let total_minutes = total_seconds / SECONDS_PER_MINUTE;
let hours = total_seconds / SECONDS_PER_HOUR;
let total = |v: i128| i64::try_from(v).map_err(|_| super::range_err());
Ok(Value::Int(match component {
DurationComponent::Years => months / 12,
DurationComponent::Months => months,
DurationComponent::MonthsOfYear => months.rem_euclid(12),
DurationComponent::Quarters => months / 3,
DurationComponent::QuartersOfYear => months.rem_euclid(12) / 3,
DurationComponent::MonthsOfQuarter => months.rem_euclid(3),
DurationComponent::Weeks => days / 7,
DurationComponent::Days => days,
DurationComponent::DaysOfWeek => days.rem_euclid(7),
DurationComponent::Hours => total(hours)?,
DurationComponent::Minutes => total(total_minutes)?,
DurationComponent::MinutesOfHour => total(total_minutes % 60)?,
DurationComponent::Seconds => total(total_seconds)?,
DurationComponent::SecondsOfMinute => total(total_seconds % 60)?,
DurationComponent::Nanos => total(nanos)?,
DurationComponent::Millis => total(nanos.div_euclid(NANOS_PER_MILLI))?,
DurationComponent::Micros => total(nanos.div_euclid(NANOS_PER_MICRO))?,
DurationComponent::MillisOfSecond => total(sub_nanos / NANOS_PER_MILLI)?,
DurationComponent::MicrosOfSecond => total(sub_nanos / NANOS_PER_MICRO)?,
DurationComponent::NanosOfSecond => total(sub_nanos)?,
}))
}
#[cfg(test)]
mod tests {
use super::*;
use crate::temporal::clock::ClockKind;
use crate::temporal::{
construct_date, construct_datetime, construct_localdatetime, construct_localtime,
construct_time,
};
fn sample(kind: ClockKind) -> Temporal {
match kind {
ClockKind::Date => construct_date(None).unwrap(),
ClockKind::LocalTime => construct_localtime(None).unwrap(),
ClockKind::Time => construct_time(None).unwrap(),
ClockKind::LocalDateTime => construct_localdatetime(None).unwrap(),
ClockKind::DateTime => construct_datetime(None).unwrap(),
}
}
#[test]
fn accessors_read_exactly_the_parts_the_kind_carries() {
let date = sample(ClockKind::Date);
assert!(read(&date, "year").is_ok());
assert!(read(&date, "dayOfQuarter").is_ok());
assert!(read(&date, "epochSeconds").is_err());
assert!(read(&date, "hour").is_err());
assert!(read(&date, "offset").is_err());
let localtime = sample(ClockKind::LocalTime);
assert!(read(&localtime, "hour").is_ok());
assert!(read(&localtime, "timezone").is_err());
assert!(read(&localtime, "year").is_err());
let time = sample(ClockKind::Time);
assert!(read(&time, "hour").is_ok());
assert!(read(&time, "offsetMinutes").is_ok());
assert!(read(&time, "timezone").is_ok());
assert!(read(&time, "year").is_err());
assert!(read(&time, "epochMillis").is_err());
let localdatetime = sample(ClockKind::LocalDateTime);
assert!(read(&localdatetime, "year").is_ok());
assert!(read(&localdatetime, "hour").is_ok());
assert!(read(&localdatetime, "timezone").is_err());
assert!(read(&localdatetime, "epochSeconds").is_err());
let datetime = sample(ClockKind::DateTime);
assert!(read(&datetime, "year").is_ok());
assert!(read(&datetime, "timezone").is_ok());
assert!(read(&datetime, "epochMillis").is_ok());
let err = read(&date, "hour").unwrap_err();
assert!(err.to_string().contains("no such component"), "{err}");
}
#[test]
fn a_zero_offset_renders_z_through_both_accessors() {
let utc = crate::temporal::parse_iso("time", "12:00Z").unwrap();
assert_eq!(read(&utc, "timezone").unwrap(), Value::String("Z".into()));
assert_eq!(read(&utc, "offset").unwrap(), Value::String("Z".into()));
let plus_one = crate::temporal::parse_iso("time", "12:00+01:00").unwrap();
assert_eq!(
read(&plus_one, "timezone").unwrap(),
Value::String("+01:00".into())
);
assert_eq!(
read(&plus_one, "offset").unwrap(),
Value::String("+01:00".into())
);
}
#[test]
fn an_out_of_range_offset_is_a_typed_range_error() {
let t = Temporal::DateTime {
utc: NaiveDate::MAX.and_hms_opt(23, 59, 59).unwrap(),
offset: 3600,
zone: None,
};
let err = read(&t, "year").unwrap_err();
assert!(err.to_string().contains("out of range"), "{err}");
}
#[test]
fn a_far_year_date_reads_the_calendar_accessors() {
let date = crate::temporal::parse_iso("date", "-999999999-01-01").unwrap();
assert!(matches!(date, Temporal::CivilDate { .. }));
assert_eq!(read(&date, "year").unwrap(), Value::Int(-999_999_999));
assert_eq!(read(&date, "month").unwrap(), Value::Int(1));
assert_eq!(read(&date, "day").unwrap(), Value::Int(1));
assert_eq!(read(&date, "quarter").unwrap(), Value::Int(1));
assert_eq!(read(&date, "week").unwrap(), Value::Int(1));
assert_eq!(read(&date, "weekYear").unwrap(), Value::Int(-999_999_999));
assert_eq!(read(&date, "dayOfWeek").unwrap(), Value::Int(1));
assert_eq!(read(&date, "ordinalDay").unwrap(), Value::Int(1));
assert_eq!(read(&date, "dayOfQuarter").unwrap(), Value::Int(1));
let top = crate::temporal::parse_iso("date", "+999999999-01-01").unwrap();
assert_eq!(read(&top, "week").unwrap(), Value::Int(53));
assert_eq!(read(&top, "weekYear").unwrap(), Value::Int(999_999_998));
assert_eq!(read(&top, "dayOfWeek").unwrap(), Value::Int(5));
let err = read(&date, "hour").unwrap_err();
assert!(err.to_string().contains("no such component"), "{err}");
}
#[test]
fn a_far_year_localdatetime_reads_calendar_and_clock() {
let local =
crate::temporal::parse_iso("localdatetime", "999999999-12-31T23:59:58.5").unwrap();
assert!(matches!(local, Temporal::CivilDateTime { .. }));
assert_eq!(read(&local, "year").unwrap(), Value::Int(999_999_999));
assert_eq!(read(&local, "month").unwrap(), Value::Int(12));
assert_eq!(read(&local, "second").unwrap(), Value::Int(58));
assert_eq!(read(&local, "millisecond").unwrap(), Value::Int(500));
assert!(read(&local, "offset").is_err());
}
#[test]
fn a_far_year_datetime_reads_zone_parts_and_bounded_epochs() {
let zoned =
crate::temporal::parse_iso("datetime", "+999999999-12-31T23:59:58+01:00").unwrap();
assert!(matches!(zoned, Temporal::CivilZoned(_)));
assert_eq!(read(&zoned, "day").unwrap(), Value::Int(31));
assert_eq!(read(&zoned, "hour").unwrap(), Value::Int(23));
assert_eq!(read(&zoned, "offsetMinutes").unwrap(), Value::Int(60));
assert_eq!(
read(&zoned, "offset").unwrap(),
Value::String("+01:00".into())
);
assert_eq!(read(&zoned, "week").unwrap(), Value::Int(52));
assert_eq!(read(&zoned, "ordinalDay").unwrap(), Value::Int(365));
for unit in ["epochSeconds", "epochMillis"] {
let err = read(&zoned, unit).unwrap_err();
assert!(err.to_string().contains("out of range"), "{err}");
}
let edge = crate::temporal::parse_iso("datetime", "+285200616-06-01T00:00Z").unwrap();
assert!(matches!(edge, Temporal::CivilZoned(_)));
assert_eq!(
read(&edge, "epochSeconds").unwrap(),
Value::Int(8_999_999_995_363_200)
);
assert_eq!(
read(&edge, "epochMillis").unwrap(),
Value::Int(8_999_999_995_363_200_000)
);
}
#[test]
fn duration_reads_only_its_own_spellings() {
let d =
crate::temporal::construct_duration(Some(&Value::String("P1Y2M3D".into()))).unwrap();
assert_eq!(read(&d, "years").unwrap(), Value::Int(1));
assert_eq!(read(&d, "months").unwrap(), Value::Int(14));
assert!(read(&d, "year").is_err());
assert!(read(&d, "weekOfMonth").is_err());
assert!(read(&d, "epochSeconds").is_err());
}
}