rfc9839 0.3.0

Implementation of the RFC 9839 specification
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
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
//! # RFC 9839 Unicode Subset Validators
//!
//! This crate provides fast, zero-allocation checks to validate whether
//! individual characters, strings, or raw byte slices conform to the subsets
//! defined in [RFC 9839]:
//!
//! - **Unicode Scalars** — all code points except the UTF-16 surrogate range.
//!   In Rust, all `char` values are scalars by construction, but functions are
//!   included for completeness and defensive validation of `&str` / byte data.
//! - **XML Characters** — the “Char” production from XML:
//!   `{TAB, LF, CR} ∪ [0x20–0xD7FF] ∪ [0xE000–0xFFFD] ∪ [0x10000–0x10FFFF]`.
//!   Excludes surrogates, C0 controls except TAB/LF/CR, and U+FFFE/U+FFFF.
//! - **Unicode Assignables** — all scalar values that are not legacy controls,
//!   surrogates, or standardized noncharacters, including currently unassigned
//!   code points.
//!
//! ## Features
//!
//! - **String-level** APIs (`is_*`) are available at the crate root and in
//!   [`mod@str`]. XML/Assignable validation uses an ASCII fast-path where validation
//!   is required: scan raw bytes first, and only fall back to `chars()` after the
//!   first non-ASCII byte.
//! - **Byte-level** APIs are available in [`bytes`] for validating raw UTF-8
//!   input. Scalar validation only needs UTF-8 validation; XML/Assignable checks
//!   decode the tail once and return `false` on invalid UTF-8.
//! - **Character-level** APIs are available in [`chars`] and implemented as
//!   `const fn` with simple range tests.
//! - Backwards-compatible aliases such as `is_xml_chars_bytes` and
//!   `is_xml_char` remain available at the crate root.
//! - Zero allocations, no heap lookups, no tables.
//!
//! ## Examples
//!
//! ```
//! use rfc9839::{bytes, chars};
//!
//! // Scalars (always true for safe Rust strings)
//! assert!(rfc9839::is_unicode_scalar("hello 🌍"));
//!
//! // XML Characters
//! assert!(rfc9839::is_xml_chars("ok\tline\n"));
//! assert!(!rfc9839::is_xml_chars("\u{0000}")); // NUL is disallowed
//!
//! // Byte and character APIs live in modules.
//! assert!(bytes::is_unicode_assignable("emoji 👍".as_bytes()));
//! assert!(!chars::is_unicode_assignable('\u{007F}')); // DEL is excluded
//! ```
//!
//! ## Performance
//!
//! All string/byte checks run in O(n). ASCII data is validated in a tight loop;
//! non-ASCII triggers a one-time `chars()` traversal or UTF-8 decode. These
//! functions are designed for high-throughput pipelines, parsers, and
//! validators.
//!
//! [RFC 9839]: https://www.rfc-editor.org/rfc/rfc9839

/// Character-level validators.
pub mod chars {
    /// Returns `true` if `c` is a Unicode scalar value per RFC 9839.
    ///
    /// Any code point except the UTF-16 surrogate range `U+D800..=U+DFFF`.
    ///
    /// In Rust, every `char` is already a scalar value by construction, so this
    /// function will return `true` for all valid `char`s. It’s provided for
    /// completeness and symmetry with the string/byte variants.
    ///
    /// # Examples
    /// ```
    /// assert!(rfc9839::chars::is_unicode_scalar('a'));
    /// assert!(rfc9839::chars::is_unicode_scalar('👍'));
    /// ```
    #[inline(always)]
    #[must_use]
    pub const fn is_unicode_scalar(_: char) -> bool {
        true
    }

    /// Returns `true` if `c` is an XML Character as defined in RFC 9839.
    ///
    /// `{ TAB, LF, CR } ∪ [0x20–0xD7FF] ∪ [0xE000–0xFFFD] ∪ [0x10000–0x10FFFF]`.
    ///
    /// This is the classic XML “Char” set: surrogates, C0 controls except
    /// TAB/LF/CR, and U+FFFE/U+FFFF are excluded.
    ///
    /// # Examples
    /// ```
    /// assert!(rfc9839::chars::is_xml_char('\t'));
    /// assert!(rfc9839::chars::is_xml_char('A'));
    /// assert!(!rfc9839::chars::is_xml_char('\u{0001}')); // disallowed control
    /// assert!(!rfc9839::chars::is_xml_char('\u{FFFF}')); // noncharacter
    /// ```
    #[inline(always)]
    #[must_use]
    pub const fn is_xml_char(c: char) -> bool {
        let u = c as u32;
        (u == 0x09)
            || (u == 0x0A)
            || (u == 0x0D)
            || (u >= 0x20 && u <= 0xD7FF)
            || (u >= 0xE000 && u <= 0xFFFD)
            || (u >= 0x10000 && u <= 0x10FFFF)
    }

    /// Returns `true` if `c` is a Unicode Assignable character per RFC 9839.
    ///
    /// All scalar values that are not legacy controls, surrogates, or standardized
    /// noncharacters, including currently unassigned code points.
    ///
    /// # Examples
    /// ```
    /// assert!(rfc9839::chars::is_unicode_assignable('A'));
    /// assert!(rfc9839::chars::is_unicode_assignable('👍'));
    /// assert!(!rfc9839::chars::is_unicode_assignable('\u{007F}'));   // DEL
    /// assert!(!rfc9839::chars::is_unicode_assignable('\u{0085}'));   // C1 control
    /// assert!(!rfc9839::chars::is_unicode_assignable('\u{FDD0}'));   // noncharacter
    /// assert!(!rfc9839::chars::is_unicode_assignable('\u{1FFFE}'));  // plane noncharacter
    /// ```
    #[inline(always)]
    #[must_use]
    pub const fn is_unicode_assignable(c: char) -> bool {
        let u = c as u32;
        (u == 0x09)
            || (u == 0x0A)
            || (u == 0x0D)
            || (u >= 0x20 && u <= 0x7E)
            || (u >= 0xA0 && u <= 0xD7FF)
            || (u >= 0xE000 && u <= 0xFDCF)
            || (u >= 0xFDF0 && u <= 0xFFFD)
            || (u >= 0x10000 && u <= 0x1FFFD)
            || (u >= 0x20000 && u <= 0x2FFFD)
            || (u >= 0x30000 && u <= 0x3FFFD)
            || (u >= 0x40000 && u <= 0x4FFFD)
            || (u >= 0x50000 && u <= 0x5FFFD)
            || (u >= 0x60000 && u <= 0x6FFFD)
            || (u >= 0x70000 && u <= 0x7FFFD)
            || (u >= 0x80000 && u <= 0x8FFFD)
            || (u >= 0x90000 && u <= 0x9FFFD)
            || (u >= 0xA0000 && u <= 0xAFFFD)
            || (u >= 0xB0000 && u <= 0xBFFFD)
            || (u >= 0xC0000 && u <= 0xCFFFD)
            || (u >= 0xD0000 && u <= 0xDFFFD)
            || (u >= 0xE0000 && u <= 0xEFFFD)
            || (u >= 0xF0000 && u <= 0xFFFFD)
            || (u >= 0x100000 && u <= 0x10FFFD)
    }
}

/// String-level validators for `&str`.
pub mod str {
    use super::{ascii_assignable_ok, ascii_xml_ok, chars};

    /// Returns `true` if all code points in `s` are Unicode scalar values.
    ///
    /// In safe Rust, any well-formed `&str` contains only scalar values, so this
    /// check will return `true`.
    ///
    /// # Examples
    /// ```
    /// assert!(rfc9839::str::is_unicode_scalar("hello 🌍"));
    /// assert!(rfc9839::is_unicode_scalar("hello 🌍"));
    /// ```
    #[inline]
    #[must_use]
    pub fn is_unicode_scalar(_: &str) -> bool {
        true
    }

    /// Returns `true` if all characters in `s` are XML Characters.
    ///
    /// Validates using an ASCII fast-path (TAB/LF/CR and 0x20..=0x7F), then
    /// switches to `chars()` on the first non-ASCII byte.
    ///
    /// # Examples
    /// ```
    /// assert!(rfc9839::str::is_xml_chars("ok\tline\n"));
    /// assert!(rfc9839::is_xml_chars("ok\tline\n"));
    /// assert!(!rfc9839::str::is_xml_chars("\u{0000}")); // NUL disallowed
    /// assert!(!rfc9839::str::is_xml_chars("\u{FFFF}")); // noncharacter
    /// ```
    #[inline]
    #[must_use]
    pub fn is_xml_chars(s: &str) -> bool {
        let bytes = s.as_bytes();
        let mut i = 0;
        while i < bytes.len() {
            let b = bytes[i];
            if b < 0x80 {
                if !ascii_xml_ok(b) {
                    return false;
                }
                i += 1;
            } else {
                // non-ASCII: validate the remainder with full char checks
                return s[i..].chars().all(chars::is_xml_char);
            }
        }
        true
    }

    /// Returns `true` if all characters in `s` are Unicode Assignables.
    ///
    /// Allows all scalar values that are not legacy controls, surrogates, or
    /// standardized noncharacters, including currently unassigned code points.
    ///
    /// # Examples
    /// ```
    /// assert!(rfc9839::str::is_unicode_assignable("Hello 👍"));
    /// assert!(rfc9839::is_unicode_assignable("Hello 👍"));
    /// assert!(!rfc9839::str::is_unicode_assignable("\u{007F}"));  // DEL
    /// assert!(!rfc9839::str::is_unicode_assignable("\u{1FFFE}")); // plane noncharacter
    /// ```
    #[inline]
    #[must_use]
    pub fn is_unicode_assignable(s: &str) -> bool {
        let bytes = s.as_bytes();
        let mut i = 0;
        while i < bytes.len() {
            let b = bytes[i];
            if b < 0x80 {
                if !ascii_assignable_ok(b) {
                    return false;
                }
                i += 1;
            } else {
                // non-ASCII: validate the remainder with full char checks
                return s[i..].chars().all(chars::is_unicode_assignable);
            }
        }
        true
    }
}

/// Byte-level validators for UTF-8 encoded data.
pub mod bytes {
    use super::{ascii_assignable_ok, ascii_xml_ok, chars};

    /// Returns `true` if `bytes` are valid Unicode scalar values.
    ///
    /// This returns `true` when `bytes` are valid UTF-8. Rust strings cannot
    /// contain surrogate code points, so UTF-8 validation is sufficient.
    ///
    /// # Examples
    /// ```
    /// assert!(rfc9839::bytes::is_unicode_scalar(b"ASCII only"));
    /// assert!(rfc9839::bytes::is_unicode_scalar("héllo".as_bytes()));
    /// assert!(!rfc9839::bytes::is_unicode_scalar(&[0xF0, 0x28, 0x8C, 0x28]));
    /// ```
    #[inline]
    #[must_use]
    pub fn is_unicode_scalar(bytes: &[u8]) -> bool {
        std::str::from_utf8(bytes).is_ok()
    }

    /// Returns `true` if `bytes` are all valid XML Characters.
    ///
    /// On the first non-ASCII byte, the tail is decoded as UTF-8; invalid UTF-8
    /// returns `false`.
    ///
    /// # Examples
    /// ```
    /// assert!(rfc9839::bytes::is_xml_chars(b"ok\t\n\r ASCII"));
    /// assert!(!rfc9839::bytes::is_xml_chars(&[0x00])); // NUL not allowed
    /// assert!(!rfc9839::bytes::is_xml_chars("a\u{FFFF}".as_bytes())); // noncharacter
    /// ```
    #[inline]
    #[must_use]
    pub fn is_xml_chars(bytes: &[u8]) -> bool {
        let mut i = 0;
        while i < bytes.len() {
            let b = bytes[i];
            if b < 0x80 {
                if !ascii_xml_ok(b) {
                    return false;
                }
                i += 1;
            } else {
                // non-ASCII: validate the remainder with full char checks
                return if let Ok(s) = std::str::from_utf8(&bytes[i..]) {
                    s.chars().all(chars::is_xml_char)
                } else {
                    false
                };
            }
        }
        true
    }

    /// Returns `true` if `bytes` are all valid Unicode Assignables.
    ///
    /// On the first non-ASCII byte, the tail is decoded as UTF-8; invalid UTF-8
    /// returns `false`.
    ///
    /// # Examples
    /// ```
    /// assert!(rfc9839::bytes::is_unicode_assignable(b"Hello World"));
    /// assert!(rfc9839::bytes::is_unicode_assignable("👍".as_bytes()));
    /// assert!(!rfc9839::bytes::is_unicode_assignable(&[0x7F])); // DEL not allowed
    /// assert!(!rfc9839::bytes::is_unicode_assignable("x\u{1FFFE}".as_bytes()));
    /// ```
    #[inline]
    #[must_use]
    pub fn is_unicode_assignable(bytes: &[u8]) -> bool {
        let mut i = 0;
        while i < bytes.len() {
            let b = bytes[i];
            if b < 0x80 {
                if !ascii_assignable_ok(b) {
                    return false;
                }
                i += 1;
            } else {
                // non-ASCII: validate the remainder with full char checks
                return if let Ok(s) = std::str::from_utf8(&bytes[i..]) {
                    s.chars().all(chars::is_unicode_assignable)
                } else {
                    false
                };
            }
        }
        true
    }
}

#[doc(inline)]
pub use str::*;

#[doc(inline)]
pub use bytes::is_unicode_assignable as is_unicode_assignable_bytes;
#[doc(inline)]
pub use bytes::is_unicode_scalar as is_unicode_scalar_bytes;
#[doc(inline)]
pub use bytes::is_xml_chars as is_xml_chars_bytes;

#[doc(inline)]
pub use chars::is_unicode_assignable as is_unicode_assignable_char;
#[doc(inline)]
pub use chars::is_unicode_scalar as is_unicode_scalar_char;
#[doc(inline)]
pub use chars::is_xml_char;

#[inline(always)]
fn ascii_xml_ok(b: u8) -> bool {
    // {TAB, LF, CR} or 0x20..=0x7F
    b == b'\t' || b == b'\n' || b == b'\r' || (0x20..=0x7F).contains(&b)
}

#[inline(always)]
fn ascii_assignable_ok(b: u8) -> bool {
    // {TAB, LF, CR} or 0x20..=0x7E
    b == b'\t' || b == b'\n' || b == b'\r' || (0x20..=0x7E).contains(&b)
}

#[cfg(test)]
mod tests {
    use super::*;

    // ---- Helpers ------------------------------------------------------------

    /// Generate a few representative scalar characters across ranges.
    fn sample_scalars() -> [char; 8] {
        [
            '\u{0000}', // NUL (scalar, though not XML/Assignable)
            'A',
            '\u{007E}',  // '~'
            '\u{00A0}',  // NBSP
            '\u{D7FF}',  // last before surrogates
            '\u{E000}',  // first after surrogates (PUA)
            '\u{FFFD}',  // replacement char
            '\u{1F600}', // 😀
        ]
    }

    fn make_ascii(n: usize) -> String {
        "A".repeat(n)
    }

    // Noncharacters FFFE/FFFF at base plane.
    const BMP_FFFE: char = '\u{FFFE}';
    const BMP_FFFF: char = '\u{FFFF}';

    // ---- is_unicode_scalar_char --------------------------------------------

    #[test]
    fn scalar_char_accepts_all_valid_char() {
        for c in sample_scalars() {
            assert!(is_unicode_scalar_char(c), "char U+{:04X}", c as u32);
        }
    }

    #[test]
    fn scalar_char_rejects_surrogates_by_construction() {
        // You cannot construct a Rust `char` in the surrogate range; this test
        // documents that invariant indirectly by checking boundary neighbors.
        assert!(is_unicode_scalar_char('\u{D7FF}'));
        assert!(is_unicode_scalar_char('\u{E000}'));
        // (No direct surrogate `char` value to test.)
    }

    // ---- is_xml_char --------------------------------------------------------

    #[test]
    fn xml_char_allows_tab_lf_cr_and_ascii_range() {
        for &c in &['\t', '\n', '\r', ' ', 'A', '~', '\u{007F}'] {
            assert!(is_xml_char(c), "expected XML char: {:?}", c);
        }
    }

    #[test]
    fn xml_char_disallows_other_c0_controls_and_nonchars() {
        assert!(!is_xml_char('\u{0000}'));
        assert!(!is_xml_char('\u{001F}')); // Unit Separator (C0)
        assert!(!is_xml_char(BMP_FFFE));
        assert!(!is_xml_char(BMP_FFFF));
    }

    #[test]
    fn xml_char_allows_valid_planes() {
        assert!(is_xml_char('\u{D7FF}')); // boundary
        assert!(is_xml_char('\u{E000}')); // boundary (PUA)
        assert!(is_xml_char('\u{FFFD}')); // replacement char
        assert!(is_xml_char('\u{10000}')); // start of SMP
        assert!(is_xml_char('\u{10FFFF}')); // max scalar
    }

    // ---- is_unicode_assignable_char ----------------------------------------

    #[test]
    fn assignable_char_allows_useful_controls_and_printable_ascii() {
        for &c in &['\t', '\n', '\r', ' ', 'A', '~'] {
            assert!(
                is_unicode_assignable_char(c),
                "expected assignable: {:?}",
                c
            );
        }
    }

    #[test]
    fn assignable_char_rejects_del_and_c1_controls() {
        assert!(!is_unicode_assignable_char('\u{007F}')); // DEL
        for cp in 0x80u32..=0x9Fu32 {
            let c = char::from_u32(cp).unwrap();
            assert!(!is_unicode_assignable_char(c), "C1 control U+{:04X}", cp);
        }
    }

    #[test]
    fn assignable_char_rejects_standardized_noncharacters() {
        // FDD0..FDEF
        for cp in 0xFDD0u32..=0xFDEFu32 {
            let c = char::from_u32(cp).unwrap();
            assert!(
                !is_unicode_assignable_char(c),
                "U+{:04X} should be excluded",
                cp
            );
        }
        // ...FFFE and ...FFFF in several planes
        let planes = [0x00000u32, 0x10000, 0x20000, 0xE0000, 0xF0000, 0x100000];
        for base in planes {
            let fffe = char::from_u32(base + 0xFFFE).unwrap();
            let ffff = char::from_u32(base + 0xFFFF).unwrap();
            assert!(
                !is_unicode_assignable_char(fffe),
                "U+{:06X} excluded",
                base + 0xFFFE
            );
            assert!(
                !is_unicode_assignable_char(ffff),
                "U+{:06X} excluded",
                base + 0xFFFF
            );
        }
    }

    #[test]
    fn assignable_char_allows_up_to_fffd_each_plane() {
        // Spot-check multiple planes at ...FFFD
        let ok_points = [0x00FFFD, 0x01FFFD, 0x02FFFD, 0x0EFFFD, 0x0FFFFD, 0x10FFFD];
        for cp in ok_points {
            let c = char::from_u32(cp).unwrap();
            assert!(
                is_unicode_assignable_char(c),
                "U+{:06X} should be allowed",
                cp
            );
        }
    }

    // ---- String validators --------------------------------------------------

    #[test]
    fn unicode_scalar_str_is_true_for_valid_utf8() {
        assert!(is_unicode_scalar("hello"));
        assert!(is_unicode_scalar("héllo"));
        assert!(is_unicode_scalar("emoji 👍"));
        assert!(is_unicode_scalar(&make_ascii(1024)));
    }

    #[test]
    fn xml_chars_str_basic_cases() {
        assert!(is_xml_chars("ok\tline\n\rmore"));
        assert!(is_xml_chars("\u{007F}"));
        assert!(!is_xml_chars("\u{0000}"));
        assert!(!is_xml_chars(&format!("x{}", BMP_FFFE)));
        assert!(is_xml_chars("valid \u{FFFD} char"));
    }

    #[test]
    fn assignable_str_basic_cases() {
        assert!(is_unicode_assignable("Hello 👍"));
        assert!(!is_unicode_assignable("\u{007F}")); // DEL
        assert!(!is_unicode_assignable("\u{0085}")); // C1 control
        assert!(!is_unicode_assignable("\u{FDD0}")); // noncharacter
        assert!(!is_unicode_assignable("\u{1FFFE}")); // plane noncharacter
    }

    #[test]
    fn ascii_fast_path_large_strings() {
        let s = make_ascii(4096);
        assert!(is_xml_chars(&s));
        assert!(is_unicode_assignable(&s));
    }

    #[test]
    fn mixed_ascii_then_utf8_tail() {
        let s = format!("{}{}", make_ascii(64), "👍👍👍");
        assert!(is_xml_chars(&s));
        assert!(is_unicode_assignable(&s));
    }

    // ---- Byte-slice validators ---------------------------------------------

    #[test]
    fn unicode_scalar_bytes_valid_and_invalid_utf8() {
        assert!(is_unicode_scalar_bytes(b"ASCII only"));
        assert!(is_unicode_scalar_bytes("héllo".as_bytes()));

        // Invalid UTF-8: overlong / bad continuation (classic example)
        let invalid = [0xF0, 0x28, 0x8C, 0x28];
        assert!(!is_unicode_scalar_bytes(&invalid));
    }

    #[test]
    fn xml_chars_bytes_respects_ascii_rules_and_utf8_decode() {
        assert!(is_xml_chars_bytes(b"ok\t\n\r ASCII"));
        assert!(is_xml_chars_bytes(&[0x7F]));
        assert!(!is_xml_chars_bytes(&[0x00])); // NUL forbidden

        let with_nonchar = "x\u{FFFF}".as_bytes().to_vec();
        assert!(!is_xml_chars_bytes(&with_nonchar));

        let invalid_utf8 = [0xE2, 0x28, 0xA1]; // invalid 3-byte sequence
        assert!(!is_xml_chars_bytes(&invalid_utf8));
    }

    #[test]
    fn assignable_bytes_respects_exclusions() {
        assert!(is_unicode_assignable_bytes(b"Hello World"));
        assert!(is_unicode_assignable_bytes("👍".as_bytes()));
        assert!(!is_unicode_assignable_bytes(&[0x7F])); // DEL
        let with_plane_nonchar = "x\u{1FFFE}".as_bytes().to_vec();
        assert!(!is_unicode_assignable_bytes(&with_plane_nonchar));
    }

    // ---- Internal ASCII helper ---------------------------------------------

    #[test]
    fn ascii_xml_ok_rules() {
        // Allowed: TAB/LF/CR and 0x20..=0x7F
        for &b in &[b'\t', b'\n', b'\r', b' ', b'~', 0x7F] {
            assert!(super::ascii_xml_ok(b), "byte 0x{:02X} should be XML-ok", b);
        }
        // Disallowed: other C0 controls (e.g., 0x1F).
        assert!(!super::ascii_xml_ok(0x1F));
    }

    #[test]
    fn ascii_assignable_ok_rules() {
        // Allowed: TAB/LF/CR and 0x20..=0x7E
        for &b in b"\t\n\r ~" {
            assert!(
                super::ascii_assignable_ok(b),
                "byte 0x{:02X} should be assignable-ok",
                b
            );
        }
        // Disallowed: other C0 controls (e.g., 0x1F) and DEL (0x7F).
        assert!(!super::ascii_assignable_ok(0x1F));
        assert!(!super::ascii_assignable_ok(0x7F));
    }

    // ---- Boundary sweeps (targeted) ----------------------------------------

    #[test]
    fn xml_boundaries() {
        // Lower boundary around 0x20
        assert!(!is_xml_char('\u{001F}'));
        assert!(is_xml_char('\u{0020}'));
        assert!(is_xml_char('\u{007F}'));

        // D7FF/E000 boundary
        assert!(is_xml_char('\u{D7FF}'));
        assert!(is_xml_char('\u{E000}'));

        // FFFD/FFFE/FFFF boundary
        assert!(is_xml_char('\u{FFFD}'));
        assert!(!is_xml_char('\u{FFFE}'));
        assert!(!is_xml_char('\u{FFFF}'));
    }

    #[test]
    fn assignable_boundaries() {
        // ASCII printable vs DEL
        assert!(is_unicode_assignable_char('\u{007E}'));
        assert!(!is_unicode_assignable_char('\u{007F}'));

        // A0 start allowed
        assert!(is_unicode_assignable_char('\u{00A0}'));
        // D7FF end allowed, E000 start allowed
        assert!(is_unicode_assignable_char('\u{D7FF}'));
        assert!(is_unicode_assignable_char('\u{E000}'));

        // FDCF allowed, FDD0..FDEF excluded, FDF0 allowed
        assert!(is_unicode_assignable_char('\u{FDCF}'));
        assert!(!is_unicode_assignable_char('\u{FDD0}'));
        assert!(!is_unicode_assignable_char('\u{FDEF}'));
        assert!(is_unicode_assignable_char('\u{FDF0}'));

        // FFfd allowed, FFFE/FFFF not
        assert!(is_unicode_assignable_char('\u{FFFD}'));
        assert!(!is_unicode_assignable_char('\u{FFFE}'));
        assert!(!is_unicode_assignable_char('\u{FFFF}'));
    }

    #[test]
    fn supplementary_plane_boundaries_assignable() {
        // At plane starts and ...FFFD ends
        for plane in 0x1u32..=0x10 {
            let start = plane << 16;
            let end_ok = (plane << 16) + 0xFFFD;
            let end_bad1 = (plane << 16) + 0xFFFE;
            let end_bad2 = (plane << 16) + 0xFFFF;

            // Skip surrogates (plane 0 has them in D800..DFFF), we are testing supplementary planes.
            let start_char = char::from_u32(start).unwrap();
            let ok_char = char::from_u32(end_ok).unwrap();
            let bad1_char = char::from_u32(end_bad1).unwrap();
            let bad2_char = char::from_u32(end_bad2).unwrap();

            assert!(
                is_unicode_assignable_char(start_char),
                "U+{:06X} should be allowed",
                start
            );
            assert!(
                is_unicode_assignable_char(ok_char),
                "U+{:06X} should be allowed",
                end_ok
            );
            assert!(
                !is_unicode_assignable_char(bad1_char),
                "U+{:06X} should be excluded",
                end_bad1
            );
            assert!(
                !is_unicode_assignable_char(bad2_char),
                "U+{:06X} should be excluded",
                end_bad2
            );
        }
    }

    // ---- Sanity: mixed strings including boundaries ------------------------

    #[test]
    fn xml_and_assignable_mixed_strings() {
        let xml_ok = format!("start\t\n\r mid {} end", '\u{FFFD}');
        assert!(is_xml_chars(&xml_ok));
        let xml_bad = format!("x{}", '\u{FFFF}');
        assert!(!is_xml_chars(&xml_bad));

        let asg_ok = format!("hello {} world {}", '\u{00A0}', '\u{1F600}');
        assert!(is_unicode_assignable(&asg_ok));
        let asg_bad = format!("bad{}", '\u{1FFFE}');
        assert!(!is_unicode_assignable(&asg_bad));
    }
}