use std::fmt;
use crate::types::{DurationKind, LogicalType};
const NANOS_PER_SEC: i64 = 1_000_000_000;
pub const NANOS_PER_MINUTE: i64 = 60 * NANOS_PER_SEC;
const NANOS_PER_HOUR: i64 = 60 * NANOS_PER_MINUTE;
pub const NANOS_PER_DAY: i64 = 24 * NANOS_PER_HOUR;
pub const MIN_DAY: i32 = -719_162;
pub const MAX_DAY: i32 = 2_932_896;
pub fn instant_at(days: i32, nanos: i64) -> Option<i64> {
i64::from(days)
.checked_mul(NANOS_PER_DAY)?
.checked_add(nanos)
}
#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
pub struct Clock {
pub nanos: i64,
pub offset: i16,
}
impl Clock {
pub fn read() -> Clock {
let nanos = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|since| i64::try_from(since.as_nanos()).unwrap_or(i64::MAX))
.unwrap_or(0);
Clock { nanos, offset: 0 }
}
pub fn instant(self) -> Temporal {
Temporal::ZonedDatetime {
nanos: self.nanos,
offset: self.offset,
}
}
}
#[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)]
pub enum Temporal {
Date(i32),
LocalTime(i64),
ZonedTime { nanos: i64, offset: i16 },
LocalDatetime(i64),
ZonedDatetime { nanos: i64, offset: i16 },
Duration(DurationKind, i64),
}
impl Temporal {
pub fn logical_type(&self) -> LogicalType {
match self {
Temporal::Date(_) => LogicalType::Date,
Temporal::LocalTime(_) => LogicalType::LocalTime,
Temporal::ZonedTime { .. } => LogicalType::ZonedTime,
Temporal::LocalDatetime(_) => LogicalType::LocalDatetime,
Temporal::ZonedDatetime { .. } => LogicalType::ZonedDatetime,
Temporal::Duration(kind, _) => LogicalType::Duration(*kind),
}
}
pub fn parse(ty: &LogicalType, text: &str) -> Option<Temporal> {
let text = text.trim();
Some(match ty {
LogicalType::Date => Temporal::Date(parse_date(text)?),
LogicalType::LocalTime => {
let (nanos, offset) = parse_time(text)?;
if offset.is_some() {
return None;
}
Temporal::LocalTime(nanos)
}
LogicalType::ZonedTime => {
let (nanos, offset) = parse_time(text)?;
Temporal::ZonedTime {
nanos,
offset: offset.unwrap_or(0),
}
}
LogicalType::LocalDatetime => {
let (nanos, offset) = parse_datetime(text)?;
if offset.is_some() {
return None;
}
Temporal::LocalDatetime(nanos)
}
LogicalType::ZonedDatetime => {
let (nanos, offset) = parse_datetime(text)?;
let offset = offset.unwrap_or(0);
Temporal::ZonedDatetime {
nanos: nanos.checked_sub(i64::from(offset) * NANOS_PER_MINUTE)?,
offset,
}
}
LogicalType::Duration(_) => parse_duration(text)?,
_ => return None,
})
}
pub fn parse_any(text: &str) -> Option<Temporal> {
let text = text.trim();
let ty = if text.starts_with('P') || text.starts_with("-P") {
LogicalType::Duration(DurationKind::DayTime)
} else if text.contains('T') || text.contains(' ') {
if has_offset(text) {
LogicalType::ZonedDatetime
} else {
LogicalType::LocalDatetime
}
} else if text.contains(':') {
if has_offset(text) {
LogicalType::ZonedTime
} else {
LogicalType::LocalTime
}
} else {
LogicalType::Date
};
Temporal::parse(&ty, text)
}
pub fn parse_sql_interval(text: &str, qualifier: &IntervalQualifier) -> Option<Temporal> {
if qualifier.start.kind() != qualifier.end.kind()
|| qualifier.start.rank() > qualifier.end.rank()
{
return None;
}
let (negative, body) = match text.strip_prefix('-') {
Some(rest) => (true, rest),
None => (false, text.strip_prefix('+').unwrap_or(text)),
};
let fields = &FIELD_ORDER[qualifier.start.rank()..=qualifier.end.rank()];
let mut parts = Vec::with_capacity(fields.len());
let mut rest = body;
for (ix, field) in fields.iter().enumerate() {
if ix + 1 == fields.len() {
parts.push(rest);
break;
}
let separator = match field {
IntervalField::Year => '-',
IntervalField::Day => ' ',
_ => ':',
};
let (head, tail) = rest.split_once(separator)?;
parts.push(head);
rest = tail;
}
let whole = parts[0].split('.').next()?;
if qualifier
.leading
.is_some_and(|limit| whole.len() > limit as usize)
{
return None;
}
let mut months = 0i64;
let mut nanos = 0i64;
for (ix, (field, text)) in fields.iter().zip(&parts).enumerate() {
let leading = ix == 0;
match field {
IntervalField::Year => {
months = months.checked_add(uint(text)?.checked_mul(12)?)?;
}
IntervalField::Month => {
months = months.checked_add(bounded(text, leading, 11)?)?;
}
IntervalField::Day => {
nanos = nanos.checked_add(uint(text)?.checked_mul(NANOS_PER_DAY)?)?;
}
IntervalField::Hour => {
nanos = nanos
.checked_add(bounded(text, leading, 23)?.checked_mul(NANOS_PER_HOUR)?)?;
}
IntervalField::Minute => {
nanos = nanos
.checked_add(bounded(text, leading, 59)?.checked_mul(NANOS_PER_MINUTE)?)?;
}
IntervalField::Second => {
nanos =
nanos.checked_add(interval_seconds(text, leading, qualifier.fraction)?)?;
}
}
}
let sign = if negative { -1 } else { 1 };
Some(match qualifier.start.kind() {
DurationKind::YearMonth => Temporal::Duration(DurationKind::YearMonth, sign * months),
DurationKind::DayTime => Temporal::Duration(DurationKind::DayTime, sign * nanos),
})
}
pub fn from_parts(ty: &LogicalType, parts: &Parts) -> Option<Temporal> {
if let LogicalType::Duration(_) = ty {
return parts.duration();
}
let days = match ty {
LogicalType::LocalTime | LogicalType::ZonedTime => 0,
_ => parts.days()?,
};
let nanos = parts.nanos()?;
let offset = parts.timezone.unwrap_or(0);
if !(-1080..=1080).contains(&offset) {
return None;
}
Some(match ty {
LogicalType::Date => Temporal::Date(days),
LogicalType::LocalTime => Temporal::LocalTime(nanos),
LogicalType::ZonedTime => Temporal::ZonedTime { nanos, offset },
LogicalType::LocalDatetime => Temporal::LocalDatetime(instant_at(days, nanos)?),
LogicalType::ZonedDatetime => Temporal::ZonedDatetime {
nanos: instant_at(days, nanos)?
.checked_sub(i64::from(offset).checked_mul(NANOS_PER_MINUTE)?)?,
offset,
},
_ => return None,
})
}
pub fn between(from: Temporal, to: Temporal, kind: DurationKind) -> Option<Temporal> {
if std::mem::discriminant(&from) != std::mem::discriminant(&to) {
return None;
}
let count = match kind {
DurationKind::DayTime => to.elapsed()?.checked_sub(from.elapsed()?)?,
DurationKind::YearMonth => {
let ((day_a, time_a), (day_b, time_b)) = (from.civil()?, to.civil()?);
let (year_a, month_a, _) = civil_from_days(day_a);
let (year_b, month_b, _) = civil_from_days(day_b);
let mut months = (i64::from(year_b) * 12 + i64::from(month_b))
- (i64::from(year_a) * 12 + i64::from(month_a));
if months != 0 {
let landed = (add_months(day_a, months)?, time_a);
let past = if months > 0 {
landed > (day_b, time_b)
} else {
landed < (day_b, time_b)
};
if past {
months -= months.signum();
}
}
months
}
};
Some(Temporal::Duration(kind, count))
}
fn elapsed(self) -> Option<i64> {
Some(match self {
Temporal::Date(days) => i64::from(days).checked_mul(NANOS_PER_DAY)?,
Temporal::LocalTime(nanos) | Temporal::LocalDatetime(nanos) => nanos,
Temporal::ZonedTime { nanos, offset } => {
nanos.checked_sub(i64::from(offset) * NANOS_PER_MINUTE)?
}
Temporal::ZonedDatetime { nanos, .. } => nanos,
Temporal::Duration(_, _) => return None,
})
}
fn civil(self) -> Option<(i32, i64)> {
let local = match self {
Temporal::Date(days) => return Some((days, 0)),
Temporal::LocalDatetime(nanos) => nanos,
Temporal::ZonedDatetime { nanos, offset } => {
nanos.checked_add(i64::from(offset) * NANOS_PER_MINUTE)?
}
Temporal::LocalTime(_) | Temporal::ZonedTime { .. } | Temporal::Duration(_, _) => {
return None;
}
};
let days = i32::try_from(local.div_euclid(NANOS_PER_DAY)).ok()?;
Some((days, local.rem_euclid(NANOS_PER_DAY)))
}
}
#[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)]
pub enum IntervalField {
Year,
Month,
Day,
Hour,
Minute,
Second,
}
const FIELD_ORDER: [IntervalField; 6] = [
IntervalField::Year,
IntervalField::Month,
IntervalField::Day,
IntervalField::Hour,
IntervalField::Minute,
IntervalField::Second,
];
impl IntervalField {
pub fn spelled(word: &str) -> Option<IntervalField> {
FIELD_ORDER
.into_iter()
.find(|field| word.eq_ignore_ascii_case(field.word()))
}
pub fn word(self) -> &'static str {
match self {
IntervalField::Year => "YEAR",
IntervalField::Month => "MONTH",
IntervalField::Day => "DAY",
IntervalField::Hour => "HOUR",
IntervalField::Minute => "MINUTE",
IntervalField::Second => "SECOND",
}
}
pub fn rank(self) -> usize {
FIELD_ORDER
.iter()
.position(|field| *field == self)
.unwrap_or(0)
}
pub fn kind(self) -> DurationKind {
match self {
IntervalField::Year | IntervalField::Month => DurationKind::YearMonth,
_ => DurationKind::DayTime,
}
}
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub struct IntervalQualifier {
pub start: IntervalField,
pub end: IntervalField,
pub leading: Option<u32>,
pub fraction: Option<u32>,
}
impl fmt::Display for IntervalQualifier {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self.start == self.end {
true => write!(f, "{}", self.start.word()),
false => write!(f, "{} TO {}", self.start.word(), self.end.word()),
}
}
}
fn uint(text: &str) -> Option<i64> {
if text.is_empty() || !text.bytes().all(|b| b.is_ascii_digit()) {
return None;
}
text.parse().ok()
}
fn bounded(text: &str, leading: bool, most: i64) -> Option<i64> {
let value = uint(text)?;
match leading || value <= most {
true => Some(value),
false => None,
}
}
fn interval_seconds(text: &str, leading: bool, digits: Option<u32>) -> Option<i64> {
let (whole, frac) = match text.split_once('.') {
Some((whole, frac)) => (whole, Some(frac)),
None => (text, None),
};
let mut nanos = bounded(whole, leading, 59)?.checked_mul(NANOS_PER_SEC)?;
if let Some(frac) = frac {
if frac.is_empty() || frac.len() > 9 || !frac.bytes().all(|b| b.is_ascii_digit()) {
return None;
}
if digits.is_some_and(|limit| frac.len() > limit as usize) {
return None;
}
let scale = 10i64.pow(9 - frac.len() as u32);
nanos = nanos.checked_add(frac.parse::<i64>().ok()? * scale)?;
}
Some(nanos)
}
fn has_offset(text: &str) -> bool {
let time = match text.split_once(['T', 't', ' ']) {
Some((_, time)) => time,
None => text,
};
time.ends_with('Z') || time.ends_with('z') || time.contains('+') || time.contains('-')
}
fn parse_date(text: &str) -> Option<i32> {
let bytes = text.as_bytes();
if bytes.len() != 10 || bytes[4] != b'-' || bytes[7] != b'-' {
return None;
}
let year: i32 = text[0..4].parse().ok()?;
let month: u32 = text[5..7].parse().ok()?;
let day: u32 = text[8..10].parse().ok()?;
if !(1..=9999).contains(&year)
|| !(1..=12).contains(&month)
|| day < 1
|| day > days_in(year, month)
{
return None;
}
Some(days_from_civil(year, month, day))
}
fn parse_time(text: &str) -> Option<(i64, Option<i16>)> {
let (time, offset) = split_offset(text)?;
let mut parts = time.split(':');
let hour: i64 = parts.next()?.parse().ok()?;
let minute: i64 = parts.next()?.parse().ok()?;
let (second, nanos) = match parts.next() {
Some(rest) => parse_seconds(rest)?,
None => (0, 0),
};
if parts.next().is_some() || hour > 23 || minute > 59 || second > 59 {
return None;
}
let total = hour * NANOS_PER_HOUR + minute * NANOS_PER_MINUTE + second * NANOS_PER_SEC + nanos;
Some((total, offset))
}
fn parse_seconds(text: &str) -> Option<(i64, i64)> {
match text.split_once('.') {
None => Some((text.parse().ok()?, 0)),
Some((whole, frac)) => {
if frac.is_empty() || frac.len() > 9 || !frac.bytes().all(|b| b.is_ascii_digit()) {
return None;
}
let scale = 10i64.pow(9 - frac.len() as u32);
Some((whole.parse().ok()?, frac.parse::<i64>().ok()? * scale))
}
}
}
pub fn zone_offset(text: &str) -> Option<i16> {
match split_offset(text.trim())? {
("", Some(minutes)) => Some(minutes),
_ => None,
}
}
fn split_offset(text: &str) -> Option<(&str, Option<i16>)> {
if let Some(rest) = text.strip_suffix('Z').or_else(|| text.strip_suffix('z')) {
return Some((rest, Some(0)));
}
let Some(sign) = text.find(['+', '-']) else {
return Some((text, None));
};
let (body, zone) = text.split_at(sign);
let negative = zone.starts_with('-');
let digits = &zone[1..];
let (hours, minutes) = match digits.split_once(':') {
Some((h, m)) => (h, m),
None if digits.len() == 4 => (&digits[0..2], &digits[2..4]),
None => (digits, "0"),
};
let hours: i16 = hours.parse().ok()?;
let minutes: i16 = minutes.parse().ok()?;
if hours > 18 || minutes > 59 {
return None;
}
let total = hours * 60 + minutes;
Some((body, Some(if negative { -total } else { total })))
}
fn parse_datetime(text: &str) -> Option<(i64, Option<i16>)> {
let Some((date, time)) = text
.split_once('T')
.or_else(|| text.split_once('t'))
.or_else(|| text.split_once(' '))
else {
return Some((instant_at(parse_date(text)?, 0)?, None));
};
let days = parse_date(date)?;
let (nanos, offset) = parse_time(time)?;
Some((instant_at(days, nanos)?, offset))
}
fn parse_duration(text: &str) -> Option<Temporal> {
let (negative, rest) = match text.strip_prefix('-') {
Some(rest) => (true, rest),
None => (false, text.strip_prefix('+').unwrap_or(text)),
};
let rest = rest.strip_prefix('P').or_else(|| rest.strip_prefix('p'))?;
let (date_part, time_part) = match rest.split_once(['T', 't']) {
Some((d, t)) => (d, Some(t)),
None => (rest, None),
};
if date_part.is_empty() && time_part.is_none_or(str::is_empty) {
return None;
}
let mut months = 0i64;
let mut nanos = 0i64;
for (value, unit) in fields(date_part)? {
match unit {
'Y' | 'y' => months = months.checked_add(whole(value)?.checked_mul(12)?)?,
'M' | 'm' => months = months.checked_add(whole(value)?)?,
'W' | 'w' => nanos = nanos.checked_add(scaled(value, 7 * NANOS_PER_DAY)?)?,
'D' | 'd' => nanos = nanos.checked_add(scaled(value, NANOS_PER_DAY)?)?,
_ => return None,
}
}
for (value, unit) in fields(time_part.unwrap_or(""))? {
match unit {
'H' | 'h' => nanos = nanos.checked_add(scaled(value, NANOS_PER_HOUR)?)?,
'M' | 'm' => nanos = nanos.checked_add(scaled(value, NANOS_PER_MINUTE)?)?,
'S' | 's' => nanos = nanos.checked_add(scaled(value, NANOS_PER_SEC)?)?,
_ => return None,
}
}
if months != 0 && nanos != 0 {
return None;
}
let sign = if negative { -1 } else { 1 };
Some(if nanos != 0 || months == 0 {
Temporal::Duration(DurationKind::DayTime, sign * nanos)
} else {
Temporal::Duration(DurationKind::YearMonth, sign * months)
})
}
fn fields(text: &str) -> Option<Vec<(&str, char)>> {
let mut out = Vec::new();
let mut start = 0;
for (ix, ch) in text.char_indices() {
if ch.is_ascii_digit() || ch == '.' || ch == ',' {
continue;
}
if (ch == '-' || ch == '+') && ix == start {
continue;
}
if ix == start {
return None;
}
out.push((&text[start..ix], ch));
start = ix + ch.len_utf8();
}
if start != text.len() {
return None;
}
Some(out)
}
fn whole(text: &str) -> Option<i64> {
text.parse().ok()
}
fn scaled(text: &str, unit: i64) -> Option<i64> {
let text = text.replace(',', ".");
let (sign, text) = match text.strip_prefix('-') {
Some(rest) => (-1, rest.to_string()),
None => (1, text.strip_prefix('+').unwrap_or(&text).to_string()),
};
let size = match text.split_once('.') {
None => text.parse::<i64>().ok()?.checked_mul(unit),
Some((whole, frac)) => {
if frac.len() > 9 || !frac.bytes().all(|b| b.is_ascii_digit()) {
return None;
}
let whole: i64 = if whole.is_empty() {
0
} else {
whole.parse().ok()?
};
let digits = frac.len() as u32;
let numerator: i64 = frac.parse().ok()?;
let part = unit.checked_mul(numerator)? / 10i64.pow(digits);
whole.checked_mul(unit)?.checked_add(part)
}
};
size?.checked_mul(sign)
}
pub fn fields_of(ty: &LogicalType) -> &'static [&'static str] {
match ty {
LogicalType::Date => &["year", "month", "day"],
LogicalType::LocalTime => &["hour", "minute", "second"],
LogicalType::ZonedTime => &["hour", "minute", "second", "timezone"],
LogicalType::LocalDatetime => &["year", "month", "day", "hour", "minute", "second"],
LogicalType::ZonedDatetime => &[
"year", "month", "day", "hour", "minute", "second", "timezone",
],
LogicalType::Duration(_) => &["year", "month", "day", "hour", "minute", "second"],
_ => &[],
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct Parts {
pub year: Option<i64>,
pub month: Option<i64>,
pub day: Option<i64>,
pub hour: Option<i64>,
pub minute: Option<i64>,
pub second: Option<f64>,
pub timezone: Option<i16>,
}
impl Parts {
fn days(&self) -> Option<i32> {
let year = i32::try_from(self.year.unwrap_or(1)).ok()?;
let month = u32::try_from(self.month.unwrap_or(1)).ok()?;
let day = u32::try_from(self.day.unwrap_or(1)).ok()?;
if !(1..=9999).contains(&year) || !(1..=12).contains(&month) {
return None;
}
if day < 1 || day > days_in(year, month) {
return None;
}
Some(days_from_civil(year, month, day))
}
fn nanos(&self) -> Option<i64> {
let hour = self.hour.unwrap_or(0);
let minute = self.minute.unwrap_or(0);
let second = self.second.unwrap_or(0.0);
if !(0..=23).contains(&hour) || !(0..=59).contains(&minute) {
return None;
}
if !(second.is_finite() && (0.0..60.0).contains(&second)) {
return None;
}
let whole = second.trunc() as i64;
let fraction = ((second - second.trunc()) * NANOS_PER_SEC as f64).round() as i64;
Some(hour * NANOS_PER_HOUR + minute * NANOS_PER_MINUTE + whole * NANOS_PER_SEC + fraction)
}
fn duration(&self) -> Option<Temporal> {
let months = self.year.unwrap_or(0).checked_mul(12)? + self.month.unwrap_or(0);
let has_months = self.year.is_some() || self.month.is_some();
let has_nanos = self.day.is_some()
|| self.hour.is_some()
|| self.minute.is_some()
|| self.second.is_some();
if has_months && has_nanos {
return None;
}
if has_months {
return Some(Temporal::Duration(DurationKind::YearMonth, months));
}
let second = self.second.unwrap_or(0.0);
if !second.is_finite() {
return None;
}
let nanos = self
.day
.unwrap_or(0)
.checked_mul(NANOS_PER_DAY)?
.checked_add(self.hour.unwrap_or(0).checked_mul(NANOS_PER_HOUR)?)?
.checked_add(self.minute.unwrap_or(0).checked_mul(NANOS_PER_MINUTE)?)?
.checked_add((second * NANOS_PER_SEC as f64).round() as i64)?;
Some(Temporal::Duration(DurationKind::DayTime, nanos))
}
}
fn days_in(year: i32, month: u32) -> u32 {
match month {
1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
4 | 6 | 9 | 11 => 30,
_ if leap(year) => 29,
_ => 28,
}
}
fn leap(year: i32) -> bool {
year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)
}
pub fn days_from_civil(year: i32, month: u32, day: u32) -> i32 {
let y = if month <= 2 { year - 1 } else { year };
let era = if y >= 0 { y } else { y - 399 } / 400;
let yoe = y - era * 400;
let m = month as i32;
let doy = (153 * (if m > 2 { m - 3 } else { m + 9 }) + 2) / 5 + day as i32 - 1;
let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
era * 146_097 + doe - 719_468
}
pub fn civil_from_days(days: i32) -> (i32, u32, u32) {
let z = days + 719_468;
let era = if z >= 0 { z } else { z - 146_096 } / 146_097;
let doe = z - era * 146_097;
let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146_096) / 365;
let y = yoe + era * 400;
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
let mp = (5 * doy + 2) / 153;
let day = (doy - (153 * mp + 2) / 5 + 1) as u32;
let month = (if mp < 10 { mp + 3 } else { mp - 9 }) as u32;
(if month <= 2 { y + 1 } else { y }, month, day)
}
pub fn add_months(days: i32, months: i64) -> Option<i32> {
let (year, month, day) = civil_from_days(days);
let total = i64::from(year) * 12 + i64::from(month) - 1 + months;
let new_year = i32::try_from(total.div_euclid(12)).ok()?;
let new_month = (total.rem_euclid(12) + 1) as u32;
if !(1..=9999).contains(&new_year) {
return None;
}
let clamped = day.min(days_in(new_year, new_month));
let out = days_from_civil(new_year, new_month, clamped);
(MIN_DAY..=MAX_DAY).contains(&out).then_some(out)
}
impl fmt::Display for Temporal {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match *self {
Temporal::Date(days) => {
let (y, m, d) = civil_from_days(days);
write!(f, "{y:04}-{m:02}-{d:02}")
}
Temporal::LocalTime(nanos) => write_time(f, nanos),
Temporal::ZonedTime { nanos, offset } => {
write_time(f, nanos)?;
write_offset(f, offset)
}
Temporal::LocalDatetime(nanos) => write_datetime(f, nanos),
Temporal::ZonedDatetime { nanos, offset } => {
write_datetime(f, nanos + i64::from(offset) * NANOS_PER_MINUTE)?;
write_offset(f, offset)
}
Temporal::Duration(kind, count) => write_duration(f, kind, count),
}
}
}
fn write_time(f: &mut fmt::Formatter<'_>, nanos: i64) -> fmt::Result {
let nanos = nanos.rem_euclid(NANOS_PER_DAY);
let (h, m) = (nanos / NANOS_PER_HOUR, nanos / NANOS_PER_MINUTE % 60);
let (s, frac) = (nanos / NANOS_PER_SEC % 60, nanos % NANOS_PER_SEC);
write!(f, "{h:02}:{m:02}:{s:02}")?;
if frac != 0 {
write!(f, ".{:09}", frac)?;
}
Ok(())
}
fn write_datetime(f: &mut fmt::Formatter<'_>, nanos: i64) -> fmt::Result {
let days = nanos.div_euclid(NANOS_PER_DAY) as i32;
let (y, m, d) = civil_from_days(days);
write!(f, "{y:04}-{m:02}-{d:02}T")?;
write_time(f, nanos.rem_euclid(NANOS_PER_DAY))
}
fn write_offset(f: &mut fmt::Formatter<'_>, offset: i16) -> fmt::Result {
if offset == 0 {
return write!(f, "Z");
}
let sign = if offset < 0 { '-' } else { '+' };
let (h, m) = (offset.abs() / 60, offset.abs() % 60);
write!(f, "{sign}{h:02}:{m:02}")
}
fn write_duration(f: &mut fmt::Formatter<'_>, kind: DurationKind, count: i64) -> fmt::Result {
if count < 0 {
write!(f, "-")?;
}
let count = count.unsigned_abs();
write!(f, "P")?;
if kind == DurationKind::YearMonth {
let (years, months) = (count / 12, count % 12);
if years != 0 {
write!(f, "{years}Y")?;
}
if months != 0 || years == 0 {
write!(f, "{months}M")?;
}
return Ok(());
}
let nanos = count as i128;
let day = NANOS_PER_DAY as i128;
let days = nanos / day;
let rest = (nanos % day) as i64;
if days != 0 {
write!(f, "{days}D")?;
}
if rest == 0 && days != 0 {
return Ok(());
}
write!(f, "T")?;
let (h, m) = (rest / NANOS_PER_HOUR, rest / NANOS_PER_MINUTE % 60);
let (s, frac) = (rest / NANOS_PER_SEC % 60, rest % NANOS_PER_SEC);
if h != 0 {
write!(f, "{h}H")?;
}
if m != 0 {
write!(f, "{m}M")?;
}
if s != 0 || frac != 0 || (h == 0 && m == 0) {
write!(f, "{s}")?;
if frac != 0 {
write!(f, ".{:09}", frac)?;
}
write!(f, "S")?;
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
fn date(text: &str) -> Temporal {
Temporal::parse(&LogicalType::Date, text).expect(text)
}
fn duration(text: &str) -> Temporal {
Temporal::parse(&LogicalType::Duration(DurationKind::DayTime), text).expect(text)
}
#[test]
fn a_date_is_a_day_count_and_prints_back_as_it_was_written() {
assert_eq!(date("1970-01-01"), Temporal::Date(0));
assert_eq!(date("2024-01-15").to_string(), "2024-01-15");
assert_eq!(date("0001-01-01"), Temporal::Date(MIN_DAY));
assert_eq!(date("9999-12-31"), Temporal::Date(MAX_DAY));
assert_eq!(Temporal::parse(&LogicalType::Date, "2023-02-29"), None);
assert_eq!(date("2024-02-29").to_string(), "2024-02-29");
assert_eq!(Temporal::parse(&LogicalType::Date, "2024-13-01"), None);
}
#[test]
fn a_round_trip_holds_across_the_whole_calendar() {
let mut day = MIN_DAY;
while day <= MAX_DAY {
let (y, m, d) = civil_from_days(day);
assert_eq!(days_from_civil(y, m, d), day, "{y:04}-{m:02}-{d:02}");
day += 97;
}
}
#[test]
fn a_time_takes_its_seconds_and_its_fraction_or_leaves_them_out() {
let time = |t: &str| Temporal::parse(&LogicalType::LocalTime, t);
assert_eq!(
time("10:30"),
Some(Temporal::LocalTime(37_800 * NANOS_PER_SEC))
);
assert_eq!(
time("10:30:15.5").map(|t| t.to_string()),
Some("10:30:15.500000000".into())
);
assert_eq!(time("24:00"), None);
assert_eq!(time("10:30+07:00"), None);
}
#[test]
fn a_zoned_datetime_stores_the_instant_and_remembers_the_offset() {
let a = Temporal::parse(&LogicalType::ZonedDatetime, "2024-01-15T10:00:00+07:00").unwrap();
let b = Temporal::parse(&LogicalType::ZonedDatetime, "2024-01-15T03:00:00Z").unwrap();
let (Temporal::ZonedDatetime { nanos: x, .. }, Temporal::ZonedDatetime { nanos: y, .. }) =
(a, b)
else {
panic!("both are zoned datetimes")
};
assert_eq!(x, y);
assert_eq!(a.to_string(), "2024-01-15T10:00:00+07:00");
assert_eq!(b.to_string(), "2024-01-15T03:00:00Z");
}
#[test]
fn a_duration_is_one_kind_or_the_other_and_never_both() {
assert_eq!(
duration("P2D"),
Temporal::Duration(DurationKind::DayTime, 2 * NANOS_PER_DAY)
);
assert_eq!(
duration("P1Y2M"),
Temporal::Duration(DurationKind::YearMonth, 14)
);
assert_eq!(
duration("PT1H30M"),
Temporal::Duration(DurationKind::DayTime, 90 * NANOS_PER_MINUTE)
);
assert_eq!(
duration("PT0.5S"),
Temporal::Duration(DurationKind::DayTime, NANOS_PER_SEC / 2)
);
assert_eq!(duration("P2D").to_string(), "P2D");
assert_eq!(duration("P1Y2M").to_string(), "P1Y2M");
assert_eq!(duration("PT1H30M").to_string(), "PT1H30M");
assert!(Temporal::parse(&LogicalType::Duration(DurationKind::DayTime), "P1M1D").is_none());
assert!(Temporal::parse(&LogicalType::Duration(DurationKind::DayTime), "P").is_none());
}
#[test]
fn a_field_of_a_duration_carries_its_own_sign() {
assert_eq!(
duration("P-1D"),
Temporal::Duration(DurationKind::DayTime, -NANOS_PER_DAY)
);
assert_eq!(
duration("P-1Y-2M"),
Temporal::Duration(DurationKind::YearMonth, -14)
);
assert_eq!(
duration("PT-0.5S"),
Temporal::Duration(DurationKind::DayTime, -NANOS_PER_SEC / 2)
);
assert_eq!(
duration("P1DT-3H"),
Temporal::Duration(DurationKind::DayTime, NANOS_PER_DAY - 3 * NANOS_PER_HOUR)
);
assert!(Temporal::parse(&LogicalType::Duration(DurationKind::DayTime), "P-D").is_none());
assert!(Temporal::parse(&LogicalType::Duration(DurationKind::DayTime), "P1-D").is_none());
}
#[test]
fn adding_months_clamps_to_the_length_of_the_month_it_lands_in() {
let jan31 = days_from_civil(2024, 1, 31);
assert_eq!(
add_months(jan31, 1).map(civil_from_days),
Some((2024, 2, 29))
);
assert_eq!(
add_months(jan31, 13).map(civil_from_days),
Some((2025, 2, 28))
);
assert_eq!(add_months(MAX_DAY, 1), None);
}
#[test]
fn a_written_value_reads_back_without_being_told_its_type() {
assert_eq!(Temporal::parse_any("2024-01-15"), Some(date("2024-01-15")));
assert_eq!(Temporal::parse_any("P2D"), Some(duration("P2D")));
assert!(matches!(
Temporal::parse_any("2024-01-15T10:00:00Z"),
Some(Temporal::ZonedDatetime { .. })
));
assert!(matches!(
Temporal::parse_any("2024-01-15T10:00:00"),
Some(Temporal::LocalDatetime(_))
));
assert!(matches!(
Temporal::parse_any("10:00:00"),
Some(Temporal::LocalTime(_))
));
assert_eq!(Temporal::parse_any("nonsense"), None);
}
fn interval(text: &str, start: IntervalField, end: IntervalField) -> Option<Temporal> {
Temporal::parse_sql_interval(
text,
&IntervalQualifier {
start,
end,
leading: None,
fraction: None,
},
)
}
#[test]
fn a_sql_interval_is_read_by_the_fields_its_qualifier_names() {
use IntervalField::{Day, Hour, Minute, Month, Second, Year};
assert_eq!(
interval("1-2", Year, Month),
Some(Temporal::Duration(DurationKind::YearMonth, 14))
);
assert_eq!(
interval("2", Month, Month),
Some(Temporal::Duration(DurationKind::YearMonth, 2))
);
assert_eq!(
interval("3 04:05:06", Day, Second),
duration("P3DT4H5M6S").into()
);
assert_eq!(interval("10:30", Hour, Minute), duration("PT10H30M").into());
assert_eq!(interval("1.5", Second, Second), duration("PT1.5S").into());
assert_eq!(interval("1", Day, Day), duration("P1D").into());
assert_eq!(interval("1", Hour, Hour), duration("PT1H").into());
assert_eq!(interval("1-2", Day, Day), None);
assert_eq!(interval("3 04:05:06", Hour, Minute), None);
assert_eq!(interval("", Day, Day), None);
assert_eq!(interval("1x", Day, Day), None);
}
#[test]
fn only_the_leading_field_of_an_interval_runs_past_its_own_size() {
use IntervalField::{Day, Hour, Minute, Month, Second, Year};
assert_eq!(interval("25", Hour, Hour), duration("PT25H").into());
assert_eq!(interval("90", Minute, Minute), duration("PT1H30M").into());
assert_eq!(
interval("13", Month, Month),
Some(Temporal::Duration(DurationKind::YearMonth, 13))
);
assert_eq!(interval("1 25:00:00", Day, Second), None);
assert_eq!(interval("1:60", Hour, Minute), None);
assert_eq!(interval("1:60", Minute, Second), None);
assert_eq!(interval("1-12", Year, Month), None);
}
#[test]
fn an_interval_precision_bounds_the_digits_that_were_written() {
use IntervalField::{Day, Second};
let bound = |text: &str, leading, fraction| {
Temporal::parse_sql_interval(
text,
&IntervalQualifier {
start: Day,
end: Day,
leading,
fraction,
},
)
.is_some()
};
assert!(bound("100", Some(3), None));
assert!(!bound("1000", Some(3), None));
assert!(bound("1000", None, None));
let seconds = |text: &str, fraction| {
Temporal::parse_sql_interval(
text,
&IntervalQualifier {
start: Second,
end: Second,
leading: Some(2),
fraction,
},
)
.is_some()
};
assert!(seconds("1.123", Some(3)));
assert!(!seconds("1.1234", Some(3)));
assert!(!seconds("100.1", Some(3)));
}
#[test]
fn a_datetime_stops_where_the_word_does_and_not_where_the_calendar_does() {
let datetime = |text: &str| Temporal::parse(&LogicalType::LocalDatetime, text);
assert!(datetime("2262-04-11T00:00:00").is_some());
assert!(datetime("1677-09-22T00:00:00").is_some());
assert_eq!(datetime("9999-12-31T00:00:00"), None);
assert_eq!(datetime("1677-09-21T00:00:00"), None);
assert_eq!(datetime("9999-12-31"), None);
assert!(datetime("2262-04-11").is_some());
assert!(datetime("2262-04-11T23:47:16").is_some());
assert_eq!(datetime("2262-04-11T23:47:17"), None);
assert_eq!(instant_at(0, 0), Some(0));
assert_eq!(instant_at(1, 5), Some(NANOS_PER_DAY + 5));
assert_eq!(instant_at(MAX_DAY, 0), None);
assert_eq!(instant_at(MIN_DAY, 0), None);
}
#[test]
fn a_session_zone_is_a_displacement_and_not_a_name() {
assert_eq!(zone_offset("+07:00"), Some(420));
assert_eq!(zone_offset("-05:30"), Some(-330));
assert_eq!(zone_offset("+0700"), Some(420));
assert_eq!(zone_offset("+07"), Some(420));
assert_eq!(zone_offset(" Z "), Some(0));
assert_eq!(zone_offset("-00:00"), Some(0));
assert_eq!(zone_offset("+00:00"), Some(0));
assert_eq!(zone_offset("UTC"), None);
assert_eq!(zone_offset("Europe/Dublin"), None);
assert_eq!(zone_offset(""), None);
assert_eq!(zone_offset("+19:00"), None);
assert_eq!(zone_offset("12:00:00+07:00"), None);
}
}