1use crate::uri;
14
15#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
17pub enum Builtin {
18 AnySimpleType,
20 String,
22 NormalizedString,
24 Token,
26 Language,
28 Name,
30 NcName,
32 Id,
34 Decimal,
36 Integer,
38 Boolean,
40 Date,
42 DateTime,
44 Time,
46 Base64Binary,
48 AnyUri,
50 IdRef,
52 Entity,
55 NmToken,
57 NonPositiveInteger,
59 NegativeInteger,
61 Long,
63 Int,
65 Short,
67 Byte,
69 NonNegativeInteger,
71 UnsignedLong,
73 UnsignedInt,
75 UnsignedShort,
77 UnsignedByte,
79 PositiveInteger,
81 Float,
83 Double,
85 Duration,
87 GYearMonth,
89 GYear,
91 GMonthDay,
93 GDay,
95 GMonth,
97 HexBinary,
99 QName,
101 Notation,
103 NmTokens,
105 IdRefs,
107 Entities,
109}
110
111#[derive(Debug, Clone, Copy, PartialEq, Eq)]
113pub(crate) enum WhiteSpace {
114 Preserve,
115 Replace,
116 Collapse,
117}
118
119impl Builtin {
120 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 #[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 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 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 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 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 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 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 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 pub(crate) fn value_key(self, value: &str) -> Option<std::borrow::Cow<'_, str>> {
412 use std::borrow::Cow;
413 match self {
414 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 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 Self::Base64Binary => Some(if value.contains(' ') {
453 Cow::Owned(value.replace(' ', ""))
454 } else {
455 Cow::Borrowed(value)
456 }),
457 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 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 pub(crate) fn is_valid_raw(self, raw: &str) -> bool {
507 match self {
508 Self::AnySimpleType | Self::String | Self::NormalizedString | Self::Token => true,
509 Self::Base64Binary => is_base64_skipping(raw, is_xml_space_byte),
512 _ => self.is_valid(&normalize(raw, self.white_space())),
513 }
514 }
515}
516
517pub(crate) fn is_xml_space(c: char) -> bool {
519 matches!(c, ' ' | '\t' | '\n' | '\r')
520}
521
522fn is_xml_space_byte(b: u8) -> bool {
524 matches!(b, b' ' | b'\t' | b'\n' | b'\r')
525}
526
527pub(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 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
562pub(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
575pub(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
602pub(crate) fn is_integer(value: &str) -> bool {
604 is_digits(value.strip_prefix(['+', '-']).unwrap_or(value))
605}
606
607fn 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
618fn 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
631pub(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
644pub(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 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
692fn 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
702fn month(s: &str) -> Option<u32> {
704 two_digits(s).filter(|m| (1..=12).contains(m))
705}
706
707pub(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
714pub(crate) fn is_g_year(value: &str) -> bool {
716 split_timezone(value).is_some_and(is_year)
717}
718
719pub(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
737pub(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
745pub(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
754pub(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
759pub(crate) fn is_nmtoken(value: &str) -> bool {
761 !value.is_empty() && value.chars().all(is_name_char)
762}
763
764pub(crate) fn is_list(value: &str, item: fn(&str) -> bool) -> bool {
768 !value.is_empty() && value.split(' ').all(item)
769}
770
771pub(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
781pub(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
791pub(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
797pub(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
803pub(crate) fn is_ncname(value: &str) -> bool {
805 !value.contains(':') && is_name(value)
806}
807
808pub(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
819fn is_base64_char(b: u8) -> bool {
821 b.is_ascii_alphanumeric() || b == b'+' || b == b'/'
822}
823
824pub(crate) fn is_base64(value: &str) -> bool {
830 is_base64_skipping(value, |b| b == b' ')
831}
832
833fn 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 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
871fn is_leap_year(digits: &str) -> bool {
875 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
881fn 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
905fn 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
927fn 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 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 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 #[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 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 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 assert!(matches!(
1451 normalize("\n 12.50\t", WhiteSpace::Collapse),
1452 std::borrow::Cow::Borrowed("12.50")
1453 ));
1454 }
1455
1456 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 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 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 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}