Skip to main content

sql_values/
zone.rs

1//! PostgreSQL 18's `TimeZone` setting as `check_timezone`, `pg_tzset` and `tzparse` read it, and the
2//! offsets `pg_localtime` and `DetermineTimeZoneOffset` find in a zone.
3//!
4//! IANA zones come from jiff's bundled database, which is asked only for a zone's offset and
5//! abbreviation at an instant and for its transitions. Fixed offsets and POSIX rules are ported
6//! and hold over PostgreSQL's whole range.
7//!
8//! The `timezone_abbreviations` sets PostgreSQL installs are bundled from its source, under the
9//! PostgreSQL license in `zone/timezonesets/COPYRIGHT`.
10
11mod 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
35/// The bundled sets as static tables, which the build script writes with the parser in
36/// `tznames`.
37mod 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
45/// 2200-01-01 00:00:00 UTC in seconds from 1970, where a scan of an IANA zone's abbreviations
46/// stops, past every rule change the database records and a century of the POSIX rules that
47/// then only repeat the same abbreviations.
48const ABBREVIATION_SCAN_END: i64 = 7_258_118_400;
49
50/// A `timezone_abbreviations` set, the abbreviations a literal may write for its zone.
51///
52/// ```
53/// use sql_values::{TimeZoneAbbreviations, TimeZoneAbbreviationsError};
54///
55/// let local = |name: &str| Some(match name {
56///     "Local" => "@INCLUDE Default\n@OVERRIDE\nIST 19800 # India\n",
57///     other => TimeZoneAbbreviations::bundled_file(other)?,
58/// });
59/// assert!(TimeZoneAbbreviations::load("Local", local).is_ok());
60/// let clash = |name: &str| match name {
61///     "Clash" => Some("@INCLUDE Default\nIST 19800\n"),
62///     other => TimeZoneAbbreviations::bundled_file(other),
63/// };
64/// assert_eq!(
65///     TimeZoneAbbreviations::load("Clash", clash),
66///     Err(TimeZoneAbbreviationsError::MultiplyDefined {
67///         abbreviation: "ist".to_owned(),
68///         file: "Clash".to_owned(),
69///         line: 2,
70///     }),
71/// );
72/// ```
73#[derive(Debug, Clone, PartialEq, Eq, Hash)]
74pub struct TimeZoneAbbreviations {
75    entries: Cow<'static, [Abbreviation]>,
76}
77
78/// `Default`, the set `timezone_abbreviations` names in a stock installation.
79pub(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    /// The set PostgreSQL installs as `name`, `Default`, `Australia` or `India`, as
91    /// `timezone_abbreviations` names it.
92    #[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    /// The text of the file PostgreSQL installs as `name`, for a set of its own that includes
103    /// one.
104    #[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    /// PostgreSQL 18's `load_tzoffsets`, the set of the file `name`, which `files` holds with
115    /// every file it includes, as PostgreSQL's `timezonesets` directory holds them.
116    ///
117    /// # Errors
118    ///
119    /// The [`TimeZoneAbbreviationsError`] PostgreSQL raises for the file or one it includes.
120    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    /// The meaning of the lowercased `word`, as `datebsearch` finds it.
132    pub(crate) fn lookup(&self, word: &[u8]) -> Option<&Meaning> {
133        tznames::search(&self.entries, word).map(|entry| &entry.meaning)
134    }
135}
136
137/// What an abbreviation means in the zone that uses it, as `pg_timezone_abbrev_is_known` and
138/// `pg_interpret_timezone_abbrev` find it.
139#[derive(Debug, Clone, Copy, PartialEq, Eq)]
140pub(crate) struct AbbreviationUse {
141    /// Seconds east of UTC.
142    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;
149/// `UNIX_EPOCH_JDATE`, the Julian day of 1970-01-01.
150const UNIX_EPOCH_JDATE: i32 = 2_440_588;
151/// 2000-01-01 00:00:00 UTC in seconds from 1970, where `pg_tz_acceptable` looks for leap seconds.
152const TIME_2000: i64 = 946_684_800;
153/// `TZ_STRLEN_MAX`, the longest name `pg_tzset` takes.
154const TZ_STRLEN_MAX: usize = 255;
155/// The largest hour `getsecs` reads, `HOURSPERDAY * DAYSPERWEEK - 1`.
156const MAX_RULE_HOUR: i32 = 167;
157/// `TZDEFRULESTRING`, the rules of a POSIX zone that names daylight saving time but no rules.
158const DEFAULT_RULES: &str = "M3.2.0,M11.1.0";
159/// Years after which the Gregorian calendar, and so every POSIX rule, repeats.
160const YEARS_PER_REPEAT: i32 = 400;
161
162/// Why PostgreSQL refuses a `TimeZone` setting, one variant per message or detail it raises.
163#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, thiserror::Error)]
164pub enum TimeZoneError {
165    /// Neither an offset, an IANA name nor a POSIX specification.
166    #[error("invalid value for parameter \"TimeZone\"")]
167    InvalidValue,
168    /// An offset in hours or an interval of 168 hours or more.
169    #[error("UTC timezone offset is out of range")]
170    OffsetOutOfRange,
171    /// An `interval '...'` setting with months.
172    #[error("cannot specify months in time zone interval")]
173    MonthsInInterval,
174    /// An `interval '...'` setting with days.
175    #[error("cannot specify days in time zone interval")]
176    DaysInInterval,
177    /// A zone whose offset at 2000-01-01 00:00:00 UTC has seconds, which PostgreSQL takes for
178    /// leap seconds.
179    #[error("time zone appears to use leap seconds")]
180    LeapSeconds,
181    /// An `interval '...'` setting `interval_in` refuses.
182    #[error(transparent)]
183    Interval(#[from] IntervalError),
184}
185
186/// A time zone as PostgreSQL's `TimeZone` setting reads it, equal to another when `SHOW timezone`
187/// names both alike.
188///
189/// ```
190/// use sql_values::{PgTimeZone, TimeZoneError};
191///
192/// assert_eq!(PgTimeZone::parse("europe/rome").unwrap().name(), "Europe/Rome");
193/// // A number is hours east of UTC, a POSIX specification hours west of it.
194/// assert_eq!(PgTimeZone::parse("+02").unwrap().name(), "<+02>-02");
195/// assert_eq!(PgTimeZone::parse("utc+2").unwrap().name(), "UTC+2");
196/// assert_eq!(PgTimeZone::parse("+168"), Err(TimeZoneError::OffsetOutOfRange));
197/// assert_eq!(PgTimeZone::parse("CEST"), Err(TimeZoneError::InvalidValue));
198/// ```
199#[derive(Debug, Clone)]
200pub struct PgTimeZone {
201    name: String,
202    rules: Rules,
203}
204
205/// How a zone's offset is found.
206#[derive(Debug, Clone)]
207enum Rules {
208    /// One offset east of UTC, in seconds, forever, and its abbreviation.
209    Fixed { offset: i32, abbreviation: String },
210    /// A POSIX specification with daylight saving time, and its two abbreviations.
211    Posix {
212        rules: Posix,
213        std_name: String,
214        dst_name: String,
215    },
216    /// An IANA zone with transitions, from jiff's database.
217    Iana(TimeZone),
218}
219
220/// A POSIX specification with daylight saving time, offsets west of UTC as `tzparse` keeps them.
221#[derive(Debug, Clone, Copy)]
222struct Posix {
223    std_offset: i32,
224    dst_offset: i32,
225    start: Rule,
226    end: Rule,
227    /// Whether any year has transitions. A zone without is in daylight saving time throughout.
228    switches: bool,
229}
230
231/// A POSIX transition rule and its local time of day in seconds.
232#[derive(Debug, Clone, Copy)]
233struct Rule {
234    date: RuleDate,
235    time: i32,
236}
237
238/// The day a POSIX rule names.
239#[derive(Debug, Clone, Copy)]
240enum RuleDate {
241    /// `Jn`, day 1 to 365 with February 29 never counted.
242    Julian(i32),
243    /// `n`, day 0 to 365 with February 29 counted.
244    DayOfYear(i32),
245    /// `Mm.w.d`, day `d` of week `w` of month `m`.
246    MonthWeekDay { month: i32, week: i32, weekday: i32 },
247}
248
249/// A cursor over a POSIX specification.
250struct 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    /// `getzname` or `getqzname`, the abbreviation read.
271    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    /// `getnum`, a decimal number within `min..=max`.
292    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    /// `getsecs`, `hh[:mm[:ss]]` in seconds.
308    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    /// `getoffset`, `[+-]hh[:mm[:ss]]` in seconds.
320    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    /// `getrule`, `Jn`, `n` or `Mm.w.d` with an optional `/time`, 02:00 by default.
330    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
360/// `tzparse` without `lastditch`, the rules of an uppercased POSIX specification.
361fn 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
421/// C's `isleap`.
422const fn is_leap(year: i32) -> bool {
423    year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)
424}
425
426impl Rule {
427    /// `transtime`, the rule's moment in seconds from January 1 of `year` at 00:00 UTC, with
428    /// `offset` seconds west of UTC in effect.
429    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                // Zeller's congruence for the weekday of the month's first day.
440                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    /// The year's two transitions, in seconds from 1970 and whether daylight saving time follows
467    /// each, as `tzparse` lays them out, or `None` when the year has none.
468    fn year(self, year: i32) -> Option<[(i64, bool); 2]> {
469        // The calendar of the same year in 2000 to 2399, where `tzparse` computes it, since
470        // Zeller's congruence in C's arithmetic holds for positive years only.
471        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    /// The offset east of UTC on either side of a transition.
489    const fn offset(self, dst: bool) -> i32 {
490        if dst {
491            -self.dst_offset
492        } else {
493            -self.std_offset
494        }
495    }
496
497    /// The transitions of the years around `year`, in order.
498    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    /// The offset east of UTC in effect at `unix`, as `localsub` finds it.
503    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    /// The first transition after `unix`, its moment and the offset east after it.
519    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
532/// The UTC year of `unix` seconds from 1970.
533fn 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
538/// C's `strtod` over the whole of `text`, skipping leading blanks and a `+`, or `None` when
539/// characters are left over.
540fn 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    /// PostgreSQL 18's `check_timezone`, reading an `interval '...'`, else a number of hours east of UTC
558    /// as C's `strtod` reads it, else a name `pg_tzset` loads, `GMT`, an IANA name in jiff's
559    /// bundled database or a POSIX specification, refused when its offset at 2000-01-01 has
560    /// seconds.
561    ///
562    /// # Errors
563    ///
564    /// The [`TimeZoneError`] PostgreSQL raises.
565    ///
566    /// ```
567    /// use sql_values::PgTimeZone;
568    ///
569    /// let name = |setting| PgTimeZone::parse(setting).map(|zone| zone.to_string());
570    /// assert_eq!(name("2.5").unwrap(), "<+02:30>-02:30");
571    /// assert_eq!(name("interval '-01:00'").unwrap(), "<-01>+01");
572    /// assert_eq!(name("est5edt").unwrap(), "EST5EDT");
573    /// assert_eq!(name("xxx3yyy").unwrap(), "XXX3YYY");
574    /// ```
575    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            // C's conversion of `-hours * SECS_PER_HOUR` to `long` truncates, and one beyond
600            // `tzparse`'s 167:59:59 is refused, as is an infinity or NaN.
601            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    /// `pg_tzset_offset`, the zone of a fixed offset `west` seconds west of UTC, named as a
619    /// POSIX specification with the offset east in its abbreviation.
620    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    /// `pg_tzset`, loading `GMT`, an IANA name, or an uppercased POSIX specification.
654    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        // `tzload` drops one leading colon, and a name that keeps one is no POSIX specification.
669        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            // A zone with no transitions keeps its one offset beyond jiff's years too.
677            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    /// The name `SHOW timezone` prints for the zone.
700    #[must_use]
701    pub fn name(&self) -> &str {
702        &self.name
703    }
704
705    /// Seconds east of UTC in effect at `unix` seconds from 1970, as `pg_localtime` finds it, or
706    /// `None` where an IANA zone is asked about an instant outside jiff's years.
707    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    /// The offset east of UTC in effect at `unix` and the first transition after it, its moment
716    /// and the offset east after it, as `pg_next_dst_boundary` finds them.
717    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    /// The offset east of UTC that `DetermineTimeZoneOffsetInternal` gives a local clock of
735    /// `local` seconds from 1970 read as UTC: the offset at the first transition after the
736    /// clock less a day, a clock the change skips taking the offset before it and one it repeats
737    /// the offset after it. `None` where an IANA zone is asked about a clock outside jiff's
738    /// years.
739    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    /// `pg_get_timezone_offset`, the zone's one offset east of UTC when it never changes. A POSIX
760    /// specification in daylight saving time throughout has one too, but its rules need commas,
761    /// which no zone name inside a literal holds.
762    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    /// `pg_timezone_abbrev_is_known`, the meaning of the uppercased `abbreviation` among the
770    /// zone's own, and whether it has only that one.
771    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    /// `pg_interpret_timezone_abbrev`, the meaning the uppercased `abbreviation` had in the zone
819    /// at `unix` seconds from 1970: the latest before it, else the one before every transition,
820    /// else the first after it.
821    ///
822    /// # Errors
823    ///
824    /// [`DateTimeError::OutsideJiffRange`] where an IANA zone is asked about an instant outside
825    /// jiff's years.
826    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
864/// The meaning of `abbreviation` in a POSIX zone, whose `tzparse` types are the standard one,
865/// named first, and the daylight one, or the daylight one alone for a zone in daylight saving
866/// time throughout.
867fn 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}