Skip to main content

time_zone/
rule.rs

1//! The packed POSIX transition rule.
2//!
3//! A POSIX TZ string ends in two rules, for example `M3.5.0,M10.5.0/3`. Each
4//! rule is packed into one 32-bit word, so `size_of::<Rule>() == 4` bytes.
5
6use crate::civil::{SECONDS_PER_DAY, days_from_civil, days_in_month, weekday_from_days};
7use core::fmt;
8
9/// The kind of date that a [`Rule`] selects.
10#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
11pub enum RuleKind {
12    /// `Mm.w.d`: month m, week w (5 means the last), day of the week d
13    /// (0 for Sunday).
14    MonthWeekDay,
15    /// `Jn`: day n of the year, 1 to 365, never counting February 29.
16    JulianNoLeap,
17    /// `n`: day n of the year, 0 to 365, counting February 29 in leap years.
18    ZeroBasedDay,
19}
20
21/// The time of a rule without `/time`: 02:00:00.
22pub(crate) const DEFAULT_RULE_TIME: i32 = 2 * 3600;
23
24/// The largest rule time of POSIX 2024: 167:59:59.
25pub(crate) const MAX_RULE_TIME: i32 = 167 * 3600 + 59 * 60 + 59;
26
27/// Bias of the packed time field. A stored value of 0 means the default time
28/// of a rule without `/time`; any other value is `time + TIME_BIAS`, which
29/// keeps every valid time positive in the 21-bit field and leaves 0 unused.
30const TIME_BIAS: i32 = MAX_RULE_TIME + 1;
31
32/// One transition rule of a POSIX TZ string, for example `M3.5.0/2`.
33///
34/// The value is a `Copy` type of 32 bits (`size_of::<Rule>() == 4`):
35///
36/// - bits 0 to 1: the [`RuleKind`],
37/// - bits 2 to 10: the date, 9 bits. For `Mm.w.d` it is
38///   `((m - 1) * 5 + (w - 1)) * 7 + d`; for `Jn` it is `n - 1`; for `n` it is `n`,
39/// - bits 11 to 31: the time of day, biased by `TIME_BIAS`; 0 means the
40///   default 02:00:00 of a rule without `/time`. The bias covers the POSIX
41///   2024 range of -167 to 167 hours with margin.
42#[repr(transparent)]
43#[derive(Clone, Copy, PartialEq, Eq, Hash)]
44pub struct Rule(u32);
45
46const KIND_MASK: u32 = 0b11;
47const DATE_MASK: u32 = 0b1_1111_1111; // 9 bits, shifted by 2
48
49impl Rule {
50    /// Pack a rule with an explicit time of day in seconds.
51    pub(crate) const fn new(kind: RuleKind, date: u16, time_seconds: i32) -> Self {
52        let kind = match kind {
53            RuleKind::MonthWeekDay => 0,
54            RuleKind::JulianNoLeap => 1,
55            RuleKind::ZeroBasedDay => 2,
56        };
57        let time = (time_seconds + TIME_BIAS) as u32;
58        Rule(kind | ((date as u32) << 2) | (time << 11))
59    }
60
61    /// Pack a rule whose time of day is the default 02:00:00.
62    pub(crate) const fn implicit(kind: RuleKind, date: u16) -> Self {
63        let kind = match kind {
64            RuleKind::MonthWeekDay => 0,
65            RuleKind::JulianNoLeap => 1,
66            RuleKind::ZeroBasedDay => 2,
67        };
68        Rule(kind | ((date as u32) << 2))
69    }
70
71    /// The kind of date this rule selects.
72    pub const fn kind(&self) -> RuleKind {
73        match self.0 & KIND_MASK {
74            0 => RuleKind::MonthWeekDay,
75            1 => RuleKind::JulianNoLeap,
76            _ => RuleKind::ZeroBasedDay,
77        }
78    }
79
80    /// The 9-bit date code, see [`Rule`] for its layout.
81    pub const fn date_code(&self) -> u16 {
82        ((self.0 >> 2) & DATE_MASK) as u16
83    }
84
85    /// The packed time field: 0 for the default time, otherwise the time of
86    /// day biased by [`TIME_BIAS`].
87    const fn time_field(&self) -> u32 {
88        self.0 >> 11
89    }
90
91    /// Whether the rule carries an explicit `/time`.
92    pub const fn has_explicit_time(&self) -> bool {
93        self.time_field() != 0
94    }
95
96    /// The time of day of the transition in seconds, signed. POSIX 2024 allows
97    /// -167 to 167 hours. A rule without `/time` returns the default 02:00:00.
98    pub const fn time_seconds(&self) -> i32 {
99        let field = self.time_field();
100        if field == 0 {
101            DEFAULT_RULE_TIME
102        } else {
103            field as i32 - TIME_BIAS
104        }
105    }
106
107    /// The month of an `Mm.w.d` rule, 1 to 12.
108    pub const fn month(&self) -> u8 {
109        (self.date_code() / 35 + 1) as u8
110    }
111
112    /// The week of an `Mm.w.d` rule, 1 to 5, where 5 means the last.
113    pub const fn week(&self) -> u8 {
114        (self.date_code() % 35 / 7 + 1) as u8
115    }
116
117    /// The day of the week of an `Mm.w.d` rule, 0 for Sunday.
118    pub const fn weekday(&self) -> u8 {
119        (self.date_code() % 7) as u8
120    }
121
122    /// The day of the year of a `Jn` rule, 1 to 365.
123    pub const fn julian_day(&self) -> u16 {
124        self.date_code() + 1
125    }
126
127    /// The day of the year of an `n` rule, 0 to 365.
128    pub const fn zero_based_day(&self) -> u16 {
129        self.date_code()
130    }
131
132    /// The day count from 1970-01-01 of the midnight that this rule selects in
133    /// the given year.
134    pub(crate) fn day_count(&self, year: i64) -> i64 {
135        match self.kind() {
136            RuleKind::MonthWeekDay => {
137                let month = i64::from(self.month());
138                let first = days_from_civil(year, month as u8, 1);
139                let first_weekday = i64::from(weekday_from_days(first));
140                let weekday = i64::from(self.weekday());
141                let week = i64::from(self.week());
142                let mut day_of_month = 1 + (weekday - first_weekday).rem_euclid(7) + (week - 1) * 7;
143                let days_in_month = i64::from(days_in_month(year, month as u8));
144                while day_of_month > days_in_month {
145                    day_of_month -= 7;
146                }
147                days_from_civil(year, month as u8, day_of_month as u8)
148            }
149            RuleKind::JulianNoLeap => {
150                // February 29 is never counted: days after it shift by one in
151                // leap years.
152                let day = i64::from(self.julian_day());
153                let mut day_of_year = day - 1;
154                if crate::civil::is_leap_year(year) && day >= 60 {
155                    day_of_year += 1;
156                }
157                days_from_civil(year, 1, 1) + day_of_year
158            }
159            RuleKind::ZeroBasedDay => {
160                days_from_civil(year, 1, 1) + i64::from(self.zero_based_day())
161            }
162        }
163    }
164
165    /// Seconds since the Unix epoch of the transition instant read in local
166    /// rule time (the caller applies the offset that is in effect before the
167    /// transition).
168    pub(crate) fn local_seconds(&self, year: i64) -> i128 {
169        // Computed in `i128` with multiply only (no division, which would
170        // pull large helper routines into small targets) so that transition
171        // instants near the ends of the `i64` second range stay exact.
172        i128::from(self.day_count(year)) * i128::from(SECONDS_PER_DAY)
173            + i128::from(self.time_seconds())
174    }
175}
176
177impl fmt::Debug for Rule {
178    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
179        match self.kind() {
180            RuleKind::MonthWeekDay => {
181                write!(f, "M{}.{}.{}", self.month(), self.week(), self.weekday())?
182            }
183            RuleKind::JulianNoLeap => write!(f, "J{}", self.julian_day())?,
184            RuleKind::ZeroBasedDay => write!(f, "{}", self.zero_based_day())?,
185        }
186        if self.has_explicit_time() {
187            write!(f, "/")?;
188            let seconds = self.time_seconds();
189            if seconds < 0 {
190                write!(f, "-")?;
191            }
192            let absolute = seconds.abs();
193            let hours = absolute / 3600;
194            let minutes = (absolute % 3600) / 60;
195            let rest = absolute % 60;
196            if rest != 0 {
197                write!(f, "{hours}:{minutes:02}:{rest:02}")?;
198            } else if minutes != 0 {
199                write!(f, "{hours}:{minutes:02}")?;
200            } else {
201                write!(f, "{hours}")?;
202            }
203        }
204        Ok(())
205    }
206}
207
208#[cfg(test)]
209mod tests {
210    use super::*;
211
212    #[test]
213    fn rule_is_32_bits() {
214        assert_eq!(core::mem::size_of::<Rule>(), 4);
215        assert_eq!(core::mem::align_of::<Rule>(), 4);
216    }
217
218    #[test]
219    fn pack_and_unpack_round_trip() {
220        for (kind, date, time) in [
221            (RuleKind::MonthWeekDay, 419, 7200),
222            (RuleKind::MonthWeekDay, 0, -MAX_RULE_TIME),
223            (RuleKind::MonthWeekDay, 209, MAX_RULE_TIME),
224            (RuleKind::JulianNoLeap, 364, -1),
225            (RuleKind::ZeroBasedDay, 365, 25 * 3600),
226        ] {
227            let rule = Rule::new(kind, date, time);
228            assert_eq!(rule.kind(), kind);
229            assert_eq!(rule.date_code(), date);
230            assert_eq!(rule.time_seconds(), time);
231            assert!(rule.has_explicit_time());
232        }
233    }
234
235    #[test]
236    fn implicit_time_is_the_default() {
237        let rule = Rule::implicit(RuleKind::MonthWeekDay, 77);
238        assert_eq!(rule.time_seconds(), DEFAULT_RULE_TIME);
239        assert!(!rule.has_explicit_time());
240        // An explicit /2 is kept apart from the default.
241        let explicit = Rule::new(RuleKind::MonthWeekDay, 77, DEFAULT_RULE_TIME);
242        assert!(explicit.has_explicit_time());
243        assert_eq!(explicit.time_seconds(), DEFAULT_RULE_TIME);
244    }
245
246    #[test]
247    fn debug_prints_the_posix_form() {
248        let rule = Rule::new(
249            RuleKind::MonthWeekDay,
250            ((3 - 1) * 5 + (5 - 1)) * 7,
251            3 * 3600,
252        );
253        assert_eq!(std::format!("{rule:?}"), "M3.5.0/3");
254        let rule = Rule::new(
255            RuleKind::MonthWeekDay,
256            ((3 - 1) * 5 + (5 - 1)) * 7,
257            2 * 3600,
258        );
259        assert_eq!(std::format!("{rule:?}"), "M3.5.0/2");
260        let rule = Rule::implicit(RuleKind::MonthWeekDay, ((3 - 1) * 5 + (5 - 1)) * 7);
261        assert_eq!(std::format!("{rule:?}"), "M3.5.0");
262        let rule = Rule::new(
263            RuleKind::MonthWeekDay,
264            ((3 - 1) * 5 + (4 - 1)) * 7 + 4,
265            2 * 3600 + 45 * 60,
266        );
267        assert_eq!(std::format!("{rule:?}"), "M3.4.4/2:45");
268        let rule = Rule::new(
269            RuleKind::MonthWeekDay,
270            ((3 - 1) * 5 + (4 - 1)) * 7 + 4,
271            26 * 3600,
272        );
273        assert_eq!(std::format!("{rule:?}"), "M3.4.4/26");
274        let rule = Rule::new(RuleKind::MonthWeekDay, ((3 - 1) * 5 + (5 - 1)) * 7, -3600);
275        assert_eq!(std::format!("{rule:?}"), "M3.5.0/-1");
276        let rule = Rule::new(RuleKind::MonthWeekDay, ((3 - 1) * 5 + (5 - 1)) * 7, 0);
277        assert_eq!(std::format!("{rule:?}"), "M3.5.0/0");
278        let rule = Rule::new(RuleKind::JulianNoLeap, 364, 25 * 3600);
279        assert_eq!(std::format!("{rule:?}"), "J365/25");
280        let rule = Rule::new(RuleKind::ZeroBasedDay, 0, 0);
281        assert_eq!(std::format!("{rule:?}"), "0/0");
282    }
283
284    #[test]
285    fn month_week_day_dates() {
286        // Last Sunday of March 2024 is March 31.
287        let rule = Rule::new(RuleKind::MonthWeekDay, ((3 - 1) * 5 + (5 - 1)) * 7, 7200);
288        let (year, month, day) = crate::civil::civil_from_days(rule.day_count(2024));
289        assert_eq!((year, month, day), (2024, 3, 31));
290        // First Sunday of October 2024 is October 6.
291        let rule = Rule::new(RuleKind::MonthWeekDay, (10 - 1) * 5 * 7, 7200);
292        let (year, month, day) = crate::civil::civil_from_days(rule.day_count(2024));
293        assert_eq!((year, month, day), (2024, 10, 6));
294        // Week 5 clamps to the last occurrence: last Saturday of September 2024
295        // is September 28.
296        let rule = Rule::new(RuleKind::MonthWeekDay, ((9 - 1) * 5 + (5 - 1)) * 7 + 6, 0);
297        let (year, month, day) = crate::civil::civil_from_days(rule.day_count(2024));
298        assert_eq!((year, month, day), (2024, 9, 28));
299    }
300
301    #[test]
302    fn julian_rules_skip_february_29() {
303        // J59 is February 28 in every year, because leap days are not counted.
304        let rule = Rule::new(RuleKind::JulianNoLeap, 58, 0); // J59
305        let (year, month, day) = crate::civil::civil_from_days(rule.day_count(2024));
306        assert_eq!((year, month, day), (2024, 2, 28));
307        let (year, month, day) = crate::civil::civil_from_days(rule.day_count(2023));
308        assert_eq!((year, month, day), (2023, 2, 28));
309        // J60 is March 1 in every year.
310        let rule = Rule::new(RuleKind::JulianNoLeap, 59, 0); // J60
311        let (year, month, day) = crate::civil::civil_from_days(rule.day_count(2024));
312        assert_eq!((year, month, day), (2024, 3, 1));
313        let (year, month, day) = crate::civil::civil_from_days(rule.day_count(2023));
314        assert_eq!((year, month, day), (2023, 3, 1));
315        // Zero based day 59 is February 29 in a leap year and March 1 otherwise.
316        let rule = Rule::new(RuleKind::ZeroBasedDay, 59, 0);
317        let (year, month, day) = crate::civil::civil_from_days(rule.day_count(2024));
318        assert_eq!((year, month, day), (2024, 2, 29));
319        let (year, month, day) = crate::civil::civil_from_days(rule.day_count(2023));
320        assert_eq!((year, month, day), (2023, 3, 1));
321    }
322}