deser-xml 0.10.0

XML support for deser
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
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
use std::borrow::Cow;
use std::fmt::Write as _;

use deser_core::ext::Number;
use deser_core::hints::Layout;
use deser_core::ser::SerializeRef;
use deser_core::ser::{self, Describe, EventSink, SerializeDriver};
use deser_core::{Atom, BytesFormat, Error, ErrorKind, Event, Serialize, State};

use crate::Names;
use crate::de::XML_NAMESPACE;
use crate::mixed::KeepsWhitespace;
use crate::root::{Declarations, RootData};

/// How the output is indented.
///
/// See [`SerializerConfig::set_indent`].
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
#[non_exhaustive]
pub enum Indent {
    /// No indentation, the document is written on a single line.
    #[default]
    None,
    /// Child elements on lines of their own, indented by the given number
    /// of spaces per level.
    Spaces(usize),
    /// Child elements on lines of their own, indented by a tab per level.
    Tab,
}

/// Configures how values are serialized to XML.
///
/// The value becomes the root element.  Its name is the one of the
/// [`Root`](crate::Root) of the value (or of the document the value was
/// read from, if it's a value that keeps event data like a
/// [`Recording`](deser_core::de::Recording)), the name of the struct (or
/// enum) that is serialized or the configured [`set_root`](Self::set_root).  Maps
/// are elements: keys with the
/// [attribute prefix](Self::set_attribute_prefix) are attributes, the
/// [text key](Self::set_text_key) is text and all other keys are child
/// elements.  Sequences are elements with the same name, one per value.
/// Null values are left out.  Attributes can come after other keys, they
/// are still written into the start tag.
///
/// Names can be `{uri}local` (the notation of James Clark, attributes are
/// `@{uri}local`, see [`qname!`](crate::qname)): their namespace gets the
/// [configured prefix](Self::namespaces) or a generated one (`ns0`, ...).
/// Every namespace has one prefix in the document, all of them are
/// declared on the root element.  Other names are written as they are.
///
/// ```
/// #[derive(deser::Serialize)]
/// struct Link {
///     #[deser(rename = "@href")]
///     href: String,
///     #[deser(rename = "$text")]
///     title: String,
/// }
///
/// #[derive(deser::Serialize)]
/// #[deser(rename = "feed")]
/// struct Feed {
///     link: Vec<Link>,
///     updated: Option<String>,
/// }
///
/// let feed = Feed {
///     link: vec![Link { href: "/a".into(), title: "A & B".into() }],
///     updated: None,
/// };
/// assert_eq!(
///     deser_xml::to_string(&feed).unwrap(),
///     r#"<feed><link href="/a">A &amp; B</link></feed>"#
/// );
/// ```
///
/// By default the output is a single line, [`set_indent`](Self::set_indent) writes
/// child elements on lines of their own.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SerializerConfig {
    names: Names,
    root: Option<&'static str>,
    declaration: bool,
    indent: Indent,
    context: deser_core::Context,
}

impl Default for SerializerConfig {
    fn default() -> SerializerConfig {
        SerializerConfig::new()
    }
}

impl SerializerConfig {
    /// Creates the default configuration.
    pub const fn new() -> SerializerConfig {
        SerializerConfig {
            names: Names::new(),
            root: None,
            declaration: false,
            indent: Indent::None,
            context: deser_core::Context::new(),
        }
    }

    /// Returns a builder for the configuration (see [`SerializerConfigBuilder`]).
    pub const fn builder() -> SerializerConfigBuilder {
        SerializerConfigBuilder::new()
    }

    /// Returns a builder that starts with this configuration.
    pub const fn into_builder(self) -> SerializerConfigBuilder {
        SerializerConfigBuilder { value: self }
    }

    /// Sets the context the values are serialized in.
    ///
    /// The values of the context are the defaults of the extension values
    /// of the state (see [`Context`](deser_core::Context)), for instance
    /// the [`BytesFormat`](deser_core::BytesFormat).  The serializers and
    /// writers created with the configuration use this context.  A context set on
    /// the driver takes precedence.
    pub fn set_context(&mut self, context: deser_core::Context) {
        self.context = context;
    }

    /// Returns the context the values are serialized in.
    pub fn context(&self) -> &deser_core::Context {
        &self.context
    }

    /// Gives the context to a driver which has none.
    #[inline]
    fn apply_context(&self, driver: &mut SerializeDriver<'_>) {
        if !self.context.is_empty() {
            driver.set_default_context(self.context.clone());
        }
    }

    /// Sets the name of the root element of values without a name.
    ///
    /// The root element is named after the [`Root`](crate::Root) of the
    /// value or the struct or enum that is serialized.  Other values (like
    /// maps) are named with this.  This is useful where values cannot be
    /// wrapped in a `Root`, for instance when transcoding from another
    /// format.
    pub const fn set_root(&mut self, name: &'static str) {
        self.root = Some(name);
    }

    /// Sets the prefix of the keys that are attributes (default `@`).
    pub const fn set_attribute_prefix(&mut self, prefix: &'static str) {
        self.names.attribute_prefix = prefix;
    }

    /// Sets the key that is the text of an element (default `$text`).
    pub const fn set_text_key(&mut self, key: &'static str) {
        self.names.text_key = key;
    }

    /// Sets the prefixes of namespaces that are declared on the root
    /// element.
    ///
    /// The namespaces of the [`Root`](crate::Root) of the value come first,
    /// configured namespaces whose prefix they use are left out.  The empty
    /// prefix declares the default namespace.  Names that are
    /// `{uri}local` are written with these prefixes, attributes only with
    /// prefixes that are not empty.  Namespaces without prefix get
    /// generated ones.  The table can be written with
    /// [`prefixes!`](crate::prefixes).
    ///
    /// ```
    /// use deser_xml::SerializerConfig;
    ///
    /// deser_xml::namespace!(
    ///     atom = "http://www.w3.org/2005/Atom",
    ///     dc = "http://purl.org/dc/elements/1.1/",
    ///     media = "http://search.yahoo.com/mrss/",
    /// );
    ///
    /// #[derive(deser::Serialize)]
    /// #[deser(rename = atom!("feed"))]
    /// struct Feed {
    ///     #[deser(rename = atom!("title"))]
    ///     title: String,
    ///     #[deser(rename = dc!("creator"))]
    ///     creator: Vec<String>,
    ///     #[deser(rename = media!("thumbnail"))]
    ///     thumbnail: String,
    /// }
    ///
    /// const CONFIG: SerializerConfig = SerializerConfig::new()
    ///     .namespaces(deser_xml::prefixes![atom as "", dc]);
    /// let feed = Feed {
    ///     title: "x".into(),
    ///     creator: vec!["y".into(), "z".into()],
    ///     thumbnail: "t.png".into(),
    /// };
    /// assert_eq!(
    ///     CONFIG.to_string(&feed).unwrap(),
    ///     "<feed xmlns=\"http://www.w3.org/2005/Atom\" \
    ///      xmlns:dc=\"http://purl.org/dc/elements/1.1/\" \
    ///      xmlns:ns0=\"http://search.yahoo.com/mrss/\"><title>x</title>\
    ///      <dc:creator>y</dc:creator><dc:creator>z</dc:creator>\
    ///      <ns0:thumbnail>t.png</ns0:thumbnail></feed>"
    /// );
    /// ```
    pub const fn namespaces(
        mut self,
        namespaces: &'static [(&'static str, &'static str)],
    ) -> SerializerConfig {
        self.names.namespaces = namespaces;
        self
    }

    /// Sets if the XML declaration is written (default `false`).
    pub const fn set_declaration(&mut self, yes: bool) {
        self.declaration = yes;
    }

    /// Sets how the output is indented.
    ///
    /// By default ([`Indent::None`]) the document is written on a single
    /// line.  Otherwise the child elements of an element are written on
    /// lines of their own, indented by their depth, and the end tag on a
    /// line of its own:
    ///
    /// ```
    /// use deser_xml::{Indent, SerializerConfig};
    ///
    /// #[derive(deser::Serialize)]
    /// #[deser(rename = "point")]
    /// struct Point {
    ///     #[deser(rename = "@id")]
    ///     id: u32,
    ///     x: i32,
    ///     y: i32,
    /// }
    ///
    /// const PRETTY: SerializerConfig =
    ///     SerializerConfig::builder().indent(Indent::Spaces(2)).build();
    /// assert_eq!(
    ///     PRETTY.to_string(&Point { id: 1, x: 3, y: 4 }).unwrap(),
    ///     "<point id=\"1\">\n  <x>3</x>\n  <y>4</y>\n</point>"
    /// );
    /// ```
    ///
    /// Unlike in JSON whitespace can be text in XML.  It is only added
    /// between tags where it's not text of the elements (the deserializer
    /// skips it), elements with text are written on a single line:
    ///
    /// * The text of elements is never changed, elements with text and
    ///   child elements (mixed content like `<p>x <b>y</b></p>`) are
    ///   written on a single line from the text on.  If the element is a
    ///   struct whose [text key](Self::set_text_key) field comes after the
    ///   child element, the element is written on a single line from the
    ///   start (unless it has [`Layout::Expanded`]).
    /// * [`Mixed`](crate::Mixed) keeps whitespace as text by default, its
    ///   content is written on a single line.
    /// * Elements and sequences with [`Layout::Compact`] (see
    ///   [`hints`](deser_core::hints)) are written on a single line, also
    ///   their content.
    ///
    /// With the [declaration](Self::set_declaration) the root element starts on
    /// a new line.  The output never ends with a line break.
    pub const fn set_indent(&mut self, indent: Indent) {
        self.indent = indent;
    }

    /// Enables or disables pretty printing.
    ///
    /// This is the same as [`set_indent`](Self::set_indent), XML has no
    /// spaces after separators like JSON.
    ///
    /// ```
    /// use std::collections::BTreeMap;
    /// use deser_xml::{Indent, SerializerConfig};
    ///
    /// let value = BTreeMap::from([("a", 1), ("b", 2)]);
    /// const PRETTY: SerializerConfig =
    ///     SerializerConfig::builder().root("r").pretty(Indent::Tab).build();
    /// assert_eq!(
    ///     PRETTY.to_string(&value).unwrap(),
    ///     "<r>\n\t<a>1</a>\n\t<b>2</b>\n</r>"
    /// );
    /// ```
    pub const fn set_pretty(&mut self, indent: Indent) {
        self.set_indent(indent);
    }

    /// Serializes a value.
    pub fn to_string<T: Serialize + ?Sized>(&self, value: &T) -> Result<String, Error> {
        self.to_string_ref(SerializeRef::new(&value))
    }

    /// Serializes a value with a configured driver.
    ///
    /// The callback is invoked with the driver before the serialization
    /// starts, for instance to add [`Layer`](deser_core::ser::Layer)s.
    pub fn to_string_with<F, T: Serialize + ?Sized>(
        &self,
        value: &T,
        setup: F,
    ) -> Result<String, Error>
    where
        F: FnOnce(&mut SerializeDriver<'_>),
    {
        let mut driver = SerializeDriver::new(&value);
        setup(&mut driver);
        self.apply_context(&mut driver);
        self.serialize_driver(&mut driver)
    }

    /// Serializes a value whose type is erased (see
    /// [`to_string`](Self::to_string)).
    ///
    /// This is not generic: the code that exists for every type only
    /// erases it.
    fn to_string_ref(&self, value: SerializeRef<'_>) -> Result<String, Error> {
        let mut driver = SerializeDriver::from_ref(value);
        self.apply_context(&mut driver);
        self.serialize_driver(&mut driver)
    }

    /// Serializes the value of a driver into a document.
    fn serialize_driver(&self, driver: &mut SerializeDriver<'_>) -> Result<String, Error> {
        let mut writer = Writer::new(self, BytesFormat::of(driver.state()));
        driver.drive_sink(&mut writer)?;
        writer.finish()?;
        Ok(writer.out)
    }

    /// Serializes (a part of) the value of a driver and appends the output
    /// that is final.
    ///
    /// The progress of the value is kept in `value` (see
    /// `StreamSerializer::drive_partial`), `true` is returned once the
    /// value is complete.  The output of a value is final once its start
    /// tag is complete, which is the case once no more attributes can come
    /// for the element (see `final_until`).  Output is only appended if
    /// this succeeds.
    pub(crate) fn serialize_part(
        &self,
        value: &mut Option<Box<Writer>>,
        driver: &mut SerializeDriver<'_>,
        out: &mut String,
        limit: usize,
    ) -> Result<bool, Error> {
        // a document that is written at once does not box the writer
        if value.is_none() && limit == usize::MAX {
            let document = self.serialize_driver(driver)?;
            if out.is_empty() {
                *out = document;
            } else {
                out.push_str(&document);
            }
            return Ok(true);
        }
        let mut writer = value
            .take()
            .unwrap_or_else(|| Box::new(Writer::new(self, BytesFormat::of(driver.state()))));
        // after an error the value is abandoned, its writer is dropped
        let done = if limit == usize::MAX {
            driver.drive_sink(&mut *writer)?;
            true
        } else {
            writer.limit = limit;
            driver.drive_until(&mut *writer)?
        };
        if let Some(err) = writer.error.take() {
            return Err(err);
        }
        if done {
            writer.finish()?;
            out.push_str(&writer.out);
            return Ok(true);
        }
        writer.pass_on(out);
        *value = Some(writer);
        Ok(false)
    }
}

/// Builds a [`SerializerConfig`].
///
/// The methods have the names of the setters of [`SerializerConfig`] (without `set_`).
#[derive(Debug, Clone)]
#[must_use]
pub struct SerializerConfigBuilder {
    value: SerializerConfig,
}

impl SerializerConfigBuilder {
    /// Creates a builder that starts with the default.
    pub const fn new() -> SerializerConfigBuilder {
        SerializerConfigBuilder {
            value: SerializerConfig::new(),
        }
    }

    /// Sets the name of the root element of values without a name.
    ///
    /// See [`SerializerConfig::set_root`].
    pub const fn root(mut self, name: &'static str) -> SerializerConfigBuilder {
        self.value.set_root(name);
        self
    }

    /// Sets the prefix of the keys that are attributes (default `@`).
    ///
    /// See [`SerializerConfig::set_attribute_prefix`].
    pub const fn attribute_prefix(mut self, prefix: &'static str) -> SerializerConfigBuilder {
        self.value.set_attribute_prefix(prefix);
        self
    }

    /// Sets the key that is the text of an element (default `$text`).
    ///
    /// See [`SerializerConfig::set_text_key`].
    pub const fn text_key(mut self, key: &'static str) -> SerializerConfigBuilder {
        self.value.set_text_key(key);
        self
    }

    /// Sets if the XML declaration is written (default `false`).
    ///
    /// See [`SerializerConfig::set_declaration`].
    pub const fn declaration(mut self, yes: bool) -> SerializerConfigBuilder {
        self.value.set_declaration(yes);
        self
    }

    /// Sets how the output is indented.
    ///
    /// See [`SerializerConfig::set_indent`].
    pub const fn indent(mut self, indent: Indent) -> SerializerConfigBuilder {
        self.value.set_indent(indent);
        self
    }

    /// Enables or disables pretty printing.
    ///
    /// See [`SerializerConfig::set_pretty`].
    pub const fn pretty(mut self, indent: Indent) -> SerializerConfigBuilder {
        self.value.set_pretty(indent);
        self
    }

    /// Sets the context the values are serialized in.
    ///
    /// See [`SerializerConfig::set_context`].
    pub fn context(mut self, context: deser_core::Context) -> SerializerConfigBuilder {
        self.value.set_context(context);
        self
    }

    /// Returns the built [`SerializerConfig`].
    pub const fn build(self) -> SerializerConfig {
        // the value cannot be moved out of the builder in a const fn as the
        // builder needs dropping (the context has a destructor)
        // SAFETY: the value is read once and the builder is forgotten
        let value = unsafe { core::ptr::read(&self.value) };
        core::mem::forget(self);
        value
    }
}

impl Default for SerializerConfigBuilder {
    fn default() -> SerializerConfigBuilder {
        SerializerConfigBuilder::new()
    }
}

/// Serializes values to XML.
///
/// This is the XML implementation of the [`Serializer`](ser::Serializer)
/// trait, which allows serializing to XML where the format is not known
/// upfront.  For a value that is serialized once
/// [`SerializerConfig::to_string`] (or [`to_string`]) is simpler.
///
/// An XML document has a single root element, serializing a second value
/// fails.  Values without a name (like maps) need a [`Root`](crate::Root)
/// or the name of the root element in the configuration (see
/// [`SerializerConfig::set_root`]).
///
/// ```
/// use std::collections::BTreeMap;
/// use deser_xml::{Serializer, SerializerConfig};
///
/// let mut serializer = Serializer::with_config(SerializerConfig::builder().root("r").build());
/// serializer.serialize(&BTreeMap::from([("@a", 1), ("b", 2)])).unwrap();
/// assert!(serializer.serialize(&BTreeMap::from([("b", 3)])).is_err());
/// assert_eq!(serializer.finish(), r#"<r a="1"><b>2</b></r>"#);
/// ```
///
/// The serializer is also the stream serializer of XML (see
/// [`StreamSerializer`](ser::StreamSerializer)): the output can be taken
/// while the document is written, and large documents can be written in
/// parts.  Output is final once the start tag it's in is complete: the
/// start tag of an element is held back until no more attributes can come,
/// which for maps (whose keys are not known upfront) is the end of the
/// element.  The namespaces that are found once the start tag of the root
/// element was written are declared on the elements that use them rather
/// than on the root element (configured
/// [namespaces](SerializerConfig::namespaces) are always declared on the
/// root element).  To write to a [`Write`](std::io::Write) use
/// [`SerializerConfig::writer`].
pub struct Serializer {
    config: SerializerConfig,
    out: String,
    written: bool,
    // the document that is written in parts
    document: Option<Box<Writer>>,
    // a document was started with `drive_partial` and is not complete
    in_progress: bool,
}

impl Default for Serializer {
    fn default() -> Serializer {
        Serializer::new()
    }
}

impl Clone for Serializer {
    /// Clones the serializer.
    ///
    /// The clone of a serializer that writes a document in parts cannot
    /// write more values (see
    /// [`StreamSerializer::in_progress`](ser::StreamSerializer::in_progress)).
    fn clone(&self) -> Serializer {
        Serializer {
            config: self.config.clone(),
            out: self.out.clone(),
            written: self.written,
            document: None,
            in_progress: self.in_progress,
        }
    }
}

impl std::fmt::Debug for Serializer {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Serializer")
            .field("config", &self.config)
            .field("output", &self.out)
            .field("written", &self.written)
            .field("in_progress", &self.in_progress)
            .finish()
    }
}

impl Serializer {
    /// Creates a serializer.
    pub fn new() -> Serializer {
        Serializer::with_config(SerializerConfig::new())
    }

    /// Creates a serializer with the given configuration.
    pub fn with_config(config: SerializerConfig) -> Serializer {
        Serializer {
            config,
            out: String::new(),
            written: false,
            document: None,
            in_progress: false,
        }
    }

    /// Returns the configuration.
    pub fn config(&self) -> &SerializerConfig {
        &self.config
    }

    /// Returns `true` once the document was written.
    pub fn written(&self) -> bool {
        self.written
    }

    /// Serializes a value.
    ///
    /// If the value fails to serialize, nothing is written.
    pub fn serialize<T: Serialize + ?Sized>(&mut self, value: &T) -> Result<(), Error> {
        ser::Serializer::serialize(self, value)
    }

    /// Serializes a value with a configured driver.
    ///
    /// The callback is invoked with the driver before the value is
    /// serialized, for instance to add [`Layer`](deser_core::ser::Layer)s.
    pub fn serialize_with<F, T: Serialize + ?Sized>(
        &mut self,
        value: &T,
        setup: F,
    ) -> Result<(), Error>
    where
        F: FnOnce(&mut SerializeDriver<'_>),
    {
        ser::Serializer::serialize_with(self, value, setup)
    }

    /// Returns the output written so far (that was not cleared).
    pub fn as_str(&self) -> &str {
        &self.out
    }

    /// Returns the output.
    pub fn finish(self) -> String {
        self.out
    }
}

impl ser::Serializer for Serializer {
    fn drive(&mut self, driver: &mut SerializeDriver<'_>) -> Result<(), Error> {
        // only `drive_partial` continues a document
        if self.in_progress {
            return Err(Error::in_progress());
        }
        ser::StreamSerializer::drive_partial(self, driver, usize::MAX).map(|_| ())
    }
}

impl ser::StreamSerializer for Serializer {
    fn output(&self) -> &[u8] {
        self.out.as_bytes()
    }

    fn clear_output(&mut self) {
        self.out.clear();
    }

    fn supports_partial(&self) -> bool {
        true
    }

    fn drive_partial(
        &mut self,
        driver: &mut SerializeDriver<'_>,
        limit: usize,
    ) -> Result<bool, Error> {
        if !self.config.context.is_empty() {
            driver.set_default_context(self.config.context.clone());
        }
        if self.document.is_none() {
            if self.in_progress {
                return Err(Error::in_progress());
            }
            if self.written {
                return Err(Error::new(
                    ErrorKind::InvalidState,
                    "an XML document holds a single root element",
                ));
            }
        }
        // the parts of a document that failed stay written (see
        // `in_progress`)
        if !self
            .config
            .serialize_part(&mut self.document, driver, &mut self.out, limit)?
        {
            self.in_progress = true;
            return Ok(false);
        }
        self.in_progress = false;
        self.written = true;
        Ok(true)
    }

    fn in_progress(&self) -> bool {
        self.in_progress
    }
}

#[cfg(feature = "io")]
impl SerializerConfig {
    /// Creates a writer of an XML document (see
    /// [`deser::io::Writer`](deser_core::io::Writer)).
    ///
    /// A stream holds a single document, writing a second value fails.  The
    /// document is written in parts while the value is serialized (see
    /// [`Serializer`]).
    ///
    /// ```
    /// use deser_xml::SerializerConfig;
    ///
    /// #[derive(deser::Serialize)]
    /// #[deser(rename = "feed")]
    /// struct Feed {
    ///     entry: Vec<u32>,
    /// }
    ///
    /// let mut writer = SerializerConfig::new().writer(Vec::new());
    /// writer.set_buffer_limit(8);
    /// writer.write(&Feed { entry: vec![1, 2, 3] }).unwrap();
    /// assert_eq!(
    ///     writer.into_inner(),
    ///     b"<feed><entry>1</entry><entry>2</entry><entry>3</entry></feed>"
    /// );
    /// ```
    pub fn writer<W: std::io::Write>(&self, writer: W) -> deser_core::io::Writer<W, Serializer> {
        deser_core::io::Writer::new(writer, Serializer::with_config(self.clone()))
    }

    /// Serializes a value as XML document to a writer.
    ///
    /// See [`to_writer`].
    pub fn to_writer<W: std::io::Write, T: Serialize + ?Sized>(
        &self,
        writer: W,
        value: &T,
    ) -> Result<(), Error> {
        self.writer(writer).write(value)
    }
}

/// Serializes a value as XML document to a writer.
///
/// The output is written in parts while the value is serialized (see
/// [`Serializer`]), the writer does not need to be buffered.
///
/// ```
/// #[derive(deser::Serialize)]
/// #[deser(rename = "a")]
/// struct Link {
///     #[deser(rename = "@href")]
///     href: String,
/// }
///
/// let mut out = Vec::new();
/// deser_xml::to_writer(&mut out, &Link { href: "/x".into() }).unwrap();
/// assert_eq!(out, br#"<a href="/x"/>"#);
/// ```
#[cfg(feature = "io")]
pub fn to_writer<W: std::io::Write, T: Serialize + ?Sized>(
    writer: W,
    value: &T,
) -> Result<(), Error> {
    SerializerConfig::new().to_writer(writer, value)
}

/// Serializes a value to XML with the default configuration.
///
/// See [`SerializerConfig`].
pub fn to_string<T: Serialize + ?Sized>(value: &T) -> Result<String, Error> {
    SerializerConfig::new().to_string(value)
}

/// An element or sequence that is being written.
enum Frame {
    Element(Element),
    /// A sequence whose values are elements with the name.
    Items {
        name: String,
        /// If the elements are written on a single line.
        compact: bool,
        /// If an element was written.
        started: bool,
    },
}

/// How the content of an element is laid out.
#[derive(Clone, Copy, PartialEq, Eq)]
enum Lines {
    /// Not decided yet, no child element was written.
    Pending,
    /// Child elements are on lines of their own.
    Indented,
    /// Everything is on a single line from here on.
    Inline,
}

/// An element whose content is a map.
struct Element {
    /// The name as written.
    name: String,
    /// Where attributes are added to the start tag (in the document).
    attrs_at: usize,
    /// If the start tag was ended because content was written.
    content: bool,
    /// Attributes that came after content, they are added to the start
    /// tag once no more can come.
    late: String,
    /// Which attributes can still come.
    attrs: Attrs,
    /// The fields of the struct and the index after the last key among
    /// them, `None` if the keys are not known.
    fields: Option<(&'static [&'static str], usize)>,
    /// The number of local namespace bindings outside of the element.
    bindings: usize,
    /// How the content is laid out.
    lines: Lines,
    /// If the layout is not predicted from the fields.
    expanded: bool,
}

/// Which attributes an element can still get.
///
/// The output from the start tag of the first element that can still get
/// attributes on is not final and cannot be passed on.
enum Attrs {
    /// Any, the keys of the map are not known.
    Unknown,
    /// Those among the fields of the struct (see `Element::fields`), the
    /// field with the index is the last attribute.
    Until(usize),
    /// None.
    Done,
}

/// What a key of a map stands for.
enum Key {
    /// An attribute, `last` if no other attribute can follow.
    Attribute {
        name: String,
        last: bool,
    },
    Text,
    Element(String),
}

/// Writes the events of a document.
pub(crate) struct Writer {
    config: SerializerConfig,
    /// How bytes are written (from the state).
    bytes: BytesFormat,
    /// The output that was not passed on yet, it starts at `base` in the
    /// document.
    out: String,
    base: usize,
    /// The driver is paused once this much output is final (see
    /// `EventSink`).
    limit: usize,
    /// An error of `pause`, which cannot fail.
    error: Option<Error>,
    stack: Vec<Frame>,
    /// The key of the next value of the element on top of the stack.
    key: Option<Key>,
    /// The prefixes of the namespaces declared on the root element, the
    /// first one is `xml` which is never declared.
    root_bindings: Vec<(String, String)>,
    /// If the declarations on the root element were written.  After that,
    /// new namespaces are declared on the elements that use them.
    root_declared: bool,
    /// Where the declarations of the root element go (after its name).
    root_declarations: Option<usize>,
    /// The prefixes declared on the elements on the stack.
    local_bindings: Vec<(String, String)>,
    /// The number of elements on the stack.
    depth: usize,
}

/// Finds the name of a type.
#[derive(Default)]
struct TypeName(Option<String>);

impl Describe for TypeName {
    fn structure(&mut self, name: &str) {
        self.0.get_or_insert_with(|| name.to_string());
    }

    fn newtype(&mut self, name: &str) {
        self.0.get_or_insert_with(|| name.to_string());
    }

    fn tuple_struct(&mut self, name: &str) {
        self.0.get_or_insert_with(|| name.to_string());
    }

    fn unit_struct(&mut self, name: &str) {
        self.0.get_or_insert_with(|| name.to_string());
    }
}

/// Finds the fields of a struct that is a map.
///
/// Values that are variants are not the struct they describe last (for
/// instance the content of an externally tagged variant is in a map with
/// the name of the variant).
#[derive(Default)]
struct Fields {
    names: Option<&'static [&'static str]>,
    variant: bool,
}

impl Describe for Fields {
    fn structure(&mut self, _name: &str) {
        self.names = None;
    }

    fn fields(&mut self, names: &'static [&'static str]) {
        self.names = Some(names);
    }

    fn variant(&mut self, _variant: &deser_core::ser::Variant<'_>) {
        self.variant = true;
    }
}

impl EventSink for Writer {
    const DESCRIBED: bool = true;

    fn event(
        &mut self,
        event: Event<'_>,
        value: SerializeRef<'_>,
        state: &mut State,
    ) -> Result<(), Error> {
        Writer::event(self, event, value, state)
    }

    fn pause(&mut self) -> bool {
        // the declarations of the root element are only written once the
        // output is passed on, as namespaces found afterwards are declared
        // on the elements that use them
        if self.final_until() - self.base < self.limit {
            return false;
        }
        if let Err(err) = self.final_len() {
            // the error is returned once the driver stopped
            self.error = Some(err);
        }
        true
    }
}

impl Writer {
    fn new(config: &SerializerConfig, bytes: BytesFormat) -> Writer {
        let mut out = String::new();
        if config.declaration {
            out.push_str("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
            if config.indent != Indent::None {
                out.push('\n');
            }
        }
        Writer {
            config: config.clone(),
            bytes,
            out,
            base: 0,
            limit: usize::MAX,
            error: None,
            stack: Vec::new(),
            key: None,
            root_bindings: std::iter::once(("xml", XML_NAMESPACE))
                .chain(config.names.namespaces.iter().copied())
                .map(|(prefix, uri)| (prefix.to_string(), uri.to_string()))
                .collect(),
            root_declared: false,
            root_declarations: None,
            local_bindings: Vec::new(),
            depth: 0,
        }
    }

    fn event(
        &mut self,
        event: Event<'_>,
        value: SerializeRef<'_>,
        state: &State,
    ) -> Result<(), Error> {
        match self.stack.last_mut() {
            None => self.root(event, value, state)?,
            Some(Frame::Items { .. }) => self.item(event, value, state)?,
            Some(Frame::Element(element)) => match self.key.take() {
                None => {
                    // flattened mixed content marks the key of its first
                    // entry
                    if matches!(event, Event::Atom(_)) && keeps_whitespace(state) {
                        element.lines = Lines::Inline;
                    }
                    self.key(event)?
                }
                Some(key) => self.entry(key, event, value, state)?,
            },
        }
        Ok(())
    }

    fn root(
        &mut self,
        event: Event<'_>,
        value: SerializeRef<'_>,
        state: &State,
    ) -> Result<(), Error> {
        // the name and the namespaces of a `Root` or of the root element the
        // value was read from come first, then the name of the type and the
        // configured name
        let root = state.event::<RootData>();
        if let Some(root) = root {
            self.bind_root(&root.namespaces)?;
        }
        let name = match root.and_then(|root| root.name.clone()) {
            Some(name) => name,
            None => {
                let mut name = TypeName::default();
                value.describe(&mut name);
                name.0
                    .or_else(|| self.config.root.map(str::to_string))
                    .ok_or_else(|| {
                        Error::new(
                            ErrorKind::UnsupportedType,
                            "the name of the root element is unknown (see deser_xml::Root)",
                        )
                    })?
            }
        };
        check_element_name(&name)?;
        match event {
            Event::MapStart(_) => self.open_element(&name, value, state),
            Event::Atom(atom) => self.atom_element(&name, &atom, true, state),
            _ => Err(Error::new(
                ErrorKind::UnsupportedType,
                "the root element must be a map or a single value",
            )),
        }
    }

    /// Declares the namespaces of the root value on the root element.
    ///
    /// They come before the configured ones, which are left out if they
    /// have the same prefix.
    fn bind_root(&mut self, namespaces: &[(String, String)]) -> Result<(), Error> {
        let mut bindings = vec![self.root_bindings[0].clone()];
        for (prefix, uri) in namespaces {
            check_prefix(prefix)?;
            if !bindings.iter().any(|(x, _)| x == prefix) {
                bindings.push((prefix.clone(), uri.clone()));
            }
        }
        for binding in self.root_bindings.drain(1..) {
            if !bindings.iter().any(|(x, _)| *x == binding.0) {
                bindings.push(binding);
            }
        }
        self.root_bindings = bindings;
        Ok(())
    }

    fn key(&mut self, event: Event<'_>) -> Result<(), Error> {
        let key = match event {
            Event::MapEnd => return self.close_element(),
            Event::Atom(ref atom) => match self.text(atom)? {
                Some(key) => key.into_owned(),
                None => return Err(unsupported_key()),
            },
            _ => return Err(unsupported_key()),
        };

        // keep track of the attributes that can still come
        let Some(Frame::Element(element)) = self.stack.last_mut() else {
            unreachable!()
        };
        let mut is_last = false;
        if let Some((names, cursor)) = &mut element.fields {
            match names[*cursor..].iter().position(|name| *name == key) {
                Some(offset) => {
                    *cursor += offset + 1;
                    if let Attrs::Until(last) = element.attrs {
                        is_last = *cursor == last + 1;
                        if *cursor > last + 1 {
                            element.attrs = Attrs::Done;
                        }
                    }
                }
                // not a field, all bets are off
                None => {
                    element.fields = None;
                    if matches!(element.attrs, Attrs::Until(_)) {
                        element.attrs = Attrs::Unknown;
                    }
                }
            }
        }

        let names = &self.config.names;
        self.key = Some(if key == names.text_key {
            Key::Text
        } else if let Some(name) = attribute_name(names, &key) {
            check_element_name(name)?;
            Key::Attribute {
                name: name.to_string(),
                last: is_last,
            }
        } else {
            check_element_name(&key)?;
            Key::Element(key)
        });
        self.settle();
        Ok(())
    }

    fn entry(
        &mut self,
        key: Key,
        event: Event<'_>,
        value: SerializeRef<'_>,
        state: &State,
    ) -> Result<(), Error> {
        match (key, event) {
            (Key::Attribute { name, last }, Event::Atom(atom)) => {
                if let Some(text) = self.text(&atom)? {
                    let text = text.into_owned();
                    self.attribute(&name, &text)?;
                }
                if last && let Some(Frame::Element(element)) = self.stack.last_mut() {
                    element.attrs = Attrs::Done;
                    self.settle();
                }
                Ok(())
            }
            (Key::Text, Event::Atom(atom)) => {
                if let Some(text) = self.text(&atom)? {
                    let text = text.into_owned();
                    self.close_start_tag();
                    if !text.is_empty() {
                        // whitespace next to text would be text
                        let Some(Frame::Element(element)) = self.stack.last_mut() else {
                            unreachable!()
                        };
                        element.lines = Lines::Inline;
                    }
                    escape(&text, false, &mut self.out)?;
                }
                Ok(())
            }
            (Key::Element(name), Event::Atom(atom)) => {
                self.atom_element(&name, &atom, false, state)
            }
            (Key::Element(name), Event::MapStart(_)) => {
                self.before_child();
                self.open_element(&name, value, state)
            }
            (Key::Element(name), Event::SeqStart(_)) => {
                self.stack.push(Frame::Items {
                    name,
                    compact: Layout::of(state) == Layout::Compact,
                    started: false,
                });
                Ok(())
            }
            (Key::Attribute { name, .. }, _) => Err(Error::new(
                ErrorKind::UnsupportedType,
                format!("attribute `{name}` must be a single value"),
            )),
            (Key::Text, _) => Err(Error::new(
                ErrorKind::UnsupportedType,
                "the text of an element must be a single value",
            )),
            (Key::Element(_), _) => unreachable!("ends are handled by the frames"),
        }
    }

    fn item(
        &mut self,
        event: Event<'_>,
        value: SerializeRef<'_>,
        state: &State,
    ) -> Result<(), Error> {
        let Some(Frame::Items { name, .. }) = self.stack.last() else {
            unreachable!()
        };
        let name = name.clone();
        match event {
            Event::SeqEnd => {
                self.stack.pop();
                Ok(())
            }
            // nulls keep their position
            Event::Atom(Atom::Null) => {
                self.before_child();
                let bindings = self.local_bindings.len();
                self.start_tag(&name, false, state)?;
                self.out.push_str("/>");
                self.local_bindings.truncate(bindings);
                Ok(())
            }
            Event::Atom(atom) => self.atom_element(&name, &atom, false, state),
            Event::MapStart(_) => {
                self.before_child();
                self.open_element(&name, value, state)
            }
            _ => Err(Error::new(
                ErrorKind::UnsupportedType,
                "sequences in sequences are not supported",
            )),
        }
    }

    /// Writes an attribute of the element on top of the stack.
    fn attribute(&mut self, name: &str, value: &str) -> Result<(), Error> {
        let mut declarations = String::new();
        let name = self.qualify(name, true, &mut declarations)?;
        let Some(Frame::Element(element)) = self.stack.last_mut() else {
            unreachable!()
        };
        let out = if !element.content {
            &mut self.out
        } else if element.attrs_at >= self.base {
            &mut element.late
        } else {
            return Err(Error::new(
                ErrorKind::InvalidValue,
                format!(
                    "attribute `{name}` comes after the start tag of the element was written \
                     (the fields the value described are not the keys it has)"
                ),
            ));
        };
        out.push_str(&declarations);
        out.push(' ');
        out.push_str(&name);
        out.push_str("=\"");
        escape(value, true, out)?;
        out.push('"');
        if !element.content {
            element.attrs_at = self.base + self.out.len();
        }
        self.settle();
        Ok(())
    }

    /// Adds the late attributes of the element on top of the stack to its
    /// start tag once no more attributes can come.
    fn settle(&mut self) {
        let Some(Frame::Element(element)) = self.stack.last_mut() else {
            return;
        };
        if !matches!(element.attrs, Attrs::Done) || element.late.is_empty() {
            return;
        }
        let late = std::mem::take(&mut element.late);
        let at = element.attrs_at;
        self.insert(at, &late);
    }

    /// Inserts text into the output which was not passed on yet.
    ///
    /// Positions of attributes at or after the text move behind it.
    fn insert(&mut self, at: usize, text: &str) {
        self.out.insert_str(at - self.base, text);
        for frame in &mut self.stack {
            if let Frame::Element(element) = frame
                && element.attrs_at >= at
            {
                element.attrs_at += text.len();
            }
        }
    }

    /// Writes an element whose content is a single value.
    ///
    /// Nulls are left out unless they are the root.
    fn atom_element(
        &mut self,
        name: &str,
        atom: &Atom<'_>,
        is_root: bool,
        state: &State,
    ) -> Result<(), Error> {
        let text = match self.text(atom)? {
            Some(text) => text.into_owned(),
            None if is_root => String::new(),
            None => return Ok(()),
        };
        self.before_child();
        let bindings = self.local_bindings.len();
        let name = self.start_tag(name, is_root, state)?;
        if text.is_empty() {
            self.out.push_str("/>");
        } else {
            self.out.push('>');
            escape(&text, false, &mut self.out)?;
            write!(self.out, "</{name}>").unwrap();
        }
        self.local_bindings.truncate(bindings);
        Ok(())
    }

    /// Writes the start tag of an element whose content is a map.
    fn open_element(
        &mut self,
        name: &str,
        value: SerializeRef<'_>,
        state: &State,
    ) -> Result<(), Error> {
        let bindings = self.local_bindings.len();
        let name = self.start_tag(name, self.stack.is_empty(), state)?;
        let (fields, attrs) = self.fields_of(value);
        let layout = Layout::of(state);
        let lines = if self.config.indent == Indent::None
            || self.in_line()
            || layout == Layout::Compact
            || keeps_whitespace(state)
        {
            Lines::Inline
        } else {
            Lines::Pending
        };
        self.stack.push(Frame::Element(Element {
            name,
            attrs_at: self.base + self.out.len(),
            content: false,
            late: String::new(),
            attrs,
            fields: fields.map(|names| (names, 0)),
            bindings,
            lines,
            expanded: layout == Layout::Expanded,
        }));
        self.depth += 1;
        Ok(())
    }

    /// Returns the fields of the map of a value and which attributes it
    /// can have.
    fn fields_of(&self, value: SerializeRef<'_>) -> (Option<&'static [&'static str]>, Attrs) {
        let mut fields = Fields::default();
        value.describe(&mut fields);
        let Some(names) = fields.names.filter(|_| !fields.variant) else {
            return (None, Attrs::Unknown);
        };
        let names_config = &self.config.names;
        let last = names.iter().rposition(|name| {
            *name != names_config.text_key && attribute_name(names_config, name).is_some()
        });
        let attrs = match last {
            Some(last) => Attrs::Until(last),
            None => Attrs::Done,
        };
        (Some(names), attrs)
    }

    /// Returns `true` if the next element is written on a single line with
    /// its parent.
    fn in_line(&self) -> bool {
        match self.stack.last() {
            None => false,
            Some(Frame::Items { compact: true, .. }) => true,
            Some(Frame::Items { .. }) => match self.stack.iter().rev().nth(1) {
                Some(Frame::Element(element)) => element.lines == Lines::Inline,
                _ => unreachable!("sequences are in elements"),
            },
            Some(Frame::Element(element)) => element.lines == Lines::Inline,
        }
    }

    /// Ends the start tag of the parent of the next element and starts a
    /// new line for it if the content of the parent is indented.
    fn before_child(&mut self) {
        self.close_start_tag();
        if self.config.indent == Indent::None {
            return;
        }
        let text_key = self.config.names.text_key;
        let mut frames = self.stack.iter_mut().rev();
        let element = match frames.next() {
            None => return,
            Some(Frame::Items {
                compact, started, ..
            }) => {
                // compact sequences are on the line of their first element
                if std::mem::replace(started, true) && *compact {
                    return;
                }
                match frames.next() {
                    Some(Frame::Element(element)) => element,
                    _ => unreachable!("sequences are in elements"),
                }
            }
            Some(Frame::Element(element)) => element,
        };
        if element.lines == Lines::Pending {
            // text that can still come is next to the child elements,
            // structs whose text comes after them are on a single line
            let text_ahead = !element.expanded
                && element
                    .fields
                    .is_some_and(|(names, cursor)| names[cursor..].contains(&text_key));
            element.lines = if text_ahead {
                Lines::Inline
            } else {
                Lines::Indented
            };
        }
        if element.lines == Lines::Indented {
            self.newline(self.depth);
        }
    }

    /// Starts a new line indented for the depth.
    fn newline(&mut self, depth: usize) {
        self.out.push('\n');
        let (unit, count) = match self.config.indent {
            Indent::None => return,
            Indent::Spaces(width) => (' ', width * depth),
            Indent::Tab => ('\t', depth),
        };
        self.out.extend(std::iter::repeat_n(unit, count));
    }

    /// Writes the start of a start tag and returns the name as written.
    ///
    /// The namespaces declared on an element (other than the root, see
    /// `bind_root`) are declared first, they are bound until the bindings
    /// are truncated to the ones before the element.
    fn start_tag(&mut self, name: &str, is_root: bool, state: &State) -> Result<String, Error> {
        let mut declarations = String::new();
        if !is_root && let Some(Declarations(namespaces)) = state.event::<Declarations>() {
            for (prefix, uri) in namespaces {
                check_prefix(prefix)?;
                if prefix == "xml" {
                    continue;
                }
                declare(prefix, uri, &mut declarations)?;
                self.local_bindings.push((prefix.clone(), uri.clone()));
            }
        }
        let name = self.qualify(name, false, &mut declarations)?;
        self.out.push('<');
        self.out.push_str(&name);
        if is_root {
            self.root_declarations = Some(self.base + self.out.len());
        }
        self.out.push_str(&declarations);
        Ok(name)
    }

    /// Returns how a name is written, `{uri}local` names get the prefix
    /// of their namespace.
    ///
    /// Namespaces without prefix are declared on the root element as long
    /// as its declarations were not written, afterwards on the element
    /// that is being written (the declaration is added to `declarations`).
    fn qualify(
        &mut self,
        name: &str,
        is_attribute: bool,
        declarations: &mut String,
    ) -> Result<String, Error> {
        let Some((uri, local)) = split_name(name)? else {
            return Ok(name.to_string());
        };
        // the default namespace (the empty prefix) does not apply to
        // attributes
        let usable = |(prefix, bound): &&(String, String)| {
            bound == uri && !(is_attribute && prefix.is_empty())
        };
        // a binding is only in effect if its prefix is not bound again
        // closer to the element
        let scoped = &self.local_bindings;
        let bound = scoped
            .iter()
            .enumerate()
            .rev()
            .find(|(index, binding)| {
                usable(binding) && !scoped[index + 1..].iter().any(|(x, _)| *x == binding.0)
            })
            .map(|(_, binding)| binding)
            .or_else(|| {
                self.root_bindings
                    .iter()
                    .find(|binding| usable(binding) && !scoped.iter().any(|(x, _)| *x == binding.0))
            });
        let prefix = match bound {
            Some((prefix, _)) => prefix,
            None => {
                // prefixes are never shadowed
                let prefix = (0..)
                    .map(|n| format!("ns{n}"))
                    .find(|prefix| {
                        self.root_bindings
                            .iter()
                            .chain(&self.local_bindings)
                            .all(|(x, _)| x != prefix)
                    })
                    .unwrap();
                let bindings = if self.root_declared {
                    declare(&prefix, uri, declarations)?;
                    &mut self.local_bindings
                } else {
                    &mut self.root_bindings
                };
                bindings.push((prefix, uri.to_string()));
                &bindings.last().unwrap().0
            }
        };
        Ok(if prefix.is_empty() {
            local.to_string()
        } else {
            format!("{prefix}:{local}")
        })
    }

    /// Writes the namespace declarations of the root element.
    fn declare_root(&mut self) -> Result<(), Error> {
        if self.root_declared {
            return Ok(());
        }
        self.root_declared = true;
        let Some(at) = self.root_declarations else {
            return Ok(());
        };
        let mut declarations = String::new();
        for (prefix, uri) in &self.root_bindings[1..] {
            declare(prefix, uri, &mut declarations)?;
        }
        self.insert(at, &declarations);
        Ok(())
    }

    /// Returns where the output that is not final starts.
    fn final_until(&self) -> usize {
        for frame in &self.stack {
            if let Frame::Element(element) = frame
                && !matches!(element.attrs, Attrs::Done)
            {
                return element.attrs_at;
            }
        }
        self.base + self.out.len()
    }

    /// Returns how much of the output that was not passed on is final.
    ///
    /// Once the start tag of the root element is final, its namespace
    /// declarations are written.  Namespaces that are found afterwards are
    /// declared on the elements that use them.
    fn final_len(&mut self) -> Result<usize, Error> {
        let mut until = self.final_until();
        // the declarations of the root element are final with it
        if !self.root_declared && self.root_declarations.is_some_and(|at| at < until) {
            self.declare_root()?;
            until = self.final_until();
        }
        Ok(until - self.base)
    }

    /// Passes the output that is final on.
    fn pass_on(&mut self, out: &mut String) {
        let len = self.final_until() - self.base;
        out.push_str(&self.out[..len]);
        self.out.drain(..len);
        self.base += len;
    }

    /// Completes the output once the document was written, the output
    /// that was not passed on is final afterwards.
    fn finish(&mut self) -> Result<(), Error> {
        if !self.stack.is_empty() || self.depth > 0 {
            return Err(Error::new(ErrorKind::InvalidState, "incomplete document"));
        }
        self.declare_root()
    }

    /// Ends the start tag of the element that contains the next content.
    fn close_start_tag(&mut self) {
        let element = self.stack.iter_mut().rev().find_map(|frame| match frame {
            Frame::Element(element) => Some(element),
            Frame::Items { .. } => None,
        });
        if let Some(element) = element
            && !element.content
        {
            element.content = true;
            self.out.push('>');
        }
    }

    fn close_element(&mut self) -> Result<(), Error> {
        if let Some(Frame::Element(element)) = self.stack.last_mut() {
            element.attrs = Attrs::Done;
        }
        self.settle();
        let Some(Frame::Element(element)) = self.stack.pop() else {
            unreachable!()
        };
        self.depth -= 1;
        if element.lines == Lines::Indented {
            self.newline(self.depth);
        }
        if element.content {
            write!(self.out, "</{}>", element.name).unwrap();
        } else {
            self.out.push_str("/>");
        }
        self.local_bindings.truncate(element.bindings);
        Ok(())
    }

    /// Returns the text of an atom, `None` for null.
    fn text<'a>(&self, atom: &'a Atom<'_>) -> Result<Option<Cow<'a, str>>, Error> {
        Ok(Some(match *atom {
            Atom::Null => return Ok(None),
            // implicit values keep their text if it's the same value in
            // XML Schema, which is the case for all but `~`, `.inf`, ...
            Atom::Implicit(ref value) => {
                return Ok(self
                    .text(&value.value().to_atom())?
                    .map(|text| Cow::Owned(text.into_owned())));
            }
            Atom::Bool(value) => Cow::Borrowed(if value { "true" } else { "false" }),
            Atom::Str(ref value) | Atom::Lexical(ref value) => Cow::Borrowed(&**value),
            Atom::Char(value) => Cow::Owned(value.to_string()),
            Atom::U64(value) => Cow::Owned(value.to_string()),
            Atom::I64(value) => Cow::Owned(value.to_string()),
            Atom::F32(value) => Cow::Owned(float_text(value)),
            Atom::F64(value) => Cow::Owned(float_text(value)),
            Atom::Bytes(ref bytes) => {
                let format = bytes.fallback.copied().unwrap_or(self.bytes);
                Cow::Owned(
                    format
                        .encode(bytes)
                        .or_else(|| BytesFormat::BASE64.encode(bytes))
                        .unwrap_or_default(),
                )
            }
            Atom::Ext(ref ext) => {
                if let Some(number) = ext.downcast_value_ref::<Number>() {
                    Cow::Owned(number.as_str().to_string())
                } else if let Some(value) = ext.downcast_ref::<u128>() {
                    Cow::Owned(value.to_string())
                } else if let Some(value) = ext.downcast_ref::<i128>() {
                    Cow::Owned(value.to_string())
                } else {
                    match ext.fallback() {
                        Atom::Ext(_) => {
                            return Err(Error::new(
                                ErrorKind::UnsupportedType,
                                format!("XML does not support {}", ext.name()),
                            ));
                        }
                        fallback => match self.text(&fallback)? {
                            Some(text) => Cow::Owned(text.into_owned()),
                            None => return Ok(None),
                        },
                    }
                }
            }
            _ => {
                return Err(Error::new(
                    ErrorKind::UnsupportedType,
                    format!("XML does not support {}", atom.name()),
                ));
            }
        }))
    }
}

/// Returns `true` if the event starts content that keeps whitespace.
fn keeps_whitespace(state: &State) -> bool {
    state
        .event::<KeepsWhitespace>()
        .is_some_and(|keeps| keeps.0)
}

/// Returns the text of a float.
///
/// Finite floats have the shortest text that reads back as the same value
/// of their type, like in the other formats.  The others are written as in
/// XML Schema.
fn float_text<F: zmij::Float + Into<f64>>(value: F) -> String {
    let wide: f64 = value.into();
    if wide.is_nan() {
        "NaN".into()
    } else if wide.is_infinite() {
        if wide > 0.0 { "INF" } else { "-INF" }.into()
    } else {
        zmij::Buffer::new().format_finite(value).into()
    }
}

/// Escapes text or the value of an attribute.
fn escape(text: &str, attribute: bool, out: &mut String) -> Result<(), Error> {
    for c in text.chars() {
        match c {
            '&' => out.push_str("&amp;"),
            '<' => out.push_str("&lt;"),
            '>' => out.push_str("&gt;"),
            '"' if attribute => out.push_str("&quot;"),
            // attribute values are normalized, whitespace is kept with
            // references
            '\t' if attribute => out.push_str("&#9;"),
            '\n' if attribute => out.push_str("&#10;"),
            '\r' => out.push_str("&#13;"),
            '\t' | '\n' => out.push(c),
            c if (c as u32) < 0x20 || c == '\u{fffe}' || c == '\u{ffff}' => {
                return Err(Error::new(
                    ErrorKind::UnsupportedType,
                    format!("the character {c:?} cannot be written in XML"),
                ));
            }
            c => out.push(c),
        }
    }
    Ok(())
}

/// Returns the name of the attribute a key stands for.
///
/// The text key is checked before.
fn attribute_name<'a>(names: &Names, key: &'a str) -> Option<&'a str> {
    key.strip_prefix(names.attribute_prefix)
        .filter(|_| !names.attribute_prefix.is_empty())
}

/// Writes the declaration of a namespace prefix.
fn declare(prefix: &str, uri: &str, out: &mut String) -> Result<(), Error> {
    out.push_str(" xmlns");
    if !prefix.is_empty() {
        out.push(':');
        out.push_str(prefix);
    }
    out.push_str("=\"");
    escape(uri, true, out)?;
    out.push('"');
    Ok(())
}

/// Splits a `{uri}local` name, other names are `None`.
fn split_name(name: &str) -> Result<Option<(&str, &str)>, Error> {
    let Some(rest) = name.strip_prefix('{') else {
        return Ok(None);
    };
    match rest.split_once('}') {
        Some((uri, local)) if !uri.is_empty() => Ok(Some((uri, local))),
        _ => Err(Error::new(
            ErrorKind::UnsupportedType,
            format!("`{name}` is not a name in XML"),
        )),
    }
}

/// Checks that a name is a name in XML or a `{uri}local` name whose local
/// name has no prefix.
fn check_element_name(name: &str) -> Result<(), Error> {
    match split_name(name)? {
        Some((_, local)) if local.contains(':') => Err(Error::new(
            ErrorKind::UnsupportedType,
            format!("`{name}` is not a name in XML"),
        )),
        Some((_, local)) => check_name(local),
        None => check_name(name),
    }
}

/// Checks that a prefix of a namespace is a prefix in XML (the empty
/// prefix is the default namespace).
fn check_prefix(prefix: &str) -> Result<(), Error> {
    if prefix.is_empty() {
        return Ok(());
    }
    check_name(prefix)?;
    if prefix.contains(':') {
        return Err(Error::new(
            ErrorKind::UnsupportedType,
            format!("`{prefix}` is not a prefix in XML"),
        ));
    }
    Ok(())
}

/// Checks that a name is a name in XML.
fn check_name(name: &str) -> Result<(), Error> {
    let mut chars = name.chars();
    let valid = match chars.next() {
        Some(c) if c.is_alphabetic() || c == '_' || c == ':' => {
            chars.all(|c| c.is_alphanumeric() || matches!(c, '_' | ':' | '-' | '.' | '\u{b7}'))
        }
        _ => false,
    };
    if valid {
        Ok(())
    } else {
        Err(Error::new(
            ErrorKind::UnsupportedType,
            format!("`{name}` is not a name in XML"),
        ))
    }
}

#[cold]
fn unsupported_key() -> Error {
    Error::new(
        ErrorKind::UnsupportedType,
        "the keys of elements must be names",
    )
}

#[cfg(test)]
mod tests {
    use std::collections::BTreeMap;

    use deser::Serialize;

    use super::*;

    /// Serializes a value in pieces that are passed on as early as possible
    /// (the driver pauses between values).
    fn pieces<T: Serialize + ?Sized>(
        config: &SerializerConfig,
        value: &T,
    ) -> Result<Vec<String>, Error> {
        let mut pieces = Vec::new();
        let mut driver = SerializeDriver::new(&value);
        let mut progress = None;
        loop {
            let mut out = String::new();
            let done = config.serialize_part(&mut progress, &mut driver, &mut out, 1)?;
            pieces.push(out);
            if done {
                return Ok(pieces);
            }
        }
    }

    #[derive(Serialize)]
    struct Feed {
        #[deser(rename = "@id")]
        id: u32,
        title: &'static str,
        entry: Vec<Entry>,
    }

    #[derive(Serialize)]
    struct Entry {
        #[deser(rename = "$text")]
        text: &'static str,
        #[deser(rename = "@n")]
        n: u32,
        #[deser(skip_serializing_if = Option::is_none)]
        note: Option<&'static str>,
    }

    fn feed() -> Feed {
        Feed {
            id: 1,
            title: "t",
            entry: vec![
                Entry {
                    text: "a",
                    n: 1,
                    note: None,
                },
                Entry {
                    text: "b",
                    n: 2,
                    note: Some("x"),
                },
            ],
        }
    }

    #[test]
    fn test_structs_stream() {
        // output is final once no more attributes can come, late
        // attributes hold back the rest of the element until they come
        assert_eq!(
            pieces(&SerializerConfig::new(), &feed()).unwrap(),
            [
                "<Feed id=\"1\"",
                "><title>t</title>",
                "<entry",
                " n=\"1\">a",
                "</entry>",
                "<entry",
                " n=\"2\">b",
                "<note>x</note>",
                "</entry>",
                "</Feed>",
            ]
        );
    }

    #[test]
    fn test_maps_are_buffered() {
        // the keys of maps are not known, their elements are final at the end
        let config = SerializerConfig::builder()
            .root("m")
            .declaration(true)
            .build();
        let map = BTreeMap::from([
            ("a", BTreeMap::from([("$text", "1"), ("@x", "2")])),
            ("b", BTreeMap::from([("$text", "3"), ("@y", "4")])),
        ]);
        assert_eq!(
            pieces(&config, &map).unwrap(),
            [
                "<?xml version=\"1.0\" encoding=\"UTF-8\"?><m",
                "><a x=\"2\">1</a><b y=\"4\">3</b></m>",
            ]
        );

        let map = BTreeMap::from([("$text", "x"), ("@a", "1"), ("b", "2")]);
        assert_eq!(
            pieces(&config, &map).unwrap(),
            [
                "<?xml version=\"1.0\" encoding=\"UTF-8\"?><m",
                " a=\"1\">x<b>2</b></m>",
            ]
        );
    }

    #[test]
    fn test_same_output() {
        let map = BTreeMap::from([("$text", "x"), ("@a", "1"), ("b", "2")]);
        let nested = BTreeMap::from([("a", BTreeMap::from([("@x", "1"), ("b", "2")]))]);
        let feed = feed();
        let values: [SerializeRef<'_>; 4] = [
            SerializeRef::new(&feed),
            SerializeRef::new(&map),
            SerializeRef::new(&nested),
            SerializeRef::new(&Some(42)),
        ];
        for config in [
            SerializerConfig::builder().root("r").build(),
            SerializerConfig::builder()
                .root("r")
                .declaration(true)
                .indent(Indent::Spaces(2))
                .build(),
        ] {
            for value in values {
                assert_eq!(
                    pieces(&config, &value).unwrap().concat(),
                    config.to_string(&value).unwrap()
                );
            }
        }
    }

    #[test]
    fn test_indent_streams() {
        // indentation does not hold back output
        let config = SerializerConfig::builder()
            .indent(Indent::Spaces(2))
            .build();
        assert_eq!(
            pieces(&config, &feed()).unwrap(),
            [
                "<Feed id=\"1\"",
                ">\n  <title>t</title>",
                "\n  <entry",
                " n=\"1\">a",
                "</entry>",
                "\n  <entry",
                " n=\"2\">b",
                "<note>x</note>",
                "</entry>",
                "\n</Feed>",
            ]
        );
    }

    #[test]
    fn test_namespaces_stream() {
        #[derive(Serialize)]
        #[deser(rename = "{urn:root}root")]
        struct Root {
            #[deser(rename = "{urn:a}a")]
            a: Vec<Child>,
        }

        #[derive(Serialize)]
        struct Child {
            #[deser(rename = "@{urn:b}b")]
            b: u32,
            #[deser(rename = "{urn:a}c")]
            c: u32,
        }

        let root = Root {
            a: vec![Child { b: 1, c: 2 }, Child { b: 3, c: 4 }],
        };

        // written at once, all namespaces are declared on the root
        let config = SerializerConfig::new();
        assert_eq!(
            config.to_string(&root).unwrap(),
            "<ns0:root xmlns:ns0=\"urn:root\" xmlns:ns1=\"urn:a\" xmlns:ns2=\"urn:b\">\
             <ns1:a ns2:b=\"1\"><ns1:c>2</ns1:c></ns1:a>\
             <ns1:a ns2:b=\"3\"><ns1:c>4</ns1:c></ns1:a></ns0:root>"
        );

        // streamed, the ones that are found after the start tag of the root
        // was written are declared where they are used
        assert_eq!(
            pieces(&config, &root).unwrap().concat(),
            "<ns0:root xmlns:ns0=\"urn:root\" xmlns:ns1=\"urn:a\">\
             <ns1:a xmlns:ns2=\"urn:b\" ns2:b=\"1\"><ns1:c>2</ns1:c></ns1:a>\
             <ns1:a xmlns:ns2=\"urn:b\" ns2:b=\"3\"><ns1:c>4</ns1:c></ns1:a>\
             </ns0:root>"
        );

        // configured namespaces are always declared on the root
        let config = SerializerConfig::new().namespaces(&[("r", "urn:root"), ("a", "urn:a")]);
        assert_eq!(
            pieces(&config, &root).unwrap().concat(),
            "<r:root xmlns:r=\"urn:root\" xmlns:a=\"urn:a\">\
             <a:a xmlns:ns0=\"urn:b\" ns0:b=\"1\"><a:c>2</a:c></a:a>\
             <a:a xmlns:ns0=\"urn:b\" ns0:b=\"3\"><a:c>4</a:c></a:a></r:root>"
        );
    }

    #[test]
    fn test_nested_declarations_stream() {
        const RESOLVE: crate::DeserializerConfig = crate::DeserializerConfig::builder()
            .resolve_namespaces(true)
            .build();
        let input = r#"<a:r xmlns:a="urn:a"><b xmlns:a="urn:b"><x>1</x></b><a:y>2</a:y></a:r>"#;
        let mut value: deser_value::Value = RESOLVE.from_str(input).unwrap();
        let config = SerializerConfig::new();
        assert_eq!(pieces(&config, &value).unwrap().concat(), input);

        // a namespace whose prefix is bound again gets another one
        let b = value.as_map_mut().unwrap().get_mut("b").unwrap();
        b.as_map_mut().unwrap().insert("{urn:a}z", "3");
        let xml = config.to_string(&value).unwrap();
        assert_eq!(
            xml,
            "<a:r xmlns:a=\"urn:a\" xmlns:ns0=\"urn:a\"><b xmlns:a=\"urn:b\"><x>1</x>\
             <ns0:z>3</ns0:z></b><a:y>2</a:y></a:r>"
        );
        assert_eq!(pieces(&config, &value).unwrap().concat(), xml);
    }

    #[test]
    fn test_wrong_fields() {
        // a value whose keys are not the fields it describes
        struct Wrong(BTreeMap<&'static str, &'static str>);

        impl Serialize for Wrong {
            fn describe(_value: &Self, d: &mut dyn Describe) {
                d.structure("Wrong");
                d.fields(&["$text"]);
            }

            fn serialize<'a>(
                value: &'a Self,
                state: &mut deser_core::State,
            ) -> Result<deser_core::ser::Emit<'a>, Error> {
                BTreeMap::<&str, &str>::serialize(&value.0, state)
            }
        }

        let wrong = Wrong(BTreeMap::from([("$text", "x"), ("@a", "1")]));
        let config = SerializerConfig::new();
        // written at once, the attribute can still go into the start tag
        assert_eq!(
            config.to_string(&wrong).unwrap(),
            r#"<Wrong a="1">x</Wrong>"#
        );
        let err = pieces(&config, &wrong).unwrap_err();
        assert!(
            err.message()
                .starts_with("attribute `a` comes after the start tag")
        );
    }
}