1mod decode;
6mod input;
7#[cfg(feature = "jiff")]
8mod jiff_conversions;
9pub(crate) mod tokens;
10
11use core::{cmp::Ordering, fmt};
12
13pub use decode::DateOrder;
14pub use input::{InputContext, parse_date, parse_time, parse_timestamp, parse_timestamp_tz};
15
16use crate::{PgTimeZone, PgType};
17
18pub(crate) const USECS_PER_SEC: i64 = 1_000_000;
19pub(crate) const USECS_PER_MINUTE: i64 = 60_000_000;
20pub(crate) const USECS_PER_HOUR: i64 = 3_600_000_000;
21pub(crate) const USECS_PER_DAY: i64 = 86_400_000_000;
22pub(crate) const MONTHS_PER_YEAR: i32 = 12;
23pub(crate) const POSTGRES_EPOCH_JDATE: i32 = 2_451_545;
25const UNIX_TO_POSTGRES_SECS: i64 = 946_684_800;
27const DATE_END_JULIAN: i32 = 2_147_483_494;
29pub(crate) const MIN_TIMESTAMP: i64 = -211_813_488_000_000_000;
31pub(crate) const END_TIMESTAMP: i64 = 9_223_371_331_200_000_000;
33const TZDISP_LIMIT: i32 = 16 * 3_600;
35
36#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, thiserror::Error)]
39#[non_exhaustive]
40pub enum DateTimeError {
41 #[error("date/time field value out of range")]
43 FieldValueOutOfRange,
44 #[error("time zone displacement out of range")]
46 TimeZoneDisplacementOutOfRange,
47 #[error("date out of range")]
49 DateOutOfRange,
50 #[error("timestamp out of range")]
52 TimestampOutOfRange,
53 #[error("value outside jiff's years -9999 to 9999")]
56 OutsideJiffRange,
57 #[error("the literal needs a time zone to read as timestamp with time zone")]
60 NeedsTimeZone,
61 #[error("time zone not recognized")]
63 TimeZoneNotRecognized,
64 #[error("invalid input syntax for type {}", .0.input_name())]
66 InvalidInputSyntax(PgType),
67 #[error("the literal needs a DateStyle field order")]
70 NeedsDateOrder,
71 #[error("the literal needs the current time")]
74 NeedsCurrentTime,
75}
76
77#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
91#[cfg_attr(
92 feature = "serde",
93 derive(serde::Serialize, serde::Deserialize),
94 serde(try_from = "i32", into = "i32")
95)]
96pub struct PgDate(i32);
97
98#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
108#[cfg_attr(
109 feature = "serde",
110 derive(serde::Serialize, serde::Deserialize),
111 serde(try_from = "i64", into = "i64")
112)]
113pub struct PgTime(i64);
114
115#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
130#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
131#[cfg_attr(feature = "serde", serde(try_from = "(i64, i32)", into = "(i64, i32)"))]
132pub struct PgTimeTz {
133 time: i64,
134 offset: i32,
135}
136
137#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
149#[cfg_attr(
150 feature = "serde",
151 derive(serde::Serialize, serde::Deserialize),
152 serde(try_from = "i64", into = "i64")
153)]
154pub struct PgTimestamp(i64);
155
156#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
166#[cfg_attr(
167 feature = "serde",
168 derive(serde::Serialize, serde::Deserialize),
169 serde(try_from = "i64", into = "i64")
170)]
171pub struct PgTimestampTz(i64);
172
173impl PgDate {
174 pub const INFINITY: Self = Self(i32::MAX);
176 pub const NEG_INFINITY: Self = Self(i32::MIN);
178
179 #[must_use]
182 pub fn from_ymd(year: i32, month: u8, day: u8) -> Option<Self> {
183 let (month, day) = (i32::from(month), i32::from(day));
184 if !(1..=12).contains(&month) || day < 1 || day > days_in_month(year, month) {
185 return None;
186 }
187 if !is_valid_julian(year, month) {
188 return None;
189 }
190 Self::from_pg_days(date2j(year, month, day) - POSTGRES_EPOCH_JDATE)
191 }
192
193 #[must_use]
196 pub const fn from_pg_days(days: i32) -> Option<Self> {
197 let valid = -POSTGRES_EPOCH_JDATE <= days && days < DATE_END_JULIAN - POSTGRES_EPOCH_JDATE;
198 if valid || days == i32::MAX || days == i32::MIN {
199 Some(Self(days))
200 } else {
201 None
202 }
203 }
204
205 #[must_use]
207 pub const fn pg_days(self) -> i32 {
208 self.0
209 }
210
211 #[must_use]
213 pub const fn is_finite(self) -> bool {
214 self.0 != i32::MAX && self.0 != i32::MIN
215 }
216
217 #[must_use]
226 pub fn ymd(self) -> Option<(i32, u8, u8)> {
227 self.is_finite().then(|| {
228 let (year, month, day) = j2date(self.0 + POSTGRES_EPOCH_JDATE);
229 (year, narrow_u8(month.into()), narrow_u8(day.into()))
230 })
231 }
232}
233
234impl PgTime {
235 pub const MIDNIGHT: Self = Self(0);
237
238 #[must_use]
240 pub const fn from_micros(micros: i64) -> Option<Self> {
241 if 0 <= micros && micros <= USECS_PER_DAY {
242 Some(Self(micros))
243 } else {
244 None
245 }
246 }
247
248 #[must_use]
251 pub fn from_hms_micro(hour: u8, minute: u8, second: u8, microsecond: u32) -> Option<Self> {
252 if hour > 24 || minute > 59 || second > 59 || microsecond > 999_999 {
253 return None;
254 }
255 Self::from_micros(
256 i64::from(hour) * USECS_PER_HOUR
257 + i64::from(minute) * USECS_PER_MINUTE
258 + i64::from(second) * USECS_PER_SEC
259 + i64::from(microsecond),
260 )
261 }
262
263 #[must_use]
265 pub const fn micros(self) -> i64 {
266 self.0
267 }
268
269 #[must_use]
278 pub fn hms_micro(self) -> (u8, u8, u8, u32) {
279 let (hour, minute, second, micro) = split_clock(self.0);
280 (
281 narrow_u8(hour),
282 narrow_u8(minute),
283 narrow_u8(second),
284 u32::try_from(micro).expect("a microsecond of a second fits u32"),
285 )
286 }
287}
288
289impl PgTimeTz {
290 #[must_use]
292 pub const fn new(time: PgTime, offset: i32) -> Option<Self> {
293 if -TZDISP_LIMIT <= offset && offset <= TZDISP_LIMIT {
294 Some(Self {
295 time: time.0,
296 offset,
297 })
298 } else {
299 None
300 }
301 }
302
303 #[must_use]
305 pub const fn time(self) -> PgTime {
306 PgTime(self.time)
307 }
308
309 #[must_use]
311 pub const fn offset(self) -> i32 {
312 self.offset
313 }
314
315 fn sort_key(self) -> (i64, i32) {
317 (
318 self.time - i64::from(self.offset) * USECS_PER_SEC,
319 -self.offset,
320 )
321 }
322}
323
324impl PartialOrd for PgTimeTz {
325 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
326 Some(self.cmp(other))
327 }
328}
329
330impl Ord for PgTimeTz {
331 fn cmp(&self, other: &Self) -> Ordering {
332 self.sort_key().cmp(&other.sort_key())
333 }
334}
335
336impl PgTimestamp {
337 pub const INFINITY: Self = Self(i64::MAX);
339 pub const NEG_INFINITY: Self = Self(i64::MIN);
341
342 #[must_use]
345 pub const fn from_pg_micros(micros: i64) -> Option<Self> {
346 if is_valid_timestamp(micros) || micros == i64::MAX || micros == i64::MIN {
347 Some(Self(micros))
348 } else {
349 None
350 }
351 }
352
353 #[must_use]
364 pub fn new(date: PgDate, time: PgTime) -> Option<Self> {
365 if !date.is_finite() {
366 return None;
367 }
368 i64::from(date.0)
369 .checked_mul(USECS_PER_DAY)
370 .and_then(|micros| micros.checked_add(time.0))
371 .and_then(Self::from_pg_micros)
372 .filter(|at| at.is_finite())
373 }
374
375 pub(crate) const fn from_stored(micros: i64) -> Self {
378 Self(micros)
379 }
380
381 #[must_use]
383 pub const fn pg_micros(self) -> i64 {
384 self.0
385 }
386
387 #[must_use]
389 pub const fn is_finite(self) -> bool {
390 self.0 != i64::MAX && self.0 != i64::MIN
391 }
392
393 #[must_use]
395 pub fn date(self) -> PgDate {
396 match self.0 {
397 i64::MAX => PgDate::INFINITY,
398 i64::MIN => PgDate::NEG_INFINITY,
399 micros => PgDate(narrow_days(micros.div_euclid(USECS_PER_DAY))),
400 }
401 }
402
403 #[must_use]
405 pub const fn time(self) -> Option<PgTime> {
406 if self.is_finite() {
407 Some(PgTime(self.0.rem_euclid(USECS_PER_DAY)))
408 } else {
409 None
410 }
411 }
412
413 pub fn to_timestamptz(self, zone: &PgTimeZone) -> Result<PgTimestampTz, DateTimeError> {
431 if !self.is_finite() {
432 return Ok(PgTimestampTz(self.0));
433 }
434 let offset = local_offset(zone, self.0)?;
435 let instant = self.0 - i64::from(offset) * USECS_PER_SEC;
436 if is_valid_timestamp(instant) {
437 Ok(PgTimestampTz(instant))
438 } else {
439 Err(DateTimeError::TimestampOutOfRange)
440 }
441 }
442}
443
444impl PgTimestampTz {
445 pub const INFINITY: Self = Self(i64::MAX);
447 pub const NEG_INFINITY: Self = Self(i64::MIN);
449
450 #[must_use]
453 pub const fn from_pg_micros(micros: i64) -> Option<Self> {
454 match PgTimestamp::from_pg_micros(micros) {
455 Some(at) => Some(Self(at.0)),
456 None => None,
457 }
458 }
459
460 pub(crate) const fn from_stored(micros: i64) -> Self {
463 Self(micros)
464 }
465
466 #[must_use]
468 pub const fn pg_micros(self) -> i64 {
469 self.0
470 }
471
472 #[must_use]
474 pub const fn is_finite(self) -> bool {
475 self.0 != i64::MAX && self.0 != i64::MIN
476 }
477
478 pub fn to_timestamp(self, zone: &PgTimeZone) -> Result<PgTimestamp, DateTimeError> {
495 if !self.is_finite() {
496 return Ok(PgTimestamp(self.0));
497 }
498 let local = self.0 + i64::from(utc_offset(zone, self.0)?) * USECS_PER_SEC;
499 if is_valid_timestamp(local) {
500 Ok(PgTimestamp(local))
501 } else {
502 Err(DateTimeError::TimestampOutOfRange)
503 }
504 }
505
506 pub fn to_date(self, zone: &PgTimeZone) -> Result<PgDate, DateTimeError> {
514 match self.0 {
515 i64::MAX => Ok(PgDate::INFINITY),
516 i64::MIN => Ok(PgDate::NEG_INFINITY),
517 utc => {
518 let local = utc + i64::from(utc_offset(zone, utc)?) * USECS_PER_SEC;
519 Ok(PgDate(narrow_days(local.div_euclid(USECS_PER_DAY))))
520 }
521 }
522 }
523}
524
525pub(crate) fn utc_offset(zone: &PgTimeZone, utc: i64) -> Result<i32, DateTimeError> {
528 let unix = utc.div_euclid(USECS_PER_SEC) + UNIX_TO_POSTGRES_SECS;
529 zone.utc_offset(unix).ok_or(DateTimeError::OutsideJiffRange)
530}
531
532pub(crate) fn local_offset(zone: &PgTimeZone, local: i64) -> Result<i32, DateTimeError> {
537 const JIFF_OFFSET_LIMIT: i64 = 26 * USECS_PER_HOUR;
539 let unix = local.div_euclid(USECS_PER_SEC) + UNIX_TO_POSTGRES_SECS;
540 zone.local_offset(unix).ok_or(
541 if (MIN_TIMESTAMP - JIFF_OFFSET_LIMIT..END_TIMESTAMP + JIFF_OFFSET_LIMIT).contains(&local) {
542 DateTimeError::OutsideJiffRange
543 } else {
544 DateTimeError::TimestampOutOfRange
545 },
546 )
547}
548
549pub(crate) fn abbreviation_offset(
553 zone: &PgTimeZone,
554 abbreviation: &str,
555 local: i64,
556) -> Result<i32, DateTimeError> {
557 let zone_offset = local_offset(zone, local)?;
558 let unix = local.div_euclid(USECS_PER_SEC) + UNIX_TO_POSTGRES_SECS - i64::from(zone_offset);
559 Ok(zone
560 .interpret_abbreviation(abbreviation, unix)?
561 .map_or(zone_offset, |meaning| meaning.offset))
562}
563
564pub(crate) const fn is_valid_timestamp(micros: i64) -> bool {
566 MIN_TIMESTAMP <= micros && micros < END_TIMESTAMP
567}
568
569pub(crate) const fn is_valid_julian(year: i32, month: i32) -> bool {
571 (year > -4713 || (year == -4713 && month >= 11))
572 && (year < 5_874_898 || (year == 5_874_898 && month < 6))
573}
574
575pub(crate) fn tm2timestamp(
578 year: i32,
579 month: i32,
580 day: i32,
581 clock: i64,
582 offset: i32,
583) -> Option<i64> {
584 if !is_valid_julian(year, month) {
585 return None;
586 }
587 let days = i64::from(date2j(year, month, day) - POSTGRES_EPOCH_JDATE);
588 days.checked_mul(USECS_PER_DAY)?
589 .checked_add(clock)?
590 .checked_sub(i64::from(offset) * USECS_PER_SEC)
591 .filter(|µs| is_valid_timestamp(micros))
592}
593
594pub(crate) fn timestamp2tm(micros: i64) -> (i32, i32, i32, i64) {
597 let (year, month, day) =
598 j2date(narrow_days(micros.div_euclid(USECS_PER_DAY)) + POSTGRES_EPOCH_JDATE);
599 (year, month, day, micros.rem_euclid(USECS_PER_DAY))
600}
601
602pub(crate) const fn date2j(year: i32, month: i32, day: i32) -> i32 {
605 let (year, month) = if month > 2 {
606 (year.wrapping_add(4800), month + 1)
607 } else {
608 (year.wrapping_add(4799), month + 13)
609 };
610 let century = year / 100;
611 let mut julian = year.wrapping_mul(365).wrapping_sub(32_167);
612 julian = julian.wrapping_add(year / 4 - century + century / 4);
613 julian.wrapping_add(7_834 * month / 256).wrapping_add(day)
614}
615
616pub(crate) const fn j2date(julian_day: i32) -> (i32, i32, i32) {
619 let mut julian = julian_day.cast_unsigned().wrapping_add(32_044);
620 let mut quad = julian / 146_097;
621 let extra = (julian - quad * 146_097) * 4 + 3;
622 julian = julian.wrapping_add(60 + quad * 3 + extra / 146_097);
623 quad = julian / 1_461;
624 julian -= quad * 1_461;
625 let mut year = julian * 4 / 1_461;
626 julian = if year == 0 {
627 (julian + 306) % 366
628 } else {
629 (julian + 305) % 365
630 } + 123;
631 year += quad * 4;
632 let quad = julian * 2_141 / 65_536;
633 let day = julian - 7_834 * quad / 256;
634 let month = (quad + 10) % 12 + 1;
635 (
637 year.cast_signed() - 4_800,
638 month.cast_signed(),
639 day.cast_signed(),
640 )
641}
642
643pub(crate) const fn days_in_month(year: i32, month: i32) -> i32 {
645 let leap = year % 4 == 0 && (year % 100 != 0 || year % 400 == 0);
646 match month {
647 2 if leap => 29,
648 2 => 28,
649 4 | 6 | 9 | 11 => 30,
650 _ => 31,
651 }
652}
653
654fn narrow_days(days: i64) -> i32 {
656 i32::try_from(days).expect("a timestamp lies under 2^31 days from 2000-01-01")
657}
658
659fn narrow_u8(field: i64) -> u8 {
661 u8::try_from(field).expect("a calendar or clock field fits u8")
662}
663
664const fn split_clock(micros: i64) -> (i64, i64, i64, i64) {
666 (
667 micros / USECS_PER_HOUR,
668 micros % USECS_PER_HOUR / USECS_PER_MINUTE,
669 micros % USECS_PER_MINUTE / USECS_PER_SEC,
670 micros % USECS_PER_SEC,
671 )
672}
673
674fn write_ymd(f: &mut fmt::Formatter<'_>, year: i32, month: i32, day: i32) -> fmt::Result {
677 let shown = if year > 0 { year } else { 1 - year };
678 write!(f, "{shown:04}-{month:02}-{day:02}")
679}
680
681fn write_clock(f: &mut fmt::Formatter<'_>, micros: i64) -> fmt::Result {
683 let (hour, minute, second, mut fraction) = split_clock(micros);
684 write!(f, "{hour:02}:{minute:02}:{second:02}")?;
685 if fraction > 0 {
686 let mut width = 6;
687 while fraction % 10 == 0 {
688 fraction /= 10;
689 width -= 1;
690 }
691 write!(f, ".{fraction:0width$}")?;
692 }
693 Ok(())
694}
695
696fn write_offset(f: &mut fmt::Formatter<'_>, offset: i32) -> fmt::Result {
698 let sign = if offset >= 0 { '+' } else { '-' };
699 let magnitude = offset.unsigned_abs();
700 let (hour, minute, second) = (magnitude / 3_600, magnitude / 60 % 60, magnitude % 60);
701 write!(f, "{sign}{hour:02}")?;
702 if second != 0 {
703 write!(f, ":{minute:02}:{second:02}")
704 } else if minute != 0 {
705 write!(f, ":{minute:02}")
706 } else {
707 Ok(())
708 }
709}
710
711fn write_timestamp(f: &mut fmt::Formatter<'_>, micros: i64, zone: bool) -> fmt::Result {
713 match micros {
714 i64::MAX => return f.write_str("infinity"),
715 i64::MIN => return f.write_str("-infinity"),
716 _ => {}
717 }
718 let (year, month, day, clock) = timestamp2tm(micros);
719 write_ymd(f, year, month, day)?;
720 f.write_str(" ")?;
721 write_clock(f, clock)?;
722 if zone {
723 f.write_str("+00")?;
724 }
725 if year <= 0 {
726 f.write_str(" BC")?;
727 }
728 Ok(())
729}
730
731impl fmt::Display for PgDate {
732 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
733 match self.0 {
734 i32::MAX => f.write_str("infinity"),
735 i32::MIN => f.write_str("-infinity"),
736 days => {
737 let (year, month, day) = j2date(days + POSTGRES_EPOCH_JDATE);
738 write_ymd(f, year, month, day)?;
739 if year <= 0 {
740 f.write_str(" BC")?;
741 }
742 Ok(())
743 }
744 }
745 }
746}
747
748impl fmt::Display for PgTime {
749 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
750 write_clock(f, self.0)
751 }
752}
753
754impl fmt::Display for PgTimeTz {
755 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
756 write_clock(f, self.time)?;
757 write_offset(f, self.offset)
758 }
759}
760
761impl fmt::Display for PgTimestamp {
762 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
763 write_timestamp(f, self.0, false)
764 }
765}
766
767impl fmt::Display for PgTimestampTz {
768 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
769 write_timestamp(f, self.0, true)
770 }
771}
772
773impl TryFrom<i32> for PgDate {
774 type Error = DateTimeError;
775
776 fn try_from(days: i32) -> Result<Self, Self::Error> {
777 Self::from_pg_days(days).ok_or(DateTimeError::DateOutOfRange)
778 }
779}
780
781impl From<PgDate> for i32 {
782 fn from(date: PgDate) -> Self {
783 date.0
784 }
785}
786
787impl TryFrom<i64> for PgTime {
788 type Error = DateTimeError;
789
790 fn try_from(micros: i64) -> Result<Self, Self::Error> {
791 Self::from_micros(micros).ok_or(DateTimeError::FieldValueOutOfRange)
792 }
793}
794
795impl From<PgTime> for i64 {
796 fn from(time: PgTime) -> Self {
797 time.0
798 }
799}
800
801impl TryFrom<(i64, i32)> for PgTimeTz {
802 type Error = DateTimeError;
803
804 fn try_from((micros, offset): (i64, i32)) -> Result<Self, Self::Error> {
805 let time = PgTime::try_from(micros)?;
806 Self::new(time, offset).ok_or(DateTimeError::TimeZoneDisplacementOutOfRange)
807 }
808}
809
810impl From<PgTimeTz> for (i64, i32) {
811 fn from(time: PgTimeTz) -> Self {
812 (time.time, time.offset)
813 }
814}
815
816impl TryFrom<i64> for PgTimestamp {
817 type Error = DateTimeError;
818
819 fn try_from(micros: i64) -> Result<Self, Self::Error> {
820 Self::from_pg_micros(micros).ok_or(DateTimeError::TimestampOutOfRange)
821 }
822}
823
824impl From<PgTimestamp> for i64 {
825 fn from(at: PgTimestamp) -> Self {
826 at.0
827 }
828}
829
830impl TryFrom<i64> for PgTimestampTz {
831 type Error = DateTimeError;
832
833 fn try_from(micros: i64) -> Result<Self, Self::Error> {
834 Self::from_pg_micros(micros).ok_or(DateTimeError::TimestampOutOfRange)
835 }
836}
837
838impl From<PgTimestampTz> for i64 {
839 fn from(at: PgTimestampTz) -> Self {
840 at.0
841 }
842}