1use std::fmt;
33
34use crate::types::{DurationKind, LogicalType};
35
36const NANOS_PER_SEC: i64 = 1_000_000_000;
40pub const NANOS_PER_MINUTE: i64 = 60 * NANOS_PER_SEC;
41const NANOS_PER_HOUR: i64 = 60 * NANOS_PER_MINUTE;
42pub const NANOS_PER_DAY: i64 = 24 * NANOS_PER_HOUR;
43
44pub const MIN_DAY: i32 = -719_162;
52pub const MAX_DAY: i32 = 2_932_896;
53
54pub fn instant_at(days: i32, nanos: i64) -> Option<i64> {
69 i64::from(days)
70 .checked_mul(NANOS_PER_DAY)?
71 .checked_add(nanos)
72}
73
74#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
89pub struct Clock {
90 pub nanos: i64,
92 pub offset: i16,
94}
95
96impl Clock {
97 pub fn read() -> Clock {
110 let nanos = std::time::SystemTime::now()
111 .duration_since(std::time::UNIX_EPOCH)
112 .map(|since| i64::try_from(since.as_nanos()).unwrap_or(i64::MAX))
113 .unwrap_or(0);
114 Clock { nanos, offset: 0 }
115 }
116
117 pub fn instant(self) -> Temporal {
120 Temporal::ZonedDatetime {
121 nanos: self.nanos,
122 offset: self.offset,
123 }
124 }
125}
126
127#[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)]
133pub enum Temporal {
134 Date(i32),
136 LocalTime(i64),
138 ZonedTime { nanos: i64, offset: i16 },
141 LocalDatetime(i64),
143 ZonedDatetime { nanos: i64, offset: i16 },
146 Duration(DurationKind, i64),
150}
151
152impl Temporal {
153 pub fn logical_type(&self) -> LogicalType {
155 match self {
156 Temporal::Date(_) => LogicalType::Date,
157 Temporal::LocalTime(_) => LogicalType::LocalTime,
158 Temporal::ZonedTime { .. } => LogicalType::ZonedTime,
159 Temporal::LocalDatetime(_) => LogicalType::LocalDatetime,
160 Temporal::ZonedDatetime { .. } => LogicalType::ZonedDatetime,
161 Temporal::Duration(kind, _) => LogicalType::Duration(*kind),
162 }
163 }
164
165 pub fn parse(ty: &LogicalType, text: &str) -> Option<Temporal> {
173 let text = text.trim();
174 Some(match ty {
175 LogicalType::Date => Temporal::Date(parse_date(text)?),
176 LogicalType::LocalTime => {
177 let (nanos, offset) = parse_time(text)?;
178 if offset.is_some() {
179 return None;
180 }
181 Temporal::LocalTime(nanos)
182 }
183 LogicalType::ZonedTime => {
184 let (nanos, offset) = parse_time(text)?;
185 Temporal::ZonedTime {
186 nanos,
187 offset: offset.unwrap_or(0),
188 }
189 }
190 LogicalType::LocalDatetime => {
191 let (nanos, offset) = parse_datetime(text)?;
192 if offset.is_some() {
193 return None;
194 }
195 Temporal::LocalDatetime(nanos)
196 }
197 LogicalType::ZonedDatetime => {
198 let (nanos, offset) = parse_datetime(text)?;
199 let offset = offset.unwrap_or(0);
205 Temporal::ZonedDatetime {
206 nanos: nanos.checked_sub(i64::from(offset) * NANOS_PER_MINUTE)?,
207 offset,
208 }
209 }
210 LogicalType::Duration(_) => parse_duration(text)?,
211 _ => return None,
212 })
213 }
214
215 pub fn parse_any(text: &str) -> Option<Temporal> {
223 let text = text.trim();
224 let ty = if text.starts_with('P') || text.starts_with("-P") {
225 LogicalType::Duration(DurationKind::DayTime)
226 } else if text.contains('T') || text.contains(' ') {
227 if has_offset(text) {
228 LogicalType::ZonedDatetime
229 } else {
230 LogicalType::LocalDatetime
231 }
232 } else if text.contains(':') {
233 if has_offset(text) {
234 LogicalType::ZonedTime
235 } else {
236 LogicalType::LocalTime
237 }
238 } else {
239 LogicalType::Date
240 };
241 Temporal::parse(&ty, text)
242 }
243
244 pub fn parse_sql_interval(text: &str, qualifier: &IntervalQualifier) -> Option<Temporal> {
263 if qualifier.start.kind() != qualifier.end.kind()
264 || qualifier.start.rank() > qualifier.end.rank()
265 {
266 return None;
267 }
268 let (negative, body) = match text.strip_prefix('-') {
269 Some(rest) => (true, rest),
270 None => (false, text.strip_prefix('+').unwrap_or(text)),
271 };
272 let fields = &FIELD_ORDER[qualifier.start.rank()..=qualifier.end.rank()];
273 let mut parts = Vec::with_capacity(fields.len());
279 let mut rest = body;
280 for (ix, field) in fields.iter().enumerate() {
281 if ix + 1 == fields.len() {
282 parts.push(rest);
283 break;
284 }
285 let separator = match field {
286 IntervalField::Year => '-',
287 IntervalField::Day => ' ',
288 _ => ':',
289 };
290 let (head, tail) = rest.split_once(separator)?;
291 parts.push(head);
292 rest = tail;
293 }
294 let whole = parts[0].split('.').next()?;
299 if qualifier
300 .leading
301 .is_some_and(|limit| whole.len() > limit as usize)
302 {
303 return None;
304 }
305 let mut months = 0i64;
306 let mut nanos = 0i64;
307 for (ix, (field, text)) in fields.iter().zip(&parts).enumerate() {
308 let leading = ix == 0;
309 match field {
310 IntervalField::Year => {
311 months = months.checked_add(uint(text)?.checked_mul(12)?)?;
312 }
313 IntervalField::Month => {
314 months = months.checked_add(bounded(text, leading, 11)?)?;
315 }
316 IntervalField::Day => {
317 nanos = nanos.checked_add(uint(text)?.checked_mul(NANOS_PER_DAY)?)?;
318 }
319 IntervalField::Hour => {
320 nanos = nanos
321 .checked_add(bounded(text, leading, 23)?.checked_mul(NANOS_PER_HOUR)?)?;
322 }
323 IntervalField::Minute => {
324 nanos = nanos
325 .checked_add(bounded(text, leading, 59)?.checked_mul(NANOS_PER_MINUTE)?)?;
326 }
327 IntervalField::Second => {
328 nanos =
329 nanos.checked_add(interval_seconds(text, leading, qualifier.fraction)?)?;
330 }
331 }
332 }
333 let sign = if negative { -1 } else { 1 };
334 Some(match qualifier.start.kind() {
335 DurationKind::YearMonth => Temporal::Duration(DurationKind::YearMonth, sign * months),
336 DurationKind::DayTime => Temporal::Duration(DurationKind::DayTime, sign * nanos),
337 })
338 }
339
340 pub fn from_parts(ty: &LogicalType, parts: &Parts) -> Option<Temporal> {
355 if let LogicalType::Duration(_) = ty {
356 return parts.duration();
357 }
358 let days = match ty {
359 LogicalType::LocalTime | LogicalType::ZonedTime => 0,
360 _ => parts.days()?,
361 };
362 let nanos = parts.nanos()?;
363 let offset = parts.timezone.unwrap_or(0);
364 if !(-1080..=1080).contains(&offset) {
365 return None;
366 }
367 Some(match ty {
368 LogicalType::Date => Temporal::Date(days),
369 LogicalType::LocalTime => Temporal::LocalTime(nanos),
370 LogicalType::ZonedTime => Temporal::ZonedTime { nanos, offset },
371 LogicalType::LocalDatetime => Temporal::LocalDatetime(instant_at(days, nanos)?),
372 LogicalType::ZonedDatetime => Temporal::ZonedDatetime {
373 nanos: instant_at(days, nanos)?
374 .checked_sub(i64::from(offset).checked_mul(NANOS_PER_MINUTE)?)?,
375 offset,
376 },
377 _ => return None,
378 })
379 }
380
381 pub fn between(from: Temporal, to: Temporal, kind: DurationKind) -> Option<Temporal> {
411 if std::mem::discriminant(&from) != std::mem::discriminant(&to) {
412 return None;
413 }
414 let count = match kind {
415 DurationKind::DayTime => to.elapsed()?.checked_sub(from.elapsed()?)?,
416 DurationKind::YearMonth => {
417 let ((day_a, time_a), (day_b, time_b)) = (from.civil()?, to.civil()?);
418 let (year_a, month_a, _) = civil_from_days(day_a);
419 let (year_b, month_b, _) = civil_from_days(day_b);
420 let mut months = (i64::from(year_b) * 12 + i64::from(month_b))
421 - (i64::from(year_a) * 12 + i64::from(month_a));
422 if months != 0 {
426 let landed = (add_months(day_a, months)?, time_a);
427 let past = if months > 0 {
428 landed > (day_b, time_b)
429 } else {
430 landed < (day_b, time_b)
431 };
432 if past {
433 months -= months.signum();
434 }
435 }
436 months
437 }
438 };
439 Some(Temporal::Duration(kind, count))
440 }
441
442 fn elapsed(self) -> Option<i64> {
447 Some(match self {
448 Temporal::Date(days) => i64::from(days).checked_mul(NANOS_PER_DAY)?,
449 Temporal::LocalTime(nanos) | Temporal::LocalDatetime(nanos) => nanos,
450 Temporal::ZonedTime { nanos, offset } => {
451 nanos.checked_sub(i64::from(offset) * NANOS_PER_MINUTE)?
452 }
453 Temporal::ZonedDatetime { nanos, .. } => nanos,
454 Temporal::Duration(_, _) => return None,
455 })
456 }
457
458 fn civil(self) -> Option<(i32, i64)> {
462 let local = match self {
463 Temporal::Date(days) => return Some((days, 0)),
464 Temporal::LocalDatetime(nanos) => nanos,
465 Temporal::ZonedDatetime { nanos, offset } => {
466 nanos.checked_add(i64::from(offset) * NANOS_PER_MINUTE)?
467 }
468 Temporal::LocalTime(_) | Temporal::ZonedTime { .. } | Temporal::Duration(_, _) => {
469 return None;
470 }
471 };
472 let days = i32::try_from(local.div_euclid(NANOS_PER_DAY)).ok()?;
473 Some((days, local.rem_euclid(NANOS_PER_DAY)))
474 }
475}
476
477#[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)]
480pub enum IntervalField {
481 Year,
482 Month,
483 Day,
484 Hour,
485 Minute,
486 Second,
487}
488
489const FIELD_ORDER: [IntervalField; 6] = [
492 IntervalField::Year,
493 IntervalField::Month,
494 IntervalField::Day,
495 IntervalField::Hour,
496 IntervalField::Minute,
497 IntervalField::Second,
498];
499
500impl IntervalField {
501 pub fn spelled(word: &str) -> Option<IntervalField> {
503 FIELD_ORDER
504 .into_iter()
505 .find(|field| word.eq_ignore_ascii_case(field.word()))
506 }
507
508 pub fn word(self) -> &'static str {
510 match self {
511 IntervalField::Year => "YEAR",
512 IntervalField::Month => "MONTH",
513 IntervalField::Day => "DAY",
514 IntervalField::Hour => "HOUR",
515 IntervalField::Minute => "MINUTE",
516 IntervalField::Second => "SECOND",
517 }
518 }
519
520 pub fn rank(self) -> usize {
523 FIELD_ORDER
524 .iter()
525 .position(|field| *field == self)
526 .unwrap_or(0)
527 }
528
529 pub fn kind(self) -> DurationKind {
533 match self {
534 IntervalField::Year | IntervalField::Month => DurationKind::YearMonth,
535 _ => DurationKind::DayTime,
536 }
537 }
538}
539
540#[derive(Clone, Copy, PartialEq, Eq, Debug)]
546pub struct IntervalQualifier {
547 pub start: IntervalField,
548 pub end: IntervalField,
549 pub leading: Option<u32>,
552 pub fraction: Option<u32>,
554}
555
556impl fmt::Display for IntervalQualifier {
557 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
558 match self.start == self.end {
559 true => write!(f, "{}", self.start.word()),
560 false => write!(f, "{} TO {}", self.start.word(), self.end.word()),
561 }
562 }
563}
564
565fn uint(text: &str) -> Option<i64> {
569 if text.is_empty() || !text.bytes().all(|b| b.is_ascii_digit()) {
570 return None;
571 }
572 text.parse().ok()
573}
574
575fn bounded(text: &str, leading: bool, most: i64) -> Option<i64> {
578 let value = uint(text)?;
579 match leading || value <= most {
580 true => Some(value),
581 false => None,
582 }
583}
584
585fn interval_seconds(text: &str, leading: bool, digits: Option<u32>) -> Option<i64> {
588 let (whole, frac) = match text.split_once('.') {
589 Some((whole, frac)) => (whole, Some(frac)),
590 None => (text, None),
591 };
592 let mut nanos = bounded(whole, leading, 59)?.checked_mul(NANOS_PER_SEC)?;
593 if let Some(frac) = frac {
594 if frac.is_empty() || frac.len() > 9 || !frac.bytes().all(|b| b.is_ascii_digit()) {
595 return None;
596 }
597 if digits.is_some_and(|limit| frac.len() > limit as usize) {
598 return None;
599 }
600 let scale = 10i64.pow(9 - frac.len() as u32);
601 nanos = nanos.checked_add(frac.parse::<i64>().ok()? * scale)?;
602 }
603 Some(nanos)
604}
605
606fn has_offset(text: &str) -> bool {
611 let time = match text.split_once(['T', 't', ' ']) {
612 Some((_, time)) => time,
613 None => text,
614 };
615 time.ends_with('Z') || time.ends_with('z') || time.contains('+') || time.contains('-')
616}
617
618fn parse_date(text: &str) -> Option<i32> {
620 let bytes = text.as_bytes();
621 if bytes.len() != 10 || bytes[4] != b'-' || bytes[7] != b'-' {
622 return None;
623 }
624 let year: i32 = text[0..4].parse().ok()?;
625 let month: u32 = text[5..7].parse().ok()?;
626 let day: u32 = text[8..10].parse().ok()?;
627 if !(1..=9999).contains(&year)
628 || !(1..=12).contains(&month)
629 || day < 1
630 || day > days_in(year, month)
631 {
632 return None;
633 }
634 Some(days_from_civil(year, month, day))
635}
636
637fn parse_time(text: &str) -> Option<(i64, Option<i16>)> {
640 let (time, offset) = split_offset(text)?;
641 let mut parts = time.split(':');
642 let hour: i64 = parts.next()?.parse().ok()?;
643 let minute: i64 = parts.next()?.parse().ok()?;
644 let (second, nanos) = match parts.next() {
645 Some(rest) => parse_seconds(rest)?,
646 None => (0, 0),
647 };
648 if parts.next().is_some() || hour > 23 || minute > 59 || second > 59 {
649 return None;
650 }
651 let total = hour * NANOS_PER_HOUR + minute * NANOS_PER_MINUTE + second * NANOS_PER_SEC + nanos;
652 Some((total, offset))
653}
654
655fn parse_seconds(text: &str) -> Option<(i64, i64)> {
657 match text.split_once('.') {
658 None => Some((text.parse().ok()?, 0)),
659 Some((whole, frac)) => {
660 if frac.is_empty() || frac.len() > 9 || !frac.bytes().all(|b| b.is_ascii_digit()) {
661 return None;
662 }
663 let scale = 10i64.pow(9 - frac.len() as u32);
664 Some((whole.parse().ok()?, frac.parse::<i64>().ok()? * scale))
665 }
666 }
667}
668
669pub fn zone_offset(text: &str) -> Option<i16> {
686 match split_offset(text.trim())? {
687 ("", Some(minutes)) => Some(minutes),
688 _ => None,
689 }
690}
691
692fn split_offset(text: &str) -> Option<(&str, Option<i16>)> {
698 if let Some(rest) = text.strip_suffix('Z').or_else(|| text.strip_suffix('z')) {
699 return Some((rest, Some(0)));
700 }
701 let Some(sign) = text.find(['+', '-']) else {
702 return Some((text, None));
703 };
704 let (body, zone) = text.split_at(sign);
705 let negative = zone.starts_with('-');
706 let digits = &zone[1..];
707 let (hours, minutes) = match digits.split_once(':') {
708 Some((h, m)) => (h, m),
709 None if digits.len() == 4 => (&digits[0..2], &digits[2..4]),
712 None => (digits, "0"),
713 };
714 let hours: i16 = hours.parse().ok()?;
715 let minutes: i16 = minutes.parse().ok()?;
716 if hours > 18 || minutes > 59 {
717 return None;
718 }
719 let total = hours * 60 + minutes;
720 Some((body, Some(if negative { -total } else { total })))
721}
722
723fn parse_datetime(text: &str) -> Option<(i64, Option<i16>)> {
731 let Some((date, time)) = text
732 .split_once('T')
733 .or_else(|| text.split_once('t'))
734 .or_else(|| text.split_once(' '))
735 else {
736 return Some((instant_at(parse_date(text)?, 0)?, None));
742 };
743 let days = parse_date(date)?;
744 let (nanos, offset) = parse_time(time)?;
745 Some((instant_at(days, nanos)?, offset))
746}
747
748fn parse_duration(text: &str) -> Option<Temporal> {
755 let (negative, rest) = match text.strip_prefix('-') {
756 Some(rest) => (true, rest),
757 None => (false, text.strip_prefix('+').unwrap_or(text)),
758 };
759 let rest = rest.strip_prefix('P').or_else(|| rest.strip_prefix('p'))?;
760 let (date_part, time_part) = match rest.split_once(['T', 't']) {
761 Some((d, t)) => (d, Some(t)),
762 None => (rest, None),
763 };
764 if date_part.is_empty() && time_part.is_none_or(str::is_empty) {
765 return None;
766 }
767 let mut months = 0i64;
768 let mut nanos = 0i64;
769 for (value, unit) in fields(date_part)? {
770 match unit {
771 'Y' | 'y' => months = months.checked_add(whole(value)?.checked_mul(12)?)?,
772 'M' | 'm' => months = months.checked_add(whole(value)?)?,
773 'W' | 'w' => nanos = nanos.checked_add(scaled(value, 7 * NANOS_PER_DAY)?)?,
774 'D' | 'd' => nanos = nanos.checked_add(scaled(value, NANOS_PER_DAY)?)?,
775 _ => return None,
776 }
777 }
778 for (value, unit) in fields(time_part.unwrap_or(""))? {
779 match unit {
780 'H' | 'h' => nanos = nanos.checked_add(scaled(value, NANOS_PER_HOUR)?)?,
781 'M' | 'm' => nanos = nanos.checked_add(scaled(value, NANOS_PER_MINUTE)?)?,
782 'S' | 's' => nanos = nanos.checked_add(scaled(value, NANOS_PER_SEC)?)?,
783 _ => return None,
784 }
785 }
786 if months != 0 && nanos != 0 {
787 return None;
788 }
789 let sign = if negative { -1 } else { 1 };
790 Some(if nanos != 0 || months == 0 {
791 Temporal::Duration(DurationKind::DayTime, sign * nanos)
792 } else {
793 Temporal::Duration(DurationKind::YearMonth, sign * months)
794 })
795}
796
797fn fields(text: &str) -> Option<Vec<(&str, char)>> {
799 let mut out = Vec::new();
800 let mut start = 0;
801 for (ix, ch) in text.char_indices() {
802 if ch.is_ascii_digit() || ch == '.' || ch == ',' {
803 continue;
804 }
805 if (ch == '-' || ch == '+') && ix == start {
811 continue;
812 }
813 if ix == start {
814 return None;
815 }
816 out.push((&text[start..ix], ch));
817 start = ix + ch.len_utf8();
818 }
819 if start != text.len() {
820 return None;
821 }
822 Some(out)
823}
824
825fn whole(text: &str) -> Option<i64> {
828 text.parse().ok()
829}
830
831fn scaled(text: &str, unit: i64) -> Option<i64> {
834 let text = text.replace(',', ".");
835 let (sign, text) = match text.strip_prefix('-') {
839 Some(rest) => (-1, rest.to_string()),
840 None => (1, text.strip_prefix('+').unwrap_or(&text).to_string()),
841 };
842 let size = match text.split_once('.') {
843 None => text.parse::<i64>().ok()?.checked_mul(unit),
844 Some((whole, frac)) => {
845 if frac.len() > 9 || !frac.bytes().all(|b| b.is_ascii_digit()) {
846 return None;
847 }
848 let whole: i64 = if whole.is_empty() {
849 0
850 } else {
851 whole.parse().ok()?
852 };
853 let digits = frac.len() as u32;
854 let numerator: i64 = frac.parse().ok()?;
855 let part = unit.checked_mul(numerator)? / 10i64.pow(digits);
856 whole.checked_mul(unit)?.checked_add(part)
857 }
858 };
859 size?.checked_mul(sign)
860}
861
862pub fn fields_of(ty: &LogicalType) -> &'static [&'static str] {
876 match ty {
877 LogicalType::Date => &["year", "month", "day"],
878 LogicalType::LocalTime => &["hour", "minute", "second"],
879 LogicalType::ZonedTime => &["hour", "minute", "second", "timezone"],
880 LogicalType::LocalDatetime => &["year", "month", "day", "hour", "minute", "second"],
881 LogicalType::ZonedDatetime => &[
882 "year", "month", "day", "hour", "minute", "second", "timezone",
883 ],
884 LogicalType::Duration(_) => &["year", "month", "day", "hour", "minute", "second"],
885 _ => &[],
886 }
887}
888
889#[derive(Clone, Copy, Debug, Default, PartialEq)]
897pub struct Parts {
898 pub year: Option<i64>,
899 pub month: Option<i64>,
900 pub day: Option<i64>,
901 pub hour: Option<i64>,
902 pub minute: Option<i64>,
903 pub second: Option<f64>,
904 pub timezone: Option<i16>,
907}
908
909impl Parts {
910 fn days(&self) -> Option<i32> {
918 let year = i32::try_from(self.year.unwrap_or(1)).ok()?;
919 let month = u32::try_from(self.month.unwrap_or(1)).ok()?;
920 let day = u32::try_from(self.day.unwrap_or(1)).ok()?;
921 if !(1..=9999).contains(&year) || !(1..=12).contains(&month) {
922 return None;
923 }
924 if day < 1 || day > days_in(year, month) {
925 return None;
926 }
927 Some(days_from_civil(year, month, day))
928 }
929
930 fn nanos(&self) -> Option<i64> {
937 let hour = self.hour.unwrap_or(0);
938 let minute = self.minute.unwrap_or(0);
939 let second = self.second.unwrap_or(0.0);
940 if !(0..=23).contains(&hour) || !(0..=59).contains(&minute) {
941 return None;
942 }
943 if !(second.is_finite() && (0.0..60.0).contains(&second)) {
944 return None;
945 }
946 let whole = second.trunc() as i64;
947 let fraction = ((second - second.trunc()) * NANOS_PER_SEC as f64).round() as i64;
948 Some(hour * NANOS_PER_HOUR + minute * NANOS_PER_MINUTE + whole * NANOS_PER_SEC + fraction)
949 }
950
951 fn duration(&self) -> Option<Temporal> {
959 let months = self.year.unwrap_or(0).checked_mul(12)? + self.month.unwrap_or(0);
960 let has_months = self.year.is_some() || self.month.is_some();
961 let has_nanos = self.day.is_some()
962 || self.hour.is_some()
963 || self.minute.is_some()
964 || self.second.is_some();
965 if has_months && has_nanos {
966 return None;
967 }
968 if has_months {
969 return Some(Temporal::Duration(DurationKind::YearMonth, months));
970 }
971 let second = self.second.unwrap_or(0.0);
972 if !second.is_finite() {
973 return None;
974 }
975 let nanos = self
976 .day
977 .unwrap_or(0)
978 .checked_mul(NANOS_PER_DAY)?
979 .checked_add(self.hour.unwrap_or(0).checked_mul(NANOS_PER_HOUR)?)?
980 .checked_add(self.minute.unwrap_or(0).checked_mul(NANOS_PER_MINUTE)?)?
981 .checked_add((second * NANOS_PER_SEC as f64).round() as i64)?;
982 Some(Temporal::Duration(DurationKind::DayTime, nanos))
983 }
984}
985
986fn days_in(year: i32, month: u32) -> u32 {
987 match month {
988 1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
989 4 | 6 | 9 | 11 => 30,
990 _ if leap(year) => 29,
991 _ => 28,
992 }
993}
994
995fn leap(year: i32) -> bool {
996 year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)
997}
998
999pub fn days_from_civil(year: i32, month: u32, day: u32) -> i32 {
1005 let y = if month <= 2 { year - 1 } else { year };
1006 let era = if y >= 0 { y } else { y - 399 } / 400;
1007 let yoe = y - era * 400;
1008 let m = month as i32;
1009 let doy = (153 * (if m > 2 { m - 3 } else { m + 9 }) + 2) / 5 + day as i32 - 1;
1010 let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
1011 era * 146_097 + doe - 719_468
1012}
1013
1014pub fn civil_from_days(days: i32) -> (i32, u32, u32) {
1016 let z = days + 719_468;
1017 let era = if z >= 0 { z } else { z - 146_096 } / 146_097;
1018 let doe = z - era * 146_097;
1019 let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146_096) / 365;
1020 let y = yoe + era * 400;
1021 let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
1022 let mp = (5 * doy + 2) / 153;
1023 let day = (doy - (153 * mp + 2) / 5 + 1) as u32;
1024 let month = (if mp < 10 { mp + 3 } else { mp - 9 }) as u32;
1025 (if month <= 2 { y + 1 } else { y }, month, day)
1026}
1027
1028pub fn add_months(days: i32, months: i64) -> Option<i32> {
1032 let (year, month, day) = civil_from_days(days);
1033 let total = i64::from(year) * 12 + i64::from(month) - 1 + months;
1034 let new_year = i32::try_from(total.div_euclid(12)).ok()?;
1035 let new_month = (total.rem_euclid(12) + 1) as u32;
1036 if !(1..=9999).contains(&new_year) {
1037 return None;
1038 }
1039 let clamped = day.min(days_in(new_year, new_month));
1040 let out = days_from_civil(new_year, new_month, clamped);
1041 (MIN_DAY..=MAX_DAY).contains(&out).then_some(out)
1042}
1043
1044impl fmt::Display for Temporal {
1045 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1046 match *self {
1047 Temporal::Date(days) => {
1048 let (y, m, d) = civil_from_days(days);
1049 write!(f, "{y:04}-{m:02}-{d:02}")
1050 }
1051 Temporal::LocalTime(nanos) => write_time(f, nanos),
1052 Temporal::ZonedTime { nanos, offset } => {
1053 write_time(f, nanos)?;
1054 write_offset(f, offset)
1055 }
1056 Temporal::LocalDatetime(nanos) => write_datetime(f, nanos),
1057 Temporal::ZonedDatetime { nanos, offset } => {
1058 write_datetime(f, nanos + i64::from(offset) * NANOS_PER_MINUTE)?;
1059 write_offset(f, offset)
1060 }
1061 Temporal::Duration(kind, count) => write_duration(f, kind, count),
1062 }
1063 }
1064}
1065
1066fn write_time(f: &mut fmt::Formatter<'_>, nanos: i64) -> fmt::Result {
1067 let nanos = nanos.rem_euclid(NANOS_PER_DAY);
1068 let (h, m) = (nanos / NANOS_PER_HOUR, nanos / NANOS_PER_MINUTE % 60);
1069 let (s, frac) = (nanos / NANOS_PER_SEC % 60, nanos % NANOS_PER_SEC);
1070 write!(f, "{h:02}:{m:02}:{s:02}")?;
1071 if frac != 0 {
1072 write!(f, ".{:09}", frac)?;
1073 }
1074 Ok(())
1075}
1076
1077fn write_datetime(f: &mut fmt::Formatter<'_>, nanos: i64) -> fmt::Result {
1078 let days = nanos.div_euclid(NANOS_PER_DAY) as i32;
1079 let (y, m, d) = civil_from_days(days);
1080 write!(f, "{y:04}-{m:02}-{d:02}T")?;
1081 write_time(f, nanos.rem_euclid(NANOS_PER_DAY))
1082}
1083
1084fn write_offset(f: &mut fmt::Formatter<'_>, offset: i16) -> fmt::Result {
1085 if offset == 0 {
1086 return write!(f, "Z");
1087 }
1088 let sign = if offset < 0 { '-' } else { '+' };
1089 let (h, m) = (offset.abs() / 60, offset.abs() % 60);
1090 write!(f, "{sign}{h:02}:{m:02}")
1091}
1092
1093fn write_duration(f: &mut fmt::Formatter<'_>, kind: DurationKind, count: i64) -> fmt::Result {
1096 if count < 0 {
1097 write!(f, "-")?;
1098 }
1099 let count = count.unsigned_abs();
1100 write!(f, "P")?;
1101 if kind == DurationKind::YearMonth {
1102 let (years, months) = (count / 12, count % 12);
1103 if years != 0 {
1104 write!(f, "{years}Y")?;
1105 }
1106 if months != 0 || years == 0 {
1107 write!(f, "{months}M")?;
1108 }
1109 return Ok(());
1110 }
1111 let nanos = count as i128;
1112 let day = NANOS_PER_DAY as i128;
1113 let days = nanos / day;
1114 let rest = (nanos % day) as i64;
1115 if days != 0 {
1116 write!(f, "{days}D")?;
1117 }
1118 if rest == 0 && days != 0 {
1119 return Ok(());
1120 }
1121 write!(f, "T")?;
1122 let (h, m) = (rest / NANOS_PER_HOUR, rest / NANOS_PER_MINUTE % 60);
1123 let (s, frac) = (rest / NANOS_PER_SEC % 60, rest % NANOS_PER_SEC);
1124 if h != 0 {
1125 write!(f, "{h}H")?;
1126 }
1127 if m != 0 {
1128 write!(f, "{m}M")?;
1129 }
1130 if s != 0 || frac != 0 || (h == 0 && m == 0) {
1131 write!(f, "{s}")?;
1132 if frac != 0 {
1133 write!(f, ".{:09}", frac)?;
1134 }
1135 write!(f, "S")?;
1136 }
1137 Ok(())
1138}
1139
1140#[cfg(test)]
1141mod tests {
1142 use super::*;
1143
1144 fn date(text: &str) -> Temporal {
1145 Temporal::parse(&LogicalType::Date, text).expect(text)
1146 }
1147
1148 fn duration(text: &str) -> Temporal {
1149 Temporal::parse(&LogicalType::Duration(DurationKind::DayTime), text).expect(text)
1150 }
1151
1152 #[test]
1153 fn a_date_is_a_day_count_and_prints_back_as_it_was_written() {
1154 assert_eq!(date("1970-01-01"), Temporal::Date(0));
1155 assert_eq!(date("2024-01-15").to_string(), "2024-01-15");
1156 assert_eq!(date("0001-01-01"), Temporal::Date(MIN_DAY));
1157 assert_eq!(date("9999-12-31"), Temporal::Date(MAX_DAY));
1158 assert_eq!(Temporal::parse(&LogicalType::Date, "2023-02-29"), None);
1161 assert_eq!(date("2024-02-29").to_string(), "2024-02-29");
1162 assert_eq!(Temporal::parse(&LogicalType::Date, "2024-13-01"), None);
1163 }
1164
1165 #[test]
1166 fn a_round_trip_holds_across_the_whole_calendar() {
1167 let mut day = MIN_DAY;
1168 while day <= MAX_DAY {
1169 let (y, m, d) = civil_from_days(day);
1170 assert_eq!(days_from_civil(y, m, d), day, "{y:04}-{m:02}-{d:02}");
1171 day += 97;
1172 }
1173 }
1174
1175 #[test]
1176 fn a_time_takes_its_seconds_and_its_fraction_or_leaves_them_out() {
1177 let time = |t: &str| Temporal::parse(&LogicalType::LocalTime, t);
1178 assert_eq!(
1179 time("10:30"),
1180 Some(Temporal::LocalTime(37_800 * NANOS_PER_SEC))
1181 );
1182 assert_eq!(
1183 time("10:30:15.5").map(|t| t.to_string()),
1184 Some("10:30:15.500000000".into())
1185 );
1186 assert_eq!(time("24:00"), None);
1187 assert_eq!(time("10:30+07:00"), None);
1189 }
1190
1191 #[test]
1194 fn a_zoned_datetime_stores_the_instant_and_remembers_the_offset() {
1195 let a = Temporal::parse(&LogicalType::ZonedDatetime, "2024-01-15T10:00:00+07:00").unwrap();
1196 let b = Temporal::parse(&LogicalType::ZonedDatetime, "2024-01-15T03:00:00Z").unwrap();
1197 let (Temporal::ZonedDatetime { nanos: x, .. }, Temporal::ZonedDatetime { nanos: y, .. }) =
1198 (a, b)
1199 else {
1200 panic!("both are zoned datetimes")
1201 };
1202 assert_eq!(x, y);
1203 assert_eq!(a.to_string(), "2024-01-15T10:00:00+07:00");
1204 assert_eq!(b.to_string(), "2024-01-15T03:00:00Z");
1205 }
1206
1207 #[test]
1208 fn a_duration_is_one_kind_or_the_other_and_never_both() {
1209 assert_eq!(
1210 duration("P2D"),
1211 Temporal::Duration(DurationKind::DayTime, 2 * NANOS_PER_DAY)
1212 );
1213 assert_eq!(
1214 duration("P1Y2M"),
1215 Temporal::Duration(DurationKind::YearMonth, 14)
1216 );
1217 assert_eq!(
1218 duration("PT1H30M"),
1219 Temporal::Duration(DurationKind::DayTime, 90 * NANOS_PER_MINUTE)
1220 );
1221 assert_eq!(
1222 duration("PT0.5S"),
1223 Temporal::Duration(DurationKind::DayTime, NANOS_PER_SEC / 2)
1224 );
1225 assert_eq!(duration("P2D").to_string(), "P2D");
1226 assert_eq!(duration("P1Y2M").to_string(), "P1Y2M");
1227 assert_eq!(duration("PT1H30M").to_string(), "PT1H30M");
1228 assert!(Temporal::parse(&LogicalType::Duration(DurationKind::DayTime), "P1M1D").is_none());
1231 assert!(Temporal::parse(&LogicalType::Duration(DurationKind::DayTime), "P").is_none());
1232 }
1233
1234 #[test]
1238 fn a_field_of_a_duration_carries_its_own_sign() {
1239 assert_eq!(
1240 duration("P-1D"),
1241 Temporal::Duration(DurationKind::DayTime, -NANOS_PER_DAY)
1242 );
1243 assert_eq!(
1244 duration("P-1Y-2M"),
1245 Temporal::Duration(DurationKind::YearMonth, -14)
1246 );
1247 assert_eq!(
1248 duration("PT-0.5S"),
1249 Temporal::Duration(DurationKind::DayTime, -NANOS_PER_SEC / 2)
1250 );
1251 assert_eq!(
1254 duration("P1DT-3H"),
1255 Temporal::Duration(DurationKind::DayTime, NANOS_PER_DAY - 3 * NANOS_PER_HOUR)
1256 );
1257 assert!(Temporal::parse(&LogicalType::Duration(DurationKind::DayTime), "P-D").is_none());
1260 assert!(Temporal::parse(&LogicalType::Duration(DurationKind::DayTime), "P1-D").is_none());
1261 }
1262
1263 #[test]
1264 fn adding_months_clamps_to_the_length_of_the_month_it_lands_in() {
1265 let jan31 = days_from_civil(2024, 1, 31);
1266 assert_eq!(
1267 add_months(jan31, 1).map(civil_from_days),
1268 Some((2024, 2, 29))
1269 );
1270 assert_eq!(
1271 add_months(jan31, 13).map(civil_from_days),
1272 Some((2025, 2, 28))
1273 );
1274 assert_eq!(add_months(MAX_DAY, 1), None);
1275 }
1276
1277 #[test]
1278 fn a_written_value_reads_back_without_being_told_its_type() {
1279 assert_eq!(Temporal::parse_any("2024-01-15"), Some(date("2024-01-15")));
1280 assert_eq!(Temporal::parse_any("P2D"), Some(duration("P2D")));
1281 assert!(matches!(
1282 Temporal::parse_any("2024-01-15T10:00:00Z"),
1283 Some(Temporal::ZonedDatetime { .. })
1284 ));
1285 assert!(matches!(
1286 Temporal::parse_any("2024-01-15T10:00:00"),
1287 Some(Temporal::LocalDatetime(_))
1288 ));
1289 assert!(matches!(
1290 Temporal::parse_any("10:00:00"),
1291 Some(Temporal::LocalTime(_))
1292 ));
1293 assert_eq!(Temporal::parse_any("nonsense"), None);
1294 }
1295
1296 fn interval(text: &str, start: IntervalField, end: IntervalField) -> Option<Temporal> {
1297 Temporal::parse_sql_interval(
1298 text,
1299 &IntervalQualifier {
1300 start,
1301 end,
1302 leading: None,
1303 fraction: None,
1304 },
1305 )
1306 }
1307
1308 #[test]
1309 fn a_sql_interval_is_read_by_the_fields_its_qualifier_names() {
1310 use IntervalField::{Day, Hour, Minute, Month, Second, Year};
1311 assert_eq!(
1312 interval("1-2", Year, Month),
1313 Some(Temporal::Duration(DurationKind::YearMonth, 14))
1314 );
1315 assert_eq!(
1316 interval("2", Month, Month),
1317 Some(Temporal::Duration(DurationKind::YearMonth, 2))
1318 );
1319 assert_eq!(
1320 interval("3 04:05:06", Day, Second),
1321 duration("P3DT4H5M6S").into()
1322 );
1323 assert_eq!(interval("10:30", Hour, Minute), duration("PT10H30M").into());
1324 assert_eq!(interval("1.5", Second, Second), duration("PT1.5S").into());
1325 assert_eq!(interval("1", Day, Day), duration("P1D").into());
1328 assert_eq!(interval("1", Hour, Hour), duration("PT1H").into());
1329 assert_eq!(interval("1-2", Day, Day), None);
1331 assert_eq!(interval("3 04:05:06", Hour, Minute), None);
1332 assert_eq!(interval("", Day, Day), None);
1333 assert_eq!(interval("1x", Day, Day), None);
1334 }
1335
1336 #[test]
1337 fn only_the_leading_field_of_an_interval_runs_past_its_own_size() {
1338 use IntervalField::{Day, Hour, Minute, Month, Second, Year};
1339 assert_eq!(interval("25", Hour, Hour), duration("PT25H").into());
1340 assert_eq!(interval("90", Minute, Minute), duration("PT1H30M").into());
1341 assert_eq!(
1342 interval("13", Month, Month),
1343 Some(Temporal::Duration(DurationKind::YearMonth, 13))
1344 );
1345 assert_eq!(interval("1 25:00:00", Day, Second), None);
1348 assert_eq!(interval("1:60", Hour, Minute), None);
1349 assert_eq!(interval("1:60", Minute, Second), None);
1350 assert_eq!(interval("1-12", Year, Month), None);
1351 }
1352
1353 #[test]
1354 fn an_interval_precision_bounds_the_digits_that_were_written() {
1355 use IntervalField::{Day, Second};
1356 let bound = |text: &str, leading, fraction| {
1357 Temporal::parse_sql_interval(
1358 text,
1359 &IntervalQualifier {
1360 start: Day,
1361 end: Day,
1362 leading,
1363 fraction,
1364 },
1365 )
1366 .is_some()
1367 };
1368 assert!(bound("100", Some(3), None));
1369 assert!(!bound("1000", Some(3), None));
1370 assert!(bound("1000", None, None));
1371 let seconds = |text: &str, fraction| {
1372 Temporal::parse_sql_interval(
1373 text,
1374 &IntervalQualifier {
1375 start: Second,
1376 end: Second,
1377 leading: Some(2),
1378 fraction,
1379 },
1380 )
1381 .is_some()
1382 };
1383 assert!(seconds("1.123", Some(3)));
1387 assert!(!seconds("1.1234", Some(3)));
1388 assert!(!seconds("100.1", Some(3)));
1389 }
1390
1391 #[test]
1397 fn a_datetime_stops_where_the_word_does_and_not_where_the_calendar_does() {
1398 let datetime = |text: &str| Temporal::parse(&LogicalType::LocalDatetime, text);
1399
1400 assert!(datetime("2262-04-11T00:00:00").is_some());
1401 assert!(datetime("1677-09-22T00:00:00").is_some());
1402 assert_eq!(datetime("9999-12-31T00:00:00"), None);
1403 assert_eq!(datetime("1677-09-21T00:00:00"), None);
1404 assert_eq!(datetime("9999-12-31"), None);
1408 assert!(datetime("2262-04-11").is_some());
1409
1410 assert!(datetime("2262-04-11T23:47:16").is_some());
1414 assert_eq!(datetime("2262-04-11T23:47:17"), None);
1415
1416 assert_eq!(instant_at(0, 0), Some(0));
1417 assert_eq!(instant_at(1, 5), Some(NANOS_PER_DAY + 5));
1418 assert_eq!(instant_at(MAX_DAY, 0), None);
1419 assert_eq!(instant_at(MIN_DAY, 0), None);
1420 }
1421
1422 #[test]
1425 fn a_session_zone_is_a_displacement_and_not_a_name() {
1426 assert_eq!(zone_offset("+07:00"), Some(420));
1427 assert_eq!(zone_offset("-05:30"), Some(-330));
1428 assert_eq!(zone_offset("+0700"), Some(420));
1429 assert_eq!(zone_offset("+07"), Some(420));
1430 assert_eq!(zone_offset(" Z "), Some(0));
1431 assert_eq!(zone_offset("-00:00"), Some(0));
1432 assert_eq!(zone_offset("+00:00"), Some(0));
1433
1434 assert_eq!(zone_offset("UTC"), None);
1435 assert_eq!(zone_offset("Europe/Dublin"), None);
1436 assert_eq!(zone_offset(""), None);
1437 assert_eq!(zone_offset("+19:00"), None);
1440 assert_eq!(zone_offset("12:00:00+07:00"), None);
1441 }
1442}