Skip to main content

structured_pkix/
time.rs

1//! The two ways a certificate writes a moment, read into one.
2//!
3//! Both preserve UTC labels, including an inserted second. The form is kept because it is
4//! part of what the certificate says: the profile requires the two-digit form
5//! through 2049 and the four-digit form afterwards, and a report that has to
6//! explain a certificate cannot explain what it did not keep.
7//!
8//! Only the fixed-width form with seconds and `Z` is accepted. The wider
9//! encodings the base standard allows, an offset from local time, minutes
10//! without seconds, a fractional part, all let one moment be written several
11//! ways, and here they would let two documents disagree about when a
12//! certificate expired while both claiming to be the same certificate.
13
14use crate::error::{Error, ErrorCode, Result};
15use crate::temporal::Instant;
16use core::fmt;
17use structured_asn1::{Element, Reader, Tag, universal};
18
19mod xsd10;
20pub use xsd10::Xsd10Label;
21
22/// UTC-qualified relation of a source label to the caller's lossless reading.
23/// This is a temporal fact, not a rule for application acceptance.
24#[derive(Debug, Clone, Copy, PartialEq, Eq)]
25pub enum Relation {
26    /// Source label is strictly before the reading.
27    Before,
28    /// Source label equals the exact reading.
29    At,
30    /// Source label is strictly after the reading.
31    After,
32    /// Supplied UTC facts cannot establish an input label.
33    Uncertain(crate::temporal::Uncertainty),
34}
35
36pub(crate) fn relation_in<W: structured_asn1::memory::Work>(
37    label: Instant,
38    now: crate::temporal::Reading,
39    utc: &crate::temporal::LeapTable<'_>,
40    execution: &W,
41    origin: (&'static str, u64),
42) -> Result<Relation> {
43    let (field, at) = origin;
44    // Two labels, three binary searches each, before calling the table core.
45    let searches = u64::from(usize::BITS - utc.transitions().len().leading_zeros() + 1);
46    execution
47        .charge_work(searches * 6 + 64)
48        .map_err(|reason| Error::resource(reason, field, at))?;
49    for compared in [label, now.start()] {
50        if let Err(reason) = utc.shift(compared, 0) {
51            return Ok(Relation::Uncertain(reason));
52        }
53    }
54    Ok(
55        if label < now.start() || (label == now.start() && now.has_subnanosecond_remainder()) {
56            Relation::Before
57        } else if label == now.start() {
58            Relation::At
59        } else {
60            Relation::After
61        },
62    )
63}
64
65/// Profile calendar conversion with producing-reader admission and location.
66pub(crate) fn read_in(
67    parent: &Reader<'_>,
68    element: &Element<'_>,
69    field: &'static str,
70) -> Result<Time> {
71    // Fixed calendar conversion plus four byte passes includes validation,
72    // digit conversion and the shared GeneralizedTime semantic core.
73    let work = u64::try_from(element.contents().len())
74        .ok()
75        .and_then(|length| length.checked_mul(4))
76        .and_then(|work| work.checked_add(64))
77        .ok_or_else(|| {
78            Error::resource(
79                structured_asn1::memory::MemoryError::WorkExceeded,
80                field,
81                element.span().start,
82            )
83        })?;
84    parent.charge(work).map_err(|error| {
85        Error::new(
86            ErrorCode::Encoding(error.code()),
87            field,
88            element.span().start,
89        )
90    })?;
91    read(element, field)
92}
93
94/// Which form a time was written in.
95#[derive(Debug, Clone, Copy, PartialEq, Eq)]
96pub enum Form {
97    /// Two digits of year, which the profile requires through 2049.
98    Utc,
99    /// Four digits of year, which the profile requires from 2050.
100    Generalized,
101}
102
103/// A moment, and how the certificate wrote it.
104///
105/// Two times are equal when they name the same moment. The form is what the
106/// certificate used to say it, not part of which moment it is.
107#[derive(Debug, Clone, Copy)]
108pub struct Time {
109    instant: Instant,
110    form: Form,
111}
112
113/// Gregorian calendar components of a labelled time, not an elapsed-time proof.
114/// The year uses astronomical numbering (zero denotes 1 BCE); callers of other
115/// calendar contracts must apply their own specified year-numbering convention.
116#[derive(Debug, Clone, Copy, PartialEq, Eq)]
117pub struct Calendar {
118    /// Signed astronomical Gregorian year.
119    pub year: i64,
120    /// Month, one through twelve.
121    pub month: u8,
122    /// Day within the month.
123    pub day: u8,
124    /// Hour, zero through twenty-three.
125    pub hour: u8,
126    /// Minute, zero through fifty-nine.
127    pub minute: u8,
128    /// Labelled second, including sixty for an inserted second.
129    pub second: u8,
130    /// Fractional nanoseconds retained by this `Time` value.
131    pub nanos: u32,
132}
133
134/// The moment `99991231235959Z` names, which the profile uses to say that a
135/// certificate has no well defined expiry rather than that it expires then.
136pub const NO_WELL_DEFINED_EXPIRY: i64 = 253_402_300_799;
137
138impl Time {
139    /// Project the original UTC label into XSD1.0 year numbering.
140    /// This retains second sixty; [`Xsd10Label::at_utc`] performs the separate
141    /// XSD value normalization. It does not change this time's UTC identity.
142    pub fn xsd10_label<W: structured_asn1::memory::Work>(
143        self,
144        execution: &W,
145    ) -> core::result::Result<Xsd10Label, structured_asn1::memory::MemoryError> {
146        let calendar = self.calendar_at_minutes(0, execution)?;
147        Ok(Xsd10Label {
148            year: if calendar.year <= 0 {
149                calendar.year - 1
150            } else {
151                calendar.year
152            },
153            month: calendar.month,
154            day: calendar.day,
155            hour: calendar.hour,
156            minute: calendar.minute,
157            second: calendar.second,
158            nanos: calendar.nanos,
159        })
160    }
161
162    /// Project the original label at a signed calendar offset.
163    /// Offset minutes need not describe a valid wire timezone; this also permits
164    /// inspecting the previous local date of a midnight label without a second
165    /// calendar implementation. No UTC correction history is inferred.
166    /// The same inverse Gregorian core serves [`Self`]'s text rendering.
167    ///
168    /// # Panics
169    /// Only if that private Gregorian core violates its bounded component
170    /// invariants; parsed time labels and any i16-minute offset preserve them.
171    pub fn calendar_at_minutes<W: structured_asn1::memory::Work>(
172        self,
173        minutes: i16,
174        execution: &W,
175    ) -> core::result::Result<Calendar, structured_asn1::memory::MemoryError> {
176        execution.charge_work(64)?;
177        // Parsed Time years are 0000..9999. The complete i16-minute offset
178        // changes this bounded label by less than 23 days, so no i64 overflow.
179        let (year, month, day, hour, minute, second) =
180            civil_from_seconds(self.seconds() + i64::from(minutes) * 60);
181        Ok(Calendar {
182            year,
183            month: u8::try_from(month).expect("Gregorian month"),
184            day: u8::try_from(day).expect("Gregorian day"),
185            hour: u8::try_from(hour).expect("Gregorian hour"),
186            minute: u8::try_from(minute).expect("Gregorian minute"),
187            second: if self.is_leap_second() {
188                60
189            } else {
190                u8::try_from(second).expect("Gregorian second")
191            },
192            nanos: self.instant.nanos(),
193        })
194    }
195
196    /// POSIX label, negative before the epoch. For an inserted second this
197    /// is the preceding ordinary second's label. Use [`Self::instant`] for
198    /// comparisons and [`crate::temporal::LeapTable`] for elapsed arithmetic.
199    #[must_use]
200    pub fn seconds(self) -> i64 {
201        self.instant.seconds()
202    }
203
204    /// The lossless UTC label; parsing does not authenticate its occurrence.
205    #[must_use]
206    pub fn instant(self) -> Instant {
207        self.instant
208    }
209
210    /// Whether the encoded time labels an inserted second.
211    #[must_use]
212    pub fn is_leap_second(self) -> bool {
213        self.instant.is_leap_second()
214    }
215
216    /// Which form the certificate wrote this in.
217    #[must_use]
218    pub fn form(self) -> Form {
219        self.form
220    }
221
222    /// Whether this is the moment the profile uses to mean that no expiry was
223    /// defined. What that means for a verdict is a policy question, and this
224    /// only reports that the certificate said it.
225    #[must_use]
226    pub fn is_no_well_defined_expiry(self) -> bool {
227        self.seconds() == NO_WELL_DEFINED_EXPIRY && !self.is_leap_second()
228    }
229}
230
231impl PartialEq for Time {
232    fn eq(&self, other: &Self) -> bool {
233        self.instant == other.instant
234    }
235}
236
237impl Eq for Time {}
238
239impl PartialOrd for Time {
240    fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
241        Some(self.cmp(other))
242    }
243}
244
245impl Ord for Time {
246    fn cmp(&self, other: &Self) -> core::cmp::Ordering {
247        self.instant.cmp(&other.instant)
248    }
249}
250
251impl fmt::Display for Time {
252    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
253        let (year, month, day, hour, minute, ordinary) = civil_from_seconds(self.seconds());
254        let second = if self.is_leap_second() { 60 } else { ordinary };
255        write!(
256            f,
257            "{year:04}-{month:02}-{day:02}T{hour:02}:{minute:02}:{second:02}Z"
258        )
259    }
260}
261
262/// Reads an element that a schema says is a time.
263///
264/// The tag chooses the form, so a field declared as a choice between the two is
265/// read by handing whichever element was found to this.
266pub(crate) fn read(element: &Element<'_>, field: &'static str) -> Result<Time> {
267    read_as(element, field, Fraction::Absent)
268}
269
270/// Whether a fractional-seconds element may close the value.
271#[derive(Clone, Copy, PartialEq, Eq)]
272pub(crate) enum Fraction {
273    /// The profile writes a certificate's validity dates without one
274    /// (RFC 5280 4.1.2.5.2), and this reader answers with one moment, which
275    /// a fraction would not change.
276    Absent,
277    /// The encoding writes one where there is one to write, with no trailing
278    /// zeros and none at all where it stands for zero (X.690 11.7.3). A
279    /// value preserved inside somebody else's payload is written under that
280    /// rule and not under the profile's narrower one.
281    Written,
282}
283
284/// Reads a time under whichever of the two rules the caller is asking about.
285pub(crate) fn read_as(
286    element: &Element<'_>,
287    field: &'static str,
288    fraction: Fraction,
289) -> Result<Time> {
290    let fail = |code| Error::new(code, field, element.span().start);
291
292    let form = if element.tag() == Tag::primitive(universal::UTC_TIME) {
293        Form::Utc
294    } else if element.tag() == Tag::primitive(universal::GENERALIZED_TIME) {
295        Form::Generalized
296    } else {
297        return Err(fail(ErrorCode::Encoding(
298            structured_asn1::ErrorCode::UnexpectedTag,
299        )));
300    };
301
302    let contents = element.contents();
303    let (year, rest) = match form {
304        Form::Utc => {
305            let (digits, rest) =
306                split(contents, 2).ok_or_else(|| fail(ErrorCode::MalformedTime))?;
307            let two = number(digits).ok_or_else(|| fail(ErrorCode::MalformedTime))?;
308            // The profile's pivot: a two-digit year is read into the window
309            // 1950 to 2049, so a certificate written in 1998 does not become
310            // one written in 2098.
311            (if two >= 50 { 1900 + two } else { 2000 + two }, rest)
312        }
313        Form::Generalized => {
314            // Any year, including one the profile tells issuers to write as a
315            // UTCTime instead. That rule binds the issuer: "CAs conforming to
316            // this profile MUST always encode certificate validity dates
317            // through the year 2049 as UTCTime". The sentence after it binds
318            // this reader the other way: "Conforming applications MUST be
319            // able to process validity dates that are encoded in either
320            // UTCTime or GeneralizedTime" (RFC 5280 4.1.2.5). A date written
321            // in the wrong form still names one moment, unambiguously, and
322            // refusing to read it would leave a person holding a document
323            // this product declined to explain over its issuer's spelling.
324            let (digits, rest) =
325                split(contents, 4).ok_or_else(|| fail(ErrorCode::MalformedTime))?;
326            let four = number(digits).ok_or_else(|| fail(ErrorCode::MalformedTime))?;
327            (four, rest)
328        }
329    };
330
331    let ([month, day, hour, minute, second], tail) =
332        fields_of(rest).ok_or_else(|| fail(ErrorCode::MalformedTime))?;
333
334    // A fraction closes the value where one is written at all: only the wider
335    // form has one, and only where the caller is reading under the encoding's
336    // rule rather than the profile's.
337    let closed = match tail.split_first() {
338        Some((b'.', digits)) if fraction == Fraction::Written && form == Form::Generalized => {
339            // At least one digit, no trailing zero, and the Z after them.
340            matches!(digits.split_last(), Some((b'Z', fraction)) if !fraction.is_empty()
341                && fraction.iter().all(u8::is_ascii_digit)
342                && fraction.last() != Some(&b'0'))
343        }
344        _ => tail == b"Z",
345    };
346    if !closed {
347        return Err(fail(ErrorCode::MalformedTime));
348    }
349
350    if form == Form::Generalized {
351        // X.680 (2021) §46.3 incorporates ISO 8601 time-of-day notation,
352        // including inserted-second labels. X.690 §11.7 restricts spelling,
353        // not UTC occurrence. After the spelling checks above, use the same
354        // calendar/label semantics as the temporal reader; a LeapTable alone
355        // can establish occurrence. UTCTime has its own 00..59 grammar below.
356        // https://www.itu.int/rec/T-REC-X.680-202102-I/en
357        // https://www.itu.int/rec/T-REC-X.690-202102-I/en
358        let instant = crate::temporal::generalized(element, field)?.start();
359        return Ok(Time { instant, form });
360    }
361
362    if !(1..=12).contains(&month) || day < 1 || day > days_in_month(year, month) {
363        return Err(fail(ErrorCode::TimeOutOfRange));
364    }
365    // X.680 (2021) §47.3(b)(2): "ss is seconds (00 to 59)" for UTCTime.
366    // https://www.itu.int/rec/T-REC-X.680-202102-I/en
367    if hour > 23 || minute > 59 || second > 59 {
368        return Err(fail(ErrorCode::TimeOutOfRange));
369    }
370
371    // Every field is bounded by the checks above and the year by its digit
372    // count, so the seconds count is at most the year 9999 in seconds and
373    // nothing here can overflow.
374    let days = days_from_civil(i64::from(year), month, day);
375    let seconds =
376        days * 86_400 + i64::from(hour) * 3_600 + i64::from(minute) * 60 + i64::from(second);
377
378    let instant = Instant::new(seconds, 0).ok_or_else(|| fail(ErrorCode::TimeOutOfRange))?;
379    Ok(Time { instant, form })
380}
381
382/// Useful time syntax under BER, independently of a PKIX validity field.
383/// X.680 (2021) §§46.2–46.3, 47.3; X.690 §8.25. CER/DER §§11.7–11.8
384/// narrow this syntax and are deliberately applied only by the DER reader.
385/// <https://www.itu.int/rec/T-REC-X.680-202102-I/en>
386pub(crate) fn ber_fits(contents: &[u8], generalized: bool) -> bool {
387    let year_width = if generalized { 4 } else { 2 };
388    let Some((year, rest)) = split(contents, year_width) else {
389        return false;
390    };
391    let Some(year) = number(year) else {
392        return false;
393    };
394    let (clock, zone) = match rest
395        .iter()
396        .position(|byte| matches!(byte, b'Z' | b'+' | b'-'))
397    {
398        Some(at) => rest.split_at(at),
399        None => (rest, &[][..]),
400    };
401    if !ber_zone(zone, generalized) {
402        return false;
403    }
404    let digits = match clock.iter().position(|byte| matches!(byte, b'.' | b',')) {
405        Some(at) if generalized => {
406            let (digits, fraction) = clock.split_at(at);
407            if fraction.len() < 2 || !fraction[1..].iter().all(u8::is_ascii_digit) {
408                return false;
409            }
410            digits
411        }
412        Some(_) => return false,
413        None => clock,
414    };
415    let Some(([month, day, hour], tail)) = fields_of(digits) else {
416        return false;
417    };
418    if month == 0 || month > 12 || day == 0 || day > days_in_month(year, month) || hour > 23 {
419        return false;
420    }
421    // UTCTime gives only the low two year digits, not a century pivot. The
422    // cycle check allows February 29 for yy=00 (some possible centuries are
423    // leap years); selecting a century belongs to the interpreting schema.
424    if tail.is_empty() {
425        return generalized;
426    }
427    let Some(([minute], tail)) = fields_of(tail) else {
428        return false;
429    };
430    if minute > 59 {
431        return false;
432    }
433    if tail.is_empty() {
434        return true;
435    }
436    let Some(([second], [])) = fields_of(tail) else {
437        return false;
438    };
439    second <= if generalized { 60 } else { 59 }
440}
441
442fn ber_zone(zone: &[u8], generalized: bool) -> bool {
443    if zone.is_empty() {
444        return generalized;
445    }
446    if zone == b"Z" {
447        return true;
448    }
449    let Some((b'+' | b'-', digits)) = zone.split_first() else {
450        return false;
451    };
452    let Some(([hour], tail)) = fields_of(digits) else {
453        return false;
454    };
455    if hour > 23 {
456        return false;
457    }
458    if tail.is_empty() {
459        return generalized;
460    }
461    matches!(fields_of(tail), Some(([minute], [])) if minute <= 59)
462}
463
464/// Splits off `count` bytes, which must all be digits.
465pub(super) fn split(contents: &[u8], count: usize) -> Option<(&[u8], &[u8])> {
466    let (digits, rest) = contents.split_at_checked(count)?;
467    digits
468        .iter()
469        .all(u8::is_ascii_digit)
470        .then_some((digits, rest))
471}
472
473/// Reads a run of digits already known to be digits.
474pub(super) fn number(digits: &[u8]) -> Option<u32> {
475    digits.iter().try_fold(0u32, |value, digit| {
476        value
477            .checked_mul(10)
478            .and_then(|value| value.checked_add(u32::from(digit - b'0')))
479    })
480}
481
482/// Where a year falls in the four-hundred-year cycle the calendar repeats
483/// on, which is what every question about its length answers to.
484///
485/// The Gregorian calendar comes back to the same shape every four hundred
486/// years: the leap rule is stated in fours, hundreds and four hundreds, and
487/// four hundred years hold a whole number of weeks. So a year of any width
488/// is answered by its last four digits, which is what makes a year too wide
489/// for a counter no less readable than a short one. The sign turns the count
490/// the other way round the cycle.
491fn in_cycle(digits: &str, negative: bool) -> u32 {
492    let counted = digits.as_bytes().iter().fold(0u32, |cycle, digit| {
493        (cycle * 10 + u32::from(digit - b'0')) % 400
494    });
495    if negative {
496        (400 - counted) % 400
497    } else {
498        counted
499    }
500}
501
502/// How many weeks a year is written in: fifty-two, and fifty-three where the
503/// year is the long one.
504///
505/// A year is long where it begins on a Thursday, and where it is a leap year
506/// beginning on a Wednesday (ISO 8601 4.1.4, which the week components of
507/// X.680 Table 7 are written in). Both are said by the day the first of
508/// January falls on, which is what the count below is: the days from the
509/// start of the calendar to that year, over seven.
510fn weeks_in_year(year: u32) -> u32 {
511    let opens = |year: u32| (year + year / 4 - year / 100 + year / 400) % 7;
512    // The second reading needs the year before, which the first year of the
513    // calendar does not have; it opens the calendar rather than continuing
514    // one, so only the first reading applies to it.
515    let long = opens(year) == 4 || year.checked_sub(1).is_some_and(|before| opens(before) == 3);
516    if long { 53 } else { 52 }
517}
518
519fn is_leap(year: u32) -> bool {
520    year.is_multiple_of(4) && (!year.is_multiple_of(100) || year.is_multiple_of(400))
521}
522
523pub(super) fn days_in_month(year: u32, month: u32) -> u32 {
524    match month {
525        1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
526        4 | 6 | 9 | 11 => 30,
527        2 if is_leap(year) => 29,
528        2 => 28,
529        _ => 0,
530    }
531}
532
533/// Days from the epoch to a date, by the shift-the-year-to-March method: with
534/// March first, the four-year, hundred-year and four-hundred-year corrections
535/// all land at the end of the year and the leap day needs no special case.
536///
537/// Every value is bounded by the calendar checks above, so ordinary arithmetic
538/// cannot overflow here.
539pub(super) fn days_from_civil(year: i64, month: u32, day: u32) -> i64 {
540    let month = i64::from(month);
541    let year = if month <= 2 { year - 1 } else { year };
542    let era = if year >= 0 { year } else { year - 399 } / 400;
543    let year_of_era = year - era * 400;
544    let day_of_year = (153 * (month + if month > 2 { -3 } else { 9 }) + 2) / 5 + i64::from(day) - 1;
545    let day_of_era = year_of_era * 365 + year_of_era / 4 - year_of_era / 100 + day_of_year;
546    // 719468 is the number of days from the epoch back to the start of the era
547    // this counts from.
548    era * 146_097 + day_of_era - 719_468
549}
550
551/// The inverse, for rendering. Bounded the same way.
552pub(super) fn civil_from_seconds(seconds: i64) -> (i64, i64, i64, i64, i64, i64) {
553    let days = seconds.div_euclid(86_400);
554    let within = seconds.rem_euclid(86_400);
555
556    let shifted = days + 719_468;
557    let era = if shifted >= 0 {
558        shifted
559    } else {
560        shifted - 146_096
561    } / 146_097;
562    let day_of_era = shifted - era * 146_097;
563    let year_of_era =
564        (day_of_era - day_of_era / 1_460 + day_of_era / 36_524 - day_of_era / 146_096) / 365;
565    let year = year_of_era + era * 400;
566    let day_of_year = day_of_era - (365 * year_of_era + year_of_era / 4 - year_of_era / 100);
567    let shifted_month = (5 * day_of_year + 2) / 153;
568    let day = day_of_year - (153 * shifted_month + 2) / 5 + 1;
569    let month = if shifted_month < 10 {
570        shifted_month + 3
571    } else {
572        shifted_month - 9
573    };
574
575    (
576        if month <= 2 { year + 1 } else { year },
577        month,
578        day,
579        within / 3_600,
580        within / 60 % 60,
581        within % 60,
582    )
583}
584
585/// Which of the types defined in X.680 38.4 a value claims to be, for the
586/// four whose notation is settled enough to hold it to.
587#[derive(Clone, Copy, PartialEq, Eq)]
588pub(crate) enum Defined {
589    /// `DATE`, a year, a month and a day.
590    Date,
591    /// `TIME-OF-DAY`, an hour, a minute and a second.
592    TimeOfDay,
593    /// `DATE-TIME`, the two of them.
594    DateTime,
595    /// `DURATION`, a length of time rather than a moment.
596    Duration,
597    /// `TIME` itself, whose notation is the whole of the interchange format
598    /// and is read here only as the characters it is written from.
599    Any,
600}
601
602/// Whether the contents of one of the newer time types are the notation that
603/// type writes.
604///
605/// The contents are the value notation in UTF-8, with the characters X.690
606/// 8.26 names removed: the hyphens of a date, the colons of a time, the T
607/// between them, the P before a duration. What is left is what this reads.
608/// A value that is not the notation is not a value of the type, and one
609/// preserved for somebody else must not claim a type it does not have.
610pub(crate) fn defined_fits(kind: Defined, contents: &[u8]) -> bool {
611    match kind {
612        Defined::Date => date_fits(contents),
613        Defined::TimeOfDay => time_of_day_fits(contents),
614        Defined::DateTime => contents
615            .split_at_checked(8)
616            .is_some_and(|(date, time)| date_fits(date) && time_of_day_fits(time)),
617        Defined::Duration => duration_fits(contents),
618        Defined::Any => core::str::from_utf8(contents).is_ok_and(any_fits),
619    }
620}
621
622/// The unrestricted type, whose notation is the whole of what the property
623/// settings can choose: a point in time, a duration, an interval of the two,
624/// and any of those repeated (X.680 Table 7).
625///
626/// Written in the extended formats, which keep their separators, and X.690
627/// 8.26.1.2 takes only the quotation marks off, so what arrives here is the
628/// notation as the table writes it.
629fn any_fits(text: &str) -> bool {
630    // Recurrence opens the value: R, how many times if it is not unlimited,
631    // and then the interval it repeats.
632    let interval = match text.strip_prefix('R') {
633        Some(after) => {
634            let count = after.bytes().take_while(u8::is_ascii_digit).count();
635            let (repeats, tail) = after.split_at(count);
636            if repeats.starts_with('0') && repeats.len() > 1 {
637                return false;
638            }
639            let Some(rest) = tail.strip_prefix('/') else {
640                return false;
641            };
642            rest
643        }
644        None => text,
645    };
646    match interval.split_once('/') {
647        // An interval is a start point and an end point, a start point and a
648        // duration, or a duration and an end point (Table 7, "Time
649        // interval"). Two durations name no interval: nothing says when.
650        Some((start, end)) => match (part_fits(start), part_fits(end)) {
651            (Some(starts), Some(ends)) => !(starts == Part::Duration && ends == Part::Duration),
652            _ => false,
653        },
654        None => part_fits(interval).is_some(),
655    }
656}
657
658/// Which of the two an end of an interval, or a value standing alone, is.
659#[derive(Clone, Copy, PartialEq, Eq)]
660enum Part {
661    Point,
662    Duration,
663}
664
665/// Whether one end of a value is a point in time or a length of one.
666fn part_fits(text: &str) -> Option<Part> {
667    if let Some(duration) = text.strip_prefix('P') {
668        return duration_fits(duration.as_bytes()).then_some(Part::Duration);
669    }
670    point_fits(text).then_some(Part::Point)
671}
672
673/// Whether text is a point in time: a date, a time of day, or both with the
674/// T between them, and the zone the value is read in if it carries one.
675fn point_fits(text: &str) -> bool {
676    match text.split_once('T') {
677        Some((date, time)) => date_part_fits(date) && zoned_time_fits(time),
678        // The hours component of a time standing alone is written without
679        // the T (Table 7, "Hours component" with Basic=Time), so what is
680        // left is one or the other.
681        None => date_part_fits(text) || zoned_time_fits(text),
682    }
683}
684
685/// Whether text is a time of day and, where it carries one, the zone it is
686/// read in: the UTC designator, or the difference from it (Table 7, the last
687/// two rows). The zone follows the time and nothing else, so it is looked
688/// for here rather than at the end of the whole point.
689fn zoned_time_fits(text: &str) -> bool {
690    let stated = match text.strip_suffix('Z') {
691        Some(rest) => rest,
692        None => match text.rfind(['+', '-']) {
693            Some(at) if difference_fits(&text[at..]) => &text[..at],
694            _ => text,
695        },
696    };
697    time_part_fits(stated)
698}
699
700/// Whether text is the difference from UTC: a sign, hours, and minutes where
701/// the difference is not a whole number of hours.
702fn difference_fits(text: &str) -> bool {
703    let Some(rest) = text.strip_prefix(['+', '-']) else {
704        return false;
705    };
706    match rest.split_once(':') {
707        Some((hours, minutes)) => {
708            two_digits(hours).is_some_and(|hours| hours <= 23)
709                && two_digits(minutes).is_some_and(|minutes| minutes <= 59)
710        }
711        None => two_digits(rest).is_some_and(|hours| hours <= 23),
712    }
713}
714
715/// Whether text is a date in the extended format: a year, and then a month
716/// and a day, a week and a day of it, or a day of the year (Table 7, the
717/// year, month, week and day components).
718fn date_part_fits(text: &str) -> bool {
719    let signed = text.starts_with(['+', '-']);
720    let rest = if signed { &text[1..] } else { text };
721    let mut parts = rest.split('-');
722    let Some(year) = parts.next() else {
723        return false;
724    };
725    // Four digits, or more where the settings ask for a wider year.
726    if year.len() < 4 || !year.bytes().all(|byte| byte.is_ascii_digit()) {
727        return false;
728    }
729    let Some(next) = parts.next() else {
730        return parts.next().is_none();
731    };
732    // How far the days and the weeks of this year run is the year's to say,
733    // and a year of any width says it: the calendar repeats every four
734    // hundred years, so where in that cycle the year falls is the whole of
735    // the answer.
736    let counted = in_cycle(year, signed);
737    if let Some(week) = next.strip_prefix('W') {
738        // A week, and then which day of it, one digit through seven.
739        let last = weeks_in_year(counted);
740        let weeks = two_digits(week).is_some_and(|week| (1..=last).contains(&week));
741        return weeks
742            && match parts.next() {
743                Some(day) => {
744                    day.len() == 1
745                        && day.bytes().all(|byte| (b'1'..=b'7').contains(&byte))
746                        && parts.next().is_none()
747                }
748                None => true,
749            };
750    }
751    if next.len() == 3 {
752        // The day of the year, which stands in for the month and the day,
753        // and runs to the length of that year.
754        let last = if is_leap(counted) { 366 } else { 365 };
755        return next.bytes().all(|byte| byte.is_ascii_digit())
756            && number(next.as_bytes()).is_some_and(|day| (1..=last).contains(&day))
757            && parts.next().is_none();
758    }
759    let Some(month) = two_digits(next).filter(|month| (1..=12).contains(month)) else {
760        return false;
761    };
762    match parts.next() {
763        Some(day) => {
764            let Some(day) = two_digits(day) else {
765                return false;
766            };
767            // The calendar decides the last day of the month, and the year
768            // decides February.
769            let last = days_in_month(counted, month);
770            day >= 1 && day <= last && parts.next().is_none()
771        }
772        None => true,
773    }
774}
775
776/// Whether text is a time of day in the extended format: hours, and then
777/// minutes and seconds, the last component present carrying a fraction where
778/// the value is written to that accuracy (Table 7).
779fn time_part_fits(text: &str) -> bool {
780    let mut parts = text.split(':');
781    let bounds = [23u32, 59, 60];
782    let mut carried = None;
783    let mut counted = 0usize;
784    let mut ending = false;
785    for (piece, most) in parts.by_ref().zip(bounds) {
786        let (digits, fraction) = match piece.split_once(['.', ',']) {
787            Some((digits, fraction)) => (digits, Some(fraction)),
788            None => (piece, None),
789        };
790        let Some(value) = two_digits(digits) else {
791            return false;
792        };
793        // A fraction says how accurately the value is written, so the
794        // component carrying one is the last (ISO 8601, 4.2.2.4).
795        if let Some(fraction) = fraction {
796            if fraction.is_empty() || !fraction.bytes().all(|byte| byte.is_ascii_digit()) {
797                return false;
798            }
799            carried = Some(counted);
800        }
801        counted += 1;
802        if carried.is_some_and(|at| at + 1 != counted) {
803            return false;
804        }
805        // Midnight at the end of a day is the twenty-fourth hour, which is
806        // the one value past the bounds (Table 7, "Hours component"). It
807        // names one instant rather than an hour a value can sit inside, so
808        // what follows it is zero and nothing carries a fraction: a
809        // fraction of that hour, or of a component after it, is a moment
810        // past the end of the day.
811        if ending && fraction.is_some() {
812            return false;
813        }
814        if counted == 1 && value == 24 {
815            ending = true;
816            if fraction.is_some() {
817                return false;
818            }
819            continue;
820        }
821        if value > most || (ending && value != 0) {
822            return false;
823        }
824    }
825    counted > 0 && parts.next().is_none()
826}
827
828/// Two digits read as a number, which is how every component but the year
829/// and the day of the year is written.
830fn two_digits(text: &str) -> Option<u32> {
831    (text.len() == 2 && text.bytes().all(|byte| byte.is_ascii_digit()))
832        .then(|| number(text.as_bytes()))?
833}
834
835/// Eight digits naming a day of the calendar (`Date=YMD Year=Basic`).
836fn date_fits(contents: &[u8]) -> bool {
837    let Some((year, rest)) = split(contents, 4) else {
838        return false;
839    };
840    let Some(([month, day], [])) = fields_of(rest) else {
841        return false;
842    };
843    let Some(year) = number(year) else {
844        return false;
845    };
846    (1..=12).contains(&month) && day >= 1 && day <= days_in_month(year, month)
847}
848
849/// Six digits naming a time of day (`Time=HMS`).
850fn time_of_day_fits(contents: &[u8]) -> bool {
851    let Some(([hour, minute, second], [])) = fields_of(contents) else {
852        return false;
853    };
854    // Midnight is written at either end of the day, so the hour reaches
855    // twenty-four where the rest of the value is zero (X.680 38.4.2), and
856    // the second reaches sixty because the interchange format writes a leap
857    // second that way.
858    let midnight = hour == 24 && minute == 0 && second == 0;
859    (hour <= 23 || midnight) && minute <= 59 && second <= 60
860}
861
862/// A duration, as X.690 8.26.5 leaves it: the notation without its leading P,
863/// so a count and its designator for each component that is present, largest
864/// first, with the time components after a T.
865fn duration_fits(contents: &[u8]) -> bool {
866    let Ok(text) = core::str::from_utf8(contents) else {
867        return false;
868    };
869    // The week form stands alone: it is one of the three alternatives and
870    // does not mix with the others (X.680 38.3.6.1).
871    if text.ends_with('W') {
872        return components_fit(text, b"W").is_some_and(|weeks| weeks.any);
873    }
874    let (date, time) = match text.split_once('T') {
875        Some((date, time)) => (date, Some(time)),
876        None => (text, None),
877    };
878    // A T with nothing after it names no component.
879    if time.is_some_and(str::is_empty) {
880        return false;
881    }
882    let Some(dated) = components_fit(date, b"YMD") else {
883        return false;
884    };
885    // A fraction ends the duration, so a date part that carries one may not
886    // be followed by a time part either (X.680 38.3.6.13).
887    if dated.fractional && time.is_some() {
888        return false;
889    }
890    let Some(timed) = time.map_or(Some(Components::NONE), |time| components_fit(time, b"HMS"))
891    else {
892        return false;
893    };
894    // Something has to be there: a duration of no components is no length of
895    // time.
896    dated.any || timed.any
897}
898
899/// What a run of designations turned out to be.
900#[derive(Clone, Copy)]
901struct Components {
902    /// Whether there were any at all, which is a form the caller decides
903    /// about rather than a malformation on its own.
904    any: bool,
905    /// Whether the last one carried a fraction, which closes the duration.
906    fractional: bool,
907}
908
909impl Components {
910    const NONE: Self = Self {
911        any: false,
912        fractional: false,
913    };
914}
915
916/// Whether a run is designations in the order given, each designator used at
917/// most once: a count, an optional fraction, and the letter naming the
918/// component (X.680 38.3.6.2 to 38.3.6.13). `None` says the run is not
919/// designations at all.
920fn components_fit(text: &str, order: &[u8]) -> Option<Components> {
921    let mut rest = text.as_bytes();
922    let mut left = order;
923    let mut seen = Components::NONE;
924    while !rest.is_empty() {
925        // The count opens with a zero only where it is the single digit zero
926        // (38.3.6.11), so the accuracy a value is written to is written one
927        // way.
928        let count = rest.iter().take_while(|byte| byte.is_ascii_digit()).count();
929        if count == 0 || (rest[0] == b'0' && count > 1) {
930            return None;
931        }
932        let after = &rest[count..];
933        let (after, fractional) = match after.split_first() {
934            Some((b'.' | b',', tail)) => {
935                let digits = tail.iter().take_while(|byte| byte.is_ascii_digit()).count();
936                if digits == 0 {
937                    return None;
938                }
939                (&tail[digits..], true)
940            }
941            _ => (after, false),
942        };
943        let (designator, tail) = after.split_first()?;
944        let at = left.iter().position(|kind| kind == designator)?;
945        left = &left[at + 1..];
946        // "If a designation contains a fractional part, there shall be no
947        // following designation" (38.3.6.13): the fraction says how
948        // accurately the duration is written, and a component after it
949        // would say something more accurate again.
950        if seen.fractional {
951            return None;
952        }
953        seen = Components {
954            any: true,
955            fractional,
956        };
957        rest = tail;
958    }
959    Some(seen)
960}
961
962/// The two-digit fields at the front of a value, and whatever follows them
963/// for the caller to hold to its own rule.
964pub(super) fn fields_of<const N: usize>(contents: &[u8]) -> Option<([u32; N], &[u8])> {
965    let mut values = [0u32; N];
966    let mut rest = contents;
967    for value in &mut values {
968        let (digits, tail) = split(rest, 2)?;
969        *value = number(digits)?;
970        rest = tail;
971    }
972    Some((values, rest))
973}
974
975#[cfg(test)]
976mod tests;