1mod arithmetic;
6mod decode;
7mod input;
8#[cfg(feature = "jiff")]
9mod jiff_conversions;
10pub(crate) mod tokens;
11
12use core::{cmp::Ordering, fmt};
13
14pub use arithmetic::DateArithmeticError;
15pub use decode::DateOrder;
16pub use input::{InputContext, parse_date, parse_time, parse_timestamp, parse_timestamp_tz};
17
18use super::{PgTimeZone, PgType};
19
20pub(crate) const USECS_PER_SEC: i64 = 1_000_000;
21pub(crate) const USECS_PER_MINUTE: i64 = 60_000_000;
22pub(crate) const USECS_PER_HOUR: i64 = 3_600_000_000;
23pub(crate) const USECS_PER_DAY: i64 = 86_400_000_000;
24pub(crate) const MONTHS_PER_YEAR: i32 = 12;
25pub(crate) const POSTGRES_EPOCH_JDATE: i32 = 2_451_545;
27const UNIX_TO_POSTGRES_SECS: i64 = 946_684_800;
29const DATE_END_JULIAN: i32 = 2_147_483_494;
31const TIMESTAMP_END_DAYS: i32 = 106_751_983;
34pub(crate) const MIN_TIMESTAMP: i64 = -211_813_488_000_000_000;
36pub(crate) const END_TIMESTAMP: i64 = 9_223_371_331_200_000_000;
38const TZDISP_LIMIT: i32 = 16 * 3_600;
40
41#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, thiserror::Error)]
44#[non_exhaustive]
45pub enum DateTimeError {
46 #[error("date/time field value out of range")]
48 FieldValueOutOfRange,
49 #[error("time zone displacement out of range")]
51 TimeZoneDisplacementOutOfRange,
52 #[error("date out of range")]
54 DateOutOfRange,
55 #[error("timestamp out of range")]
57 TimestampOutOfRange,
58 #[error("value outside jiff's years -9999 to 9999")]
61 OutsideJiffRange,
62 #[error("the literal needs a time zone to read as timestamp with time zone")]
65 NeedsTimeZone,
66 #[error("time zone not recognized")]
68 TimeZoneNotRecognized,
69 #[error("invalid input syntax for type {}", .0.input_name())]
71 InvalidInputSyntax(PgType),
72 #[error("the literal needs a DateStyle field order")]
75 NeedsDateOrder,
76 #[error("the literal needs the current time")]
79 NeedsCurrentTime,
80}
81
82#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
96#[cfg_attr(
97 feature = "serde",
98 derive(serde::Serialize, serde::Deserialize),
99 serde(try_from = "i32", into = "i32")
100)]
101pub struct PgDate(i32);
102
103#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
113#[cfg_attr(
114 feature = "serde",
115 derive(serde::Serialize, serde::Deserialize),
116 serde(try_from = "i64", into = "i64")
117)]
118pub struct PgTime(i64);
119
120#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
135#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
136#[cfg_attr(feature = "serde", serde(try_from = "(i64, i32)", into = "(i64, i32)"))]
137pub struct PgTimeTz {
138 time: i64,
139 offset: i32,
140}
141
142#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
154#[cfg_attr(
155 feature = "serde",
156 derive(serde::Serialize, serde::Deserialize),
157 serde(try_from = "i64", into = "i64")
158)]
159pub struct PgTimestamp(i64);
160
161#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
171#[cfg_attr(
172 feature = "serde",
173 derive(serde::Serialize, serde::Deserialize),
174 serde(try_from = "i64", into = "i64")
175)]
176pub struct PgTimestampTz(i64);
177
178impl PgDate {
179 pub const INFINITY: Self = Self(i32::MAX);
181 pub const NEG_INFINITY: Self = Self(i32::MIN);
183
184 #[must_use]
187 pub fn from_ymd(year: i32, month: u8, day: u8) -> Option<Self> {
188 let (month, day) = (i32::from(month), i32::from(day));
189 if !(1..=12).contains(&month) || day < 1 || day > days_in_month(year, month) {
190 return None;
191 }
192 if !is_valid_julian(year, month) {
193 return None;
194 }
195 Self::from_pg_days(date2j(year, month, day) - POSTGRES_EPOCH_JDATE)
196 }
197
198 #[must_use]
201 pub const fn from_pg_days(days: i32) -> Option<Self> {
202 if is_valid_date(days) || days == i32::MAX || days == i32::MIN {
203 Some(Self(days))
204 } else {
205 None
206 }
207 }
208
209 #[must_use]
211 pub const fn pg_days(self) -> i32 {
212 self.0
213 }
214
215 #[must_use]
217 pub const fn is_finite(self) -> bool {
218 self.0 != i32::MAX && self.0 != i32::MIN
219 }
220
221 #[must_use]
230 pub fn ymd(self) -> Option<(i32, u8, u8)> {
231 self.is_finite().then(|| {
232 let (year, month, day) = j2date(self.0 + POSTGRES_EPOCH_JDATE);
233 (year, narrow_u8(month.into()), narrow_u8(day.into()))
234 })
235 }
236}
237
238impl PgTime {
239 pub const MIDNIGHT: Self = Self(0);
241
242 #[must_use]
244 pub const fn from_micros(micros: i64) -> Option<Self> {
245 if 0 <= micros && micros <= USECS_PER_DAY {
246 Some(Self(micros))
247 } else {
248 None
249 }
250 }
251
252 #[must_use]
255 pub fn from_hms_micro(hour: u8, minute: u8, second: u8, microsecond: u32) -> Option<Self> {
256 if hour > 24 || minute > 59 || second > 59 || microsecond > 999_999 {
257 return None;
258 }
259 Self::from_micros(
260 i64::from(hour) * USECS_PER_HOUR
261 + i64::from(minute) * USECS_PER_MINUTE
262 + i64::from(second) * USECS_PER_SEC
263 + i64::from(microsecond),
264 )
265 }
266
267 #[must_use]
269 pub const fn micros(self) -> i64 {
270 self.0
271 }
272
273 #[must_use]
282 pub fn hms_micro(self) -> (u8, u8, u8, u32) {
283 let (hour, minute, second, micro) = split_clock(self.0);
284 (
285 narrow_u8(hour),
286 narrow_u8(minute),
287 narrow_u8(second),
288 u32::try_from(micro).expect("a microsecond of a second fits u32"),
289 )
290 }
291}
292
293impl PgTimeTz {
294 #[must_use]
296 pub const fn new(time: PgTime, offset: i32) -> Option<Self> {
297 if -TZDISP_LIMIT <= offset && offset <= TZDISP_LIMIT {
298 Some(Self {
299 time: time.0,
300 offset,
301 })
302 } else {
303 None
304 }
305 }
306
307 #[must_use]
309 pub const fn time(self) -> PgTime {
310 PgTime(self.time)
311 }
312
313 #[must_use]
315 pub const fn offset(self) -> i32 {
316 self.offset
317 }
318
319 fn sort_key(self) -> (i64, i32) {
321 (
322 self.time - i64::from(self.offset) * USECS_PER_SEC,
323 -self.offset,
324 )
325 }
326}
327
328impl PartialOrd for PgTimeTz {
329 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
330 Some(self.cmp(other))
331 }
332}
333
334impl Ord for PgTimeTz {
335 fn cmp(&self, other: &Self) -> Ordering {
336 self.sort_key().cmp(&other.sort_key())
337 }
338}
339
340impl PgTimestamp {
341 pub const INFINITY: Self = Self(i64::MAX);
343 pub const NEG_INFINITY: Self = Self(i64::MIN);
345
346 #[must_use]
349 pub const fn from_pg_micros(micros: i64) -> Option<Self> {
350 if is_valid_timestamp(micros) || micros == i64::MAX || micros == i64::MIN {
351 Some(Self(micros))
352 } else {
353 None
354 }
355 }
356
357 #[must_use]
368 pub fn new(date: PgDate, time: PgTime) -> Option<Self> {
369 if !date.is_finite() {
370 return None;
371 }
372 i64::from(date.0)
373 .checked_mul(USECS_PER_DAY)
374 .and_then(|micros| micros.checked_add(time.0))
375 .and_then(Self::from_pg_micros)
376 .filter(|at| at.is_finite())
377 }
378
379 pub(crate) const fn from_stored(micros: i64) -> Self {
382 Self(micros)
383 }
384
385 #[must_use]
387 pub const fn pg_micros(self) -> i64 {
388 self.0
389 }
390
391 #[must_use]
393 pub const fn is_finite(self) -> bool {
394 self.0 != i64::MAX && self.0 != i64::MIN
395 }
396
397 #[must_use]
399 pub fn date(self) -> PgDate {
400 match self.0 {
401 i64::MAX => PgDate::INFINITY,
402 i64::MIN => PgDate::NEG_INFINITY,
403 micros => PgDate(narrow_days(micros.div_euclid(USECS_PER_DAY))),
404 }
405 }
406
407 #[must_use]
409 pub const fn time(self) -> Option<PgTime> {
410 if self.is_finite() {
411 Some(PgTime(self.0.rem_euclid(USECS_PER_DAY)))
412 } else {
413 None
414 }
415 }
416
417 pub fn to_timestamptz(self, zone: &PgTimeZone) -> Result<PgTimestampTz, DateTimeError> {
438 if !self.is_finite() {
439 return Ok(PgTimestampTz(self.0));
440 }
441 let offset = local_offset(zone, self.0)?;
442 let instant = self.0 - i64::from(offset) * USECS_PER_SEC;
443 if is_valid_timestamp(instant) {
444 Ok(PgTimestampTz(instant))
445 } else {
446 Err(DateTimeError::TimestampOutOfRange)
447 }
448 }
449}
450
451impl PgTimestampTz {
452 pub const INFINITY: Self = Self(i64::MAX);
454 pub const NEG_INFINITY: Self = Self(i64::MIN);
456
457 #[must_use]
460 pub const fn from_pg_micros(micros: i64) -> Option<Self> {
461 match PgTimestamp::from_pg_micros(micros) {
462 Some(at) => Some(Self(at.0)),
463 None => None,
464 }
465 }
466
467 pub(crate) const fn from_stored(micros: i64) -> Self {
470 Self(micros)
471 }
472
473 #[must_use]
475 pub const fn pg_micros(self) -> i64 {
476 self.0
477 }
478
479 #[must_use]
481 pub const fn is_finite(self) -> bool {
482 self.0 != i64::MAX && self.0 != i64::MIN
483 }
484
485 pub fn to_timestamp(self, zone: &PgTimeZone) -> Result<PgTimestamp, DateTimeError> {
505 if !self.is_finite() {
506 return Ok(PgTimestamp(self.0));
507 }
508 let local = self.0 + i64::from(utc_offset(zone, self.0)?) * USECS_PER_SEC;
509 if is_valid_timestamp(local) {
510 Ok(PgTimestamp(local))
511 } else {
512 Err(DateTimeError::TimestampOutOfRange)
513 }
514 }
515
516 pub fn to_date(self, zone: &PgTimeZone) -> Result<PgDate, DateTimeError> {
524 match self.0 {
525 i64::MAX => Ok(PgDate::INFINITY),
526 i64::MIN => Ok(PgDate::NEG_INFINITY),
527 utc => {
528 let local = utc + i64::from(utc_offset(zone, utc)?) * USECS_PER_SEC;
529 Ok(PgDate(narrow_days(local.div_euclid(USECS_PER_DAY))))
530 }
531 }
532 }
533}
534
535pub(crate) fn utc_offset(zone: &PgTimeZone, utc: i64) -> Result<i32, DateTimeError> {
538 let unix = utc.div_euclid(USECS_PER_SEC) + UNIX_TO_POSTGRES_SECS;
539 zone.utc_offset(unix).ok_or(DateTimeError::OutsideJiffRange)
540}
541
542pub(crate) fn local_offset(zone: &PgTimeZone, local: i64) -> Result<i32, DateTimeError> {
547 const JIFF_OFFSET_LIMIT: i64 = 26 * USECS_PER_HOUR;
549 let unix = local.div_euclid(USECS_PER_SEC) + UNIX_TO_POSTGRES_SECS;
550 zone.local_offset(unix).ok_or(
551 if (MIN_TIMESTAMP - JIFF_OFFSET_LIMIT..END_TIMESTAMP + JIFF_OFFSET_LIMIT).contains(&local) {
552 DateTimeError::OutsideJiffRange
553 } else {
554 DateTimeError::TimestampOutOfRange
555 },
556 )
557}
558
559pub(crate) fn abbreviation_offset(
563 zone: &PgTimeZone,
564 abbreviation: &str,
565 local: i64,
566) -> Result<i32, DateTimeError> {
567 let zone_offset = local_offset(zone, local)?;
568 let unix = local.div_euclid(USECS_PER_SEC) + UNIX_TO_POSTGRES_SECS - i64::from(zone_offset);
569 Ok(zone
570 .interpret_abbreviation(abbreviation, unix)?
571 .map_or(zone_offset, |meaning| meaning.offset))
572}
573
574pub(crate) const fn is_valid_timestamp(micros: i64) -> bool {
576 MIN_TIMESTAMP <= micros && micros < END_TIMESTAMP
577}
578
579const fn is_valid_date(days: i32) -> bool {
581 -POSTGRES_EPOCH_JDATE <= days && days < DATE_END_JULIAN - POSTGRES_EPOCH_JDATE
582}
583
584pub(crate) const fn is_valid_julian(year: i32, month: i32) -> bool {
586 (year > -4713 || (year == -4713 && month >= 11))
587 && (year < 5_874_898 || (year == 5_874_898 && month < 6))
588}
589
590pub(crate) fn tm2timestamp(
593 year: i32,
594 month: i32,
595 day: i32,
596 clock: i64,
597 offset: i32,
598) -> Option<i64> {
599 if !is_valid_julian(year, month) {
600 return None;
601 }
602 let days = i64::from(date2j(year, month, day) - POSTGRES_EPOCH_JDATE);
603 days.checked_mul(USECS_PER_DAY)?
604 .checked_add(clock)?
605 .checked_sub(i64::from(offset) * USECS_PER_SEC)
606 .filter(|µs| is_valid_timestamp(micros))
607}
608
609pub(crate) fn timestamp2tm(micros: i64) -> (i32, i32, i32, i64) {
612 let (year, month, day) =
613 j2date(narrow_days(micros.div_euclid(USECS_PER_DAY)) + POSTGRES_EPOCH_JDATE);
614 (year, month, day, micros.rem_euclid(USECS_PER_DAY))
615}
616
617pub(crate) const fn date2j(year: i32, month: i32, day: i32) -> i32 {
620 let (year, month) = if month > 2 {
621 (year.wrapping_add(4800), month + 1)
622 } else {
623 (year.wrapping_add(4799), month + 13)
624 };
625 let century = year / 100;
626 let mut julian = year.wrapping_mul(365).wrapping_sub(32_167);
627 julian = julian.wrapping_add(year / 4 - century + century / 4);
628 julian.wrapping_add(7_834 * month / 256).wrapping_add(day)
629}
630
631pub(crate) const fn j2date(julian_day: i32) -> (i32, i32, i32) {
634 let mut julian = julian_day.cast_unsigned().wrapping_add(32_044);
635 let mut quad = julian / 146_097;
636 let extra = (julian - quad * 146_097) * 4 + 3;
637 julian = julian.wrapping_add(60 + quad * 3 + extra / 146_097);
638 quad = julian / 1_461;
639 julian -= quad * 1_461;
640 let mut year = julian * 4 / 1_461;
641 julian = if year == 0 {
642 (julian + 306) % 366
643 } else {
644 (julian + 305) % 365
645 } + 123;
646 year += quad * 4;
647 let quad = julian * 2_141 / 65_536;
648 let day = julian - 7_834 * quad / 256;
649 let month = (quad + 10) % 12 + 1;
650 (
652 year.cast_signed() - 4_800,
653 month.cast_signed(),
654 day.cast_signed(),
655 )
656}
657
658pub(crate) const fn days_in_month(year: i32, month: i32) -> i32 {
660 let leap = year % 4 == 0 && (year % 100 != 0 || year % 400 == 0);
661 match month {
662 2 if leap => 29,
663 2 => 28,
664 4 | 6 | 9 | 11 => 30,
665 _ => 31,
666 }
667}
668
669fn narrow_days(days: i64) -> i32 {
671 i32::try_from(days).expect("a timestamp lies under 2^31 days from 2000-01-01")
672}
673
674fn narrow_u8(field: i64) -> u8 {
676 u8::try_from(field).expect("a calendar or clock field fits u8")
677}
678
679const fn split_clock(micros: i64) -> (i64, i64, i64, i64) {
681 (
682 micros / USECS_PER_HOUR,
683 micros % USECS_PER_HOUR / USECS_PER_MINUTE,
684 micros % USECS_PER_MINUTE / USECS_PER_SEC,
685 micros % USECS_PER_SEC,
686 )
687}
688
689fn write_ymd(f: &mut fmt::Formatter<'_>, year: i32, month: i32, day: i32) -> fmt::Result {
692 let shown = if year > 0 { year } else { 1 - year };
693 write!(f, "{shown:04}-{month:02}-{day:02}")
694}
695
696fn write_clock(f: &mut fmt::Formatter<'_>, micros: i64) -> fmt::Result {
698 let (hour, minute, second, mut fraction) = split_clock(micros);
699 write!(f, "{hour:02}:{minute:02}:{second:02}")?;
700 if fraction > 0 {
701 let mut width = 6;
702 while fraction % 10 == 0 {
703 fraction /= 10;
704 width -= 1;
705 }
706 write!(f, ".{fraction:0width$}")?;
707 }
708 Ok(())
709}
710
711fn write_offset(f: &mut fmt::Formatter<'_>, offset: i32) -> fmt::Result {
713 let sign = if offset >= 0 { '+' } else { '-' };
714 let magnitude = offset.unsigned_abs();
715 let (hour, minute, second) = (magnitude / 3_600, magnitude / 60 % 60, magnitude % 60);
716 write!(f, "{sign}{hour:02}")?;
717 if second != 0 {
718 write!(f, ":{minute:02}:{second:02}")
719 } else if minute != 0 {
720 write!(f, ":{minute:02}")
721 } else {
722 Ok(())
723 }
724}
725
726fn write_timestamp(f: &mut fmt::Formatter<'_>, micros: i64, zone: bool) -> fmt::Result {
728 match micros {
729 i64::MAX => return f.write_str("infinity"),
730 i64::MIN => return f.write_str("-infinity"),
731 _ => {}
732 }
733 let (year, month, day, clock) = timestamp2tm(micros);
734 write_ymd(f, year, month, day)?;
735 f.write_str(" ")?;
736 write_clock(f, clock)?;
737 if zone {
738 f.write_str("+00")?;
739 }
740 if year <= 0 {
741 f.write_str(" BC")?;
742 }
743 Ok(())
744}
745
746impl fmt::Display for PgDate {
747 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
748 match self.0 {
749 i32::MAX => f.write_str("infinity"),
750 i32::MIN => f.write_str("-infinity"),
751 days => {
752 let (year, month, day) = j2date(days + POSTGRES_EPOCH_JDATE);
753 write_ymd(f, year, month, day)?;
754 if year <= 0 {
755 f.write_str(" BC")?;
756 }
757 Ok(())
758 }
759 }
760 }
761}
762
763impl fmt::Display for PgTime {
764 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
765 write_clock(f, self.0)
766 }
767}
768
769impl fmt::Display for PgTimeTz {
770 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
771 write_clock(f, self.time)?;
772 write_offset(f, self.offset)
773 }
774}
775
776impl fmt::Display for PgTimestamp {
777 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
778 write_timestamp(f, self.0, false)
779 }
780}
781
782impl fmt::Display for PgTimestampTz {
783 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
784 write_timestamp(f, self.0, true)
785 }
786}
787
788impl TryFrom<i32> for PgDate {
789 type Error = DateTimeError;
790
791 fn try_from(days: i32) -> Result<Self, Self::Error> {
792 Self::from_pg_days(days).ok_or(DateTimeError::DateOutOfRange)
793 }
794}
795
796impl From<PgDate> for i32 {
797 fn from(date: PgDate) -> Self {
798 date.0
799 }
800}
801
802impl TryFrom<i64> for PgTime {
803 type Error = DateTimeError;
804
805 fn try_from(micros: i64) -> Result<Self, Self::Error> {
806 Self::from_micros(micros).ok_or(DateTimeError::FieldValueOutOfRange)
807 }
808}
809
810impl From<PgTime> for i64 {
811 fn from(time: PgTime) -> Self {
812 time.0
813 }
814}
815
816impl TryFrom<(i64, i32)> for PgTimeTz {
817 type Error = DateTimeError;
818
819 fn try_from((micros, offset): (i64, i32)) -> Result<Self, Self::Error> {
820 let time = PgTime::try_from(micros)?;
821 Self::new(time, offset).ok_or(DateTimeError::TimeZoneDisplacementOutOfRange)
822 }
823}
824
825impl From<PgTimeTz> for (i64, i32) {
826 fn from(time: PgTimeTz) -> Self {
827 (time.time, time.offset)
828 }
829}
830
831impl TryFrom<i64> for PgTimestamp {
832 type Error = DateTimeError;
833
834 fn try_from(micros: i64) -> Result<Self, Self::Error> {
835 Self::from_pg_micros(micros).ok_or(DateTimeError::TimestampOutOfRange)
836 }
837}
838
839impl From<PgTimestamp> for i64 {
840 fn from(at: PgTimestamp) -> Self {
841 at.0
842 }
843}
844
845impl TryFrom<i64> for PgTimestampTz {
846 type Error = DateTimeError;
847
848 fn try_from(micros: i64) -> Result<Self, Self::Error> {
849 Self::from_pg_micros(micros).ok_or(DateTimeError::TimestampOutOfRange)
850 }
851}
852
853impl From<PgTimestampTz> for i64 {
854 fn from(at: PgTimestampTz) -> Self {
855 at.0
856 }
857}