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