Skip to main content

predicator_rs/
civil.rs

1//! Civil dates, instants in UTC and durations: small value types with
2//! hand-written arithmetic on the proleptic Gregorian calendar.
3
4use crate::{Error, EvaluationError, Map, Value};
5use core::fmt;
6
7/// Seconds in a civil day; an instant here has no leap seconds.
8const SECONDS_PER_DAY: i64 = 86_400;
9
10/// Microseconds in a second.
11const MICROS_PER_SECOND: u32 = 1_000_000;
12
13/// The days from 1970-01-01 to the given civil date, negative before it.
14/// The year is any `i32`, so no step can overflow an `i64`.
15fn days_from_civil(year: i32, month: u32, day: u32) -> i64 {
16    let year = i64::from(year) - i64::from(month <= 2);
17    let era = year.div_euclid(400);
18    let year_of_era = year.rem_euclid(400);
19    let month_from_march = (i64::from(month) + 9) % 12;
20    let day_of_year = (153 * month_from_march + 2) / 5 + i64::from(day) - 1;
21    let day_of_era = year_of_era * 365 + year_of_era / 4 - year_of_era / 100 + day_of_year;
22    era * 146_097 + day_of_era - 719_468
23}
24
25/// The civil date `days` after 1970-01-01, or `None` when its year is
26/// outside `i32`.
27fn civil_from_days(days: i64) -> Option<Date> {
28    let shifted = days.checked_add(719_468)?;
29    let era = shifted.div_euclid(146_097);
30    let day_of_era = shifted.rem_euclid(146_097);
31    let year_of_era =
32        (day_of_era - day_of_era / 1460 + day_of_era / 36_524 - day_of_era / 146_096) / 365;
33    let day_of_year = day_of_era - (365 * year_of_era + year_of_era / 4 - year_of_era / 100);
34    let month_from_march = (5 * day_of_year + 2) / 153;
35    let day = day_of_year - (153 * month_from_march + 2) / 5 + 1;
36    let month = if month_from_march < 10 {
37        month_from_march + 3
38    } else {
39        month_from_march - 9
40    };
41    let year = era
42        .checked_mul(400)?
43        .checked_add(year_of_era + i64::from(month <= 2))?;
44    Some(Date {
45        year: i32::try_from(year).ok()?,
46        month: u8::try_from(month).ok()?,
47        day: u8::try_from(day).ok()?,
48    })
49}
50
51fn is_leap_year(year: i32) -> bool {
52    year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)
53}
54
55fn days_in_month(year: i32, month: u32) -> u32 {
56    match month {
57        2 if is_leap_year(year) => 29,
58        2 => 28,
59        4 | 6 | 9 | 11 => 30,
60        _ => 31,
61    }
62}
63
64/// A civil date: a year, a month and a day on the proleptic Gregorian
65/// calendar, with no time of day and no zone. Dates order chronologically.
66///
67/// ```
68/// use predicator_rs::Date;
69///
70/// let date = Date::new(2026, 8, 6).unwrap();
71/// assert_eq!((date.year(), date.month(), date.day()), (2026, 8, 6));
72/// assert_eq!(date.to_string(), "2026-08-06");
73/// assert!(Date::new(2026, 2, 29).is_none());
74/// assert!(date < Date::new(2026, 8, 7).unwrap());
75/// ```
76#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
77pub struct Date {
78    year: i32,
79    month: u8,
80    day: u8,
81}
82
83impl Date {
84    /// The date with these parts, or `None` when they name no calendar
85    /// date (a month outside 1 to 12, a day past the month's end).
86    ///
87    /// ```
88    /// use predicator_rs::Date;
89    ///
90    /// assert!(Date::new(2024, 2, 29).is_some());
91    /// assert!(Date::new(2023, 2, 29).is_none());
92    /// assert!(Date::new(2024, 13, 1).is_none());
93    /// ```
94    pub fn new(year: i32, month: u32, day: u32) -> Option<Date> {
95        if !(1..=12).contains(&month) || day == 0 || day > days_in_month(year, month) {
96            return None;
97        }
98        Some(Date {
99            year,
100            month: u8::try_from(month).ok()?,
101            day: u8::try_from(day).ok()?,
102        })
103    }
104
105    /// The year; negative before year 0 (1 BC).
106    ///
107    /// ```
108    /// use predicator_rs::Date;
109    ///
110    /// assert_eq!(Date::new(-5, 1, 1).map(|date| date.year()), Some(-5));
111    /// ```
112    pub fn year(&self) -> i32 {
113        self.year
114    }
115
116    /// The month, 1 to 12.
117    ///
118    /// ```
119    /// use predicator_rs::Date;
120    ///
121    /// assert_eq!(Date::new(2030, 12, 1).map(|date| date.month()), Some(12));
122    /// ```
123    pub fn month(&self) -> u32 {
124        u32::from(self.month)
125    }
126
127    /// The day of the month, from 1.
128    ///
129    /// ```
130    /// use predicator_rs::Date;
131    ///
132    /// assert_eq!(Date::new(2030, 1, 31).map(|date| date.day()), Some(31));
133    /// ```
134    pub fn day(&self) -> u32 {
135        u32::from(self.day)
136    }
137
138    /// The days since 1970-01-01, negative before it.
139    pub(crate) fn days(self) -> i64 {
140        days_from_civil(self.year, self.month(), self.day())
141    }
142
143    /// The date `days` after 1970-01-01 (before it when negative), or
144    /// `None` when its year is outside `i32`.
145    pub(crate) fn from_days(days: i64) -> Option<Date> {
146        civil_from_days(days)
147    }
148
149    /// Reads `YYYY-MM-DD` with a four-digit year, the form the tagged
150    /// encoding carries.
151    pub(crate) fn parse(text: &str) -> Option<Date> {
152        let mut parts = Digits::new(text);
153        let year = parts.number(4)?;
154        parts.literal(b'-')?;
155        let month = parts.number(2)?;
156        parts.literal(b'-')?;
157        let day = parts.number(2)?;
158        parts.end()?;
159        Date::new(i32::try_from(year).ok()?, month, day)
160    }
161}
162
163impl fmt::Display for Date {
164    /// ISO 8601, `YYYY-MM-DD`. A year outside 0 to 9999 is written with as
165    /// many digits as it takes, and a minus sign below 0.
166    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
167        let sign = if self.year < 0 { "-" } else { "" };
168        write!(
169            f,
170            "{sign}{:04}-{:02}-{:02}",
171            self.year.unsigned_abs(),
172            self.month,
173            self.day
174        )
175    }
176}
177
178impl fmt::Debug for Date {
179    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
180        write!(f, "Date({self})")
181    }
182}
183
184/// An instant in UTC to the microsecond. Its date may be any [`Date`], so
185/// years past 9999 (and before 0) are held without overflow. Instants order
186/// chronologically, and two values at the same instant are equal however
187/// they were made.
188///
189/// ```
190/// use predicator_rs::{Date, DateTime};
191///
192/// let date = Date::new(2026, 8, 6).unwrap();
193/// let instant = DateTime::new(date, 12, 0, 0, 500_000).unwrap();
194/// assert_eq!(instant.to_string(), "2026-08-06T12:00:00.500000Z");
195/// assert_eq!(instant.date(), date);
196/// assert_eq!(
197///     DateTime::from_unix(instant.unix_seconds(), 500_000),
198///     Some(instant)
199/// );
200/// assert_eq!(DateTime::from_unix(0, 0).unwrap().to_string(), "1970-01-01T00:00:00Z");
201/// ```
202#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
203pub struct DateTime {
204    date: Date,
205    second_of_day: u32,
206    microsecond: u32,
207}
208
209impl DateTime {
210    /// The instant at a time of day on `date`, or `None` when the hour is
211    /// past 23, the minute or second past 59 or the microsecond past
212    /// 999999.
213    ///
214    /// ```
215    /// use predicator_rs::{Date, DateTime};
216    ///
217    /// let date = Date::new(2030, 1, 15).unwrap();
218    /// let instant = DateTime::new(date, 23, 59, 59, 999_999).unwrap();
219    /// assert_eq!(instant.to_string(), "2030-01-15T23:59:59.999999Z");
220    /// assert!(DateTime::new(date, 24, 0, 0, 0).is_none());
221    /// ```
222    pub fn new(
223        date: Date,
224        hour: u32,
225        minute: u32,
226        second: u32,
227        microsecond: u32,
228    ) -> Option<DateTime> {
229        if hour > 23 || minute > 59 || second > 59 || microsecond >= MICROS_PER_SECOND {
230            return None;
231        }
232        Some(DateTime {
233            date,
234            second_of_day: hour * 3600 + minute * 60 + second,
235            microsecond,
236        })
237    }
238
239    /// The instant `seconds` after 1970-01-01T00:00:00Z (before it when
240    /// negative) and `microsecond` into that second, or `None` when the
241    /// microsecond is past 999999 or the year is outside `i32`.
242    ///
243    /// ```
244    /// use predicator_rs::DateTime;
245    ///
246    /// let instant = DateTime::from_unix(-1, 0).unwrap();
247    /// assert_eq!(instant.to_string(), "1969-12-31T23:59:59Z");
248    /// assert!(DateTime::from_unix(0, 1_000_000).is_none());
249    /// ```
250    pub fn from_unix(seconds: i64, microsecond: u32) -> Option<DateTime> {
251        if microsecond >= MICROS_PER_SECOND {
252            return None;
253        }
254        Some(DateTime {
255            date: civil_from_days(seconds.div_euclid(SECONDS_PER_DAY))?,
256            second_of_day: u32::try_from(seconds.rem_euclid(SECONDS_PER_DAY)).ok()?,
257            microsecond,
258        })
259    }
260
261    /// The whole seconds since 1970-01-01T00:00:00Z, negative before it.
262    ///
263    /// ```
264    /// use predicator_rs::{Date, DateTime};
265    ///
266    /// let date = Date::new(1970, 1, 2).unwrap();
267    /// let instant = DateTime::new(date, 0, 0, 1, 0).unwrap();
268    /// assert_eq!(instant.unix_seconds(), 86_401);
269    /// ```
270    pub fn unix_seconds(&self) -> i64 {
271        self.date.days() * SECONDS_PER_DAY + i64::from(self.second_of_day)
272    }
273
274    /// The microsecond within the second, 0 to 999999.
275    ///
276    /// ```
277    /// use predicator_rs::DateTime;
278    ///
279    /// let instant = DateTime::from_unix(0, 250_000).unwrap();
280    /// assert_eq!(instant.microsecond(), 250_000);
281    /// ```
282    pub fn microsecond(&self) -> u32 {
283        self.microsecond
284    }
285
286    /// The instant's calendar date in UTC.
287    ///
288    /// ```
289    /// use predicator_rs::{Date, DateTime};
290    ///
291    /// let instant = DateTime::from_unix(86_399, 0).unwrap();
292    /// assert_eq!(instant.date(), Date::new(1970, 1, 1).unwrap());
293    /// ```
294    pub fn date(&self) -> Date {
295        self.date
296    }
297
298    /// The hour, 0 to 23.
299    ///
300    /// ```
301    /// use predicator_rs::DateTime;
302    ///
303    /// assert_eq!(DateTime::from_unix(7_200, 0).map(|at| at.hour()), Some(2));
304    /// ```
305    pub fn hour(&self) -> u32 {
306        self.second_of_day / 3600
307    }
308
309    /// The minute, 0 to 59.
310    ///
311    /// ```
312    /// use predicator_rs::DateTime;
313    ///
314    /// assert_eq!(DateTime::from_unix(180, 0).map(|at| at.minute()), Some(3));
315    /// ```
316    pub fn minute(&self) -> u32 {
317        self.second_of_day % 3600 / 60
318    }
319
320    /// The second, 0 to 59.
321    ///
322    /// ```
323    /// use predicator_rs::DateTime;
324    ///
325    /// assert_eq!(DateTime::from_unix(65, 0).map(|at| at.second()), Some(5));
326    /// ```
327    pub fn second(&self) -> u32 {
328        self.second_of_day % 60
329    }
330
331    /// Reads ISO 8601 text as the reference's codec reads it: a four-digit
332    /// year, a `T` or a space before the time, an optional fraction after a
333    /// full stop or a comma (any count of digits, read to the microsecond),
334    /// and an offset of `Z`, `+HH:MM`, `+HHMM` or `+HH` (either sign) read
335    /// as the instant it names. `-00:00` is refused, and so is an instant
336    /// outside the years 0 to 9999 the encoding carries.
337    pub(crate) fn parse(text: &str) -> Option<DateTime> {
338        let mut parts = Digits::new(text);
339        let year = parts.number(4)?;
340        parts.literal(b'-')?;
341        let month = parts.number(2)?;
342        parts.literal(b'-')?;
343        let day = parts.number(2)?;
344        if parts.literal(b'T').is_none() {
345            parts.literal(b' ')?;
346        }
347        let hour = parts.number(2)?;
348        parts.literal(b':')?;
349        let minute = parts.number(2)?;
350        parts.literal(b':')?;
351        let second = parts.number(2)?;
352        let microsecond = match parts.peek() {
353            Some(b'.' | b',') => {
354                parts.skip();
355                parts.fraction()?
356            }
357            _ => 0,
358        };
359        let offset = parts.offset()?;
360        parts.end()?;
361        let date = Date::new(i32::try_from(year).ok()?, month, day)?;
362        let local = DateTime::new(date, hour, minute, second, microsecond)?;
363        let instant = DateTime::from_unix(local.unix_seconds() - offset, microsecond)?;
364        (0..=9999).contains(&instant.date.year).then_some(instant)
365    }
366}
367
368impl fmt::Display for DateTime {
369    /// ISO 8601 in UTC: the fraction left out when the microsecond is zero
370    /// and exactly six digits when it is not.
371    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
372        write!(
373            f,
374            "{}T{:02}:{:02}:{:02}",
375            self.date,
376            self.hour(),
377            self.minute(),
378            self.second()
379        )?;
380        if self.microsecond != 0 {
381            write!(f, ".{:06}", self.microsecond)?;
382        }
383        f.write_str("Z")
384    }
385}
386
387impl fmt::Debug for DateTime {
388    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
389        write!(f, "DateTime({self})")
390    }
391}
392
393/// A duration: the eight units the reference's duration carries, every one
394/// present and zero unless set. A unit may be negative (the difference of
395/// two dates can be). Two durations are equal when every unit is.
396///
397/// Its text, the form `Display` writes, is the duration-literal grammar:
398/// the units largest first, each followed by its suffix (`y`, `mo`, `w`,
399/// `d`, `h`, `m`, `s`, `ms`), a zero unit left out, and `0s` when every
400/// unit is zero. A negative unit is written with its minus sign.
401///
402/// ```
403/// use predicator_rs::Duration;
404///
405/// let duration = Duration { weeks: 2, days: 3, ..Duration::default() };
406/// assert_eq!(duration.to_string(), "2w3d");
407/// assert_eq!(Duration::default().to_string(), "0s");
408/// assert_eq!(Duration { days: -3, ..Duration::default() }.to_string(), "-3d");
409/// ```
410#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
411pub struct Duration {
412    /// Years.
413    pub years: i64,
414    /// Months.
415    pub months: i64,
416    /// Weeks.
417    pub weeks: i64,
418    /// Days.
419    pub days: i64,
420    /// Hours.
421    pub hours: i64,
422    /// Minutes.
423    pub minutes: i64,
424    /// Seconds.
425    pub seconds: i64,
426    /// Milliseconds.
427    pub milliseconds: i64,
428}
429
430impl Duration {
431    /// The units with their names in the tagged encoding, largest first.
432    pub(crate) fn units(&self) -> [(&'static str, &'static str, i64); 8] {
433        [
434            ("years", "y", self.years),
435            ("months", "mo", self.months),
436            ("weeks", "w", self.weeks),
437            ("days", "d", self.days),
438            ("hours", "h", self.hours),
439            ("minutes", "m", self.minutes),
440            ("seconds", "s", self.seconds),
441            ("milliseconds", "ms", self.milliseconds),
442        ]
443    }
444
445    /// The unit named `name` in the tagged encoding, for writing.
446    pub(crate) fn unit_mut(&mut self, name: &str) -> Option<&mut i64> {
447        match name {
448            "years" => Some(&mut self.years),
449            "months" => Some(&mut self.months),
450            "weeks" => Some(&mut self.weeks),
451            "days" => Some(&mut self.days),
452            "hours" => Some(&mut self.hours),
453            "minutes" => Some(&mut self.minutes),
454            "seconds" => Some(&mut self.seconds),
455            "milliseconds" => Some(&mut self.milliseconds),
456            _ => None,
457        }
458    }
459
460    /// The plain map of the eight units, each under its name.
461    pub(crate) fn unit_map(&self) -> Map {
462        self.units()
463            .into_iter()
464            .map(|(name, _, amount)| (name, Value::Integer(amount)))
465            .collect()
466    }
467
468    /// The duration a plain map's unit names spell, read by their string
469    /// names: a unit the map leaves out is 0 and a key that names no unit
470    /// is passed over. `None` when a unit the map holds is not an integer,
471    /// or when one of `required` is left out.
472    pub(crate) fn from_unit_map(map: &Map, required: &[&str]) -> Option<Duration> {
473        if required.iter().any(|name| map.get_str(name).is_none()) {
474            return None;
475        }
476        let mut duration = Duration::default();
477        for (name, _, _) in Duration::default().units() {
478            match map.get_str(name) {
479                None => {}
480                Some(Value::Integer(amount)) => *duration.unit_mut(name)? = *amount,
481                Some(_) => return None,
482            }
483        }
484        Some(duration)
485    }
486
487    /// Reads the duration-literal grammar as the reference's duration
488    /// parser reads it: the whole text is one or more pairs of an amount
489    /// and a unit, the amount `[0-9]+` with an optional fraction
490    /// `\.[0-9]+`, the unit `mo`, `ms`, `y`, `w`, `d`, `h`, `m` or `s`
491    /// (the two-letter units tried first). No sign, no space, no empty
492    /// text. A repeated unit adds to the amount before it. A fraction must
493    /// come to a whole count of milliseconds: the whole part keeps its own
494    /// unit and the rest is spread largest first over days, hours,
495    /// minutes, seconds and milliseconds (a month 30 days, a year 365), so
496    /// `0.5mo` is 15 days. A unit whose amount is outside `i64` is
497    /// [`DurationText::Overflow`].
498    pub(crate) fn parse(text: &str) -> Result<Duration, DurationText> {
499        let mut duration = Duration::default();
500        let mut rest = text.as_bytes();
501        if rest.is_empty() {
502            return Err(DurationText::Malformed);
503        }
504        while !rest.is_empty() {
505            let (whole, after) = digit_run(rest);
506            let (fraction, after) = match after.split_first() {
507                Some((b'.', after)) => match digit_run(after) {
508                    ([], _) => return Err(DurationText::Malformed),
509                    run => run,
510                },
511                _ => (&[][..], after),
512            };
513            if whole.is_empty() {
514                return Err(DurationText::Malformed);
515            }
516            let (unit, after) = duration_unit(after).ok_or(DurationText::Malformed)?;
517            duration.add_component(whole, fraction, unit)?;
518            rest = after;
519        }
520        Ok(duration)
521    }
522
523    /// Adds one `whole.fraction` amount of `unit` (its suffix).
524    fn add_component(
525        &mut self,
526        whole: &[u8],
527        fraction: &[u8],
528        unit: &str,
529    ) -> Result<(), DurationText> {
530        let amount = whole.iter().try_fold(0_i64, |amount, digit| {
531            amount.checked_mul(10)?.checked_add(i64::from(digit - b'0'))
532        });
533        self.add_unit(unit, amount.ok_or(DurationText::Overflow)?)?;
534        // Trailing zeros of a fraction change nothing; past eleven more
535        // digits no unit's milliseconds can clear the denominator.
536        let mut fraction = fraction;
537        while let Some((b'0', head)) = fraction.split_last() {
538            fraction = head;
539        }
540        if fraction.is_empty() {
541            return Ok(());
542        }
543        if fraction.len() > 11 {
544            return Err(DurationText::Malformed);
545        }
546        let numerator = fraction
547            .iter()
548            .fold(0_i128, |sum, digit| sum * 10 + i128::from(digit - b'0'));
549        let denominator = fraction.iter().fold(1_i128, |power, _| power * 10);
550        let total = numerator * unit_milliseconds(unit);
551        if total % denominator != 0 {
552            return Err(DurationText::Malformed);
553        }
554        let mut left = total / denominator;
555        for (suffix, size) in [
556            ("d", 86_400_000),
557            ("h", 3_600_000),
558            ("m", 60_000),
559            ("s", 1_000),
560            ("ms", 1),
561        ] {
562            let count = left / size;
563            left %= size;
564            if count > 0 {
565                self.add_unit(
566                    suffix,
567                    i64::try_from(count).map_err(|_| DurationText::Overflow)?,
568                )?;
569            }
570        }
571        Ok(())
572    }
573
574    /// Adds `amount` to the unit whose suffix is `suffix`.
575    fn add_unit(&mut self, suffix: &str, amount: i64) -> Result<(), DurationText> {
576        let slot = match suffix {
577            "y" => &mut self.years,
578            "mo" => &mut self.months,
579            "w" => &mut self.weeks,
580            "d" => &mut self.days,
581            "h" => &mut self.hours,
582            "m" => &mut self.minutes,
583            "s" => &mut self.seconds,
584            _ => &mut self.milliseconds,
585        };
586        *slot = slot.checked_add(amount).ok_or(DurationText::Overflow)?;
587        Ok(())
588    }
589}
590
591/// Reads a duration from its literal spelling, such as `"3d8h30m"` or
592/// `"1.5s"`: the spelling a `::duration` cast reads and a `::string` cast
593/// writes.
594///
595/// The text is one or more components, each a whole number with an
596/// optional decimal fraction followed by one of the units `y`, `mo`, `w`,
597/// `d`, `h`, `m`, `s` and `ms`, with no whitespace, no sign and no empty
598/// text. A repeated unit adds to the amount before it. A fraction is spread
599/// over whole smaller units (a month 30 days, a year 365), and one that does
600/// not come to a whole number of milliseconds is refused.
601///
602/// A text that does not spell a duration answers an
603/// [`EvaluationError`](crate::EvaluationError) with the reason
604/// `invalid_duration_format`, and one whose unit is outside `i64` the reason
605/// `integer_overflow`.
606///
607/// ```
608/// use predicator_rs::{Duration, parse_duration};
609///
610/// assert_eq!(parse_duration("1h30m")?, Duration { hours: 1, minutes: 30, ..Duration::default() });
611/// assert_eq!(parse_duration("0.5mo")?, Duration { days: 15, ..Duration::default() });
612/// assert_eq!(parse_duration("1d ").unwrap_err().reason(), "invalid_duration_format");
613/// # Ok::<(), predicator_rs::Error>(())
614/// ```
615pub fn parse_duration(text: &str) -> Result<Duration, Error> {
616    Duration::parse(text).map_err(|refused| {
617        match refused {
618            DurationText::Malformed => EvaluationError::new(
619                "invalid_duration_format",
620                format!("Invalid duration format: {text}"),
621            ),
622            DurationText::Overflow => EvaluationError::new(
623                "integer_overflow",
624                format!("the duration {text:?} has a unit outside the 64-bit range"),
625            ),
626        }
627        .into()
628    })
629}
630
631/// Why a text is not a duration.
632#[derive(Debug, Clone, Copy, PartialEq, Eq)]
633pub(crate) enum DurationText {
634    /// The text is not the duration-literal grammar, or a fraction leaves
635    /// less than a millisecond over.
636    Malformed,
637    /// A unit's amount is outside `i64`.
638    Overflow,
639}
640
641/// The leading ASCII digits of `bytes`, and what follows them.
642fn digit_run(bytes: &[u8]) -> (&[u8], &[u8]) {
643    let count = bytes
644        .iter()
645        .take_while(|byte| byte.is_ascii_digit())
646        .count();
647    bytes.split_at_checked(count).unwrap_or((bytes, &[]))
648}
649
650/// The duration unit `bytes` starts with, two-letter units first, and what
651/// follows it.
652fn duration_unit(bytes: &[u8]) -> Option<(&'static str, &[u8])> {
653    for unit in ["mo", "ms", "y", "w", "d", "h", "m", "s"] {
654        if let Some(rest) = bytes.strip_prefix(unit.as_bytes()) {
655            return Some((unit, rest));
656        }
657    }
658    None
659}
660
661/// The milliseconds in one of `unit`, a month 30 days and a year 365.
662fn unit_milliseconds(unit: &str) -> i128 {
663    match unit {
664        "y" => 31_536_000_000,
665        "mo" => 2_592_000_000,
666        "w" => 604_800_000,
667        "d" => 86_400_000,
668        "h" => 3_600_000,
669        "m" => 60_000,
670        "s" => 1_000,
671        _ => 1,
672    }
673}
674
675impl fmt::Display for Duration {
676    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
677        let mut written = false;
678        for (_, suffix, amount) in self.units() {
679            if amount != 0 {
680                write!(f, "{amount}{suffix}")?;
681                written = true;
682            }
683        }
684        if written { Ok(()) } else { f.write_str("0s") }
685    }
686}
687
688/// A reader over ASCII text, one fixed field at a time; every step answers
689/// `None` on text it does not expect.
690struct Digits<'a> {
691    bytes: &'a [u8],
692    at: usize,
693}
694
695impl<'a> Digits<'a> {
696    fn new(text: &'a str) -> Self {
697        Digits {
698            bytes: text.as_bytes(),
699            at: 0,
700        }
701    }
702
703    fn peek(&self) -> Option<u8> {
704        self.bytes.get(self.at).copied()
705    }
706
707    fn skip(&mut self) {
708        self.at += 1;
709    }
710
711    fn digit(&mut self) -> Option<u32> {
712        let byte = self.peek().filter(u8::is_ascii_digit)?;
713        self.skip();
714        Some(u32::from(byte - b'0'))
715    }
716
717    /// Exactly `count` digits, as a number.
718    fn number(&mut self, count: usize) -> Option<u32> {
719        let mut value = 0;
720        for _ in 0..count {
721            value = value * 10 + self.digit()?;
722        }
723        Some(value)
724    }
725
726    fn literal(&mut self, byte: u8) -> Option<()> {
727        (self.peek()? == byte).then(|| self.skip())
728    }
729
730    /// One or more digits of a fraction of a second, as microseconds:
731    /// digits past the sixth are dropped.
732    fn fraction(&mut self) -> Option<u32> {
733        let mut micros = 0;
734        let mut count = 0;
735        while let Some(digit) = self.digit() {
736            if count < 6 {
737                micros = micros * 10 + digit;
738            }
739            count += 1;
740        }
741        if count == 0 {
742            return None;
743        }
744        for _ in count..6 {
745            micros *= 10;
746        }
747        Some(micros)
748    }
749
750    /// An offset from UTC in seconds: `Z`, or a sign, two digits of hours
751    /// and optionally two of minutes, with or without a colon.
752    fn offset(&mut self) -> Option<i64> {
753        let sign = match self.peek()? {
754            b'Z' => {
755                self.skip();
756                return Some(0);
757            }
758            b'+' => 1,
759            b'-' => -1,
760            _ => return None,
761        };
762        self.skip();
763        let hours = self.number(2)?;
764        let colon = self.literal(b':').is_some();
765        let minutes = match self.peek() {
766            Some(byte) if byte.is_ascii_digit() => self.number(2)?,
767            _ if colon => return None,
768            _ => 0,
769        };
770        if hours > 23 || minutes > 59 || (sign < 0 && colon && hours == 0 && minutes == 0) {
771            return None;
772        }
773        Some(sign * i64::from(hours * 3600 + minutes * 60))
774    }
775
776    fn end(&self) -> Option<()> {
777        (self.at == self.bytes.len()).then_some(())
778    }
779}
780
781#[cfg(test)]
782mod tests {
783    use super::*;
784
785    fn date(year: i32, month: u32, day: u32) -> Date {
786        Date::new(year, month, day).unwrap()
787    }
788
789    // Sabotage: with days_in_month giving February 29 days in every year,
790    // this test fails.
791    #[test]
792    fn a_date_is_a_calendar_date() {
793        assert!(Date::new(2024, 2, 29).is_some());
794        assert!(Date::new(2000, 2, 29).is_some());
795        assert!(Date::new(1900, 2, 29).is_none());
796        assert!(Date::new(2023, 2, 29).is_none());
797        assert!(Date::new(2026, 4, 31).is_none());
798        assert!(Date::new(2026, 13, 1).is_none());
799        assert!(Date::new(2026, 0, 1).is_none());
800        assert!(Date::new(2026, 1, 0).is_none());
801        assert_eq!(date(2026, 1, 31).day(), 31);
802    }
803
804    // Sabotage: with civil_from_days's month taken as month_from_march + 2,
805    // this test fails.
806    #[test]
807    fn day_numbers_round_trip_across_eras() {
808        assert_eq!(date(1970, 1, 1).days(), 0);
809        assert_eq!(date(2000, 3, 1).days(), 11_017);
810        assert_eq!(date(1969, 12, 31).days(), -1);
811        for days in [
812            -1_000_000, -719_528, -1, 0, 59, 60, 11_016, 2_932_896, 9_000_000,
813        ] {
814            let back = civil_from_days(days).unwrap();
815            assert_eq!(back.days(), days, "{back:?}");
816        }
817        assert_eq!(civil_from_days(-719_528), Some(date(0, 1, 1)));
818        assert_eq!(civil_from_days(2_932_896), Some(date(9999, 12, 31)));
819        assert_eq!(civil_from_days(i64::MAX), None);
820        let last = date(i32::MAX, 12, 31);
821        assert_eq!(civil_from_days(last.days()), Some(last));
822        assert_eq!(civil_from_days(last.days() + 1), None);
823        let first = date(i32::MIN, 1, 1);
824        assert_eq!(civil_from_days(first.days()), Some(first));
825        assert_eq!(civil_from_days(first.days() - 1), None);
826    }
827
828    // Sabotage: with Date's Display writing the year without zero padding,
829    // this test fails.
830    #[test]
831    fn a_date_writes_and_reads_iso_text() {
832        assert_eq!(date(2026, 8, 6).to_string(), "2026-08-06");
833        assert_eq!(date(7, 1, 2).to_string(), "0007-01-02");
834        assert_eq!(date(12_026, 1, 2).to_string(), "12026-01-02");
835        assert_eq!(date(-1, 1, 2).to_string(), "-0001-01-02");
836        assert_eq!(format!("{:?}", date(2026, 8, 6)), "Date(2026-08-06)");
837        assert_eq!(Date::parse("2026-08-06"), Some(date(2026, 8, 6)));
838        for text in [
839            "2026-8-06",
840            "20260806",
841            "+2026-08-06",
842            "2026-02-30",
843            "2026-08-06 ",
844            "12026-01-01",
845        ] {
846            assert_eq!(Date::parse(text), None, "{text}");
847        }
848    }
849
850    // Sabotage: with DateTime::new accepting an hour of 24, this test fails.
851    #[test]
852    fn an_instant_holds_the_microsecond_and_far_years() {
853        let instant = DateTime::new(date(2026, 8, 9), 10, 30, 0, 500_000).unwrap();
854        assert_eq!(instant.to_string(), "2026-08-09T10:30:00.500000Z");
855        assert_eq!(
856            (instant.hour(), instant.minute(), instant.second()),
857            (10, 30, 0)
858        );
859        assert_eq!(instant.microsecond(), 500_000);
860        assert_eq!(
861            format!("{instant:?}"),
862            "DateTime(2026-08-09T10:30:00.500000Z)"
863        );
864        assert!(DateTime::new(date(2026, 8, 9), 24, 0, 0, 0).is_none());
865        assert!(DateTime::new(date(2026, 8, 9), 0, 60, 0, 0).is_none());
866        assert!(DateTime::new(date(2026, 8, 9), 0, 0, 60, 0).is_none());
867        assert!(DateTime::new(date(2026, 8, 9), 0, 0, 0, 1_000_000).is_none());
868        assert!(DateTime::from_unix(0, 1_000_000).is_none());
869        let before = DateTime::from_unix(-1, 999_999).unwrap();
870        assert_eq!(before.to_string(), "1969-12-31T23:59:59.999999Z");
871        let far = DateTime::new(date(i32::MAX, 12, 31), 23, 59, 59, 999_999).unwrap();
872        assert_eq!(DateTime::from_unix(far.unix_seconds(), 999_999), Some(far));
873        assert!(DateTime::from_unix(far.unix_seconds() + 1, 0).is_none());
874        assert!(DateTime::from_unix(i64::MIN, 0).is_none());
875        assert!(before < DateTime::from_unix(0, 0).unwrap());
876    }
877
878    // Sabotage: with the offset added to the local instant rather than
879    // subtracted, this test fails.
880    #[test]
881    fn an_instant_reads_the_forms_the_reference_reads() {
882        let read = |text: &str| DateTime::parse(text).map(|instant| instant.to_string());
883        assert_eq!(
884            read("2026-08-06T12:00:00Z").as_deref(),
885            Some("2026-08-06T12:00:00Z")
886        );
887        assert_eq!(
888            read("2026-08-06 12:00:00Z").as_deref(),
889            Some("2026-08-06T12:00:00Z")
890        );
891        assert_eq!(
892            read("2026-08-06T12:00:00,5Z").as_deref(),
893            Some("2026-08-06T12:00:00.500000Z")
894        );
895        assert_eq!(
896            read("2026-08-06T12:00:00.1234567Z").as_deref(),
897            Some("2026-08-06T12:00:00.123456Z")
898        );
899        assert_eq!(
900            read("2026-08-06T12:00:00+0130").as_deref(),
901            Some("2026-08-06T10:30:00Z")
902        );
903        assert_eq!(
904            read("2026-08-06T12:00:00+01").as_deref(),
905            Some("2026-08-06T11:00:00Z")
906        );
907        assert_eq!(
908            read("2026-08-06T12:00:00-01:00").as_deref(),
909            Some("2026-08-06T13:00:00Z")
910        );
911        assert_eq!(
912            read("2026-08-06T12:00:00-0000").as_deref(),
913            Some("2026-08-06T12:00:00Z")
914        );
915        for text in [
916            "2026-08-06t12:00:00z",
917            "2026-08-06T12:00:00-00:00",
918            "2026-08-06T12:00:00",
919            "2026-08-06T24:00:00Z",
920            "2026-08-06T12:00:60Z",
921            "2026-08-06T12:00Z",
922            "2026-08-06T12:00:00.Z",
923            "2026-08-06T12:00:00+01:",
924            "2026-08-06T12:00:00+24:00",
925            "2026-08-06T12:00:00Z ",
926            "20260806T120000Z",
927            "9999-12-31T23:30:00-01:00",
928            "0000-01-01T00:30:00+01:00",
929        ] {
930            assert_eq!(read(text), None, "{text}");
931        }
932    }
933
934    // Sabotage: with Duration's Display skipping negative units as the
935    // reference's code does, this test fails.
936    #[test]
937    fn a_duration_writes_its_units_largest_first() {
938        let every = Duration {
939            years: 1,
940            months: 2,
941            weeks: 3,
942            days: 4,
943            hours: 5,
944            minutes: 6,
945            seconds: 7,
946            milliseconds: 8,
947        };
948        assert_eq!(every.to_string(), "1y2mo3w4d5h6m7s8ms");
949        assert_eq!(
950            Duration {
951                seconds: -90,
952                ..Duration::default()
953            }
954            .to_string(),
955            "-90s"
956        );
957        assert_eq!(Duration::default().to_string(), "0s");
958        let mut written = Duration::default();
959        for (name, _, _) in every.units() {
960            *written.unit_mut(name).unwrap() = 1;
961        }
962        assert!(written.units().iter().all(|(_, _, amount)| *amount == 1));
963        assert!(written.unit_mut("fortnights").is_none());
964    }
965
966    /// The duration `text` reads as, its text, or why it is refused.
967    fn read(text: &str) -> String {
968        match Duration::parse(text) {
969            Ok(duration) => format!("{duration:?}"),
970            Err(why) => format!("{why:?}"),
971        }
972    }
973
974    fn of(duration: Duration) -> String {
975        format!("{duration:?}")
976    }
977
978    // Sabotage: with a fraction's remainder truncated to the millisecond
979    // rather than refused, this test fails.
980    #[test]
981    fn a_duration_reads_the_literal_grammar_with_its_fractions() {
982        assert_eq!(
983            read("3d8h30m"),
984            of(Duration {
985                days: 3,
986                hours: 8,
987                minutes: 30,
988                ..Duration::default()
989            })
990        );
991        assert_eq!(
992            read("1mo1ms1m"),
993            of(Duration {
994                months: 1,
995                milliseconds: 1,
996                minutes: 1,
997                ..Duration::default()
998            })
999        );
1000        assert_eq!(
1001            read("1d2d"),
1002            of(Duration {
1003                days: 3,
1004                ..Duration::default()
1005            })
1006        );
1007        assert_eq!(read("0s"), of(Duration::default()));
1008        assert_eq!(
1009            read("1.5s"),
1010            of(Duration {
1011                seconds: 1,
1012                milliseconds: 500,
1013                ..Duration::default()
1014            })
1015        );
1016        assert_eq!(
1017            read("0.5mo"),
1018            of(Duration {
1019                days: 15,
1020                ..Duration::default()
1021            })
1022        );
1023        assert_eq!(
1024            read("0.5y"),
1025            of(Duration {
1026                days: 182,
1027                hours: 12,
1028                ..Duration::default()
1029            })
1030        );
1031        assert_eq!(
1032            read("1.25d0.5d"),
1033            of(Duration {
1034                days: 1,
1035                hours: 18,
1036                ..Duration::default()
1037            })
1038        );
1039        assert_eq!(
1040            read(&format!("2.{}s", "0".repeat(40))),
1041            of(Duration {
1042                seconds: 2,
1043                ..Duration::default()
1044            })
1045        );
1046        assert_eq!(
1047            read("0.00000000001mo"),
1048            "Malformed",
1049            "eleven digits leave less than a millisecond"
1050        );
1051        assert_eq!(
1052            read("0.0009765625mo"),
1053            of(Duration {
1054                minutes: 42,
1055                seconds: 11,
1056                milliseconds: 250,
1057                ..Duration::default()
1058            })
1059        );
1060        for refused in [
1061            "", "0.5ms", "1.s", ".5s", "1", "d", "1d ", " 1d", "-1d", "1x", "1mos", "1d\n", "1D",
1062        ] {
1063            assert_eq!(read(refused), "Malformed", "{refused:?}");
1064        }
1065        assert_eq!(read("9223372036854775808s"), "Overflow");
1066        assert_eq!(read("9223372036854775807d1d"), "Overflow");
1067        assert_eq!(read("9223372036854775807h0.5d"), "Overflow");
1068        assert_eq!(
1069            read("9223372036854775807ms"),
1070            of(Duration {
1071                milliseconds: i64::MAX,
1072                ..Duration::default()
1073            })
1074        );
1075    }
1076
1077    // Sabotage: with parse_duration answering integer_overflow for a
1078    // malformed text, this test fails.
1079    #[test]
1080    fn parse_duration_answers_the_duration_or_names_its_refusal() {
1081        assert_eq!(
1082            parse_duration("3d8h30m"),
1083            Ok(Duration {
1084                days: 3,
1085                hours: 8,
1086                minutes: 30,
1087                ..Duration::default()
1088            })
1089        );
1090        let reason = |text: &str| {
1091            parse_duration(text).map_err(|error| (error.type_name(), error.reason().to_owned()))
1092        };
1093        assert_eq!(
1094            reason(""),
1095            Err(("EvaluationError", "invalid_duration_format".to_owned()))
1096        );
1097        assert_eq!(
1098            reason("0.5ms"),
1099            Err(("EvaluationError", "invalid_duration_format".to_owned()))
1100        );
1101        assert_eq!(
1102            reason("9223372036854775808s"),
1103            Err(("EvaluationError", "integer_overflow".to_owned()))
1104        );
1105    }
1106}