Coverage Report

Created: 2026-03-31 07:35

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/rust/registry/src/index.crates.io-1949cf8c6b5b557f/jiff-0.2.23/src/tz/posix.rs
Line
Count
Source
1
/*!
2
Provides a parser for [POSIX's `TZ` environment variable][posix-env].
3
4
NOTE: Sadly, at time of writing, the actual parser is in `src/shared/posix.rs`.
5
This is so it can be shared (via simple code copying) with proc macros like
6
the one found in `jiff-tzdb-static`. The parser populates a "lowest common
7
denominator" data type. In normal use in Jiff, this type is converted into
8
the types defined below. This module still does provide the various time zone
9
operations. Only the parsing is written elsewhere.
10
11
The `TZ` environment variable is most commonly used to set a time zone. For
12
example, `TZ=America/New_York`. But it can also be used to tersely define DST
13
transitions. Moreover, the format is not just used as an environment variable,
14
but is also included at the end of TZif files (version 2 or greater). The IANA
15
Time Zone Database project also [documents the `TZ` variable][iana-env] with
16
a little more commentary.
17
18
Note that we (along with pretty much everyone else) don't strictly follow
19
POSIX here. Namely, `TZ=America/New_York` isn't a POSIX compatible usage,
20
and I believe it technically should be `TZ=:America/New_York`. Nevertheless,
21
apparently some group of people (IANA folks?) decided `TZ=America/New_York`
22
should be fine. From the [IANA `theory.html` documentation][iana-env]:
23
24
> It was recognized that allowing the TZ environment variable to take on values
25
> such as 'America/New_York' might cause "old" programs (that expect TZ to have
26
> a certain form) to operate incorrectly; consideration was given to using
27
> some other environment variable (for example, TIMEZONE) to hold the string
28
> used to generate the TZif file's name. In the end, however, it was decided
29
> to continue using TZ: it is widely used for time zone purposes; separately
30
> maintaining both TZ and TIMEZONE seemed a nuisance; and systems where "new"
31
> forms of TZ might cause problems can simply use legacy TZ values such as
32
> "EST5EDT" which can be used by "new" programs as well as by "old" programs
33
> that assume pre-POSIX TZ values.
34
35
Indeed, even [musl subscribes to this behavior][musl-env]. So that's what we do
36
here too.
37
38
Note that a POSIX time zone like `EST5` corresponds to the UTC offset `-05:00`,
39
and `GMT-4` corresponds to the UTC offset `+04:00`. Yes, it's backwards. How
40
fun.
41
42
# IANA v3+ Support
43
44
While this module and many of its types are directly associated with POSIX,
45
this module also plays a supporting role for `TZ` strings in the IANA TZif
46
binary format for versions 2 and greater. Specifically, for versions 3 and
47
greater, some minor extensions are supported here via `IanaTz::parse`. But
48
using `PosixTz::parse` is limited to parsing what is specified by POSIX.
49
Nevertheless, we generally use `IanaTz::parse` everywhere, even when parsing
50
the `TZ` environment variable. The reason for this is that it seems to be what
51
other programs do in practice (for example, GNU date).
52
53
# `no-std` and `no-alloc` support
54
55
A big part of this module works fine in core-only environments. But because
56
core-only environments provide means of indirection, and embedding a
57
`PosixTimeZone` into a `TimeZone` without indirection would use up a lot of
58
space (and thereby make `Zoned` quite chunky), we provide core-only support
59
principally through a proc macro. Namely, a `PosixTimeZone` can be parsed by
60
the proc macro and then turned into static data.
61
62
POSIX time zone support isn't explicitly provided directly as a public API
63
for core-only environments, but is implicitly supported via TZif. (Since TZif
64
data contains POSIX time zone strings.)
65
66
[posix-env]: https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap08.html#tag_08_03
67
[iana-env]: https://data.iana.org/time-zones/tzdb-2024a/theory.html#functions
68
[musl-env]: https://wiki.musl-libc.org/environment-variables
69
*/
70
71
use core::fmt::Debug;
72
73
use crate::{
74
    civil::DateTime,
75
    error::{tz::posix::Error as E, Error, ErrorContext},
76
    shared,
77
    timestamp::Timestamp,
78
    tz::{
79
        timezone::TimeZoneAbbreviation, AmbiguousOffset, Dst, Offset,
80
        TimeZoneOffsetInfo, TimeZoneTransition,
81
    },
82
    util::{array_str::Abbreviation, parse},
83
};
84
85
/// The result of parsing the POSIX `TZ` environment variable.
86
///
87
/// A `TZ` variable can either be a time zone string with an optional DST
88
/// transition rule, or it can begin with a `:` followed by an arbitrary set of
89
/// bytes that is implementation defined.
90
///
91
/// In practice, the content following a `:` is treated as an IANA time zone
92
/// name. Moreover, even if the `TZ` string doesn't start with a `:` but
93
/// corresponds to a IANA time zone name, then it is interpreted as such.
94
/// (See the module docs.) However, this type only encapsulates the choices
95
/// strictly provided by POSIX: either a time zone string with an optional DST
96
/// transition rule, or an implementation defined string with a `:` prefix. If,
97
/// for example, `TZ="America/New_York"`, then that case isn't encapsulated by
98
/// this type. Callers needing that functionality will need to handle the error
99
/// returned by parsing this type and layer their own semantics on top.
100
#[cfg(feature = "tz-system")]
101
#[derive(Debug, Eq, PartialEq)]
102
pub(crate) enum PosixTzEnv {
103
    /// A valid POSIX time zone with an optional DST transition rule.
104
    Rule(PosixTimeZoneOwned),
105
    /// An implementation defined string. This occurs when the `TZ` value
106
    /// starts with a `:`. The string returned here does not include the `:`.
107
    Implementation(alloc::boxed::Box<str>),
108
}
109
110
#[cfg(feature = "tz-system")]
111
impl PosixTzEnv {
112
    /// Parse a POSIX `TZ` environment variable string from the given bytes.
113
0
    fn parse(bytes: impl AsRef<[u8]>) -> Result<PosixTzEnv, Error> {
114
0
        let bytes = bytes.as_ref();
115
0
        if bytes.get(0) == Some(&b':') {
116
0
            let Ok(string) = core::str::from_utf8(&bytes[1..]) else {
117
0
                return Err(Error::from(E::ColonPrefixInvalidUtf8));
118
            };
119
0
            Ok(PosixTzEnv::Implementation(string.into()))
120
        } else {
121
0
            PosixTimeZone::parse(bytes).map(PosixTzEnv::Rule)
122
        }
123
0
    }
124
125
    /// Parse a POSIX `TZ` environment variable string from the given `OsStr`.
126
0
    pub(crate) fn parse_os_str(
127
0
        osstr: impl AsRef<std::ffi::OsStr>,
128
0
    ) -> Result<PosixTzEnv, Error> {
129
0
        PosixTzEnv::parse(parse::os_str_bytes(osstr.as_ref())?)
130
0
    }
131
}
132
133
#[cfg(feature = "tz-system")]
134
impl core::fmt::Display for PosixTzEnv {
135
0
    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
136
0
        match *self {
137
0
            PosixTzEnv::Rule(ref tz) => core::fmt::Display::fmt(tz, f),
138
0
            PosixTzEnv::Implementation(ref imp) => {
139
0
                f.write_str(":")?;
140
0
                core::fmt::Display::fmt(imp, f)
141
            }
142
        }
143
0
    }
144
}
145
146
/// An owned POSIX time zone.
147
///
148
/// That is, a POSIX time zone whose abbreviations are inlined into the
149
/// representation. As opposed to a static POSIX time zone whose abbreviations
150
/// are `&'static str`.
151
pub(crate) type PosixTimeZoneOwned = PosixTimeZone<Abbreviation>;
152
153
/// An owned POSIX time zone whose abbreviations are `&'static str`.
154
pub(crate) type PosixTimeZoneStatic = PosixTimeZone<&'static str>;
155
156
/// A POSIX time zone.
157
///
158
/// # On "reasonable" POSIX time zones
159
///
160
/// Jiff only supports "reasonable" POSIX time zones. A "reasonable" POSIX time
161
/// zone is a POSIX time zone that has a DST transition rule _when_ it has a
162
/// DST time zone abbreviation. Without the transition rule, it isn't possible
163
/// to know when DST starts and stops.
164
///
165
/// POSIX technically allows a DST time zone abbreviation *without* a
166
/// transition rule, but the behavior is literally unspecified. So Jiff just
167
/// rejects them.
168
///
169
/// Note that if you're confused as to why Jiff accepts `TZ=EST5EDT` (where
170
/// `EST5EDT` is an example of an _unreasonable_ POSIX time zone), that's
171
/// because Jiff rejects `EST5EDT` and instead attempts to use it as an IANA
172
/// time zone identifier. And indeed, the IANA Time Zone Database contains an
173
/// entry for `EST5EDT` (presumably for legacy reasons).
174
///
175
/// Also, we expect `TZ` strings parsed from IANA v2+ formatted `tzfile`s to
176
/// also be reasonable or parsing fails. This also seems to be consistent with
177
/// the [GNU C Library]'s treatment of the `TZ` variable: it only documents
178
/// support for reasonable POSIX time zone strings.
179
///
180
/// Note that a V2 `TZ` string is precisely identical to a POSIX `TZ`
181
/// environment variable string. A V3 `TZ` string however supports signed DST
182
/// transition times, and hours in the range `0..=167`. The V2 and V3 here
183
/// reference how `TZ` strings are defined in the TZif format specified by
184
/// [RFC 9636]. V2 is the original version of it straight from POSIX, where as
185
/// V3+ corresponds to an extension added to V3 (and newer versions) of the
186
/// TZif format. V3 is a superset of V2, so in practice, Jiff just permits
187
/// V3 everywhere.
188
///
189
/// [GNU C Library]: https://www.gnu.org/software/libc/manual/2.25/html_node/TZ-Variable.html
190
/// [RFC 9636]: https://datatracker.ietf.org/doc/rfc9636/
191
#[derive(Clone, Debug, Eq, PartialEq)]
192
// NOT part of Jiff's public API
193
#[doc(hidden)]
194
// This ensures the alignment of this type is always *at least* 8 bytes. This
195
// is required for the pointer tagging inside of `TimeZone` to be sound. At
196
// time of writing (2024-02-24), this explicit `repr` isn't required on 64-bit
197
// systems since the type definition is such that it will have an alignment of
198
// at least 8 bytes anyway. But this *is* required for 32-bit systems, where
199
// the type definition at present only has an alignment of 4 bytes.
200
#[repr(align(8))]
201
pub struct PosixTimeZone<ABBREV> {
202
    inner: shared::PosixTimeZone<ABBREV>,
203
}
204
205
impl PosixTimeZone<Abbreviation> {
206
    /// Parse a IANA tzfile v3+ `TZ` string from the given bytes.
207
    #[cfg(feature = "alloc")]
208
0
    pub(crate) fn parse(
209
0
        bytes: impl AsRef<[u8]>,
210
0
    ) -> Result<PosixTimeZoneOwned, Error> {
211
0
        let bytes = bytes.as_ref();
212
0
        let inner = shared::PosixTimeZone::parse(bytes.as_ref())
213
0
            .map_err(Error::posix_tz)
214
0
            .context(E::InvalidPosixTz)?;
215
0
        Ok(PosixTimeZone { inner })
216
0
    }
Unexecuted instantiation: <jiff::tz::posix::PosixTimeZone<jiff::shared::util::array_str::ArrayStr<30>>>::parse::<&[u8]>
Unexecuted instantiation: <jiff::tz::posix::PosixTimeZone<jiff::shared::util::array_str::ArrayStr<30>>>::parse::<&str>
217
218
    /// Like `parse`, but parses a POSIX TZ string from a prefix of the
219
    /// given input. And remaining input is returned.
220
    #[cfg(feature = "alloc")]
221
0
    pub(crate) fn parse_prefix<'b, B: AsRef<[u8]> + ?Sized + 'b>(
222
0
        bytes: &'b B,
223
0
    ) -> Result<(PosixTimeZoneOwned, &'b [u8]), Error> {
224
0
        let bytes = bytes.as_ref();
225
0
        let (inner, remaining) =
226
0
            shared::PosixTimeZone::parse_prefix(bytes.as_ref())
227
0
                .map_err(Error::posix_tz)
228
0
                .context(E::InvalidPosixTz)?;
229
0
        Ok((PosixTimeZone { inner }, remaining))
230
0
    }
231
232
    /// Converts from the shared-but-internal API for use in proc macros.
233
    #[cfg(feature = "alloc")]
234
0
    pub(crate) fn from_shared_owned(
235
0
        sh: shared::PosixTimeZone<Abbreviation>,
236
0
    ) -> PosixTimeZoneOwned {
237
0
        PosixTimeZone { inner: sh }
238
0
    }
239
}
240
241
impl PosixTimeZone<&'static str> {
242
    /// Converts from the shared-but-internal API for use in proc macros.
243
    ///
244
    /// This works in a `const` context by requiring that the time zone
245
    /// abbreviations are `static` strings. This is used when converting
246
    /// code generated by a proc macro to this Jiff internal type.
247
0
    pub(crate) const fn from_shared_const(
248
0
        sh: shared::PosixTimeZone<&'static str>,
249
0
    ) -> PosixTimeZoneStatic {
250
0
        PosixTimeZone { inner: sh }
251
0
    }
252
}
253
254
impl<ABBREV: AsRef<str> + Debug> PosixTimeZone<ABBREV> {
255
    /// Returns the appropriate time zone offset to use for the given
256
    /// timestamp.
257
    ///
258
    /// If you need information like whether the offset is in DST or not, or
259
    /// the time zone abbreviation, then use `PosixTimeZone::to_offset_info`.
260
    /// But that API may be more expensive to use, so only use it if you need
261
    /// the additional data.
262
0
    pub(crate) fn to_offset(&self, timestamp: Timestamp) -> Offset {
263
0
        Offset::from_ioffset_const(
264
0
            self.inner.to_offset(timestamp.to_itimestamp_const()),
265
        )
266
0
    }
Unexecuted instantiation: <jiff::tz::posix::PosixTimeZone<jiff::shared::util::array_str::ArrayStr<30>>>::to_offset
Unexecuted instantiation: <jiff::tz::posix::PosixTimeZone<&str>>::to_offset
Unexecuted instantiation: <jiff::tz::posix::PosixTimeZone<jiff::shared::util::array_str::ArrayStr<30>>>::to_offset
Unexecuted instantiation: <jiff::tz::posix::PosixTimeZone<&str>>::to_offset
Unexecuted instantiation: <jiff::tz::posix::PosixTimeZone<jiff::shared::util::array_str::ArrayStr<30>>>::to_offset
Unexecuted instantiation: <jiff::tz::posix::PosixTimeZone<&str>>::to_offset
Unexecuted instantiation: <jiff::tz::posix::PosixTimeZone<jiff::shared::util::array_str::ArrayStr<30>>>::to_offset
Unexecuted instantiation: <jiff::tz::posix::PosixTimeZone<&str>>::to_offset
Unexecuted instantiation: <jiff::tz::posix::PosixTimeZone<jiff::shared::util::array_str::ArrayStr<30>>>::to_offset
Unexecuted instantiation: <jiff::tz::posix::PosixTimeZone<&str>>::to_offset
267
268
    /// Returns the appropriate time zone offset to use for the given
269
    /// timestamp.
270
    ///
271
    /// This also includes whether the offset returned should be considered
272
    /// to be "DST" or not, along with the time zone abbreviation (e.g., EST
273
    /// for standard time in New York, and EDT for DST in New York).
274
0
    pub(crate) fn to_offset_info(
275
0
        &self,
276
0
        timestamp: Timestamp,
277
0
    ) -> TimeZoneOffsetInfo<'_> {
278
0
        let (ioff, abbrev, is_dst) =
279
0
            self.inner.to_offset_info(timestamp.to_itimestamp_const());
280
0
        let offset = Offset::from_ioffset_const(ioff);
281
0
        let abbreviation = TimeZoneAbbreviation::Borrowed(abbrev);
282
0
        TimeZoneOffsetInfo { offset, dst: Dst::from(is_dst), abbreviation }
283
0
    }
Unexecuted instantiation: <jiff::tz::posix::PosixTimeZone<jiff::shared::util::array_str::ArrayStr<30>>>::to_offset_info
Unexecuted instantiation: <jiff::tz::posix::PosixTimeZone<&str>>::to_offset_info
284
285
    /// Returns a possibly ambiguous timestamp for the given civil datetime.
286
    ///
287
    /// The given datetime should correspond to the "wall" clock time of what
288
    /// humans use to tell time for this time zone.
289
    ///
290
    /// Note that "ambiguous timestamp" is represented by the possible
291
    /// selection of offsets that could be applied to the given datetime. In
292
    /// general, it is only ambiguous around transitions to-and-from DST. The
293
    /// ambiguity can arise as a "fold" (when a particular wall clock time is
294
    /// repeated) or as a "gap" (when a particular wall clock time is skipped
295
    /// entirely).
296
0
    pub(crate) fn to_ambiguous_kind(&self, dt: DateTime) -> AmbiguousOffset {
297
0
        let iamoff = self.inner.to_ambiguous_kind(dt.to_idatetime_const());
298
0
        AmbiguousOffset::from_iambiguous_offset_const(iamoff)
299
0
    }
Unexecuted instantiation: <jiff::tz::posix::PosixTimeZone<jiff::shared::util::array_str::ArrayStr<30>>>::to_ambiguous_kind
Unexecuted instantiation: <jiff::tz::posix::PosixTimeZone<&str>>::to_ambiguous_kind
Unexecuted instantiation: <jiff::tz::posix::PosixTimeZone<jiff::shared::util::array_str::ArrayStr<30>>>::to_ambiguous_kind
Unexecuted instantiation: <jiff::tz::posix::PosixTimeZone<&str>>::to_ambiguous_kind
Unexecuted instantiation: <jiff::tz::posix::PosixTimeZone<jiff::shared::util::array_str::ArrayStr<30>>>::to_ambiguous_kind
Unexecuted instantiation: <jiff::tz::posix::PosixTimeZone<&str>>::to_ambiguous_kind
Unexecuted instantiation: <jiff::tz::posix::PosixTimeZone<jiff::shared::util::array_str::ArrayStr<30>>>::to_ambiguous_kind
Unexecuted instantiation: <jiff::tz::posix::PosixTimeZone<&str>>::to_ambiguous_kind
Unexecuted instantiation: <jiff::tz::posix::PosixTimeZone<jiff::shared::util::array_str::ArrayStr<30>>>::to_ambiguous_kind
Unexecuted instantiation: <jiff::tz::posix::PosixTimeZone<&str>>::to_ambiguous_kind
300
301
    /// Returns the timestamp of the most recent time zone transition prior
302
    /// to the timestamp given. If one doesn't exist, `None` is returned.
303
0
    pub(crate) fn previous_transition<'t>(
304
0
        &'t self,
305
0
        timestamp: Timestamp,
306
0
    ) -> Option<TimeZoneTransition<'t>> {
307
0
        let (its, ioff, abbrev, is_dst) =
308
0
            self.inner.previous_transition(timestamp.to_itimestamp_const())?;
309
0
        let timestamp = Timestamp::from_itimestamp_const(its);
310
0
        let offset = Offset::from_ioffset_const(ioff);
311
0
        let dst = Dst::from(is_dst);
312
0
        Some(TimeZoneTransition { timestamp, offset, abbrev, dst })
313
0
    }
Unexecuted instantiation: <jiff::tz::posix::PosixTimeZone<jiff::shared::util::array_str::ArrayStr<30>>>::previous_transition
Unexecuted instantiation: <jiff::tz::posix::PosixTimeZone<&str>>::previous_transition
314
315
    /// Returns the timestamp of the soonest time zone transition after the
316
    /// timestamp given. If one doesn't exist, `None` is returned.
317
0
    pub(crate) fn next_transition<'t>(
318
0
        &'t self,
319
0
        timestamp: Timestamp,
320
0
    ) -> Option<TimeZoneTransition<'t>> {
321
0
        let (its, ioff, abbrev, is_dst) =
322
0
            self.inner.next_transition(timestamp.to_itimestamp_const())?;
323
0
        let timestamp = Timestamp::from_itimestamp_const(its);
324
0
        let offset = Offset::from_ioffset_const(ioff);
325
0
        let dst = Dst::from(is_dst);
326
0
        Some(TimeZoneTransition { timestamp, offset, abbrev, dst })
327
0
    }
Unexecuted instantiation: <jiff::tz::posix::PosixTimeZone<jiff::shared::util::array_str::ArrayStr<30>>>::next_transition
Unexecuted instantiation: <jiff::tz::posix::PosixTimeZone<&str>>::next_transition
328
}
329
330
impl<ABBREV: AsRef<str>> core::fmt::Display for PosixTimeZone<ABBREV> {
331
0
    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
332
0
        core::fmt::Display::fmt(&self.inner, f)
333
0
    }
334
}
335
336
// The tests below require parsing which requires alloc.
337
#[cfg(feature = "alloc")]
338
#[cfg(test)]
339
mod tests {
340
    use super::*;
341
342
    #[cfg(feature = "tz-system")]
343
    #[test]
344
    fn parse_posix_tz() {
345
        // We used to parse this and then error when we tried to
346
        // convert to a "reasonable" POSIX time zone with a DST
347
        // transition rule. We never actually used unreasonable POSIX
348
        // time zones and it was complicating the type definitions, so
349
        // now we just reject it outright.
350
        assert!(PosixTzEnv::parse("EST5EDT").is_err());
351
352
        let tz = PosixTzEnv::parse(":EST5EDT").unwrap();
353
        assert_eq!(tz, PosixTzEnv::Implementation("EST5EDT".into()));
354
355
        // We require implementation strings to be UTF-8, because we're
356
        // sensible.
357
        assert!(PosixTzEnv::parse(b":EST5\xFFEDT").is_err());
358
    }
359
}