deser-json5 0.10.1

JSON5 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
// @generated from deser-template-json/src/ser.rs by
// deser-template-json/generate.py.  Do not edit.
use alloc::boxed::Box;
use alloc::string::String;
use alloc::string::ToString;
use alloc::vec::Vec;
use core::mem::ManuallyDrop;

use deser_core::ext::RawInput;
use deser_core::ext::{BigInt, Decimal, ExtValue, Number};
use deser_core::ser::SerializeRef;
use deser_core::ser::{self, EventSink, SerializeDriver};
use deser_core::{Atom, BytesFormat, Error, ErrorKind, Event, Implicit, ImplicitValue, Serialize};

use crate::Trailing;
use crate::buf::Buffer;
use crate::escape::find_escape;
use crate::pretty::PrettyWriter;
use crate::scan::skip_to_escape;

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

/// When maps and sequences are written on a single line in indented
/// output.
///
/// Maps and sequences with the [`Layout::Compact`](deser_core::hints::Layout)
/// hint are always written on a single line, the ones with
/// [`Layout::Expanded`](deser_core::hints::Layout) never (unless they are in a
/// map or sequence on a single line).  See [`SerializerConfig::set_inline`].
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
#[non_exhaustive]
pub enum InlinePolicy {
    /// Only compact maps and sequences are written on a single line.
    #[default]
    Never,
    /// Maps and sequences which only contain scalars (no maps or
    /// sequences, not even empty ones) are written on a single line if
    /// that line is not longer than the given number of characters
    /// (including the indentation, a tab counts as one character).
    LeafIfFits(usize),
}

/// Configures how values are serialized to JSON.
///
/// By default the output is as short as possible: no line breaks and no
/// spaces.  [`set_pretty`](Self::set_pretty) writes every entry on a line of its
/// own:
///
/// ```
/// use std::collections::BTreeMap;
/// use deser_json5::{Indent, SerializerConfig};
///
/// let value = BTreeMap::from([("name", vec!["a", "b"])]);
/// assert_eq!(
///     deser_json5::to_string(&value).unwrap(),
///     r#"{"name":["a","b"]}"#
/// );
///
/// const PRETTY: SerializerConfig =
///     SerializerConfig::builder().pretty(Indent::Spaces(2)).build();
/// assert_eq!(
///     PRETTY.to_string(&value).unwrap(),
///     "{\n  \"name\": [\n    \"a\",\n    \"b\"\n  ]\n}"
/// );
/// ```
///
/// In indented output maps and sequences with the
/// [`Layout::Compact`](deser_core::hints::Layout) hint (see
/// [`hints`](deser_core::hints)) are written on a single line.  The output never
/// ends with a line break.
///
/// [`to_string`](Self::to_string) works like the
/// [`to_string`] function.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SerializerConfig {
    indent: Indent,
    compact: bool,
    inline: InlinePolicy,
    trailing: Trailing,
    non_finite_floats: bool,
    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 {
            indent: Indent::None,
            compact: true,
            inline: InlinePolicy::Never,
            trailing: Trailing::Strict,
            non_finite_floats: false,
            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 what follows the values of a stream.
    ///
    /// This is the counterpart of
    /// [`DeserializerConfig::set_trailing`](crate::DeserializerConfig::set_trailing)
    /// for writing more than one value (with a [`Serializer`] or a stream
    /// writer), it does not affect [`to_string`](Self::to_string):
    ///
    /// * [`Trailing::Strict`]: the stream holds a single value, writing a
    ///   second one fails.  This is the default.
    /// * [`Trailing::Newline`]: every value is followed by a line break
    ///   ([JSON Lines](https://jsonlines.org/)).  The values must not be
    ///   indented.
    /// * [`Trailing::Stop`]: values are separated by line breaks.
    ///
    /// ```
    /// use deser_json5::{Serializer, SerializerConfig, Trailing};
    ///
    /// const LINES: SerializerConfig =
    ///     SerializerConfig::builder().trailing(Trailing::Newline).build();
    /// let mut serializer = Serializer::with_config(LINES);
    /// serializer.serialize(&vec![1, 2]).unwrap();
    /// serializer.serialize(&vec![3]).unwrap();
    /// assert_eq!(serializer.finish(), "[1,2]\n[3]\n");
    /// ```
    pub const fn set_trailing(&mut self, trailing: Trailing) {
        self.trailing = trailing;
    }

    /// Returns what follows the values of a stream.
    pub(crate) fn trailing_mode(&self) -> Trailing {
        self.trailing
    }

    /// Sets how the output is indented.
    ///
    /// By default ([`Indent::None`]) the value is written on a single line.
    /// Otherwise every entry of a map or sequence is written on a line of
    /// its own, indented by its depth.  Empty maps and sequences are always
    /// written as `{}` and `[]`.  This does not change the spaces after
    /// separators, see [`set_compact`](Self::set_compact).  To indent with spaces
    /// after separators use [`set_pretty`](Self::set_pretty).
    ///
    /// ```
    /// use deser_json5::{Indent, SerializerConfig};
    ///
    /// const TAB: SerializerConfig = SerializerConfig::builder().indent(Indent::Tab).build();
    /// assert_eq!(TAB.to_string(&vec![1, 2]).unwrap(), "[\n\t1,\n\t2\n]");
    /// ```
    pub const fn set_indent(&mut self, indent: Indent) {
        self.indent = indent;
    }

    /// Controls the spaces after separators.
    ///
    /// When enabled (which is the default) there are no spaces after `:`
    /// and `,`.  When disabled a space follows every `:` and every `,`
    /// that is not followed by a line break:
    ///
    /// ```
    /// use std::collections::BTreeMap;
    /// use deser_json5::SerializerConfig;
    ///
    /// let value = BTreeMap::from([("a", vec![1, 2])]);
    /// const SPACED: SerializerConfig = SerializerConfig::builder().compact(false).build();
    /// assert_eq!(SPACED.to_string(&value).unwrap(), r#"{"a": [1, 2]}"#);
    /// ```
    pub const fn set_compact(&mut self, yes: bool) {
        self.compact = yes;
    }

    /// Sets when maps and sequences are written on a single line in
    /// indented output.
    ///
    /// ```
    /// use deser::Serialize;
    /// use deser_json5::{Indent, InlinePolicy, SerializerConfig};
    ///
    /// #[derive(Serialize)]
    /// struct Shape {
    ///     name: &'static str,
    ///     points: Vec<Vec<i32>>,
    /// }
    ///
    /// let shape = Shape {
    ///     name: "line",
    ///     points: vec![vec![0, 0], vec![3, 4]],
    /// };
    /// const CONFIG: SerializerConfig = SerializerConfig::builder()
    ///     .pretty(Indent::Spaces(2))
    ///     .inline(InlinePolicy::LeafIfFits(80)).build();
    /// assert_eq!(CONFIG.to_string(&shape).unwrap(), r#"{
    ///   "name": "line",
    ///   "points": [
    ///     [0, 0],
    ///     [3, 4]
    ///   ]
    /// }"#);
    /// ```
    ///
    /// This has no effect without [indentation](Self::set_indent).
    pub const fn set_inline(&mut self, policy: InlinePolicy) {
        self.inline = policy;
    }

    /// Enables or disables pretty printing.
    ///
    /// This sets the [indentation](Self::set_indent) and writes spaces after
    /// separators (see [`set_compact`](Self::set_compact)) unless the indentation
    /// is [`Indent::None`], in which case the output is compact again.
    ///
    /// ```
    /// use std::collections::BTreeMap;
    /// use deser_json5::{Indent, SerializerConfig};
    ///
    /// let value = BTreeMap::from([("a", 1)]);
    /// const PRETTY: SerializerConfig =
    ///     SerializerConfig::builder().pretty(Indent::Spaces(4)).build();
    /// assert_eq!(PRETTY.to_string(&value).unwrap(), "{\n    \"a\": 1\n}");
    /// const NOT_PRETTY: SerializerConfig = PRETTY.into_builder().pretty(Indent::None).build();
    /// assert_eq!(NOT_PRETTY.to_string(&value).unwrap(), r#"{"a":1}"#);
    /// ```
    pub const fn set_pretty(&mut self, indent: Indent) {
        self.indent = indent;
        self.compact = matches!(indent, Indent::None);
    }

    /// Writes NaN and infinite floats as `NaN`, `Infinity` and `-Infinity`.
    ///
    /// JSON cannot represent these values, by default (`false`) they are
    /// written as `null`.  [JSON5](https://json5.org/) (and for instance
    /// the `json` module of Python) supports them with these literals, the
    /// output is then no longer JSON.  The serialization functions of
    /// [`deser-json5`](https://docs.rs/deser-json5) enable this.
    ///
    /// ```
    /// use deser_json5::SerializerConfig;
    ///
    /// let values = [f64::NAN, f64::INFINITY, f64::NEG_INFINITY];
    /// assert_eq!(
    ///     SerializerConfig::new().to_string(&values).unwrap(),
    ///     "[null,null,null]"
    /// );
    /// const NON_FINITE: SerializerConfig =
    ///     SerializerConfig::builder().non_finite_floats(true).build();
    /// assert_eq!(
    ///     NON_FINITE.to_string(&values).unwrap(),
    ///     "[NaN,Infinity,-Infinity]"
    /// );
    /// ```
    pub const fn set_non_finite_floats(&mut self, yes: bool) {
        self.non_finite_floats = yes;
    }

    /// Serializes the given value.
    // inlined so that the pretty writer is not linked for constant compact
    // configurations (see `serialize_driver`)
    #[inline]
    pub fn to_string<T: Serialize + ?Sized>(&self, value: &T) -> Result<String, Error> {
        // the code that exists for every type only erases it.  If the
        // configuration is a constant (like the one of `to_string`) only
        // the writer that is used ends up in the binary.
        let value = SerializeRef::new(&value);
        if self.is_compact() {
            self.to_string_compact(value)
        } else {
            self.to_string_pretty(value)
        }
    }

    /// Serializes a value without indentation (see `to_string`).
    #[inline(never)]
    fn to_string_compact(&self, value: SerializeRef<'_>) -> Result<String, Error> {
        let mut driver = SerializeDriver::from_ref(value);
        self.apply_context(&mut driver);
        accept_raw(&mut driver);
        self.serialize_compact(&mut driver)
    }

    /// Serializes a value with the pretty writer (see `to_string`).
    #[inline(never)]
    fn to_string_pretty(&self, value: SerializeRef<'_>) -> Result<String, Error> {
        let mut driver = SerializeDriver::from_ref(value);
        self.apply_context(&mut driver);
        accept_raw(&mut driver);
        self.serialize_pretty(&mut driver)
    }

    /// Serializes the given 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.
    ///
    /// ```
    /// use deser::ser::{Layer, Next};
    /// use deser::{Atom, Error, Event};
    /// use deser_json5::SerializerConfig;
    ///
    /// /// Writes all numbers as strings.
    /// struct NumbersAsStrings;
    ///
    /// impl Layer for NumbersAsStrings {
    ///     fn event(
    ///         &mut self,
    ///         event: Event<'_>,
    ///         next: &mut Next<'_>,
    ///     ) -> Result<(), Error> {
    ///         match event {
    ///             Event::Atom(Atom::U64(value)) => {
    ///                 next.emit(value.to_string().into())
    ///             }
    ///             event => next.emit(event),
    ///         }
    ///     }
    /// }
    ///
    /// let json = SerializerConfig::new()
    ///     .to_string_with(&vec![1u64, 2], |driver| {
    ///         driver.push_layer(NumbersAsStrings)
    ///     })
    ///     .unwrap();
    /// assert_eq!(json, r#"["1","2"]"#);
    /// ```
    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 the value of a driver.
    ///
    /// This is inlined: if the configuration is a constant (like the one
    /// of `to_string`) only the writer that is used ends up in the binary.
    #[inline]
    pub(crate) fn serialize_driver(
        &self,
        driver: &mut SerializeDriver<'_>,
    ) -> Result<String, Error> {
        accept_raw(driver);
        if self.is_compact() {
            self.serialize_compact(driver)
        } else {
            self.serialize_pretty(driver)
        }
    }

    /// Returns `true` if the output is written by `Writer`.
    #[inline(always)]
    fn is_compact(&self) -> bool {
        self.indent == Indent::None && self.compact
    }

    /// Serializes the value of a driver without indentation.
    #[inline(never)]
    fn serialize_compact(&self, driver: &mut SerializeDriver<'_>) -> Result<String, Error> {
        let bytes = BytesFormat::of(driver.state());
        let mut writer = self.compact_writer(Buffer::with_capacity(128), bytes);
        driver.drive_sink(&mut writer)?;
        Ok(writer.ser.out.into_string())
    }

    /// Serializes the value of a driver with the pretty writer.
    #[inline(never)]
    fn serialize_pretty(&self, driver: &mut SerializeDriver<'_>) -> Result<String, Error> {
        let bytes = BytesFormat::of(driver.state());
        let mut writer = self.pretty_writer(Buffer::with_capacity(128), bytes);
        driver.drive(|event, state| writer.event(event, state))?;
        Ok(writer.finish())
    }

    /// Creates the writer for compact output.
    fn compact_writer(&self, out: Buffer, bytes: BytesFormat) -> Writer {
        Writer {
            ser: Output {
                out,
                bytes,
                non_finite_floats: self.non_finite_floats,
            },
            stack: Vec::new(),
            container: Container::Top,
            first: true,
            is_key: false,
            limit: usize::MAX,
        }
    }

    /// Creates the writer for everything but compact output.
    fn pretty_writer(&self, out: Buffer, bytes: BytesFormat) -> PrettyWriter {
        let ser = Output {
            out,
            bytes,
            non_finite_floats: self.non_finite_floats,
        };
        let inline_width = match self.inline {
            InlinePolicy::Never => None,
            InlinePolicy::LeafIfFits(width) => Some(width),
        };
        PrettyWriter::new(ser, self.indent, self.compact, inline_width)
    }

    /// Creates the writer for a value which writes into the buffer.
    pub(crate) fn value_writer(&self, out: Buffer, bytes: BytesFormat) -> ValueWriter {
        if self.is_compact() {
            ValueWriter::Compact(self.compact_writer(out, bytes))
        } else {
            ValueWriter::Pretty(self.pretty_writer(out, bytes))
        }
    }
}

/// 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 what follows the values of a stream.
    ///
    /// See [`SerializerConfig::set_trailing`].
    pub const fn trailing(mut self, trailing: Trailing) -> SerializerConfigBuilder {
        self.value.set_trailing(trailing);
        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
    }

    /// Controls the spaces after separators.
    ///
    /// See [`SerializerConfig::set_compact`].
    pub const fn compact(mut self, yes: bool) -> SerializerConfigBuilder {
        self.value.set_compact(yes);
        self
    }

    /// Sets when maps and sequences are written on a single line in
    ///
    /// See [`SerializerConfig::set_inline`].
    pub const fn inline(mut self, policy: InlinePolicy) -> SerializerConfigBuilder {
        self.value.set_inline(policy);
        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
    }

    /// Writes NaN and infinite floats as `NaN`, `Infinity` and `-Infinity`.
    ///
    /// See [`SerializerConfig::set_non_finite_floats`].
    pub const fn non_finite_floats(mut self, yes: bool) -> SerializerConfigBuilder {
        self.value.set_non_finite_floats(yes);
        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()
    }
}

/// Declares that raw values of the dialect are written as they are.
fn accept_raw(driver: &mut SerializeDriver<'_>) {
    driver.state_mut().declare_raw_format(&crate::raw::ID);
}

/// Writes the events of a value.
pub(crate) enum ValueWriter {
    /// Compact output (no indentation, no spaces).
    Compact(Writer),
    /// Everything else.
    Pretty(PrettyWriter),
}

impl ValueWriter {
    /// Writes the events of the driver.
    ///
    /// Returns `false` if the driver was paused as the output holds at
    /// least `limit` bytes (see `take_output`).  With a limit of
    /// `usize::MAX` the value is written at once.
    pub(crate) fn drive(
        &mut self,
        driver: &mut SerializeDriver<'_>,
        limit: usize,
    ) -> Result<bool, Error> {
        if limit == usize::MAX {
            return self.drive_whole(driver).map(|()| true);
        }
        match self {
            ValueWriter::Compact(writer) => {
                writer.limit = limit;
                driver.drive_until(writer)
            }
            ValueWriter::Pretty(writer) => {
                writer.limit = limit;
                driver.drive_until(writer)
            }
        }
    }

    /// Writes the events of the driver at once.
    ///
    /// Unlike `drive` this does not refer to the pausable instances of the
    /// driver which are only needed by stream serializers.
    pub(crate) fn drive_whole(&mut self, driver: &mut SerializeDriver<'_>) -> Result<(), Error> {
        match self {
            ValueWriter::Compact(writer) => driver.drive_sink(writer),
            ValueWriter::Pretty(writer) => driver.drive(|event, state| writer.event(event, state)),
        }
    }

    /// Returns the output buffer.
    pub(crate) fn output(&mut self) -> &mut Buffer {
        match self {
            ValueWriter::Compact(writer) => &mut writer.ser.out,
            ValueWriter::Pretty(writer) => writer.output(),
        }
    }

    /// Takes the output written so far (which is final after `drive`
    /// returned), the writer continues with an empty output.
    pub(crate) fn take_output(&mut self) -> Vec<u8> {
        match self {
            ValueWriter::Compact(writer) => writer.ser.out.take(),
            ValueWriter::Pretty(writer) => writer.take_output(),
        }
    }
}

/// Serializes values into JSON.
///
/// Every call to [`serialize`](Self::serialize) writes a value.  What
/// follows the values depends on [`SerializerConfig::set_trailing`]: by default
/// only a single value can be written, with [`Trailing::Newline`] every
/// value is followed by a line break ([JSON Lines](https://jsonlines.org/)).
///
/// ```
/// use deser_json5::{Serializer, SerializerConfig, Trailing};
///
/// const LINES: SerializerConfig =
///     SerializerConfig::builder().trailing(Trailing::Newline).build();
/// let mut serializer = Serializer::with_config(LINES);
/// serializer.serialize(&vec![1, 2]).unwrap();
/// serializer.serialize(&"x").unwrap();
/// assert_eq!(serializer.finish(), "[1,2]\n\"x\"\n");
/// ```
///
/// The serializer is also the stream serializer of JSON (see
/// [`StreamSerializer`](ser::StreamSerializer)): the output can be taken
/// while values are written, and large values can be written in parts.
/// To write to a [`Write`](std::io::Write) use
/// [`SerializerConfig::writer`]:
///
/// ```
/// # #[cfg(feature = "io")] {
/// use deser_json5::SerializerConfig;
///
/// let mut writer = SerializerConfig::new().writer(Vec::new());
/// writer.set_buffer_limit(4);
/// writer.write(&vec!["a", "b", "c"]).unwrap();
/// assert_eq!(writer.into_inner(), br#"["a","b","c"]"#);
/// # }
/// ```
pub struct Serializer {
    config: SerializerConfig,
    // only holds the output of value writers and line breaks, which is
    // valid UTF-8
    out: Vec<u8>,
    written: usize,
    // the value that is written in parts
    value: Option<Box<ValueWriter>>,
    // a value 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 value 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,
            value: None,
            in_progress: self.in_progress,
        }
    }
}

impl core::fmt::Debug for Serializer {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.debug_struct("Serializer")
            .field("config", &self.config)
            .field("output", &self.as_str())
            .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::with_written(config, 0)
    }

    /// Creates a serializer for a stream that continues after the given
    /// number of values.
    ///
    /// This is useful to append to a stream that was written before (see
    /// [`SerializerConfig::set_trailing`] for what separates the values).
    pub fn with_written(config: SerializerConfig, written: usize) -> Serializer {
        Serializer {
            config,
            out: Vec::new(),
            written,
            value: None,
            in_progress: false,
        }
    }

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

    /// Returns the number of values that were written.
    pub fn written(&self) -> usize {
        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 {
        // SAFETY: the output is valid UTF-8, see `out`
        unsafe { core::str::from_utf8_unchecked(&self.out) }
    }

    /// Returns the output.
    pub fn finish(self) -> String {
        // SAFETY: the output is valid UTF-8, see `out`
        unsafe { String::from_utf8_unchecked(self.out) }
    }

    /// Starts a value: writes what separates it from the previous value.
    fn start_value(&mut self) -> Result<(), Error> {
        if self.in_progress {
            return Err(Error::in_progress());
        }
        match self.config.trailing_mode() {
            Trailing::Strict if self.written > 0 => Err(Error::new(
                ErrorKind::InvalidState,
                "with Trailing::Strict only a single value can be written",
            )),
            Trailing::Stop if self.written > 0 => {
                self.out.push(b'\n');
                Ok(())
            }
            _ => Ok(()),
        }
    }

    /// Completes a value.
    fn finish_value(&mut self) {
        if self.config.trailing_mode() == Trailing::Newline {
            self.out.push(b'\n');
        }
        self.written += 1;
        self.in_progress = false;
    }
}

impl ser::Serializer for Serializer {
    fn drive(&mut self, driver: &mut SerializeDriver<'_>) -> Result<(), Error> {
        // only `drive_partial` continues a value
        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
    }

    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());
        }
        accept_raw(driver);
        let rollback = self.out.len();
        let (mut local, adopt) = match self.value.take() {
            // the writer writes into the output directly if it's empty,
            // otherwise its output is appended
            Some(mut writer) => {
                let adopt = self.out.is_empty();
                if adopt {
                    *writer.output() = Buffer::from_vec(core::mem::take(&mut self.out));
                }
                (writer, adopt)
            }
            None => {
                self.start_value()?;
                // a writer that completes the value at once is not boxed
                let out = Buffer::from_vec(core::mem::take(&mut self.out));
                let writer = self
                    .config
                    .value_writer(out, BytesFormat::of(driver.state()));
                if limit == usize::MAX {
                    return self.drive_whole(writer, driver, rollback);
                }
                (Box::new(writer), true)
            }
        };
        let rv = local.drive(driver, limit);
        match rv {
            Ok(done) => {
                let output = local.take_output();
                if adopt {
                    self.out = output;
                } else {
                    self.out.extend_from_slice(&output);
                }
                if done {
                    self.finish_value();
                    Ok(true)
                } else {
                    self.value = Some(local);
                    self.in_progress = true;
                    Ok(false)
                }
            }
            Err(err) => {
                // the value is abandoned, what was written of it is
                // discarded.  If parts of it were taken the stream stays
                // broken (`in_progress`).
                if adopt {
                    self.out = local.output().take();
                    self.out.truncate(rollback);
                }
                Err(err)
            }
        }
    }

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

impl Serializer {
    /// Writes a value at once (see `drive_partial`).
    fn drive_whole(
        &mut self,
        mut writer: ValueWriter,
        driver: &mut SerializeDriver<'_>,
        rollback: usize,
    ) -> Result<bool, Error> {
        let rv = writer.drive_whole(driver);
        self.out = writer.output().take();
        match rv {
            Ok(_) => {
                self.finish_value();
                Ok(true)
            }
            Err(err) => {
                self.out.truncate(rollback);
                Err(err)
            }
        }
    }
}

#[cfg(feature = "io")]
impl SerializerConfig {
    /// Creates a writer of a stream of values (see
    /// [`deser::io::Writer`](deser_core::io::Writer)).
    ///
    /// What follows the values depends on [`set_trailing`](Self::set_trailing).
    /// The output of large values is written in parts while they are
    /// serialized.
    ///
    /// ```
    /// use deser_json5::{SerializerConfig, Trailing};
    ///
    /// const LINES: SerializerConfig =
    ///     SerializerConfig::builder().trailing(Trailing::Newline).build();
    /// let mut writer = LINES.writer(Vec::new());
    /// writer.write(&1).unwrap();
    /// writer.write(&"x").unwrap();
    /// assert_eq!(writer.into_inner(), b"1\n\"x\"\n");
    /// ```
    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 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 JSON5 to a writer.
///
/// Like [`to_string`] the output is JSON except for NaN and infinite
/// floats.  The output of large values is written in parts while they are
/// serialized (see [`deser::io`](deser_core::io)), the writer does not
/// need to be buffered.
///
/// ```
/// let mut out = Vec::new();
/// deser_json5::to_writer(&mut out, &vec![f64::NAN]).unwrap();
/// assert_eq!(out, b"[NaN]");
/// ```
#[cfg(feature = "io")]
pub fn to_writer<W: std::io::Write, T: Serialize + ?Sized>(
    writer: W,
    value: &T,
) -> Result<(), Error> {
    JSON5_CONFIG.to_writer(writer, value)
}

/// The output of the serializer.
pub(crate) struct Output {
    pub(crate) out: Buffer,
    bytes: BytesFormat,
    // NaN and infinities are written as JSON5 literals instead of `null`
    non_finite_floats: bool,
}

#[derive(Clone, Copy, PartialEq, Eq)]
enum Container {
    Top,
    Seq,
    Map,
}

/// Holds the state of the serializer while writing.
pub(crate) struct Writer {
    ser: Output,
    // the state of the current container is held here, the state of the
    // outer containers is saved on the stack.
    stack: Vec<Container>,
    container: Container,
    first: bool,
    is_key: bool,
    // the output is passed on once it's this long (see `EventSink`)
    limit: usize,
}

impl EventSink for Writer {
    #[inline(always)]
    fn event(
        &mut self,
        event: Event<'_>,
        _value: SerializeRef<'_>,
        _state: &mut deser_core::State,
    ) -> Result<(), Error> {
        Writer::event(self, event)
    }

    #[inline(always)]
    fn pause(&mut self) -> bool {
        self.ser.out.len() >= self.limit
    }
}

impl Writer {
    #[inline(always)]
    fn event(&mut self, event: Event) -> Result<(), Error> {
        match event {
            Event::Atom(atom) => {
                if self.is_key {
                    self.ser.write_key_atom(atom, self.first)?;
                    self.is_key = false;
                } else {
                    match self.container {
                        Container::Seq => {
                            if !self.first {
                                self.ser.write_char(',');
                            }
                        }
                        Container::Map => self.is_key = true,
                        Container::Top => {}
                    }
                    self.ser.write_atom(atom)?;
                }
                self.first = false;
                Ok(())
            }
            Event::MapStart(_) => self.start(true),
            Event::SeqStart(_) => self.start(false),
            Event::MapEnd => self.end(true),
            Event::SeqEnd => self.end(false),
        }
    }

    #[inline]
    fn start(&mut self, is_map: bool) -> Result<(), Error> {
        if self.is_key {
            return Err(Error::new(
                ErrorKind::UnsupportedType,
                "JSON does not support this value for map keys",
            ));
        }
        if self.container == Container::Seq && !self.first {
            self.ser.write_char(',');
        }
        self.stack.push(self.container);
        self.first = true;
        if is_map {
            self.container = Container::Map;
            self.is_key = true;
            self.ser.write_char('{');
        } else {
            self.container = Container::Seq;
            self.ser.write_char('[');
        }
        Ok(())
    }

    #[inline]
    fn end(&mut self, is_map: bool) -> Result<(), Error> {
        if is_map {
            if self.container != Container::Map || !self.is_key {
                return Err(Error::new(ErrorKind::InvalidState, "unexpected map end"));
            }
            self.ser.write_char('}');
        } else {
            if self.container != Container::Seq {
                return Err(Error::new(ErrorKind::InvalidState, "unexpected array end"));
            }
            self.ser.write_char(']');
        }
        self.container = self.stack.pop().unwrap_or(Container::Top);
        // a container is never a key, so after it the next item in a map is
        // a key again.
        self.first = false;
        self.is_key = self.container == Container::Map;
        Ok(())
    }
}

impl Output {
    /// Writes an atom in key position including separator and colon.
    #[inline(always)]
    fn write_key_atom(&mut self, atom: Atom, first: bool) -> Result<(), Error> {
        // borrowed strings do not need to be dropped, the atom is only
        // dropped for the other values.
        let atom = ManuallyDrop::new(atom);
        match *atom {
            // fast path for the common case of string keys
            Atom::Str(ref val) | Atom::Lexical(ref val) if val.is_borrowed() => {
                self.write_key(val, first);
                Ok(())
            }
            _ => self.write_other_key_atom(ManuallyDrop::into_inner(atom), first),
        }
    }

    #[inline(never)]
    fn write_other_key_atom(&mut self, atom: Atom, first: bool) -> Result<(), Error> {
        if !first {
            self.write_char(',');
        }
        self.write_key_text(atom)?;
        self.write_char(':');
        Ok(())
    }

    /// Writes an atom as map key without separator and colon.
    pub(crate) fn write_key_text(&mut self, atom: Atom) -> Result<(), Error> {
        match atom {
            Atom::Str(ref val) | Atom::Lexical(ref val) => self.write_escaped_str(val),
            Atom::Char(c) => self.write_escaped_str(c.encode_utf8(&mut [0u8; 4])),
            Atom::U64(val) => {
                self.write_char('"');
                self.write_u64(val);
                self.write_char('"');
            }
            Atom::I64(val) => {
                self.write_char('"');
                self.write_i64(val);
                self.write_char('"');
            }
            Atom::Bool(val) => self.write_str(if val { "\"true\"" } else { "\"false\"" }),
            Atom::Ext(ref ext) => self.write_ext_key(ext)?,
            Atom::Bytes(ref val) => self.write_bytes_str(val, val.fallback),
            Atom::Implicit(ref val) => match json_literal(val) {
                Some(text) if val.value() != ImplicitValue::Null => self.write_escaped_str(text),
                _ => return self.write_key_text(val.value().to_atom()),
            },
            _ => {
                return Err(Error::new(
                    ErrorKind::UnsupportedType,
                    "JSON does not support this value for map keys",
                ));
            }
        }
        Ok(())
    }

    /// Writes an atom in value position.
    #[inline(always)]
    pub(crate) fn write_atom(&mut self, atom: Atom) -> Result<(), Error> {
        // borrowed strings and scalars do not need to be dropped, the atom
        // is only dropped for the other values.
        let atom = ManuallyDrop::new(atom);
        match *atom {
            Atom::Null => self.write_str("null"),
            Atom::Bool(true) => self.write_str("true"),
            Atom::Bool(false) => self.write_str("false"),
            Atom::Str(ref val) if val.is_borrowed() => self.write_escaped_str(val),
            Atom::Char(c) => self.write_escaped_str(c.encode_utf8(&mut [0u8; 4])),
            Atom::U64(val) => self.write_u64(val),
            Atom::I64(val) => self.write_i64(val),
            Atom::F64(val) => self.write_float(val),
            Atom::F32(val) => self.write_float(val),
            _ => return self.write_other_atom(ManuallyDrop::into_inner(atom)),
        }
        Ok(())
    }

    #[inline(never)]
    fn write_other_atom(&mut self, atom: Atom) -> Result<(), Error> {
        match atom {
            Atom::Str(ref val) | Atom::Lexical(ref val) => self.write_escaped_str(val),
            Atom::Ext(ref ext) => self.write_ext_value(ext)?,
            Atom::Bytes(ref val) => {
                self.write_bytes(val, val.fallback.copied().unwrap_or(self.bytes))
            }
            // values whose type was inferred from text keep their text if
            // it's the same value in JSON, otherwise they are written as
            // their value
            Atom::Implicit(ref val) => match json_literal(val) {
                Some(text) => self.write_str(text),
                None => return self.write_atom(val.value().to_atom()),
            },
            _ => return Err(Error::new(ErrorKind::UnsupportedType, "unknown atom")),
        }
        Ok(())
    }

    /// Writes bytes in the given format.
    fn write_bytes(&mut self, bytes: &[u8], format: BytesFormat) {
        match format.encode(bytes) {
            Some(encoded) => self.write_escaped_str(&encoded),
            None => {
                self.write_char('[');
                for (idx, &byte) in bytes.iter().enumerate() {
                    if idx > 0 {
                        self.write_char(',');
                    }
                    self.write_u64(byte.into());
                }
                self.write_char(']');
            }
        }
    }

    /// Writes bytes as string, for instance as map key.
    ///
    /// Bytes that would be sequences are base64.
    fn write_bytes_str(&mut self, bytes: &[u8], fallback: Option<&BytesFormat>) {
        let format = fallback.copied().unwrap_or(self.bytes);
        let encoded = format
            .encode(bytes)
            .or_else(|| BytesFormat::BASE64.encode(bytes))
            .unwrap_or_default();
        self.write_escaped_str(&encoded);
    }

    #[inline(always)]
    pub(crate) fn write_str(&mut self, s: &str) {
        self.out.push_str(s);
    }

    #[inline(always)]
    pub(crate) fn write_char(&mut self, c: char) {
        // checked here as `as u8` cuts off characters above 255.  The
        // characters are mostly constants, then the check is free.
        assert!(c.is_ascii(), "only ASCII characters can be written");
        self.out.push(c as u8);
    }

    /// Writes a map key including the separator and the colon.
    #[inline]
    fn write_key(&mut self, key: &str, first: bool) {
        if find_escape(key.as_bytes()) != key.len() {
            if !first {
                self.write_char(',');
            }
            self.write_escaped_str_slow(key);
            self.write_char(':');
            return;
        }
        self.out.reserve(key.len() + 4);
        // SAFETY: the capacity was reserved above, the bytes are ASCII
        unsafe {
            if !first {
                self.out.push_unchecked(b',');
            }
            self.out.push_unchecked(b'"');
            self.out.push_str_unchecked(key);
            self.out.push_unchecked(b'"');
            self.out.push_unchecked(b':');
        }
    }

    /// Writes a float with the shortest text that reads back as the same
    /// value of its type (`f32` or `f64`).
    #[inline]
    fn write_float<F: zmij::Float + Into<f64>>(&mut self, val: F) {
        let wide: f64 = val.into();
        if wide.is_finite() {
            self.write_str(zmij::Buffer::new().format_finite(val))
        } else {
            self.write_non_finite(wide)
        }
    }

    /// Writes NaN or an infinite float.
    #[cold]
    fn write_non_finite(&mut self, val: f64) {
        self.write_str(if !self.non_finite_floats {
            "null"
        } else if val.is_nan() {
            "NaN"
        } else if val > 0.0 {
            "Infinity"
        } else {
            "-Infinity"
        })
    }

    /// Writes an extension value as map key.
    ///
    /// Extension values that JSON does not natively support are written in
    /// their fallback representation.
    #[cold]
    fn write_ext_key(&mut self, ext: &ExtValue) -> Result<(), Error> {
        if ext.is::<u128>() || ext.is::<i128>() {
            self.write_char('"');
            self.write_ext_value(ext)?;
            self.write_char('"');
            return Ok(());
        }
        match ext.fallback() {
            Atom::Str(val) | Atom::Lexical(val) => self.write_escaped_str(&val),
            Atom::Char(c) => self.write_escaped_str(c.encode_utf8(&mut [0u8; 4])),
            Atom::U64(val) => {
                self.write_char('"');
                self.write_u64(val);
                self.write_char('"');
            }
            Atom::I64(val) => {
                self.write_char('"');
                self.write_i64(val);
                self.write_char('"');
            }
            Atom::Bool(val) => self.write_str(if val { "\"true\"" } else { "\"false\"" }),
            _ => {
                return Err(Error::new(
                    ErrorKind::UnsupportedType,
                    "JSON does not support this value for map keys",
                ));
            }
        }
        Ok(())
    }

    /// Writes an extension value.
    ///
    /// Extension values that JSON does not natively support are written in
    /// their fallback representation.
    #[cold]
    fn write_ext_value(&mut self, ext: &ExtValue) -> Result<(), Error> {
        // raw values of the dialect are written as they are, the
        // serialization only passes them on if they are (see `accept_raw`)
        if let Some(raw) = ext.downcast_value_ref::<RawInput>()
            && raw.is_format(&crate::raw::ID)
            && let Some(text) = raw.as_str()
        {
            self.write_str(text);
            return Ok(());
        }
        // JSON numbers have arbitrary precision, so wide integers and
        // decimals can be written natively.
        if let Some(&val) = ext.downcast_ref::<u128>() {
            self.write_int(val);
            return Ok(());
        } else if let Some(&val) = ext.downcast_ref::<i128>() {
            self.write_int(val);
            return Ok(());
        } else if let Some(val) = ext.downcast_ref::<BigInt>() {
            let text = val.to_string();
            check_number(&text)?;
            self.write_str(&text);
            return Ok(());
        } else if let Some(val) = ext.downcast_ref::<Decimal>() {
            // decimals use the syntax of JSON numbers
            check_number(val.as_str())?;
            self.write_str(val.as_str());
            return Ok(());
        } else if let Some(val) = ext.downcast_value_ref::<Number>() {
            // numbers keep their text, so they roundtrip exactly
            check_number(val.as_str())?;
            self.write_str(val.as_str());
            return Ok(());
        }
        match ext.fallback() {
            Atom::Null => self.write_str("null"),
            Atom::Bool(val) => self.write_str(if val { "true" } else { "false" }),
            Atom::Str(val) | Atom::Lexical(val) => self.write_escaped_str(&val),
            Atom::Char(c) => self.write_escaped_str(c.encode_utf8(&mut [0u8; 4])),
            Atom::U64(val) => self.write_u64(val),
            Atom::I64(val) => self.write_i64(val),
            Atom::F64(val) => self.write_float(val),
            Atom::F32(val) => self.write_float(val),
            // like in TOML the fallbacks of extension values are never
            // sequences
            Atom::Bytes(val) => self.write_bytes_str(&val, val.fallback),
            _ => {
                return Err(Error::new(
                    ErrorKind::UnsupportedType,
                    "JSON does not support this value",
                ));
            }
        }
        Ok(())
    }

    fn write_int<I: core::fmt::Display>(&mut self, val: I) {
        self.write_str(&val.to_string())
    }

    #[inline]
    fn write_u64(&mut self, val: u64) {
        self.write_str(itoa::Buffer::new().format(val))
    }

    #[inline]
    fn write_i64(&mut self, val: i64) {
        self.write_str(itoa::Buffer::new().format(val))
    }

    #[inline]
    fn write_escaped_str(&mut self, value: &str) {
        if find_escape(value.as_bytes()) != value.len() {
            return self.write_escaped_str_slow(value);
        }
        self.out.reserve(value.len() + 2);
        // SAFETY: the capacity was reserved above, the bytes are ASCII
        unsafe {
            self.out.push_unchecked(b'"');
            self.out.push_str_unchecked(value);
            self.out.push_unchecked(b'"');
        }
    }

    #[inline(never)]
    fn write_escaped_str_slow(&mut self, value: &str) {
        self.write_char('"');

        let bytes = value.as_bytes();
        let mut start = 0;

        loop {
            let next = skip_to_escape(bytes, start);
            if start < next {
                self.write_str(&value[start..next]);
            }
            if next == bytes.len() {
                break;
            }

            let byte = bytes[next];
            match ESCAPE[byte as usize] {
                self::BB => self.write_str("\\b"),
                self::TT => self.write_str("\\t"),
                self::NN => self.write_str("\\n"),
                self::FF => self.write_str("\\f"),
                self::RR => self.write_str("\\r"),
                self::QU => self.write_str("\\\""),
                self::BS => self.write_str("\\\\"),
                self::U => {
                    static HEX_DIGITS: [u8; 16] = *b"0123456789abcdef";
                    self.write_str("\\u00");
                    self.write_char(HEX_DIGITS[(byte >> 4) as usize] as char);
                    self.write_char(HEX_DIGITS[(byte & 0xF) as usize] as char);
                }
                _ => unreachable!(),
            }

            start = next + 1;
        }

        self.write_char('"');
    }
}

const BB: u8 = b'b'; // \x08
const TT: u8 = b't'; // \x09
const NN: u8 = b'n'; // \x0A
const FF: u8 = b'f'; // \x0C
const RR: u8 = b'r'; // \x0D
const QU: u8 = b'"'; // \x22
const BS: u8 = b'\\'; // \x5C
const U: u8 = b'u'; // \x00...\x1F except the ones above

// Lookup table of escape sequences. A value of b'x' at index i means that byte
// i is escaped as "\x" in JSON. A value of 0 means that byte i is not escaped.
#[rustfmt::skip]
static ESCAPE: [u8; 256] = [
    //  1   2   3   4   5   6   7   8   9   A   B   C   D   E   F
    U,  U,  U,  U,  U,  U,  U,  U, BB, TT, NN,  U, FF, RR,  U,  U, // 0
    U,  U,  U,  U,  U,  U,  U,  U,  U,  U,  U,  U,  U,  U,  U,  U, // 1
    0,  0, QU,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, // 2
    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, // 3
    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, // 4
    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, BS,  0,  0,  0, // 5
    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, // 6
    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, // 7
    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, // 8
    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, // 9
    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, // A
    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, // B
    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, // C
    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, // D
    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, // E
    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, // F
];

/// The configuration of [`to_string`] and [`to_writer`].
const JSON5_CONFIG: SerializerConfig = SerializerConfig::builder().non_finite_floats(true).build();

/// Serializes a value to JSON5.
///
/// The output is JSON, except for NaN and infinite floats which are
/// written as `NaN`, `Infinity` and `-Infinity` (the default
/// [`SerializerConfig`] writes them as `null`, see
/// [`SerializerConfig::set_non_finite_floats`]).
///
/// ```
/// let value = vec![1.0, f64::INFINITY];
/// assert_eq!(deser_json5::to_string(&value).unwrap(), "[1.0,Infinity]");
/// ```
#[inline]
pub fn to_string<T: Serialize + ?Sized>(value: &T) -> Result<String, Error> {
    JSON5_CONFIG.to_string(value)
}

/// Returns the text of an implicit value if it's a JSON literal for the
/// same value.
///
/// This keeps the text of numbers like `1.10` which would otherwise be
/// written as `1.1`.  Text that is not JSON (like `0x1F` or `~`) is not.
fn json_literal<'a>(value: &'a Implicit) -> Option<&'a str> {
    let text = value.text().as_str();
    let same = match value.value() {
        ImplicitValue::Null => text == "null",
        ImplicitValue::Bool(value) => text == if value { "true" } else { "false" },
        ImplicitValue::U64(value) => is_json_int(text) && text.parse::<u64>() == Ok(value),
        ImplicitValue::I64(value) => is_json_int(text) && text.parse::<i64>() == Ok(value),
        ImplicitValue::F64(value) => {
            value.is_finite()
                && Number::parse(text)
                    .is_ok_and(|x| !x.is_integer() && x.value().to_bits() == value.to_bits())
        }
        _ => false,
    };
    same.then_some(text)
}

/// Checks that the parser can read a number.
///
/// Numbers beyond the range of `f64` are an error when they are parsed
/// (also with exact numbers, which carry the value as `f64`).
#[cold]
fn check_number(text: &str) -> Result<(), Error> {
    match text.parse::<f64>() {
        Ok(value) if value.is_finite() => Ok(()),
        _ => Err(Error::new(ErrorKind::OutOfRange, "number out of range")),
    }
}

/// Checks the syntax of JSON integers (an optional minus and digits
/// without leading zeros).
fn is_json_int(text: &str) -> bool {
    let digits = text.strip_prefix('-').unwrap_or(text).as_bytes();
    match digits {
        [b'0'] => true,
        [b'1'..=b'9', rest @ ..] => rest.iter().all(u8::is_ascii_digit),
        _ => false,
    }
}