use std::fmt;
use chrono::{NaiveDate, NaiveDateTime, NaiveTime, Timelike, Weekday};
use crate::{Error, Value};
mod arith;
mod between;
mod clock;
mod component;
mod construct;
mod duration;
mod duration_pattern;
mod duration_tokens;
mod exact;
mod field;
mod field_rules;
mod format;
mod parse;
mod pattern;
mod relations;
#[cfg(test)]
mod test_support;
#[cfg(test)]
mod tests;
#[cfg(test)]
mod tests_arith;
#[cfg(test)]
mod tests_between;
#[cfg(test)]
mod tests_civil_zoned;
#[cfg(test)]
mod tests_clock;
#[cfg(test)]
mod tests_construct;
#[cfg(test)]
mod tests_duration;
#[cfg(test)]
mod tests_fields;
#[cfg(test)]
mod tests_pattern;
#[cfg(test)]
mod tests_ranges;
#[cfg(test)]
mod tests_zone;
mod truncate;
mod zone;
use format::format_zone_offset;
pub use arith::{
add_duration, civil_epoch_days, civil_epoch_seconds, civil_from_days, negate_duration,
scale_duration, sub_duration,
};
pub use between::{duration_between, duration_between_unit, BetweenUnit};
pub use clock::{
clock_access, clock_spelling, clock_spelling_rows, clock_spellings, construct_clock,
now_epoch_millis, now_utc_dt, ClockKind, ClockMode, QueryClockGuard, TransactionClock,
};
pub use construct::{
accepts_pattern, clock_kind, construct_date, construct_datetime, construct_duration,
construct_localdatetime, construct_localtime, construct_named, construct_time, is_constructor,
samples_clock,
};
pub use format::format_pattern;
pub use parse::{
datetime_from_epoch, datetime_from_epoch_millis, padded_iso_date_value, parse_iso,
parse_pattern,
};
pub use truncate::{truncate, truncate_now};
pub use zone::{zone_offset_at, zone_offset_at_utc, zone_region, ZoneError, MAX_OFFSET_SECONDS};
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Temporal {
Date(NaiveDate),
CivilDate {
year: i64,
month: u32,
day: u32,
},
LocalTime(NaiveTime),
Time {
time: NaiveTime,
offset: i32,
},
LocalDateTime(NaiveDateTime),
CivilDateTime {
year: i64,
month: u32,
day: u32,
time: NaiveTime,
},
DateTime {
utc: NaiveDateTime,
offset: i32,
zone: Option<String>,
},
CivilZoned(Box<CivilZonedFields>),
Duration {
months: i64,
days: i64,
nanos: i128,
},
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CivilZonedFields {
pub year: i64,
pub month: u32,
pub day: u32,
pub time: NaiveTime,
pub offset: i32,
pub zone: Option<String>,
}
impl CivilZonedFields {
pub fn epoch_nanos(&self) -> i128 {
civil_epoch_days(self.year, self.month, self.day) * NANOS_PER_DAY
+ i128::from(time_to_nanos(self.time))
- i128::from(self.offset) * 1_000_000_000
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TemporalKind {
DateTime,
LocalDateTime,
Date,
Time,
LocalTime,
Duration,
}
impl TemporalKind {
pub(crate) fn name(self) -> &'static str {
match self {
TemporalKind::DateTime => "datetime",
TemporalKind::LocalDateTime => "localdatetime",
TemporalKind::Date => "date",
TemporalKind::Time => "time",
TemporalKind::LocalTime => "localtime",
TemporalKind::Duration => "duration",
}
}
}
impl Temporal {
pub fn kind(&self) -> TemporalKind {
match self {
Temporal::DateTime { .. } | Temporal::CivilZoned(_) => TemporalKind::DateTime,
Temporal::LocalDateTime(_) | Temporal::CivilDateTime { .. } => {
TemporalKind::LocalDateTime
}
Temporal::Date(_) | Temporal::CivilDate { .. } => TemporalKind::Date,
Temporal::Time { .. } => TemporalKind::Time,
Temporal::LocalTime(_) => TemporalKind::LocalTime,
Temporal::Duration { .. } => TemporalKind::Duration,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ZonedParts<'a> {
pub instant: i128,
pub offset: i32,
pub region: Option<&'a str>,
}
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum ZoneId {
Named(String),
Offset(i32),
}
impl ZoneId {
pub fn of(zone: Option<&str>, offset: i32) -> ZoneId {
Self::of_region(zone_region(zone), offset)
}
pub(crate) fn of_region(region: Option<&str>, offset: i32) -> ZoneId {
match region {
Some(name) => ZoneId::Named(name.to_string()),
None => ZoneId::Offset(offset),
}
}
}
impl Temporal {
pub(crate) fn duration_checked(months: i64, days: i64, nanos: i128) -> Result<Temporal, Error> {
let (seconds, _) = split_seconds(nanos);
if !(-MAX_DURATION_SECONDS..=MAX_DURATION_SECONDS).contains(&seconds) {
return Err(range_err());
}
let seconds = seconds.clamp(i128::from(i64::MIN), i128::from(i64::MAX));
let average = i128::from(months) * AVG_SECONDS_PER_MONTH
+ i128::from(days) * (NANOS_PER_DAY / NANOS_PER_SECOND)
+ seconds;
i64::try_from(average).map_err(|_| range_err())?;
Ok(Temporal::Duration {
months,
days,
nanos,
})
}
pub(crate) fn duration_checked_exact(
months: i64,
days: i64,
nanos: i128,
) -> Result<Temporal, Error> {
if nanos.div_euclid(NANOS_PER_SECOND) > i128::from(i64::MAX) {
return Err(range_err());
}
Self::duration_checked(months, days, nanos)
}
pub fn kind_name(&self) -> &'static str {
self.kind().name()
}
pub fn has_date(&self) -> bool {
matches!(
self.kind(),
TemporalKind::Date | TemporalKind::LocalDateTime | TemporalKind::DateTime
)
}
pub fn has_time(&self) -> bool {
matches!(
self.kind(),
TemporalKind::LocalTime
| TemporalKind::Time
| TemporalKind::LocalDateTime
| TemporalKind::DateTime
)
}
pub fn has_date_and_time(&self) -> bool {
self.has_date() && self.has_time()
}
pub fn iso_string(&self) -> String {
format::render(self, false)
}
pub fn full_seconds_string(&self) -> String {
format::render(self, true)
}
pub fn component(&self, key: &str) -> Result<Value, Error> {
component::read(self, key)
}
}
impl fmt::Display for Temporal {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.iso_string())
}
}
fn time_to_nanos(t: NaiveTime) -> i64 {
t.num_seconds_from_midnight() as i64 * 1_000_000_000 + t.nanosecond() as i64
}
pub(super) fn decimal_comma_as_dot(s: &str) -> std::borrow::Cow<'_, str> {
if s.contains(',') {
std::borrow::Cow::Owned(s.replace(',', "."))
} else {
std::borrow::Cow::Borrowed(s)
}
}
pub(super) fn utc_time_nanos(t: NaiveTime, offset: i32) -> i64 {
time_to_nanos(t) - i64::from(offset) * 1_000_000_000
}
pub type WallClockParts = (i64, u32, u32, NaiveTime);
fn split_seconds(nanos: i128) -> (i128, i128) {
(
nanos.div_euclid(NANOS_PER_SECOND),
nanos.rem_euclid(NANOS_PER_SECOND),
)
}
fn nanos_to_time(n: i64) -> NaiveTime {
let secs = (n / 1_000_000_000) as u32;
let nano = (n % 1_000_000_000) as u32;
NaiveTime::from_num_seconds_from_midnight_opt(secs, nano).unwrap_or(NaiveTime::MIN)
}
pub(super) fn range_err() -> Error {
Error::ty("temporal value out of range")
}
pub(super) fn duration_overflow_err(operation: &str) -> Error {
Error::ty(format!(
"the result of the operation '{operation}' has caused an overflow"
))
}
pub(super) fn checked_lane(value: i128, operation: &str) -> crate::Result<i64> {
i64::try_from(value).map_err(|_| duration_overflow_err(operation))
}
pub(super) fn map_temporal<'a>(
map: &'a std::collections::BTreeMap<String, Value>,
k: &str,
) -> Option<&'a Temporal> {
map.get(k).and_then(Value::as_temporal)
}
pub(super) fn lookup<T: Copy>(table: &[(&str, T)], name: &str) -> Option<T> {
table
.iter()
.find(|(spelling, _)| *spelling == name)
.map(|(_, value)| *value)
}
pub(super) fn f64_to_i128_range(v: f64) -> Result<i128, Error> {
if v.is_finite() && v.abs() < 1.0e38 {
Ok(v as i128)
} else {
Err(range_err())
}
}
pub(super) fn f64_to_i64_range(v: f64) -> Result<i64, Error> {
i64::try_from(f64_to_i128_range(v)?).map_err(|_| range_err())
}
fn weekday_from_i(i: i64) -> Weekday {
match i.rem_euclid(7) {
1 => Weekday::Mon,
2 => Weekday::Tue,
3 => Weekday::Wed,
4 => Weekday::Thu,
5 => Weekday::Fri,
6 => Weekday::Sat,
_ => Weekday::Sun,
}
}
use field::{
DurationField, AVG_NANOS_PER_MONTH, AVG_SECONDS_PER_MONTH, MAX_DURATION_SECONDS,
MONTHS_PER_QUARTER, MONTHS_PER_YEAR, NANOS_PER_DAY, NANOS_PER_HOUR, NANOS_PER_MICRO,
NANOS_PER_MILLI, NANOS_PER_MINUTE, NANOS_PER_SECOND, SECONDS_PER_HOUR, SECONDS_PER_MINUTE,
};