Skip to main content

einvoice_xsd/
datatypes.rs

1//! The built-in simple types of XML Schema 1.0 (Second Edition, Part 2): whitespace
2//! processing and lexical spaces. Every primitive and derived built-in datatype is here;
3//! the schemas use some of them, and a document can name any of them in `xsi:type`.
4//!
5//! Each check works on the value after whitespace processing (the `whiteSpace` facet
6//! of the type: `preserve` for `string`, `replace` for `normalizedString`, `collapse`
7//! for every other type here). Where a value is valid only in a context (an `xs:QName`
8//! whose prefix must be declared, an `xs:IDREF` that must match an `xs:ID` of the
9//! document, an `xs:ENTITY` that must name an unparsed entity, an `xs:NOTATION` that
10//! must name a notation of the schema), the lexical check is here and the validation
11//! checks the rest.
12
13use crate::uri;
14
15/// A built-in simple type this crate implements.
16#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
17pub enum Builtin {
18    /// `xs:anySimpleType`: any string.
19    AnySimpleType,
20    /// `xs:string`.
21    String,
22    /// `xs:normalizedString`.
23    NormalizedString,
24    /// `xs:token`.
25    Token,
26    /// `xs:language`.
27    Language,
28    /// `xs:Name`.
29    Name,
30    /// `xs:NCName`.
31    NcName,
32    /// `xs:ID`: an `NCName`, unique within the document when it types an attribute.
33    Id,
34    /// `xs:decimal`, any number of digits.
35    Decimal,
36    /// `xs:integer`, any number of digits.
37    Integer,
38    /// `xs:boolean`.
39    Boolean,
40    /// `xs:date`.
41    Date,
42    /// `xs:dateTime`.
43    DateTime,
44    /// `xs:time`.
45    Time,
46    /// `xs:base64Binary`.
47    Base64Binary,
48    /// `xs:anyURI`.
49    AnyUri,
50    /// `xs:IDREF`: an `NCName`, which must be the value of an `xs:ID` of the document.
51    IdRef,
52    /// `xs:ENTITY`: an `NCName`, which must be the name of an unparsed entity of the
53    /// document type declaration.
54    Entity,
55    /// `xs:NMTOKEN`.
56    NmToken,
57    /// `xs:nonPositiveInteger`.
58    NonPositiveInteger,
59    /// `xs:negativeInteger`.
60    NegativeInteger,
61    /// `xs:long`: from -2^63 to 2^63 - 1.
62    Long,
63    /// `xs:int`: from -2^31 to 2^31 - 1.
64    Int,
65    /// `xs:short`: from -2^15 to 2^15 - 1.
66    Short,
67    /// `xs:byte`: from -128 to 127.
68    Byte,
69    /// `xs:nonNegativeInteger`.
70    NonNegativeInteger,
71    /// `xs:unsignedLong`: from 0 to 2^64 - 1.
72    UnsignedLong,
73    /// `xs:unsignedInt`: from 0 to 2^32 - 1.
74    UnsignedInt,
75    /// `xs:unsignedShort`: from 0 to 65535.
76    UnsignedShort,
77    /// `xs:unsignedByte`: from 0 to 255.
78    UnsignedByte,
79    /// `xs:positiveInteger`.
80    PositiveInteger,
81    /// `xs:float`.
82    Float,
83    /// `xs:double`.
84    Double,
85    /// `xs:duration`.
86    Duration,
87    /// `xs:gYearMonth`.
88    GYearMonth,
89    /// `xs:gYear`.
90    GYear,
91    /// `xs:gMonthDay`.
92    GMonthDay,
93    /// `xs:gDay`.
94    GDay,
95    /// `xs:gMonth`.
96    GMonth,
97    /// `xs:hexBinary`.
98    HexBinary,
99    /// `xs:QName`: its prefix, if any, must be declared where the value is.
100    QName,
101    /// `xs:NOTATION`: a `QName` naming a notation declared in the schema.
102    Notation,
103    /// `xs:NMTOKENS`: a list of one or more `NMTOKEN`.
104    NmTokens,
105    /// `xs:IDREFS`: a list of one or more `IDREF`.
106    IdRefs,
107    /// `xs:ENTITIES`: a list of one or more `ENTITY`.
108    Entities,
109}
110
111/// The `whiteSpace` facet.
112#[derive(Debug, Clone, Copy, PartialEq, Eq)]
113pub(crate) enum WhiteSpace {
114    Preserve,
115    Replace,
116    Collapse,
117}
118
119impl Builtin {
120    /// Every built-in simple type, base types before the types derived from them.
121    pub(crate) const ALL: [Self; 45] = [
122        Self::AnySimpleType,
123        Self::String,
124        Self::NormalizedString,
125        Self::Token,
126        Self::Language,
127        Self::Name,
128        Self::NcName,
129        Self::Id,
130        Self::Decimal,
131        Self::Integer,
132        Self::Boolean,
133        Self::Date,
134        Self::DateTime,
135        Self::Time,
136        Self::Base64Binary,
137        Self::AnyUri,
138        Self::IdRef,
139        Self::Entity,
140        Self::NmToken,
141        Self::NonPositiveInteger,
142        Self::NegativeInteger,
143        Self::Long,
144        Self::Int,
145        Self::Short,
146        Self::Byte,
147        Self::NonNegativeInteger,
148        Self::UnsignedLong,
149        Self::UnsignedInt,
150        Self::UnsignedShort,
151        Self::UnsignedByte,
152        Self::PositiveInteger,
153        Self::Float,
154        Self::Double,
155        Self::Duration,
156        Self::GYearMonth,
157        Self::GYear,
158        Self::GMonthDay,
159        Self::GDay,
160        Self::GMonth,
161        Self::HexBinary,
162        Self::QName,
163        Self::Notation,
164        Self::NmTokens,
165        Self::IdRefs,
166        Self::Entities,
167    ];
168
169    /// The local name in the XML Schema namespace.
170    #[must_use]
171    pub fn name(self) -> &'static str {
172        match self {
173            Self::AnySimpleType => "anySimpleType",
174            Self::String => "string",
175            Self::NormalizedString => "normalizedString",
176            Self::Token => "token",
177            Self::Language => "language",
178            Self::Name => "Name",
179            Self::NcName => "NCName",
180            Self::Id => "ID",
181            Self::Decimal => "decimal",
182            Self::Integer => "integer",
183            Self::Boolean => "boolean",
184            Self::Date => "date",
185            Self::DateTime => "dateTime",
186            Self::Time => "time",
187            Self::Base64Binary => "base64Binary",
188            Self::AnyUri => "anyURI",
189            Self::IdRef => "IDREF",
190            Self::Entity => "ENTITY",
191            Self::NmToken => "NMTOKEN",
192            Self::NonPositiveInteger => "nonPositiveInteger",
193            Self::NegativeInteger => "negativeInteger",
194            Self::Long => "long",
195            Self::Int => "int",
196            Self::Short => "short",
197            Self::Byte => "byte",
198            Self::NonNegativeInteger => "nonNegativeInteger",
199            Self::UnsignedLong => "unsignedLong",
200            Self::UnsignedInt => "unsignedInt",
201            Self::UnsignedShort => "unsignedShort",
202            Self::UnsignedByte => "unsignedByte",
203            Self::PositiveInteger => "positiveInteger",
204            Self::Float => "float",
205            Self::Double => "double",
206            Self::Duration => "duration",
207            Self::GYearMonth => "gYearMonth",
208            Self::GYear => "gYear",
209            Self::GMonthDay => "gMonthDay",
210            Self::GDay => "gDay",
211            Self::GMonth => "gMonth",
212            Self::HexBinary => "hexBinary",
213            Self::QName => "QName",
214            Self::Notation => "NOTATION",
215            Self::NmTokens => "NMTOKENS",
216            Self::IdRefs => "IDREFS",
217            Self::Entities => "ENTITIES",
218        }
219    }
220
221    /// The base type definition: the built-in this one is derived from by restriction,
222    /// or `anySimpleType` for the primitive types and the list types (`None` for
223    /// `anySimpleType`, whose base is `anyType`).
224    pub(crate) fn base(self) -> Option<Self> {
225        match self {
226            Self::AnySimpleType => None,
227            Self::NormalizedString => Some(Self::String),
228            Self::Token => Some(Self::NormalizedString),
229            Self::Language | Self::Name | Self::NmToken => Some(Self::Token),
230            Self::NcName => Some(Self::Name),
231            Self::Id | Self::IdRef | Self::Entity => Some(Self::NcName),
232            Self::Integer => Some(Self::Decimal),
233            Self::NonPositiveInteger | Self::Long | Self::NonNegativeInteger => Some(Self::Integer),
234            Self::NegativeInteger => Some(Self::NonPositiveInteger),
235            Self::Int => Some(Self::Long),
236            Self::Short => Some(Self::Int),
237            Self::Byte => Some(Self::Short),
238            Self::UnsignedLong | Self::PositiveInteger => Some(Self::NonNegativeInteger),
239            Self::UnsignedInt => Some(Self::UnsignedLong),
240            Self::UnsignedShort => Some(Self::UnsignedInt),
241            Self::UnsignedByte => Some(Self::UnsignedShort),
242            Self::String
243            | Self::Decimal
244            | Self::Boolean
245            | Self::Date
246            | Self::DateTime
247            | Self::Time
248            | Self::Base64Binary
249            | Self::AnyUri
250            | Self::Float
251            | Self::Double
252            | Self::Duration
253            | Self::GYearMonth
254            | Self::GYear
255            | Self::GMonthDay
256            | Self::GDay
257            | Self::GMonth
258            | Self::HexBinary
259            | Self::QName
260            | Self::Notation
261            | Self::NmTokens
262            | Self::IdRefs
263            | Self::Entities => Some(Self::AnySimpleType),
264        }
265    }
266
267    pub(crate) fn white_space(self) -> WhiteSpace {
268        match self {
269            Self::AnySimpleType | Self::String => WhiteSpace::Preserve,
270            Self::NormalizedString => WhiteSpace::Replace,
271            _ => WhiteSpace::Collapse,
272        }
273    }
274
275    /// Whether `value`, already whitespace-processed, is in the lexical space.
276    pub(crate) fn is_valid(self, value: &str) -> bool {
277        match self {
278            Self::AnySimpleType | Self::String | Self::NormalizedString | Self::Token => true,
279            Self::Language => is_language(value),
280            Self::Name => is_name(value),
281            Self::NcName | Self::Id | Self::IdRef | Self::Entity => is_ncname(value),
282            Self::Decimal => is_decimal(value),
283            Self::Integer => is_integer(value),
284            Self::Boolean => matches!(value, "true" | "false" | "1" | "0"),
285            Self::Date => is_date(value),
286            Self::DateTime => is_date_time(value),
287            Self::Time => is_time(value),
288            Self::Base64Binary => is_base64(value),
289            Self::AnyUri => uri::is_any_uri(value),
290            Self::NmToken => is_nmtoken(value),
291            Self::NonPositiveInteger
292            | Self::NegativeInteger
293            | Self::Long
294            | Self::Int
295            | Self::Short
296            | Self::Byte
297            | Self::NonNegativeInteger
298            | Self::UnsignedLong
299            | Self::UnsignedInt
300            | Self::UnsignedShort
301            | Self::UnsignedByte
302            | Self::PositiveInteger => self.is_in_range(value),
303            Self::Float | Self::Double => is_float(value),
304            Self::Duration => is_duration(value),
305            Self::GYearMonth => is_g_year_month(value),
306            Self::GYear => is_g_year(value),
307            Self::GMonthDay => is_g_month_day(value),
308            Self::GDay => is_g_day(value),
309            Self::GMonth => is_g_month(value),
310            Self::HexBinary => is_hex_binary(value),
311            Self::QName | Self::Notation => split_qname(value).is_some(),
312            Self::NmTokens => is_list(value, is_nmtoken),
313            Self::IdRefs | Self::Entities => is_list(value, is_ncname),
314        }
315    }
316
317    /// The bounds of an integer type derived from `xs:integer`, as signed decimal
318    /// strings without leading zeros: `None` for no bound.
319    fn integer_bounds(self) -> (Option<&'static str>, Option<&'static str>) {
320        match self {
321            Self::NonPositiveInteger => (None, Some("0")),
322            Self::NegativeInteger => (None, Some("-1")),
323            Self::Long => (Some("-9223372036854775808"), Some("9223372036854775807")),
324            Self::Int => (Some("-2147483648"), Some("2147483647")),
325            Self::Short => (Some("-32768"), Some("32767")),
326            Self::Byte => (Some("-128"), Some("127")),
327            Self::NonNegativeInteger => (Some("0"), None),
328            Self::UnsignedLong => (Some("0"), Some("18446744073709551615")),
329            Self::UnsignedInt => (Some("0"), Some("4294967295")),
330            Self::UnsignedShort => (Some("0"), Some("65535")),
331            Self::UnsignedByte => (Some("0"), Some("255")),
332            Self::PositiveInteger => (Some("1"), None),
333            _ => (None, None),
334        }
335    }
336
337    /// Whether `value` is an `xs:integer` within the bounds of the type (Part 2,
338    /// 3.3.14 to 3.3.25: each is derived from `xs:integer` by `minInclusive` and
339    /// `maxInclusive` alone, so that its lexical space is that of `xs:integer` for the
340    /// values in range, any sign and leading zeros included).
341    fn is_in_range(self, value: &str) -> bool {
342        if !is_integer(value) {
343            return false;
344        }
345        let (min, max) = self.integer_bounds();
346        min.is_none_or(|min| compare_integers(value, min).is_ge())
347            && max.is_none_or(|max| compare_integers(value, max).is_le())
348    }
349
350    /// Whether the length facets (`minLength`, `maxLength`) apply to the type and
351    /// this crate implements them: the types derived from `xs:string`, whose length
352    /// is counted in characters (Part 2, 4.3.1). They also apply to `xs:anyURI` and
353    /// `xs:base64Binary`, which the supported schemas never restrict that way; they
354    /// do not apply to the other types here.
355    pub(crate) fn has_length(self) -> bool {
356        matches!(
357            self,
358            Self::String
359                | Self::NormalizedString
360                | Self::Token
361                | Self::Language
362                | Self::Name
363                | Self::NcName
364                | Self::Id
365                | Self::IdRef
366                | Self::Entity
367                | Self::NmToken
368        )
369    }
370
371    /// Whether the length facets apply to the type (Part 2, 4.1.5, Applicable Facets):
372    /// the string types, `anyURI`, the binary types, `QName`, `NOTATION` and the list
373    /// types (whose length is counted in items).
374    pub(crate) fn length_applies(self) -> bool {
375        self.has_length()
376            || matches!(
377                self,
378                Self::AnyUri
379                    | Self::Base64Binary
380                    | Self::HexBinary
381                    | Self::QName
382                    | Self::Notation
383                    | Self::NmTokens
384                    | Self::IdRefs
385                    | Self::Entities
386            )
387    }
388
389    /// Whether a value of the type is valid only in a context the lexical check does
390    /// not see: an `xs:QName` (its prefix), an `xs:NOTATION` (the notations of the
391    /// schema), an `xs:IDREF` (the `xs:ID` of the document), an `xs:ENTITY` (the
392    /// unparsed entities of the document type declaration), and their lists.
393    pub(crate) fn needs_context(self) -> bool {
394        matches!(
395            self,
396            Self::QName
397                | Self::Notation
398                | Self::IdRef
399                | Self::IdRefs
400                | Self::Entity
401                | Self::Entities
402        )
403    }
404
405    /// The value of a lexical form, already whitespace-processed and valid, as a
406    /// key: two valid lexical forms of the type denote the same value (Part 2,
407    /// 2.2.1: equality in the value space) exactly when their keys are equal.
408    /// `None` for the date and time types, whose values (instants with an optional
409    /// timezone) this crate does not compare: a value constraint on them is
410    /// refused when the schema is loaded.
411    pub(crate) fn value_key(self, value: &str) -> Option<std::borrow::Cow<'_, str>> {
412        use std::borrow::Cow;
413        match self {
414            // The string types and anyURI: the value is the string itself (anyURI
415            // values are not URI-normalised: Part 2, 3.2.17 defines no equality
416            // beyond identity of the strings).
417            Self::AnySimpleType
418            | Self::String
419            | Self::NormalizedString
420            | Self::Token
421            | Self::Language
422            | Self::Name
423            | Self::NcName
424            | Self::Id
425            | Self::IdRef
426            | Self::Entity
427            | Self::NmToken
428            | Self::AnyUri => Some(Cow::Borrowed(value)),
429            Self::Decimal
430            | Self::Integer
431            | Self::NonPositiveInteger
432            | Self::NegativeInteger
433            | Self::Long
434            | Self::Int
435            | Self::Short
436            | Self::Byte
437            | Self::NonNegativeInteger
438            | Self::UnsignedLong
439            | Self::UnsignedInt
440            | Self::UnsignedShort
441            | Self::UnsignedByte
442            | Self::PositiveInteger => Some(Cow::Owned(canonical_decimal(value))),
443            // Two hexadecimal digits per octet, in either case.
444            Self::HexBinary => Some(Cow::Owned(value.to_ascii_uppercase())),
445            Self::Boolean => Some(Cow::Borrowed(match value {
446                "true" | "1" => "true",
447                _ => "false",
448            })),
449            // The lexical space admits one encoding per octet sequence (the bits
450            // a padded group leaves unused must be zero), up to the spaces between
451            // characters.
452            Self::Base64Binary => Some(if value.contains(' ') {
453                Cow::Owned(value.replace(' ', ""))
454            } else {
455                Cow::Borrowed(value)
456            }),
457            // Instants and durations with an optional timezone, floating-point values
458            // (NaN, zeros of either sign), qualified names (resolved in a context) and
459            // lists: not compared.
460            Self::Date
461            | Self::DateTime
462            | Self::Time
463            | Self::Float
464            | Self::Double
465            | Self::Duration
466            | Self::GYearMonth
467            | Self::GYear
468            | Self::GMonthDay
469            | Self::GDay
470            | Self::GMonth
471            | Self::QName
472            | Self::Notation
473            | Self::NmTokens
474            | Self::IdRefs
475            | Self::Entities => None,
476        }
477    }
478
479    /// Whether [`Self::value_key`] compares the values of the type.
480    pub(crate) fn has_value_key(self) -> bool {
481        !matches!(
482            self,
483            Self::Date
484                | Self::DateTime
485                | Self::Time
486                | Self::Float
487                | Self::Double
488                | Self::Duration
489                | Self::GYearMonth
490                | Self::GYear
491                | Self::GMonthDay
492                | Self::GDay
493                | Self::GMonth
494                | Self::QName
495                | Self::Notation
496                | Self::NmTokens
497                | Self::IdRefs
498                | Self::Entities
499        )
500    }
501
502    /// Whether `raw`, before whitespace processing, is in the lexical space once
503    /// processed: `self.is_valid(&normalize(raw, self.white_space()))`, without
504    /// building the processed value when the check does not need it (the string
505    /// types accept every value; base64 skips whitespace as it goes).
506    pub(crate) fn is_valid_raw(self, raw: &str) -> bool {
507        match self {
508            Self::AnySimpleType | Self::String | Self::NormalizedString | Self::Token => true,
509            // Collapsing, then dropping the single spaces left between
510            // characters, drops every whitespace character.
511            Self::Base64Binary => is_base64_skipping(raw, is_xml_space_byte),
512            _ => self.is_valid(&normalize(raw, self.white_space())),
513        }
514    }
515}
516
517/// XML whitespace: space, tab, line feed, carriage return.
518pub(crate) fn is_xml_space(c: char) -> bool {
519    matches!(c, ' ' | '\t' | '\n' | '\r')
520}
521
522/// [`is_xml_space`] on a byte of UTF-8 text.
523fn is_xml_space_byte(b: u8) -> bool {
524    matches!(b, b' ' | b'\t' | b'\n' | b'\r')
525}
526
527/// Applies a `whiteSpace` facet.
528pub(crate) fn normalize(value: &str, white_space: WhiteSpace) -> std::borrow::Cow<'_, str> {
529    use std::borrow::Cow;
530    match white_space {
531        WhiteSpace::Preserve => Cow::Borrowed(value),
532        WhiteSpace::Replace => {
533            if value.contains(['\t', '\n', '\r']) {
534                Cow::Owned(value.replace(['\t', '\n', '\r'], " "))
535            } else {
536                Cow::Borrowed(value)
537            }
538        }
539        WhiteSpace::Collapse => {
540            // Leading and trailing whitespace only: the value is a slice.
541            let trimmed = value.trim_matches(is_xml_space);
542            if !trimmed.contains(['\t', '\n', '\r']) && !trimmed.contains("  ") {
543                Cow::Borrowed(trimmed)
544            } else {
545                let mut collapsed = String::with_capacity(trimmed.len());
546                for word in trimmed.split(is_xml_space).filter(|s| !s.is_empty()) {
547                    if !collapsed.is_empty() {
548                        collapsed.push(' ');
549                    }
550                    collapsed.push_str(word);
551                }
552                Cow::Owned(collapsed)
553            }
554        }
555    }
556}
557
558fn is_digits(s: &str) -> bool {
559    !s.is_empty() && s.bytes().all(|b| b.is_ascii_digit())
560}
561
562/// `(\+|-)?([0-9]+(\.[0-9]*)?|\.[0-9]+)`
563pub(crate) fn is_decimal(value: &str) -> bool {
564    let unsigned = value.strip_prefix(['+', '-']).unwrap_or(value);
565    match unsigned.split_once('.') {
566        None => is_digits(unsigned),
567        Some((int, frac)) => {
568            (int.is_empty() || is_digits(int))
569                && (frac.is_empty() || is_digits(frac))
570                && !(int.is_empty() && frac.is_empty())
571        }
572    }
573}
574
575/// The canonical representation of a valid `xs:decimal` lexical form (Part 2,
576/// 3.2.3.2), with no digit limit: no `+`, no leading zeros before the point, no
577/// trailing zeros after it, no point for an integral value, and `0` for zero
578/// (whatever its sign).
579pub(crate) fn canonical_decimal(value: &str) -> String {
580    let (negative, unsigned) = match value.strip_prefix('-') {
581        Some(rest) => (true, rest),
582        None => (false, value.strip_prefix('+').unwrap_or(value)),
583    };
584    let (int, frac) = unsigned.split_once('.').unwrap_or((unsigned, ""));
585    let int = int.trim_start_matches('0');
586    let frac = frac.trim_end_matches('0');
587    if int.is_empty() && frac.is_empty() {
588        return "0".to_owned();
589    }
590    let mut out = String::with_capacity(int.len() + frac.len() + 3);
591    if negative {
592        out.push('-');
593    }
594    out.push_str(if int.is_empty() { "0" } else { int });
595    if !frac.is_empty() {
596        out.push('.');
597        out.push_str(frac);
598    }
599    out
600}
601
602/// `[\-+]?[0-9]+`
603pub(crate) fn is_integer(value: &str) -> bool {
604    is_digits(value.strip_prefix(['+', '-']).unwrap_or(value))
605}
606
607/// The sign of an `xs:integer` lexical form (zero is never negative) and its digits
608/// without leading zeros.
609fn integer_parts(s: &str) -> (bool, &str) {
610    let (negative, digits) = match s.strip_prefix('-') {
611        Some(rest) => (true, rest),
612        None => (false, s.strip_prefix('+').unwrap_or(s)),
613    };
614    let digits = digits.trim_start_matches('0');
615    (negative && !digits.is_empty(), digits)
616}
617
618/// Compares two `xs:integer` lexical forms (any sign, leading zeros) by value.
619fn compare_integers(a: &str, b: &str) -> std::cmp::Ordering {
620    use std::cmp::Ordering;
621    let ((a_negative, a), (b_negative, b)) = (integer_parts(a), integer_parts(b));
622    let magnitude = a.len().cmp(&b.len()).then_with(|| a.cmp(b));
623    match (a_negative, b_negative) {
624        (false, false) => magnitude,
625        (true, true) => magnitude.reverse(),
626        (true, false) => Ordering::Less,
627        (false, true) => Ordering::Greater,
628    }
629}
630
631/// `xs:float` and `xs:double` (Part 2, 3.2.4.1 and 3.2.5.1): a decimal mantissa
632/// optionally followed by `E` or `e` and an integer exponent, or `INF`, `-INF`, `NaN`
633/// (XML Schema 1.0 has no `+INF`).
634pub(crate) fn is_float(value: &str) -> bool {
635    if matches!(value, "INF" | "-INF" | "NaN") {
636        return true;
637    }
638    match value.split_once(['e', 'E']) {
639        Some((mantissa, exponent)) => is_decimal(mantissa) && is_integer(exponent),
640        None => is_decimal(value),
641    }
642}
643
644/// `xs:duration` (Part 2, 3.2.6.1): an optional `-`, `P`, then years, months and days
645/// (`nY`, `nM`, `nD`, in that order, each optional), then optionally `T` and hours,
646/// minutes and seconds (`nH`, `nM`, `nS`, at least one), with at least one component
647/// in all; the numbers are unsigned integers of any length, the seconds a decimal
648/// (`1.`, `.5` and `1.5` alike, as XML Schema 1.1 writes the grammar).
649pub(crate) fn is_duration(value: &str) -> bool {
650    let unsigned = value.strip_prefix('-').unwrap_or(value);
651    let Some(rest) = unsigned.strip_prefix('P') else {
652        return false;
653    };
654    let (date, time) = match rest.split_once('T') {
655        Some((date, time)) => (date, Some(time)),
656        None => (rest, None),
657    };
658    // Components `digits designator`, in the order of `designators`, each at most once.
659    let components = |s: &str, designators: &[u8], seconds: bool| -> Option<usize> {
660        let mut count = 0;
661        let mut next = 0;
662        let mut rest = s;
663        while !rest.is_empty() {
664            let end = rest.find(|c: char| !(c.is_ascii_digit() || (seconds && c == '.')))?;
665            let (number, tail) = rest.split_at(end);
666            let designator = *tail.as_bytes().first()?;
667            let position = designators[next..].iter().position(|&d| d == designator)? + next;
668            let is_seconds = seconds && designator == b'S';
669            let valid = if is_seconds {
670                is_decimal(number) && !number.starts_with(['+', '-'])
671            } else {
672                is_digits(number)
673            };
674            if !valid {
675                return None;
676            }
677            count += 1;
678            next = position + 1;
679            rest = &tail[1..];
680        }
681        Some(count)
682    };
683    let Some(date_count) = components(date, b"YMD", false) else {
684        return false;
685    };
686    match time {
687        None => date_count > 0,
688        Some(time) => components(time, b"HMS", true).is_some_and(|n| n > 0),
689    }
690}
691
692/// A year of a date or `g*` type: an optional `-`, at least four digits, no leading
693/// zero when there are more, and not zero (XML Schema 1.0 has no year zero).
694fn is_year(s: &str) -> bool {
695    let digits = s.strip_prefix('-').unwrap_or(s);
696    digits.len() >= 4
697        && is_digits(digits)
698        && !(digits.len() > 4 && digits.starts_with('0'))
699        && !digits.bytes().all(|b| b == b'0')
700}
701
702/// A month, `01` to `12`.
703fn month(s: &str) -> Option<u32> {
704    two_digits(s).filter(|m| (1..=12).contains(m))
705}
706
707/// `xs:gYearMonth`: `year-mm`, then an optional timezone.
708pub(crate) fn is_g_year_month(value: &str) -> bool {
709    split_timezone(value)
710        .and_then(|rest| rest.rsplit_once('-'))
711        .is_some_and(|(year, mm)| is_year(year) && month(mm).is_some())
712}
713
714/// `xs:gYear`: a year, then an optional timezone.
715pub(crate) fn is_g_year(value: &str) -> bool {
716    split_timezone(value).is_some_and(is_year)
717}
718
719/// `xs:gMonthDay`: `--mm-dd`, a day that exists in that month in some year (February
720/// 29 included), then an optional timezone.
721pub(crate) fn is_g_month_day(value: &str) -> bool {
722    let Some((mm, dd)) = split_timezone(value)
723        .and_then(|rest| rest.strip_prefix("--"))
724        .and_then(|rest| rest.split_once('-'))
725    else {
726        return false;
727    };
728    let days = match month(mm) {
729        Some(2) => 29,
730        Some(4 | 6 | 9 | 11) => 30,
731        Some(_) => 31,
732        None => return false,
733    };
734    two_digits(dd).is_some_and(|d| (1..=days).contains(&d))
735}
736
737/// `xs:gDay`: `---dd`, 01 to 31, then an optional timezone.
738pub(crate) fn is_g_day(value: &str) -> bool {
739    split_timezone(value)
740        .and_then(|rest| rest.strip_prefix("---"))
741        .and_then(two_digits)
742        .is_some_and(|d| (1..=31).contains(&d))
743}
744
745/// `xs:gMonth`: `--mm` (as corrected by the errata of the Second Edition), then an
746/// optional timezone.
747pub(crate) fn is_g_month(value: &str) -> bool {
748    split_timezone(value)
749        .and_then(|rest| rest.strip_prefix("--"))
750        .and_then(month)
751        .is_some()
752}
753
754/// `xs:hexBinary`: pairs of hexadecimal digits, in either case.
755pub(crate) fn is_hex_binary(value: &str) -> bool {
756    value.len().is_multiple_of(2) && value.bytes().all(|b| b.is_ascii_hexdigit())
757}
758
759/// `Nmtoken` of XML 1.0 Fifth Edition: one or more name characters.
760pub(crate) fn is_nmtoken(value: &str) -> bool {
761    !value.is_empty() && value.chars().all(is_name_char)
762}
763
764/// A list type (Part 2, 2.5.1.2): items separated by single spaces (the value is
765/// collapsed), each valid, at least one (the built-in list types have a `minLength` of
766/// 1).
767pub(crate) fn is_list(value: &str, item: fn(&str) -> bool) -> bool {
768    !value.is_empty() && value.split(' ').all(item)
769}
770
771/// `[a-zA-Z]{1,8}(-[a-zA-Z0-9]{1,8})*` (XML Schema 1.0 Second Edition).
772pub(crate) fn is_language(value: &str) -> bool {
773    let mut parts = value.split('-');
774    let first_ok = parts
775        .next()
776        .is_some_and(|p| (1..=8).contains(&p.len()) && p.bytes().all(|b| b.is_ascii_alphabetic()));
777    first_ok
778        && parts.all(|p| (1..=8).contains(&p.len()) && p.bytes().all(|b| b.is_ascii_alphanumeric()))
779}
780
781/// `NameStartChar` of XML 1.0 Fifth Edition.
782pub(crate) fn is_name_start_char(c: char) -> bool {
783    matches!(c,
784        ':' | 'A'..='Z' | '_' | 'a'..='z'
785        | '\u{C0}'..='\u{D6}' | '\u{D8}'..='\u{F6}' | '\u{F8}'..='\u{2FF}'
786        | '\u{370}'..='\u{37D}' | '\u{37F}'..='\u{1FFF}' | '\u{200C}'..='\u{200D}'
787        | '\u{2070}'..='\u{218F}' | '\u{2C00}'..='\u{2FEF}' | '\u{3001}'..='\u{D7FF}'
788        | '\u{F900}'..='\u{FDCF}' | '\u{FDF0}'..='\u{FFFD}' | '\u{10000}'..='\u{EFFFF}')
789}
790
791/// `NameChar` of XML 1.0 Fifth Edition.
792pub(crate) fn is_name_char(c: char) -> bool {
793    is_name_start_char(c)
794        || matches!(c, '-' | '.' | '0'..='9' | '\u{B7}' | '\u{300}'..='\u{36F}' | '\u{203F}'..='\u{2040}')
795}
796
797/// `Name` of XML 1.0 Fifth Edition.
798pub(crate) fn is_name(value: &str) -> bool {
799    let mut chars = value.chars();
800    chars.next().is_some_and(is_name_start_char) && chars.all(is_name_char)
801}
802
803/// `NCName` of Namespaces in XML 1.0: a `Name` without colons.
804pub(crate) fn is_ncname(value: &str) -> bool {
805    !value.contains(':') && is_name(value)
806}
807
808/// `QName` of Namespaces in XML 1.0: `(NCName ':')? NCName`.
809pub(crate) fn split_qname(value: &str) -> Option<(Option<&str>, &str)> {
810    match value.split_once(':') {
811        Some((prefix, local)) if is_ncname(prefix) && is_ncname(local) => {
812            Some((Some(prefix), local))
813        }
814        None if is_ncname(value) => Some((None, value)),
815        _ => None,
816    }
817}
818
819/// The base64 alphabet.
820fn is_base64_char(b: u8) -> bool {
821    b.is_ascii_alphanumeric() || b == b'+' || b == b'/'
822}
823
824/// The lexical space of `base64Binary` (Part 2, 3.2.16, as corrected by the errata of
825/// the Second Edition): groups of four characters of the base64 alphabet, the last
826/// group optionally padded with one `=` (third character in `AEIMQUYcgkosw048`) or
827/// two (second character in `AQgw`), with single spaces allowed between characters.
828/// The value is already collapsed, so it has no leading, trailing or double spaces.
829pub(crate) fn is_base64(value: &str) -> bool {
830    is_base64_skipping(value, |b| b == b' ')
831}
832
833/// [`is_base64`] on the characters of `value` that `skip` does not drop, in one
834/// pass: the characters left must be a multiple of four, every one of them base64
835/// except a final run of at most two `=`, and the padding must fit the last
836/// character before it.
837fn is_base64_skipping(value: &str, skip: impl Fn(u8) -> bool) -> bool {
838    let mut count = 0_usize;
839    let mut padding = 0_usize;
840    let mut last = None;
841    for b in value.bytes().filter(|&b| !skip(b)) {
842        count += 1;
843        if b == b'=' {
844            padding += 1;
845        } else if padding > 0 || !is_base64_char(b) {
846            // A character after padding, or outside the alphabet.
847            return false;
848        } else {
849            last = Some(b);
850        }
851    }
852    if !count.is_multiple_of(4) || padding > 2 {
853        return false;
854    }
855    match (padding, last) {
856        (0, _) => true,
857        (1, Some(last)) => b"AEIMQUYcgkosw048".contains(&last),
858        (2, Some(last)) => b"AQgw".contains(&last),
859        _ => false,
860    }
861}
862
863fn two_digits(s: &str) -> Option<u32> {
864    if s.len() == 2 && s.bytes().all(|b| b.is_ascii_digit()) {
865        s.parse().ok()
866    } else {
867        None
868    }
869}
870
871/// Whether a year, given by its digits (no sign), is a leap year. Negative years
872/// follow the same rule on their absolute value, as libxml2 does: XML Schema 1.0 has
873/// no year zero and does not spell out the rule for years before the common era.
874fn is_leap_year(digits: &str) -> bool {
875    // 10^4 is a multiple of 400: the last four digits decide.
876    let tail = &digits[digits.len().saturating_sub(4)..];
877    let year: u32 = tail.parse().unwrap_or(1);
878    (year.is_multiple_of(4) && !year.is_multiple_of(100)) || year.is_multiple_of(400)
879}
880
881/// `-?yyyy-mm-dd` with at least four year digits, no leading zero when there are more,
882/// year zero excluded, and a day that exists in that month.
883fn date_part(s: &str) -> Option<()> {
884    let unsigned = s.strip_prefix('-').unwrap_or(s);
885    let mut fields = unsigned.rsplitn(3, '-');
886    let day = two_digits(fields.next()?)?;
887    let month = two_digits(fields.next()?)?;
888    let year = fields.next()?;
889    if year.len() < 4 || !is_digits(year) || (year.len() > 4 && year.starts_with('0')) {
890        return None;
891    }
892    if year.bytes().all(|b| b == b'0') {
893        return None;
894    }
895    let days = match month {
896        1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
897        4 | 6 | 9 | 11 => 30,
898        2 if is_leap_year(year) => 29,
899        2 => 28,
900        _ => return None,
901    };
902    (1..=days).contains(&day).then_some(())
903}
904
905/// `hh:mm:ss(.s+)?`, hours 00 to 23, or 24:00:00 with a zero fraction.
906fn time_part(s: &str) -> Option<()> {
907    let (whole, fraction) = match s.split_once('.') {
908        Some((whole, fraction)) => (whole, Some(fraction)),
909        None => (s, None),
910    };
911    if let Some(fraction) = fraction
912        && !is_digits(fraction)
913    {
914        return None;
915    }
916    let mut fields = whole.split(':');
917    let hour = two_digits(fields.next()?)?;
918    let minute = two_digits(fields.next()?)?;
919    let second = two_digits(fields.next()?)?;
920    if fields.next().is_some() || minute > 59 || second > 59 {
921        return None;
922    }
923    let zero_fraction = fraction.is_none_or(|f| f.bytes().all(|b| b == b'0'));
924    (hour < 24 || (hour == 24 && minute == 0 && second == 0 && zero_fraction)).then_some(())
925}
926
927/// Splits an optional timezone (`Z` or `(+|-)hh:mm`, at most 14:00 away from UTC)
928/// off the end of a date or time; `None` if a timezone is present but invalid.
929fn split_timezone(s: &str) -> Option<&str> {
930    if let Some(rest) = s.strip_suffix('Z') {
931        return Some(rest);
932    }
933    let bytes = s.as_bytes();
934    if bytes.len() >= 6
935        && matches!(bytes[bytes.len() - 6], b'+' | b'-')
936        && bytes[bytes.len() - 3] == b':'
937    {
938        let (rest, zone) = s.split_at(s.len() - 6);
939        let hours = two_digits(&zone[1..3])?;
940        let minutes = two_digits(&zone[4..6])?;
941        // A date ending in `-dd` also matches `-hh:mm` only if it has a colon, which
942        // dates do not: the shape check above is unambiguous.
943        return (minutes <= 59 && (hours < 14 || (hours == 14 && minutes == 0))).then_some(rest);
944    }
945    Some(s)
946}
947
948pub(crate) fn is_date(value: &str) -> bool {
949    split_timezone(value).and_then(date_part).is_some()
950}
951
952pub(crate) fn is_time(value: &str) -> bool {
953    split_timezone(value).and_then(time_part).is_some()
954}
955
956pub(crate) fn is_date_time(value: &str) -> bool {
957    split_timezone(value)
958        .and_then(|rest| rest.split_once('T'))
959        .and_then(|(date, time)| date_part(date).and(time_part(time)))
960        .is_some()
961}
962
963#[cfg(test)]
964mod tests {
965    use super::*;
966
967    #[test]
968    fn decimals() {
969        for ok in [
970            "0",
971            "-1",
972            "+1.5",
973            ".5",
974            "5.",
975            "-.5",
976            "00.",
977            "0001.000",
978            "123456789012345678901234567890",
979        ] {
980            assert!(is_decimal(ok), "{ok}");
981        }
982        for bad in [
983            "", ".", "-", "+", "+.", "1.2.3", "1e3", "1,5", "--1", " 1", "NaN", "INF", "0x10", "1",
984        ] {
985            assert!(!is_decimal(bad), "{bad}");
986        }
987    }
988
989    #[test]
990    fn canonical_decimals() {
991        for (value, canonical) in [
992            ("0", "0"),
993            ("-0", "0"),
994            ("+0.000", "0"),
995            (".0", "0"),
996            ("0.", "0"),
997            ("1.50", "1.5"),
998            ("+01.500", "1.5"),
999            ("-001", "-1"),
1000            ("-.5", "-0.5"),
1001            ("5.", "5"),
1002            ("100", "100"),
1003            ("10.010", "10.01"),
1004            (
1005                "000123456789012345678901234567890.000",
1006                "123456789012345678901234567890",
1007            ),
1008        ] {
1009            assert_eq!(canonical_decimal(value), canonical, "{value}");
1010        }
1011    }
1012
1013    #[test]
1014    fn value_keys() {
1015        let key = |builtin: Builtin, value: &str| {
1016            builtin.value_key(value).map(std::borrow::Cow::into_owned)
1017        };
1018        assert_eq!(key(Builtin::Boolean, "1"), key(Builtin::Boolean, "true"));
1019        assert_eq!(key(Builtin::Boolean, "0"), key(Builtin::Boolean, "false"));
1020        assert_ne!(key(Builtin::Boolean, "0"), key(Builtin::Boolean, "true"));
1021        assert_eq!(key(Builtin::Integer, "+002"), key(Builtin::Integer, "2"));
1022        assert_eq!(key(Builtin::Decimal, "1.5"), key(Builtin::Decimal, "1.50"));
1023        assert_eq!(
1024            key(Builtin::Base64Binary, "Q U J D"),
1025            key(Builtin::Base64Binary, "QUJD")
1026        );
1027        // Strings are compared as they are: whitespace processing comes first.
1028        assert_ne!(key(Builtin::String, " a"), key(Builtin::String, "a"));
1029        assert_ne!(key(Builtin::Language, "EN"), key(Builtin::Language, "en"));
1030        assert_ne!(key(Builtin::AnyUri, "a%20b"), key(Builtin::AnyUri, "a b"));
1031        for builtin in [Builtin::Date, Builtin::DateTime, Builtin::Time] {
1032            assert!(!builtin.has_value_key());
1033            assert_eq!(builtin.value_key("2024-01-01"), None);
1034        }
1035        for builtin in Builtin::ALL {
1036            assert_eq!(
1037                builtin.has_value_key(),
1038                builtin.value_key("").is_some(),
1039                "{builtin:?}"
1040            );
1041        }
1042    }
1043
1044    #[test]
1045    fn length_facets_apply_to_the_string_types() {
1046        let with_length: Vec<Builtin> = Builtin::ALL
1047            .into_iter()
1048            .filter(|b| b.has_length())
1049            .collect();
1050        assert_eq!(
1051            with_length,
1052            [
1053                Builtin::String,
1054                Builtin::NormalizedString,
1055                Builtin::Token,
1056                Builtin::Language,
1057                Builtin::Name,
1058                Builtin::NcName,
1059                Builtin::Id,
1060                Builtin::IdRef,
1061                Builtin::Entity,
1062                Builtin::NmToken
1063            ]
1064        );
1065        let length_applies: Vec<Builtin> = Builtin::ALL
1066            .into_iter()
1067            .filter(|b| b.length_applies() && !b.has_length())
1068            .collect();
1069        assert_eq!(
1070            length_applies,
1071            [
1072                Builtin::Base64Binary,
1073                Builtin::AnyUri,
1074                Builtin::HexBinary,
1075                Builtin::QName,
1076                Builtin::Notation,
1077                Builtin::NmTokens,
1078                Builtin::IdRefs,
1079                Builtin::Entities
1080            ]
1081        );
1082    }
1083
1084    #[test]
1085    fn integers() {
1086        for ok in ["0", "-0", "+42", "1234567890123456789012345"] {
1087            assert!(is_integer(ok), "{ok}");
1088        }
1089        for bad in ["", "+", "1.0", "1 2", "a"] {
1090            assert!(!is_integer(bad), "{bad}");
1091        }
1092    }
1093
1094    #[test]
1095    fn dates() {
1096        for ok in [
1097            "2024-02-29",
1098            "2000-02-29",
1099            "12024-01-01",
1100            "-0001-01-01",
1101            "-0004-02-29",
1102            "2024-03-01Z",
1103            "2024-03-01+14:00",
1104            "2024-03-01-14:00",
1105            "2024-03-01+13:59",
1106        ] {
1107            assert!(is_date(ok), "{ok}");
1108        }
1109        for bad in [
1110            "2024-02-30",
1111            "2023-02-29",
1112            "1900-02-29",
1113            "-0001-02-29",
1114            "2024-13-01",
1115            "2024-00-10",
1116            "2024-03-00",
1117            "24-03-01",
1118            "2024-3-1",
1119            "0000-01-01",
1120            "02024-01-01",
1121            "+2024-03-01",
1122            "2024-03-01+14:01",
1123            "2024-03-01+15:00",
1124            "2024-03-01+01:60",
1125            "2024-03-01+0100",
1126            "2024-03-01z",
1127            "2024-03-01T00:00:00",
1128            "",
1129            "2024-03-01 Z",
1130        ] {
1131            assert!(!is_date(bad), "{bad}");
1132        }
1133    }
1134
1135    #[test]
1136    fn times() {
1137        for ok in [
1138            "10:15:30",
1139            "24:00:00",
1140            "24:00:00.000",
1141            "24:00:00+01:00",
1142            "10:15:30.123Z",
1143            "23:59:59.99999999999999999999",
1144        ] {
1145            assert!(is_time(ok), "{ok}");
1146        }
1147        for bad in [
1148            "24:00:01",
1149            "24:01:00",
1150            "25:00:00",
1151            "23:60:00",
1152            "23:59:60",
1153            "10:15",
1154            "10:15:30.",
1155            "1:15:30",
1156            "10:15:30+24:00",
1157            "10:15:30,5",
1158            "24:00:00.1",
1159        ] {
1160            assert!(!is_time(bad), "{bad}");
1161        }
1162    }
1163
1164    #[test]
1165    fn date_times() {
1166        for ok in [
1167            "2024-03-01T10:15:30",
1168            "2024-12-31T24:00:00Z",
1169            "2024-03-01T10:15:30.250+01:00",
1170        ] {
1171            assert!(is_date_time(ok), "{ok}");
1172        }
1173        for bad in [
1174            "2024-03-01 10:15:30",
1175            "2024-03-01t10:15:30",
1176            "2024-03-01",
1177            "2023-02-29T10:00:00",
1178            "2024-03-01T10:15Z",
1179            "2024-03-01T10:15:30Zx",
1180        ] {
1181            assert!(!is_date_time(bad), "{bad}");
1182        }
1183    }
1184
1185    #[test]
1186    fn base64() {
1187        for ok in [
1188            "",
1189            "QQ==",
1190            "QUI=",
1191            "QUJD",
1192            "Q U J D Q Q = =",
1193            "QUJD QUJD QUI=",
1194        ] {
1195            assert!(is_base64(ok), "{ok}");
1196        }
1197        for bad in [
1198            "abc",
1199            "QR==",
1200            "QUJ=",
1201            "Q===",
1202            "====",
1203            "QQ=",
1204            "QQ==QUJD",
1205            "QU!JD",
1206            "-_-_",
1207            "QQ== QQ==",
1208        ] {
1209            assert!(!is_base64(bad), "{bad}");
1210        }
1211    }
1212
1213    #[test]
1214    fn languages() {
1215        for ok in ["en", "en-GB", "x-a1-B2", "englishx-language"] {
1216            assert!(is_language(ok), "{ok}");
1217        }
1218        for bad in [
1219            "",
1220            "en_GB",
1221            "123",
1222            "e1",
1223            "en-123456789",
1224            "englishxx",
1225            "en-",
1226            "en--GB",
1227            "-en",
1228        ] {
1229            assert!(!is_language(bad), "{bad}");
1230        }
1231    }
1232
1233    #[test]
1234    fn names() {
1235        assert!(is_ncname("signature-1"));
1236        assert!(is_ncname("sïgnature"));
1237        assert!(!is_ncname("1signature"));
1238        assert!(!is_ncname("a:b"));
1239        assert!(!is_ncname(""));
1240        assert_eq!(split_qname("a:b"), Some((Some("a"), "b")));
1241        assert_eq!(split_qname("b"), Some((None, "b")));
1242        assert_eq!(split_qname("a:b:c"), None);
1243        assert_eq!(split_qname("1"), None);
1244    }
1245
1246    /// The lexical spaces of the built-in types a document can name in `xsi:type`,
1247    /// after whitespace processing (Part 2 of XML Schema 1.0, Second Edition).
1248    #[test]
1249    #[expect(clippy::too_many_lines, reason = "one table of cases")]
1250    fn other_built_in_types() {
1251        use Builtin as B;
1252        let cases: &[(Builtin, &[&str], &[&str])] = &[
1253            (
1254                B::Float,
1255                &[
1256                    "1", "1.5", "-1.5E3", "1e3", ".5", "5.", "+1", "INF", "-INF", "NaN", "1.5e+3",
1257                    "1e1000", "-0", "+.5e-1",
1258                ],
1259                &[
1260                    "", "+INF", "inf", "nan", "1E", "1E+", "E1", "1 2", "0x10", ".", "-", "1.2.3",
1261                    "1d", "1f", ".e1", "1e1.5",
1262                ],
1263            ),
1264            (B::Double, &["1e400", "-0.0e-0", "NaN"], &["+INF", ""]),
1265            (
1266                B::Duration,
1267                &[
1268                    "P1Y",
1269                    "P1Y2M3DT4H5M6.7S",
1270                    "-P1D",
1271                    "PT1H",
1272                    "PT1.5S",
1273                    "PT.5S",
1274                    "PT1.S",
1275                    "P0Y",
1276                    "PT1M",
1277                    "P1M",
1278                    "-PT0S",
1279                    "P99999999999999999999Y",
1280                ],
1281                &[
1282                    "P", "PT", "P1DT", "P1H", "PT1D", "P1.5Y", "+P1D", "P-1D", "1Y", "P1M1Y",
1283                    "P1Y1Y", "pt1h", "P1D T1H", "P1Y2MT", "P0.5D", "PT1H2H", "P1W", "P1Y-1M",
1284                    "PT1S1S", "P1DT1.5H",
1285                ],
1286            ),
1287            (
1288                B::GYearMonth,
1289                &[
1290                    "2024-02",
1291                    "-0001-01",
1292                    "12024-01",
1293                    "2024-01Z",
1294                    "2024-01+14:00",
1295                    "0001-01",
1296                ],
1297                &[
1298                    "2024-13",
1299                    "2024-00",
1300                    "0000-01",
1301                    "-0000-01",
1302                    "024-01",
1303                    "2024-01+14:01",
1304                    "2024-1",
1305                    "02024-01",
1306                    "2024-01-01",
1307                ],
1308            ),
1309            (
1310                B::GYear,
1311                &[
1312                    "2024",
1313                    "-2024",
1314                    "12345",
1315                    "2024Z",
1316                    "2024-05:00",
1317                    "2024+00:00",
1318                    "99999999999999999999",
1319                ],
1320                &[
1321                    "0000",
1322                    "-0000",
1323                    "012345",
1324                    "024",
1325                    "+2024",
1326                    "2024-14:30",
1327                    "2024+1:00",
1328                ],
1329            ),
1330            (
1331                B::GMonthDay,
1332                &["--02-29", "--12-31", "--01-01Z", "--01-01+01:00"],
1333                &[
1334                    "--02-30", "--04-31", "--13-01", "--01-00", "-01-01", "--1-01",
1335                ],
1336            ),
1337            (
1338                B::GDay,
1339                &["---01", "---31", "---01Z", "---15-12:00", "---31+14:00"],
1340                &["---32", "---00", "---1", "--01"],
1341            ),
1342            (
1343                B::GMonth,
1344                &["--01", "--12", "--01Z", "--05+10:00"],
1345                &["--13", "--00", "--01--", "--1", "-01"],
1346            ),
1347            (
1348                B::HexBinary,
1349                &["", "0F", "0f", "0FB7"],
1350                &["F", "0G", "0F B7", "0Fb"],
1351            ),
1352            (
1353                B::NonPositiveInteger,
1354                &["0", "-0", "+0", "-1", "-00001"],
1355                &["1", "+1", "", "-1.0"],
1356            ),
1357            (
1358                B::NegativeInteger,
1359                &["-1", "-99999999999999999999999"],
1360                &["0", "-0", "1"],
1361            ),
1362            (
1363                B::Long,
1364                &[
1365                    "9223372036854775807",
1366                    "-9223372036854775808",
1367                    "+1",
1368                    "00009223372036854775807",
1369                ],
1370                &["9223372036854775808", "-9223372036854775809", "1.0", "-"],
1371            ),
1372            (
1373                B::Int,
1374                &["2147483647", "-2147483648", "+0"],
1375                &["2147483648", "-2147483649"],
1376            ),
1377            (B::Short, &["32767", "-32768"], &["32768", "-32769"]),
1378            (B::Byte, &["127", "-128", "+127", "0127"], &["128", "-129"]),
1379            (
1380                B::NonNegativeInteger,
1381                &["0", "-0", "+1", "99999999999999999999999"],
1382                &["-1"],
1383            ),
1384            (
1385                B::UnsignedLong,
1386                &["18446744073709551615", "0", "-0", "+1"],
1387                &["18446744073709551616", "-1"],
1388            ),
1389            (B::UnsignedInt, &["4294967295", "-0", "+5"], &["4294967296"]),
1390            (B::UnsignedShort, &["65535"], &["65536"]),
1391            (B::UnsignedByte, &["255", "+255", "-0"], &["256", "-1"]),
1392            (B::PositiveInteger, &["1", "+1", "01"], &["0", "-0", "-1"]),
1393            (
1394                B::NmToken,
1395                &["abc", "1a", "-.:_", "\u{e9}"],
1396                &["a b", "", "a@b"],
1397            ),
1398            (B::NmTokens, &["a b c", "a"], &["", "a @"]),
1399            (B::IdRef, &["a1"], &["1a", "a:b", ""]),
1400            (B::IdRefs, &["a b", "a"], &["", "a 1"]),
1401            (B::Entity, &["a"], &["1", ""]),
1402            (B::Entities, &["a b"], &[""]),
1403            (
1404                B::QName,
1405                &["a", "xs:a", "xmlns:a"],
1406                &["1a", ":a", "a:", "xs:a:b", ""],
1407            ),
1408            (B::Notation, &["a", "xs:a"], &["1"]),
1409        ];
1410        for (builtin, valid, invalid) in cases {
1411            for value in *valid {
1412                assert!(builtin.is_valid(value), "{builtin:?} {value:?}");
1413            }
1414            for value in *invalid {
1415                assert!(!builtin.is_valid(value), "{builtin:?} {value:?}");
1416            }
1417        }
1418        // Whitespace is collapsed first.
1419        assert!(B::Duration.is_valid_raw(" P1D "));
1420        assert!(B::NmTokens.is_valid_raw("  a \t b "));
1421        assert!(!B::HexBinary.is_valid_raw("0F B7"));
1422        // Every type derives from anySimpleType, through its base types.
1423        for builtin in Builtin::ALL {
1424            let mut current = builtin;
1425            let mut steps = 0;
1426            while let Some(base) = current.base() {
1427                assert!(
1428                    Builtin::ALL.iter().position(|b| *b == base)
1429                        < Builtin::ALL.iter().position(|b| *b == current),
1430                    "{builtin:?}: base {base:?} after it in ALL"
1431                );
1432                current = base;
1433                steps += 1;
1434            }
1435            assert_eq!(current, B::AnySimpleType, "{builtin:?}");
1436            assert!(steps <= 7, "{builtin:?}");
1437        }
1438        assert_eq!(compare_integers("+0010", "10"), std::cmp::Ordering::Equal);
1439        assert_eq!(compare_integers("-0", "0"), std::cmp::Ordering::Equal);
1440        assert_eq!(compare_integers("-11", "-2"), std::cmp::Ordering::Less);
1441        assert_eq!(compare_integers("9", "10"), std::cmp::Ordering::Less);
1442    }
1443
1444    #[test]
1445    fn white_space() {
1446        assert_eq!(normalize(" a \t\n b ", WhiteSpace::Collapse), "a b");
1447        assert_eq!(normalize("a\tb\n", WhiteSpace::Replace), "a b ");
1448        assert_eq!(normalize(" a ", WhiteSpace::Preserve), " a ");
1449        // Only leading and trailing whitespace: a slice of the value, not a copy.
1450        assert!(matches!(
1451            normalize("\n  12.50\t", WhiteSpace::Collapse),
1452            std::borrow::Cow::Borrowed("12.50")
1453        ));
1454    }
1455
1456    /// The collapsed value as XML Schema Part 2 defines it: runs of whitespace
1457    /// become one space, then leading and trailing spaces go.
1458    fn reference_collapse(value: &str) -> String {
1459        value
1460            .split(is_xml_space)
1461            .filter(|s| !s.is_empty())
1462            .collect::<Vec<_>>()
1463            .join(" ")
1464    }
1465
1466    /// `base64Binary` checked on a copy of the value without its spaces.
1467    fn reference_base64(value: &str) -> bool {
1468        let bytes: Vec<u8> = value.bytes().filter(|&b| b != b' ').collect();
1469        if !bytes.len().is_multiple_of(4) {
1470            return false;
1471        }
1472        let padding = bytes.iter().rev().take_while(|&&b| b == b'=').count();
1473        let data = &bytes[..bytes.len() - padding];
1474        if padding > 2 || !data.iter().all(|&b| is_base64_char(b)) {
1475            return false;
1476        }
1477        match (padding, data.last()) {
1478            (0, _) => true,
1479            (1, Some(last)) => b"AEIMQUYcgkosw048".contains(last),
1480            (2, Some(last)) => b"AQgw".contains(last),
1481            _ => false,
1482        }
1483    }
1484
1485    proptest::proptest! {
1486        #![proptest_config(proptest::prelude::ProptestConfig::with_cases(4000))]
1487
1488        #[test]
1489        fn collapse_matches_the_definition(value in "[ \t\n\ra-c.]{0,12}") {
1490            let collapsed = normalize(&value, WhiteSpace::Collapse);
1491            proptest::prop_assert_eq!(collapsed.as_ref(), reference_collapse(&value));
1492        }
1493
1494        #[test]
1495        fn base64_in_one_pass(value in "[A-Da-dQgwU0-3+/= !\t\n\r-]{0,16}") {
1496            proptest::prop_assert_eq!(is_base64(&value), reference_base64(&value));
1497        }
1498
1499        #[test]
1500        fn decimal_keys_are_numeric_equality(
1501            a in "[+-]?[0-9]{0,6}(\\.[0-9]{0,6})?",
1502            b in "[+-]?[0-9]{0,6}(\\.[0-9]{0,6})?",
1503        ) {
1504            proptest::prop_assume!(is_decimal(&a) && is_decimal(&b));
1505            // Reference: the value scaled by 10^6, exact in an i64.
1506            let scaled = |value: &str| -> i64 {
1507                let negative = value.starts_with('-');
1508                let unsigned = value.trim_start_matches(['+', '-']);
1509                let (int, frac) = unsigned.split_once('.').unwrap_or((unsigned, ""));
1510                let int: i64 = if int.is_empty() { 0 } else { int.parse().unwrap() };
1511                let frac: i64 = format!("{frac:0<6}").parse().unwrap();
1512                let magnitude = int * 1_000_000 + frac;
1513                if negative { -magnitude } else { magnitude }
1514            };
1515            proptest::prop_assert_eq!(
1516                canonical_decimal(&a) == canonical_decimal(&b),
1517                scaled(&a) == scaled(&b),
1518                "{} {}", a, b
1519            );
1520            // The canonical form is itself a valid decimal with the same value.
1521            proptest::prop_assert!(is_decimal(&canonical_decimal(&a)));
1522            proptest::prop_assert_eq!(scaled(&canonical_decimal(&a)), scaled(&a));
1523        }
1524
1525        #[test]
1526        fn decimal_keys_ignore_zeros_and_plus(
1527            negative: bool,
1528            int in "[0-9]{0,4}",
1529            frac in "[0-9]{0,4}",
1530            lead in 0_usize..3,
1531            trail in 0_usize..3,
1532            plus: bool,
1533        ) {
1534            proptest::prop_assume!(!int.is_empty() || !frac.is_empty());
1535            let sign = if negative { "-" } else { "" };
1536            let a = format!("{sign}{int}.{frac}");
1537            let other_sign = if negative { "-" } else if plus { "+" } else { "" };
1538            let b = format!("{other_sign}{}{int}.{frac}{}", "0".repeat(lead), "0".repeat(trail));
1539            proptest::prop_assert_eq!(canonical_decimal(&a), canonical_decimal(&b));
1540        }
1541
1542        #[test]
1543        fn raw_values_as_processed_values(
1544            value in "[ \t\n\r0-9a-zA-Z+/=:.T-]{0,16}",
1545            index in 0..Builtin::ALL.len(),
1546        ) {
1547            let builtin = Builtin::ALL[index];
1548            let processed = normalize(&value, builtin.white_space());
1549            proptest::prop_assert_eq!(builtin.is_valid_raw(&value), builtin.is_valid(&processed));
1550        }
1551    }
1552}