1mod tznames;
13
14use alloc::{borrow::Cow, string::String, vec::Vec};
15use core::{
16 fmt,
17 hash::{Hash, Hasher},
18};
19
20#[cfg(feature = "tzdb")]
21use jiff::{Timestamp, tz::TimeZone};
22use tznames::Abbreviation;
23pub(crate) use tznames::Meaning;
24pub use tznames::TimeZoneAbbreviationsError;
25
26use super::{
27 IntervalError,
28 datetime::{date2j, days_in_month, j2date},
29 interval::strtod,
30 parse_interval,
31};
32
33mod bundled {
36 use alloc::borrow::Cow;
37
38 use super::tznames::{Abbreviation, Meaning};
39
40 include!(concat!(env!("OUT_DIR"), "/timezone_abbreviations.rs"));
41}
42
43#[cfg(feature = "tzdb")]
47const ABBREVIATION_SCAN_END: i64 = 7_258_118_400;
48
49#[derive(Debug, Clone, PartialEq, Eq, Hash)]
73pub struct TimeZoneAbbreviations {
74 entries: Cow<'static, [Abbreviation]>,
75}
76
77pub(crate) static DEFAULT_ABBREVIATIONS: TimeZoneAbbreviations = TimeZoneAbbreviations {
79 entries: Cow::Borrowed(&bundled::DEFAULT),
80};
81static AUSTRALIA: TimeZoneAbbreviations = TimeZoneAbbreviations {
82 entries: Cow::Borrowed(&bundled::AUSTRALIA),
83};
84static INDIA: TimeZoneAbbreviations = TimeZoneAbbreviations {
85 entries: Cow::Borrowed(&bundled::INDIA),
86};
87
88impl TimeZoneAbbreviations {
89 #[must_use]
92 pub fn bundled(name: &str) -> Option<&'static Self> {
93 match name {
94 "Default" => Some(&DEFAULT_ABBREVIATIONS),
95 "Australia" => Some(&AUSTRALIA),
96 "India" => Some(&INDIA),
97 _ => None,
98 }
99 }
100
101 #[must_use]
104 pub fn bundled_file(name: &str) -> Option<&'static str> {
105 match name {
106 "Default" => Some(include_str!("zone/timezonesets/Default")),
107 "Australia" => Some(include_str!("zone/timezonesets/Australia")),
108 "India" => Some(include_str!("zone/timezonesets/India")),
109 _ => None,
110 }
111 }
112
113 pub fn load<'f>(
120 name: &str,
121 mut files: impl FnMut(&str) -> Option<&'f str>,
122 ) -> Result<Self, TimeZoneAbbreviationsError> {
123 let mut entries = Vec::new();
124 tznames::parse_file(name, 0, &mut files, &mut entries)?;
125 Ok(Self {
126 entries: Cow::Owned(entries),
127 })
128 }
129
130 pub(crate) fn lookup(&self, word: &[u8]) -> Option<&Meaning> {
132 tznames::search(&self.entries, word).map(|entry| &entry.meaning)
133 }
134}
135
136#[derive(Debug, Clone, Copy, PartialEq, Eq)]
139pub(crate) struct AbbreviationUse {
140 pub(crate) offset: i32,
142 pub(crate) dst: bool,
143}
144
145const SECS_PER_MINUTE: i32 = 60;
146const SECS_PER_HOUR: i32 = 3_600;
147const SECS_PER_DAY: i64 = 86_400;
148const UNIX_EPOCH_JDATE: i32 = 2_440_588;
150const TIME_2000: i64 = 946_684_800;
152const TZ_STRLEN_MAX: usize = 255;
154const MAX_RULE_HOUR: i32 = 167;
156const DEFAULT_RULES: &str = "M3.2.0,M11.1.0";
158const YEARS_PER_REPEAT: i32 = 400;
160#[cfg(feature = "tzdb")]
162const SECS_PER_REPEAT: i64 = 146_097 * SECS_PER_DAY;
163
164#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, thiserror::Error)]
166pub enum TimeZoneError {
167 #[error("invalid value for parameter \"TimeZone\"")]
169 InvalidValue,
170 #[error("UTC timezone offset is out of range")]
172 OffsetOutOfRange,
173 #[error("cannot specify months in time zone interval")]
175 MonthsInInterval,
176 #[error("cannot specify days in time zone interval")]
178 DaysInInterval,
179 #[error("time zone appears to use leap seconds")]
182 LeapSeconds,
183 #[error(transparent)]
185 Interval(#[from] IntervalError),
186}
187
188#[derive(Debug, Clone)]
203pub struct PgTimeZone {
204 name: String,
205 rules: Rules,
206}
207
208#[derive(Debug, Clone)]
210enum Rules {
211 Fixed { offset: i32, abbreviation: String },
213 Posix {
215 rules: Posix,
216 std_name: String,
217 dst_name: String,
218 },
219 #[cfg(feature = "tzdb")]
221 Iana(TimeZone),
222}
223
224#[derive(Debug, Clone, Copy)]
226struct Posix {
227 std_offset: i32,
228 dst_offset: i32,
229 start: Rule,
230 end: Rule,
231 switches: bool,
233}
234
235#[derive(Debug, Clone, Copy)]
237struct Rule {
238 date: RuleDate,
239 time: i32,
240}
241
242pub(crate) enum ZoneAbbreviation<'a> {
244 Borrowed(&'a str),
245 #[cfg(feature = "tzdb")]
246 Iana(jiff::tz::TimeZoneOffsetInfo<'a>),
247}
248
249impl ZoneAbbreviation<'_> {
250 pub(crate) fn as_str(&self) -> &str {
251 match self {
252 Self::Borrowed(name) => name,
253 #[cfg(feature = "tzdb")]
254 Self::Iana(info) => info.abbreviation(),
255 }
256 }
257}
258
259#[derive(Debug, Clone, Copy)]
261enum RuleDate {
262 Julian(i32),
264 DayOfYear(i32),
266 MonthWeekDay { month: i32, week: i32, weekday: i32 },
268}
269
270struct Spec<'a> {
272 bytes: &'a [u8],
273 at: usize,
274}
275
276impl<'a> Spec<'a> {
277 fn peek(&self) -> Option<u8> {
278 self.bytes.get(self.at).copied()
279 }
280
281 fn eat(&mut self, byte: u8) -> bool {
282 let found = self.peek() == Some(byte);
283 self.at += usize::from(found);
284 found
285 }
286
287 fn is_done(&self) -> bool {
288 self.at == self.bytes.len()
289 }
290
291 fn name(&mut self) -> Option<&'a [u8]> {
293 if self.eat(b'<') {
294 let start = self.at;
295 while self.peek().is_some_and(|b| b != b'>') {
296 self.at += 1;
297 }
298 let name = &self.bytes[start..self.at];
299 self.eat(b'>').then_some(name)
300 } else {
301 let start = self.at;
302 while self
303 .peek()
304 .is_some_and(|b| !b.is_ascii_digit() && !matches!(b, b',' | b'-' | b'+'))
305 {
306 self.at += 1;
307 }
308 Some(&self.bytes[start..self.at])
309 }
310 }
311
312 fn number(&mut self, min: i32, max: i32) -> Option<i32> {
314 if !self.peek().is_some_and(|b| b.is_ascii_digit()) {
315 return None;
316 }
317 let mut value = 0;
318 while let Some(digit) = self.peek().filter(u8::is_ascii_digit) {
319 value = value * 10 + i32::from(digit - b'0');
320 if value > max {
321 return None;
322 }
323 self.at += 1;
324 }
325 (value >= min).then_some(value)
326 }
327
328 fn seconds(&mut self) -> Option<i32> {
330 let mut seconds = self.number(0, MAX_RULE_HOUR)? * SECS_PER_HOUR;
331 if self.eat(b':') {
332 seconds += self.number(0, 59)? * SECS_PER_MINUTE;
333 if self.eat(b':') {
334 seconds += self.number(0, 60)?;
335 }
336 }
337 Some(seconds)
338 }
339
340 fn offset(&mut self) -> Option<i32> {
342 let negative = self.eat(b'-');
343 if !negative {
344 self.eat(b'+');
345 }
346 let seconds = self.seconds()?;
347 Some(if negative { -seconds } else { seconds })
348 }
349
350 fn rule(&mut self) -> Option<Rule> {
352 let date = if self.eat(b'J') {
353 RuleDate::Julian(self.number(1, 365)?)
354 } else if self.eat(b'M') {
355 let month = self.number(1, 12)?;
356 if !self.eat(b'.') {
357 return None;
358 }
359 let week = self.number(1, 5)?;
360 if !self.eat(b'.') {
361 return None;
362 }
363 let weekday = self.number(0, 6)?;
364 RuleDate::MonthWeekDay {
365 month,
366 week,
367 weekday,
368 }
369 } else {
370 RuleDate::DayOfYear(self.number(0, 365)?)
371 };
372 let time = if self.eat(b'/') {
373 self.offset()?
374 } else {
375 2 * SECS_PER_HOUR
376 };
377 Some(Rule { date, time })
378 }
379}
380
381fn tzparse(spec: &str) -> Option<Rules> {
383 let mut cursor = Spec {
384 bytes: spec.as_bytes(),
385 at: 0,
386 };
387 let text = |name: &[u8]| String::from_utf8_lossy(name).into_owned();
388 let std_name = text(cursor.name()?);
389 if cursor.is_done() {
390 return None;
391 }
392 let std_offset = cursor.offset()?;
393 if cursor.is_done() {
394 return Some(Rules::Fixed {
395 offset: -std_offset,
396 abbreviation: std_name,
397 });
398 }
399 let dst_name = text(cursor.name()?);
400 if dst_name.is_empty() {
401 return None;
402 }
403 let dst_offset = if cursor.is_done() || matches!(cursor.peek(), Some(b',' | b';')) {
404 std_offset - SECS_PER_HOUR
405 } else {
406 cursor.offset()?
407 };
408 let mut rules = Spec {
409 bytes: DEFAULT_RULES.as_bytes(),
410 at: 0,
411 };
412 let rules = if cursor.is_done() {
413 &mut rules
414 } else if cursor.eat(b',') || cursor.eat(b';') {
415 &mut cursor
416 } else {
417 return None;
418 };
419 let start = rules.rule()?;
420 if !rules.eat(b',') {
421 return None;
422 }
423 let end = rules.rule()?;
424 if !rules.is_done() {
425 return None;
426 }
427 let mut posix = Posix {
428 std_offset,
429 dst_offset,
430 start,
431 end,
432 switches: false,
433 };
434 posix.switches = (2000..2000 + YEARS_PER_REPEAT).any(|year| posix.year(year).is_some());
435 Some(Rules::Posix {
436 rules: posix,
437 std_name,
438 dst_name,
439 })
440}
441
442const fn is_leap(year: i32) -> bool {
444 year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)
445}
446
447impl Rule {
448 fn transtime(self, year: i32, offset: i32) -> i64 {
451 let leap = is_leap(year);
452 let day = match self.date {
453 RuleDate::Julian(day) => day - 1 + i32::from(leap && day >= 60),
454 RuleDate::DayOfYear(day) => day,
455 RuleDate::MonthWeekDay {
456 month,
457 week,
458 weekday,
459 } => {
460 let m1 = (month + 9) % 12 + 1;
462 let yy0 = if month <= 2 { year - 1 } else { year };
463 let (yy1, yy2) = (yy0 / 100, yy0 % 100);
464 let mut dow = ((26 * m1 - 2) / 10 + 1 + yy2 + yy2 / 4 + yy1 / 4 - 2 * yy1) % 7;
465 if dow < 0 {
466 dow += 7;
467 }
468 let mut d = weekday - dow;
469 if d < 0 {
470 d += 7;
471 }
472 let length = days_in_month(year, month);
473 for _ in 1..week {
474 if d + 7 >= length {
475 break;
476 }
477 d += 7;
478 }
479 d + (1..month).map(|m| days_in_month(year, m)).sum::<i32>()
480 }
481 };
482 i64::from(day) * SECS_PER_DAY + i64::from(self.time) + i64::from(offset)
483 }
484}
485
486impl Posix {
487 fn year(self, year: i32) -> Option<[(i64, bool); 2]> {
490 let calendar = 2000 + (year - 2000).rem_euclid(YEARS_PER_REPEAT);
493 let mut start = self.start.transtime(calendar, self.std_offset);
494 let mut end = self.end.transtime(calendar, self.dst_offset);
495 let year_secs = if is_leap(calendar) { 366 } else { 365 } * SECS_PER_DAY;
496 let reversed = end < start;
497 if reversed {
498 core::mem::swap(&mut start, &mut end);
499 }
500 let spans =
501 start < end && end - start < year_secs + i64::from(self.std_offset - self.dst_offset);
502 if !(reversed || spans) {
503 return None;
504 }
505 let jan_first = i64::from(date2j(year, 1, 1) - UNIX_EPOCH_JDATE) * SECS_PER_DAY;
506 Some([(jan_first + start, !reversed), (jan_first + end, reversed)])
507 }
508
509 const fn offset(self, dst: bool) -> i32 {
511 if dst {
512 -self.dst_offset
513 } else {
514 -self.std_offset
515 }
516 }
517
518 fn around(self, year: i32) -> impl DoubleEndedIterator<Item = (i64, bool)> {
520 (year - 1..=year + 1).flat_map(move |year| self.year(year).into_iter().flatten())
521 }
522
523 fn dst_at(self, unix: i64) -> bool {
525 if !self.switches {
526 return true;
527 }
528 let year = year_of(unix);
529 (0..=YEARS_PER_REPEAT)
530 .find_map(|back| {
531 self.around(year - back)
532 .rev()
533 .find(|&(at, _)| at <= unix)
534 .map(|(_, dst)| dst)
535 })
536 .expect("a zone that switches has a transition within 400 years")
537 }
538
539 fn offset_at(self, unix: i64) -> i32 {
541 self.offset(self.dst_at(unix))
542 }
543
544 fn next_transition(self, unix: i64) -> Option<(i64, i32)> {
546 if !self.switches {
547 return None;
548 }
549 let year = year_of(unix);
550 (0..=YEARS_PER_REPEAT).find_map(|ahead| {
551 self.around(year + ahead)
552 .find(|&(at, _)| at > unix)
553 .map(|(at, dst)| (at, self.offset(dst)))
554 })
555 }
556}
557
558fn year_of(unix: i64) -> i32 {
560 let julian = unix.div_euclid(SECS_PER_DAY) + i64::from(UNIX_EPOCH_JDATE);
561 j2date(i32::try_from(julian).expect("PostgreSQL's instants lie within int Julian days")).0
562}
563
564fn strtod_whole(text: &str) -> Option<f64> {
567 let bytes = text.as_bytes();
568 let mut at = bytes
569 .iter()
570 .take_while(|&&b| super::cast::is_pg_space(b))
571 .count();
572 if bytes.get(at) == Some(&b'+') {
573 at += 1;
574 if bytes.get(at) == Some(&b'-') {
575 return None;
576 }
577 }
578 let (value, end, _) = strtod(bytes, at)?;
579 (end == bytes.len()).then_some(value)
580}
581
582impl PgTimeZone {
583 pub fn parse(setting: &str) -> Result<Self, TimeZoneError> {
602 if setting
603 .get(..8)
604 .is_some_and(|prefix| prefix.eq_ignore_ascii_case("interval"))
605 {
606 let blanks = setting.as_bytes()[8..]
607 .iter()
608 .take_while(|&&b| super::cast::is_pg_space(b))
609 .count();
610 let body = setting[8 + blanks..]
611 .strip_prefix('\'')
612 .and_then(|rest| rest.strip_suffix('\''))
613 .filter(|body| !body.contains('\''))
614 .ok_or(TimeZoneError::InvalidValue)?;
615 let interval = parse_interval(body)?;
616 if interval.months != 0 {
617 return Err(TimeZoneError::MonthsInInterval);
618 }
619 if interval.days != 0 {
620 return Err(TimeZoneError::DaysInInterval);
621 }
622 return Self::from_offset_west(-(interval.microseconds / 1_000_000));
623 }
624 if let Some(hours) = strtod_whole(setting) {
625 let west = -hours * f64::from(SECS_PER_HOUR);
628 let limit = f64::from(MAX_RULE_HOUR + 1) * f64::from(SECS_PER_HOUR);
629 if !west.is_finite() || west.abs() >= limit {
630 return Err(TimeZoneError::OffsetOutOfRange);
631 }
632 return Self::from_offset_west(super::float::truncate_to_i64(west));
633 }
634 let zone = Self::load(setting).ok_or(TimeZoneError::InvalidValue)?;
635 if zone.utc_offset(TIME_2000) % 60 != 0 {
636 return Err(TimeZoneError::LeapSeconds);
637 }
638 Ok(zone)
639 }
640
641 fn from_offset_west(west: i64) -> Result<Self, TimeZoneError> {
644 let magnitude = west.unsigned_abs();
645 if magnitude >= u64::from((MAX_RULE_HOUR + 1).unsigned_abs()) * 3_600 {
646 return Err(TimeZoneError::OffsetOutOfRange);
647 }
648 let mut clock = alloc::format!("{:02}", magnitude / 3_600);
649 if !magnitude.is_multiple_of(3_600) {
650 clock += &alloc::format!(":{:02}", magnitude % 3_600 / 60);
651 if !magnitude.is_multiple_of(60) {
652 clock += &alloc::format!(":{:02}", magnitude % 60);
653 }
654 }
655 let (abbreviation, name) = if west > 0 {
656 (
657 alloc::format!("-{clock}"),
658 alloc::format!("<-{clock}>+{clock}"),
659 )
660 } else {
661 (
662 alloc::format!("+{clock}"),
663 alloc::format!("<+{clock}>-{clock}"),
664 )
665 };
666 let west = i32::try_from(west).expect("an offset under 168 hours fits int");
667 Ok(Self {
668 name,
669 rules: Rules::Fixed {
670 offset: -west,
671 abbreviation,
672 },
673 })
674 }
675
676 pub(crate) fn load(name: &str) -> Option<Self> {
678 if name.len() > TZ_STRLEN_MAX {
679 return None;
680 }
681 let upper = name.to_ascii_uppercase();
682 if upper == "GMT" {
683 return Some(Self {
684 name: upper.clone(),
685 rules: Rules::Fixed {
686 offset: 0,
687 abbreviation: upper,
688 },
689 });
690 }
691 #[cfg(feature = "tzdb")]
693 if let Some(zone) = Self::load_iana(name.strip_prefix(':').unwrap_or(name)) {
694 return Some(zone);
695 }
696 if upper.starts_with(':') {
697 return None;
698 }
699 let rules = tzparse(&upper)?;
700 Some(Self { name: upper, rules })
701 }
702
703 #[cfg(feature = "tzdb")]
705 fn load_iana(file: &str) -> Option<Self> {
706 let zone = jiff::tz::db()
707 .get(file)
708 .ok()
709 .filter(|zone| !zone.is_unknown())?;
710 let canonical = String::from(zone.iana_name().unwrap_or(file));
711 let rules = match zone.following(Timestamp::MIN).next() {
713 None => {
714 let info = zone.to_offset_info(Timestamp::MIN);
715 Rules::Fixed {
716 offset: info.offset().seconds(),
717 abbreviation: String::from(info.abbreviation()),
718 }
719 }
720 Some(_) => Rules::Iana(zone),
721 };
722 Some(Self {
723 name: canonical,
724 rules,
725 })
726 }
727
728 #[must_use]
730 pub fn name(&self) -> &str {
731 &self.name
732 }
733
734 #[must_use]
759 pub fn fixed_offset(&self) -> Option<i32> {
760 match &self.rules {
761 Rules::Fixed { offset, .. } => Some(*offset),
762 Rules::Posix { rules, .. } => (!rules.switches || rules.std_offset == rules.dst_offset)
763 .then(|| rules.offset(true)),
764 #[cfg(feature = "tzdb")]
767 Rules::Iana(_) => None,
768 }
769 }
770
771 pub(crate) fn utc_offset(&self, unix: i64) -> i32 {
773 match &self.rules {
774 Rules::Fixed { offset, .. } => *offset,
775 Rules::Posix { rules, .. } => rules.offset_at(unix),
776 #[cfg(feature = "tzdb")]
777 Rules::Iana(zone) => zone.to_offset(iana_moment(unix).0).seconds(),
778 }
779 }
780
781 pub(crate) fn local_time_type(&self, unix: i64) -> (i32, ZoneAbbreviation<'_>) {
784 match &self.rules {
785 Rules::Fixed {
786 offset,
787 abbreviation,
788 } => (*offset, ZoneAbbreviation::Borrowed(abbreviation)),
789 Rules::Posix {
790 rules,
791 std_name,
792 dst_name,
793 } => {
794 let dst = rules.dst_at(unix);
795 let name = if dst { dst_name } else { std_name };
796 (rules.offset(dst), ZoneAbbreviation::Borrowed(name))
797 }
798 #[cfg(feature = "tzdb")]
799 Rules::Iana(zone) => {
800 let info = zone.to_offset_info(iana_moment(unix).0);
801 (info.offset().seconds(), ZoneAbbreviation::Iana(info))
802 }
803 }
804 }
805
806 fn next_boundary(&self, unix: i64) -> (i32, Option<(i64, i32)>) {
809 match &self.rules {
810 Rules::Fixed { offset, .. } => (*offset, None),
811 Rules::Posix { rules, .. } => (rules.offset_at(unix), rules.next_transition(unix)),
812 #[cfg(feature = "tzdb")]
813 Rules::Iana(zone) => {
814 let (at, shift) = iana_moment(unix);
815 let next = zone.following(at).next().map(|change| {
816 (
817 change.timestamp().as_second() + shift,
818 change.offset().seconds(),
819 )
820 });
821 (zone.to_offset(at).seconds(), next)
822 }
823 }
824 }
825
826 pub(crate) fn local_offset(&self, local: i64) -> i32 {
831 let (before, next) = self.next_boundary(local - SECS_PER_DAY);
832 let Some((boundary, after)) = next else {
833 return before;
834 };
835 let before_time = local - i64::from(before);
836 let after_time = local - i64::from(after);
837 if before_time < boundary && after_time < boundary {
838 before
839 } else if before_time >= boundary && after_time >= boundary {
840 after
841 } else if before_time > after_time {
842 before
843 } else {
844 after
845 }
846 }
847
848 pub(crate) fn abbreviation_offset(&self, abbreviation: &str, local: i64) -> i32 {
852 let zone_offset = self.local_offset(local);
853 self.interpret_abbreviation(abbreviation, local - i64::from(zone_offset))
854 .map_or(zone_offset, |meaning| meaning.offset)
855 }
856}
857
858#[cfg(feature = "tzdb")]
863fn iana_moment(unix: i64) -> (Timestamp, i64) {
864 let last = Timestamp::MAX.as_second();
865 let shift = if unix > last {
866 ((unix - last - 1) / SECS_PER_REPEAT + 1) * SECS_PER_REPEAT
867 } else {
868 0
869 };
870 let moment = Timestamp::from_second(unix - shift).unwrap_or(Timestamp::MIN);
871 (moment, shift)
872}
873
874impl PgTimeZone {
875 pub(crate) fn abbreviation_is_known(
878 &self,
879 abbreviation: &str,
880 ) -> Option<(AbbreviationUse, bool)> {
881 let mut uses = Vec::new();
882 match &self.rules {
883 Rules::Fixed {
884 offset,
885 abbreviation: own,
886 } => {
887 if own == abbreviation {
888 uses.push(AbbreviationUse {
889 offset: *offset,
890 dst: false,
891 });
892 }
893 }
894 Rules::Posix {
895 rules,
896 std_name,
897 dst_name,
898 } => uses.extend(posix_use(rules, std_name, dst_name, abbreviation)),
899 #[cfg(feature = "tzdb")]
900 Rules::Iana(zone) => {
901 let first = zone.to_offset_info(Timestamp::MIN);
902 if first.abbreviation() == abbreviation {
903 uses.push(AbbreviationUse {
904 offset: first.offset().seconds(),
905 dst: first.dst().is_dst(),
906 });
907 }
908 for change in zone
909 .following(Timestamp::MIN)
910 .take_while(|change| change.timestamp().as_second() <= ABBREVIATION_SCAN_END)
911 {
912 if change.abbreviation() == abbreviation {
913 uses.push(AbbreviationUse {
914 offset: change.offset().seconds(),
915 dst: change.dst().is_dst(),
916 });
917 }
918 }
919 }
920 }
921 let first = *uses.first()?;
922 Some((first, uses.iter().all(|other| *other == first)))
923 }
924
925 pub(crate) fn interpret_abbreviation(
929 &self,
930 abbreviation: &str,
931 #[cfg_attr(
932 not(feature = "tzdb"),
933 expect(unused_variables, reason = "only an IANA zone reads the instant")
934 )]
935 unix: i64,
936 ) -> Option<AbbreviationUse> {
937 match &self.rules {
938 Rules::Fixed { .. } | Rules::Posix { .. } => self
939 .abbreviation_is_known(abbreviation)
940 .map(|(use_, _)| use_),
941 #[cfg(feature = "tzdb")]
942 Rules::Iana(zone) => interpret_iana_abbreviation(zone, abbreviation, unix),
943 }
944 }
945}
946
947#[cfg(feature = "tzdb")]
949fn interpret_iana_abbreviation(
950 zone: &TimeZone,
951 abbreviation: &str,
952 unix: i64,
953) -> Option<AbbreviationUse> {
954 let (at, _) = iana_moment(unix);
955 let after = Timestamp::from_second(at.as_second() + 1).unwrap_or(Timestamp::MAX);
956 let matching = |abbreviation_used: &str, offset: jiff::tz::Offset, dst: jiff::tz::Dst| {
957 (abbreviation_used == abbreviation).then(|| AbbreviationUse {
958 offset: offset.seconds(),
959 dst: dst.is_dst(),
960 })
961 };
962 if let Some(found) = zone
963 .preceding(after)
964 .find_map(|change| matching(change.abbreviation(), change.offset(), change.dst()))
965 {
966 return Some(found);
967 }
968 let first = zone.to_offset_info(Timestamp::MIN);
969 if let Some(found) = matching(first.abbreviation(), first.offset(), first.dst()) {
970 return Some(found);
971 }
972 zone.following(at)
973 .take_while(|change| change.timestamp().as_second() <= ABBREVIATION_SCAN_END)
974 .find_map(|change| matching(change.abbreviation(), change.offset(), change.dst()))
975}
976
977fn posix_use(
981 rules: &Posix,
982 std_name: &str,
983 dst_name: &str,
984 abbreviation: &str,
985) -> Option<AbbreviationUse> {
986 if std_name == abbreviation {
987 rules.switches.then(|| AbbreviationUse {
988 offset: rules.offset(false),
989 dst: false,
990 })
991 } else if dst_name == abbreviation {
992 Some(AbbreviationUse {
993 offset: rules.offset(true),
994 dst: true,
995 })
996 } else {
997 None
998 }
999}
1000
1001impl PartialEq for PgTimeZone {
1002 fn eq(&self, other: &Self) -> bool {
1003 self.name == other.name
1004 }
1005}
1006
1007impl Eq for PgTimeZone {}
1008
1009impl Hash for PgTimeZone {
1010 fn hash<H: Hasher>(&self, state: &mut H) {
1011 self.name.hash(state);
1012 }
1013}
1014
1015impl fmt::Display for PgTimeZone {
1016 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1017 f.write_str(&self.name)
1018 }
1019}