xmlschema 0.0.8

XML Schema (XSD) validation for Rust, with zero unsafe code
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
// SPDX-License-Identifier: MIT OR Apache-2.0
// Copyright (c) 2026 xmlschema. All rights reserved.

//! The lexical and value rules of the XSD built-in datatypes.
//!
//! Each type is checked on the values that distinguish it from its
//! nearest relative, because that is where a collapsed lattice used to
//! agree by accident: `xs:byte` differs from `xs:integer` only past
//! 127, and `xs:NCName` from `xs:string` only when a colon appears.

use xmlschema::datatype::{Datatype, WhiteSpace};

fn ty(name: &str) -> Datatype {
    Datatype::from_name(name)
        .unwrap_or_else(|| panic!("`{name}` should resolve"))
}

#[test]
fn a_prefix_is_ignored_when_resolving_a_name() {
    assert_eq!(ty("xs:integer"), ty("integer"));
    assert_eq!(ty("xsd:integer"), ty("integer"));
    assert_eq!(Datatype::from_name("notAType"), None);
    assert_eq!(Datatype::from_name(""), None);
}

#[test]
fn whitespace_processing_differs_by_type() {
    assert_eq!(ty("string").white_space(), WhiteSpace::Preserve);
    assert_eq!(ty("normalizedString").white_space(), WhiteSpace::Replace);
    assert_eq!(ty("token").white_space(), WhiteSpace::Collapse);
    assert_eq!(ty("integer").white_space(), WhiteSpace::Collapse);

    // Preserve keeps the value exactly; replace turns tabs into
    // spaces; collapse also squeezes runs and trims.
    assert_eq!(ty("string").normalise("  a\tb  "), "  a\tb  ");
    assert_eq!(ty("normalizedString").normalise("a\tb"), "a b");
    assert_eq!(ty("token").normalise("  a\t\tb  "), "a b");
}

#[test]
fn booleans_take_four_forms_and_no_others() {
    for v in ["true", "false", "1", "0"] {
        assert!(ty("boolean").accepts(v), "{v}");
    }
    for v in ["True", "FALSE", "yes", "2", ""] {
        assert!(!ty("boolean").accepts(v), "{v}");
    }
}

#[test]
fn numeric_lexical_forms_are_distinguished() {
    assert!(ty("integer").accepts("+5"));
    assert!(ty("integer").accepts("-5"));
    assert!(ty("integer").accepts("007"));
    assert!(!ty("integer").accepts("5.0"));
    assert!(!ty("integer").accepts("5e3"));
    assert!(!ty("integer").accepts("+"));
    assert!(!ty("integer").accepts(""));

    assert!(ty("decimal").accepts("5.0"));
    assert!(ty("decimal").accepts(".5"));
    assert!(ty("decimal").accepts("5."));
    assert!(!ty("decimal").accepts("5e3"));
    assert!(!ty("decimal").accepts("."));

    assert!(ty("double").accepts("5e3"));
    assert!(ty("double").accepts("-5.0E-3"));
    assert!(ty("double").accepts("INF"));
    assert!(ty("double").accepts("-INF"));
    assert!(ty("double").accepts("NaN"));
    assert!(!ty("double").accepts("inf"));
    assert!(!ty("double").accepts("5e"));
}

#[test]
fn hex_and_base64_check_their_shape() {
    assert!(ty("hexBinary").accepts("0FB7"));
    assert!(ty("hexBinary").accepts(""));
    assert!(!ty("hexBinary").accepts("0FB"), "odd length");
    assert!(!ty("hexBinary").accepts("0FBG"), "not a hex digit");

    assert!(ty("base64Binary").accepts("QUJD"));
    assert!(ty("base64Binary").accepts("QQ=="));
    assert!(!ty("base64Binary").accepts("QUJ"), "not a multiple of four");
    assert!(!ty("base64Binary").accepts("QU*D"));
}

#[test]
fn names_follow_the_xml_productions() {
    assert!(ty("Name").accepts("a:b"));
    assert!(ty("Name").accepts("_x"));
    assert!(
        !ty("Name").accepts("1a"),
        "a name may not start with a digit"
    );
    assert!(!ty("Name").accepts("-a"));
    assert!(!ty("Name").accepts(""));

    assert!(ty("NCName").accepts("abc"));
    assert!(!ty("NCName").accepts("a:b"), "no colon in an NCName");

    assert!(ty("NMTOKEN").accepts("-a.1"));
    assert!(!ty("NMTOKEN").accepts("a b"));
    assert!(!ty("NMTOKEN").accepts(""));

    assert!(ty("NMTOKENS").accepts("a b c"));
    assert!(!ty("NMTOKENS").accepts(""), "the empty list is not a value");

    assert!(ty("QName").accepts("p:l"));
    assert!(ty("QName").accepts("l"));
    assert!(!ty("QName").accepts("p:l:x"));
    assert!(!ty("QName").accepts(":l"));
}

#[test]
fn language_tags_follow_rfc_3066() {
    assert!(ty("language").accepts("en"));
    assert!(ty("language").accepts("en-GB"));
    assert!(ty("language").accepts("x-klingon-1"));
    assert!(
        !ty("language").accepts("e0"),
        "the primary tag is alphabetic"
    );
    assert!(!ty("language").accepts("en-"), "an empty subtag");
    assert!(!ty("language").accepts("toolongprimary"));
}

#[test]
fn the_calendar_is_real() {
    assert!(ty("date").accepts("2004-02-29"), "a leap year");
    assert!(!ty("date").accepts("2001-02-29"), "not a leap year");
    assert!(!ty("date").accepts("1900-02-29"), "a century that is not");
    assert!(ty("date").accepts("2000-02-29"), "a century that is");
    assert!(!ty("date").accepts("2001-04-31"), "April has thirty days");
    assert!(!ty("date").accepts("2001-13-01"));
    assert!(!ty("date").accepts("0000-01-01"), "there is no year zero");
    // Timezones are permitted on every date and time form.
    assert!(ty("date").accepts("2001-01-01Z"));
    assert!(ty("date").accepts("2001-01-01+05:30"));
    assert!(ty("date").accepts("-2001-01-01"), "a negative year");
}

#[test]
fn times_permit_midnight_at_the_end_of_a_day() {
    assert!(ty("time").accepts("00:00:00"));
    assert!(ty("time").accepts("23:59:59.999"));
    assert!(ty("time").accepts("24:00:00"), "the end of a day");
    assert!(!ty("time").accepts("24:00:01"), "and nothing past it");
    assert!(!ty("time").accepts("23:60:00"));
    assert!(!ty("time").accepts("23:59"), "seconds are not optional");
    assert!(!ty("time").accepts("23:59:59."), "an empty fraction");
}

#[test]
fn durations_need_a_component_and_an_order() {
    assert!(ty("duration").accepts("P1Y2M3DT4H5M6S"));
    assert!(ty("duration").accepts("-P1Y"));
    assert!(ty("duration").accepts("PT0.5S"));
    assert!(!ty("duration").accepts("P"), "no component");
    assert!(!ty("duration").accepts("P1YT"), "a T with no time");
    assert!(!ty("duration").accepts("P1S"), "S belongs after T");
    assert!(!ty("duration").accepts("1Y"), "no P");
    assert!(
        !ty("duration").accepts("P1.5Y"),
        "only seconds may be fractional"
    );
}

#[test]
fn the_gregorian_forms_are_distinct() {
    assert!(ty("gYear").accepts("2001"));
    assert!(ty("gMonth").accepts("--02"));
    assert!(ty("gMonth").accepts("--02--"), "the original 1.0 form");
    assert!(ty("gDay").accepts("---15"));
    assert!(ty("gMonthDay").accepts("--02-29"));
    assert!(ty("gYearMonth").accepts("2001-02"));
    assert!(!ty("gMonth").accepts("02"));
    assert!(!ty("gDay").accepts("--15"));
    assert!(!ty("gMonthDay").accepts("--13-01"));
}

#[test]
fn only_ordered_types_have_an_ordering() {
    assert!(ty("integer").is_ordered());
    assert!(ty("date").is_ordered());
    assert!(ty("duration").is_ordered());
    assert!(!ty("string").is_ordered());
    assert!(!ty("boolean").is_ordered());
    assert!(!ty("hexBinary").is_ordered());

    assert!(ty("date").is_temporal());
    assert!(!ty("integer").is_temporal());
    assert!(ty("integer").is_numeric());
    assert!(!ty("date").is_numeric());
}

#[test]
fn comparison_is_exact_and_type_aware() {
    use std::cmp::Ordering;
    let int = ty("integer");
    assert_eq!(int.compare("1", "2"), Some(Ordering::Less));
    assert_eq!(int.compare("2", "1"), Some(Ordering::Greater));
    assert_eq!(int.compare("+1", "1"), Some(Ordering::Equal));
    assert_eq!(int.compare("007", "7"), Some(Ordering::Equal));
    assert_eq!(int.compare("-0", "0"), Some(Ordering::Equal));
    assert_eq!(int.compare("-1", "1"), Some(Ordering::Less));
    // Past the point an f64 can distinguish.
    assert_eq!(
        int.compare("999999999999999998", "999999999999999999"),
        Some(Ordering::Less)
    );

    let dec = ty("decimal");
    assert_eq!(dec.compare("1.10", "1.1"), Some(Ordering::Equal));
    assert_eq!(dec.compare("1.5", "1.45"), Some(Ordering::Greater));

    let date = ty("date");
    assert_eq!(
        date.compare("2000-12-31", "2001-01-01"),
        Some(Ordering::Less)
    );
    assert_eq!(
        date.compare("2000-02-29", "2000-03-01"),
        Some(Ordering::Less)
    );

    // A value the type does not accept has no place in the ordering.
    assert_eq!(int.compare("x", "1"), None);
}

#[test]
fn the_built_in_list_types_know_their_item() {
    assert!(ty("NMTOKENS").is_built_in_list());
    assert!(ty("IDREFS").is_built_in_list());
    assert!(ty("ENTITIES").is_built_in_list());
    assert!(!ty("NMTOKEN").is_built_in_list());
    assert_eq!(ty("NMTOKENS").item_type(), ty("NMTOKEN"));
    assert_eq!(ty("IDREFS").item_type(), ty("IDREF"));
    // Everything else is its own item type, so a caller need not ask.
    assert_eq!(ty("integer").item_type(), ty("integer"));
}

/// Every built-in resolves, describes itself, and is distinct.
///
/// A diagnostic naming the wrong type is worse than none, and a
/// description is the only place several of these types appear.
#[test]
fn every_built_in_resolves_and_describes_itself() {
    const ALL: &[&str] = &[
        "anySimpleType",
        "anyType",
        "string",
        "normalizedString",
        "token",
        "language",
        "NMTOKEN",
        "NMTOKENS",
        "Name",
        "NCName",
        "ID",
        "IDREF",
        "IDREFS",
        "ENTITY",
        "ENTITIES",
        "boolean",
        "decimal",
        "integer",
        "nonPositiveInteger",
        "negativeInteger",
        "long",
        "int",
        "short",
        "byte",
        "nonNegativeInteger",
        "unsignedLong",
        "unsignedInt",
        "unsignedShort",
        "unsignedByte",
        "positiveInteger",
        "float",
        "double",
        "duration",
        "dateTime",
        "time",
        "date",
        "gYearMonth",
        "gYear",
        "gMonthDay",
        "gMonth",
        "gDay",
        "hexBinary",
        "base64Binary",
        "anyURI",
        "QName",
        "NOTATION",
    ];
    let mut described = Vec::new();
    for name in ALL {
        let t = ty(name);
        let text = t.describe();
        assert!(!text.is_empty(), "{name} describes itself as nothing");
        described.push((t, text));
    }
    // `anyType` is a spelling of `anySimpleType`; every other name is
    // its own type.
    let mut kinds: Vec<_> = described.iter().map(|(t, _)| *t).collect();
    kinds.sort_by_key(|t| format!("{t:?}"));
    kinds.dedup();
    assert_eq!(kinds.len(), ALL.len() - 1, "one alias, no other collapse");
}

/// The types with no constraint accept anything, including nothing.
#[test]
fn the_unconstrained_types_accept_anything() {
    for name in ["anySimpleType", "anyType", "string", "token", "anyURI"] {
        for value in ["", "anything at all", "  spaced  ", "<>&"] {
            assert!(ty(name).accepts(value), "{name} should accept {value:?}");
        }
    }
}

/// Every temporal type has an ordering, and it has to be the right one.
#[test]
fn temporal_ordering_covers_every_form() {
    use std::cmp::Ordering::{Greater, Less};
    let cases: &[(&str, &str, &str)] = &[
        // (type, smaller, larger)
        ("date", "2000-12-31", "2001-01-01"),
        ("date", "-0001-01-01", "0001-01-01"),
        ("dateTime", "2001-01-01T00:00:00", "2001-01-01T00:00:01"),
        ("dateTime", "2001-01-01T23:59:59", "2001-01-02T00:00:00"),
        ("time", "00:00:00", "23:59:59"),
        ("time", "12:00:00", "12:00:01"),
        ("gYear", "1999", "2000"),
        ("gYearMonth", "2001-01", "2001-02"),
        ("gMonth", "--01", "--12"),
        ("gDay", "---01", "---31"),
        ("gMonthDay", "--01-01", "--12-31"),
        ("duration", "P1D", "P1M"),
        ("duration", "P1M", "P1Y"),
        ("duration", "PT1S", "PT1M"),
        ("duration", "-P1Y", "P1Y"),
    ];
    for (name, small, large) in cases {
        let t = ty(name);
        assert_eq!(
            t.compare(small, large),
            Some(Less),
            "{name}: {small} < {large}"
        );
        assert_eq!(
            t.compare(large, small),
            Some(Greater),
            "{name}: {large} > {small}"
        );
        assert_eq!(
            t.compare(small, small),
            Some(std::cmp::Ordering::Equal),
            "{name}: {small} = {small}"
        );
    }
}

#[test]
fn an_unordered_type_has_no_comparison() {
    assert_eq!(ty("string").compare("a", "b"), None);
    assert_eq!(ty("boolean").compare("true", "false"), None);
    assert_eq!(ty("hexBinary").compare("00", "FF"), None);
}

#[test]
fn a_value_outside_its_type_has_no_place_in_the_ordering() {
    assert_eq!(ty("date").compare("not-a-date", "2001-01-01"), None);
    assert_eq!(ty("duration").compare("P", "P1Y"), None);
    assert_eq!(ty("integer").compare("1.5", "2"), None);
    assert_eq!(ty("double").compare("NaN", "1"), None);
}

#[test]
fn whitespace_is_processed_before_the_value_is_read() {
    // Every type but string and normalizedString collapses first, so
    // a padded value is still valid.
    assert!(ty("integer").accepts("  5  "));
    assert!(ty("boolean").accepts("\ttrue\n"));
    assert!(ty("date").accepts(" 2001-01-01 "));
    // And it is the collapsed value that gets compared.
    assert_eq!(
        ty("integer").compare(" 5 ", "5"),
        Some(std::cmp::Ordering::Equal)
    );
    // A string keeps its spaces, so they count towards its length.
    assert_eq!(ty("string").normalise(" a "), " a ");
}

#[test]
fn the_bounded_integers_reject_their_own_edges() {
    let cases: &[(&str, &str, &str)] = &[
        // (type, largest accepted, smallest rejected)
        ("byte", "127", "128"),
        ("short", "32767", "32768"),
        ("int", "2147483647", "2147483648"),
        ("long", "9223372036854775807", "9223372036854775808"),
        ("unsignedByte", "255", "256"),
        ("unsignedShort", "65535", "65536"),
        ("unsignedInt", "4294967295", "4294967296"),
        (
            "unsignedLong",
            "18446744073709551615",
            "18446744073709551616",
        ),
    ];
    for (name, ok, bad) in cases {
        assert!(ty(name).accepts(ok), "{name} should accept {ok}");
        assert!(!ty(name).accepts(bad), "{name} should reject {bad}");
    }
    // The unsigned types have a floor as well as a ceiling.
    for name in [
        "unsignedByte",
        "unsignedShort",
        "unsignedInt",
        "unsignedLong",
    ] {
        assert!(!ty(name).accepts("-1"), "{name} should reject -1");
    }
}

#[test]
fn the_list_types_require_every_item_to_be_valid() {
    assert!(ty("IDREFS").accepts("a b c"));
    assert!(!ty("IDREFS").accepts("a b:c"), "an IDREF is an NCName");
    assert!(ty("ENTITIES").accepts("one"));
    assert!(!ty("ENTITIES").accepts("1one"));
}

/// Whitespace processing returns the input untouched when there is
/// nothing to change.
#[test]
fn normalising_an_already_normal_value_changes_nothing() {
    assert_eq!(
        ty("normalizedString").normalise("no tabs here"),
        "no tabs here"
    );
    assert_eq!(
        ty("token").normalise("single spaces only"),
        "single spaces only"
    );
    assert_eq!(ty("string").normalise("\t kept \t"), "\t kept \t");
    // And when there *is* something to change.
    assert_eq!(ty("normalizedString").normalise("a\tb"), "a b");
    assert_eq!(ty("token").normalise("  a   b  "), "a b");
}

#[test]
fn every_built_in_list_names_its_item_type() {
    assert_eq!(ty("NMTOKENS").item_type(), ty("NMTOKEN"));
    assert_eq!(ty("IDREFS").item_type(), ty("IDREF"));
    assert_eq!(ty("ENTITIES").item_type(), ty("ENTITY"));
}

/// Comparison falls back to a float where a decimal form does not
/// apply, and refuses where no order exists.
#[test]
fn comparison_handles_the_forms_decimals_cannot() {
    use std::cmp::Ordering;
    let d = ty("double");
    // Scientific notation has no decimal lexical form to compare.
    assert_eq!(d.compare("1e3", "2e3"), Some(Ordering::Less));
    assert_eq!(d.compare("1e3", "1000"), Some(Ordering::Equal));
    // The specials.
    assert_eq!(d.compare("INF", "1"), Some(Ordering::Greater));
    assert_eq!(d.compare("-INF", "1"), Some(Ordering::Less));
    assert_eq!(d.compare("NaN", "NaN"), None, "NaN orders with nothing");
    assert_eq!(d.compare("1", "NaN"), None);
}

/// A `dateTime` orders across both halves, and a timezone does not
/// change which value it is.
#[test]
fn temporal_keys_read_every_component() {
    use std::cmp::Ordering;
    let dt = ty("dateTime");
    assert_eq!(
        dt.compare("2001-01-01T00:00:00Z", "2001-01-01T00:00:01Z"),
        Some(Ordering::Less)
    );
    let t = ty("time");
    assert_eq!(t.compare("01:00:00", "02:00:00"), Some(Ordering::Less));
    assert_eq!(t.compare("00:00:01", "00:00:00"), Some(Ordering::Greater));
    let gmd = ty("gMonthDay");
    assert_eq!(gmd.compare("--01-31", "--02-01"), Some(Ordering::Less));
    let gd = ty("gDay");
    assert_eq!(gd.compare("---01", "---02"), Some(Ordering::Less));
    let gym = ty("gYearMonth");
    assert_eq!(gym.compare("2001-12", "2002-01"), Some(Ordering::Less));
}

/// Names may be non-ASCII, and the productions say which characters.
#[test]
fn the_name_productions_reach_beyond_ascii() {
    assert!(ty("NCName").accepts("Ünïcödé"));
    assert!(ty("NCName").accepts("Ωμέγα"));
    assert!(ty("NCName").accepts("日本語"));
    assert!(
        ty("Name").accepts("_a\u{0300}"),
        "a combining mark may follow"
    );
    assert!(!ty("Name").accepts("\u{0300}a"), "but may not lead");
    assert!(!ty("NCName").accepts("a b"));
}