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