1mod tznames;
12
13use alloc::{
14 borrow::Cow,
15 string::{String, ToString},
16 vec::Vec,
17};
18use core::{
19 fmt,
20 hash::{Hash, Hasher},
21};
22
23use jiff::{Timestamp, tz::TimeZone};
24use tznames::Abbreviation;
25pub(crate) use tznames::Meaning;
26pub use tznames::TimeZoneAbbreviationsError;
27
28use crate::{
29 DateTimeError, IntervalError,
30 datetime::{date2j, days_in_month, j2date},
31 interval::strtod,
32 parse_interval,
33};
34
35mod bundled {
38 use alloc::borrow::Cow;
39
40 use super::tznames::{Abbreviation, Meaning};
41
42 include!(concat!(env!("OUT_DIR"), "/timezone_abbreviations.rs"));
43}
44
45const ABBREVIATION_SCAN_END: i64 = 7_258_118_400;
49
50#[derive(Debug, Clone, PartialEq, Eq, Hash)]
74pub struct TimeZoneAbbreviations {
75 entries: Cow<'static, [Abbreviation]>,
76}
77
78pub(crate) static DEFAULT_ABBREVIATIONS: TimeZoneAbbreviations = TimeZoneAbbreviations {
80 entries: Cow::Borrowed(&bundled::DEFAULT),
81};
82static AUSTRALIA: TimeZoneAbbreviations = TimeZoneAbbreviations {
83 entries: Cow::Borrowed(&bundled::AUSTRALIA),
84};
85static INDIA: TimeZoneAbbreviations = TimeZoneAbbreviations {
86 entries: Cow::Borrowed(&bundled::INDIA),
87};
88
89impl TimeZoneAbbreviations {
90 #[must_use]
93 pub fn bundled(name: &str) -> Option<&'static Self> {
94 match name {
95 "Default" => Some(&DEFAULT_ABBREVIATIONS),
96 "Australia" => Some(&AUSTRALIA),
97 "India" => Some(&INDIA),
98 _ => None,
99 }
100 }
101
102 #[must_use]
105 pub fn bundled_file(name: &str) -> Option<&'static str> {
106 match name {
107 "Default" => Some(include_str!("zone/timezonesets/Default")),
108 "Australia" => Some(include_str!("zone/timezonesets/Australia")),
109 "India" => Some(include_str!("zone/timezonesets/India")),
110 _ => None,
111 }
112 }
113
114 pub fn load<'f>(
121 name: &str,
122 mut files: impl FnMut(&str) -> Option<&'f str>,
123 ) -> Result<Self, TimeZoneAbbreviationsError> {
124 let mut entries = Vec::new();
125 tznames::parse_file(name, 0, &mut files, &mut entries)?;
126 Ok(Self {
127 entries: Cow::Owned(entries),
128 })
129 }
130
131 pub(crate) fn lookup(&self, word: &[u8]) -> Option<&Meaning> {
133 tznames::search(&self.entries, word).map(|entry| &entry.meaning)
134 }
135}
136
137#[derive(Debug, Clone, Copy, PartialEq, Eq)]
140pub(crate) struct AbbreviationUse {
141 pub(crate) offset: i32,
143 pub(crate) dst: bool,
144}
145
146const SECS_PER_MINUTE: i32 = 60;
147const SECS_PER_HOUR: i32 = 3_600;
148const SECS_PER_DAY: i64 = 86_400;
149const UNIX_EPOCH_JDATE: i32 = 2_440_588;
151const TIME_2000: i64 = 946_684_800;
153const TZ_STRLEN_MAX: usize = 255;
155const MAX_RULE_HOUR: i32 = 167;
157const DEFAULT_RULES: &str = "M3.2.0,M11.1.0";
159const YEARS_PER_REPEAT: i32 = 400;
161
162#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, thiserror::Error)]
164pub enum TimeZoneError {
165 #[error("invalid value for parameter \"TimeZone\"")]
167 InvalidValue,
168 #[error("UTC timezone offset is out of range")]
170 OffsetOutOfRange,
171 #[error("cannot specify months in time zone interval")]
173 MonthsInInterval,
174 #[error("cannot specify days in time zone interval")]
176 DaysInInterval,
177 #[error("time zone appears to use leap seconds")]
180 LeapSeconds,
181 #[error(transparent)]
183 Interval(#[from] IntervalError),
184}
185
186#[derive(Debug, Clone)]
200pub struct PgTimeZone {
201 name: String,
202 rules: Rules,
203}
204
205#[derive(Debug, Clone)]
207enum Rules {
208 Fixed { offset: i32, abbreviation: String },
210 Posix {
212 rules: Posix,
213 std_name: String,
214 dst_name: String,
215 },
216 Iana(TimeZone),
218}
219
220#[derive(Debug, Clone, Copy)]
222struct Posix {
223 std_offset: i32,
224 dst_offset: i32,
225 start: Rule,
226 end: Rule,
227 switches: bool,
229}
230
231#[derive(Debug, Clone, Copy)]
233struct Rule {
234 date: RuleDate,
235 time: i32,
236}
237
238#[derive(Debug, Clone, Copy)]
240enum RuleDate {
241 Julian(i32),
243 DayOfYear(i32),
245 MonthWeekDay { month: i32, week: i32, weekday: i32 },
247}
248
249struct Spec<'a> {
251 bytes: &'a [u8],
252 at: usize,
253}
254
255impl<'a> Spec<'a> {
256 fn peek(&self) -> Option<u8> {
257 self.bytes.get(self.at).copied()
258 }
259
260 fn eat(&mut self, byte: u8) -> bool {
261 let found = self.peek() == Some(byte);
262 self.at += usize::from(found);
263 found
264 }
265
266 fn is_done(&self) -> bool {
267 self.at == self.bytes.len()
268 }
269
270 fn name(&mut self) -> Option<&'a [u8]> {
272 if self.eat(b'<') {
273 let start = self.at;
274 while self.peek().is_some_and(|b| b != b'>') {
275 self.at += 1;
276 }
277 let name = &self.bytes[start..self.at];
278 self.eat(b'>').then_some(name)
279 } else {
280 let start = self.at;
281 while self
282 .peek()
283 .is_some_and(|b| !b.is_ascii_digit() && !matches!(b, b',' | b'-' | b'+'))
284 {
285 self.at += 1;
286 }
287 Some(&self.bytes[start..self.at])
288 }
289 }
290
291 fn number(&mut self, min: i32, max: i32) -> Option<i32> {
293 if !self.peek().is_some_and(|b| b.is_ascii_digit()) {
294 return None;
295 }
296 let mut value = 0;
297 while let Some(digit) = self.peek().filter(u8::is_ascii_digit) {
298 value = value * 10 + i32::from(digit - b'0');
299 if value > max {
300 return None;
301 }
302 self.at += 1;
303 }
304 (value >= min).then_some(value)
305 }
306
307 fn seconds(&mut self) -> Option<i32> {
309 let mut seconds = self.number(0, MAX_RULE_HOUR)? * SECS_PER_HOUR;
310 if self.eat(b':') {
311 seconds += self.number(0, 59)? * SECS_PER_MINUTE;
312 if self.eat(b':') {
313 seconds += self.number(0, 60)?;
314 }
315 }
316 Some(seconds)
317 }
318
319 fn offset(&mut self) -> Option<i32> {
321 let negative = self.eat(b'-');
322 if !negative {
323 self.eat(b'+');
324 }
325 let seconds = self.seconds()?;
326 Some(if negative { -seconds } else { seconds })
327 }
328
329 fn rule(&mut self) -> Option<Rule> {
331 let date = if self.eat(b'J') {
332 RuleDate::Julian(self.number(1, 365)?)
333 } else if self.eat(b'M') {
334 let month = self.number(1, 12)?;
335 if !self.eat(b'.') {
336 return None;
337 }
338 let week = self.number(1, 5)?;
339 if !self.eat(b'.') {
340 return None;
341 }
342 let weekday = self.number(0, 6)?;
343 RuleDate::MonthWeekDay {
344 month,
345 week,
346 weekday,
347 }
348 } else {
349 RuleDate::DayOfYear(self.number(0, 365)?)
350 };
351 let time = if self.eat(b'/') {
352 self.offset()?
353 } else {
354 2 * SECS_PER_HOUR
355 };
356 Some(Rule { date, time })
357 }
358}
359
360fn tzparse(spec: &str) -> Option<Rules> {
362 let mut cursor = Spec {
363 bytes: spec.as_bytes(),
364 at: 0,
365 };
366 let text = |name: &[u8]| String::from_utf8_lossy(name).into_owned();
367 let std_name = text(cursor.name()?);
368 if cursor.is_done() {
369 return None;
370 }
371 let std_offset = cursor.offset()?;
372 if cursor.is_done() {
373 return Some(Rules::Fixed {
374 offset: -std_offset,
375 abbreviation: std_name,
376 });
377 }
378 let dst_name = text(cursor.name()?);
379 if dst_name.is_empty() {
380 return None;
381 }
382 let dst_offset = if cursor.is_done() || matches!(cursor.peek(), Some(b',' | b';')) {
383 std_offset - SECS_PER_HOUR
384 } else {
385 cursor.offset()?
386 };
387 let mut rules = Spec {
388 bytes: DEFAULT_RULES.as_bytes(),
389 at: 0,
390 };
391 let rules = if cursor.is_done() {
392 &mut rules
393 } else if cursor.eat(b',') || cursor.eat(b';') {
394 &mut cursor
395 } else {
396 return None;
397 };
398 let start = rules.rule()?;
399 if !rules.eat(b',') {
400 return None;
401 }
402 let end = rules.rule()?;
403 if !rules.is_done() {
404 return None;
405 }
406 let mut posix = Posix {
407 std_offset,
408 dst_offset,
409 start,
410 end,
411 switches: false,
412 };
413 posix.switches = (2000..2000 + YEARS_PER_REPEAT).any(|year| posix.year(year).is_some());
414 Some(Rules::Posix {
415 rules: posix,
416 std_name,
417 dst_name,
418 })
419}
420
421const fn is_leap(year: i32) -> bool {
423 year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)
424}
425
426impl Rule {
427 fn transtime(self, year: i32, offset: i32) -> i64 {
430 let leap = is_leap(year);
431 let day = match self.date {
432 RuleDate::Julian(day) => day - 1 + i32::from(leap && day >= 60),
433 RuleDate::DayOfYear(day) => day,
434 RuleDate::MonthWeekDay {
435 month,
436 week,
437 weekday,
438 } => {
439 let m1 = (month + 9) % 12 + 1;
441 let yy0 = if month <= 2 { year - 1 } else { year };
442 let (yy1, yy2) = (yy0 / 100, yy0 % 100);
443 let mut dow = ((26 * m1 - 2) / 10 + 1 + yy2 + yy2 / 4 + yy1 / 4 - 2 * yy1) % 7;
444 if dow < 0 {
445 dow += 7;
446 }
447 let mut d = weekday - dow;
448 if d < 0 {
449 d += 7;
450 }
451 let length = days_in_month(year, month);
452 for _ in 1..week {
453 if d + 7 >= length {
454 break;
455 }
456 d += 7;
457 }
458 d + (1..month).map(|m| days_in_month(year, m)).sum::<i32>()
459 }
460 };
461 i64::from(day) * SECS_PER_DAY + i64::from(self.time) + i64::from(offset)
462 }
463}
464
465impl Posix {
466 fn year(self, year: i32) -> Option<[(i64, bool); 2]> {
469 let calendar = 2000 + (year - 2000).rem_euclid(YEARS_PER_REPEAT);
472 let mut start = self.start.transtime(calendar, self.std_offset);
473 let mut end = self.end.transtime(calendar, self.dst_offset);
474 let year_secs = if is_leap(calendar) { 366 } else { 365 } * SECS_PER_DAY;
475 let reversed = end < start;
476 if reversed {
477 core::mem::swap(&mut start, &mut end);
478 }
479 let spans =
480 start < end && end - start < year_secs + i64::from(self.std_offset - self.dst_offset);
481 if !(reversed || spans) {
482 return None;
483 }
484 let jan_first = i64::from(date2j(year, 1, 1) - UNIX_EPOCH_JDATE) * SECS_PER_DAY;
485 Some([(jan_first + start, !reversed), (jan_first + end, reversed)])
486 }
487
488 const fn offset(self, dst: bool) -> i32 {
490 if dst {
491 -self.dst_offset
492 } else {
493 -self.std_offset
494 }
495 }
496
497 fn around(self, year: i32) -> impl DoubleEndedIterator<Item = (i64, bool)> {
499 (year - 1..=year + 1).flat_map(move |year| self.year(year).into_iter().flatten())
500 }
501
502 fn offset_at(self, unix: i64) -> i32 {
504 if !self.switches {
505 return self.offset(true);
506 }
507 let year = year_of(unix);
508 (0..=YEARS_PER_REPEAT)
509 .find_map(|back| {
510 self.around(year - back)
511 .rev()
512 .find(|&(at, _)| at <= unix)
513 .map(|(_, dst)| self.offset(dst))
514 })
515 .expect("a zone that switches has a transition within 400 years")
516 }
517
518 fn next_transition(self, unix: i64) -> Option<(i64, i32)> {
520 if !self.switches {
521 return None;
522 }
523 let year = year_of(unix);
524 (0..=YEARS_PER_REPEAT).find_map(|ahead| {
525 self.around(year + ahead)
526 .find(|&(at, _)| at > unix)
527 .map(|(at, dst)| (at, self.offset(dst)))
528 })
529 }
530}
531
532fn year_of(unix: i64) -> i32 {
534 let julian = unix.div_euclid(SECS_PER_DAY) + i64::from(UNIX_EPOCH_JDATE);
535 j2date(i32::try_from(julian).expect("PostgreSQL's instants lie within int Julian days")).0
536}
537
538fn strtod_whole(text: &str) -> Option<f64> {
541 let bytes = text.as_bytes();
542 let mut at = bytes
543 .iter()
544 .take_while(|&&b| crate::cast::is_pg_space(b))
545 .count();
546 if bytes.get(at) == Some(&b'+') {
547 at += 1;
548 if bytes.get(at) == Some(&b'-') {
549 return None;
550 }
551 }
552 let (value, end, _) = strtod(bytes, at)?;
553 (end == bytes.len()).then_some(value)
554}
555
556impl PgTimeZone {
557 pub fn parse(setting: &str) -> Result<Self, TimeZoneError> {
576 if setting
577 .get(..8)
578 .is_some_and(|prefix| prefix.eq_ignore_ascii_case("interval"))
579 {
580 let blanks = setting.as_bytes()[8..]
581 .iter()
582 .take_while(|&&b| crate::cast::is_pg_space(b))
583 .count();
584 let body = setting[8 + blanks..]
585 .strip_prefix('\'')
586 .and_then(|rest| rest.strip_suffix('\''))
587 .filter(|body| !body.contains('\''))
588 .ok_or(TimeZoneError::InvalidValue)?;
589 let interval = parse_interval(body)?;
590 if interval.months != 0 {
591 return Err(TimeZoneError::MonthsInInterval);
592 }
593 if interval.days != 0 {
594 return Err(TimeZoneError::DaysInInterval);
595 }
596 return Self::from_offset_west(-(interval.microseconds / 1_000_000));
597 }
598 if let Some(hours) = strtod_whole(setting) {
599 let west = -hours * f64::from(SECS_PER_HOUR);
602 let limit = f64::from(MAX_RULE_HOUR + 1) * f64::from(SECS_PER_HOUR);
603 if !west.is_finite() || west.abs() >= limit {
604 return Err(TimeZoneError::OffsetOutOfRange);
605 }
606 return Self::from_offset_west(crate::float::truncate_to_i64(west));
607 }
608 let zone = Self::load(setting).ok_or(TimeZoneError::InvalidValue)?;
609 if zone
610 .utc_offset(TIME_2000)
611 .is_some_and(|offset| offset % 60 != 0)
612 {
613 return Err(TimeZoneError::LeapSeconds);
614 }
615 Ok(zone)
616 }
617
618 fn from_offset_west(west: i64) -> Result<Self, TimeZoneError> {
621 let magnitude = west.unsigned_abs();
622 if magnitude >= u64::from((MAX_RULE_HOUR + 1).unsigned_abs()) * 3_600 {
623 return Err(TimeZoneError::OffsetOutOfRange);
624 }
625 let mut clock = alloc::format!("{:02}", magnitude / 3_600);
626 if !magnitude.is_multiple_of(3_600) {
627 clock += &alloc::format!(":{:02}", magnitude % 3_600 / 60);
628 if !magnitude.is_multiple_of(60) {
629 clock += &alloc::format!(":{:02}", magnitude % 60);
630 }
631 }
632 let (abbreviation, name) = if west > 0 {
633 (
634 alloc::format!("-{clock}"),
635 alloc::format!("<-{clock}>+{clock}"),
636 )
637 } else {
638 (
639 alloc::format!("+{clock}"),
640 alloc::format!("<+{clock}>-{clock}"),
641 )
642 };
643 let west = i32::try_from(west).expect("an offset under 168 hours fits int");
644 Ok(Self {
645 name,
646 rules: Rules::Fixed {
647 offset: -west,
648 abbreviation,
649 },
650 })
651 }
652
653 pub(crate) fn load(name: &str) -> Option<Self> {
655 if name.len() > TZ_STRLEN_MAX {
656 return None;
657 }
658 let upper = name.to_ascii_uppercase();
659 if upper == "GMT" {
660 return Some(Self {
661 name: upper.clone(),
662 rules: Rules::Fixed {
663 offset: 0,
664 abbreviation: upper,
665 },
666 });
667 }
668 let file = name.strip_prefix(':').unwrap_or(name);
670 if let Some(zone) = jiff::tz::db()
671 .get(file)
672 .ok()
673 .filter(|zone| !zone.is_unknown())
674 {
675 let canonical = zone.iana_name().unwrap_or(file).to_string();
676 let rules = match zone.following(Timestamp::MIN).next() {
678 None => {
679 let info = zone.to_offset_info(Timestamp::MIN);
680 Rules::Fixed {
681 offset: info.offset().seconds(),
682 abbreviation: info.abbreviation().to_string(),
683 }
684 }
685 Some(_) => Rules::Iana(zone),
686 };
687 return Some(Self {
688 name: canonical,
689 rules,
690 });
691 }
692 if upper.starts_with(':') {
693 return None;
694 }
695 let rules = tzparse(&upper)?;
696 Some(Self { name: upper, rules })
697 }
698
699 #[must_use]
701 pub fn name(&self) -> &str {
702 &self.name
703 }
704
705 pub(crate) fn utc_offset(&self, unix: i64) -> Option<i32> {
708 match &self.rules {
709 Rules::Fixed { offset, .. } => Some(*offset),
710 Rules::Posix { rules, .. } => Some(rules.offset_at(unix)),
711 Rules::Iana(zone) => Some(zone.to_offset(Timestamp::from_second(unix).ok()?).seconds()),
712 }
713 }
714
715 fn next_boundary(&self, unix: i64) -> Option<(i32, Option<(i64, i32)>)> {
718 match &self.rules {
719 Rules::Fixed { offset, .. } => Some((*offset, None)),
720 Rules::Posix { rules, .. } => {
721 Some((rules.offset_at(unix), rules.next_transition(unix)))
722 }
723 Rules::Iana(zone) => {
724 let at = Timestamp::from_second(unix).ok()?;
725 let next = zone
726 .following(at)
727 .next()
728 .map(|change| (change.timestamp().as_second(), change.offset().seconds()));
729 Some((zone.to_offset(at).seconds(), next))
730 }
731 }
732 }
733
734 pub(crate) fn local_offset(&self, local: i64) -> Option<i32> {
740 let (before, next) = self.next_boundary(local - SECS_PER_DAY)?;
741 let Some((boundary, after)) = next else {
742 return Some(before);
743 };
744 let before_time = local - i64::from(before);
745 let after_time = local - i64::from(after);
746 Some(if before_time < boundary && after_time < boundary {
747 before
748 } else if before_time >= boundary && after_time >= boundary {
749 after
750 } else if before_time > after_time {
751 before
752 } else {
753 after
754 })
755 }
756}
757
758impl PgTimeZone {
759 pub(crate) fn fixed_offset(&self) -> Option<i32> {
763 match &self.rules {
764 Rules::Fixed { offset, .. } => Some(*offset),
765 Rules::Posix { .. } | Rules::Iana(_) => None,
766 }
767 }
768
769 pub(crate) fn abbreviation_is_known(
772 &self,
773 abbreviation: &str,
774 ) -> Option<(AbbreviationUse, bool)> {
775 let mut uses = Vec::new();
776 match &self.rules {
777 Rules::Fixed {
778 offset,
779 abbreviation: own,
780 } => {
781 if own == abbreviation {
782 uses.push(AbbreviationUse {
783 offset: *offset,
784 dst: false,
785 });
786 }
787 }
788 Rules::Posix {
789 rules,
790 std_name,
791 dst_name,
792 } => uses.extend(posix_use(rules, std_name, dst_name, abbreviation)),
793 Rules::Iana(zone) => {
794 let first = zone.to_offset_info(Timestamp::MIN);
795 if first.abbreviation() == abbreviation {
796 uses.push(AbbreviationUse {
797 offset: first.offset().seconds(),
798 dst: first.dst().is_dst(),
799 });
800 }
801 for change in zone
802 .following(Timestamp::MIN)
803 .take_while(|change| change.timestamp().as_second() <= ABBREVIATION_SCAN_END)
804 {
805 if change.abbreviation() == abbreviation {
806 uses.push(AbbreviationUse {
807 offset: change.offset().seconds(),
808 dst: change.dst().is_dst(),
809 });
810 }
811 }
812 }
813 }
814 let first = *uses.first()?;
815 Some((first, uses.iter().all(|other| *other == first)))
816 }
817
818 pub(crate) fn interpret_abbreviation(
827 &self,
828 abbreviation: &str,
829 unix: i64,
830 ) -> Result<Option<AbbreviationUse>, DateTimeError> {
831 let zone = match &self.rules {
832 Rules::Fixed { .. } | Rules::Posix { .. } => {
833 return Ok(self
834 .abbreviation_is_known(abbreviation)
835 .map(|(use_, _)| use_));
836 }
837 Rules::Iana(zone) => zone,
838 };
839 let at = Timestamp::from_second(unix).map_err(|_| DateTimeError::OutsideJiffRange)?;
840 let after = Timestamp::from_second(unix + 1).unwrap_or(Timestamp::MAX);
841 let matching = |abbreviation_used: &str, offset: jiff::tz::Offset, dst: jiff::tz::Dst| {
842 (abbreviation_used == abbreviation).then(|| AbbreviationUse {
843 offset: offset.seconds(),
844 dst: dst.is_dst(),
845 })
846 };
847 if let Some(found) = zone
848 .preceding(after)
849 .find_map(|change| matching(change.abbreviation(), change.offset(), change.dst()))
850 {
851 return Ok(Some(found));
852 }
853 let first = zone.to_offset_info(Timestamp::MIN);
854 if let Some(found) = matching(first.abbreviation(), first.offset(), first.dst()) {
855 return Ok(Some(found));
856 }
857 Ok(zone
858 .following(at)
859 .take_while(|change| change.timestamp().as_second() <= ABBREVIATION_SCAN_END)
860 .find_map(|change| matching(change.abbreviation(), change.offset(), change.dst())))
861 }
862}
863
864fn posix_use(
868 rules: &Posix,
869 std_name: &str,
870 dst_name: &str,
871 abbreviation: &str,
872) -> Option<AbbreviationUse> {
873 if std_name == abbreviation {
874 rules.switches.then(|| AbbreviationUse {
875 offset: rules.offset(false),
876 dst: false,
877 })
878 } else if dst_name == abbreviation {
879 Some(AbbreviationUse {
880 offset: rules.offset(true),
881 dst: true,
882 })
883 } else {
884 None
885 }
886}
887
888impl PartialEq for PgTimeZone {
889 fn eq(&self, other: &Self) -> bool {
890 self.name == other.name
891 }
892}
893
894impl Eq for PgTimeZone {}
895
896impl Hash for PgTimeZone {
897 fn hash<H: Hasher>(&self, state: &mut H) {
898 self.name.hash(state);
899 }
900}
901
902impl fmt::Display for PgTimeZone {
903 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
904 f.write_str(&self.name)
905 }
906}