safehtml 0.2.0

A high-performance, no_std Rust library for Type-Driven Security (XSS and injection prevention).
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
use safehtml::{
    INNOCUOUS_PROPERTY_VALUE, INNOCUOUS_URL, SafeHtml, SafeHtmlProto, SafeScript, SafeScriptProto,
    SafeStyle, SafeStyleProto, SafeStyleSheet, SafeStyleSheetProto, SafeUrl, SafeUrlProto,
    TrustedResourceUrl, TrustedResourceUrlProto, coerce_bytes_to_interchange_valid,
    coerce_bytes_to_interchange_valid_to, coerce_to_interchange_valid_to,
    escape_allow_character_references_to, escape_html_and_coerce_to, escape_html_bytes,
    escape_html_bytes_and_coerce_to, escape_json_for_script, escape_json_for_script_to,
    html_escaped, is_interchange_invalid, is_safe_css_selector, is_safe_style_property_name,
    is_safe_style_property_value, is_safe_url_block_javascript, is_safe_url_restrictive,
    is_safe_url_restrictive_with_schemes, percent_escape_css_url, percent_escape_css_url_to,
    safe_html_cat, url_encode_component, url_encode_component_to,
};

#[test]
fn test_is_interchange_invalid() {
    // Valid characters
    assert!(!is_interchange_invalid('a'));
    assert!(!is_interchange_invalid(' '));
    assert!(!is_interchange_invalid('\n'));
    assert!(!is_interchange_invalid('\r'));
    assert!(!is_interchange_invalid('\t'));
    assert!(!is_interchange_invalid('\x0C')); // FF

    // Invalid control characters
    assert!(is_interchange_invalid('\0'));
    assert!(is_interchange_invalid('\x01'));
    assert!(is_interchange_invalid('\x08'));
    assert!(is_interchange_invalid('\x0B')); // VT
    assert!(is_interchange_invalid('\x1F'));
    assert!(is_interchange_invalid('\x7F'));
    assert!(is_interchange_invalid('\u{9F}'));

    // Non-characters
    assert!(is_interchange_invalid('\u{FDD0}'));
    assert!(is_interchange_invalid('\u{FDEF}'));
    assert!(is_interchange_invalid('\u{FFFE}'));
    assert!(is_interchange_invalid('\u{FFFF}'));
    assert!(is_interchange_invalid('\u{1FFFE}'));
    assert!(is_interchange_invalid('\u{10FFFF}'));
}

#[test]
fn test_coerce_to_interchange_valid_basic() {
    let mut s = String::new();
    coerce_to_interchange_valid_to("hello\x00world\u{FFFE}", &mut s).unwrap();
    assert_eq!(s, "hello\u{FFFD}world\u{FFFD}");
}

#[test]
fn test_escape_html() {
    let mut s = String::new();
    escape_html_and_coerce_to("a < b & c > d \" e ' f\x00", &mut s).unwrap();
    assert_eq!(s, "a &lt; b &amp; c &gt; d &#34; e &#39; f\u{FFFD}");

    // Test SafeHtml::escape
    let safe = SafeHtml::escape("a < b");
    assert_eq!(safe.as_str(), "a &lt; b");
}

#[test]
fn test_escape_allow_character_references() {
    let mut s = String::new();
    escape_allow_character_references_to("foo &nbsp; &amp; &#39; &#x27; &invalid; &; bar", &mut s)
        .unwrap();
    assert_eq!(s, "foo &nbsp; &amp; &#39; &#x27; &invalid; &amp;; bar");

    let safe = SafeHtml::escape_allow_character_references("foo &nbsp;");
    assert_eq!(safe.as_str(), "foo &nbsp;");
}

#[test]
fn test_html_comment() {
    let safe = SafeHtml::comment("foo --> bar <script>");
    assert_eq!(safe.as_str(), "<!--foo --&gt; bar &lt;script&gt;-->");
}

#[test]
fn test_percent_escape_css_url() {
    let mut s = String::new();
    percent_escape_css_url_to("http://foo.com/bar?a=1&b=2#frag(3)", &mut s).unwrap();
    // '(' and ')' should be escaped, others in standard URL allowed list should not
    assert_eq!(s, "http://foo.com/bar?a=1&b=2#frag%283%29");

    let css_safe = SafeUrl::sanitize_for_css("http://foo.com/bar?a=1&b=2#frag(3)");
    assert_eq!(css_safe.as_str(), "http://foo.com/bar?a=1&b=2#frag%283%29");
}

#[test]
fn test_is_safe_url_block_javascript() {
    // Relative/schemeless
    assert!(is_safe_url_block_javascript("/foo/bar"));
    assert!(is_safe_url_block_javascript("foo/bar"));
    assert!(is_safe_url_block_javascript("foo/bar?a=1&b=2"));
    assert!(is_safe_url_block_javascript("path/to:file"));
    assert!(is_safe_url_block_javascript(""));

    // Safe schemes
    assert!(is_safe_url_block_javascript("http://test.com"));
    assert!(is_safe_url_block_javascript("https://test.com"));
    assert!(is_safe_url_block_javascript("mailto:foo@bar.com"));
    assert!(is_safe_url_block_javascript("ftp://foo.bar"));
    assert!(is_safe_url_block_javascript("foo://bar")); // blocked only javascript

    // Unsafe / Javascript
    assert!(!is_safe_url_block_javascript("javascript:alert(1)"));
    assert!(!is_safe_url_block_javascript("JAVASCRIPT:alert(1)"));
    assert!(!is_safe_url_block_javascript(" javascript:alert(1)")); // spaces
    assert!(!is_safe_url_block_javascript("java\nscript:alert(1)"));
    assert!(!is_safe_url_block_javascript("javascript&colon;alert(1)")); // entity bypasses
}

#[test]
fn test_is_safe_url_restrictive() {
    // Relative/schemeless
    assert!(is_safe_url_restrictive("/foo/bar"));
    assert!(is_safe_url_restrictive("foo/bar"));
    assert!(is_safe_url_restrictive("foo/bar?a=1&b=2"));
    assert!(is_safe_url_restrictive(""));

    // Safe schemes
    assert!(is_safe_url_restrictive("http://test.com"));
    assert!(is_safe_url_restrictive("https://test.com"));
    assert!(is_safe_url_restrictive("mailto:foo@bar.com"));
    assert!(is_safe_url_restrictive("ftp://foo.bar"));

    // Non-default schemes
    assert!(!is_safe_url_restrictive("foo://bar"));
    assert!(!is_safe_url_restrictive("javascript:alert(1)"));

    // Custom schemes
    assert!(is_safe_url_restrictive_with_schemes("foo://bar", &["foo"]));
    assert!(is_safe_url_restrictive_with_schemes(
        "foo-bar://baz",
        &["foo_bar"]
    )); // handles underscore/dash translation

    // Safe Data URLs
    assert!(is_safe_url_restrictive(
        "data:image/png;base64,iVBORw0KGgoAAAANS="
    ));
    assert!(is_safe_url_restrictive("data:text/plain;base64,SGVsbG8="));
    assert!(is_safe_url_restrictive("DATA:IMAGE/JPEG;BASE64,aBc123+/"));

    // Unsafe/Invalid Data URLs
    assert!(!is_safe_url_restrictive("data:text/html;base64,SGVsbG8=")); // HTML is unsafe
    assert!(!is_safe_url_restrictive(
        "data:image/png;base64,invalid characters!"
    ));
    assert!(!is_safe_url_restrictive("data:image/png;base64,")); // empty data
}

#[test]
fn test_safe_html_concat_and_join() {
    let h1 = SafeHtml::escape("hello");
    let h2 = SafeHtml::escape("world");
    let joined = SafeHtml::join(vec![h1, h2], &SafeHtml::escape(" - "));
    assert_eq!(joined.as_str(), "hello - world");

    let h1 = SafeHtml::escape("hello");
    let h2 = SafeHtml::escape("world");
    let concatenated = SafeHtml::concat(vec![h1, h2]);
    assert_eq!(concatenated.as_str(), "helloworld");
}

#[test]
fn test_safe_html_cat_macro() {
    let h1 = SafeHtml::escape("<b>hello</b>");
    let raw_text = "<script>alert(1)</script>";
    let result = safe_html_cat!(h1, " - ", raw_text, " count: ", 42);
    assert_eq!(
        result.as_str(),
        "&lt;b&gt;hello&lt;/b&gt; - &lt;script&gt;alert(1)&lt;/script&gt; count: 42"
    );
}

#[test]
fn test_safe_url_sanitize() {
    let u1 = SafeUrl::sanitize("https://test.com");
    assert_eq!(u1.as_str(), "https://test.com");

    let u2 = SafeUrl::sanitize("javascript:alert(1)");
    assert_eq!(u2.as_str(), INNOCUOUS_URL);

    let u3 = SafeUrl::sanitize_block_only_javascript("foo://bar");
    assert_eq!(u3.as_str(), "foo://bar");

    let u4 = SafeUrl::sanitize_block_only_javascript("javascript:alert(1)");
    assert_eq!(u4.as_str(), INNOCUOUS_URL);
}

#[cfg(feature = "serde")]
#[test]
fn test_serde() {
    let h = SafeHtml::escape("hello <world>");
    let serialized_html = serde_json::to_string(&h).unwrap();
    assert_eq!(serialized_html, "\"hello &lt;world&gt;\"");

    let deserialized_html: SafeHtml = serde_json::from_str(&serialized_html).unwrap();
    assert_eq!(deserialized_html.as_str(), "hello &lt;world&gt;");

    let u = SafeUrl::sanitize("https://test.com");
    let serialized_url = serde_json::to_string(&u).unwrap();
    assert_eq!(serialized_url, "\"https://test.com\"");

    let deserialized_url: SafeUrl = serde_json::from_str(&serialized_url).unwrap();
    assert_eq!(deserialized_url.as_str(), "https://test.com");

    // Test that deserializing an unsafe url fails
    let unsafe_serialized_url = "\"javascript:alert(1)\"";
    let deserialized_unsafe_url: Result<SafeUrl, _> = serde_json::from_str(unsafe_serialized_url);
    assert!(deserialized_unsafe_url.is_err());
}

#[test]
fn test_html_escaped() {
    let raw_html = "<>'\"&";
    let escaped_html = "&lt;&gt;&#39;&#34;&amp;";
    let got = SafeHtml::escape(raw_html);
    assert_eq!(got.as_str(), escaped_html);
}

#[test]
fn test_html_concat() {
    struct TestCase {
        in_vec: Vec<&'static str>,
        want: &'static str,
    }
    let tests = [
        TestCase {
            in_vec: vec![],
            want: "",
        },
        TestCase {
            in_vec: vec![""],
            want: "",
        },
        TestCase {
            in_vec: vec!["Hello world!"],
            want: "Hello world!",
        },
        TestCase {
            in_vec: vec!["Hello", " ", "world!"],
            want: "Hello world!",
        },
    ];
    for t in &tests {
        let mut htmls = Vec::new();
        for &s in &t.in_vec {
            unsafe {
                htmls.push(SafeHtml::from_string_unchecked(s.to_string()));
            }
        }
        let got = SafeHtml::concat(htmls);
        assert_eq!(got.as_str(), t.want);
    }
}

#[test]
fn test_html_from_proto() {
    let raw_html = "<>'\"&";
    let escaped_html = "&lt;&gt;&#39;&#34;&amp;";
    let html = SafeHtml::escape(raw_html);
    let proto = html.to_proto();
    assert!(
        proto
            .private_do_not_access_or_else_safe_html_wrapped_value
            .contains(escaped_html)
    );

    let html2 = SafeHtml::from_proto(Some(&proto));
    assert_eq!(html, html2);

    // Nil handling (in Rust we use None)
    let html3 = SafeHtml::from_proto(None);
    assert_eq!(html3.as_str(), "");

    let html4 = SafeHtml::from_proto(Some(&SafeHtmlProto::default()));
    assert_eq!(html4.as_str(), "");
}

#[test]
fn test_coerce_to_interchange_valid() {
    // Single character tests
    struct CharTest {
        in_bytes: &'static [u8],
        replaced: bool,
    }
    let char_tests = [
        // Control characters.
        CharTest {
            in_bytes: b"\x00",
            replaced: true,
        },
        CharTest {
            in_bytes: b"\x04",
            replaced: true,
        },
        CharTest {
            in_bytes: b"\x08",
            replaced: true,
        },
        CharTest {
            in_bytes: b"\t",
            replaced: false,
        }, // x09
        CharTest {
            in_bytes: b"\n",
            replaced: false,
        }, // x0A
        CharTest {
            in_bytes: b"\x0B",
            replaced: true,
        }, // x0B
        CharTest {
            in_bytes: b"\x0C",
            replaced: false,
        }, // x0C
        CharTest {
            in_bytes: b"\r",
            replaced: false,
        }, // x0D
        CharTest {
            in_bytes: b"\x0E",
            replaced: true,
        },
        CharTest {
            in_bytes: b"\x0F",
            replaced: true,
        },
        // Non-character codepoints.
        CharTest {
            in_bytes: "\u{FDCF}".as_bytes(),
            replaced: false,
        }, // Begin border
        CharTest {
            in_bytes: "\u{FDD0}".as_bytes(),
            replaced: true,
        }, // Begin range
        CharTest {
            in_bytes: "\u{FDD5}".as_bytes(),
            replaced: true,
        }, // Mid range
        CharTest {
            in_bytes: "\u{FDEF}".as_bytes(),
            replaced: true,
        }, // End range
        CharTest {
            in_bytes: "\u{FDF0}".as_bytes(),
            replaced: false,
        }, // End border
        CharTest {
            in_bytes: "\u{FFFE}".as_bytes(),
            replaced: true,
        },
        CharTest {
            in_bytes: "\u{FFFF}".as_bytes(),
            replaced: true,
        },
        CharTest {
            in_bytes: "\u{1FFFE}".as_bytes(),
            replaced: true,
        },
        CharTest {
            in_bytes: "\u{1FFFF}".as_bytes(),
            replaced: true,
        },
        CharTest {
            in_bytes: "\u{2FFFE}".as_bytes(),
            replaced: true,
        },
        CharTest {
            in_bytes: "\u{2FFFF}".as_bytes(),
            replaced: true,
        },
        CharTest {
            in_bytes: "\u{3FFFE}".as_bytes(),
            replaced: true,
        },
        CharTest {
            in_bytes: "\u{3FFFF}".as_bytes(),
            replaced: true,
        },
        CharTest {
            in_bytes: "\u{4FFFE}".as_bytes(),
            replaced: true,
        },
        CharTest {
            in_bytes: "\u{4FFFF}".as_bytes(),
            replaced: true,
        },
        CharTest {
            in_bytes: "\u{5FFFE}".as_bytes(),
            replaced: true,
        },
        CharTest {
            in_bytes: "\u{5FFFF}".as_bytes(),
            replaced: true,
        },
        CharTest {
            in_bytes: "\u{6FFFE}".as_bytes(),
            replaced: true,
        },
        CharTest {
            in_bytes: "\u{6FFFF}".as_bytes(),
            replaced: true,
        },
        CharTest {
            in_bytes: "\u{7FFFE}".as_bytes(),
            replaced: true,
        },
        CharTest {
            in_bytes: "\u{7FFFF}".as_bytes(),
            replaced: true,
        },
        CharTest {
            in_bytes: "\u{8FFFE}".as_bytes(),
            replaced: true,
        },
        CharTest {
            in_bytes: "\u{8FFFF}".as_bytes(),
            replaced: true,
        },
        CharTest {
            in_bytes: "\u{9FFFE}".as_bytes(),
            replaced: true,
        },
        CharTest {
            in_bytes: "\u{9FFFF}".as_bytes(),
            replaced: true,
        },
        CharTest {
            in_bytes: "\u{AFFFE}".as_bytes(),
            replaced: true,
        },
        CharTest {
            in_bytes: "\u{AFFFF}".as_bytes(),
            replaced: true,
        },
        CharTest {
            in_bytes: "\u{BFFFE}".as_bytes(),
            replaced: true,
        },
        CharTest {
            in_bytes: "\u{BFFFF}".as_bytes(),
            replaced: true,
        },
        CharTest {
            in_bytes: "\u{CFFFE}".as_bytes(),
            replaced: true,
        },
        CharTest {
            in_bytes: "\u{CFFFF}".as_bytes(),
            replaced: true,
        },
        CharTest {
            in_bytes: "\u{DFFFE}".as_bytes(),
            replaced: true,
        },
        CharTest {
            in_bytes: "\u{DFFFF}".as_bytes(),
            replaced: true,
        },
        CharTest {
            in_bytes: "\u{EFFFE}".as_bytes(),
            replaced: true,
        },
        CharTest {
            in_bytes: "\u{EFFFF}".as_bytes(),
            replaced: true,
        },
        CharTest {
            in_bytes: "\u{FFFFE}".as_bytes(),
            replaced: true,
        },
        CharTest {
            in_bytes: "\u{FFFFF}".as_bytes(),
            replaced: true,
        },
        CharTest {
            in_bytes: "\u{10FFFE}".as_bytes(),
            replaced: true,
        },
        CharTest {
            in_bytes: "\u{10FFFF}".as_bytes(),
            replaced: true,
        },
        // Invalid UTF8.
        CharTest {
            in_bytes: b"\xed",
            replaced: true,
        },
        // Valid UTF8.
        CharTest {
            in_bytes: b" ",
            replaced: false,
        },
        // Replacement character.
        CharTest {
            in_bytes: "\u{FFFD}".as_bytes(),
            replaced: false,
        },
    ];
    for tt in &char_tests {
        let coerced = coerce_bytes_to_interchange_valid(tt.in_bytes);
        if tt.replaced {
            assert_eq!(
                coerced, "\u{FFFD}",
                "coerce_bytes_to_interchange_valid({:?}) should be replaced with FFFD",
                tt.in_bytes
            );
        } else {
            let expected_str = core::str::from_utf8(tt.in_bytes).unwrap();
            assert_eq!(coerced, expected_str);
        }
    }

    // String tests
    struct StrTest {
        in_bytes: &'static [u8],
        expected: &'static str,
    }
    let string_tests = [
        StrTest {
            in_bytes: b"abcd",
            expected: "abcd",
        },
        StrTest {
            in_bytes: "丄ê𐒖t".as_bytes(),
            expected: "丄ê𐒖t",
        },
        // String with all classes of codepoints above.
        StrTest {
            in_bytes: b"\n\xe4\xb8\x84\xed \x00\xf0\x9f\xbf\xbea\xef\xbf\xbd",
            expected: "\n丄\u{FFFD} \u{FFFD}\u{FFFD}a\u{FFFD}",
        },
        // Invalid byte sequence.
        StrTest {
            in_bytes: b"\xff\x7e",
            expected: "\u{FFFD}\x7e",
        },
        // Single surrogate.
        StrTest {
            in_bytes: b"\xED\xA0\x80",
            expected: "\u{FFFD}\u{FFFD}\u{FFFD}",
        },
        // Supplementary point U+233B4 encoded as a surrogate pair.
        StrTest {
            in_bytes: b"\xED\xA1\x8C\xED\xBE\xB4",
            expected: "\u{FFFD}\u{FFFD}\u{FFFD}\u{FFFD}\u{FFFD}\u{FFFD}",
        },
        // Overlong sequence.
        StrTest {
            in_bytes: b"\xC0\x80",
            expected: "\u{FFFD}\u{FFFD}",
        },
    ];
    for tt in &string_tests {
        let coerced = coerce_bytes_to_interchange_valid(tt.in_bytes);
        assert_eq!(
            coerced, tt.expected,
            "coerce_bytes_to_interchange_valid({:?})",
            tt.in_bytes
        );
    }
}

const TEST_HTML: &str = "a<b & c>d \" e' f";
const ESCAPED_HTML: &str = "a&lt;b &amp; c&gt;d &#34; e&#39; f";
const INTERCHANGE_INVALID_HTML: &str = "hello\x00world\u{FDD0}";
const INTERCHANGE_ESCAPED_HTML: &str = "hello\u{FFFD}world\u{FFFD}";
const NON_ASCII_CHARS: &str = "hello 丄ê𐒖t";
const NUL_HTML: &str = "hello \x00 world";
const NUL_ESCAPED_HTML: &str = "hello \u{FFFD} world";

#[test]
fn test_safe_html_unchecked_and_empty_constructors() {
    let html = unsafe { SafeHtml::from_string_unchecked(TEST_HTML.to_string()) };
    assert_eq!(html.as_str(), TEST_HTML);

    let empty = SafeHtml::empty();
    assert!(empty.as_str().is_empty());
}

#[test]
fn test_safe_html_escape_all_specials() {
    assert_eq!(SafeHtml::escape(TEST_HTML).as_str(), ESCAPED_HTML);
}

#[test]
fn test_safe_html_comment_wraps_and_escapes() {
    assert_eq!(
        SafeHtml::comment("<script>").as_str(),
        "<!--&lt;script&gt;-->"
    );
}

#[test]
fn test_safe_html_nbsp_constant() {
    assert_eq!(SafeHtml::nbsp().as_str(), "&nbsp;");
}

#[test]
fn test_safe_html_doctype_constant() {
    assert_eq!(
        SafeHtml::html5_doctype_declaration().as_str(),
        "<!DOCTYPE html>"
    );
}

#[test]
fn test_safe_html_escape_empty_string() {
    assert_eq!(SafeHtml::escape("").as_str(), "");
}

#[test]
fn test_safe_html_escape_coerces_interchange_invalid() {
    assert_eq!(
        SafeHtml::escape(INTERCHANGE_INVALID_HTML).as_str(),
        INTERCHANGE_ESCAPED_HTML
    );
}

#[test]
fn test_safe_html_escape_preserves_non_ascii() {
    assert_eq!(SafeHtml::escape(NON_ASCII_CHARS).as_str(), NON_ASCII_CHARS);
}

#[test]
fn test_safe_html_escape_replaces_nul() {
    assert_eq!(SafeHtml::escape(NUL_HTML).as_str(), NUL_ESCAPED_HTML);
}

#[test]
fn test_safe_html_append_safe_value() {
    let mut html = SafeHtml::escape("Hi!");
    let other = SafeHtml::escape(TEST_HTML);
    html.append(&other);
    let expected = String::from("Hi!") + ESCAPED_HTML;
    assert_eq!(html.as_str(), expected);
}

#[test]
fn test_escape_and_append_appends_escaped() {
    let mut html = SafeHtml::escape("Hi!");
    html.escape_and_append(TEST_HTML);
    let expected = String::from("Hi!") + ESCAPED_HTML;
    assert_eq!(html.as_str(), expected);
}

#[test]
fn test_escape_and_append_empty_input_is_noop() {
    let mut html = SafeHtml::escape(TEST_HTML);
    html.escape_and_append("");
    assert_eq!(html.as_str(), ESCAPED_HTML);
}

#[test]
fn test_escape_and_append_onto_empty() {
    let mut html = SafeHtml::empty();
    html.escape_and_append(TEST_HTML);
    assert_eq!(html.as_str(), ESCAPED_HTML);
}

#[test]
fn test_escape_and_append_coerces_interchange_invalid() {
    let mut html = SafeHtml::escape("Hi!");
    html.escape_and_append(INTERCHANGE_INVALID_HTML);
    let expected = String::from("Hi!") + INTERCHANGE_ESCAPED_HTML;
    assert_eq!(html.as_str(), expected);
}

#[test]
fn test_escape_and_append_preserves_non_ascii() {
    let mut html = SafeHtml::escape("Hi!");
    html.escape_and_append(NON_ASCII_CHARS);
    let expected = String::from("Hi!") + NON_ASCII_CHARS;
    assert_eq!(html.as_str(), expected);
}

#[test]
fn test_escape_and_append_replaces_nul() {
    let mut html = SafeHtml::escape("Hi!");
    html.escape_and_append(NUL_HTML);
    let expected = String::from("Hi!") + NUL_ESCAPED_HTML;
    assert_eq!(html.as_str(), expected);
}

#[test]
fn test_character_reference_preservation_vectors() {
    assert_eq!(
        SafeHtml::escape_allow_character_references("&nbsp;").as_str(),
        "&nbsp;"
    );
    assert_eq!(
        SafeHtml::escape_allow_character_references("&#60;").as_str(),
        "&#60;"
    );
    assert_eq!(
        SafeHtml::escape_allow_character_references("&#x6F;").as_str(),
        "&#x6F;"
    );
    assert_eq!(
        SafeHtml::escape_allow_character_references("&n<bsp>!0 ").as_str(),
        "&amp;n&lt;bsp&gt;!0 "
    );
    assert_eq!(
        SafeHtml::escape_allow_character_references("&nbsp").as_str(),
        "&amp;nbsp"
    );
    assert_eq!(
        SafeHtml::escape_allow_character_references("<script>&nbsp;</script>").as_str(),
        "&lt;script&gt;&nbsp;&lt;/script&gt;"
    );
    assert_eq!(
        SafeHtml::escape_allow_character_references("&nbsp<script>;").as_str(),
        "&amp;nbsp&lt;script&gt;;"
    );
    assert_eq!(
        SafeHtml::escape_allow_character_references("&foo;&").as_str(),
        "&foo;&amp;"
    );
    assert_eq!(
        SafeHtml::escape_allow_character_references("&nbsp;&nbsp;").as_str(),
        "&nbsp;&nbsp;"
    );
    assert_eq!(
        SafeHtml::escape_allow_character_references("&foo;&;").as_str(),
        "&foo;&amp;;"
    );
    assert_eq!(
        SafeHtml::escape_allow_character_references("foo&&&").as_str(),
        "foo&amp;&amp;&amp;"
    );
    assert_eq!(
        SafeHtml::escape_allow_character_references("foo&lt;&&gt;").as_str(),
        "foo&lt;&amp;&gt;"
    );
    assert_eq!(
        SafeHtml::escape_allow_character_references("foo&lt\n;").as_str(),
        "foo&amp;lt\n;"
    );
    assert_eq!(
        SafeHtml::escape_allow_character_references("foo&lt\x07;").as_str(),
        "foo&amp;lt\u{FFFD};"
    );
}

#[test]
fn test_safe_html_from_proto_variants() {
    let empty_proto = SafeHtmlProto::default();
    let html = SafeHtml::from_proto(Some(&empty_proto));
    assert!(html.as_str().is_empty());

    let test_proto = SafeHtmlProto {
        private_do_not_access_or_else_safe_html_wrapped_value: TEST_HTML.to_string(),
    };
    let html2 = SafeHtml::from_proto(Some(&test_proto));
    assert_eq!(html2.as_str(), TEST_HTML);
}

#[test]
fn test_safe_html_to_proto_wraps_value() {
    let html = unsafe { SafeHtml::from_string_unchecked(TEST_HTML.to_string()) };
    let proto = html.to_proto();
    assert_eq!(
        proto.private_do_not_access_or_else_safe_html_wrapped_value,
        TEST_HTML
    );
}

#[test]
fn test_safe_html_display_formats_value() {
    let html = unsafe { SafeHtml::from_string_unchecked(TEST_HTML.to_string()) };
    let s = format!("{}", html);
    assert_eq!(s, TEST_HTML);
}

#[test]
fn test_html_operators() {
    let mut h1 = SafeHtml::escape("hello");
    let h2 = SafeHtml::escape(" world");
    h1 += &h2;
    assert_eq!(h1.as_str(), "hello world");

    let h3 = h1 + h2;
    assert_eq!(h3.as_str(), "hello world world");
}

#[test]
fn test_url_encode_component() {
    assert_eq!(url_encode_component("hello world"), "hello%20world");
    assert_eq!(url_encode_component("a-b.c_d~e"), "a-b.c_d~e");
    assert_eq!(url_encode_component("?&=#%+"), "%3F%26%3D%23%25%2B");
    assert_eq!(url_encode_component("1/2"), "1%2F2");
}

#[test]
fn test_safe_script_json() {
    let raw_json = r#"{"name": "<script>alert(1)</script>", "age": 20, "query": "a&b"}"#;
    let expected = r#"{"name": "\u003cscript\u003ealert(1)\u003c/script\u003e", "age": 20, "query": "a\u0026b"}"#;

    assert_eq!(escape_json_for_script(raw_json), expected);

    let script = SafeScript::from_escaped_json(raw_json);
    assert_eq!(script.as_str(), expected);
}

// =============================================================================
// Escape/coerce parity and scanner corner cases
// =============================================================================

/// The single most important structural test: `escape_html_and_coerce_to` must
/// agree with `coerce_to_interchange_valid_to` on every low codepoint that is
/// not one of the five HTML specials. A divergence here means the fast-path
/// byte scanner and the character classifier fell out of sync (this exact bug
/// previously shipped for DEL/0x7F).
#[test]
fn test_escape_coerce_parity_low_codepoints() {
    for u in 0u32..=0xA0 {
        let c = char::from_u32(u).unwrap();
        if matches!(c, '&' | '<' | '>' | '"' | '\'') {
            continue;
        }
        let s = format!("a{}b", c);
        let mut coerced = String::new();
        coerce_to_interchange_valid_to(&s, &mut coerced).unwrap();
        let mut escaped = String::new();
        escape_html_and_coerce_to(&s, &mut escaped).unwrap();
        assert_eq!(coerced, escaped, "divergence at U+{:04X}", u);
    }
    // A sample of non-characters and boundaries must also agree.
    for c in [
        '\u{FDD0}',
        '\u{FDEF}',
        '\u{FFFE}',
        '\u{10FFFF}',
        '\u{FDCF}',
        '\u{FDF0}',
    ] {
        let s = format!("a{}b", c);
        let mut coerced = String::new();
        coerce_to_interchange_valid_to(&s, &mut coerced).unwrap();
        let mut escaped = String::new();
        escape_html_and_coerce_to(&s, &mut escaped).unwrap();
        assert_eq!(coerced, escaped, "divergence at U+{:04X}", c as u32);
    }
}

/// Differential test against a naive per-character reference implementation.
#[test]
fn test_escape_matches_reference() {
    fn reference_escape(s: &str) -> String {
        let mut out = String::new();
        for c in s.chars() {
            match c {
                '&' => out.push_str("&amp;"),
                '<' => out.push_str("&lt;"),
                '>' => out.push_str("&gt;"),
                '"' => out.push_str("&#34;"),
                '\'' => out.push_str("&#39;"),
                c if is_interchange_invalid(c) => out.push('\u{FFFD}'),
                c => out.push(c),
            }
        }
        out
    }
    let samples = [
        "",
        "plain ascii with no specials at all",
        "<>&\"'",
        "a\x7Fb\u{85}c\u{9F}d",
        "mixed 丄ê𐒖t <b>bold</b> & 'quoted' \"text\" \u{FDD0}",
        "\t\n\r\x0C allowed whitespace survives",
        "🎉<🎉>🎉&🎉",
        "trailing special <",
        "< leading special",
    ];
    for s in samples {
        assert_eq!(
            SafeHtml::escape(s).as_str(),
            reference_escape(s),
            "input: {:?}",
            s
        );
    }
}

/// Positional sweep: a special character at every index of inputs spanning
/// several lengths, guarding any future chunked/SIMD scanner implementation.
#[test]
fn test_scanner_positional_sweep() {
    for len in [1usize, 2, 15, 16, 17, 31, 32, 33] {
        for pos in 0..len {
            let mut bytes = vec![b'a'; len];
            bytes[pos] = b'<';
            let s = String::from_utf8(bytes).unwrap();
            let mut got = String::new();
            escape_html_and_coerce_to(&s, &mut got).unwrap();
            assert_eq!(got, s.replace('<', "&lt;"), "len={} pos={}", len, pos);
        }
    }
}

#[test]
fn test_escape_html_del_and_controls() {
    // DEL (0x7F) must be coerced like every other invalid control.
    assert_eq!(SafeHtml::escape("a\x7Fb").as_str(), "a\u{FFFD}b");
    // C1 controls (multi-byte in UTF-8) are also coerced.
    assert_eq!(SafeHtml::escape("a\u{85}b").as_str(), "a\u{FFFD}b");
    // Allowed whitespace passes through untouched.
    assert_eq!(SafeHtml::escape("\t\n\r\x0C").as_str(), "\t\n\r\x0C");
}

#[test]
fn test_escape_html_multibyte_adjacency() {
    assert_eq!(SafeHtml::escape("🎉<🎉").as_str(), "🎉&lt;🎉");
    assert_eq!(SafeHtml::escape("é<").as_str(), "é&lt;");
    assert_eq!(SafeHtml::escape("<é").as_str(), "&lt;é");
    assert_eq!(SafeHtml::escape("𐒖").as_str(), "𐒖");
}

#[test]
fn test_escape_html_bytes_corner_cases() {
    // Invalid UTF-8 interleaved with HTML specials.
    assert_eq!(escape_html_bytes(b"<\xFF>"), "&lt;\u{FFFD}&gt;");
    // Truncated multi-byte sequence at end of input: one replacement char,
    // matching String::from_utf8_lossy semantics.
    assert_eq!(escape_html_bytes(b"abc\xE4\xB8"), "abc\u{FFFD}");
    assert_eq!(escape_html_bytes(b""), "");
    assert_eq!(escape_html_bytes("é<".as_bytes()), "é&lt;");
    // Specials directly adjacent to the invalid-byte resume boundary.
    assert_eq!(escape_html_bytes(b"\xFF<\xFF"), "\u{FFFD}&lt;\u{FFFD}");
}

// =============================================================================
// JSON-for-script corner cases
// =============================================================================

#[test]
fn test_json_escape_line_separators() {
    // U+2028/U+2029 are valid JSON but were invalid in pre-ES2019 JS string
    // literals; they must be escaped.
    assert_eq!(
        escape_json_for_script("a\u{2028}b\u{2029}c"),
        "a\\u2028b\\u2029c"
    );
    // Other characters sharing the 0xE2 lead byte pass through untouched.
    assert_eq!(escape_json_for_script("†‡•"), "†‡•");
}

#[test]
fn test_json_escape_edges() {
    assert_eq!(escape_json_for_script(""), "");
    assert_eq!(escape_json_for_script("<"), "\\u003c");
    assert_eq!(
        escape_json_for_script("<<<<"),
        "\\u003c\\u003c\\u003c\\u003c"
    );
    assert_eq!(escape_json_for_script("</script>"), "\\u003c/script\\u003e");
    // No specials at all: input must round-trip byte-identically.
    let plain = r#"{"key": "value with spaces and 'quotes'"}"#;
    assert_eq!(escape_json_for_script(plain), plain);
}

// =============================================================================
// URL policy pins: deliberate behaviors that must not change silently
// =============================================================================

#[test]
fn test_url_policy_pins() {
    // Protocol-relative URLs are treated as relative and accepted by both
    // validators. They cannot change the scheme but DO change the origin.
    assert!(is_safe_url_block_javascript("//evil.example/x"));
    assert!(is_safe_url_restrictive("//evil.example/x"));

    // A bare word with no colon is a relative URL.
    assert!(is_safe_url_restrictive("http"));

    // Default schemes match case-insensitively.
    assert!(is_safe_url_restrictive("HTTP://a"));
    assert!(is_safe_url_restrictive("HtTpS://a"));
    assert!(is_safe_url_restrictive("MAILTO:a@b"));
    assert!(!is_safe_url_restrictive("httpx://a"));

    // The block-only-javascript check deliberately allows every other scheme,
    // including data: and vbscript:. Use the restrictive check for allowlists.
    assert!(is_safe_url_block_javascript("data:text/html,<script>"));
    assert!(is_safe_url_block_javascript("vbscript:x"));

    // Extra schemes are trusted verbatim — they can even re-allow javascript.
    assert!(is_safe_url_restrictive_with_schemes(
        "javascript:alert(1)",
        &["javascript"]
    ));

    // A configured scheme must not match URLs whose scheme merely starts with it.
    assert!(!is_safe_url_restrictive_with_schemes("foobar:x", &["foo"]));
    // An empty extra scheme matches nothing.
    assert!(!is_safe_url_restrictive_with_schemes("foo://bar", &[""]));

    // Empty scheme (leading colon) is rejected by both validators.
    assert!(!is_safe_url_block_javascript(":foo"));
    assert!(!is_safe_url_restrictive(":foo"));

    // Ampersand before any path separator is rejected (entity-bypass hardening).
    assert!(!is_safe_url_restrictive("a&b"));

    // Whitespace inside a would-be scheme invalidates it.
    assert!(!is_safe_url_block_javascript("java\tscript:alert(1)"));
    assert!(!is_safe_url_block_javascript("java script:alert(1)"));
}

#[test]
fn test_data_url_corners() {
    // SVG can contain scripts and must be rejected.
    assert!(!is_safe_url_restrictive(
        "data:image/svg+xml;base64,PHN2Zz4="
    ));
    // Structural failures.
    assert!(!is_safe_url_restrictive("data:image/png;base64")); // no comma
    assert!(!is_safe_url_restrictive("data:;base64,QUJD")); // empty mime
    assert!(!is_safe_url_restrictive("data:image/png,plain")); // not base64 form
    assert!(!is_safe_url_restrictive(
        "data:image/png;foo=bar;base64,QUJD"
    )); // params
    // Padding rules: '=' only at the end.
    assert!(is_safe_url_restrictive("data:image/png;base64,QQ=="));
    assert!(!is_safe_url_restrictive("data:image/png;base64,Q=Q"));
    // Pins current behavior: a payload of bare padding passes the structural
    // check (browsers will simply fail to decode it — harmless).
    assert!(is_safe_url_restrictive("data:image/png;base64,="));
    // Less-common allowlisted MIME type.
    assert!(is_safe_url_restrictive("data:audio/x-matroska;base64,QUJD"));
}

#[test]
fn test_innocuous_url_fixed_point() {
    // Sanitizing the innocuous URL itself must never produce something else.
    assert_eq!(SafeUrl::sanitize(INNOCUOUS_URL).as_str(), INNOCUOUS_URL);
    assert_eq!(
        SafeUrl::sanitize_block_only_javascript(INNOCUOUS_URL).as_str(),
        INNOCUOUS_URL
    );
}

#[test]
fn test_safe_url_sanitize_variants() {
    assert_eq!(
        SafeUrl::sanitize_for_css("javascript:alert(1)").as_str(),
        INNOCUOUS_URL
    );
    assert_eq!(
        SafeUrl::sanitize_with_schemes("git://host/repo", &["git"]).as_str(),
        "git://host/repo"
    );
    assert_eq!(
        SafeUrl::sanitize_with_schemes("evil://x", &["git"]).as_str(),
        INNOCUOUS_URL
    );
}

// =============================================================================
// Character-reference corner cases
// =============================================================================

#[test]
fn test_char_refs_corners() {
    // Pins current behavior: a '#'-only entity shape is preserved.
    assert_eq!(
        SafeHtml::escape_allow_character_references("&#;").as_str(),
        "&#;"
    );
    // Entity names are matched by shape, not validated against the HTML spec.
    assert_eq!(
        SafeHtml::escape_allow_character_references("&NBSP;").as_str(),
        "&NBSP;"
    );
    // A non-ASCII character breaks the candidate; prefix is escaped.
    assert_eq!(
        SafeHtml::escape_allow_character_references("&nb\u{E9}sp;").as_str(),
        "&amp;nbésp;"
    );
    // Pathologically long non-reference stays linear and fully escaped.
    let long = format!("&{}", "a".repeat(10_000));
    assert_eq!(
        SafeHtml::escape_allow_character_references(&long).as_str(),
        format!("&amp;{}", "a".repeat(10_000))
    );
}

// =============================================================================
// Percent-encoding corner cases
// =============================================================================

#[test]
fn test_url_encode_non_ascii() {
    assert_eq!(url_encode_component("é"), "%C3%A9");
    assert_eq!(url_encode_component("naïve day"), "na%C3%AFve%20day");
    assert_eq!(url_encode_component(""), "");
}

#[test]
fn test_css_url_escape_corners() {
    // '%' passes through: already-encoded input is not double-encoded.
    assert_eq!(percent_escape_css_url("a%27b"), "a%27b");
    // Quotes, backslash, parens, and commas are all escaped.
    assert_eq!(percent_escape_css_url("'\"\\(),"), "%27%22%5C%28%29%2C");
    // Multi-byte characters are encoded per byte.
    assert_eq!(percent_escape_css_url("é"), "%C3%A9");
}

// =============================================================================
// Writer-error propagation (the panic-free claim, exercised)
// =============================================================================

struct FailingWriter {
    budget: usize,
}

impl core::fmt::Write for FailingWriter {
    fn write_str(&mut self, s: &str) -> core::fmt::Result {
        if s.len() > self.budget {
            return Err(core::fmt::Error);
        }
        self.budget -= s.len();
        Ok(())
    }
}

#[test]
fn test_writer_errors_propagate_without_panic() {
    let input = "a<b\x7F\u{2028}é🎉&nbsp;\x00 end";
    for budget in 0..64 {
        let _ = escape_html_and_coerce_to(input, &mut FailingWriter { budget });
        let _ = coerce_to_interchange_valid_to(input, &mut FailingWriter { budget });
        let _ = escape_allow_character_references_to(input, &mut FailingWriter { budget });
        let _ = escape_json_for_script_to(input, &mut FailingWriter { budget });
        let _ = url_encode_component_to(input, &mut FailingWriter { budget });
        let _ = percent_escape_css_url_to(input, &mut FailingWriter { budget });
        let _ =
            coerce_bytes_to_interchange_valid_to(input.as_bytes(), &mut FailingWriter { budget });
        let _ = escape_html_bytes_and_coerce_to(b"<\xFF>", &mut FailingWriter { budget });
    }
    // Zero-budget writers must produce Err for non-empty output...
    assert!(escape_html_and_coerce_to("<", &mut FailingWriter { budget: 0 }).is_err());
    // ...and Ok when there is nothing to write.
    assert!(escape_html_and_coerce_to("", &mut FailingWriter { budget: 0 }).is_ok());
}

// =============================================================================
// Type API coverage
// =============================================================================

#[test]
fn test_from_constant_and_default() {
    assert_eq!(SafeHtml::from_constant("<div>").as_str(), "<div>");
    assert_eq!(
        SafeUrl::from_constant("https://cdn.example/a").as_str(),
        "https://cdn.example/a"
    );
    assert_eq!(
        SafeScript::from_constant("console.log(1)").as_str(),
        "console.log(1)"
    );
    assert_eq!(
        TrustedResourceUrl::from_constant("/static/app.js").as_str(),
        "/static/app.js"
    );
    assert_eq!(
        SafeStyle::from_constant("width:1em;").as_str(),
        "width:1em;"
    );
    assert_eq!(
        SafeStyleSheet::from_constant("p{width:1em;}").as_str(),
        "p{width:1em;}"
    );

    assert_eq!(SafeHtml::default().as_str(), "");
    assert_eq!(SafeUrl::default().as_str(), "");
    assert_eq!(SafeScript::default().as_str(), "");
    assert_eq!(TrustedResourceUrl::default().as_str(), "");
    assert_eq!(SafeStyle::default().as_str(), "");
    assert_eq!(SafeStyleSheet::default().as_str(), "");
}

#[test]
fn test_trusted_resource_url_basics() {
    let empty = TrustedResourceUrl::empty();
    assert!(empty.as_str().is_empty());
    let u = TrustedResourceUrl::from_constant("/app.js");
    assert_eq!(format!("{}", u), "/app.js");
    assert_eq!(u.as_ref(), "/app.js");
    assert_eq!(u.clone().into_string(), "/app.js");
    let raw = unsafe { TrustedResourceUrl::from_string_unchecked("x".to_string()) };
    assert_eq!(raw.as_str(), "x");
}

#[test]
fn test_safe_script_basics() {
    assert!(SafeScript::empty().as_str().is_empty());
    let s = SafeScript::from_constant("var x = 1;");
    assert_eq!(format!("{}", s), "var x = 1;");
    assert_eq!(s.clone().into_string(), "var x = 1;");
}

#[test]
fn test_push_query_param() {
    let mut u = SafeUrl::sanitize("https://example.com/search");
    u.push_query_param("q", "a&b=c d");
    assert_eq!(u.as_str(), "https://example.com/search?q=a%26b%3Dc%20d");
    u.push_query_param("page", "2");
    assert_eq!(
        u.as_str(),
        "https://example.com/search?q=a%26b%3Dc%20d&page=2"
    );

    // Parameters are inserted before the fragment.
    let mut f = SafeUrl::sanitize("https://example.com/p?x=1#frag");
    f.push_query_param("y", "2");
    assert_eq!(f.as_str(), "https://example.com/p?x=1&y=2#frag");

    let mut t = TrustedResourceUrl::from_constant("/static/app.js");
    t.push_query_param("v", "1.2.3");
    assert_eq!(t.as_str(), "/static/app.js?v=1.2.3");
}

#[test]
fn test_proto_symmetry() {
    let url = SafeUrl::sanitize("https://example.com");
    let p = url.to_proto();
    assert_eq!(SafeUrl::from_proto(Some(&p)), url);
    assert_eq!(SafeUrl::from_proto(None).as_str(), "");
    assert_eq!(
        SafeUrl::from_proto(Some(&SafeUrlProto::default())).as_str(),
        ""
    );

    let script = SafeScript::from_constant("f()");
    let p = script.to_proto();
    assert_eq!(SafeScript::from_proto(Some(&p)), script);
    assert_eq!(SafeScript::from_proto(None).as_str(), "");
    assert_eq!(
        SafeScript::from_proto(Some(&SafeScriptProto::default())).as_str(),
        ""
    );

    let tru = TrustedResourceUrl::from_constant("/x.js");
    let p = tru.to_proto();
    assert_eq!(TrustedResourceUrl::from_proto(Some(&p)), tru);
    assert_eq!(TrustedResourceUrl::from_proto(None).as_str(), "");
    assert_eq!(
        TrustedResourceUrl::from_proto(Some(&TrustedResourceUrlProto::default())).as_str(),
        ""
    );

    let style = SafeStyle::from_constant("width:1em;");
    let p = style.to_proto();
    assert_eq!(SafeStyle::from_proto(Some(&p)), style);
    assert_eq!(SafeStyle::from_proto(None).as_str(), "");
    assert_eq!(
        SafeStyle::from_proto(Some(&SafeStyleProto::default())).as_str(),
        ""
    );

    let sheet = SafeStyleSheet::from_constant("p{width:1em;}");
    let p = sheet.to_proto();
    assert_eq!(SafeStyleSheet::from_proto(Some(&p)), sheet);
    assert_eq!(SafeStyleSheet::from_proto(None).as_str(), "");
    assert_eq!(
        SafeStyleSheet::from_proto(Some(&SafeStyleSheetProto::default())).as_str(),
        ""
    );
}

#[test]
fn test_from_and_from_iterator() {
    let s: String = SafeHtml::escape("x<y").into();
    assert_eq!(s, "x&lt;y");

    let parts = vec![SafeHtml::escape("a"), SafeHtml::escape("b")];
    // join/concat over borrowed items — no cloning required.
    let joined = SafeHtml::join(&parts, &SafeHtml::escape(","));
    assert_eq!(joined.as_str(), "a,b");
    let collected: SafeHtml = parts.iter().collect();
    assert_eq!(collected.as_str(), "ab");
    let collected_owned: SafeHtml = parts.into_iter().collect();
    assert_eq!(collected_owned.as_str(), "ab");
}

#[test]
fn test_join_concat_empty() {
    assert_eq!(SafeHtml::concat(Vec::<SafeHtml>::new()).as_str(), "");
    assert_eq!(
        SafeHtml::join(Vec::<SafeHtml>::new(), &SafeHtml::nbsp()).as_str(),
        ""
    );
    let parts = vec![SafeHtml::escape("a"), SafeHtml::escape("b")];
    assert_eq!(SafeHtml::join(&parts, &SafeHtml::empty()).as_str(), "ab");
}

#[test]
fn test_safe_html_cat_edges() {
    assert_eq!(safe_html_cat!().as_str(), "");
    assert_eq!(safe_html_cat!('<').as_str(), "&lt;");
    assert_eq!(
        safe_html_cat!(-5, " ", 2.5, " ", true).as_str(),
        "-5 2.5 true"
    );
}

#[test]
fn test_html_escaped_display() {
    assert_eq!(
        format!("{}", html_escaped("<a href='x'>")),
        "&lt;a href=&#39;x&#39;&gt;"
    );
    assert_eq!(
        format!("pre {} post", html_escaped("a&b")),
        "pre a&amp;b post"
    );
}

// =============================================================================
// SafeStyle / SafeStyleSheet
// =============================================================================

#[test]
fn test_style_property_value_validation() {
    // Allowed values.
    assert!(is_safe_style_property_value("1em"));
    assert!(is_safe_style_property_value("100%"));
    assert!(is_safe_style_property_value("#f00"));
    assert!(is_safe_style_property_value("red !important"));
    assert!(is_safe_style_property_value("0 auto"));
    assert!(is_safe_style_property_value(""));
    // '*' and '/' are fine in isolation...
    assert!(is_safe_style_property_value("1/2"));
    // ...but comment markers are blocked.
    assert!(!is_safe_style_property_value("/* comment */"));
    assert!(!is_safe_style_property_value("a//b"));
    assert!(!is_safe_style_property_value("a*/b*"));
    // Function calls, strings, and structural characters are blocked.
    assert!(!is_safe_style_property_value("url(http://evil)"));
    assert!(!is_safe_style_property_value("expression(alert(1))"));
    assert!(!is_safe_style_property_value("red;background:url(x)"));
    assert!(!is_safe_style_property_value("'quoted'"));
    assert!(!is_safe_style_property_value("a:b"));
    assert!(!is_safe_style_property_value("<style>"));

    // Property names: letters and hyphens only.
    assert!(is_safe_style_property_name("background-color"));
    assert!(!is_safe_style_property_name(""));
    assert!(!is_safe_style_property_name("color:red;x"));
}

#[test]
fn test_safe_style_from_properties() {
    let style = SafeStyle::from_properties(&[
        ("width", "1em"),
        ("background-color", "#fff"),
        ("height", " 2em "), // trimmed
    ]);
    assert_eq!(
        style.as_str(),
        "width:1em;background-color:#fff;height:2em;"
    );

    // Invalid values are replaced with the innocuous placeholder.
    let evil = SafeStyle::from_properties(&[("color", "red;}</style><script>x</script>")]);
    assert_eq!(
        evil.as_str(),
        format!("color:{};", INNOCUOUS_PROPERTY_VALUE)
    );

    // Invalid names are skipped entirely.
    let skipped = SafeStyle::from_properties(&[("bad name!", "red"), ("color", "red")]);
    assert_eq!(skipped.as_str(), "color:red;");

    // Composability: append keeps the declaration sequence well-formed.
    let mut a = SafeStyle::from_properties(&[("width", "1em")]);
    a.append(&SafeStyle::from_properties(&[("height", "2em")]));
    assert_eq!(a.as_str(), "width:1em;height:2em;");
}

#[test]
fn test_safe_style_background_image_url() {
    let mut style = SafeStyle::empty();
    style.push_background_image_url("https://example.com/img.png?a=1");
    assert_eq!(
        style.as_str(),
        "background-image:url(\"https://example.com/img.png?a=1\");"
    );

    // Quotes and parens in the URL cannot break out of url("...").
    let mut breakout = SafeStyle::empty();
    breakout.push_background_image_url("https://e.com/\");background:url(\"x");
    assert!(!breakout.as_str().contains("\")b"));
    assert!(breakout.as_str().starts_with("background-image:url(\""));

    // Unsafe schemes collapse to the innocuous URL.
    let mut evil = SafeStyle::empty();
    evil.push_background_image_url("javascript:alert(1)");
    assert!(evil.as_str().contains("about:invalid"));
}

#[test]
fn test_css_selector_validation() {
    assert!(is_safe_css_selector("p"));
    assert!(is_safe_css_selector("div.card > ul li:first-child"));
    assert!(is_safe_css_selector("#id, .cls, a:hover"));
    assert!(is_safe_css_selector("input[type=\"text\"]"));
    assert!(is_safe_css_selector("*"));
    // Rejections: breakout and comment characters, imbalance.
    assert!(!is_safe_css_selector(""));
    assert!(!is_safe_css_selector("p{color:red}q"));
    assert!(!is_safe_css_selector("p</style>"));
    assert!(!is_safe_css_selector("a/*b*/"));
    assert!(!is_safe_css_selector("p;q"));
    assert!(!is_safe_css_selector("@media"));
    assert!(!is_safe_css_selector("p)"));
    assert!(!is_safe_css_selector("p("));
    assert!(!is_safe_css_selector("a[b"));
    assert!(!is_safe_css_selector("a\"b"));
    assert!(!is_safe_css_selector("a\\b"));
}

#[test]
fn test_safe_style_sheet_rules() {
    let style = SafeStyle::from_properties(&[("color", "red")]);
    let sheet = SafeStyleSheet::from_style_rule("p.note", &style).unwrap();
    assert_eq!(sheet.as_str(), "p.note{color:red;}");

    assert!(SafeStyleSheet::from_style_rule("p{}</style>", &style).is_none());

    let mut combined = SafeStyleSheet::from_style_rule("p", &style).unwrap();
    combined.append(&SafeStyleSheet::from_style_rule("q", &style).unwrap());
    assert_eq!(combined.as_str(), "p{color:red;}q{color:red;}");
}

// =============================================================================
// Serde coverage for the remaining types
// =============================================================================

#[cfg(feature = "serde")]
#[test]
fn test_serde_script_style_and_trusted() {
    let s = SafeScript::from_constant("f(1)");
    let ser = serde_json::to_string(&s).unwrap();
    assert_eq!(ser, "\"f(1)\"");
    let de: SafeScript = serde_json::from_str(&ser).unwrap();
    assert_eq!(de, s);

    let t = TrustedResourceUrl::from_constant("/a.js");
    let ser = serde_json::to_string(&t).unwrap();
    let de: TrustedResourceUrl = serde_json::from_str(&ser).unwrap();
    assert_eq!(de, t);

    let st = SafeStyle::from_properties(&[("width", "1em")]);
    let ser = serde_json::to_string(&st).unwrap();
    let de: SafeStyle = serde_json::from_str(&ser).unwrap();
    assert_eq!(de, st);

    let sh = SafeStyleSheet::from_constant("p{width:1em;}");
    let ser = serde_json::to_string(&sh).unwrap();
    let de: SafeStyleSheet = serde_json::from_str(&ser).unwrap();
    assert_eq!(de, sh);

    // Relative URLs deserialize successfully.
    let rel: SafeUrl = serde_json::from_str("\"/path?x=1\"").unwrap();
    assert_eq!(rel.as_str(), "/path?x=1");
}

// --- Cow<'static, str> internals: const constructors and copy-on-write ---

#[test]
fn const_constructors_are_const_and_correct() {
    const HTML: SafeHtml = SafeHtml::from_constant("<b>hi</b>");
    const EMPTY: SafeHtml = SafeHtml::empty();
    const NBSP: SafeHtml = SafeHtml::nbsp();
    static URL: SafeUrl = SafeUrl::from_constant("https://example.com");
    const SCRIPT: SafeScript = SafeScript::from_constant("run();");
    const RES: TrustedResourceUrl = TrustedResourceUrl::from_constant("/static/app.js");
    const STYLE: SafeStyle = SafeStyle::from_constant("color:red;");
    const SHEET: SafeStyleSheet = SafeStyleSheet::from_constant("p{color:red;}");

    assert_eq!(HTML.as_str(), "<b>hi</b>");
    assert_eq!(EMPTY.as_str(), "");
    assert_eq!(NBSP.as_str(), "&nbsp;");
    assert_eq!(URL.as_str(), "https://example.com");
    assert_eq!(SCRIPT.as_str(), "run();");
    assert_eq!(RES.as_str(), "/static/app.js");
    assert_eq!(STYLE.as_str(), "color:red;");
    assert_eq!(SHEET.as_str(), "p{color:red;}");
}

#[test]
fn constants_promote_to_owned_on_mutation() {
    let mut html = SafeHtml::from_constant("<b>");
    html.escape_and_append("<i>");
    assert_eq!(html.as_str(), "<b>&lt;i&gt;");

    let mut url = SafeUrl::from_constant("https://example.com/");
    url.push_query_param("q", "a b");
    assert_eq!(url.as_str(), "https://example.com/?q=a%20b");

    let mut style = SafeStyle::from_constant("color:red;");
    style.push_property("margin", "0");
    assert_eq!(style.as_str(), "color:red;margin:0;");

    let mut sheet = SafeStyleSheet::from_constant("p{color:red;}");
    sheet.append(&SafeStyleSheet::from_constant("b{margin:0;}"));
    assert_eq!(sheet.as_str(), "p{color:red;}b{margin:0;}");

    assert_eq!(SafeHtml::from_constant("x").into_string(), "x");
    assert_eq!(String::from(SafeUrl::from_constant("/a")), "/a");
}

// --- Borrowed no_std safe types (SafeHtmlStr family) ---

#[test]
fn borrowed_types_const_construction() {
    use safehtml::{SafeHtmlStr, SafeStyleStr, SafeUrlStr};

    const GREETING: &SafeHtmlStr = SafeHtmlStr::from_constant("<b>hello</b>");
    static STYLE: &SafeStyleStr = SafeStyleStr::from_constant("color:red;");

    assert_eq!(GREETING.as_str(), "<b>hello</b>");
    assert_eq!(STYLE.as_str(), "color:red;");
    assert_eq!(SafeHtmlStr::EMPTY.as_str(), "");
    assert_eq!(SafeUrlStr::INNOCUOUS.as_str(), INNOCUOUS_URL);
    // Deref to str gives the usual string API.
    assert_eq!(GREETING.len(), 12);
    assert!(GREETING.starts_with("<b>"));
}

#[test]
fn borrowed_and_owned_interop() {
    use safehtml::SafeHtmlStr;

    let owned = SafeHtml::escape("<i>");
    // Owned derefs to borrowed…
    let borrowed: &SafeHtmlStr = &owned;
    assert_eq!(borrowed.as_str(), "&lt;i&gt;");
    // …and str methods still reach through the chain.
    assert!(owned.contains("lt"));

    // Borrowed round-trips back to owned via ToOwned / From.
    let owned_again: SafeHtml = borrowed.to_owned();
    assert_eq!(owned_again, owned);
    let converted = SafeHtml::from(SafeHtmlStr::from_constant("<hr>"));
    assert_eq!(converted.as_str(), "<hr>");

    // Cross-type comparison.
    assert_eq!(owned, *borrowed);

    // Cow over the borrowed type works (Borrow + ToOwned).
    let cow: std::borrow::Cow<'_, SafeHtmlStr> = std::borrow::Cow::Borrowed(borrowed);
    assert_eq!(cow.as_str(), "&lt;i&gt;");

    // Borrowed parts interpolate into safe_html_cat! unescaped.
    let cat = safehtml::safe_html_cat!(SafeHtmlStr::from_constant("<p>"), "5 < 6");
    assert_eq!(cat.as_str(), "<p>5 &lt; 6");
}