1/*!
2Building blocks for supporting time zones.
3*/
45use crate::{Timestamp, util::SmallStr};
67mod offset;
8pub mod posix;
9pub mod tzif;
1011pub use self::offset::{
12AmbiguousError, AmbiguousOffset, AmbiguousTimestamp, Offset,
13};
1415/// A limit on how much stack space we're willing to use for time zone
16/// abbreviations.
17///
18/// POSIX says this:
19///
20/// > Indicate no less than three, nor more than {TZNAME_MAX}, bytes that are
21/// > the designation for the standard (std) or the alternative (dst -such as
22/// > Daylight Savings Time) timezone.
23///
24/// But it doesn't seem worth the trouble to query `TZNAME_MAX`. Interestingly,
25/// IANA says:
26///
27/// > are 3 or more characters specifying the standard and daylight saving time
28/// > (DST) zone abbreviations
29///
30/// Which implies that IANA thinks there is no limit. But that seems unwise.
31/// Moreover, in practice, it seems like the `date` utility supports fairly
32/// long abbreviations. On my mac (so, BSD `date` as I understand it):
33///
34/// ```text
35/// $ TZ=ZZZ5YYYYYYYYYYYYYYYYYYYYY date
36/// Sun Mar 17 20:05:58 YYYYYYYYYYYYYYYYYYYYY 2024
37/// ```
38///
39/// And on my Linux machine (so, GNU `date`):
40///
41/// ```text
42/// $ TZ=ZZZ5YYYYYYYYYYYYYYYYYYYYY date
43/// Sun Mar 17 08:05:36 PM YYYYYYYYYYYYYYYYYYYYY 2024
44/// ```
45///
46/// I don't know exactly what limit these programs use, but 30 seems good
47/// enough?
48///
49/// Previously, I had been using 255 and stuffing the string in a `Box<str>`.
50/// But as part of work on [#168], I was looking to remove allocation from as
51/// many places as possible. And this was one candidate. But making room on the
52/// stack for 255 byte abbreviations seemed gratuitous. So I picked something
53/// smaller. If we come across an abbreviation bigger than this max, then we'll
54/// error.
55///
56/// In environments with dynamic memory allocation, this maximum is just the
57/// maximum number of bytes we're willing to spend on array-backed storage of
58/// a time zone abbreviation. If we hit anything bigger, we'll use the heap.
59///
60/// In core-only environments, we use a bigger limit as mentioned above.
61/// Anything bigger than this will result in a parse error.
62///
63/// [#168]: https://github.com/BurntSushi/jiff/issues/168
64const TIME_ZONE_ABBREVIATION_MAX: usize = {
65#[cfg(feature = "alloc")]
66{
67// 6 + 1 byte for the length gives us a nice 7 bytes total for the
68 // array.
696
70}
71#[cfg(not(feature = "alloc"))]
72{
73 REASONABLE_ABBREVIATION_MAX
74 }
75};
7677/// When a time zone abbreviation is bigger than this, we give up and error.
78const REASONABLE_ABBREVIATION_MAX: usize = {
79#[cfg(feature = "alloc")]
80{
81// Let this expand to a pretty unreasonable amount.
82 // We could make this even higher, but we should have some
83 // kind of limit.
84255
85}
86#[cfg(not(feature = "alloc"))]
87{
88// We make this the same as the array capacity maximum in environments
89 // with dynamic memory allocation as a conservative choice.
90 //
91 // This seems short, but at time of writing, the maximum possible
92 // abbreviation in the tzdb is 5 bytes.
93 //
94 // Actually, we make this bigger so that an abbreviation can fit a
95 // full offset to second resolution. e.g., `+10:30:25`.
969
97}
98};
99100/// A limit on how much stack space we're willing to use for time zone
101/// identifiers.
102///
103/// As of 2026-07-03, 32 is the length of the longest IANA time zone
104/// identifier. Specifically, `America/Argentina/ComodRivadavia`. Anything
105/// bigger than this will error in core-only environments and spill
106/// over to the heap in all other environments. For environments with
107/// a heap, we set a slightly smaller array to make the total size a
108/// bit smaller (4 words on x86-64 instead of 5). This just means that
109/// `America/Argentina/ComodRivadavia` will spill to the heap, but nothing else
110/// should.
111const TIME_ZONE_ID_MAX: usize = {
112#[cfg(feature = "alloc")]
113{
11430
115}
116#[cfg(not(feature = "alloc"))]
117{
11832
119}
120};
121122/// A type that defines the storage for an IANA time zone identifier.
123pub type TimeZoneId = SmallStr<TIME_ZONE_ID_MAX>;
124125/// A type that defines the storage for a time zone abbreviation.
126///
127/// For an abbreviation whose length is less than or equal to a certain
128/// implementation defined number, it will be stored inline inside an array.
129/// All other cases spill out into the heap. (Unless callers do not have
130/// dynamic memory allocation, in which case, whatever tried to store the
131/// time zone abbreviation will return an error. For example, parsing a POSIX
132/// time zone transition rule will fail in that case.)
133pub type Abbreviation = SmallStr<TIME_ZONE_ABBREVIATION_MAX>;
134135/// A representation a single time zone transition.
136#[derive(#[automatically_derived]impl ::core::clone::Clone for Transition {
#[inline]
#[rustc_trivial_field_reads]
fn clone(&self) -> Self {
Transition {
timestamp: ::core::clone::Clone::clone(&self.timestamp),
info: ::core::clone::Clone::clone(&self.info),
}
}
}Clone, #[automatically_derived]impl ::core::fmt::Debug for Transition {
#[inline]
#[rustc_trivial_field_reads]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field2_finish(f,
"Transition timestamp info", &self.timestamp, &&self.info)
}
}Debug)]
137pub struct Transition {
138 timestamp: Timestamp,
139 info: OffsetInfo,
140}
141142impl Transition {
143/// Returns the timestamp at which this transition began.
144pub fn timestamp(&self) -> Timestamp {
145self.timestamp
146 }
147148/// Returns the offset corresponding to this time zone transition. All
149 /// instants at and following this transition's timestamp (and before the
150 /// next transition's timestamp) need to apply this offset from UTC to get
151 /// the civil or "local" time in the corresponding time zone.
152pub fn offset(&self) -> Offset {
153self.info.offset()
154 }
155156/// Returns the time zone abbreviation corresponding to this time
157 /// zone transition.
158pub fn abbreviation(&self) -> &Abbreviation {
159&self.info.abbreviation()
160 }
161162/// Returns whether daylight saving time is enabled for this time zone
163 /// transition.
164pub fn dst(&self) -> Dst {
165self.info.dst()
166 }
167168/// Consumes this transition and returns the underlying `OffsetInfo`.
169pub fn into_offset_info(self) -> OffsetInfo {
170self.info
171 }
172}
173174/// Information associated with an offset when doing a time zone transition
175/// lookup.
176///
177/// Callers should generally only need the offset. This exposes additional
178/// information such as the time zone abbreviation or whether a timestamp is in
179/// daylight saving time or not.
180#[derive(#[automatically_derived]impl ::core::clone::Clone for OffsetInfo {
#[inline]
#[rustc_trivial_field_reads]
fn clone(&self) -> Self {
OffsetInfo {
offset: ::core::clone::Clone::clone(&self.offset),
abbreviation: ::core::clone::Clone::clone(&self.abbreviation),
dst: ::core::clone::Clone::clone(&self.dst),
}
}
}Clone, #[automatically_derived]impl ::core::fmt::Debug for OffsetInfo {
#[inline]
#[rustc_trivial_field_reads]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field3_finish(f,
"OffsetInfo offset abbreviation dst", &self.offset,
&self.abbreviation, &&self.dst)
}
}Debug, #[automatically_derived]impl ::core::cmp::Eq for OffsetInfo {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<Offset>;
let _: ::core::cmp::AssertParamIsEq<Abbreviation>;
let _: ::core::cmp::AssertParamIsEq<Dst>;
}
}Eq, #[automatically_derived]impl ::core::hash::Hash for OffsetInfo {
#[inline]
fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
::core::hash::Hash::hash(&self.offset, state);
::core::hash::Hash::hash(&self.abbreviation, state);
::core::hash::Hash::hash(&self.dst, state)
}
}Hash, #[automatically_derived]impl ::core::marker::StructuralPartialEq for
OffsetInfo {
}
#[automatically_derived]impl ::core::cmp::PartialEq for OffsetInfo {
#[inline]
fn eq(&self, other: &Self) -> bool {
self.offset == other.offset && self.abbreviation == other.abbreviation
&& self.dst == other.dst
}
}PartialEq)]
181pub struct OffsetInfo {
182 offset: Offset,
183 abbreviation: Abbreviation,
184 dst: Dst,
185}
186187impl OffsetInfo {
188/// Returns the offset corresponding to this time zone transition. All
189 /// instants at and following this transition's timestamp (and before the
190 /// next transition's timestamp) need to apply this offset from UTC to get
191 /// the civil or "local" time in the corresponding time zone.
192pub fn offset(&self) -> Offset {
193self.offset
194 }
195196/// Returns the time zone abbreviation corresponding to this time
197 /// zone transition.
198pub fn abbreviation(&self) -> &Abbreviation {
199&self.abbreviation
200 }
201202/// Consumes this offset info and returns its abbreviation.
203pub fn into_abbreviation(self) -> Abbreviation {
204self.abbreviation
205 }
206207/// Returns whether daylight saving time is enabled for this time zone
208 /// transition.
209pub fn dst(&self) -> Dst {
210self.dst
211 }
212}
213214/// An enum indicating whether a particular datetime is in daylight saving time
215/// (DST) or not.
216#[derive(#[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
for Dst {
}
#[automatically_derived]impl ::core::clone::Clone for Dst {
#[inline]
#[rustc_trivial_field_reads]
fn clone(&self) -> Self { *self }
}Clone, #[automatically_derived]impl ::core::marker::Copy for Dst { }Copy, #[automatically_derived]impl ::core::fmt::Debug for Dst {
#[inline]
#[rustc_trivial_field_reads]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::write_str(f,
match self { Dst::No => "No", Dst::Yes => "Yes", })
}
}Debug, #[automatically_derived]impl ::core::cmp::Eq for Dst { }Eq, #[automatically_derived]impl ::core::hash::Hash for Dst {
#[inline]
fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
::core::hash::Hash::hash(&::core::intrinsics::discriminant_value(self),
state)
}
}Hash, #[automatically_derived]impl ::core::marker::StructuralPartialEq for Dst { }
#[automatically_derived]impl ::core::cmp::PartialEq for Dst {
#[inline]
fn eq(&self, other: &Self) -> bool {
::core::intrinsics::discriminant_value(self) ==
::core::intrinsics::discriminant_value(other)
}
}PartialEq, #[automatically_derived]impl ::core::cmp::PartialOrd for Dst {
#[inline]
fn partial_cmp(&self, other: &Self)
-> ::core::option::Option<::core::cmp::Ordering> {
::core::option::Option::Some(::core::cmp::Ord::cmp(self, other))
}
}PartialOrd, #[automatically_derived]impl ::core::cmp::Ord for Dst {
#[inline]
fn cmp(&self, other: &Self) -> ::core::cmp::Ordering {
::core::cmp::Ord::cmp(&::core::intrinsics::discriminant_value(self),
&::core::intrinsics::discriminant_value(other))
}
}Ord)]
217#[cfg_attr(feature = "defmt", derive(defmt::Format))]
218pub enum Dst {
219/// DST is not in effect. In other words, standard time is in effect.
220No,
221/// DST is in effect.
222Yes,
223}
224225impl Dst {
226/// Returns true when this value is equal to `Dst::Yes`.
227pub fn is_dst(self) -> bool {
228#[allow(non_exhaustive_omitted_patterns)] match self {
Dst::Yes => true,
_ => false,
}matches!(self, Dst::Yes)229 }
230231/// Returns true when this value is equal to `Dst::No`.
232 ///
233 /// `std` in this context refers to "standard time." That is, it is the
234 /// offset from UTC used when DST is not in effect.
235pub fn is_std(self) -> bool {
236#[allow(non_exhaustive_omitted_patterns)] match self {
Dst::No => true,
_ => false,
}matches!(self, Dst::No)237 }
238}
239240impl From<bool> for Dst {
241fn from(is_dst: bool) -> Dst {
242if is_dst { Dst::Yes } else { Dst::No }
243 }
244}
245246/// Creates a new time zone offset in a `const` context from a given number
247/// of hours.
248///
249/// Negative offsets correspond to time zones west of the prime meridian,
250/// while positive offsets correspond to time zones east of the prime
251/// meridian. Equivalently, in all cases, `civil-time - offset = UTC`.
252///
253/// The fallible non-const version of this constructor is
254/// [`Offset::from_hours`].
255///
256/// This is a convenience free function for [`Offset::constant`]. It is
257/// intended to provide a terse syntax for constructing `Offset` values from
258/// a value that is known to be valid.
259///
260/// # Panics
261///
262/// This routine panics when the given number of hours is out of range.
263/// Namely, `hours` must be in the range `-25..=25`.
264///
265/// Similarly, when used in a const context, an out of bounds hour will prevent
266/// your Rust program from compiling.
267///
268/// # Example
269///
270/// ```
271/// use jiff_core::tz::offset;
272///
273/// let o = offset(-5);
274/// assert_eq!(o.seconds(), -18_000);
275/// let o = offset(5);
276/// assert_eq!(o.seconds(), 18_000);
277/// ```
278#[inline]
279pub const fn offset(hours: i8) -> Offset {
280Offset::constant(hours)
281}
282283#[cfg(test)]
284mod tests {
285// Don't bother trying to test this on non-64 bit. It's too annoying to
286 // keep this test updated.
287#[cfg(target_pointer_width = "64")]
288 #[test]
289fn sizes() {
290use super::*;
291292assert_eq!(24, core::mem::size_of::<Abbreviation>());
293294#[cfg(feature = "alloc")]
295assert_eq!(32, core::mem::size_of::<TimeZoneId>());
296#[cfg(not(feature = "alloc"))]
297assert_eq!(40, core::mem::size_of::<TimeZoneId>());
298 }
299}