1mod input;
6#[cfg(feature = "jiff")]
7mod jiff_conversions;
8
9use core::{cmp::Ordering, fmt};
10
11pub use input::{InputContext, parse_date, parse_time, parse_timestamp, parse_timestamp_tz};
12
13use crate::PgTimeZone;
14
15pub(crate) const USECS_PER_SEC: i64 = 1_000_000;
16pub(crate) const USECS_PER_MINUTE: i64 = 60_000_000;
17pub(crate) const USECS_PER_HOUR: i64 = 3_600_000_000;
18pub(crate) const USECS_PER_DAY: i64 = 86_400_000_000;
19pub(crate) const MONTHS_PER_YEAR: i32 = 12;
20pub(crate) const POSTGRES_EPOCH_JDATE: i32 = 2_451_545;
22const UNIX_TO_POSTGRES_SECS: i64 = 946_684_800;
24const DATE_END_JULIAN: i32 = 2_147_483_494;
26pub(crate) const MIN_TIMESTAMP: i64 = -211_813_488_000_000_000;
28pub(crate) const END_TIMESTAMP: i64 = 9_223_371_331_200_000_000;
30const TZDISP_LIMIT: i32 = 16 * 3_600;
32
33#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, thiserror::Error)]
36pub enum DateTimeError {
37 #[error("date/time field value out of range")]
39 FieldValueOutOfRange,
40 #[error("time zone displacement out of range")]
42 TimeZoneDisplacementOutOfRange,
43 #[error("date out of range")]
45 DateOutOfRange,
46 #[error("timestamp out of range")]
48 TimestampOutOfRange,
49 #[error("value outside jiff's years -9999 to 9999")]
52 OutsideJiffRange,
53 #[error("the literal needs a time zone to read as timestamp with time zone")]
56 NeedsTimeZone,
57 #[error("time zone not recognized")]
59 TimeZoneNotRecognized,
60 #[error("date/time spelling not modelled")]
65 Unsupported,
66}
67
68#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
82#[cfg_attr(
83 feature = "serde",
84 derive(serde::Serialize, serde::Deserialize),
85 serde(try_from = "i32", into = "i32")
86)]
87pub struct PgDate(i32);
88
89#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
99#[cfg_attr(
100 feature = "serde",
101 derive(serde::Serialize, serde::Deserialize),
102 serde(try_from = "i64", into = "i64")
103)]
104pub struct PgTime(i64);
105
106#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
121#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
122#[cfg_attr(feature = "serde", serde(try_from = "(i64, i32)", into = "(i64, i32)"))]
123pub struct PgTimeTz {
124 time: i64,
125 offset: i32,
126}
127
128#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
140#[cfg_attr(
141 feature = "serde",
142 derive(serde::Serialize, serde::Deserialize),
143 serde(try_from = "i64", into = "i64")
144)]
145pub struct PgTimestamp(i64);
146
147#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
157#[cfg_attr(
158 feature = "serde",
159 derive(serde::Serialize, serde::Deserialize),
160 serde(try_from = "i64", into = "i64")
161)]
162pub struct PgTimestampTz(i64);
163
164impl PgDate {
165 pub const INFINITY: Self = Self(i32::MAX);
167 pub const NEG_INFINITY: Self = Self(i32::MIN);
169
170 #[must_use]
173 pub fn from_ymd(year: i32, month: u8, day: u8) -> Option<Self> {
174 let (month, day) = (i32::from(month), i32::from(day));
175 if !(1..=12).contains(&month) || day < 1 || day > days_in_month(year, month) {
176 return None;
177 }
178 if !is_valid_julian(year, month) {
179 return None;
180 }
181 Self::from_pg_days(date2j(year, month, day) - POSTGRES_EPOCH_JDATE)
182 }
183
184 #[must_use]
187 pub const fn from_pg_days(days: i32) -> Option<Self> {
188 let valid = -POSTGRES_EPOCH_JDATE <= days && days < DATE_END_JULIAN - POSTGRES_EPOCH_JDATE;
189 if valid || days == i32::MAX || days == i32::MIN {
190 Some(Self(days))
191 } else {
192 None
193 }
194 }
195
196 #[must_use]
198 pub const fn pg_days(self) -> i32 {
199 self.0
200 }
201
202 #[must_use]
204 pub const fn is_finite(self) -> bool {
205 self.0 != i32::MAX && self.0 != i32::MIN
206 }
207
208 #[must_use]
217 pub fn ymd(self) -> Option<(i32, u8, u8)> {
218 self.is_finite().then(|| {
219 let (year, month, day) = j2date(self.0 + POSTGRES_EPOCH_JDATE);
220 (year, narrow_u8(month.into()), narrow_u8(day.into()))
221 })
222 }
223}
224
225impl PgTime {
226 pub const MIDNIGHT: Self = Self(0);
228
229 #[must_use]
231 pub const fn from_micros(micros: i64) -> Option<Self> {
232 if 0 <= micros && micros <= USECS_PER_DAY {
233 Some(Self(micros))
234 } else {
235 None
236 }
237 }
238
239 #[must_use]
242 pub fn from_hms_micro(hour: u8, minute: u8, second: u8, microsecond: u32) -> Option<Self> {
243 if hour > 24 || minute > 59 || second > 59 || microsecond > 999_999 {
244 return None;
245 }
246 Self::from_micros(
247 i64::from(hour) * USECS_PER_HOUR
248 + i64::from(minute) * USECS_PER_MINUTE
249 + i64::from(second) * USECS_PER_SEC
250 + i64::from(microsecond),
251 )
252 }
253
254 #[must_use]
256 pub const fn micros(self) -> i64 {
257 self.0
258 }
259
260 #[must_use]
269 pub fn hms_micro(self) -> (u8, u8, u8, u32) {
270 let (hour, minute, second, micro) = split_clock(self.0);
271 (
272 narrow_u8(hour),
273 narrow_u8(minute),
274 narrow_u8(second),
275 u32::try_from(micro).expect("a microsecond of a second fits u32"),
276 )
277 }
278}
279
280impl PgTimeTz {
281 #[must_use]
283 pub const fn new(time: PgTime, offset: i32) -> Option<Self> {
284 if -TZDISP_LIMIT <= offset && offset <= TZDISP_LIMIT {
285 Some(Self {
286 time: time.0,
287 offset,
288 })
289 } else {
290 None
291 }
292 }
293
294 #[must_use]
296 pub const fn time(self) -> PgTime {
297 PgTime(self.time)
298 }
299
300 #[must_use]
302 pub const fn offset(self) -> i32 {
303 self.offset
304 }
305
306 fn sort_key(self) -> (i64, i32) {
308 (
309 self.time - i64::from(self.offset) * USECS_PER_SEC,
310 -self.offset,
311 )
312 }
313}
314
315impl PartialOrd for PgTimeTz {
316 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
317 Some(self.cmp(other))
318 }
319}
320
321impl Ord for PgTimeTz {
322 fn cmp(&self, other: &Self) -> Ordering {
323 self.sort_key().cmp(&other.sort_key())
324 }
325}
326
327impl PgTimestamp {
328 pub const INFINITY: Self = Self(i64::MAX);
330 pub const NEG_INFINITY: Self = Self(i64::MIN);
332
333 #[must_use]
336 pub const fn from_pg_micros(micros: i64) -> Option<Self> {
337 if is_valid_timestamp(micros) || micros == i64::MAX || micros == i64::MIN {
338 Some(Self(micros))
339 } else {
340 None
341 }
342 }
343
344 #[must_use]
355 pub fn new(date: PgDate, time: PgTime) -> Option<Self> {
356 if !date.is_finite() {
357 return None;
358 }
359 i64::from(date.0)
360 .checked_mul(USECS_PER_DAY)
361 .and_then(|micros| micros.checked_add(time.0))
362 .and_then(Self::from_pg_micros)
363 .filter(|at| at.is_finite())
364 }
365
366 pub(crate) const fn from_stored(micros: i64) -> Self {
369 Self(micros)
370 }
371
372 #[must_use]
374 pub const fn pg_micros(self) -> i64 {
375 self.0
376 }
377
378 #[must_use]
380 pub const fn is_finite(self) -> bool {
381 self.0 != i64::MAX && self.0 != i64::MIN
382 }
383
384 #[must_use]
386 pub fn date(self) -> PgDate {
387 match self.0 {
388 i64::MAX => PgDate::INFINITY,
389 i64::MIN => PgDate::NEG_INFINITY,
390 micros => PgDate(narrow_days(micros.div_euclid(USECS_PER_DAY))),
391 }
392 }
393
394 #[must_use]
396 pub const fn time(self) -> Option<PgTime> {
397 if self.is_finite() {
398 Some(PgTime(self.0.rem_euclid(USECS_PER_DAY)))
399 } else {
400 None
401 }
402 }
403
404 pub fn to_timestamptz(self, zone: &PgTimeZone) -> Result<PgTimestampTz, DateTimeError> {
422 if !self.is_finite() {
423 return Ok(PgTimestampTz(self.0));
424 }
425 let offset = local_offset(zone, self.0)?;
426 let instant = self.0 - i64::from(offset) * USECS_PER_SEC;
427 if is_valid_timestamp(instant) {
428 Ok(PgTimestampTz(instant))
429 } else {
430 Err(DateTimeError::TimestampOutOfRange)
431 }
432 }
433}
434
435impl PgTimestampTz {
436 pub const INFINITY: Self = Self(i64::MAX);
438 pub const NEG_INFINITY: Self = Self(i64::MIN);
440
441 #[must_use]
444 pub const fn from_pg_micros(micros: i64) -> Option<Self> {
445 match PgTimestamp::from_pg_micros(micros) {
446 Some(at) => Some(Self(at.0)),
447 None => None,
448 }
449 }
450
451 pub(crate) const fn from_stored(micros: i64) -> Self {
454 Self(micros)
455 }
456
457 #[must_use]
459 pub const fn pg_micros(self) -> i64 {
460 self.0
461 }
462
463 #[must_use]
465 pub const fn is_finite(self) -> bool {
466 self.0 != i64::MAX && self.0 != i64::MIN
467 }
468
469 pub fn to_timestamp(self, zone: &PgTimeZone) -> Result<PgTimestamp, DateTimeError> {
486 if !self.is_finite() {
487 return Ok(PgTimestamp(self.0));
488 }
489 let local = self.0 + i64::from(utc_offset(zone, self.0)?) * USECS_PER_SEC;
490 if is_valid_timestamp(local) {
491 Ok(PgTimestamp(local))
492 } else {
493 Err(DateTimeError::TimestampOutOfRange)
494 }
495 }
496
497 pub fn to_date(self, zone: &PgTimeZone) -> Result<PgDate, DateTimeError> {
505 match self.0 {
506 i64::MAX => Ok(PgDate::INFINITY),
507 i64::MIN => Ok(PgDate::NEG_INFINITY),
508 utc => {
509 let local = utc + i64::from(utc_offset(zone, utc)?) * USECS_PER_SEC;
510 Ok(PgDate(narrow_days(local.div_euclid(USECS_PER_DAY))))
511 }
512 }
513 }
514}
515
516pub(crate) fn utc_offset(zone: &PgTimeZone, utc: i64) -> Result<i32, DateTimeError> {
519 let unix = utc.div_euclid(USECS_PER_SEC) + UNIX_TO_POSTGRES_SECS;
520 zone.utc_offset(unix).ok_or(DateTimeError::OutsideJiffRange)
521}
522
523pub(crate) fn local_offset(zone: &PgTimeZone, local: i64) -> Result<i32, DateTimeError> {
528 const JIFF_OFFSET_LIMIT: i64 = 26 * USECS_PER_HOUR;
530 let unix = local.div_euclid(USECS_PER_SEC) + UNIX_TO_POSTGRES_SECS;
531 zone.local_offset(unix).ok_or(
532 if (MIN_TIMESTAMP - JIFF_OFFSET_LIMIT..END_TIMESTAMP + JIFF_OFFSET_LIMIT).contains(&local) {
533 DateTimeError::OutsideJiffRange
534 } else {
535 DateTimeError::TimestampOutOfRange
536 },
537 )
538}
539
540pub(crate) fn abbreviation_offset(
544 zone: &PgTimeZone,
545 abbreviation: &str,
546 local: i64,
547) -> Result<i32, DateTimeError> {
548 let zone_offset = local_offset(zone, local)?;
549 let unix = local.div_euclid(USECS_PER_SEC) + UNIX_TO_POSTGRES_SECS - i64::from(zone_offset);
550 Ok(zone
551 .interpret_abbreviation(abbreviation, unix)?
552 .map_or(zone_offset, |meaning| meaning.offset))
553}
554
555pub(crate) const fn is_valid_timestamp(micros: i64) -> bool {
557 MIN_TIMESTAMP <= micros && micros < END_TIMESTAMP
558}
559
560pub(crate) const fn is_valid_julian(year: i32, month: i32) -> bool {
562 (year > -4713 || (year == -4713 && month >= 11))
563 && (year < 5_874_898 || (year == 5_874_898 && month < 6))
564}
565
566pub(crate) fn tm2timestamp(
569 year: i32,
570 month: i32,
571 day: i32,
572 clock: i64,
573 offset: i32,
574) -> Option<i64> {
575 if !is_valid_julian(year, month) {
576 return None;
577 }
578 let days = i64::from(date2j(year, month, day) - POSTGRES_EPOCH_JDATE);
579 days.checked_mul(USECS_PER_DAY)?
580 .checked_add(clock)?
581 .checked_sub(i64::from(offset) * USECS_PER_SEC)
582 .filter(|µs| is_valid_timestamp(micros))
583}
584
585pub(crate) fn timestamp2tm(micros: i64) -> (i32, i32, i32, i64) {
588 let (year, month, day) =
589 j2date(narrow_days(micros.div_euclid(USECS_PER_DAY)) + POSTGRES_EPOCH_JDATE);
590 (year, month, day, micros.rem_euclid(USECS_PER_DAY))
591}
592
593pub(crate) const fn date2j(year: i32, month: i32, day: i32) -> i32 {
595 let (year, month) = if month > 2 {
596 (year + 4800, month + 1)
597 } else {
598 (year + 4799, month + 13)
599 };
600 let century = year / 100;
601 let mut julian = year * 365 - 32_167;
602 julian += year / 4 - century + century / 4;
603 julian + 7_834 * month / 256 + day
604}
605
606pub(crate) const fn j2date(julian_day: i32) -> (i32, i32, i32) {
608 let mut julian = julian_day.cast_unsigned().wrapping_add(32_044);
610 let mut quad = julian / 146_097;
611 let extra = (julian - quad * 146_097) * 4 + 3;
612 julian += 60 + quad * 3 + extra / 146_097;
613 quad = julian / 1_461;
614 julian -= quad * 1_461;
615 let mut year = julian * 4 / 1_461;
616 julian = if year == 0 {
617 (julian + 306) % 366
618 } else {
619 (julian + 305) % 365
620 } + 123;
621 year += quad * 4;
622 let quad = julian * 2_141 / 65_536;
623 let day = julian - 7_834 * quad / 256;
624 let month = (quad + 10) % 12 + 1;
625 (
627 year.cast_signed() - 4_800,
628 month.cast_signed(),
629 day.cast_signed(),
630 )
631}
632
633pub(crate) const fn days_in_month(year: i32, month: i32) -> i32 {
635 let leap = year % 4 == 0 && (year % 100 != 0 || year % 400 == 0);
636 match month {
637 2 if leap => 29,
638 2 => 28,
639 4 | 6 | 9 | 11 => 30,
640 _ => 31,
641 }
642}
643
644fn narrow_days(days: i64) -> i32 {
646 i32::try_from(days).expect("a timestamp lies under 2^31 days from 2000-01-01")
647}
648
649fn narrow_u8(field: i64) -> u8 {
651 u8::try_from(field).expect("a calendar or clock field fits u8")
652}
653
654const fn split_clock(micros: i64) -> (i64, i64, i64, i64) {
656 (
657 micros / USECS_PER_HOUR,
658 micros % USECS_PER_HOUR / USECS_PER_MINUTE,
659 micros % USECS_PER_MINUTE / USECS_PER_SEC,
660 micros % USECS_PER_SEC,
661 )
662}
663
664fn write_ymd(f: &mut fmt::Formatter<'_>, year: i32, month: i32, day: i32) -> fmt::Result {
667 let shown = if year > 0 { year } else { 1 - year };
668 write!(f, "{shown:04}-{month:02}-{day:02}")
669}
670
671fn write_clock(f: &mut fmt::Formatter<'_>, micros: i64) -> fmt::Result {
673 let (hour, minute, second, mut fraction) = split_clock(micros);
674 write!(f, "{hour:02}:{minute:02}:{second:02}")?;
675 if fraction > 0 {
676 let mut width = 6;
677 while fraction % 10 == 0 {
678 fraction /= 10;
679 width -= 1;
680 }
681 write!(f, ".{fraction:0width$}")?;
682 }
683 Ok(())
684}
685
686fn write_offset(f: &mut fmt::Formatter<'_>, offset: i32) -> fmt::Result {
688 let sign = if offset >= 0 { '+' } else { '-' };
689 let magnitude = offset.unsigned_abs();
690 let (hour, minute, second) = (magnitude / 3_600, magnitude / 60 % 60, magnitude % 60);
691 write!(f, "{sign}{hour:02}")?;
692 if second != 0 {
693 write!(f, ":{minute:02}:{second:02}")
694 } else if minute != 0 {
695 write!(f, ":{minute:02}")
696 } else {
697 Ok(())
698 }
699}
700
701fn write_timestamp(f: &mut fmt::Formatter<'_>, micros: i64, zone: bool) -> fmt::Result {
703 match micros {
704 i64::MAX => return f.write_str("infinity"),
705 i64::MIN => return f.write_str("-infinity"),
706 _ => {}
707 }
708 let (year, month, day, clock) = timestamp2tm(micros);
709 write_ymd(f, year, month, day)?;
710 f.write_str(" ")?;
711 write_clock(f, clock)?;
712 if zone {
713 f.write_str("+00")?;
714 }
715 if year <= 0 {
716 f.write_str(" BC")?;
717 }
718 Ok(())
719}
720
721impl fmt::Display for PgDate {
722 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
723 match self.0 {
724 i32::MAX => f.write_str("infinity"),
725 i32::MIN => f.write_str("-infinity"),
726 days => {
727 let (year, month, day) = j2date(days + POSTGRES_EPOCH_JDATE);
728 write_ymd(f, year, month, day)?;
729 if year <= 0 {
730 f.write_str(" BC")?;
731 }
732 Ok(())
733 }
734 }
735 }
736}
737
738impl fmt::Display for PgTime {
739 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
740 write_clock(f, self.0)
741 }
742}
743
744impl fmt::Display for PgTimeTz {
745 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
746 write_clock(f, self.time)?;
747 write_offset(f, self.offset)
748 }
749}
750
751impl fmt::Display for PgTimestamp {
752 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
753 write_timestamp(f, self.0, false)
754 }
755}
756
757impl fmt::Display for PgTimestampTz {
758 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
759 write_timestamp(f, self.0, true)
760 }
761}
762
763impl TryFrom<i32> for PgDate {
764 type Error = DateTimeError;
765
766 fn try_from(days: i32) -> Result<Self, Self::Error> {
767 Self::from_pg_days(days).ok_or(DateTimeError::DateOutOfRange)
768 }
769}
770
771impl From<PgDate> for i32 {
772 fn from(date: PgDate) -> Self {
773 date.0
774 }
775}
776
777impl TryFrom<i64> for PgTime {
778 type Error = DateTimeError;
779
780 fn try_from(micros: i64) -> Result<Self, Self::Error> {
781 Self::from_micros(micros).ok_or(DateTimeError::FieldValueOutOfRange)
782 }
783}
784
785impl From<PgTime> for i64 {
786 fn from(time: PgTime) -> Self {
787 time.0
788 }
789}
790
791impl TryFrom<(i64, i32)> for PgTimeTz {
792 type Error = DateTimeError;
793
794 fn try_from((micros, offset): (i64, i32)) -> Result<Self, Self::Error> {
795 let time = PgTime::try_from(micros)?;
796 Self::new(time, offset).ok_or(DateTimeError::TimeZoneDisplacementOutOfRange)
797 }
798}
799
800impl From<PgTimeTz> for (i64, i32) {
801 fn from(time: PgTimeTz) -> Self {
802 (time.time, time.offset)
803 }
804}
805
806impl TryFrom<i64> for PgTimestamp {
807 type Error = DateTimeError;
808
809 fn try_from(micros: i64) -> Result<Self, Self::Error> {
810 Self::from_pg_micros(micros).ok_or(DateTimeError::TimestampOutOfRange)
811 }
812}
813
814impl From<PgTimestamp> for i64 {
815 fn from(at: PgTimestamp) -> Self {
816 at.0
817 }
818}
819
820impl TryFrom<i64> for PgTimestampTz {
821 type Error = DateTimeError;
822
823 fn try_from(micros: i64) -> Result<Self, Self::Error> {
824 Self::from_pg_micros(micros).ok_or(DateTimeError::TimestampOutOfRange)
825 }
826}
827
828impl From<PgTimestampTz> for i64 {
829 fn from(at: PgTimestampTz) -> Self {
830 at.0
831 }
832}