Skip to main content

sql_values/postgres/
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 under the `tzdb` feature, which is asked only for
5//! a zone's offset and abbreviation at an instant and for its transitions. Without it a name
6//! loads as in a PostgreSQL with no time zone files. Fixed offsets and POSIX rules are ported and
7//! hold over PostgreSQL's whole range.
8//!
9//! The `timezone_abbreviations` sets PostgreSQL installs are bundled from its source, under the
10//! PostgreSQL license in `zone/timezonesets/COPYRIGHT`.
11
12mod 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
33/// The bundled sets as static tables, which the build script writes with the parser in
34/// `tznames`.
35mod 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/// 2200-01-01 00:00:00 UTC in seconds from 1970, where a scan of an IANA zone's abbreviations
44/// stops, past every rule change the database records and a century of the POSIX rules that
45/// then only repeat the same abbreviations.
46#[cfg(feature = "tzdb")]
47const ABBREVIATION_SCAN_END: i64 = 7_258_118_400;
48
49/// A `timezone_abbreviations` set, the abbreviations a literal may write for its zone.
50///
51/// ```
52/// use sql_values::postgres::{TimeZoneAbbreviations, TimeZoneAbbreviationsError};
53///
54/// let local = |name: &str| Some(match name {
55///     "Local" => "@INCLUDE Default\n@OVERRIDE\nIST 19800 # India\n",
56///     other => TimeZoneAbbreviations::bundled_file(other)?,
57/// });
58/// assert!(TimeZoneAbbreviations::load("Local", local).is_ok());
59/// let clash = |name: &str| match name {
60///     "Clash" => Some("@INCLUDE Default\nIST 19800\n"),
61///     other => TimeZoneAbbreviations::bundled_file(other),
62/// };
63/// assert_eq!(
64///     TimeZoneAbbreviations::load("Clash", clash),
65///     Err(TimeZoneAbbreviationsError::MultiplyDefined {
66///         abbreviation: "ist".to_owned(),
67///         file: "Clash".to_owned(),
68///         line: 2,
69///     }),
70/// );
71/// ```
72#[derive(Debug, Clone, PartialEq, Eq, Hash)]
73pub struct TimeZoneAbbreviations {
74    entries: Cow<'static, [Abbreviation]>,
75}
76
77/// `Default`, the set `timezone_abbreviations` names in a stock installation.
78pub(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    /// The set PostgreSQL installs as `name`, `Default`, `Australia` or `India`, as
90    /// `timezone_abbreviations` names it.
91    #[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    /// The text of the file PostgreSQL installs as `name`, for a set of its own that includes
102    /// one.
103    #[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    /// PostgreSQL 18's `load_tzoffsets`, the set of the file `name`, which `files` holds with
114    /// every file it includes, as PostgreSQL's `timezonesets` directory holds them.
115    ///
116    /// # Errors
117    ///
118    /// The [`TimeZoneAbbreviationsError`] PostgreSQL raises for the file or one it includes.
119    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    /// The meaning of the lowercased `word`, as `datebsearch` finds it.
131    pub(crate) fn lookup(&self, word: &[u8]) -> Option<&Meaning> {
132        tznames::search(&self.entries, word).map(|entry| &entry.meaning)
133    }
134}
135
136/// What an abbreviation means in the zone that uses it, as `pg_timezone_abbrev_is_known` and
137/// `pg_interpret_timezone_abbrev` find it.
138#[derive(Debug, Clone, Copy, PartialEq, Eq)]
139pub(crate) struct AbbreviationUse {
140    /// Seconds east of UTC.
141    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;
148/// `UNIX_EPOCH_JDATE`, the Julian day of 1970-01-01.
149const UNIX_EPOCH_JDATE: i32 = 2_440_588;
150/// 2000-01-01 00:00:00 UTC in seconds from 1970, where `pg_tz_acceptable` looks for leap seconds.
151const TIME_2000: i64 = 946_684_800;
152/// `TZ_STRLEN_MAX`, the longest name `pg_tzset` takes.
153const TZ_STRLEN_MAX: usize = 255;
154/// The largest hour `getsecs` reads, `HOURSPERDAY * DAYSPERWEEK - 1`.
155const MAX_RULE_HOUR: i32 = 167;
156/// `TZDEFRULESTRING`, the rules of a POSIX zone that names daylight saving time but no rules.
157const DEFAULT_RULES: &str = "M3.2.0,M11.1.0";
158/// Years after which the Gregorian calendar, and so every POSIX rule, repeats.
159const YEARS_PER_REPEAT: i32 = 400;
160/// `SECSPERREPEAT`, the seconds in [`YEARS_PER_REPEAT`] Gregorian years.
161#[cfg(feature = "tzdb")]
162const SECS_PER_REPEAT: i64 = 146_097 * SECS_PER_DAY;
163
164/// Why PostgreSQL refuses a `TimeZone` setting, one variant per message or detail it raises.
165#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, thiserror::Error)]
166pub enum TimeZoneError {
167    /// Neither an offset, an IANA name nor a POSIX specification.
168    #[error("invalid value for parameter \"TimeZone\"")]
169    InvalidValue,
170    /// An offset in hours or an interval of 168 hours or more.
171    #[error("UTC timezone offset is out of range")]
172    OffsetOutOfRange,
173    /// An `interval '...'` setting with months.
174    #[error("cannot specify months in time zone interval")]
175    MonthsInInterval,
176    /// An `interval '...'` setting with days.
177    #[error("cannot specify days in time zone interval")]
178    DaysInInterval,
179    /// A zone whose offset at 2000-01-01 00:00:00 UTC has seconds, which PostgreSQL takes for
180    /// leap seconds.
181    #[error("time zone appears to use leap seconds")]
182    LeapSeconds,
183    /// An `interval '...'` setting `interval_in` refuses.
184    #[error(transparent)]
185    Interval(#[from] IntervalError),
186}
187
188/// A time zone as PostgreSQL's `TimeZone` setting reads it, equal to another when `SHOW timezone`
189/// names both alike.
190///
191/// ```
192/// use sql_values::postgres::{PgTimeZone, TimeZoneError};
193///
194/// #[cfg(feature = "tzdb")]
195/// assert_eq!(PgTimeZone::parse("europe/rome").unwrap().name(), "Europe/Rome");
196/// // A number is hours east of UTC, a POSIX specification hours west of it.
197/// assert_eq!(PgTimeZone::parse("+02").unwrap().name(), "<+02>-02");
198/// assert_eq!(PgTimeZone::parse("utc+2").unwrap().name(), "UTC+2");
199/// assert_eq!(PgTimeZone::parse("+168"), Err(TimeZoneError::OffsetOutOfRange));
200/// assert_eq!(PgTimeZone::parse("CEST"), Err(TimeZoneError::InvalidValue));
201/// ```
202#[derive(Debug, Clone)]
203pub struct PgTimeZone {
204    name: String,
205    rules: Rules,
206}
207
208/// How a zone's offset is found.
209#[derive(Debug, Clone)]
210enum Rules {
211    /// One offset east of UTC, in seconds, forever, and its abbreviation.
212    Fixed { offset: i32, abbreviation: String },
213    /// A POSIX specification with daylight saving time, and its two abbreviations.
214    Posix {
215        rules: Posix,
216        std_name: String,
217        dst_name: String,
218    },
219    /// An IANA zone with transitions, from jiff's database.
220    #[cfg(feature = "tzdb")]
221    Iana(TimeZone),
222}
223
224/// A POSIX specification with daylight saving time, offsets west of UTC as `tzparse` keeps them.
225#[derive(Debug, Clone, Copy)]
226struct Posix {
227    std_offset: i32,
228    dst_offset: i32,
229    start: Rule,
230    end: Rule,
231    /// Whether any year has transitions. A zone without is in daylight saving time throughout.
232    switches: bool,
233}
234
235/// A POSIX transition rule and its local time of day in seconds.
236#[derive(Debug, Clone, Copy)]
237struct Rule {
238    date: RuleDate,
239    time: i32,
240}
241
242/// A zone's abbreviation at an instant, borrowed from the zone or held by jiff's answer.
243pub(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/// The day a POSIX rule names.
260#[derive(Debug, Clone, Copy)]
261enum RuleDate {
262    /// `Jn`, day 1 to 365 with February 29 never counted.
263    Julian(i32),
264    /// `n`, day 0 to 365 with February 29 counted.
265    DayOfYear(i32),
266    /// `Mm.w.d`, day `d` of week `w` of month `m`.
267    MonthWeekDay { month: i32, week: i32, weekday: i32 },
268}
269
270/// A cursor over a POSIX specification.
271struct 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    /// `getzname` or `getqzname`, the abbreviation read.
292    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    /// `getnum`, a decimal number within `min..=max`.
313    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    /// `getsecs`, `hh[:mm[:ss]]` in seconds.
329    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    /// `getoffset`, `[+-]hh[:mm[:ss]]` in seconds.
341    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    /// `getrule`, `Jn`, `n` or `Mm.w.d` with an optional `/time`, 02:00 by default.
351    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
381/// `tzparse` without `lastditch`, the rules of an uppercased POSIX specification.
382fn 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
442/// C's `isleap`.
443const fn is_leap(year: i32) -> bool {
444    year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)
445}
446
447impl Rule {
448    /// `transtime`, the rule's moment in seconds from January 1 of `year` at 00:00 UTC, with
449    /// `offset` seconds west of UTC in effect.
450    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                // Zeller's congruence for the weekday of the month's first day.
461                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    /// The year's two transitions, in seconds from 1970 and whether daylight saving time follows
488    /// each, as `tzparse` lays them out, or `None` when the year has none.
489    fn year(self, year: i32) -> Option<[(i64, bool); 2]> {
490        // The calendar of the same year in 2000 to 2399, where `tzparse` computes it, since
491        // Zeller's congruence in C's arithmetic holds for positive years only.
492        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    /// The offset east of UTC on either side of a transition.
510    const fn offset(self, dst: bool) -> i32 {
511        if dst {
512            -self.dst_offset
513        } else {
514            -self.std_offset
515        }
516    }
517
518    /// The transitions of the years around `year`, in order.
519    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    /// Whether daylight saving time is in effect at `unix`, as `localsub` finds it.
524    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    /// The offset east of UTC in effect at `unix`, as `localsub` finds it.
540    fn offset_at(self, unix: i64) -> i32 {
541        self.offset(self.dst_at(unix))
542    }
543
544    /// The first transition after `unix`, its moment and the offset east after it.
545    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
558/// The UTC year of `unix` seconds from 1970.
559fn 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
564/// C's `strtod` over the whole of `text`, skipping leading blanks and a `+`, or `None` when
565/// characters are left over.
566fn 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    /// PostgreSQL 18's `check_timezone`, reading an `interval '...'`, else a number of hours east of UTC
584    /// as C's `strtod` reads it, else a name `pg_tzset` loads, `GMT`, an IANA name in jiff's
585    /// bundled database or a POSIX specification, refused when its offset at 2000-01-01 has
586    /// seconds.
587    ///
588    /// # Errors
589    ///
590    /// The [`TimeZoneError`] PostgreSQL raises.
591    ///
592    /// ```
593    /// use sql_values::postgres::PgTimeZone;
594    ///
595    /// let name = |setting| PgTimeZone::parse(setting).map(|zone| zone.to_string());
596    /// assert_eq!(name("2.5").unwrap(), "<+02:30>-02:30");
597    /// assert_eq!(name("interval '-01:00'").unwrap(), "<-01>+01");
598    /// assert_eq!(name("est5edt").unwrap(), "EST5EDT");
599    /// assert_eq!(name("xxx3yyy").unwrap(), "XXX3YYY");
600    /// ```
601    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            // C's conversion of `-hours * SECS_PER_HOUR` to `long` truncates, and one beyond
626            // `tzparse`'s 167:59:59 is refused, as is an infinity or NaN.
627            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    /// `pg_tzset_offset`, the zone of a fixed offset `west` seconds west of UTC, named as a
642    /// POSIX specification with the offset east in its abbreviation.
643    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    /// `pg_tzset`, loading `GMT`, an IANA name, or an uppercased POSIX specification.
677    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        // `tzload` drops one leading colon, and a name that keeps one is no POSIX specification.
692        #[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    /// `tzload`, the IANA zone `file` names in jiff's bundled database.
704    #[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        // A zone with no transitions has one fixed offset, which `fixed_offset` reports.
712        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    /// The name `SHOW timezone` prints for the zone.
729    #[must_use]
730    pub fn name(&self) -> &str {
731        &self.name
732    }
733
734    /// The zone's one offset east of UTC in seconds when it never changes, as
735    /// `pg_get_timezone_offset` finds it. A POSIX specification counts hours west of UTC, so
736    /// `+05:30` is five and a half hours behind it.
737    ///
738    /// ```
739    /// use sql_values::postgres::PgTimeZone;
740    ///
741    /// let offset = |setting| PgTimeZone::parse(setting).unwrap().fixed_offset();
742    /// #[cfg(feature = "tzdb")]
743    /// {
744    ///     assert_eq!(offset("UTC"), Some(0));
745    ///     assert_eq!(offset("Etc/GMT+5"), Some(-18_000));
746    ///     assert_eq!(offset("Europe/Rome"), None);
747    /// }
748    /// assert_eq!(offset("+2"), Some(7_200));
749    /// assert_eq!(offset("interval '-01:00'"), Some(-3_600));
750    /// assert_eq!(offset("+05:30"), Some(-19_800));
751    /// // Daylight saving time all year, and a daylight offset equal to the standard one.
752    /// assert_eq!(offset("EST5EDT,0/0,J365/26"), Some(-14_400));
753    /// assert_eq!(offset("EST5EDT5"), Some(-18_000));
754    /// // Daylight saving time that ends at the instant it starts again still has two offsets.
755    /// assert_eq!(offset("EST5EDT,0/0,J365/25"), None);
756    /// assert_eq!(offset("EST5EDT"), None);
757    /// ```
758    #[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            // `load` keeps an IANA zone without transitions as `Fixed`, and every transition in
765            // jiff's database changes the offset.
766            #[cfg(feature = "tzdb")]
767            Rules::Iana(_) => None,
768        }
769    }
770
771    /// Seconds east of UTC in effect at `unix` seconds from 1970, as `pg_localtime` finds it.
772    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    /// The offset east of UTC and the abbreviation in effect at `unix` seconds from 1970, the
782    /// `tm_gmtoff` and `tm_zone` of `pg_localtime`.
783    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    /// The offset east of UTC in effect at `unix` and the first transition after it, its moment
807    /// and the offset east after it, as `pg_next_dst_boundary` finds them.
808    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    /// The offset east of UTC that `DetermineTimeZoneOffsetInternal` gives a local clock of
827    /// `local` seconds from 1970 read as UTC: the offset at the first transition after the
828    /// clock less a day, a clock the change skips taking the offset before it and one it repeats
829    /// the offset after it.
830    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    /// `DetermineTimeZoneAbbrevOffset`, the offset the uppercased `abbreviation` had at the
849    /// local clock of `local` seconds from 1970 read as UTC, or the zone's own offset there when
850    /// the zone never used it.
851    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/// The moment jiff places for an IANA zone asked about `unix` seconds from 1970, and the seconds
859/// `unix` lies past it. As `localsub` moves an instant past a zone's last transition, one past
860/// jiff's last moment moves back by whole [`YEARS_PER_REPEAT`] cycles of the zone's POSIX rule,
861/// and one before jiff's first moment, before every zone's first transition, takes jiff's first.
862#[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    /// `pg_timezone_abbrev_is_known`, the meaning of the uppercased `abbreviation` among the
876    /// zone's own, and whether it has only that one.
877    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    /// `pg_interpret_timezone_abbrev`, the meaning the uppercased `abbreviation` had in the zone
926    /// at `unix` seconds from 1970: the latest before it, else the one before every transition,
927    /// else the first after it.
928    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/// [`PgTimeZone::interpret_abbreviation`] in an IANA zone.
948#[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
977/// The meaning of `abbreviation` in a POSIX zone, whose `tzparse` types are the standard one,
978/// named first, and the daylight one, or the daylight one alone for a zone in daylight saving
979/// time throughout.
980fn 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}