xml-sec 0.2.0

Pure Rust XML Security: XMLDSig, XMLEnc, C14N. Drop-in replacement for libxmlsec1.
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
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
use std::cell::Cell;
use std::collections::{HashMap, HashSet};
use std::fmt::Write as _;
use std::ops::Deref;

#[cfg(feature = "embedded")]
use crate::xml_input_shared as xml_sec_xml_input;

use super::budget::Meter;
use super::{BudgetKind, Document, Error, NodeId, NodeKind, Result};

/// XSLT output method.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum OutputMethod {
    #[default]
    Xml,
    Html,
    Text,
}

/// Compiled `xsl:output` properties.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct OutputDefinition {
    pub method: OutputMethod,
    pub version: Option<String>,
    pub encoding: String,
    pub omit_xml_declaration: bool,
    pub standalone: Option<bool>,
    pub doctype_public: Option<String>,
    pub doctype_system: Option<String>,
    pub indent: bool,
    pub media_type: Option<String>,
    pub cdata_section_elements: HashSet<super::ExpandedName>,
    pub(crate) method_explicit: bool,
    pub(crate) encoding_explicit: bool,
    pub(crate) indent_explicit: bool,
    pub(crate) inject_content_type: bool,
}

impl Default for OutputDefinition {
    fn default() -> Self {
        Self {
            method: OutputMethod::Xml,
            version: Some("1.0".into()),
            encoding: "UTF-8".into(),
            omit_xml_declaration: false,
            standalone: None,
            doctype_public: None,
            doctype_system: None,
            indent: false,
            media_type: None,
            cdata_section_elements: HashSet::new(),
            method_explicit: false,
            encoding_explicit: false,
            indent_explicit: false,
            inject_content_type: true,
        }
    }
}

impl OutputDefinition {
    pub(crate) fn owned_bytes(&self) -> usize {
        self.version
            .as_ref()
            .map_or(0, String::len)
            .saturating_add(self.encoding.len())
            .saturating_add(self.doctype_public.as_ref().map_or(0, String::len))
            .saturating_add(self.doctype_system.as_ref().map_or(0, String::len))
            .saturating_add(self.media_type.as_ref().map_or(0, String::len))
            .saturating_add(super::budget::retained_hash_storage::<super::ExpandedName>(
                self.cdata_section_elements.capacity(),
            ))
            .saturating_add(
                self.cdata_section_elements
                    .iter()
                    .fold(0usize, |total, name| {
                        total
                            .saturating_add(name.namespace.as_ref().map_or(0, String::len))
                            .saturating_add(name.local.len())
                    }),
            )
    }
}

struct EffectiveOutputDefinition<'a> {
    source: &'a OutputDefinition,
    method: OutputMethod,
    indent: bool,
    xml_version: &'a str,
}

impl Deref for EffectiveOutputDefinition<'_> {
    type Target = OutputDefinition;

    fn deref(&self) -> &Self::Target {
        self.source
    }
}

/// Exact serialized result bytes and metadata.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SerializedOutput {
    pub bytes: Vec<u8>,
    pub encoding: String,
    pub media_type: Option<String>,
}

enum OutputEncoding {
    Utf8,
    Utf16,
    Utf16Le,
    Utf16Be,
    Ascii,
    Registered(xml_sec_xml_input::IanaSingleByteEncoding),
    Other {
        encoding: &'static encoding_rs::Encoding,
        representable: [Cell<Option<(char, bool)>>; 16],
    },
}

impl OutputEncoding {
    fn new(label: &str) -> Result<Self> {
        if label.eq_ignore_ascii_case("utf-8") {
            Ok(Self::Utf8)
        } else if label.eq_ignore_ascii_case("utf-16") {
            Ok(Self::Utf16)
        } else if label.eq_ignore_ascii_case("utf-16le") {
            Ok(Self::Utf16Le)
        } else if label.eq_ignore_ascii_case("utf-16be") {
            Ok(Self::Utf16Be)
        } else if is_ascii_encoding_label(label) {
            Ok(Self::Ascii)
        } else if let Some(encoding) = xml_sec_xml_input::registered_single_byte_encoding(label) {
            Ok(Self::Registered(encoding))
        } else {
            encoding_rs::Encoding::for_label_no_replacement(label.as_bytes())
                .and_then(|encoding| {
                    xml_sec_xml_input::legacy_label_matches_encoding(label, encoding).then_some(
                        Self::Other {
                            encoding,
                            representable: [const { Cell::new(None) }; 16],
                        },
                    )
                })
                .ok_or_else(|| Error::Serialization(format!("unsupported output encoding {label}")))
        }
    }

    fn represents(&self, character: char) -> bool {
        match self {
            Self::Utf8 | Self::Utf16 | Self::Utf16Le | Self::Utf16Be => true,
            Self::Ascii => character.is_ascii(),
            Self::Registered(encoding) => encoding.encode_char(character).is_some(),
            Self::Other {
                encoding,
                representable,
            } => {
                let slot = &representable[u32::from(character) as usize % representable.len()];
                if let Some((cached, value)) = slot.get()
                    && cached == character
                {
                    return value;
                }
                let value = encoding_represents(encoding, character);
                slot.set(Some((character, value)));
                value
            }
        }
    }

    fn canonical_name(&self) -> &'static str {
        match self {
            Self::Utf8 => "UTF-8",
            Self::Utf16 => "UTF-16",
            Self::Utf16Le => "UTF-16LE",
            Self::Utf16Be => "UTF-16BE",
            Self::Ascii => "US-ASCII",
            Self::Registered(encoding) => encoding.name(),
            Self::Other { encoding, .. } => encoding.name(),
        }
    }

    fn declaration_name<'a>(&self, requested: &'a str) -> &'a str {
        if matches!(self, Self::Ascii) {
            if requested.eq_ignore_ascii_case("ascii") || requested.eq_ignore_ascii_case("us-ascii")
            {
                requested
            } else {
                self.canonical_name()
            }
        } else if xml_sec_xml_input::is_xml_encoding_name(requested) {
            requested
        } else {
            self.canonical_name()
        }
    }
}

fn encoding_represents(encoding: &'static encoding_rs::Encoding, character: char) -> bool {
    let mut utf8 = [0_u8; 4];
    let mut source: &str = character.encode_utf8(&mut utf8);
    let mut encoder = encoding.new_encoder();
    let mut output = [0_u8; 32];
    loop {
        let (result, read, _) =
            encoder.encode_from_utf8_without_replacement(source, &mut output, true);
        source = &source[read..];
        match result {
            encoding_rs::EncoderResult::InputEmpty => return true,
            encoding_rs::EncoderResult::OutputFull => {}
            encoding_rs::EncoderResult::Unmappable(_) => return false,
        }
    }
}

fn is_ascii_encoding_label(label: &str) -> bool {
    [
        "us-ascii",
        "ascii",
        "ansi_x3.4-1968",
        "ansi_x3.4-1986",
        "iso-ir-6",
        "iso_646.irv:1991",
        "iso646-us",
        "ibm367",
        "cp367",
        "csascii",
        "us",
    ]
    .iter()
    .any(|alias| label.eq_ignore_ascii_case(alias))
}

pub(crate) fn serialize(
    document: &Document,
    definition: &OutputDefinition,
    meter: &mut Meter,
) -> Result<SerializedOutput> {
    serialize_charged(document, definition, meter, BudgetKind::SerializedBytes)
}

pub(crate) fn serialize_fragment(document: &Document, meter: &mut Meter) -> Result<String> {
    let mut definition = OutputDefinition {
        omit_xml_declaration: true,
        ..OutputDefinition::default()
    };
    definition.method_explicit = true;
    definition.indent_explicit = true;
    let definition = EffectiveOutputDefinition {
        method: definition.method,
        indent: definition.indent,
        xml_version: supported_xml_version(&definition),
        source: &definition,
    };
    let (used, limit) = meter.usage(BudgetKind::OwnedBytes)?;
    let mut counter = RenderBuffer::counting(
        EncodingCounter::new(&OutputEncoding::Utf8),
        BudgetKind::OwnedBytes,
        used,
        limit,
    );
    render(
        document,
        &definition,
        &OutputEncoding::Utf8,
        &mut counter,
        meter,
    )?;
    let bytes = counter.len();
    meter.charge(BudgetKind::OwnedBytes, bytes)?;
    let mut text = RenderBuffer::Text(String::with_capacity(bytes));
    render(
        document,
        &definition,
        &OutputEncoding::Utf8,
        &mut text,
        meter,
    )?;
    Ok(text.into_string())
}

fn serialize_charged(
    document: &Document,
    definition: &OutputDefinition,
    meter: &mut Meter,
    budget_kind: BudgetKind,
) -> Result<SerializedOutput> {
    let infer_html_method = !definition.method_explicit && infer_html_output(document);
    let infer_indent = (infer_html_method || definition.method == OutputMethod::Html)
        && !definition.indent_explicit;
    let effective = EffectiveOutputDefinition {
        source: definition,
        method: if infer_html_method {
            OutputMethod::Html
        } else {
            definition.method
        },
        indent: infer_indent || definition.indent,
        xml_version: supported_xml_version(definition),
    };
    serialize_with_definition(document, &effective, meter, budget_kind)
}

fn serialize_with_definition(
    document: &Document,
    definition: &EffectiveOutputDefinition<'_>,
    meter: &mut Meter,
    budget_kind: BudgetKind,
) -> Result<SerializedOutput> {
    if definition.method == OutputMethod::Xml
        && ((!definition.omit_xml_declaration && definition.standalone.is_some())
            || definition.doctype_system.is_some())
    {
        validate_document_output_shape(document)?;
    }
    let encoding = OutputEncoding::new(&definition.encoding)?;
    let (used, limit) = meter.usage(budget_kind)?;
    let mut counter =
        RenderBuffer::counting(EncodingCounter::new(&encoding), budget_kind, used, limit);
    render(document, definition, &encoding, &mut counter, meter)?;
    let text_bytes = counter.len();
    let encoded_bytes = counter.encoded_len()?;
    meter.check_additional(budget_kind, encoded_bytes)?;
    meter.charge(BudgetKind::OwnedBytes, text_bytes)?;
    let mut text = RenderBuffer::Text(String::with_capacity(text_bytes));
    render(document, definition, &encoding, &mut text, meter)?;
    let text = text.into_string();
    if definition.method == OutputMethod::Xml {
        validate_xml_characters(&text, definition.xml_version)?;
    }
    if definition.method == OutputMethod::Text {
        validate_text_encoding(&text, &encoding, &definition.encoding)?;
    } else {
        reject_unrepresentable_markup(&text, &encoding, "serialized output")?;
    }
    let bytes = encode(
        text,
        text_bytes,
        encoded_bytes,
        &encoding,
        meter,
        budget_kind,
    )?;
    let media_type = definition
        .media_type
        .as_deref()
        .unwrap_or(match definition.method {
            OutputMethod::Xml => "text/xml",
            OutputMethod::Html => "text/html",
            OutputMethod::Text => "text/plain",
        });
    meter.charge(
        BudgetKind::OwnedBytes,
        definition.encoding.len().saturating_add(media_type.len()),
    )?;
    Ok(SerializedOutput {
        bytes,
        encoding: definition.encoding.clone(),
        media_type: Some(media_type.into()),
    })
}

fn supported_xml_version(definition: &OutputDefinition) -> &str {
    // XSLT 1.0 section 16.1 requires an unsupported requested XML version to fall back to a
    // version the processor supports. XML 1.0 is the deterministic compatibility fallback.
    // https://www.w3.org/TR/1999/REC-xslt-19991116#section-XML-Output-Method
    match definition.version.as_deref() {
        Some(version @ ("1.0" | "1.1")) => version,
        _ => "1.0",
    }
}

fn render(
    document: &Document,
    definition: &EffectiveOutputDefinition<'_>,
    encoding: &OutputEncoding,
    text: &mut RenderBuffer,
    meter: &mut Meter,
) -> Result<()> {
    if definition.method == OutputMethod::Xml && !definition.omit_xml_declaration {
        text.push_str("<?xml version=\"");
        text.push_str(definition.xml_version);
        text.push('"');
        // XSLT 1.0 section 16.1 recommends, but does not require, an encoding pseudo-attribute.
        // Match pinned libxslt output by emitting it only for an explicit xsl:output encoding.
        // https://www.w3.org/TR/1999/REC-xslt-19991116#section-XML-Output-Method
        if definition.encoding_explicit {
            text.push_str(" encoding=\"");
            text.push_str(encoding.declaration_name(&definition.encoding));
            text.push('"');
        }
        if let Some(standalone) = definition.standalone {
            text.push_str(if standalone {
                " standalone=\"yes\""
            } else {
                " standalone=\"no\""
            });
        }
        text.push_str("?>");
        text.push('\n');
    }
    let children = &document
        .node(document.root())
        .ok_or_else(|| Error::Serialization("missing result root".into()))?
        .children;
    let document_element = children.iter().copied().find(|child| {
        document
            .node(*child)
            .is_some_and(|node| matches!(node.kind, NodeKind::Element { .. }))
    });
    for (index, child) in children.iter().enumerate() {
        // XSLT 1.0 section 16.3 defines text output as the concatenation of text nodes;
        // serialization-only declarations therefore cannot appear in it.
        // https://www.w3.org/TR/1999/REC-xslt-19991116#output
        if definition.method != OutputMethod::Text && Some(*child) == document_element {
            render_doctype(document, *child, definition, encoding, text)?;
        }
        serialize_node(
            document,
            *child,
            definition,
            encoding,
            text,
            RenderContext::root(),
            meter,
        )?;
        if definition.method == OutputMethod::Xml
            && (definition.indent || !definition.omit_xml_declaration)
            && index + 1 < children.len()
            && document
                .node(*child)
                .is_some_and(|node| matches!(node.kind, NodeKind::Comment(_)))
        {
            text.push('\n');
        }
    }
    // XSLT 1.0 section 16.1 says an effective indent=no "should not" add whitespace, rather
    // than imposing a must-not requirement. Pinned libxslt appends this final newline when
    // `indent` is omitted but suppresses it for explicit indent=no, so preserve that observable
    // compatibility distinction: https://www.w3.org/TR/1999/REC-xslt-19991116#output
    if definition.method != OutputMethod::Text && (!definition.indent_explicit || definition.indent)
    {
        text.push('\n');
    }
    Ok(())
}

fn render_doctype(
    document: &Document,
    element: NodeId,
    definition: &EffectiveOutputDefinition<'_>,
    encoding: &OutputEncoding,
    text: &mut RenderBuffer,
) -> Result<()> {
    // XSLT 1.0 section 16.2 emits an HTML document type declaration only when
    // doctype-public or doctype-system is specified; version alone is not a declaration request.
    // https://www.w3.org/TR/1999/REC-xslt-19991116#section-HTML-Output-Method
    if definition.doctype_system.is_none()
        && !(definition.method == OutputMethod::Html && definition.doctype_public.is_some())
    {
        return Ok(());
    }
    if definition.method == OutputMethod::Xml
        && let Some(public) = &definition.doctype_public
    {
        validate_xml_public_identifier(public)?;
    }
    if definition.method == OutputMethod::Xml
        && let Some(system) = &definition.doctype_system
    {
        validate_xml_system_identifier(system)?;
    }
    let Some(NodeKind::Element { name, prefix, .. }) =
        document.node(element).map(|node| &node.kind)
    else {
        return Err(Error::Serialization(
            "document element disappeared during serialization".into(),
        ));
    };
    text.push_str("<!DOCTYPE ");
    if definition.method == OutputMethod::Html {
        // XSLT 1.0 section 16.2 fixes this name to HTML independently of the result root.
        // https://www.w3.org/TR/1999/REC-xslt-19991116#section-HTML-Output-Method
        text.push_str("html");
    } else {
        push_name(prefix.as_deref(), &name.local, encoding, text)?;
    }
    match (&definition.doctype_public, &definition.doctype_system) {
        (Some(public), Some(system)) => {
            text.push_str(" PUBLIC ");
            push_external_identifier_literal(public, "public identifier", encoding, text)?;
            text.push(' ');
            push_external_identifier_literal(system, "system identifier", encoding, text)?;
        }
        (Some(public), None) if definition.method == OutputMethod::Html => {
            text.push_str(" PUBLIC ");
            push_external_identifier_literal(public, "public identifier", encoding, text)?;
        }
        (Some(_), None) => {}
        (None, Some(system)) => {
            text.push_str(" SYSTEM ");
            push_external_identifier_literal(system, "system identifier", encoding, text)?;
        }
        (None, None) => {}
    }
    text.push('>');
    text.push('\n');
    Ok(())
}

fn validate_xml_public_identifier(value: &str) -> Result<()> {
    if value.chars().all(|character| {
        character.is_ascii_alphanumeric()
            || matches!(
                character,
                ' ' | '\r'
                    | '\n'
                    | '-'
                    | '\''
                    | '('
                    | ')'
                    | '+'
                    | ','
                    | '.'
                    | '/'
                    | ':'
                    | '='
                    | '?'
                    | ';'
                    | '!'
                    | '*'
                    | '#'
                    | '@'
                    | '$'
                    | '_'
                    | '%'
            )
    }) {
        Ok(())
    } else {
        Err(Error::Serialization(
            "doctype public identifier contains a character outside XML PubidChar".into(),
        ))
    }
}

fn validate_xml_system_identifier(value: &str) -> Result<()> {
    // XML 1.0 section 4.2.2 makes a fragment identifier in a SystemLiteral an error:
    // https://www.w3.org/TR/xml/#sec-external-ent
    if value.contains('#') {
        return Err(Error::Serialization(
            "doctype system identifier must not contain a fragment identifier".into(),
        ));
    }
    Ok(())
}

fn push_external_identifier_literal(
    value: &str,
    kind: &str,
    encoding: &OutputEncoding,
    output: &mut RenderBuffer,
) -> Result<()> {
    reject_unrepresentable_markup(value, encoding, kind)?;
    let delimiter = if !value.contains('"') {
        '"'
    } else if !value.contains('\'') {
        '\''
    } else {
        return Err(Error::Serialization(format!(
            "doctype {kind} contains both quote delimiters"
        )));
    };
    output.push(delimiter);
    output.push_str(value);
    output.push(delimiter);
    Ok(())
}

enum RenderBuffer {
    Count {
        counter: EncodingCounter,
        kind: BudgetKind,
        used: usize,
        limit: usize,
        exceeded: Option<usize>,
    },
    Text(String),
}

impl RenderBuffer {
    fn counting(counter: EncodingCounter, kind: BudgetKind, used: usize, limit: usize) -> Self {
        Self::Count {
            counter,
            kind,
            used,
            limit,
            exceeded: None,
        }
    }

    fn push_str(&mut self, value: &str) {
        match self {
            Self::Count {
                counter,
                used,
                limit,
                exceeded,
                ..
            } => {
                if exceeded.is_some() {
                    return;
                }
                counter.push_str(value);
                let actual = used.saturating_add(counter.encoded_bytes);
                if actual > *limit {
                    *exceeded = Some(actual);
                }
            }
            Self::Text(output) => output.push_str(value),
        }
    }

    fn push(&mut self, value: char) {
        match self {
            Self::Count { .. } => {
                let mut buffer = [0_u8; 4];
                self.push_str(value.encode_utf8(&mut buffer));
            }
            Self::Text(output) => output.push(value),
        }
    }

    fn push_repeated(&mut self, byte: u8, count: usize) -> Result<()> {
        const CHUNK_SIZE: usize = 64;
        let chunk = [byte; CHUNK_SIZE];
        let chunk = std::str::from_utf8(&chunk)
            .map_err(|_| Error::Serialization("non-ASCII repeated render byte".into()))?;
        let mut remaining = count;
        while remaining >= CHUNK_SIZE {
            self.push_str(chunk);
            self.ensure_within_limit()?;
            remaining -= CHUNK_SIZE;
        }
        if remaining > 0 {
            self.push_str(&chunk[..remaining]);
            self.ensure_within_limit()?;
        }
        Ok(())
    }

    fn ensure_within_limit(&self) -> Result<()> {
        if let Self::Count {
            kind,
            limit,
            exceeded: Some(actual),
            ..
        } = self
        {
            return Err(Error::Budget {
                kind: *kind,
                limit: *limit,
                actual: *actual,
            });
        }
        Ok(())
    }

    const fn len(&self) -> usize {
        match self {
            Self::Count { counter, .. } => counter.utf8_bytes,
            Self::Text(output) => output.len(),
        }
    }

    fn into_string(self) -> String {
        match self {
            Self::Text(output) => output,
            Self::Count { .. } => unreachable!("counting buffer does not contain rendered text"),
        }
    }

    fn encoded_len(&mut self) -> Result<usize> {
        match self {
            Self::Count {
                counter,
                used,
                limit,
                exceeded,
                ..
            } => {
                let encoded = counter.finish();
                let actual = used.saturating_add(encoded);
                if actual > *limit {
                    *exceeded = Some(actual);
                }
                self.ensure_within_limit()?;
                Ok(encoded)
            }
            Self::Text(output) => Ok(output.len()),
        }
    }
}

impl std::fmt::Write for RenderBuffer {
    fn write_str(&mut self, value: &str) -> std::fmt::Result {
        self.push_str(value);
        Ok(())
    }
}

enum EncodingCounterKind {
    Utf8,
    Ascii,
    Registered,
    Utf16,
    Other(encoding_rs::Encoder),
}

struct EncodingCounter {
    utf8_bytes: usize,
    encoded_bytes: usize,
    kind: EncodingCounterKind,
    finished: bool,
}

impl EncodingCounter {
    fn new(encoding: &OutputEncoding) -> Self {
        let kind = match encoding {
            OutputEncoding::Utf8 => EncodingCounterKind::Utf8,
            OutputEncoding::Ascii => EncodingCounterKind::Ascii,
            OutputEncoding::Registered(_) => EncodingCounterKind::Registered,
            OutputEncoding::Utf16 | OutputEncoding::Utf16Le | OutputEncoding::Utf16Be => {
                EncodingCounterKind::Utf16
            }
            OutputEncoding::Other { encoding, .. } => {
                EncodingCounterKind::Other(encoding.new_encoder())
            }
        };
        let encoded_bytes = matches!(encoding, OutputEncoding::Utf16)
            .then_some(2)
            .unwrap_or(0);
        Self {
            utf8_bytes: 0,
            encoded_bytes,
            kind,
            finished: false,
        }
    }

    fn push_str(&mut self, value: &str) {
        self.utf8_bytes = self.utf8_bytes.saturating_add(value.len());
        match &mut self.kind {
            EncodingCounterKind::Utf8 => {
                self.encoded_bytes = self.encoded_bytes.saturating_add(value.len())
            }
            EncodingCounterKind::Ascii | EncodingCounterKind::Registered => {
                self.encoded_bytes = self.encoded_bytes.saturating_add(value.chars().count());
            }
            EncodingCounterKind::Utf16 => {
                self.encoded_bytes = self
                    .encoded_bytes
                    .saturating_add(value.encode_utf16().count().saturating_mul(2));
            }
            EncodingCounterKind::Other(encoder) => {
                self.encoded_bytes = self
                    .encoded_bytes
                    .saturating_add(count_encoded(encoder, value, false));
            }
        }
    }

    fn finish(&mut self) -> usize {
        if !self.finished {
            if let EncodingCounterKind::Other(encoder) = &mut self.kind {
                self.encoded_bytes = self
                    .encoded_bytes
                    .saturating_add(count_encoded(encoder, "", true));
            }
            self.finished = true;
        }
        self.encoded_bytes
    }
}

fn count_encoded(encoder: &mut encoding_rs::Encoder, mut source: &str, last: bool) -> usize {
    let mut total = 0usize;
    let mut buffer = [0_u8; 4096];
    loop {
        let (result, read, written, _) = encoder.encode_from_utf8(source, &mut buffer, last);
        total = total.saturating_add(written);
        source = &source[read..];
        match result {
            encoding_rs::CoderResult::InputEmpty => break,
            encoding_rs::CoderResult::OutputFull => {}
        }
    }
    total
}

#[derive(Clone)]
struct RenderContext {
    depth: usize,
    parent: Option<NodeId>,
    parent_mixed: bool,
    html_whitespace_sensitive: bool,
}

struct NamespaceRollback<'document> {
    prefix: Option<&'document str>,
    previous_uri: Option<&'document str>,
}

impl RenderContext {
    fn root() -> Self {
        Self {
            depth: 0,
            parent: None,
            parent_mixed: false,
            html_whitespace_sensitive: false,
        }
    }
}

enum RenderTask {
    Node(NodeId, RenderContext),
    CdataRange {
        parent: NodeId,
        start: usize,
        end: usize,
    },
    Children {
        parent: NodeId,
        next: usize,
        context: RenderContext,
        cdata: bool,
        skip_legacy_content_type: bool,
    },
    CloseElement {
        id: NodeId,
        depth: usize,
        mixed: bool,
        parent_mixed: bool,
        html_whitespace_sensitive: bool,
        has_element_child: bool,
        html_void: bool,
        namespace_rollback_len: usize,
    },
}

struct RenderWorkspace<'document> {
    tasks: Vec<RenderTask>,
    active_namespaces: HashMap<Option<&'document str>, &'document str>,
    namespace_rollbacks: Vec<NamespaceRollback<'document>>,
    reserved_owned_bytes: usize,
    namespace_index_bytes: usize,
}

impl<'document> RenderWorkspace<'document> {
    fn new() -> Self {
        Self {
            tasks: Vec::new(),
            active_namespaces: HashMap::new(),
            namespace_rollbacks: Vec::new(),
            reserved_owned_bytes: 0,
            namespace_index_bytes: 0,
        }
    }

    fn push(&mut self, task: RenderTask, meter: &mut Meter) -> Result<()> {
        super::budget::reserve_temporary_vec_slot(
            &mut self.tasks,
            meter,
            &mut self.reserved_owned_bytes,
        )?;
        self.tasks.push(task);
        Ok(())
    }

    fn bind_namespace(
        &mut self,
        prefix: Option<&'document str>,
        uri: &'document str,
        meter: &mut Meter,
    ) -> Result<()> {
        super::budget::reserve_temporary_vec_slot(
            &mut self.namespace_rollbacks,
            meter,
            &mut self.reserved_owned_bytes,
        )?;
        if !self.active_namespaces.contains_key(&prefix) {
            super::budget::reserve_retained_hash_map_slot(
                &mut self.active_namespaces,
                meter,
                &mut self.namespace_index_bytes,
            )?;
        }
        let previous_uri = self.active_namespaces.insert(prefix, uri);
        self.namespace_rollbacks.push(NamespaceRollback {
            prefix,
            previous_uri,
        });
        Ok(())
    }

    fn rollback_namespaces(&mut self, checkpoint: usize) {
        while self.namespace_rollbacks.len() > checkpoint {
            let rollback = self
                .namespace_rollbacks
                .pop()
                .expect("namespace rollback checkpoint is valid");
            if let Some(uri) = rollback.previous_uri {
                self.active_namespaces.insert(rollback.prefix, uri);
            } else {
                self.active_namespaces.remove(&rollback.prefix);
            }
        }
    }
}

fn serialize_node(
    document: &Document,
    id: NodeId,
    definition: &EffectiveOutputDefinition<'_>,
    encoding: &OutputEncoding,
    output: &mut RenderBuffer,
    context: RenderContext,
    meter: &mut Meter,
) -> Result<()> {
    let mut workspace = RenderWorkspace::new();
    workspace.push(RenderTask::Node(id, context), meter)?;
    let result = serialize_node_tasks(
        document,
        definition,
        encoding,
        output,
        meter,
        &mut workspace,
    );
    meter.release_owned_bytes(
        workspace
            .reserved_owned_bytes
            .saturating_add(workspace.namespace_index_bytes),
    );
    result
}

fn serialize_node_tasks<'document>(
    document: &'document Document,
    definition: &EffectiveOutputDefinition<'_>,
    encoding: &OutputEncoding,
    output: &mut RenderBuffer,
    meter: &mut Meter,
    workspace: &mut RenderWorkspace<'document>,
) -> Result<()> {
    while let Some(task) = workspace.tasks.pop() {
        output.ensure_within_limit()?;
        if let RenderTask::Children {
            parent,
            mut next,
            context,
            cdata,
            skip_legacy_content_type,
        } = task
        {
            let node = document
                .node(parent)
                .ok_or_else(|| Error::Serialization("result element disappeared".into()))?;
            while next < node.children.len()
                && skip_legacy_content_type
                && document
                    .node(node.children[next])
                    .is_some_and(is_replaceable_legacy_content_type_meta)
            {
                next += 1;
            }
            if next == node.children.len() {
                continue;
            }
            let child = node.children[next];
            if cdata
                && matches!(
                    document.node(child).map(|node| &node.kind),
                    Some(NodeKind::Text {
                        disable_output_escaping: false,
                        ..
                    })
                )
            {
                let start = next;
                next += 1;
                while let Some(child) = node.children.get(next)
                    && matches!(
                        document.node(*child).map(|node| &node.kind),
                        Some(NodeKind::Text {
                            disable_output_escaping: false,
                            ..
                        })
                    )
                {
                    next += 1;
                }
                workspace.push(
                    RenderTask::Children {
                        parent,
                        next,
                        context,
                        cdata,
                        skip_legacy_content_type,
                    },
                    meter,
                )?;
                workspace.push(
                    RenderTask::CdataRange {
                        parent,
                        start,
                        end: next,
                    },
                    meter,
                )?;
                continue;
            }
            workspace.push(
                RenderTask::Children {
                    parent,
                    next: next + 1,
                    context: context.clone(),
                    cdata,
                    skip_legacy_content_type,
                },
                meter,
            )?;
            workspace.push(RenderTask::Node(child, context), meter)?;
            continue;
        }
        if let RenderTask::CdataRange { parent, start, end } = task {
            push_cdata_range(
                document,
                parent,
                start,
                end,
                definition.xml_version,
                encoding,
                output,
            )?;
            continue;
        }
        if let RenderTask::CloseElement {
            id,
            depth,
            mixed,
            parent_mixed,
            html_whitespace_sensitive,
            has_element_child,
            html_void,
            namespace_rollback_len,
        } = task
        {
            if definition.indent
                && !mixed
                && !parent_mixed
                && !html_whitespace_sensitive
                && has_element_child
            {
                output.push('\n');
                output.push_repeated(b' ', depth.saturating_mul(2))?;
            }
            if !html_void {
                let Some(NodeKind::Element { name, prefix, .. }) =
                    document.node(id).map(|node| &node.kind)
                else {
                    return Err(Error::Serialization(
                        "result element disappeared during serialization".into(),
                    ));
                };
                output.push_str("</");
                push_name(prefix.as_deref(), &name.local, encoding, output)?;
                output.push('>');
            }
            workspace.rollback_namespaces(namespace_rollback_len);
            continue;
        }
        let RenderTask::Node(id, context) = task else {
            unreachable!("render task variants were handled above")
        };
        let node = document
            .node(id)
            .ok_or_else(|| Error::Serialization("invalid result node".into()))?;
        match &node.kind {
            NodeKind::Root => {
                workspace.push(
                    RenderTask::Children {
                        parent: id,
                        next: 0,
                        context,
                        cdata: false,
                        skip_legacy_content_type: false,
                    },
                    meter,
                )?;
            }
            NodeKind::Text {
                value,
                disable_output_escaping,
            } => {
                let parent_name = context.parent.and_then(|parent| {
                    document.node(parent).and_then(|node| match &node.kind {
                        NodeKind::Element { name, .. } => Some(name),
                        _ => None,
                    })
                });
                if definition.method == OutputMethod::Text
                    || parent_name.is_some_and(|name| {
                        definition.method == OutputMethod::Html
                            && name.namespace.is_none()
                            && ["script", "style"]
                                .iter()
                                .any(|candidate| name.local.eq_ignore_ascii_case(candidate))
                    })
                {
                    if definition.method == OutputMethod::Html {
                        reject_unrepresentable_markup(value, encoding, "HTML raw text")?;
                    }
                    output.push_str(value);
                } else if *disable_output_escaping {
                    if definition.method == OutputMethod::Xml {
                        validate_xml_characters(value, definition.xml_version)?;
                    }
                    push_xml_raw_text(value, definition.xml_version, encoding, output);
                // XSLT 1.0 section 16.1 defines cdata-section-elements only for XML output;
                // HTML has separate escaping rules in section 16.2:
                // https://www.w3.org/TR/1999/REC-xslt-19991116#output
                } else if definition.method == OutputMethod::Xml
                    && parent_name
                        .is_some_and(|name| definition.cdata_section_elements.contains(name))
                {
                    validate_xml_characters(value, definition.xml_version)?;
                    push_cdata(value, definition.xml_version, encoding, output);
                } else {
                    escape_text(
                        value,
                        definition.xml_version,
                        encoding,
                        definition.method == OutputMethod::Xml,
                        output,
                    )?;
                }
            }
            NodeKind::Comment(value) if definition.method != OutputMethod::Text => {
                reject_xml11_restricted_markup(value, definition, "comment")?;
                reject_unrepresentable_markup(value, encoding, "comment")?;
                output.push_str("<!--");
                output.push_str(value);
                output.push_str("-->");
            }
            NodeKind::ProcessingInstruction { target, value }
                if definition.method != OutputMethod::Text =>
            {
                if let Some(value) = value {
                    reject_xml11_restricted_markup(value, definition, "processing instruction")?;
                    reject_unrepresentable_markup(value, encoding, "processing instruction")?;
                }
                reject_unrepresentable_markup(target, encoding, "processing-instruction target")?;
                output.push_str("<?");
                output.push_str(target);
                if let Some(value) = value {
                    output.push(' ');
                    output.push_str(value);
                }
                output.push_str(if definition.method == OutputMethod::Html {
                    ">"
                } else {
                    "?>"
                });
            }
            NodeKind::Element { .. } if definition.method == OutputMethod::Text => {
                workspace.push(
                    RenderTask::Children {
                        parent: id,
                        next: 0,
                        context,
                        cdata: false,
                        skip_legacy_content_type: false,
                    },
                    meter,
                )?;
            }
            NodeKind::Element {
                name,
                prefix,
                attributes,
                namespaces,
            } if definition.method != OutputMethod::Text => {
                let mixed = node.children.iter().any(|child| {
                    matches!(
                        document.node(*child).map(|child| &child.kind),
                        Some(NodeKind::Text { value, .. }) if !value.is_empty()
                    )
                });
                if definition.indent
                    && context.depth > 0
                    && !context.parent_mixed
                    && !context.html_whitespace_sensitive
                {
                    output.push('\n');
                    output.push_repeated(b' ', context.depth.saturating_mul(2))?;
                }
                output.push('<');
                push_name(prefix.as_deref(), &name.local, encoding, output)?;
                let namespace_rollback_len = workspace.namespace_rollbacks.len();
                let inherited_default_namespace = workspace.active_namespaces.get(&None).copied();
                let inherits_empty_default_namespace =
                    inherited_default_namespace.is_none_or(str::is_empty);
                if name.namespace.is_none()
                    && inherited_default_namespace.is_some_and(|uri| !uri.is_empty())
                    && !namespaces
                        .iter()
                        .any(|namespace| namespace.prefix.is_none() && namespace.uri.is_empty())
                {
                    output.push_str(" xmlns=\"\"");
                    workspace.bind_namespace(None, "", meter)?;
                }
                let element_namespace_index = prefix.as_ref().and_then(|_| {
                    namespaces.iter().position(|namespace| {
                        namespace.prefix.as_deref() == prefix.as_deref()
                            && Some(namespace.uri.as_str()) == name.namespace.as_deref()
                    })
                });
                let ordered_namespaces = element_namespace_index
                    .into_iter()
                    .map(|index| (index, &namespaces[index]))
                    .chain(
                        namespaces
                            .iter()
                            .enumerate()
                            .filter_map(|(index, namespace)| {
                                (Some(index) != element_namespace_index)
                                    .then_some((index, namespace))
                            }),
                    );
                for (_namespace_index, namespace) in ordered_namespaces {
                    if namespace.prefix.as_deref() == Some("xml")
                        && namespace.uri == "http://www.w3.org/XML/1998/namespace"
                    {
                        continue;
                    }
                    if namespace.prefix.is_none()
                        && namespace.uri.is_empty()
                        && inherits_empty_default_namespace
                    {
                        continue;
                    }
                    if workspace
                        .active_namespaces
                        .get(&namespace.prefix.as_deref())
                        .copied()
                        .is_some_and(|uri| uri == namespace.uri)
                    {
                        continue;
                    }
                    output.push_str(" xmlns");
                    if let Some(prefix) = &namespace.prefix {
                        output.push(':');
                        reject_unrepresentable_markup(prefix, encoding, "namespace prefix")?;
                        output.push_str(prefix);
                    }
                    output.push_str("=\"");
                    escape_attribute(
                        &namespace.uri,
                        definition.xml_version,
                        encoding,
                        definition.method == OutputMethod::Xml,
                        output,
                    )?;
                    output.push('"');
                    workspace.bind_namespace(
                        namespace.prefix.as_deref(),
                        namespace.uri.as_str(),
                        meter,
                    )?;
                }
                for attribute in attributes {
                    output.push(' ');
                    push_name(
                        attribute.prefix.as_deref(),
                        &attribute.name.local,
                        encoding,
                        output,
                    )?;
                    if definition.method == OutputMethod::Html
                        && name.namespace.is_none()
                        && attribute.name.namespace.is_none()
                        && is_html_boolean_attribute(&name.local, &attribute.name.local)
                        && attribute.value.eq_ignore_ascii_case(&attribute.name.local)
                    {
                        continue;
                    }
                    output.push_str("=\"");
                    let html_uri_escaping = if definition.method == OutputMethod::Html
                        && name.namespace.is_none()
                        && attribute.name.namespace.is_none()
                    {
                        html_uri_escaping(&name.local, &attribute.name.local)
                    } else {
                        None
                    };
                    if let Some(escaping) = html_uri_escaping {
                        escape_html_uri_attribute(&attribute.value, escaping, encoding, output);
                    } else if definition.method == OutputMethod::Html && name.namespace.is_none() {
                        escape_html_attribute(&attribute.value, encoding, output);
                    } else {
                        // XSLT 1.0 section 16.2 recommends XML output for namespaced elements;
                        // XML escaping preserves their attribute values under the HTML method.
                        // https://www.w3.org/TR/1999/REC-xslt-19991116#section-HTML-Output-Method
                        escape_attribute(
                            &attribute.value,
                            definition.xml_version,
                            encoding,
                            definition.method == OutputMethod::Xml,
                            output,
                        )?;
                    }
                    output.push('"');
                }
                if node.children.is_empty() && definition.method == OutputMethod::Xml {
                    output.push_str(
                        if name.namespace.as_deref() == Some("http://www.w3.org/1999/xhtml")
                            && definition
                                .doctype_public
                                .as_deref()
                                .is_some_and(|public| public.contains("XHTML"))
                        {
                            " />"
                        } else {
                            "/>"
                        },
                    );
                    workspace.rollback_namespaces(namespace_rollback_len);
                    continue;
                }
                output.push('>');
                let html_head = definition.method == OutputMethod::Html
                    && name.local.eq_ignore_ascii_case("head")
                    && (is_html_output_namespace(name.namespace.as_deref())
                        || (name.namespace.as_deref() == Some("http://www.w3.org/1999/xhtml")
                            && definition
                                .doctype_public
                                .as_deref()
                                .is_some_and(|public| public.contains("XHTML"))));
                // XSLT 1.0 section 16.2 requires generated HTML content-type metadata immediately
                // after HEAD and identifies the HTML 4 META http-equiv form for that contract.
                // https://www.w3.org/TR/1999/REC-xslt-19991116#section-HTML-Output-Method
                if definition.inject_content_type && html_head {
                    if definition.indent {
                        output.push('\n');
                        output.push_repeated(
                            b' ',
                            context.depth.saturating_add(1).saturating_mul(2),
                        )?;
                    }
                    output.push_str(
                        "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=",
                    );
                    escape_attribute(
                        &definition.encoding,
                        definition.xml_version,
                        encoding,
                        definition.method == OutputMethod::Xml,
                        output,
                    )?;
                    output.push_str(if definition.method == OutputMethod::Html {
                        "\">"
                    } else {
                        "\" />"
                    });
                }
                let cdata = definition.method == OutputMethod::Xml
                    && definition.cdata_section_elements.contains(name);
                // XSLT 1.0 section 16.2 permits HTML indentation only when rendering is
                // unchanged. Whitespace is content in these HTML elements, so descendants must
                // inherit a no-indentation context.
                // https://www.w3.org/TR/1999/REC-xslt-19991116#section-HTML-Output-Method
                let html_whitespace_sensitive = context.html_whitespace_sensitive
                    || (definition.indent
                        && definition.method == OutputMethod::Html
                        && name.namespace.is_none()
                        && ["pre", "textarea", "script", "style"]
                            .iter()
                            .any(|candidate| name.local.eq_ignore_ascii_case(candidate)));
                let child_context = RenderContext {
                    depth: context.depth + 1,
                    parent: Some(id),
                    parent_mixed: context.parent_mixed || mixed,
                    html_whitespace_sensitive,
                };
                let html_void = definition.method == OutputMethod::Html
                    && name.namespace.is_none()
                    && [
                        "area", "base", "basefont", "br", "col", "frame", "hr", "img", "input",
                        "isindex", "link", "meta", "param",
                    ]
                    .iter()
                    .any(|candidate| name.local.eq_ignore_ascii_case(candidate));
                workspace.push(
                    RenderTask::CloseElement {
                        id,
                        depth: context.depth,
                        mixed,
                        parent_mixed: context.parent_mixed,
                        html_whitespace_sensitive,
                        has_element_child: node.children.iter().any(|child| {
                            matches!(
                                document.node(*child).map(|node| &node.kind),
                                Some(NodeKind::Element { .. })
                            )
                        }),
                        html_void,
                        namespace_rollback_len,
                    },
                    meter,
                )?;
                workspace.push(
                    RenderTask::Children {
                        parent: id,
                        next: 0,
                        context: child_context,
                        cdata,
                        skip_legacy_content_type: definition.inject_content_type && html_head,
                    },
                    meter,
                )?;
            }
            _ => {}
        }
    }
    Ok(())
}

fn is_html_output_namespace(namespace: Option<&str>) -> bool {
    // XSLT 1.0 section 16.2 reserves HTML output behavior for null-namespace elements.
    // https://www.w3.org/TR/1999/REC-xslt-19991116#section-HTML-Output-Method
    namespace.is_none()
}

fn push_cdata(value: &str, version: &str, encoding: &OutputEncoding, output: &mut RenderBuffer) {
    output.push_str("<![CDATA[");
    CdataWriter::new(version, encoding, output).write_and_finish(value);
    output.push_str("]]>");
}

fn push_cdata_range(
    document: &Document,
    parent: NodeId,
    start: usize,
    end: usize,
    version: &str,
    encoding: &OutputEncoding,
    output: &mut RenderBuffer,
) -> Result<()> {
    let children = &document
        .node(parent)
        .ok_or_else(|| Error::Serialization("CDATA parent disappeared".into()))?
        .children;
    let children = children
        .get(start..end)
        .ok_or_else(|| Error::Serialization("CDATA text range is stale".into()))?;
    output.push_str("<![CDATA[");
    let mut writer = CdataWriter::new(version, encoding, output);
    for child in children {
        let Some(NodeKind::Text {
            value,
            disable_output_escaping: false,
        }) = document.node(*child).map(|node| &node.kind)
        else {
            return Err(Error::Serialization(
                "CDATA text run changed during serialization".into(),
            ));
        };
        writer.write(value);
    }
    writer.finish();
    output.push_str("]]>");
    Ok(())
}

struct CdataWriter<'a> {
    version: &'a str,
    encoding: &'a OutputEncoding,
    output: &'a mut RenderBuffer,
    trailing_brackets: usize,
}

impl<'a> CdataWriter<'a> {
    fn new(version: &'a str, encoding: &'a OutputEncoding, output: &'a mut RenderBuffer) -> Self {
        Self {
            version,
            encoding,
            output,
            trailing_brackets: 0,
        }
    }

    fn write_and_finish(mut self, value: &str) {
        self.write(value);
        self.finish();
    }

    fn write(&mut self, value: &str) {
        let mut start = 0usize;
        for (offset, character) in value.char_indices() {
            let reference = if character == '\r' {
                // XML 1.0 section 2.11 normalizes literal CR even inside CDATA; markup is
                // required to preserve the result-tree character across reparsing.
                // https://www.w3.org/TR/xml/#sec-line-ends
                Some(false)
            } else if self.version == "1.1" && xml11_requires_reference(character) {
                Some(true)
            } else if !self.encoding.represents(character) {
                Some(false)
            } else {
                None
            };
            let Some(hexadecimal) = reference else {
                continue;
            };
            self.push_segment(&value[start..offset]);
            self.flush_trailing_brackets();
            self.output.push_str("]]>");
            if hexadecimal {
                push_hex_reference(self.output, character);
            } else {
                push_decimal_reference(self.output, character);
            }
            self.output.push_str("<![CDATA[");
            start = offset + character.len_utf8();
        }
        self.push_segment(&value[start..]);
    }

    fn finish(mut self) {
        self.flush_trailing_brackets();
    }

    fn push_segment(&mut self, value: &str) {
        let trailing_brackets = value
            .as_bytes()
            .iter()
            .rev()
            .take(2)
            .take_while(|byte| **byte == b']')
            .count();
        let body_end = value.len() - trailing_brackets;
        let body = &value[..body_end];
        if body.is_empty() {
            let total = self.trailing_brackets + trailing_brackets;
            self.push_brackets(total.saturating_sub(2));
            self.trailing_brackets = total.min(2);
            return;
        }

        let leading_brackets = body
            .as_bytes()
            .iter()
            .take_while(|byte| **byte == b']')
            .count();
        if body.as_bytes().get(leading_brackets) == Some(&b'>')
            && self.trailing_brackets + leading_brackets >= 2
        {
            let excess = self.trailing_brackets + leading_brackets - 2;
            let pending_excess = excess.min(self.trailing_brackets);
            self.push_brackets(pending_excess);
            let body_excess = excess - pending_excess;
            self.output.push_str(&body[..body_excess]);
            self.output.push_str("]]]]><![CDATA[>");
            push_cdata_segment(&body[leading_brackets + 1..], self.output);
        } else {
            self.flush_trailing_brackets();
            push_cdata_segment(body, self.output);
        }
        self.trailing_brackets = trailing_brackets;
    }

    fn flush_trailing_brackets(&mut self) {
        self.push_brackets(self.trailing_brackets);
        self.trailing_brackets = 0;
    }

    fn push_brackets(&mut self, count: usize) {
        for _ in 0..count {
            self.output.push(']');
        }
    }
}

fn push_cdata_segment(value: &str, output: &mut RenderBuffer) {
    // Preserve the two closing brackets as character data before opening a
    // new section; `]]><![CDATA[>` would silently delete them.
    let mut fragments = value.split("]]>");
    if let Some(first) = fragments.next() {
        output.push_str(first);
    }
    for fragment in fragments {
        output.push_str("]]]]><![CDATA[>");
        output.push_str(fragment);
    }
}

fn push_xml_raw_text(
    value: &str,
    version: &str,
    encoding: &OutputEncoding,
    output: &mut RenderBuffer,
) {
    for character in value.chars() {
        if version == "1.1" && xml11_requires_reference(character) {
            push_hex_reference(output, character);
        } else if !encoding.represents(character) {
            push_decimal_reference(output, character);
        } else {
            output.push(character);
        }
    }
}

fn push_hex_reference(output: &mut RenderBuffer, character: char) {
    write!(output, "&#x{:X};", u32::from(character))
        .expect("writing character reference to render buffer cannot fail");
}

fn push_decimal_reference(output: &mut RenderBuffer, character: char) {
    write!(output, "&#{};", u32::from(character))
        .expect("writing character reference to render buffer cannot fail");
}

fn reject_xml11_restricted_markup(
    value: &str,
    definition: &EffectiveOutputDefinition<'_>,
    kind: &str,
) -> Result<()> {
    if definition.method == OutputMethod::Xml
        && definition.xml_version == "1.1"
        && value.chars().any(is_xml11_restricted)
    {
        return Err(Error::Serialization(format!(
            "XML 1.1 {kind} cannot contain restricted control characters"
        )));
    }
    Ok(())
}

#[derive(Clone, Copy)]
enum HtmlUriEscaping {
    NonAsciiAndSpaces,
    NonAscii,
}

fn html_uri_escaping(element: &str, attribute: &str) -> Option<HtmlUriEscaping> {
    // HTML 4.01 section 12.2 defines A/href as a URI but A/name as an anchor identifier.
    // https://www.w3.org/TR/html401/struct/links.html#h-12.2
    let libxslt_pair = (attribute.eq_ignore_ascii_case("action")
        && element.eq_ignore_ascii_case("form"))
        || (attribute.eq_ignore_ascii_case("cite")
            && ascii_eq_any(element, &["blockquote", "q", "del", "ins"]))
        || (attribute.eq_ignore_ascii_case("href")
            && ascii_eq_any(element, &["a", "area", "link", "base"]))
        || (attribute.eq_ignore_ascii_case("longdesc")
            && ascii_eq_any(element, &["img", "frame", "iframe"]))
        || (attribute.eq_ignore_ascii_case("src")
            && ascii_eq_any(element, &["img", "input", "frame", "iframe", "script"]))
        || (attribute.eq_ignore_ascii_case("usemap")
            && ascii_eq_any(element, &["img", "input", "object"]));
    if libxslt_pair {
        return Some(HtmlUriEscaping::NonAsciiAndSpaces);
    }
    ((attribute.eq_ignore_ascii_case("background") && element.eq_ignore_ascii_case("body"))
        || (attribute.eq_ignore_ascii_case("profile") && element.eq_ignore_ascii_case("head"))
        || (ascii_eq_any(attribute, &["classid", "data"])
            && element.eq_ignore_ascii_case("object"))
        // HTML 4.01 section 13.4 defines APPLET codebase as a URI and archive as a URI list.
        // XSLT 1.0 section 16.2 applies the same recommended non-ASCII escaping as OBJECT.
        // https://www.w3.org/TR/html401/struct/objects.html#h-13.4
        || (ascii_eq_any(attribute, &["archive", "codebase"])
            && ascii_eq_any(element, &["applet", "object"])))
    .then_some(HtmlUriEscaping::NonAscii)
}

fn escape_html_uri_attribute(
    value: &str,
    escaping: HtmlUriEscaping,
    encoding: &OutputEncoding,
    output: &mut RenderBuffer,
) {
    // XSLT 1.0 section 16.2 requires non-ASCII URI bytes to be escaped without changing the
    // result-tree value. libxslt also escapes ASCII spaces for its historical URI table, but not
    // for all HTML URI pairs; leading whitespace is therefore processed rather than trimmed.
    // https://www.w3.org/TR/1999/REC-xslt-19991116#section-HTML-Output-Method
    let escape_spaces = matches!(escaping, HtmlUriEscaping::NonAsciiAndSpaces);
    let mut plain_start = 0;
    for (index, character) in value.char_indices() {
        if !character.is_ascii() || (escape_spaces && character == ' ') {
            escape_html_attribute(&value[plain_start..index], encoding, output);
            let mut utf8 = [0_u8; 4];
            for byte in character.encode_utf8(&mut utf8).bytes() {
                const HEX: &[u8; 16] = b"0123456789ABCDEF";
                output.push('%');
                output.push(char::from(HEX[usize::from(byte >> 4)]));
                output.push(char::from(HEX[usize::from(byte & 0x0f)]));
            }
            plain_start = index + character.len_utf8();
        }
    }
    escape_html_attribute(&value[plain_start..], encoding, output);
}

fn is_replaceable_legacy_content_type_meta(node: &super::Node) -> bool {
    let NodeKind::Element {
        name, attributes, ..
    } = &node.kind
    else {
        return false;
    };
    name.namespace.is_none()
        && name.local.eq_ignore_ascii_case("meta")
        && attributes.iter().any(|attribute| {
            attribute.name.namespace.is_none()
                && attribute.name.local.eq_ignore_ascii_case("http-equiv")
                && attribute.value.eq_ignore_ascii_case("content-type")
        })
}

fn push_name(
    prefix: Option<&str>,
    local: &str,
    encoding: &OutputEncoding,
    output: &mut RenderBuffer,
) -> Result<()> {
    if let Some(prefix) = prefix {
        reject_unrepresentable_markup(prefix, encoding, "XML name")?;
        output.push_str(prefix);
        output.push(':');
    }
    reject_unrepresentable_markup(local, encoding, "XML name")?;
    output.push_str(local);
    Ok(())
}

fn escape_text(
    value: &str,
    version: &str,
    encoding: &OutputEncoding,
    validate_xml: bool,
    output: &mut RenderBuffer,
) -> Result<()> {
    for character in value.chars() {
        if validate_xml {
            validate_xml_character(character, version)?;
        }
        if version == "1.1" && xml11_requires_reference(character) {
            push_hex_reference(output, character);
            continue;
        } else if !encoding.represents(character) {
            push_decimal_reference(output, character);
            continue;
        }
        match character {
            '&' => output.push_str("&amp;"),
            '<' => output.push_str("&lt;"),
            '>' => output.push_str("&gt;"),
            '\r' => output.push_str("&#13;"),
            _ => output.push(character),
        }
    }
    Ok(())
}

fn escape_attribute(
    value: &str,
    version: &str,
    encoding: &OutputEncoding,
    validate_xml: bool,
    output: &mut RenderBuffer,
) -> Result<()> {
    for character in value.chars() {
        if validate_xml {
            validate_xml_character(character, version)?;
        }
        if version == "1.1" && xml11_requires_reference(character) {
            push_hex_reference(output, character);
            continue;
        } else if !encoding.represents(character) {
            push_decimal_reference(output, character);
            continue;
        }
        match character {
            '&' => output.push_str("&amp;"),
            '<' => output.push_str("&lt;"),
            '"' => output.push_str("&quot;"),
            '\r' => output.push_str("&#13;"),
            '\n' => output.push_str("&#10;"),
            '\t' => output.push_str("&#9;"),
            _ => output.push(character),
        }
    }
    Ok(())
}

fn is_xml11_restricted(character: char) -> bool {
    matches!(
        u32::from(character),
        0x1..=0x8 | 0xB..=0xC | 0xE..=0x1F | 0x7F..=0x84 | 0x86..=0x9F
    )
}

fn xml11_requires_reference(character: char) -> bool {
    // XML 1.1 sections 2.2 and 2.11: restricted characters require references; literal NEL/LS
    // undergo end-of-line normalization, including inside CDATA, and cannot preserve the value.
    // https://www.w3.org/TR/xml11/#charsets
    // https://www.w3.org/TR/xml11/#sec-line-ends
    is_xml11_restricted(character) || matches!(character, '\u{85}' | '\u{2028}')
}

fn is_html_boolean_attribute(element: &str, attribute: &str) -> bool {
    (attribute.eq_ignore_ascii_case("nohref") && element.eq_ignore_ascii_case("area"))
        || (attribute.eq_ignore_ascii_case("compact")
            && ascii_eq_any(element, &["dir", "menu", "ol", "ul", "dl"]))
        || (attribute.eq_ignore_ascii_case("noresize") && element.eq_ignore_ascii_case("frame"))
        || (attribute.eq_ignore_ascii_case("noshade") && element.eq_ignore_ascii_case("hr"))
        || (attribute.eq_ignore_ascii_case("ismap") && ascii_eq_any(element, &["img", "input"]))
        || (attribute.eq_ignore_ascii_case("checked") && element.eq_ignore_ascii_case("input"))
        || (attribute.eq_ignore_ascii_case("declare") && element.eq_ignore_ascii_case("object"))
        || (attribute.eq_ignore_ascii_case("selected") && element.eq_ignore_ascii_case("option"))
        || (attribute.eq_ignore_ascii_case("defer") && element.eq_ignore_ascii_case("script"))
        || (attribute.eq_ignore_ascii_case("multiple") && element.eq_ignore_ascii_case("select"))
        || (attribute.eq_ignore_ascii_case("nowrap") && ascii_eq_any(element, &["td", "th"]))
        || (attribute.eq_ignore_ascii_case("readonly")
            && ascii_eq_any(element, &["input", "textarea"]))
        || (attribute.eq_ignore_ascii_case("disabled")
            && ascii_eq_any(
                element,
                &[
                    "button", "input", "optgroup", "option", "select", "textarea",
                ],
            ))
}

fn ascii_eq_any(value: &str, candidates: &[&str]) -> bool {
    candidates
        .iter()
        .any(|candidate| value.eq_ignore_ascii_case(candidate))
}

fn escape_html_attribute(value: &str, encoding: &OutputEncoding, output: &mut RenderBuffer) {
    for character in value.chars() {
        if !encoding.represents(character) {
            push_decimal_reference(output, character);
            continue;
        }
        match character {
            '&' => output.push_str("&amp;"),
            '"' => output.push_str("&quot;"),
            _ => output.push(character),
        }
    }
}

fn reject_unrepresentable_markup(value: &str, encoding: &OutputEncoding, kind: &str) -> Result<()> {
    if let Some(character) = value
        .chars()
        .find(|character| !encoding.represents(*character))
    {
        return Err(Error::Serialization(format!(
            "{kind} character `{character}` is not representable in the output encoding"
        )));
    }
    Ok(())
}

fn encode(
    value: String,
    utf8_bytes: usize,
    encoded_bytes: usize,
    encoding: &OutputEncoding,
    meter: &mut Meter,
    budget_kind: BudgetKind,
) -> Result<Vec<u8>> {
    meter.charge(budget_kind, encoded_bytes)?;
    if matches!(encoding, OutputEncoding::Utf8 | OutputEncoding::Ascii) {
        if matches!(encoding, OutputEncoding::Ascii) && !value.is_ascii() {
            return Err(Error::Serialization(
                "non-ASCII character reached the US-ASCII encoder without escaping".into(),
            ));
        }
        return Ok(value.into_bytes());
    }
    meter.charge(BudgetKind::OwnedBytes, encoded_bytes)?;
    if let OutputEncoding::Registered(encoding) = encoding {
        let mut bytes = Vec::with_capacity(encoded_bytes);
        for character in value.chars() {
            let byte = encoding.encode_char(character).ok_or_else(|| {
                Error::Serialization(format!(
                    "character `{character}` reached the {} encoder without escaping",
                    encoding.name()
                ))
            })?;
            bytes.push(byte);
        }
        meter.release_owned_bytes(utf8_bytes);
        return Ok(bytes);
    }
    if matches!(encoding, OutputEncoding::Utf16 | OutputEncoding::Utf16Le) {
        let mut bytes = Vec::with_capacity(encoded_bytes);
        if matches!(encoding, OutputEncoding::Utf16) {
            // RFC 2781 section 3.3 requires the generic UTF-16 label to carry byte-order
            // information, while explicit UTF-16LE/BE labels must not prepend a BOM.
            // https://www.rfc-editor.org/rfc/rfc2781.html#section-3.3
            bytes.extend_from_slice(&[0xFF, 0xFE]);
        }
        for unit in value.encode_utf16() {
            bytes.extend_from_slice(&unit.to_le_bytes());
        }
        meter.release_owned_bytes(utf8_bytes);
        return Ok(bytes);
    }
    if matches!(encoding, OutputEncoding::Utf16Be) {
        let mut bytes = Vec::with_capacity(encoded_bytes);
        for unit in value.encode_utf16() {
            bytes.extend_from_slice(&unit.to_be_bytes());
        }
        meter.release_owned_bytes(utf8_bytes);
        return Ok(bytes);
    }
    let OutputEncoding::Other { encoding, .. } = encoding else {
        unreachable!("all built-in output encodings returned above")
    };
    let mut encoder = encoding.new_encoder();
    let mut source = value.as_str();
    let mut bytes = Vec::with_capacity(encoded_bytes);
    let mut buffer = [0_u8; 4096];
    loop {
        let (result, read, written, _) = encoder.encode_from_utf8(source, &mut buffer, true);
        bytes.extend_from_slice(&buffer[..written]);
        source = &source[read..];
        match result {
            encoding_rs::CoderResult::InputEmpty => break,
            encoding_rs::CoderResult::OutputFull => {}
        }
    }
    meter.release_owned_bytes(utf8_bytes);
    Ok(bytes)
}

fn validate_text_encoding(value: &str, encoding: &OutputEncoding, label: &str) -> Result<()> {
    if let Some(character) = value
        .chars()
        .find(|character| !encoding.represents(*character))
    {
        return Err(Error::Serialization(format!(
            "text output character `{character}` is not representable in {label}"
        )));
    }
    Ok(())
}

fn infer_html_output(document: &Document) -> bool {
    // XSLT 1.0 section 16 also requires no preceding non-whitespace text children.
    // https://www.w3.org/TR/1999/REC-xslt-19991116#output
    let Some(root) = document.node(document.root()) else {
        return false;
    };
    for child in &root.children {
        match document.node(*child).map(|node| &node.kind) {
            Some(NodeKind::Text { value, .. })
                if !value.chars().all(super::lexical::is_xml_whitespace) =>
            {
                return false;
            }
            Some(NodeKind::Element { name, .. }) => {
                return name.namespace.is_none() && name.local.eq_ignore_ascii_case("html");
            }
            _ => {}
        }
    }
    false
}

fn validate_document_output_shape(document: &Document) -> Result<()> {
    // XSLT 1.0 section 16.1, erratum E4 requires a document rather than a parsed entity when
    // standalone or DOCTYPE is emitted. Ordinary XML fragment output remains permitted.
    // https://www.w3.org/1999/11/REC-xslt-19991116-errata/#E4
    let root = document
        .node(document.root())
        .ok_or_else(|| Error::Serialization("missing result root".into()))?;
    let mut has_element = false;
    for child in &root.children {
        match document.node(*child).map(|node| &node.kind) {
            Some(NodeKind::Element { .. }) if !has_element => has_element = true,
            Some(NodeKind::Comment(_) | NodeKind::ProcessingInstruction { .. }) => {},
            Some(NodeKind::Text { value, .. }) if value.chars().all(super::lexical::is_xml_whitespace) => {},
            _ => return Err(Error::Serialization("standalone/DOCTYPE output requires one document element and no top-level character data".into())),
        }
    }
    if !has_element {
        return Err(Error::Serialization(
            "standalone/DOCTYPE output requires a document element".into(),
        ));
    }
    Ok(())
}

fn validate_xml_characters(value: &str, version: &str) -> Result<()> {
    for character in value.chars() {
        validate_xml_character(character, version)?;
    }
    Ok(())
}

fn validate_xml_character(character: char, version: &str) -> Result<()> {
    let code = u32::from(character);
    let valid = if version == "1.1" {
        matches!(code, 0x1..=0xD7FF | 0xE000..=0xFFFD | 0x10000..=0x10FFFF)
    } else {
        super::lexical::is_xml10_character(character)
    };
    if !valid {
        // XML 1.0 section 4.1 requires a character reference to denote a Char too. Validate
        // before an output encoding can turn the forbidden scalar into otherwise valid markup.
        // https://www.w3.org/TR/2008/REC-xml-20081126/#wf-Legalchar
        return Err(Error::Serialization(format!(
            "character U+{code:04X} is forbidden by XML {version}"
        )));
    }
    Ok(())
}

#[cfg(all(test, not(feature = "embedded")))]
mod tests;