Skip to main content

openbim_dt/
value.rs

1//! ISO 23387 lexical value contracts.
2
3use std::{error::Error, fmt, str::FromStr};
4
5/// A value rejected by an ISO 23387 lexical contract.
6#[derive(Debug, Clone, PartialEq, Eq)]
7pub struct ValueError {
8    kind: ValueErrorKind,
9    value: String,
10}
11
12impl ValueError {
13    fn new(kind: ValueErrorKind, value: impl Into<String>) -> Self {
14        Self {
15            kind,
16            value: value.into(),
17        }
18    }
19
20    /// The failed lexical contract.
21    #[must_use]
22    pub const fn kind(&self) -> ValueErrorKind {
23        self.kind
24    }
25}
26
27impl fmt::Display for ValueError {
28    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
29        write!(formatter, "invalid {:?} value {:?}", self.kind, self.value)
30    }
31}
32
33impl Error for ValueError {}
34
35/// Lexical contracts checked by [`ValueError`].
36///
37/// Non-exhaustive: new ISO 23387 lexical contracts are added as the owned
38/// model grows, and matching code must keep a wildcard arm.
39#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
40#[non_exhaustive]
41pub enum ValueErrorKind {
42    /// ISO 23387 `GuidType`.
43    Guid,
44    /// XML Schema `language`.
45    Language,
46    /// ISO 23387 `RationalType`.
47    Rational,
48    /// XML Schema `decimal`.
49    Decimal,
50    /// XML Schema `positiveInteger`.
51    PositiveInteger,
52    /// A semantically identified reference with neither GUID nor URI.
53    EmptyReference,
54    /// XML Schema `dateTime`.
55    CreationDate,
56    /// XML Schema `anyURI`.
57    Uri,
58    /// XML Schema `nonNegativeInteger`.
59    NonNegativeInteger,
60    /// XML Schema `base64Binary`.
61    Base64Binary,
62}
63
64/// An ISO 23387 GUID, preserving its validated source spelling.
65#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
66pub struct Guid(String);
67
68impl Guid {
69    /// Returns the original validated lexical value.
70    #[must_use]
71    pub fn as_str(&self) -> &str {
72        &self.0
73    }
74}
75
76impl FromStr for Guid {
77    type Err = ValueError;
78
79    fn from_str(value: &str) -> Result<Self, Self::Err> {
80        const HYPHENS: [usize; 4] = [8, 13, 18, 23];
81        let valid = value.len() == 36
82            && value.bytes().enumerate().all(|(index, byte)| {
83                if HYPHENS.contains(&index) {
84                    byte == b'-'
85                } else {
86                    byte.is_ascii_hexdigit()
87                }
88            });
89        valid
90            .then(|| Self(value.to_owned()))
91            .ok_or_else(|| ValueError::new(ValueErrorKind::Guid, value))
92    }
93}
94
95impl fmt::Display for Guid {
96    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
97        formatter.write_str(&self.0)
98    }
99}
100
101/// XML Schema `language` used by DT and importing standards.
102#[derive(Debug, Clone, PartialEq, Eq, Hash)]
103pub struct Language(String);
104
105impl Language {
106    #[must_use]
107    pub fn as_str(&self) -> &str {
108        &self.0
109    }
110}
111
112impl FromStr for Language {
113    type Err = ValueError;
114
115    fn from_str(value: &str) -> Result<Self, Self::Err> {
116        let value = collapse_whitespace(value);
117        is_language(&value)
118            .then(|| Self(value.clone()))
119            .ok_or_else(|| ValueError::new(ValueErrorKind::Language, value))
120    }
121}
122
123/// XML Schema `dateTime` value after whitespace collapsing and lexical validation.
124#[derive(Debug, Clone, PartialEq, Eq, Hash)]
125pub struct DateTime(String);
126
127impl DateTime {
128    #[must_use]
129    pub fn as_str(&self) -> &str {
130        &self.0
131    }
132}
133
134impl FromStr for DateTime {
135    type Err = ValueError;
136
137    fn from_str(value: &str) -> Result<Self, Self::Err> {
138        let value = collapse_whitespace(value);
139        is_xs_datetime(&value)
140            .then(|| Self(value.clone()))
141            .ok_or_else(|| ValueError::new(ValueErrorKind::CreationDate, value))
142    }
143}
144
145/// XML Schema 1.0 `anyURI` after whitespace collapsing.
146///
147/// Its lexical space is broader than an ASCII URI-reference: XML Schema's
148/// escaping procedure admits Unicode and spaces that become percent-encoded in
149/// the corresponding URI. The stored value retains that pre-escaped spelling.
150#[derive(Debug, Clone, PartialEq, Eq, Hash)]
151pub struct AnyUri(String);
152
153impl AnyUri {
154    #[must_use]
155    pub fn as_str(&self) -> &str {
156        &self.0
157    }
158}
159
160impl FromStr for AnyUri {
161    type Err = ValueError;
162
163    fn from_str(value: &str) -> Result<Self, Self::Err> {
164        let value = collapse_whitespace(value);
165        value
166            .chars()
167            .all(is_xml_10_character)
168            .then(|| Self(value.clone()))
169            .ok_or_else(|| ValueError::new(ValueErrorKind::Uri, value))
170    }
171}
172
173/// ISO 23387 multilingual text.
174#[derive(Debug, Clone, PartialEq, Eq, Hash)]
175pub struct MultiLanguageText {
176    language: Language,
177    text: String,
178}
179
180impl MultiLanguageText {
181    /// Creates text after validating the XML Schema `language` lexeme.
182    pub fn new(language: impl Into<String>, text: impl Into<String>) -> Result<Self, ValueError> {
183        let language = language.into().parse()?;
184        Ok(Self {
185            language,
186            text: text.into(),
187        })
188    }
189
190    /// Language tag exactly as supplied.
191    #[must_use]
192    pub fn language(&self) -> &str {
193        self.language.as_str()
194    }
195
196    /// Text value exactly as supplied.
197    #[must_use]
198    pub fn text(&self) -> &str {
199        &self.text
200    }
201}
202
203/// An ISO 23387 reference by GUID, URI, or both.
204#[derive(Debug, Clone, PartialEq, Eq, Hash)]
205pub struct Reference {
206    guid: Option<Guid>,
207    uri: Option<AnyUri>,
208}
209
210impl Reference {
211    /// Creates the exact XSD contract. Annex E permits both attributes to be absent.
212    #[must_use]
213    pub const fn new(guid: Option<Guid>, uri: Option<AnyUri>) -> Self {
214        Self { guid, uri }
215    }
216
217    /// Creates a semantically identified reference, rejecting the XSD-valid empty state.
218    pub fn identified(guid: Option<Guid>, uri: Option<AnyUri>) -> Result<Self, ValueError> {
219        if guid.is_none() && uri.is_none() {
220            return Err(ValueError::new(ValueErrorKind::EmptyReference, ""));
221        }
222        Ok(Self::new(guid, uri))
223    }
224
225    #[must_use]
226    pub const fn is_empty(&self) -> bool {
227        self.guid.is_none() && self.uri.is_none()
228    }
229
230    /// Referenced GUID, when present.
231    #[must_use]
232    pub const fn guid(&self) -> Option<&Guid> {
233        self.guid.as_ref()
234    }
235
236    /// Referenced URI, when present.
237    #[must_use]
238    pub fn uri(&self) -> Option<&str> {
239        self.uri.as_ref().map(AnyUri::as_str)
240    }
241}
242
243/// Generates a slice getter and an appending adder for a repeatable field.
244macro_rules! list_accessors {
245    ($($(#[$doc:meta])* $field:ident: $ty:ty => $getter:ident, $adder:ident;)*) => {
246        $(
247            $(#[$doc])*
248            #[must_use]
249            pub fn $getter(&self) -> &[$ty] {
250                &self.$field
251            }
252            $(#[$doc])*
253            pub fn $adder(&mut self, value: $ty) {
254                self.$field.push(value);
255            }
256        )*
257    };
258}
259
260/// Owned ISO 23387 `ConceptType`: every attribute and child it declares.
261///
262/// Each field corresponds to exactly one declared child element (or
263/// attribute), and every repeatable child is a `Vec`, so a value decoded by
264/// [`Concept`]-bearing `from_element` codecs holds everything the schema
265/// permits. `ConceptType` content is a repeating choice, so child order
266/// carries no meaning and is not stored.
267///
268/// The schema requires at least one child from the choice, and `new` always
269/// supplies a name. `from_identity` builds an empty concept for decoders and
270/// callers that add content afterwards.
271#[derive(Debug, Clone, PartialEq, Eq)]
272pub struct Concept {
273    guid: Guid,
274    date_of_creation: DateTime,
275    about: Option<AnyUri>,
276    names: Vec<MultiLanguageText>,
277    definitions: Vec<MultiLanguageText>,
278    descriptions: Vec<MultiLanguageText>,
279    examples: Vec<MultiLanguageText>,
280    reference_document_refs: Vec<Reference>,
281    similar_to_refs: Vec<Reference>,
282    replaced_objects_refs: Vec<Reference>,
283    dictionary_refs: Vec<Reference>,
284    languages_of_creator: Vec<Language>,
285    countries_of_origin: Vec<String>,
286    visual_representations: Vec<Base64Binary>,
287    major_versions: Vec<NonNegativeInteger>,
288    minor_versions: Vec<NonNegativeInteger>,
289    statuses: Vec<String>,
290    deprecation_explanations: Vec<String>,
291}
292
293impl Concept {
294    /// Creates a concept with one name and one definition.
295    #[must_use]
296    pub fn new(
297        guid: Guid,
298        date_of_creation: DateTime,
299        first_name: MultiLanguageText,
300        definition: MultiLanguageText,
301    ) -> Self {
302        let mut concept = Self::from_identity(guid, date_of_creation);
303        concept.names.push(first_name);
304        concept.definitions.push(definition);
305        concept
306    }
307
308    /// Creates a concept carrying only its required attributes.
309    ///
310    /// It is not schema-valid until at least one child is added.
311    #[must_use]
312    pub const fn from_identity(guid: Guid, date_of_creation: DateTime) -> Self {
313        Self {
314            guid,
315            date_of_creation,
316            about: None,
317            names: Vec::new(),
318            definitions: Vec::new(),
319            descriptions: Vec::new(),
320            examples: Vec::new(),
321            reference_document_refs: Vec::new(),
322            similar_to_refs: Vec::new(),
323            replaced_objects_refs: Vec::new(),
324            dictionary_refs: Vec::new(),
325            languages_of_creator: Vec::new(),
326            countries_of_origin: Vec::new(),
327            visual_representations: Vec::new(),
328            major_versions: Vec::new(),
329            minor_versions: Vec::new(),
330            statuses: Vec::new(),
331            deprecation_explanations: Vec::new(),
332        }
333    }
334
335    #[must_use]
336    pub const fn guid(&self) -> &Guid {
337        &self.guid
338    }
339
340    #[must_use]
341    pub fn date_of_creation(&self) -> &str {
342        self.date_of_creation.as_str()
343    }
344
345    /// The `dt:about` attribute, when present.
346    #[must_use]
347    pub fn about(&self) -> Option<&str> {
348        self.about.as_ref().map(AnyUri::as_str)
349    }
350
351    pub fn set_about(&mut self, value: Option<AnyUri>) {
352        self.about = value;
353    }
354
355    /// The first `Definition`, when present.
356    ///
357    /// `ConceptType` permits any number of definitions (typically one per
358    /// language); use [`Concept::definitions`] to see all of them.
359    #[must_use]
360    pub fn definition(&self) -> Option<&MultiLanguageText> {
361        self.definitions.first()
362    }
363
364    /// Replaces every definition with `definition`.
365    pub fn set_definition(&mut self, definition: MultiLanguageText) {
366        self.definitions.clear();
367        self.definitions.push(definition);
368    }
369
370    /// `ReferenceDocumentRef` children.
371    #[deprecated(since = "0.3.0", note = "use `reference_document_refs`")]
372    #[must_use]
373    pub fn references(&self) -> &[Reference] {
374        &self.reference_document_refs
375    }
376
377    /// Appends a `ReferenceDocumentRef`.
378    #[deprecated(since = "0.3.0", note = "use `add_reference_document_ref`")]
379    pub fn add_reference(&mut self, reference: Reference) {
380        self.reference_document_refs.push(reference);
381    }
382
383    list_accessors! {
384        /// `Name` children.
385        names: MultiLanguageText => names, add_name;
386        /// `Definition` children.
387        definitions: MultiLanguageText => definitions, add_definition;
388        /// `Description` children.
389        descriptions: MultiLanguageText => descriptions, add_description;
390        /// `Example` children.
391        examples: MultiLanguageText => examples, add_example;
392        /// `ReferenceDocumentRef` children.
393        reference_document_refs: Reference => reference_document_refs, add_reference_document_ref;
394        /// `SimilarToRef` children.
395        similar_to_refs: Reference => similar_to_refs, add_similar_to_ref;
396        /// `ReplacedObjectsRef` children.
397        replaced_objects_refs: Reference => replaced_objects_refs, add_replaced_objects_ref;
398        /// `DictionaryRef` children.
399        dictionary_refs: Reference => dictionary_refs, add_dictionary_ref;
400        /// `LanguageOfCreator` children.
401        languages_of_creator: Language => languages_of_creator, add_language_of_creator;
402        /// `CountryOfOrigin` children.
403        countries_of_origin: String => countries_of_origin, add_country_of_origin;
404        /// `VisualRepresentation` children.
405        visual_representations: Base64Binary => visual_representations, add_visual_representation;
406        /// `MajorVersion` children.
407        major_versions: NonNegativeInteger => major_versions, add_major_version;
408        /// `MinorVersion` children.
409        minor_versions: NonNegativeInteger => minor_versions, add_minor_version;
410        /// `Status` children.
411        statuses: String => statuses, add_status;
412        /// `DeprecationExplanation` children.
413        deprecation_explanations: String => deprecation_explanations, add_deprecation_explanation;
414    }
415
416    pub(crate) const fn date_of_creation_value(&self) -> &DateTime {
417        &self.date_of_creation
418    }
419
420    pub(crate) const fn about_value(&self) -> Option<&AnyUri> {
421        self.about.as_ref()
422    }
423}
424
425/// ISO 23387 property data-type names with forward-compatible retention.
426#[derive(Debug, Clone, PartialEq, Eq, Hash)]
427pub enum DataTypeName {
428    Boolean,
429    Integer,
430    Rational,
431    Real,
432    Complex,
433    String,
434    DateTime,
435    /// A future or extension value retained verbatim.
436    Other(String),
437}
438
439impl DataTypeName {
440    /// Wire spelling.
441    #[must_use]
442    pub fn as_str(&self) -> &str {
443        match self {
444            Self::Boolean => "BOOLEAN",
445            Self::Integer => "INTEGER",
446            Self::Rational => "RATIONAL",
447            Self::Real => "REAL",
448            Self::Complex => "COMPLEX",
449            Self::String => "STRING",
450            Self::DateTime => "DATETIME",
451            Self::Other(value) => value,
452        }
453    }
454}
455
456impl From<&str> for DataTypeName {
457    fn from(value: &str) -> Self {
458        match value {
459            "BOOLEAN" => Self::Boolean,
460            "INTEGER" => Self::Integer,
461            "RATIONAL" => Self::Rational,
462            "REAL" => Self::Real,
463            "COMPLEX" => Self::Complex,
464            "STRING" => Self::String,
465            "DATETIME" => Self::DateTime,
466            other => Self::Other(other.to_owned()),
467        }
468    }
469}
470
471/// Unit scale with forward-compatible retention.
472#[derive(Debug, Clone, PartialEq, Eq, Hash)]
473pub enum Scale {
474    Linear,
475    Logarithmic,
476    Other(String),
477}
478
479impl From<&str> for Scale {
480    fn from(value: &str) -> Self {
481        match value {
482            "LINEAR" => Self::Linear,
483            "LOGARITHMIC" => Self::Logarithmic,
484            other => Self::Other(other.to_owned()),
485        }
486    }
487}
488
489impl Scale {
490    /// Wire spelling; the inverse of `From<&str>`.
491    #[must_use]
492    pub fn as_str(&self) -> &str {
493        match self {
494            Self::Linear => "LINEAR",
495            Self::Logarithmic => "LOGARITHMIC",
496            Self::Other(value) => value,
497        }
498    }
499}
500
501/// Unit logarithm base with forward-compatible retention.
502#[derive(Debug, Clone, PartialEq, Eq, Hash)]
503pub enum Base {
504    One,
505    Two,
506    E,
507    Pi,
508    Ten,
509    Other(String),
510}
511
512impl From<&str> for Base {
513    fn from(value: &str) -> Self {
514        match value {
515            "ONE" => Self::One,
516            "TWO" => Self::Two,
517            "E" => Self::E,
518            "PI" => Self::Pi,
519            "TEN" => Self::Ten,
520            other => Self::Other(other.to_owned()),
521        }
522    }
523}
524
525impl Base {
526    /// Wire spelling; the inverse of `From<&str>`.
527    #[must_use]
528    pub fn as_str(&self) -> &str {
529        match self {
530            Self::One => "ONE",
531            Self::Two => "TWO",
532            Self::E => "E",
533            Self::Pi => "PI",
534            Self::Ten => "TEN",
535            Self::Other(value) => value,
536        }
537    }
538}
539
540/// XML Schema decimal preserving its whitespace-collapsed validated lexeme.
541#[derive(Debug, Clone, PartialEq, Eq, Hash)]
542pub struct Decimal(String);
543
544impl Decimal {
545    #[must_use]
546    pub fn as_str(&self) -> &str {
547        &self.0
548    }
549}
550
551impl FromStr for Decimal {
552    type Err = ValueError;
553
554    fn from_str(value: &str) -> Result<Self, Self::Err> {
555        let value = collapse_whitespace(value);
556        let unsigned = value.strip_prefix(['+', '-']).unwrap_or(&value);
557        let mut parts = unsigned.split('.');
558        let integer = parts.next().unwrap_or_default();
559        let fraction = parts.next();
560        let valid_integer = integer.bytes().all(|byte| byte.is_ascii_digit());
561        let valid_fraction =
562            fraction.is_none_or(|part| part.bytes().all(|byte| byte.is_ascii_digit()));
563        let has_digit = !integer.is_empty() || fraction.is_some_and(|part| !part.is_empty());
564        let valid = valid_integer && valid_fraction && has_digit && parts.next().is_none();
565        valid
566            .then(|| Self(value.clone()))
567            .ok_or_else(|| ValueError::new(ValueErrorKind::Decimal, value))
568    }
569}
570
571/// XML Schema `positiveInteger`, preserved after whitespace collapse.
572#[derive(Debug, Clone, PartialEq, Eq, Hash)]
573pub struct PositiveInteger(String);
574
575impl PositiveInteger {
576    #[must_use]
577    pub fn as_str(&self) -> &str {
578        &self.0
579    }
580}
581
582impl FromStr for PositiveInteger {
583    type Err = ValueError;
584
585    fn from_str(value: &str) -> Result<Self, Self::Err> {
586        let value = collapse_whitespace(value);
587        let digits = value.strip_prefix('+').unwrap_or(&value);
588        let valid = !digits.is_empty()
589            && digits.bytes().all(|byte| byte.is_ascii_digit())
590            && digits.bytes().any(|byte| byte != b'0');
591        valid
592            .then(|| Self(value.clone()))
593            .ok_or_else(|| ValueError::new(ValueErrorKind::PositiveInteger, value))
594    }
595}
596
597/// XML Schema `nonNegativeInteger`, preserving the validated source lexeme.
598///
599/// The lexeme is kept verbatim after whitespace collapse (`007` stays `007`),
600/// so the type is unbounded and round trips are exact.
601#[derive(Debug, Clone, PartialEq, Eq, Hash)]
602pub struct NonNegativeInteger(String);
603
604impl NonNegativeInteger {
605    #[must_use]
606    pub fn as_str(&self) -> &str {
607        &self.0
608    }
609}
610
611impl FromStr for NonNegativeInteger {
612    type Err = ValueError;
613
614    /// Accepts `[+]?[0-9]+`, and `-0` style zero, per the XSD lexical space.
615    fn from_str(value: &str) -> Result<Self, Self::Err> {
616        let value = collapse_whitespace(value);
617        let (negative, digits) = match value.strip_prefix('-') {
618            Some(rest) => (true, rest),
619            None => (false, value.strip_prefix('+').unwrap_or(&value)),
620        };
621        let valid = !digits.is_empty()
622            && digits.bytes().all(|byte| byte.is_ascii_digit())
623            && (!negative || digits.bytes().all(|byte| byte == b'0'));
624        valid
625            .then(|| Self(value.clone()))
626            .ok_or_else(|| ValueError::new(ValueErrorKind::NonNegativeInteger, value))
627    }
628}
629
630/// XML Schema `base64Binary`, preserving the validated source lexeme.
631///
632/// Validation follows the XSD 1.1 canonical-lexical grammar: whitespace-
633/// separated base64 characters in groups of four, with at most two `=` pad
634/// characters at the end whose preceding character is restricted so the
635/// padding bits are zero. The empty value is valid (zero octets).
636#[derive(Debug, Clone, PartialEq, Eq, Hash)]
637pub struct Base64Binary(String);
638
639impl Base64Binary {
640    #[must_use]
641    pub fn as_str(&self) -> &str {
642        &self.0
643    }
644}
645
646impl FromStr for Base64Binary {
647    type Err = ValueError;
648
649    fn from_str(value: &str) -> Result<Self, Self::Err> {
650        let collapsed = collapse_whitespace(value);
651        is_base64_lexeme(&collapsed)
652            .then(|| Self(collapsed.clone()))
653            .ok_or_else(|| ValueError::new(ValueErrorKind::Base64Binary, collapsed))
654    }
655}
656
657fn is_base64_lexeme(value: &str) -> bool {
658    let symbols: Vec<u8> = value.bytes().filter(|byte| *byte != b' ').collect();
659    if !symbols.len().is_multiple_of(4) {
660        return false;
661    }
662    let padding = symbols
663        .iter()
664        .rev()
665        .take_while(|byte| **byte == b'=')
666        .count();
667    if padding > 2 {
668        return false;
669    }
670    let body = &symbols[..symbols.len() - padding];
671    if !body
672        .iter()
673        .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'+' | b'/'))
674    {
675        return false;
676    }
677    // The last data character before padding may only carry zero padding bits:
678    // one pad => B04 alphabet (value % 4 == 0), two pads => B16 (value % 16 == 0).
679    match (padding, body.last()) {
680        (0, _) | (_, None) => padding == 0,
681        (1, Some(&last)) => base64_value(last).is_multiple_of(4),
682        (2, Some(&last)) => base64_value(last).is_multiple_of(16),
683        _ => false,
684    }
685}
686
687const fn base64_value(byte: u8) -> u8 {
688    match byte {
689        b'A'..=b'Z' => byte - b'A',
690        b'a'..=b'z' => byte - b'a' + 26,
691        b'0'..=b'9' => byte - b'0' + 52,
692        b'+' => 62,
693        _ => 63,
694    }
695}
696
697/// ISO 23387 rational value preserving the validated source lexeme.
698#[derive(Debug, Clone, PartialEq, Eq, Hash)]
699pub struct Rational(String);
700
701impl Rational {
702    #[must_use]
703    pub fn as_str(&self) -> &str {
704        &self.0
705    }
706}
707
708impl FromStr for Rational {
709    type Err = ValueError;
710
711    fn from_str(value: &str) -> Result<Self, Self::Err> {
712        let unsigned = value.strip_prefix(['+', '-']).unwrap_or(value);
713        let mut parts = unsigned.split('/');
714        let numerator = parts.next().unwrap_or_default();
715        let denominator = parts.next();
716        let valid_numerator =
717            !numerator.is_empty() && numerator.bytes().all(|b| b.is_ascii_digit());
718        let valid_denominator = denominator.is_none_or(|part| {
719            part.bytes()
720                .next()
721                .is_some_and(|first| matches!(first, b'1'..=b'9'))
722                && part.bytes().all(|b| b.is_ascii_digit())
723        });
724        let valid = valid_numerator && valid_denominator && parts.next().is_none();
725        valid
726            .then(|| Self(value.to_owned()))
727            .ok_or_else(|| ValueError::new(ValueErrorKind::Rational, value))
728    }
729}
730
731fn collapse_whitespace(value: &str) -> String {
732    let mut output = String::with_capacity(value.len());
733    let mut pending_space = false;
734    for character in value.chars() {
735        if matches!(character, ' ' | '\t' | '\r' | '\n') {
736            pending_space = !output.is_empty();
737        } else {
738            if pending_space {
739                output.push(' ');
740                pending_space = false;
741            }
742            output.push(character);
743        }
744    }
745    output
746}
747
748fn is_xml_10_character(value: char) -> bool {
749    matches!(value, '\u{9}' | '\u{A}' | '\u{D}')
750        || ('\u{20}'..='\u{D7FF}').contains(&value)
751        || ('\u{E000}'..='\u{FFFD}').contains(&value)
752        || ('\u{10000}'..='\u{10FFFF}').contains(&value)
753}
754
755fn is_language(value: &str) -> bool {
756    let mut parts = value.split('-');
757    let Some(first) = parts.next() else {
758        return false;
759    };
760    let first_valid =
761        (1..=8).contains(&first.len()) && first.bytes().all(|b| b.is_ascii_alphabetic());
762    first_valid
763        && parts.all(|part| {
764            (1..=8).contains(&part.len()) && part.bytes().all(|b| b.is_ascii_alphanumeric())
765        })
766}
767
768fn is_xs_datetime(value: &str) -> bool {
769    let Some((date, time_and_zone)) = value.split_once('T') else {
770        return false;
771    };
772    if time_and_zone.contains('T') || !valid_xs_date(date) {
773        return false;
774    }
775    let (time, zone) = split_timezone(time_and_zone);
776    valid_xs_time(time) && zone.is_none_or(valid_timezone)
777}
778
779fn valid_xs_date(value: &str) -> bool {
780    let unsigned = value.strip_prefix('-').unwrap_or(value);
781    let mut parts = unsigned.split('-');
782    let (Some(year), Some(month), Some(day)) = (parts.next(), parts.next(), parts.next()) else {
783        return false;
784    };
785    if parts.next().is_some()
786        || year.len() < 4
787        || (year.len() > 4 && year.starts_with('0'))
788        || !year.bytes().all(|b| b.is_ascii_digit())
789        || year.bytes().all(|b| b == b'0')
790        || month.len() != 2
791        || day.len() != 2
792    {
793        return false;
794    }
795    let (Ok(month), Ok(day)) = (month.parse::<u8>(), day.parse::<u8>()) else {
796        return false;
797    };
798    let year_mod_400 = year.bytes().fold(0_u16, |value, digit| {
799        (value * 10 + u16::from(digit - b'0')) % 400
800    });
801    let leap = year_mod_400 % 4 == 0 && (year_mod_400 % 100 != 0 || year_mod_400 == 0);
802    let max_day = match month {
803        1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
804        4 | 6 | 9 | 11 => 30,
805        2 if leap => 29,
806        2 => 28,
807        _ => return false,
808    };
809    (1..=max_day).contains(&day)
810}
811
812fn valid_xs_time(value: &str) -> bool {
813    let mut parts = value.split(':');
814    let (Some(hour), Some(minute), Some(second)) = (parts.next(), parts.next(), parts.next())
815    else {
816        return false;
817    };
818    if parts.next().is_some() || hour.len() != 2 || minute.len() != 2 {
819        return false;
820    }
821    let (Ok(hour), Ok(minute)) = (hour.parse::<u8>(), minute.parse::<u8>()) else {
822        return false;
823    };
824    let mut second_parts = second.split('.');
825    let whole = second_parts.next().unwrap_or_default();
826    let fraction = second_parts.next();
827    let valid_second = whole.len() == 2
828        && whole.bytes().all(|b| b.is_ascii_digit())
829        && whole.parse::<u8>().is_ok_and(|v| v <= 59)
830        && fraction.is_none_or(|v| !v.is_empty() && v.bytes().all(|b| b.is_ascii_digit()))
831        && second_parts.next().is_none();
832    valid_second
833        && minute <= 59
834        && (hour <= 23
835            || (hour == 24
836                && minute == 0
837                && whole == "00"
838                && fraction.is_none_or(|value| value.bytes().all(|byte| byte == b'0'))))
839}
840
841fn split_timezone(value: &str) -> (&str, Option<&str>) {
842    if let Some(time) = value.strip_suffix('Z') {
843        return (time, Some("Z"));
844    }
845    if value.len() >= 6 {
846        let boundary = value.len() - 6;
847        if matches!(value.as_bytes()[boundary], b'+' | b'-') {
848            return (&value[..boundary], Some(&value[boundary..]));
849        }
850    }
851    (value, None)
852}
853
854fn valid_timezone(value: &str) -> bool {
855    if value == "Z" {
856        return true;
857    }
858    let bytes = value.as_bytes();
859    if bytes.len() != 6 || !matches!(bytes[0], b'+' | b'-') || bytes[3] != b':' {
860        return false;
861    }
862    let (Ok(hour), Ok(minute)) = (value[1..3].parse::<u8>(), value[4..6].parse::<u8>()) else {
863        return false;
864    };
865    hour <= 14 && minute <= 59 && (hour != 14 || minute == 0)
866}