Skip to main content

jiff_core/tz/tzif/
query.rs

1use crate::{
2    Timestamp,
3    civil::DateTime,
4    tz::{
5        Abbreviation, AmbiguousOffset, AmbiguousTimestamp, Offset, OffsetInfo,
6        Transition, posix,
7    },
8};
9
10use super::{
11    DateTime as TzifDateTime, LocalTimeType, TimeZone,
12    Timestamp as TzifTimestamp, TransitionInfo as TzifTransitionInfo,
13    TransitionKind,
14};
15
16impl TimeZone {
17    /// Returns the appropriate time zone offset to use for the given
18    /// timestamp.
19    pub fn to_offset(&self, timestamp: Timestamp) -> Offset {
20        match self.to_local_time_type(timestamp) {
21            Ok(typ) => typ.offset,
22            Err(tz) => tz.to_offset(timestamp),
23        }
24    }
25
26    /// Returns the appropriate time zone offset to use for the given
27    /// timestamp.
28    ///
29    /// This also includes whether the offset returned should be considered to
30    /// be DST or not, along with the time zone abbreviation (e.g., EST for
31    /// standard time in New York, and EDT for DST in New York).
32    pub fn to_offset_info(&self, timestamp: Timestamp) -> OffsetInfo {
33        let typ = match self.to_local_time_type(timestamp) {
34            Ok(typ) => typ,
35            Err(tz) => return tz.to_offset_info(timestamp),
36        };
37        // This clone will generally just be a memcpy. It only does a heap
38        // alloc when the designation is unusually long. (Which should be never
39        // for standard tzdata.)
40        let abbreviation = self.designation(typ).clone();
41        OffsetInfo { offset: typ.offset, abbreviation, dst: typ.dst }
42    }
43
44    /// Returns the local time type for the timestamp given.
45    ///
46    /// If one could not be found, then this implies that the caller should
47    /// use the POSIX time zone returned in the error variant.
48    fn to_local_time_type(
49        &self,
50        timestamp: Timestamp,
51    ) -> Result<&LocalTimeType, &posix::TimeZone> {
52        let timestamp = TzifTimestamp::new(timestamp);
53        // This is guaranteed because we always push at least one transition.
54        // This isn't guaranteed by TZif since it might have 0 transitions,
55        // but we always add a "dummy" first transition with our minimum
56        // `Timestamp` value. TZif doesn't do this because there is no
57        // universal minimum timestamp. (`i64::MIN` is a candidate, but that's
58        // likely to cause overflow in readers that don't do error checking.)
59        //
60        // The result of the dummy transition is that the code below is simpler
61        // with fewer special cases.
62        let timestamps = self.timestamps();
63        let last = *timestamps.last().expect("non-empty transitions");
64        let index = if timestamp > last {
65            timestamps.len() - 1
66        } else {
67            let search = self.timestamps().binary_search(&timestamp);
68            match search {
69                // Since the first transition is always Timestamp::MIN, it's
70                // impossible for any timestamp to sort before it.
71                Err(0) => {
72                    {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("impossible to come before Timestamp::MIN")));
}unreachable!("impossible to come before Timestamp::MIN")
73                }
74                Ok(i) => i,
75                // i points to the position immediately after the matching
76                // timestamp. And since we know that i>0 because of the i==0
77                // check above, we can safely subtract 1.
78                Err(i) => i.checked_sub(1).expect("i is non-zero"),
79            }
80        };
81        // Our index is always in bounds. The only way it couldn't be is if
82        // binary search returns an Err(len) for a time greater than the
83        // maximum transition. But we account for that above by converting
84        // Err(len) to Err(len-1).
85        if true {
    if !(index < timestamps.len()) {
        ::core::panicking::panic("assertion failed: index < timestamps.len()")
    };
};debug_assert!(index < timestamps.len());
86        // RFC 8536 says: "Local time for timestamps on or after the last
87        // transition is specified by the TZ string in the footer (Section 3.3)
88        // if present and nonempty; otherwise, it is unspecified."
89        //
90        // Subtracting 1 is OK because we know self.transitions is not empty.
91        let index = if index < timestamps.len() - 1 {
92            // This is the typical case in "fat" TZif files: we found a
93            // matching transition.
94            index
95        } else {
96            match self.posix_tz() {
97                // This is the typical case in "slim" TZif files, where the
98                // last transition is, as I understand it, the transition at
99                // which a consistent rule started that a POSIX TZ string can
100                // fully describe. For example, (as of 2024-03-27) the last
101                // transition in the "fat" America/New_York TZif file is
102                // in 2037, where as in the "slim" version it is 2007.
103                //
104                // This is likely why some things break with the "slim"
105                // version: they don't support POSIX TZ strings (or don't
106                // support them correctly).
107                Some(tz) => return Err(tz),
108                // This case is technically unspecified, but I think the
109                // typical thing to do is to just use the last transition.
110                // I'm not 100% sure on this one.
111                None => index,
112            }
113        };
114        Ok(self.local_time_type(index))
115    }
116
117    /// Returns a possibly ambiguous timestamp for the given civil datetime.
118    ///
119    /// The given datetime should correspond to the "wall" clock time of what
120    /// humans use to tell time for this time zone.
121    ///
122    /// Note that "ambiguous timestamp" is represented by the possible
123    /// selection of offsets that could be applied to the given datetime. In
124    /// general, it is only ambiguous around transitions to-and-from DST. The
125    /// ambiguity can arise as a "fold" (when a particular wall clock time is
126    /// repeated) or as a "gap" (when a particular wall clock time is skipped
127    /// entirely).
128    pub fn to_ambiguous_timestamp(&self, dt: DateTime) -> AmbiguousTimestamp {
129        // This implementation very nearly mirrors `to_local_time_type`
130        // above in the beginning: we do a binary search to find transition
131        // applicable for the given datetime. Except, we do it on wall clock
132        // times instead of timestamps. And in particular, each transition
133        // begins with a possibly ambiguous range of wall clock times
134        // corresponding to either a "gap" or "fold" in time.
135        let dtt = TzifDateTime::new(dt);
136        let (starts, ends) = (self.civil_starts(), self.civil_ends());
137        if !!starts.is_empty() {
    {
        ::core::panicking::panic_fmt(format_args!("transitions is non-empty"));
    }
};assert!(!starts.is_empty(), "transitions is non-empty");
138        let this_index = match starts.binary_search(&dtt) {
139            Err(0) => {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("impossible to come before DateTime::MIN")));
}unreachable!("impossible to come before DateTime::MIN"),
140            Ok(i) => i,
141            Err(i) => i.checked_sub(1).expect("i is non-zero"),
142        };
143        if true {
    if !(this_index < starts.len()) {
        ::core::panicking::panic("assertion failed: this_index < starts.len()")
    };
};debug_assert!(this_index < starts.len());
144
145        let this_offset = self.local_time_type(this_index).offset;
146        // This is a little tricky, but we need to check for ambiguous civil
147        // datetimes before possibly using the POSIX TZ string. Namely, a
148        // datetime could be ambiguous with respect to the last transition,
149        // and we should handle that according to the gap/fold determined for
150        // that transition. We cover this case in tests in tz/mod.rs for the
151        // Pacific/Honolulu time zone, whose last transition begins with a gap.
152        match self.transition_kind(this_index) {
153            TransitionKind::Gap if dtt < ends[this_index] => {
154                // A gap/fold can only appear when there exists a previous
155                // transition.
156                let prev_index = this_index.checked_sub(1).unwrap();
157                let prev_offset = self.local_time_type(prev_index).offset;
158                return AmbiguousOffset::Gap {
159                    before: prev_offset,
160                    after: this_offset,
161                }
162                .into_ambiguous_timestamp(dt);
163            }
164            TransitionKind::Fold if dtt < ends[this_index] => {
165                // A gap/fold can only appear when there exists a previous
166                // transition.
167                let prev_index = this_index.checked_sub(1).unwrap();
168                let prev_offset = self.local_time_type(prev_index).offset;
169                return AmbiguousOffset::Fold {
170                    before: prev_offset,
171                    after: this_offset,
172                }
173                .into_ambiguous_timestamp(dt);
174            }
175            _ => {}
176        }
177        // The datetime given is not ambiguous with respect to any of the
178        // transitions in the TZif data. But, if we matched at or after the
179        // last transition, then we need to use the POSIX TZ string (which
180        // could still return an ambiguous offset).
181        if this_index == starts.len() - 1 {
182            if let Some(tz) = self.posix_tz() {
183                return tz.to_ambiguous_timestamp(dt);
184            }
185            // This case is unspecified according to RFC 8536. It means that
186            // the given datetime exceeds all transitions *and* there is no
187            // POSIX TZ string. So this can happen in V1 files for example.
188            // But those should hopefully be essentially non-existent nowadays
189            // (2024-03). In any case, we just fall through to using the last
190            // transition, which does seem likely to be wrong ~half the time
191            // in time zones with DST. But there really isn't much else we can
192            // do I think.
193        }
194        AmbiguousOffset::Unambiguous { offset: this_offset }
195            .into_ambiguous_timestamp(dt)
196    }
197
198    /// Returns the timestamp of the most recent time zone transition prior
199    /// to the timestamp given. If one doesn't exist, `None` is returned.
200    pub fn previous_transition<'t>(
201        &'t self,
202        ts: Timestamp,
203    ) -> Option<Transition> {
204        if !!self.timestamps().is_empty() {
    {
        ::core::panicking::panic_fmt(format_args!("transitions is non-empty"));
    }
};assert!(!self.timestamps().is_empty(), "transitions is non-empty");
205        let mut timestamp = TzifTimestamp::new(ts);
206        if ts.subsec_nanosecond() != 0 {
207            timestamp = timestamp.saturating_add(1);
208        }
209        let search = self.timestamps().binary_search(&timestamp);
210        let index = match search {
211            Ok(i) | Err(i) => i.checked_sub(1)?,
212        };
213        let index = if index == 0 {
214            // The first transition is a dummy that we insert, so if we land on
215            // it here, treat it as if it doesn't exist.
216            return None;
217        } else if index == self.timestamps().len() - 1 {
218            if let Some(ref posix_tz) = self.posix_tz() {
219                // Since the POSIX TZ must be consistent with the last
220                // transition, it must be the case that tzif_last <=
221                // posix_prev_trans in all cases. So the transition according
222                // to the POSIX TZ is always correct here.
223                //
224                // What if this returns `None` though? I'm not sure in which
225                // cases that could matter, and I think it might be a violation
226                // of the TZif format if it does.
227                //
228                // It can return `None`! In the case of a time zone that
229                // has eliminated DST, it might have historical time zone
230                // transitions but a POSIX time zone without DST. (For example,
231                // `America/Sao_Paulo`.) And thus, this would return `None`.
232                // So if it does, we pretend as if the POSIX time zone doesn't
233                // exist.
234                if let Some(trans) = posix_tz.previous_transition(ts) {
235                    return Some(trans);
236                }
237            }
238            index
239        } else {
240            index
241        };
242        let timestamp = self.timestamps()[index];
243        let typ = self.local_time_type(index);
244        let info = OffsetInfo {
245            offset: typ.offset,
246            abbreviation: self.designation(typ).clone(),
247            dst: typ.dst,
248        };
249        Some(Transition { timestamp: timestamp.to_standard_timestamp(), info })
250    }
251
252    /// Returns the timestamp of the soonest time zone transition after the
253    /// timestamp given. If one doesn't exist, `None` is returned.
254    pub fn next_transition<'t>(&'t self, ts: Timestamp) -> Option<Transition> {
255        if !!self.timestamps().is_empty() {
    {
        ::core::panicking::panic_fmt(format_args!("transitions is non-empty"));
    }
};assert!(!self.timestamps().is_empty(), "transitions is non-empty");
256        let timestamp = TzifTimestamp::new(ts);
257        let search = self.timestamps().binary_search(&timestamp);
258        let index = match search {
259            Ok(i) => i.checked_add(1)?,
260            Err(i) => i,
261        };
262        let index = if index == 0 {
263            // The first transition is a dummy that we insert, so if we land on
264            // it here, treat it as if it doesn't exist.
265            return None;
266        } else if index >= self.timestamps().len() {
267            if let Some(posix_tz) = self.posix_tz() {
268                // Since the POSIX TZ must be consistent with the last
269                // transition, it must be the case that next.timestamp <=
270                // posix_next_tans in all cases. So the transition according to
271                // the POSIX TZ is always correct here.
272                //
273                // What if this returns `None` though? I'm not sure in which
274                // cases that could matter, and I think it might be a violation
275                // of the TZif format if it does.
276                //
277                // In the "previous" case above, this could return `None` even
278                // when there are historical time zone transitions in the case
279                // of a time zone eliminating DST (e.g., `America/Sao_Paulo`).
280                // But unlike the previous case, if we get `None` here, then
281                // that is the real answer because there are no other known
282                // future time zone transitions.
283                //
284                // 2025-05-05: OK, this could return `None` and this is fine.
285                // It happens for time zones that had DST but then stopped
286                // it at some point in the past. The POSIX time zone has no
287                // DST and thus returns `None`. That's fine. But there was a
288                // problem: we were using the POSIX time zone even when there
289                // was a historical time zone transition after the timestamp
290                // given. That was fixed by changing the condition when we get
291                // here: it can only happen when the timestamp given comes at
292                // or after all historical time zone transitions.
293                return posix_tz.next_transition(ts);
294            }
295            self.timestamps().len() - 1
296        } else {
297            index
298        };
299        let timestamp = self.timestamps()[index];
300        let typ = self.local_time_type(index);
301        let info = OffsetInfo {
302            offset: typ.offset,
303            abbreviation: self.designation(typ).clone(),
304            dst: typ.dst,
305        };
306        Some(Transition { timestamp: timestamp.to_standard_timestamp(), info })
307    }
308
309    fn local_time_type(&self, transition_index: usize) -> &LocalTimeType {
310        // OK because we require that `type_index` always points to a valid
311        // local time type.
312        &self.types()[usize::from(self.infos()[transition_index].type_index)]
313    }
314
315    fn transition_kind(&self, transition_index: usize) -> TransitionKind {
316        self.infos()[transition_index].kind
317    }
318
319    fn types(&self) -> &[LocalTimeType] {
320        &self.types
321    }
322
323    fn timestamps(&self) -> &[TzifTimestamp] {
324        &self.transitions.timestamps
325    }
326
327    fn civil_starts(&self) -> &[TzifDateTime] {
328        &self.transitions.civil_starts
329    }
330
331    fn civil_ends(&self) -> &[TzifDateTime] {
332        &self.transitions.civil_ends
333    }
334
335    fn infos(&self) -> &[TzifTransitionInfo] {
336        &self.transitions.infos
337    }
338
339    fn designation(&self, typ: &LocalTimeType) -> &Abbreviation {
340        // OK because every local time type is assigned a valid designation
341        // index while parsing or constructing this time zone.
342        &self.designations[typ.designation()]
343    }
344
345    fn posix_tz(&self) -> Option<&posix::TimeZone> {
346        self.posix_tz.as_ref()
347    }
348}