sorug 0.5.0

Ultra-high-performance, zero-copy, WHATWG-compliant URL parser
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
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
//! Minimal IDNA / Punycode for WHATWG host parsing.
//!
//! Implements RFC 3492 Bootstring (Punycode) encoding plus a deliberately small
//! UTS #46 mapping surface — enough for the WPT `urltestdata` suite without
//! shipping ICU / the `idna` crate at runtime.
//!
//! Membership classifiers (`CheckBidi`, `CheckJoiners`, disallowed, Ext-B, …)
//! use compile-time range tables from [`super::unicode_ranges`] generated by
//! `build.rs` from **vendored** Unicode UCD files under `data/ucd/` (pinned in
//! `UNICODE_VERSION`) merged with `data/idna_overlay.txt` (Node/WPT deltas).
//! Value-producing remaps stay in [`map_char`].
//!
//! WHATWG domain parser (`beStrict = false`):
//! - ASCII input → lowercase pass-through (even if ACE labels are invalid)
//! - Common IDN (Latin-1 lowercase / CJK / kana / Hangul) → Punycode only
//!   ([`Scan::SimpleIdentity`]; skips NFC + CheckBidi/Joiners)
//! - Other non-ASCII → map (if needed) → NFC → validity checks → Punycode

use alloc::borrow::Cow;
use alloc::string::String;
use alloc::vec::Vec;

use unicode_normalization::UnicodeNormalization;
use unicode_normalization::char::canonical_combining_class;

use super::percent::AppendBuf;
use super::unicode_ranges::{
    is_arabic_ext_b_compatible_cp, is_arabic_ext_b_era_mark_cp, is_arabic_ext_b_era_ok_cp,
    is_arabic_ext_b_letter_cp, is_bidi_ignored_mark, is_bidi_number_cp, is_disallowed_cp,
    is_joining_letter_cp, is_legacy_arabic_cp, is_ltr_letter_block, is_rtl_alphabetic_block,
    is_rtl_non_letter, is_uts46_ignored_cp, maps_nfkc_via_space_cp, uts46_needs_map_cp,
};

/// Convert a domain to ASCII per WHATWG (non-strict).
pub(crate) fn to_ascii(domain: &str) -> Result<Cow<'_, str>, ()> {
    if domain.is_empty() {
        return Err(());
    }

    if domain.is_ascii() {
        let lower = lowercase_ascii(domain);
        if contains_forbidden_domain_code_point(lower.as_ref()) {
            return Err(());
        }
        return Ok(lower);
    }

    let mut out = String::with_capacity(domain.len().saturating_add(16));
    to_ascii_into(domain, &mut out)?;
    if out.is_empty() || contains_forbidden_domain_code_point(&out) {
        return Err(());
    }
    Ok(Cow::Owned(out))
}

/// Append the WHATWG ToASCII form of `domain` to `out`.
///
/// `domain` must be non-empty and non-ASCII (ASCII callers should use the
/// borrow-friendly [`to_ascii`] path). On error, `out` may contain a partial write.
pub(crate) fn to_ascii_into(domain: &str, out: &mut impl AppendBuf) -> Result<(), ()> {
    debug_assert!(!domain.is_empty());
    debug_assert!(!domain.is_ascii());

    match scan_non_ascii(domain)? {
        // Common IDN (Latin-1 / CJK / kana / Hangul): Punycode only — no NFC or
        // CheckBidi/CheckJoiners (those code points cannot fail those checks).
        Scan::SimpleIdentity => encode_domain_labels_simple(domain, out)?,
        Scan::Identity => encode_domain_labels(domain, out)?,
        Scan::NeedsMap => {
            let mapped = uts46_map_checked(domain)?;
            if mapped.is_empty() {
                return Err(());
            }
            encode_domain_labels(&mapped, out)?;
        }
    }

    Ok(())
}

/// Like [`to_ascii_into`], but validates the written slice and rolls back `out`
/// to `start_len` on failure. Used when writing directly into the URL buffer.
pub(crate) fn to_ascii_append_validated(
    domain: &str,
    out: &mut super::serialization::SerializationBuf<'_>,
) -> Result<(), ()> {
    if domain.is_empty() {
        return Err(());
    }

    let start = out.len();

    if domain.is_ascii() {
        if domain.bytes().all(|b| !b.is_ascii_uppercase()) {
            if contains_forbidden_domain_code_point(domain) {
                return Err(());
            }
            out.push_str(domain);
        } else {
            let lower = domain.to_ascii_lowercase();
            if contains_forbidden_domain_code_point(&lower) {
                return Err(());
            }
            out.push_str(&lower);
        }
    } else if to_ascii_into(domain, out).is_err() {
        out.truncate(start);
        return Err(());
    } else {
        let written = &out.as_str()[start..];
        if written.is_empty() || contains_forbidden_domain_code_point(written) {
            out.truncate(start);
            return Err(());
        }
    }

    Ok(())
}

#[derive(Copy, Clone, Debug, Eq, PartialEq)]
enum Scan {
    /// Non-ASCII but every code point is in the simple-identity set (Latin-1
    /// lowercase / CJK / kana / Hangul). Skip NFC + CheckBidi/Joiners.
    SimpleIdentity,
    /// No UTS #46 mapping / case folding required — encode labels as-is.
    Identity,
    /// Must run [`uts46_map_checked`] before encoding.
    NeedsMap,
}

/// Single pass: reject disallowed code points and detect whether mapping is needed.
fn scan_non_ascii(domain: &str) -> Result<Scan, ()> {
    let mut needs_map = false;
    let mut all_simple = true;
    for c in domain.chars() {
        if is_disallowed_idna(c) {
            return Err(());
        }
        if c.is_ascii() {
            if c.is_ascii_uppercase() {
                needs_map = true;
                all_simple = false;
            }
            continue;
        }
        if is_simple_identity_cp(c) {
            continue;
        }
        all_simple = false;
        if !needs_map && char_needs_uts46_map(c) {
            needs_map = true;
        }
    }
    Ok(if needs_map {
        Scan::NeedsMap
    } else if all_simple {
        Scan::SimpleIdentity
    } else {
        Scan::Identity
    })
}

/// Code points that are already UTS #46 identity, NFC, LTR, and joiner-safe.
/// Covers the Criterion IDNA bench (`türkçe`) and common CJK/kana/Hangul IDNs.
///
/// Must not include combining marks: skipping NFC for those would both accept
/// leading Mn (should reject) and produce distinct ACE labels for precomposed
/// vs decomposed kana (homograph risk).
#[inline]
fn is_simple_identity_cp(c: char) -> bool {
    let u = c as u32;
    // Latin-1 lowercase letters + ß (non-transitional keeps ß).
    // Excludes × (U+00D7) and ÷ (U+00F7) by range gaps.
    if (0x00E0..=0x00F6).contains(&u) || (0x00F8..=0x00FF).contains(&u) || u == 0x00DF {
        return true;
    }
    // CJK Unified Ideographs + Extension A (all Lo; no combining marks).
    if (0x3400..=0x4DBF).contains(&u) || (0x4E00..=0x9FFF).contains(&u) {
        return true;
    }
    // Hiragana / Katakana — exclude unassigned U+3040/U+3097/U+3098 and Mn U+3099/U+309A.
    if (0x3041..=0x3096).contains(&u)
        || (0x309B..=0x309F).contains(&u)
        || (0x30A0..=0x30FF).contains(&u)
    {
        return true;
    }
    // Hangul syllables (Unicode ends at U+D7A3; U+D7A4..=U+D7AF are unassigned).
    (0xAC00..=0xD7A3).contains(&u)
}

#[inline]
fn char_needs_uts46_map(c: char) -> bool {
    // Static membership (ignored / rewritten / compatibility) from generated tables.
    if uts46_needs_map_cp(c) || maps_nfkc_via_space(c) || letterlike_nfkc_ascii(c).is_some() {
        return true;
    }
    if c.is_ascii() {
        return c.is_ascii_uppercase();
    }
    // Hot IDN letters: no map / case fold / NFKC.
    if is_simple_identity_cp(c) {
        return false;
    }
    // Latin-1 uppercase → needs fold (before expensive NFKC).
    let u = c as u32;
    if (0x00C0..=0x00D6).contains(&u) || (0x00D8..=0x00DE).contains(&u) {
        return true;
    }
    // Detect U+0345 without allocating an NFD `String`.
    let mut has_ypogegrammeni = false;
    unicode_normalization::char::decompose_canonical(c, |d| {
        if d == '\u{0345}' {
            has_ypogegrammeni = true;
        }
    });
    if has_ypogegrammeni {
        return true;
    }
    let mut it = c.nfkc();
    match (it.next(), it.next()) {
        (Some(ch), None) if ch == c => needs_unicode_case_fold(c),
        _ => true, // expands or remaps under NFKC
    }
}

/// True when `c.to_lowercase()` is not the single code point `c`.
#[inline]
fn needs_unicode_case_fold(c: char) -> bool {
    let u = c as u32;
    // Fast path: already-lowercase Latin-1 letters (covers ü/ç/ö/… IDN bench).
    if (0x00E0..=0x00F6).contains(&u) || (0x00F8..=0x00FF).contains(&u) || u == 0x00DF {
        return false;
    }
    // Latin-1 uppercase → needs fold.
    if (0x00C0..=0x00D6).contains(&u) || (0x00D8..=0x00DE).contains(&u) {
        return true;
    }
    // General Unicode: only call std tables when outside the Latin-1 shortcuts.
    let mut iter = c.to_lowercase();
    match (iter.next(), iter.next()) {
        (Some(l), None) => l != c,
        _ => true,
    }
}

/// Minimal UTS #46 disallowed set covering WPT failures (noncharacters, spaces,
/// replacement char, line/paragraph separators). Full UTS46 tables are
/// intentionally not embedded — membership ranges are derived at build time
/// from vendored UCD (`data/ucd/`) plus `data/idna_overlay.txt`.
#[inline]
fn is_disallowed_idna(c: char) -> bool {
    if is_disallowed_cp(c) {
        return true;
    }
    let u = c as u32;
    // Unassigned Unicode planes 4..=13 (e.g. U+D71CB).
    if matches!(u >> 16, 4..=13) {
        return true;
    }
    // Noncharacters: any plane's U+FFFE / U+FFFF.
    (u & 0xFFFE) == 0xFFFE
}

fn lowercase_ascii(s: &str) -> Cow<'_, str> {
    if s.bytes().all(|b| !b.is_ascii_uppercase()) {
        Cow::Borrowed(s)
    } else {
        Cow::Owned(s.to_ascii_lowercase())
    }
}

/// Forbidden host code point, C0 control, `%`, or DEL.
#[inline]
fn contains_forbidden_domain_code_point(s: &str) -> bool {
    s.bytes().any(|b| {
        matches!(
            b,
            0x00..=0x1F
                | b' '
                | b'#'
                | b'/'
                | b':'
                | b'<'
                | b'>'
                | b'?'
                | b'@'
                | b'['
                | b'\\'
                | b']'
                | b'^'
                | b'|'
                | b'%'
                | 0x7F
        )
    })
}

/// Minimal CheckBidi (RFC 5893 subset used by UTS #46 CheckBidi=true):
/// - Reject labels mixing RTL script with LTR letters.
/// - RTL labels must start with an RTL letter and end with RTL or a digit (EN/AN).
fn label_fails_check_bidi(label: &str) -> bool {
    let mut has_rtl = false;
    let mut has_ltr = false;
    for c in label.chars() {
        // NSM / combining marks / ZWNJ are neither R nor L for CheckBidi mixing.
        if is_bidi_transparent(c) {
            continue;
        }
        if is_rtl_script(c) {
            has_rtl = true;
        } else if is_ltr_letter(c) {
            has_ltr = true;
        }
        if has_rtl && has_ltr {
            return true;
        }
    }
    if has_rtl && !has_ltr {
        let mut chars = label.chars();
        let first = chars.next();
        // Skip trailing NSM (e.g. Thaana vowel signs U+07A6..=U+07B0): browsers
        // / ICU treat the last *strong* char as the CheckBidi end (Node accepts
        // `\u{7a3}\u{7aa}` → xn--hrbo).
        let last_strong = label.chars().rev().find(|c| !is_bidi_transparent(*c));
        let last_ok = last_strong.is_some_and(|c| is_rtl_script(c) || is_bidi_number(c));
        if !first.is_some_and(is_rtl_script) || !last_ok {
            return true;
        }
    }
    false
}

#[inline]
fn is_bidi_transparent(c: char) -> bool {
    // NSM / combining marks from the generated table, plus ZWNJ/ZWJ (CheckJoiners).
    is_bidi_ignored_mark(c) || matches!(c, '\u{200C}' | '\u{200D}')
}

/// EN (ASCII digits) or AN (Arabic-Indic digits) — valid RTL-label trailers.
#[inline]
fn is_bidi_number(c: char) -> bool {
    c.is_ascii_digit() || is_bidi_number_cp(c)
}

#[inline]
fn is_rtl_script(c: char) -> bool {
    // Strong RTL letters. Arabic/Hebrew *marks* (Mn), e.g. U+0613, must not
    // trip CheckBidi mixing even though Rust's `is_alphabetic()` is true for some.
    // Neutrals like U+06DE stay out so `\u{6de}e` still encodes.
    if is_bidi_ignored_mark(c) {
        return false;
    }
    if is_rtl_non_letter(c) {
        return true;
    }
    c.is_alphabetic() && is_rtl_alphabetic_block(c)
}

/// Node/ICU rejects Arabic Extended-B letters mixed with older Arabic letters or
/// other RTL scripts. Allowed companions: other Ext-B, U14+ Ext-A (U+08B5,
/// U+08C8..), marks/NSM, EN/AN digits, and neutrals.
fn label_fails_arabic_ext_b_mix(label: &str) -> bool {
    let mut has_ext_b = false;
    let mut has_incompatible = false;
    for c in label.chars() {
        if is_bidi_transparent(c) {
            continue;
        }
        if is_arabic_ext_b_letter(c) {
            has_ext_b = true;
            continue;
        }
        if c == '\u{0888}' {
            // Ext-B Sk symbol — allowed with Ext-B letters; counts as Ext-B context.
            has_ext_b = true;
            continue;
        }
        if is_arabic_ext_b_compatible(c) || is_bidi_number(c) || c.is_ascii() {
            continue;
        }
        // Other strong RTL / legacy Arabic letters / LTR letters are incompatible.
        if is_rtl_script(c) || is_legacy_arabic_letter(c) || is_ltr_letter(c) {
            has_incompatible = true;
        }
        if has_ext_b && has_incompatible {
            return true;
        }
    }
    has_ext_b && has_incompatible
}

#[inline]
fn is_arabic_ext_b_letter(c: char) -> bool {
    is_arabic_ext_b_letter_cp(c)
}

/// Ext-A letters that Node allows beside Arabic Extended-B (Unicode 14+).
#[inline]
fn is_arabic_ext_b_compatible(c: char) -> bool {
    is_arabic_ext_b_compatible_cp(c)
}

/// U14 Ext-B / early Ext-A Mn: Node allows with Ext-B / U14 Ext-A / LTR, not with
/// classic Arabic / Thaana / other legacy RTL.
#[inline]
fn is_arabic_ext_b_era_mark(c: char) -> bool {
    is_arabic_ext_b_era_mark_cp(c)
}

fn label_fails_ext_b_era_mark_mix(label: &str) -> bool {
    if !label.chars().any(is_arabic_ext_b_era_mark) {
        return false;
    }
    for c in label.chars() {
        if is_bidi_transparent(c) || is_arabic_ext_b_era_mark(c) {
            continue;
        }
        if is_arabic_ext_b_letter(c)
            || c == '\u{0888}'
            || is_arabic_ext_b_era_ok_cp(c)
            || is_bidi_number(c)
            || c.is_ascii()
            || is_ltr_letter(c)
        {
            continue;
        }
        if is_rtl_script(c) || is_legacy_arabic_letter(c) {
            return true;
        }
    }
    false
}

#[inline]
fn is_legacy_arabic_letter(c: char) -> bool {
    is_legacy_arabic_cp(c)
}

/// Minimal CheckJoiners (UTS #46):
/// - ZWNJ (U+200C): only between two joining letters (Arabic/Syriac; NSM skipped).
/// - ZWJ (U+200D): ContextJ — preceding code point has CCC=Virama (9) (Node/ICU).
fn label_fails_check_joiners(label: &str) -> bool {
    // UTF-8 for U+200C/U+200D is E2 80 8C / E2 80 8D — skip Vec alloc when absent.
    if !label_may_contain_zwj_or_zwnj(label) {
        return false;
    }
    let chars: Vec<char> = label.chars().collect();
    for (i, &c) in chars.iter().enumerate() {
        if c == '\u{200D}' {
            // RFC 5892 §A.2: Before(cp) is the immediately preceding character.
            match chars.get(i.wrapping_sub(1)).filter(|_| i > 0) {
                Some(&b) if canonical_combining_class(b) == 9 => {}
                _ => return true,
            }
            continue;
        }
        if c != '\u{200C}' {
            continue;
        }
        let before = chars[..i].iter().rev().find(|c| !is_bidi_transparent(**c));
        let after = chars[i + 1..].iter().find(|c| !is_bidi_transparent(**c));
        match (before, after) {
            (Some(&b), Some(&a)) if is_joining_letter(b) && is_joining_letter(a) => {}
            _ => return true,
        }
    }
    false
}

#[inline]
fn label_may_contain_zwj_or_zwnj(label: &str) -> bool {
    let bytes = label.as_bytes();
    let mut i = 0;
    while i + 2 < bytes.len() {
        if bytes[i] == 0xE2 && bytes[i + 1] == 0x80 && matches!(bytes[i + 2], 0x8C | 0x8D) {
            return true;
        }
        i += 1;
    }
    false
}

#[inline]
fn is_joining_letter(c: char) -> bool {
    c.is_alphabetic() && is_joining_letter_cp(c)
}

#[inline]
fn is_ltr_letter(c: char) -> bool {
    // ASCII / Latin / Greek / Cyrillic *letters* only (not ÷ U+00F7 etc.).
    c.is_alphabetic() && (c.is_ascii_alphabetic() || is_ltr_letter_block(c))
}

/// Fast path for [`Scan::SimpleIdentity`]: Punycode-encode non-ASCII labels only.
fn encode_domain_labels_simple(mapped: &str, out: &mut impl AppendBuf) -> Result<(), ()> {
    let mut first = true;
    for label in mapped.split('.') {
        if !first {
            out.push('.');
        }
        first = false;
        if label.is_empty() {
            continue;
        }
        if label.is_ascii() {
            out.push_str(label);
        } else {
            out.push_str("xn--");
            encode_punycode(label, out)?;
        }
    }
    Ok(())
}

fn encode_domain_labels(mapped: &str, out: &mut impl AppendBuf) -> Result<(), ()> {
    let mut first = true;
    for label in mapped.split('.') {
        if !first {
            out.push('.');
        }
        first = false;
        if label.is_empty() {
            continue;
        }
        // UTS #46: NFC before validity checks + Punycode. Composition can move a
        // mark onto a prior starter (e.g. n+virama+cedilla → ņ+virama), which
        // CheckJoiners must observe so ZWJ still sees CCC=Virama immediately before.
        let nfc_owned;
        let label = if unicode_normalization::is_nfc(label) {
            label
        } else {
            nfc_owned = label.nfc().collect::<String>();
            nfc_owned.as_str()
        };
        // Leading combining mark (no base character) — reject (ada/rust-url).
        if label.chars().next().is_some_and(is_bidi_ignored_mark) {
            return Err(());
        }
        if label_fails_check_bidi(label) {
            return Err(());
        }
        if label_fails_arabic_ext_b_mix(label) {
            return Err(());
        }
        if label_fails_ext_b_era_mark_mix(label) {
            return Err(());
        }
        if label_fails_check_joiners(label) {
            return Err(());
        }
        if label.is_ascii() {
            out.push_str(label);
        } else {
            out.push_str("xn--");
            encode_punycode(label, out)?;
        }
    }
    Ok(())
}

/// Map + reject disallowed code points that appear only after mapping.
fn uts46_map_checked(input: &str) -> Result<String, ()> {
    let mut out = String::with_capacity(input.len());
    for c in input.chars() {
        map_char(c, &mut out);
    }
    if out.is_empty()
        || out.chars().any(is_disallowed_idna)
        || contains_forbidden_domain_code_point(&out)
    {
        return Err(());
    }
    Ok(out)
}

fn map_char(c: char, out: &mut String) {
    // Ignored (UTS #46): soft hyphen, ZWSP, WJ, BOM, CGJ, Hangul fillers,
    // variation selectors (incl. supplementary) — membership from generated table.
    if is_uts46_ignored_cp(c) {
        return;
    }

    match c {
        // U+2000..=U+200A space-ish → ASCII space (then forbidden-host rejects).
        '\u{2000}'..='\u{200A}' => out.push(' '),

        // Non-breaking hyphen → NFKC hyphen (U+2010); stays non-ASCII for Punycode.
        '\u{2011}' => out.push('\u{2010}'),

        // Ideographic full stop / halfwidth variant → ASCII dot.
        '\u{3002}' | '\u{FF61}' => out.push('.'),

        // Cyrillic Extended-C (UTS #46 mapped; NFKC is identity).
        '\u{1C80}' => out.push('\u{0432}'), // rounded ve → в
        '\u{1C81}' => out.push('\u{0434}'), // long-legged de → д
        '\u{1C82}' => out.push('\u{043E}'), // narrow o → о
        '\u{1C83}' => out.push('\u{0441}'), // wide es → с
        '\u{1C84}' | '\u{1C85}' => out.push('\u{0442}'), // tall/three-legged te → т
        '\u{1C86}' => out.push('\u{044A}'), // tall hard sign → ъ
        '\u{1C87}' => out.push('\u{0463}'), // tall yat → ѣ
        '\u{1C88}' => out.push('\u{A64B}'), // unblended uk → ꙋ
        '\u{1C89}' => out.push('\u{1C8A}'), // capital tje → small tje

        // Cherokee small letters U+13F8..=U+13FD → capitals U+13F0..=U+13F5
        // (UTS #46; must not case-fold to U+AB70 phonetic extensions).
        '\u{13F8}' => out.push('\u{13F0}'),
        '\u{13F9}' => out.push('\u{13F1}'),
        '\u{13FA}' => out.push('\u{13F2}'),
        '\u{13FB}' => out.push('\u{13F3}'),
        '\u{13FC}' => out.push('\u{13F4}'),
        '\u{13FD}' => out.push('\u{13F5}'),

        // Cherokee Supplement small letters → capital Cherokee (UTS #46 mapped).
        // Rust `to_lowercase` is a no-op here; case fold is AB70+n → 13A0+n.
        c @ '\u{AB70}'..='\u{ABBF}' => {
            out.push(char::from_u32(0x13A0 + (c as u32 - 0xAB70)).unwrap_or(c));
        }

        // U+203E OVERLINE → NFKC `<space><combining overline>`; space then fails
        // the forbidden-host check (matches ada / rust-url rejection).
        '\u{203E}' => {
            out.push(' ');
            out.push('\u{0305}');
        }

        // Compatibility chars whose NFKC introduces SPACE (then forbidden-host rejects).
        c if maps_nfkc_via_space(c) => {
            for ch in c.nfkc() {
                out.push(ch);
            }
        }

        // Vulgar fractions / Number Forms → NFKC (e.g. ¼ → 1⁄4, ⅛ → 1⁄8).
        // Case-fold too: U+2183 ROMAN NUMERAL REVERSED ONE HUNDRED → U+2184.
        '\u{00BC}'..='\u{00BE}' | '\u{2150}'..='\u{2189}' => {
            for ch in c.nfkc() {
                for folded in ch.to_lowercase() {
                    if folded.is_ascii() {
                        out.push(folded.to_ascii_lowercase());
                    } else {
                        out.push(folded);
                    }
                }
            }
        }

        // Superscripts / subscripts → NFKC (e.g. ⁵ → 5) so IPv4 ends-in-a-number works.
        '\u{00B2}' | '\u{00B3}' | '\u{00B9}' | '\u{2070}'..='\u{209F}' => {
            for ch in c.nfkc() {
                out.push(ch);
            }
        }

        // U+0345 COMBINING GREEK YPOGEGRAMMENI → ι (Unicode case fold).
        '\u{0345}' => out.push('\u{03B9}'),
        // U+03F2 LUNATE SIGMA → U+03C3 (browsers keep U+03C2 final sigma as-is).
        '\u{03F2}' => out.push('\u{03C3}'),
        // Mathematical *final* sigma variants: UTS #46 maps to U+03C3 (not NFKC's U+03C2).
        '\u{1D6D3}' | '\u{1D70D}' | '\u{1D747}' | '\u{1D781}' | '\u{1D7BB}' => out.push('\u{03C3}'),
        '\u{00AA}'
        | '\u{00BA}'
        | '\u{01C4}'..='\u{01CC}'
        | '\u{03D0}'..='\u{03D7}'
        | '\u{03F0}'..='\u{03F1}'
        | '\u{03F4}'..='\u{03F5}' => {
            for ch in c.nfkc() {
                for folded in ch.to_lowercase() {
                    if folded.is_ascii() {
                        out.push(folded.to_ascii_lowercase());
                    } else {
                        out.push(folded);
                    }
                }
            }
        }

        // Fullwidth ASCII (! through ~): U+FF01..=U+FF5E → U+0021..=U+007E
        '\u{FF01}'..='\u{FF5E}' => {
            let mapped = char::from_u32(u32::from(c) - 0xFEE0).unwrap_or(c);
            out.push(mapped.to_ascii_lowercase());
        }

        // Mathematical Bold Capitals A–Z (U+1D400..=U+1D419)
        c if (0x1D400..=0x1D419).contains(&(c as u32)) => {
            out.push(char::from(b'a' + (c as u32 - 0x1D400) as u8));
        }
        // Mathematical Bold Small a–z (U+1D41A..=U+1D433)
        c if (0x1D41A..=0x1D433).contains(&(c as u32)) => {
            out.push(char::from(b'a' + (c as u32 - 0x1D41A) as u8));
        }

        // Letterlike Symbols → ASCII NFKC (then lowercased).
        c if letterlike_nfkc_ascii(c).is_some() => {
            let mapped = letterlike_nfkc_ascii(c).unwrap();
            for ch in mapped.chars() {
                out.push(ch.to_ascii_lowercase());
            }
        }

        c if c.is_ascii() => out.push(c.to_ascii_lowercase()),

        // Latin-1 already-lowercase / ß: push without std Unicode tables.
        c if {
            let u = c as u32;
            (0x00E0..=0x00F6).contains(&u) || (0x00F8..=0x00FF).contains(&u) || u == 0x00DF
        } =>
        {
            out.push(c);
        }

        // Latin-1 uppercase → lowercase without iterator.
        c if {
            let u = c as u32;
            (0x00C0..=0x00D6).contains(&u) || (0x00D8..=0x00DE).contains(&u)
        } =>
        {
            out.push(char::from_u32((c as u32) + 0x20).unwrap_or(c));
        }

        c => {
            // UTS #46 compatibility mapping via NFKC (ligatures, Hangul compat,
            // math symbols like U+2230 → 3×U+222E, …), then case fold.
            // Cherokee U+13A0..=U+13F5: ada/ICU keep uppercase code points (do not
            // map to U+AB70 small letters) — matches Node domainToASCII.
            for ch in c.nfkc() {
                if matches!(ch, '\u{13A0}'..='\u{13F5}') {
                    out.push(ch);
                    continue;
                }
                if ch == '\u{3002}' {
                    out.push('.');
                    continue;
                }
                // Greek ypogegrammeni forms (e.g. U+1FC4): NFD then U+0345 → ι
                // so NFC later yields ήι like ICU/Node (Rust to_lowercase keeps 1FC4).
                let nfd: String = ch.nfd().collect();
                if nfd.contains('\u{0345}') {
                    for d in nfd.chars() {
                        if d == '\u{0345}' {
                            out.push('\u{03B9}');
                        } else {
                            for folded in d.to_lowercase() {
                                if folded.is_ascii() {
                                    out.push(folded.to_ascii_lowercase());
                                } else {
                                    out.push(folded);
                                }
                            }
                        }
                    }
                    continue;
                }
                for folded in ch.to_lowercase() {
                    if folded.is_ascii() {
                        out.push(folded.to_ascii_lowercase());
                    } else {
                        out.push(folded);
                    }
                }
            }
        }
    }
}

/// Compatibility characters whose NFKC form starts with SPACE (rejected as host).
#[inline]
fn maps_nfkc_via_space(c: char) -> bool {
    maps_nfkc_via_space_cp(c)
}

/// Compact UTS #46 / NFKC ASCII mappings for Letterlike Symbols (U+2100..=U+214F).
#[inline]
fn letterlike_nfkc_ascii(c: char) -> Option<&'static str> {
    Some(match c {
        '\u{2100}' => "a/c",
        '\u{2101}' => "a/s",
        '\u{2102}' => "C",
        '\u{2105}' => "c/o",
        '\u{2106}' => "c/u",
        '\u{210A}' => "g",
        '\u{210B}' => "H",
        '\u{210C}' => "H",
        '\u{210D}' => "H",
        '\u{210E}' => "h",
        '\u{2110}' => "I",
        '\u{2111}' => "I",
        '\u{2112}' => "L",
        '\u{2113}' => "l",
        '\u{2115}' => "N",
        '\u{2116}' => "No",
        '\u{2119}' => "P",
        '\u{211A}' => "Q",
        '\u{211B}' => "R",
        '\u{211C}' => "R",
        '\u{211D}' => "R",
        '\u{2120}' => "SM",
        '\u{2121}' => "TEL",
        '\u{2122}' => "TM",
        '\u{2124}' => "Z",
        '\u{2128}' => "Z",
        '\u{212A}' => "K",
        '\u{212C}' => "B",
        '\u{212D}' => "C",
        '\u{212F}' => "e",
        '\u{2130}' => "E",
        '\u{2131}' => "F",
        '\u{2133}' => "M",
        '\u{2134}' => "o",
        '\u{2139}' => "i",
        '\u{213B}' => "FAX",
        '\u{2145}' => "D",
        '\u{2146}' => "d",
        '\u{2147}' => "e",
        '\u{2148}' => "i",
        '\u{2149}' => "j",
        _ => return None,
    })
}

// ---------------------------------------------------------------------------
// RFC 3492 Punycode encode
// ---------------------------------------------------------------------------

const BASE: u32 = 36;
const TMIN: u32 = 1;
const TMAX: u32 = 26;
const SKEW: u32 = 38;
const DAMP: u32 = 700;
const INITIAL_BIAS: u32 = 72;
const INITIAL_N: u32 = 128;

/// Stack buffer for typical IDN labels (DNS label ≤ 63 octets after ACE).
const STACK_LABEL_CHARS: usize = 64;

fn encode_punycode(input: &str, out: &mut impl AppendBuf) -> Result<(), ()> {
    #![allow(clippy::many_single_char_names)] // RFC 3492 names: n, h, b, m, q, k
    // Stack ACE buffer (DNS label ≤ 63; headroom for edge cases before reject).
    let mut ace = [0u8; 128];
    let mut ace_len = 0usize;
    let push_ascii = |ace: &mut [u8; 128], ace_len: &mut usize, b: u8| -> Result<(), ()> {
        if *ace_len >= ace.len() {
            return Err(());
        }
        ace[*ace_len] = b;
        *ace_len += 1;
        Ok(())
    };

    let mut n = INITIAL_N;
    let mut delta: u32 = 0;
    let mut bias = INITIAL_BIAS;

    let mut stack = [0u32; STACK_LABEL_CHARS];
    let mut heap: Vec<u32> = Vec::new();
    let mut len = 0usize;
    for c in input.chars() {
        let cp = c as u32;
        if len < STACK_LABEL_CHARS && heap.is_empty() {
            stack[len] = cp;
            len += 1;
        } else {
            if heap.is_empty() {
                heap.reserve(len + 8);
                heap.extend_from_slice(&stack[..len]);
            }
            heap.push(cp);
            len += 1;
        }
    }
    // Oversized inputs rejected early (DNS-scale labels stay well below this).
    if len > 256 {
        return Err(());
    }
    let chars: &[u32] = if heap.is_empty() {
        &stack[..len]
    } else {
        &heap
    };

    let mut basic_count = 0u32;
    for &cp in chars {
        if cp < 0x80 {
            push_ascii(&mut ace, &mut ace_len, (cp as u8).to_ascii_lowercase())?;
            basic_count += 1;
        }
    }

    let mut h = basic_count;
    let b = basic_count;
    if b > 0 {
        push_ascii(&mut ace, &mut ace_len, b'-')?;
    }

    while (h as usize) < chars.len() {
        let mut m = u32::MAX;
        for &cp in chars {
            if cp >= n && cp < m {
                m = cp;
            }
        }
        if m == u32::MAX {
            return Err(());
        }

        let advance = m.checked_sub(n).ok_or(())?;
        delta = delta
            .checked_add(advance.checked_mul(h.checked_add(1).ok_or(())?).ok_or(())?)
            .ok_or(())?;
        n = m;

        for &cp in chars {
            if cp < n {
                delta = delta.checked_add(1).ok_or(())?;
            } else if cp == n {
                let mut q = delta;
                let mut k = BASE;
                loop {
                    let t = if k <= bias {
                        TMIN
                    } else if k >= bias.saturating_add(TMAX) {
                        TMAX
                    } else {
                        k - bias
                    };
                    if q < t {
                        break;
                    }
                    let code = t + ((q - t) % (BASE - t));
                    push_ascii(&mut ace, &mut ace_len, digit_to_byte(code)?)?;
                    q = (q - t) / (BASE - t);
                    k = k.checked_add(BASE).ok_or(())?;
                }
                push_ascii(&mut ace, &mut ace_len, digit_to_byte(q)?)?;
                bias = adapt(delta, h + 1, h == b);
                delta = 0;
                h += 1;
            }
        }
        delta = delta.checked_add(1).ok_or(())?;
        n = n.checked_add(1).ok_or(())?;
    }
    let ace_str = core::str::from_utf8(&ace[..ace_len]).map_err(|_| ())?;
    out.push_str(ace_str);
    Ok(())
}

fn adapt(mut delta: u32, num_points: u32, first_time: bool) -> u32 {
    delta = if first_time { delta / DAMP } else { delta / 2 };
    delta += delta / num_points;
    let mut k = 0u32;
    while delta > ((BASE - TMIN) * TMAX) / 2 {
        delta /= BASE - TMIN;
        k += BASE;
    }
    k + (((BASE - TMIN + 1) * delta) / (delta + SKEW))
}

fn digit_to_byte(d: u32) -> Result<u8, ()> {
    match d {
        0..=25 => Ok(b'a' + d as u8),
        26..=35 => Ok(b'0' + (d as u8 - 26)),
        _ => Err(()),
    }
}

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

    #[test]
    fn ascii_passthrough_invalid_punycode() {
        assert_eq!(
            to_ascii("a.b.c.xn--pokxncvks").unwrap(),
            "a.b.c.xn--pokxncvks"
        );
        assert_eq!(to_ascii("XN--").unwrap(), "xn--");
    }

    #[test]
    fn punycode_examples() {
        assert_eq!(to_ascii("é").unwrap(), "xn--9ca");
        assert_eq!(to_ascii("你好你好").unwrap(), "xn--6qqa088eba");
        assert_eq!(to_ascii("faß.ExAmPlE").unwrap(), "xn--fa-hia.example");
        assert_eq!(to_ascii("").unwrap(), "xn--n3h");
        assert!(to_ascii("\u{fffd}").is_err());
        assert!(to_ascii("GOO\u{a0}goo.com").is_err());
    }

    #[test]
    fn mapping_examples() {
        assert_eq!(to_ascii("Go.com").unwrap(), "go.com");
        assert_eq!(to_ascii("www.foo。bar.com").unwrap(), "www.foo.bar.com");
        assert_eq!(
            to_ascii("GOO\u{200b}\u{2060}\u{feff}goo.com").unwrap(),
            "googoo.com"
        );
        assert_eq!(to_ascii("a\u{ad}b").unwrap(), "ab");
        assert_eq!(to_ascii("loC𝐀𝐋𝐇𝐨𝐬𝐭").unwrap(), "localhost");
        // U+210B SCRIPT CAPITAL H → h (letterlike NFKC)
        assert_eq!(to_ascii("\u{210B}").unwrap(), "h");
        // CheckBidi: Arabic + Cyrillic in one label
        assert!(to_ascii("ےў").is_err());
        // CheckBidi: RTL label must not start with hyphen
        assert!(to_ascii("-\u{068B}").is_err());
        // Unassigned plane
        assert!(to_ascii("\u{d71cb}").is_err());
        // OVERLINE maps to space+mark → forbidden
        assert!(to_ascii("\u{203E}").is_err());
        // Combining mark + Latin can fail joining/bidi depending on input; `*` alone is allowed
        // (UseSTD3ASCIIRules=false in WHATWG URL).
        assert_eq!(to_ascii("sw*").unwrap(), "sw*");
    }

    #[test]
    fn identity_turkish_bench_label() {
        assert_eq!(to_ascii("türkçe.com").unwrap(), "xn--trke-2oa7j.com");
        assert_eq!(scan_non_ascii("türkçe.com"), Ok(Scan::SimpleIdentity));
        assert_eq!(scan_non_ascii("你好你好.com"), Ok(Scan::SimpleIdentity));
        // Combining mark → full Identity / NeedsMap path (NFC required).
        assert_ne!(scan_non_ascii("a\u{0301}.com"), Ok(Scan::SimpleIdentity));
    }

    #[test]
    fn to_ascii_into_matches_to_ascii() {
        let domain = "türkçe.com";
        let mut buf = String::new();
        to_ascii_into(domain, &mut buf).unwrap();
        assert_eq!(buf, to_ascii(domain).unwrap());
    }
}

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

    #[test]
    fn arabic_nsm_with_latin_ok() {
        let domain = "ex\u{613}";
        assert!(!domain.is_ascii());
        let scan = scan_non_ascii(domain);
        assert!(scan.is_ok(), "scan={scan:?}");
        println!("scan={:?}", scan.unwrap());

        // CheckBidi on label
        assert!(!label_fails_check_bidi(domain), "bidi failed");

        let mut buf = String::new();
        let enc = encode_domain_labels(domain, &mut buf);
        assert!(enc.is_ok(), "encode={enc:?} buf={buf}");
        println!("encoded={buf}");

        let r = to_ascii(domain);
        assert!(r.is_ok(), "to_ascii={r:?}");
    }
}

#[cfg(test)]
mod tick_fixes {
    use super::*;
    #[test]
    fn nfc_cedilla() {
        assert_eq!(to_ascii("--tabout\u{327}").unwrap(), "xn----tabou-drb");
    }
    #[test]
    fn leading_mark_rejected() {
        assert!(to_ascii("\u{34b}g").is_err());
        assert!(to_ascii("\u{5c7}e").is_err());
        // U+05CC is unassigned (not a mark) — rejected via disallowed set.
        assert!(to_ascii("\u{5cc}sw*").is_err());
    }
    #[test]
    fn nfkc_fractions_and_space_compat() {
        assert_eq!(to_ascii("sst\u{00bc}r").unwrap(), "xn--sst14r-sq0c");
        assert_eq!(to_ascii("h\u{215b}1").unwrap(), "xn--h181-1g7a");
        assert!(to_ascii("h\u{00a8}J").is_err());
        assert!(to_ascii("z\u{0385}").is_err());
        assert!(to_ascii("0w\u{02d9}\u{043f}.").is_err());
        assert!(to_ascii("8888888888888\u{202b}out8B88HTTP").is_err());
        assert!(to_ascii("+t\u{00fc}M\u{008e}=1\u{00e7}.com").is_err());
        assert_eq!(to_ascii("\u{01ca}s").unwrap(), "njs");
        assert_eq!(to_ascii("h\u{2011}").unwrap(), "xn--h-0gn");
        assert_eq!(to_ascii("\u{03d2}").unwrap(), "xn--6xa");
        assert_eq!(to_ascii("2e2\u{00aa}dta0").unwrap(), "2e2adta0");
        assert!(to_ascii("c\u{e691}").is_err());
        assert!(to_ascii("\u{200d}b").is_err());
        assert_eq!(
            to_ascii("255.255.255.2\u{2075}85").unwrap(),
            "255.255.255.2585"
        );
        assert_eq!(to_ascii("\u{587}7\u{187}7f").unwrap(), "xn--77f-h4a750c8e");
        assert_eq!(to_ascii("7\u{2230},").unwrap(), "xn--7,-cevaa");
        assert_eq!(to_ascii("\u{314f}ile").unwrap(), "xn--ile-3do");
        assert_eq!(to_ascii("\u{6de}e").unwrap(), "xn--e-fxc");
        assert!(to_ascii("\u{6de}").is_ok(), "{:?}", to_ascii("\u{6de}"));
        // Thaana letter + trailing vowel sign (NSM): CheckBidi end skips NSM.
        assert_eq!(to_ascii("\u{7a3}\u{7aa}").unwrap(), "xn--hrbo");
        assert_eq!(to_ascii("\u{7ff}\u{5e8}").unwrap(), "xn--teb38h");
        assert_eq!(to_ascii("\u{5c0}").unwrap(), "xn--odb");
        assert!(to_ascii("0x=7f00\u{248b}ac").is_err());
        assert_eq!(to_ascii("s\u{3f2}x").unwrap(), "xn--sx-vbc");
        assert_eq!(to_ascii("c\u{3c2}").unwrap(), "xn--c-ymb"); // keep final sigma
        assert_eq!(to_ascii("D\u{7fd}").unwrap(), "xn--d-ued");
        assert_eq!(to_ascii("\u{7ff}\u{7c8}").unwrap(), "xn--jsb3i");
        assert_eq!(to_ascii("a\u{1160}b").unwrap(), "ab");
        assert_eq!(to_ascii("5x\u{345}fl").unwrap(), "xn--5xfl-6md");
    }
    #[test]
    fn unassigned_greek() {
        assert!(to_ascii("s\u{38d}w").is_err());
    }
}

#[cfg(test)]
mod tick18 {
    use super::*;
    #[test]
    fn cases() {
        assert_eq!(
            to_ascii("\u{5c6}\u{7fd}\u{5c7}\u{6fd}").unwrap(),
            "xn--udbc44gi3a"
        );
        assert_eq!(
            to_ascii("87\u{116e}\u{13a5}\u{116b}B").unwrap(),
            "xn--87b-bfoo615a"
        );
    }
}

#[cfg(test)]
mod tick19 {
    use super::*;
    #[test]
    fn check_bidi_skips_cyrillic_marks() {
        assert_eq!(to_ascii("\u{5c0}\u{484}\u{5c5}").unwrap(), "xn--n3a54dpa");
    }
    #[test]
    fn greek_ypogegrammeni_expands() {
        assert_eq!(
            to_ascii("\u{1940}DXXE\u{1c80}").unwrap(),
            "xn--dxxe-j4d9443a"
        );
        assert_eq!(to_ascii("\u{13fa}").unwrap(), "xn--ice");
        assert_eq!(to_ascii("\u{1c89}").unwrap(), "xn--d4f");
        assert_eq!(to_ascii("\u{1fc4}\u{1c89}").unwrap(), "xn--jxaw371q");
        assert_eq!(to_ascii("\u{fd9e}\u{ff9e}").unwrap(), "xn--ngbm8fw67r");
        assert_eq!(to_ascii("\u{ffa0}.").unwrap(), ".");
        assert!(to_ascii("\u{ffa0}").is_err()); // ignored → empty host
        assert_eq!(
            to_ascii("\u{700}\u{1dc0}\u{1dc0}\u{1dc0}").unwrap(),
            "xn--tmb267iaa"
        );
        assert_eq!(to_ascii("\u{069c}\u{1032}").unwrap(), "xn--yjb220c");
        assert_eq!(
            to_ascii("\u{079c}\u{065c}\u{0658}\u{0a4b}").unwrap(),
            "xn--0hbh37gu8e"
        );
        assert_eq!(
            to_ascii("\u{079c}\u{065e}\u{065c}\u{0658}\u{0902}").unwrap(),
            "xn--0hbhg48jizc"
        );
        assert_eq!(
            to_ascii("vvvvv\u{fb1e}\u{fb1e}").unwrap(),
            "xn--vvvvv-xi82aa"
        );
        assert_eq!(to_ascii("f\u{fb1e}\u{ff9e}").unwrap(), "xn--f-wdu9988e");
        assert_eq!(
            to_ascii("\u{079c}\u{065c}\u{1886}").unwrap(),
            "xn--4hb35dg58a"
        );
        assert_eq!(to_ascii("\u{080f}2\u{09c1}").unwrap(), "xn--2-ufd71k");
        assert_eq!(to_ascii("\u{079c}\u{0861}").unwrap(), "xn--9qb80b");
        assert_eq!(
            to_ascii("\u{0642}\u{065c}\u{200c}\u{0642}\u{065c}").unwrap(),
            "xn--ehba1fb2993a"
        );
        assert!(to_ascii("a\u{200c}b").is_err());
        assert_eq!(to_ascii("\u{0629}\u{0c81}").unwrap(), "xn--ogb263a");
        assert_eq!(to_ascii("\u{0869}\u{0c81}").unwrap(), "xn--4wb01s");
        assert_eq!(to_ascii("\u{088f}").unwrap(), "xn--7xb");
        assert!(to_ascii("\u{088f}\u{084f}").is_err()); // CheckBidi mix
        assert!(to_ascii("\u{0890}").is_err());
        assert!(to_ascii("\u{1c8b}").is_err());
        assert!(to_ascii("\u{079c}\u{08d2}").is_err()); // Node rejects Ext-A mark mix
        assert!(to_ascii("AGAAA.\u{33c2}\u{3002}DFx").is_err());
        assert_eq!(to_ascii("\u{1940}DE\u{1fc4}").unwrap(), "xn--de-38b8b108q");
    }
}

#[cfg(test)]
mod tick20 {
    use super::*;
    #[test]
    fn division_not_ltr() {
        assert_eq!(to_ascii("\u{624}\u{f7}0001").unwrap(), "xn--0001-9qa360f");
        assert!(to_ascii("2a\u{2026}7g").is_err());
    }
}

#[cfg(test)]
mod tick21 {
    use super::*;
    #[test]
    fn check_bidi_tibetan_and_ext_marks() {
        // Tibetan Mn U+0F8F with Thaana (Node: xn--9qb481b).
        assert_eq!(to_ascii("\u{079c}\u{0f8f}").unwrap(), "xn--9qb481b");
        // Combining Ext U+1ABA with Syriac punctuation (Node: xn--tmb412h).
        assert_eq!(to_ascii("\u{0700}\u{1aba}").unwrap(), "xn--tmb412h");
        // U+1ACF unassigned / Node CheckBidi fail with RTL; alone is fine.
        assert!(to_ascii("\u{0798}\u{1acf}").is_err());
        assert_eq!(to_ascii("\u{1acf}").unwrap(), "xn--prf");
        assert!(to_ascii("\u{0798}\u{1ace}").is_err()); // Node rejects Ext Mn ≥1AC1
    }
}

#[cfg(test)]
mod tick22 {
    use super::*;
    #[test]
    fn vedic_thai_rejang_and_syriac_zwnj() {
        assert_eq!(to_ascii("\u{0704}\u{1ce7}").unwrap(), "xn--xmb023i");
        assert_eq!(to_ascii("\u{069c}\u{0e49}").unwrap(), "xn--yjb440b");
        assert_eq!(
            to_ascii("\u{0642}\u{065c}\u{200c}\u{0722}").unwrap(),
            "xn--ehb6cs6ah11f"
        );
        assert_eq!(
            to_ascii("\u{079c}\u{065e}\u{a94f}").unwrap(),
            "xn--6hb94dg266a"
        );
        assert!(to_ascii("\u{079c}\u{1ce1}").is_err()); // Vedic Mc
        assert!(to_ascii("\u{05d0}\u{200c}\u{0642}").is_err()); // Hebrew↔Arabic ZWNJ
    }
}

#[cfg(test)]
mod tick23 {
    use super::*;
    #[test]
    fn vedic_nihshvasa_and_cherokee_supplement() {
        // U+1CD3 Po is UTS #46 valid (NV8); not a leading Mn.
        assert_eq!(to_ascii("\u{1cd3}").unwrap(), "xn--g6f");
        assert!(to_ascii("\u{1cd0}").is_err()); // Mn alone
        // Cherokee Supplement → capital Cherokee (Node: xn--78d).
        assert_eq!(to_ascii("\u{ab72}").unwrap(), "xn--78d");
        assert_eq!(to_ascii("\u{13a2}").unwrap(), "xn--78d");
        assert_eq!(to_ascii("\u{ab70}").unwrap(), "xn--58d");
        assert_eq!(
            to_ascii("\u{069c}\u{0e49}\u{0ec9}").unwrap(),
            "xn--yjb440b8k"
        ); // Thai + Lao Mn
        assert_eq!(to_ascii("\u{069c}\u{0d81}").unwrap(), "xn--yjb446a");
        assert_eq!(to_ascii("\u{069c}\u{0dd4}").unwrap(), "xn--yjb018a");
        assert_eq!(to_ascii("\u{0704}\u{1a77}").unwrap(), "xn--xmb270h"); // Tai Tham Mn
        assert_eq!(
            to_ascii("\u{0704}\u{0704}\u{1ce7}\u{2de7}").unwrap(),
            "xn--xmba329nnrp"
        );
        assert_eq!(to_ascii("\u{0704}\u{1b37}").unwrap(), "xn--xmb654h");
        assert_eq!(to_ascii("\u{0700}\u{1b3a}").unwrap(), "xn--tmb074h");
        assert_eq!(to_ascii("\u{0851}=\u{083c}").unwrap(), "xn--=-gid5d");
        assert_eq!(
            to_ascii("\u{062c}\u{1c33}\u{061a}\u{1b73}").unwrap(),
            "xn--8fb9a697i5va"
        ); // Lepcha Mn
        assert!(to_ascii("\u{088f}\u{fb9e}").is_err()); // Node rejects Ext-B + Arabic
        assert_eq!(to_ascii("\u{069c}\u{1bef}").unwrap(), "xn--yjb230i"); // Batak Mn
        assert_eq!(to_ascii("\u{069c}\u{1bed}").unwrap(), "xn--yjb820i");
        assert_eq!(to_ascii("\u{0834}\u{1b80}").unwrap(), "xn--mvb499g"); // Sundanese Mn
        assert_eq!(
            to_ascii("\u{08b5}\u{aac1}\u{0ac1}").unwrap(),
            "xn--bzb26h302y"
        ); // Tai Viet Mn
        assert!(to_ascii("\u{0868}\u{08d1}\u{0a51}").is_err()); // Node rejects Ext-A mark mix
        assert!(to_ascii("\u{17b4}").is_err()); // Khmer inherent — ignored → empty
        assert_eq!(to_ascii("\u{0624}\u{17b4}").unwrap(), "xn--jgb");
        assert_eq!(to_ascii("\u{0851}\u{a9bc}").unwrap(), "xn--gwb0673f"); // Javanese Mn
        assert_eq!(
            to_ascii("\u{0704}\u{1773}\u{1cdd}").unwrap(),
            "xn--xmb825f25d"
        ); // Tagbanwa Mn
        assert_eq!(to_ascii("\u{0851}\u{aaf6}").unwrap(), "xn--gwb8834f");
        assert_eq!(
            to_ascii("\u{0624}\u{abed}\u{1bed}").unwrap(),
            "xn--jgb862i025h"
        );
        assert_eq!(to_ascii("\u{0851}\u{aa36}").unwrap(), "xn--gwb4004f"); // Cham Mn
        assert_eq!(to_ascii("\u{0851}\u{a8f0}").unwrap(), "xn--gwb2533f"); // Combining Devanagari
        // Old Hungarian (Bidi=R) + Hebrew NSM/letter — CheckBidi must treat OH as RTL
        assert_eq!(
            to_ascii("\u{10c9d}\u{05c7}\u{05dd}\u{10cb2}").unwrap(),
            "xn--vdb8b4637jqca"
        );
        // Avestan (Bidi=R) + Old South Arabian
        assert_eq!(to_ascii("\u{10b1d}\u{10a72}").unwrap(), "xn--hu9cll");
        // Syriac punct + Tagalog Mn
        assert_eq!(to_ascii("\u{0704}\u{1713}").unwrap(), "xn--xmb633f");
        assert_eq!(to_ascii("\u{10c32}\u{11c32}").unwrap(), "xn--969c66y"); // Bhaiksuki Mn
        assert_eq!(to_ascii("\u{0851}\u{a80b}").unwrap(), "xn--gwb4982f"); // Syloti Mn
        assert_eq!(to_ascii("\u{10e9d}\u{10e72}").unwrap(), "xn--qo0dzc"); // Rumi AN trailer
        assert_eq!(to_ascii("\u{10810}&0\u{11c32}").unwrap(), "xn--&0-li9nk85d");
        // Meroitic Cursive number (Bidi=R, No) + letter
        assert_eq!(to_ascii("\u{109f2}\u{109b2}").unwrap(), "xn--zo9che");
        // Kharoshthi + Nabataean (both Bidi=R)
        assert_eq!(to_ascii("\u{10a1d}\u{1089d}").unwrap(), "xn--2g9crz");
        // Sidetic (U+10945) + Old North Arabian — Node rejects (CheckBidi); we match Node
        assert!(to_ascii("\u{10a85}\u{10a85}\u{10945}").is_err());
        assert_eq!(to_ascii("\u{10b0b}\u{10f1d}").unwrap(), "xn--uy9co3e"); // Old Sogdian number
        assert_eq!(
            to_ascii("\u{0624}\u{1bed}\u{a92d}").unwrap(),
            "xn--jgb862ip43h"
        ); // Kayah Li Mn
        assert_eq!(to_ascii("\u{10b1d}\u{10a9d}").unwrap(), "xn--pv9cpi"); // ONA number
        assert_eq!(
            to_ascii("\u{10a9d}\u{10e9d}.\u{10e9d}\u{10e9d}.\u{10cb2}").unwrap(),
            "xn--pv9ci2e.xn--yp0da.xn--rd0d"
        );
        assert_eq!(to_ascii("\u{10a85}\u{11a05}").unwrap(), "xn--0u9cq8x"); // Zanabazar Mn
        assert_eq!(
            to_ascii("\u{10810}0\u{1143a}\u{11c3a}").unwrap(),
            "xn--0-tf4im51ac5h"
        ); // Newa Mn
        assert_eq!(to_ascii("\u{10a72}\u{10af2}").unwrap(), "xn--hu9cqi"); // Manichaean punct
        assert!(to_ascii("\u{10a85}\u{10ec5}").is_err()); // Arabic Ext-C mix; Node rejects
        assert_eq!(to_ascii("\u{10877}\u{10872}").unwrap(), "xn--uf9cja"); // Palmyrene fleuron
        assert_eq!(to_ascii("\u{10b72}\u{10b79}").unwrap(), "xn--s19coa"); // Pahlavi number
        assert_eq!(to_ascii("\u{108af}\u{108f2}").unwrap(), "xn--lh9coe"); // Nabataean number
        assert_eq!(to_ascii("\u{10c32}\u{116b2}").unwrap(), "xn--969cg3p"); // Takri Mn
        assert_eq!(
            to_ascii("\u{0704}\u{135d}\u{1cdd}").unwrap(),
            "xn--xmb634dpmh"
        ); // Ethiopic Mn
        assert_eq!(to_ascii("\u{0624}\u{a9e5}").unwrap(), "xn--jgb6594f"); // Myanmar Shan Mn
        assert_eq!(
            to_ascii("\u{0624}\u{a9e5}\u{abe5}").unwrap(),
            "xn--jgb6594f5ib"
        );
        assert!(to_ascii("\u{10a85}\u{10d85}").is_err()); // Garay+ONA; Node rejects
        assert_eq!(to_ascii("\u{10810}0\u{11832}").unwrap(), "xn--0-tf4iw31b"); // Dogra Mn
        assert_eq!(to_ascii("\u{10add}\u{102e6}").unwrap(), "xn--987cr4l"); // Coptic Epact EN
        assert_eq!(to_ascii("\u{109bf}\u{1093f}").unwrap(), "xn--pl9cpi"); // Lydian mark
        assert_eq!(to_ascii("\u{10810}\u{11d3a}").unwrap(), "xn--1c9cg57a"); // Masaram Gondi Mn
        assert_eq!(to_ascii("\u{10a85}\u{10fc5}").unwrap(), "xn--0u9cs3g"); // Chorasmian number
        assert_eq!(
            to_ascii("\u{10810}\u{1183a}\u{1143a}\u{1103a}").unwrap(),
            "xn--1c9ck3l0md96e"
        ); // Brahmi Mn
        assert_eq!(to_ascii("\u{10878}\u{10cfc}").unwrap(), "xn--0f9c60f"); // Old Hungarian number
        assert_eq!(
            to_ascii("\u{10c9d}\u{10c9d}\u{11cb2}.\u{10cb2}").unwrap(),
            "xn--5c0da372j.xn--rd0d"
        ); // Marchen Mn
        assert_eq!(
            to_ascii("\u{0851}\u{aab8}\u{a678}").unwrap(),
            "xn--gwb8802fixc"
        ); // Cyr Ext Mn
        assert_eq!(
            to_ascii("\u{10810}\u{11831}\u{1163a}\u{1143a}").unwrap(),
            "xn--1c9cs1s4pbq1c"
        ); // Modi Mn
        assert_eq!(to_ascii("\u{10910}\u{1091a}").unwrap(), "xn--dk9cua"); // Phoenician number
        assert_eq!(
            to_ascii("\u{0642}\u{20dc}\u{065c}\u{065c}\u{065c}\u{065c}").unwrap(),
            "xn--ehb6caaa8181b"
        ); // Comb marks for symbols
        assert_eq!(to_ascii("\u{10a90}\u{1da9d}").unwrap(), "xn--cv9cw466a"); // SignWriting Mn
        assert_eq!(
            to_ascii("\u{10e9d}\u{10e9d}\u{11236}").unwrap(),
            "xn--yp0da77y"
        ); // Khojki Mn
        assert_eq!(
            to_ascii("\u{10810}\u{11d32}\u{10810}\u{10d32}").unwrap(),
            "xn--1c9ca650bc5t"
        ); // Hanifi Rohingya digit
        assert_eq!(
            to_ascii("\u{0851}\u{a672}\u{aa36}").unwrap(),
            "xn--gwb6702fwmc"
        ); // Cyr Me
        assert_eq!(
            to_ascii("\u{10810}\u{1183a}\u{1143a}\u{114ba}").unwrap(),
            "xn--1c9cs1s8kar9i"
        ); // Tirhuta Mn
        assert!(to_ascii("\u{10810}\u{11f3a}").is_err()); // Kawi+Cypriot; Node rejects
        assert_eq!(to_ascii("\u{1e810}\u{1e010}").unwrap(), "xn--xh4h51k"); // Comb Glagolitic
        assert_eq!(to_ascii("\u{10810}\u{115b3}").unwrap(), "xn--1c9cw6u"); // Siddham Mn
        assert_eq!(to_ascii("\u{fe73}\u{fe2f}").unwrap(), "xn--s96cte"); // Half Marks
        assert_eq!(to_ascii("\u{10e85}\u{11943}").unwrap(), "xn--9o0dk7p"); // Dives Akuru Mn
        assert!(to_ascii("\u{10810}\u{13440}").is_err()); // Egyptian hieroglyph + Cypriot; Node rejects
        assert_eq!(to_ascii("\u{10f52}\u{10f50}").unwrap(), "xn--2u0dd"); // Sogdian Mn
        assert_eq!(to_ascii("\u{0798}\u{1a18}").unwrap(), "xn--5qb685g"); // Buginese Mn
        assert_eq!(
            to_ascii("\u{0704}\u{1922}\u{1ba2}\u{1ba2}\u{1ba2}").unwrap(),
            "xn--xmb093g4ybaa"
        ); // Limbu Mn
        assert_eq!(to_ascii("\u{1e950}\u{1e810}").unwrap(), "xn--g55h5t"); // Adlam digit
        assert_eq!(to_ascii("\u{10a52}\u{11a52}").unwrap(), "xn--kt9c66y"); // Soyombo Mn
        assert_eq!(to_ascii("\u{10810}\u{11128}").unwrap(), "xn--1c9cg9m"); // Chakma Mn
        assert_eq!(
            to_ascii("\u{10810}\u{11d32}\u{10810}\u{11372}").unwrap(),
            "xn--1c9ca658fhyj"
        ); // Grantha Mn
        assert_eq!(to_ascii("\u{10e9d}\u{110b6}").unwrap(), "xn--yp0dy9a"); // Kaithi Mn
        assert!(to_ascii("\u{fe12}").is_err()); // Vertical ideographic full stop; Node rejects
        assert!(to_ascii("\u{fe52}").is_err()); // Small full stop; Node rejects
        assert_eq!(to_ascii("\u{10817}\u{111b8}").unwrap(), "xn--8c9ck8n"); // Sharada Mn
        assert_eq!(
            to_ascii("\u{10e9d}\u{114b6}\u{10e9d}\u{114b6}\u{10ead}\u{114b6}").unwrap(),
            "xn--yp0da2c889abab"
        ); // Yezidi hyphenation mark RTL
        assert_eq!(to_ascii("-\u{10d25}").unwrap(), "xn----6j6i"); // Hanifi Rohingya Mn
        assert_eq!(to_ascii("\u{10810}\u{11173}").unwrap(), "xn--1c9cg4n"); // Mahajani Mn
        assert!(to_ascii("\u{10a85}\u{10f85}").is_err()); // Old Uyghur+ONA; Node rejects
        assert_eq!(
            to_ascii("..\u{6fd}\u{d4d}\u{d4d}\u{16b35}").unwrap(),
            "..xn--qmb643aa81496a"
        ); // Pahawh Hmong Mn
        assert_eq!(to_ascii("\u{10cb2}\u{119d6}").unwrap(), "xn--rd0d43t"); // Nandinagari Mn
        assert_eq!(to_ascii("\u{1e950}\u{1e946}").unwrap(), "xn--bf6hta"); // Adlam Mn
        assert_eq!(
            to_ascii("\u{1e810}\u{1e020}\u{1ec90}\u{1e020}").unwrap(),
            "xn--ei4ha802dyxe"
        ); // Indic Siyaq number
        assert!(to_ascii("\u{10e9d}\u{11b63}").is_err()); // unassigned+Yezidi; Node rejects
        assert_eq!(
            to_ascii("\u{8b5}\u{9e2}\u{9fe}\u{9e2}\u{9e2}").unwrap(),
            "xn--bzb61daa2l"
        ); // Bengali sandhi mark
        assert_eq!(to_ascii("\u{7d1}\u{aa7c}").unwrap(), "xn--ssb0044f"); // Tai Laing tone
        assert_eq!(
            to_ascii("\u{10e9d}\u{1bc9d}\u{11c92}\u{11c92}\u{11c92}").unwrap(),
            "xn--yp0dg2vaa6695r"
        ); // Duployan Mn
        assert_eq!(to_ascii("\u{1e810}\u{1e8c7}").unwrap(), "xn--g55hol"); // Mende digit
        assert_eq!(
            to_ascii("\u{851}\u{a8e3}\u{a8e3}\u{a8c4}\u{a8e3}").unwrap(),
            "xn--gwb4623fxcaaa"
        ); // Saurashtra virama
        assert_eq!(to_ascii("\u{1ec90}\u{1e8d0}").unwrap(), "xn--xb6h53d"); // Mende combining teens
        assert_eq!(
            to_ascii("\u{1e810}\u{1e010}\u{1e8d0}\u{1e010}\u{1e010}").unwrap(),
            "xn--xh4haa303fp1a"
        );
        assert!(to_ascii("\u{1ed1e}&\u{088c}").is_err()); // Siyaq+Ext-B; Node rejects
        assert_eq!(to_ascii("\u{856}\u{a6f1}").unwrap(), "xn--lwb0232f"); // Bamum Mn
        assert_eq!(
            to_ascii("\u{856}\u{a6f1}\u{aa31}\u{aa31}\u{aa31}").unwrap(),
            "xn--lwb0232flbcaa"
        );
        assert!(to_ascii("\u{1bca0}").is_err()); // Shorthand alone → empty; Node rejects
        assert_eq!(to_ascii("\u{1bca2}tttt").unwrap(), "tttt"); // Shorthand format ignored
        assert_eq!(to_ascii("'\u{1bca2}").unwrap(), "'");
        assert_eq!(
            to_ascii("\u{10a94}\u{1d17d}\u{1da3d}").unwrap(),
            "xn--gv9cw805a9qf"
        ); // Musical + SignWriting Mn
        assert_eq!(
            to_ascii("\u{10cea}\u{1da84}\u{1d244}\u{1da84}\u{1da84}").unwrap(),
            "xn--jd0d8184a9ffbaa"
        ); // Greek musical Mn
        assert_eq!(to_ascii("\u{7dc}\u{302a}").unwrap(), "xn--3sb057r"); // Ideographic tone mark
        assert_eq!(to_ascii("-\u{1d17a}").unwrap(), "-"); // Musical format control ignored
        assert_eq!(
            to_ascii("nx\u{11a99}\u{200d}atac").unwrap(),
            "xn--nxatac-qf0ct836r"
        ); // ZWJ after virama (Soyombo)
        assert!(to_ascii("a\u{200d}b").is_err()); // ZWJ without virama
        assert!(to_ascii("\u{1ee10}1\u{088f}").is_err()); // Arabic math + Ext-B; Node rejects
        assert_eq!(to_ascii("\u{1ec90}\u{1e131}").unwrap(), "xn--6p4h35p"); // Nyiaeng Hmong Mn
        assert_eq!(to_ascii("\u{10af2}\u{16af2}").unwrap(), "xn--4x9cm25n"); // Bassa Vah Mn
        assert_eq!(to_ascii("\u{fdf8}\u{fbba}").unwrap(), "xn--ygb8adj78252a"); // Arabic symbol
        assert_eq!(to_ascii("\u{10810}\u{11ef4}").unwrap(), "xn--1c9cu40b"); // Makasar Mn
        assert_eq!(
            to_ascii("\u{7c1}\u{7c1}\u{1172b}\u{116ab}\u{116ab}\u{116ab}").unwrap(),
            "xn--csba6719raa97e"
        ); // Ahom Mn
        assert!(to_ascii("\u{10f32}\u{1cf32}").is_err()); // Znamenny+Sogdian; Node rejects
        assert_eq!(to_ascii("\u{10828}\u{10378}").unwrap(), "xn--ge8cv6f"); // Old Permic Mn
        assert_eq!(to_ascii("\u{108fd}\u{101fd}").unwrap(), "xn--m27cq7j"); // Phaistos Disc Mn
        assert!(to_ascii("\u{1e810}\u{1e6e6}").is_err()); // unassigned+Mende; Node rejects
        // Syriac + Coptic combining Ni above (Node: xn--xnb854q)
        assert_eq!(to_ascii("\u{0727}\u{2cef}").unwrap(), "xn--xnb854q");
        // Thaana + Coptic Epact thousands + Khudawadi Mn
        assert_eq!(
            to_ascii("\u{0798}\u{102e0}\u{112e4}").unwrap(),
            "xn--5qb0779jpbk"
        );
        // Manichaean + Khudawadi Mn
        assert_eq!(to_ascii("\u{10add}\u{112e6}").unwrap(), "xn--jx9c80l");
        // Kharoshthi + Khudawadi anusvara + Masaram Gondi Mn
        assert_eq!(
            to_ascii("\u{10a10}\u{112df}\u{11d3f}").unwrap(),
            "xn--or9ck4mx1i"
        );
        // NFC before CheckJoiners: n+Soyombo virama+cedilla → ņ+virama, then ZWJ OK
        assert_eq!(
            to_ascii("n\u{11a99}\u{0327}\u{200d}n").unwrap(),
            "xn--n-lla157uje6t"
        );
        assert!(to_ascii("n\u{11a99}\u{0308}\u{200d}n").is_err()); // no n+diaeresis composite
        // Math final sigma → σ (UTS #46), not NFKC's ς
        assert_eq!(to_ascii("\u{1d781}").unwrap(), "xn--4xa");
        assert_eq!(to_ascii("\u{1d6d3}").unwrap(), "xn--4xa");
        assert_eq!(to_ascii("\u{03c2}").unwrap(), "xn--3xa"); // bare final sigma kept
        // Arabic Extended-B + Ext-A (Node: xn--3xb6j)
        assert_eq!(to_ascii("\u{088b}\u{08c8}").unwrap(), "xn--3xb6j");
        // Ext-B letter + Ext-A Mn; Greek + Ext-B Mn (trailing NSM)
        assert_eq!(to_ascii("\u{088f}\u{08cf}").unwrap(), "xn--7xb2k");
        assert_eq!(to_ascii("\u{0398}\u{089f}").unwrap(), "xn--txa42w");
        assert_eq!(to_ascii("\u{088f}\u{0888}").unwrap(), "xn--0xbn"); // Ext-B Sk
        assert_eq!(to_ascii("\u{0888}\u{089f}").unwrap(), "xn--0xb0c"); // Sk + Ext-B Mn
        assert_eq!(to_ascii("\u{0888}\u{0898}").unwrap(), "xn--0xb6a");
        // Combining Cyrillic Ext letter as LTR with Mende — Node rejects; we match Node
        assert!(to_ascii("\u{1e810}\u{1e08f}\u{1e010}").is_err());
    }
}

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

    #[test]
    fn leading_kana_voicing_mark_rejected() {
        // U+3099 sits inside the kana block but must not take SimpleIdentity
        // (would skip the leading-Mn reject).
        let domain = "\u{3099}a.com";
        assert_ne!(scan_non_ascii(domain), Ok(Scan::SimpleIdentity));
        assert!(to_ascii(domain).is_err(), "leading Mn must be rejected");
        assert!(to_ascii("\u{309A}").is_err());
    }

    #[test]
    fn kana_nfd_and_nfc_share_ace() {
        // Skipping NFC for U+3099 would encode か+゙ differently from が.
        let nfd = "\u{304b}\u{3099}"; // か + voiced mark
        let nfc = "\u{304c}"; //        assert_ne!(scan_non_ascii(nfd), Ok(Scan::SimpleIdentity));
        assert_eq!(to_ascii(nfd).unwrap(), to_ascii(nfc).unwrap());
    }

    #[test]
    fn turkish_and_cjk_still_simple_identity() {
        assert_eq!(scan_non_ascii("türkçe.com"), Ok(Scan::SimpleIdentity));
        assert_eq!(scan_non_ascii("你好你好.com"), Ok(Scan::SimpleIdentity));
        assert_eq!(to_ascii("türkçe.com").unwrap(), "xn--trke-2oa7j.com");
    }

    #[test]
    fn noncharacter_still_rejected() {
        assert!(to_ascii("\u{ffff}").is_err());
    }
}

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

    #[test]
    fn unassigned_in_former_simple_ranges_rejected() {
        let cps: &[u32] = &[
            0x3040, 0x3097, 0x3098, // unassigned kana
            0xD7A4, 0xD7AF, // unassigned hangul tail
        ];
        for &cp in cps {
            let ch = char::from_u32(cp).unwrap();
            let domain = format!("{ch}.com");
            assert!(
                to_ascii(&domain).is_err(),
                "U+{cp:04X} must be rejected (servo/UTS46 unassigned)"
            );
            assert_ne!(
                scan_non_ascii(&domain),
                Ok(Scan::SimpleIdentity),
                "U+{cp:04X} must not be SimpleIdentity"
            );
        }
    }
}