Coverage Report

Created: 2026-05-02 06:29

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/json/src/ser.rs
Line
Count
Source
1
//! Serialize a Rust data structure into JSON data.
2
3
use crate::error::{Error, ErrorCode, Result};
4
use crate::io;
5
use alloc::string::String;
6
#[cfg(feature = "raw_value")]
7
use alloc::string::ToString;
8
use alloc::vec::Vec;
9
use core::fmt::{self, Display};
10
use core::hint;
11
use core::num::FpCategory;
12
use core::str;
13
use serde::ser::{self, Impossible, Serialize};
14
15
/// A structure for serializing Rust values into JSON.
16
#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
17
pub struct Serializer<W, F = CompactFormatter> {
18
    writer: W,
19
    formatter: F,
20
}
21
22
impl<W> Serializer<W>
23
where
24
    W: io::Write,
25
{
26
    /// Creates a new JSON serializer.
27
    #[inline]
28
0
    pub fn new(writer: W) -> Self {
29
0
        Serializer::with_formatter(writer, CompactFormatter)
30
0
    }
31
}
32
33
impl<'a, W> Serializer<W, PrettyFormatter<'a>>
34
where
35
    W: io::Write,
36
{
37
    /// Creates a new JSON pretty print serializer.
38
    #[inline]
39
0
    pub fn pretty(writer: W) -> Self {
40
0
        Serializer::with_formatter(writer, PrettyFormatter::new())
41
0
    }
42
}
43
44
impl<W, F> Serializer<W, F>
45
where
46
    W: io::Write,
47
    F: Formatter,
48
{
49
    /// Creates a new JSON visitor whose output will be written to the writer
50
    /// specified.
51
    #[inline]
52
0
    pub fn with_formatter(writer: W, formatter: F) -> Self {
53
0
        Serializer { writer, formatter }
54
0
    }
Unexecuted instantiation: <serde_json::ser::Serializer<&mut <serde_json::value::Value as core::fmt::Display>::fmt::WriterFormatter>>::with_formatter
Unexecuted instantiation: <serde_json::ser::Serializer<&mut <serde_json::value::Value as core::fmt::Display>::fmt::WriterFormatter, serde_json::ser::PrettyFormatter>>::with_formatter
55
56
    /// Unwrap the `Writer` from the `Serializer`.
57
    #[inline]
58
    pub fn into_inner(self) -> W {
59
        self.writer
60
    }
61
}
62
63
impl<'a, W, F> ser::Serializer for &'a mut Serializer<W, F>
64
where
65
    W: io::Write,
66
    F: Formatter,
67
{
68
    type Ok = ();
69
    type Error = Error;
70
71
    type SerializeSeq = Compound<'a, W, F>;
72
    type SerializeTuple = Compound<'a, W, F>;
73
    type SerializeTupleStruct = Compound<'a, W, F>;
74
    type SerializeTupleVariant = Compound<'a, W, F>;
75
    type SerializeMap = Compound<'a, W, F>;
76
    type SerializeStruct = Compound<'a, W, F>;
77
    type SerializeStructVariant = Compound<'a, W, F>;
78
79
    #[inline]
80
0
    fn serialize_bool(self, value: bool) -> Result<()> {
81
0
        self.formatter
82
0
            .write_bool(&mut self.writer, value)
83
0
            .map_err(Error::io)
84
0
    }
Unexecuted instantiation: <&mut serde_json::ser::Serializer<&mut <serde_json::value::Value as core::fmt::Display>::fmt::WriterFormatter> as serde_core::ser::Serializer>::serialize_bool
Unexecuted instantiation: <&mut serde_json::ser::Serializer<&mut <serde_json::value::Value as core::fmt::Display>::fmt::WriterFormatter, serde_json::ser::PrettyFormatter> as serde_core::ser::Serializer>::serialize_bool
85
86
    #[inline]
87
    fn serialize_i8(self, value: i8) -> Result<()> {
88
        self.formatter
89
            .write_i8(&mut self.writer, value)
90
            .map_err(Error::io)
91
    }
92
93
    #[inline]
94
    fn serialize_i16(self, value: i16) -> Result<()> {
95
        self.formatter
96
            .write_i16(&mut self.writer, value)
97
            .map_err(Error::io)
98
    }
99
100
    #[inline]
101
    fn serialize_i32(self, value: i32) -> Result<()> {
102
        self.formatter
103
            .write_i32(&mut self.writer, value)
104
            .map_err(Error::io)
105
    }
106
107
    #[inline]
108
0
    fn serialize_i64(self, value: i64) -> Result<()> {
109
0
        self.formatter
110
0
            .write_i64(&mut self.writer, value)
111
0
            .map_err(Error::io)
112
0
    }
Unexecuted instantiation: <&mut serde_json::ser::Serializer<&mut <serde_json::value::Value as core::fmt::Display>::fmt::WriterFormatter> as serde_core::ser::Serializer>::serialize_i64
Unexecuted instantiation: <&mut serde_json::ser::Serializer<&mut <serde_json::value::Value as core::fmt::Display>::fmt::WriterFormatter, serde_json::ser::PrettyFormatter> as serde_core::ser::Serializer>::serialize_i64
113
114
    fn serialize_i128(self, value: i128) -> Result<()> {
115
        self.formatter
116
            .write_i128(&mut self.writer, value)
117
            .map_err(Error::io)
118
    }
119
120
    #[inline]
121
    fn serialize_u8(self, value: u8) -> Result<()> {
122
        self.formatter
123
            .write_u8(&mut self.writer, value)
124
            .map_err(Error::io)
125
    }
126
127
    #[inline]
128
    fn serialize_u16(self, value: u16) -> Result<()> {
129
        self.formatter
130
            .write_u16(&mut self.writer, value)
131
            .map_err(Error::io)
132
    }
133
134
    #[inline]
135
    fn serialize_u32(self, value: u32) -> Result<()> {
136
        self.formatter
137
            .write_u32(&mut self.writer, value)
138
            .map_err(Error::io)
139
    }
140
141
    #[inline]
142
0
    fn serialize_u64(self, value: u64) -> Result<()> {
143
0
        self.formatter
144
0
            .write_u64(&mut self.writer, value)
145
0
            .map_err(Error::io)
146
0
    }
Unexecuted instantiation: <&mut serde_json::ser::Serializer<&mut <serde_json::value::Value as core::fmt::Display>::fmt::WriterFormatter> as serde_core::ser::Serializer>::serialize_u64
Unexecuted instantiation: <&mut serde_json::ser::Serializer<&mut <serde_json::value::Value as core::fmt::Display>::fmt::WriterFormatter, serde_json::ser::PrettyFormatter> as serde_core::ser::Serializer>::serialize_u64
147
148
    fn serialize_u128(self, value: u128) -> Result<()> {
149
        self.formatter
150
            .write_u128(&mut self.writer, value)
151
            .map_err(Error::io)
152
    }
153
154
    #[inline]
155
    fn serialize_f32(self, value: f32) -> Result<()> {
156
        match value.classify() {
157
            FpCategory::Nan | FpCategory::Infinite => self
158
                .formatter
159
                .write_null(&mut self.writer)
160
                .map_err(Error::io),
161
            _ => self
162
                .formatter
163
                .write_f32(&mut self.writer, value)
164
                .map_err(Error::io),
165
        }
166
    }
167
168
    #[inline]
169
0
    fn serialize_f64(self, value: f64) -> Result<()> {
170
0
        match value.classify() {
171
0
            FpCategory::Nan | FpCategory::Infinite => self
172
0
                .formatter
173
0
                .write_null(&mut self.writer)
174
0
                .map_err(Error::io),
175
0
            _ => self
176
0
                .formatter
177
0
                .write_f64(&mut self.writer, value)
178
0
                .map_err(Error::io),
179
        }
180
0
    }
Unexecuted instantiation: <&mut serde_json::ser::Serializer<&mut <serde_json::value::Value as core::fmt::Display>::fmt::WriterFormatter> as serde_core::ser::Serializer>::serialize_f64
Unexecuted instantiation: <&mut serde_json::ser::Serializer<&mut <serde_json::value::Value as core::fmt::Display>::fmt::WriterFormatter, serde_json::ser::PrettyFormatter> as serde_core::ser::Serializer>::serialize_f64
181
182
    #[inline]
183
    fn serialize_char(self, value: char) -> Result<()> {
184
        // A char encoded as UTF-8 takes 4 bytes at most.
185
        let mut buf = [0; 4];
186
        self.serialize_str(value.encode_utf8(&mut buf))
187
    }
188
189
    #[inline]
190
0
    fn serialize_str(self, value: &str) -> Result<()> {
191
0
        format_escaped_str(&mut self.writer, &mut self.formatter, value).map_err(Error::io)
192
0
    }
Unexecuted instantiation: <&mut serde_json::ser::Serializer<&mut <serde_json::value::Value as core::fmt::Display>::fmt::WriterFormatter> as serde_core::ser::Serializer>::serialize_str
Unexecuted instantiation: <&mut serde_json::ser::Serializer<&mut <serde_json::value::Value as core::fmt::Display>::fmt::WriterFormatter, serde_json::ser::PrettyFormatter> as serde_core::ser::Serializer>::serialize_str
193
194
    #[inline]
195
    fn serialize_bytes(self, value: &[u8]) -> Result<()> {
196
        self.formatter
197
            .write_byte_array(&mut self.writer, value)
198
            .map_err(Error::io)
199
    }
200
201
    #[inline]
202
0
    fn serialize_unit(self) -> Result<()> {
203
0
        self.formatter
204
0
            .write_null(&mut self.writer)
205
0
            .map_err(Error::io)
206
0
    }
Unexecuted instantiation: <&mut serde_json::ser::Serializer<&mut <serde_json::value::Value as core::fmt::Display>::fmt::WriterFormatter> as serde_core::ser::Serializer>::serialize_unit
Unexecuted instantiation: <&mut serde_json::ser::Serializer<&mut <serde_json::value::Value as core::fmt::Display>::fmt::WriterFormatter, serde_json::ser::PrettyFormatter> as serde_core::ser::Serializer>::serialize_unit
207
208
    #[inline]
209
    fn serialize_unit_struct(self, _name: &'static str) -> Result<()> {
210
        self.serialize_unit()
211
    }
212
213
    #[inline]
214
    fn serialize_unit_variant(
215
        self,
216
        _name: &'static str,
217
        _variant_index: u32,
218
        variant: &'static str,
219
    ) -> Result<()> {
220
        self.serialize_str(variant)
221
    }
222
223
    /// Serialize newtypes without an object wrapper.
224
    #[inline]
225
    fn serialize_newtype_struct<T>(self, _name: &'static str, value: &T) -> Result<()>
226
    where
227
        T: ?Sized + Serialize,
228
    {
229
        value.serialize(self)
230
    }
231
232
    #[inline]
233
    fn serialize_newtype_variant<T>(
234
        self,
235
        _name: &'static str,
236
        _variant_index: u32,
237
        variant: &'static str,
238
        value: &T,
239
    ) -> Result<()>
240
    where
241
        T: ?Sized + Serialize,
242
    {
243
        tri!(self
244
            .formatter
245
            .begin_object(&mut self.writer)
246
            .map_err(Error::io));
247
        tri!(self
248
            .formatter
249
            .begin_object_key(&mut self.writer, true)
250
            .map_err(Error::io));
251
        tri!(self.serialize_str(variant));
252
        tri!(self
253
            .formatter
254
            .end_object_key(&mut self.writer)
255
            .map_err(Error::io));
256
        tri!(self
257
            .formatter
258
            .begin_object_value(&mut self.writer)
259
            .map_err(Error::io));
260
        tri!(value.serialize(&mut *self));
261
        tri!(self
262
            .formatter
263
            .end_object_value(&mut self.writer)
264
            .map_err(Error::io));
265
        self.formatter
266
            .end_object(&mut self.writer)
267
            .map_err(Error::io)
268
    }
269
270
    #[inline]
271
    fn serialize_none(self) -> Result<()> {
272
        self.serialize_unit()
273
    }
274
275
    #[inline]
276
    fn serialize_some<T>(self, value: &T) -> Result<()>
277
    where
278
        T: ?Sized + Serialize,
279
    {
280
        value.serialize(self)
281
    }
282
283
    #[inline]
284
0
    fn serialize_seq(self, len: Option<usize>) -> Result<Self::SerializeSeq> {
285
0
        tri!(self
286
0
            .formatter
287
0
            .begin_array(&mut self.writer)
288
0
            .map_err(Error::io));
289
0
        if len == Some(0) {
290
0
            tri!(self
291
0
                .formatter
292
0
                .end_array(&mut self.writer)
293
0
                .map_err(Error::io));
294
0
            Ok(Compound::Map {
295
0
                ser: self,
296
0
                state: State::Empty,
297
0
            })
298
        } else {
299
0
            Ok(Compound::Map {
300
0
                ser: self,
301
0
                state: State::First,
302
0
            })
303
        }
304
0
    }
Unexecuted instantiation: <&mut serde_json::ser::Serializer<&mut <serde_json::value::Value as core::fmt::Display>::fmt::WriterFormatter> as serde_core::ser::Serializer>::serialize_seq
Unexecuted instantiation: <&mut serde_json::ser::Serializer<&mut <serde_json::value::Value as core::fmt::Display>::fmt::WriterFormatter, serde_json::ser::PrettyFormatter> as serde_core::ser::Serializer>::serialize_seq
305
306
    #[inline]
307
    fn serialize_tuple(self, len: usize) -> Result<Self::SerializeTuple> {
308
        self.serialize_seq(Some(len))
309
    }
310
311
    #[inline]
312
    fn serialize_tuple_struct(
313
        self,
314
        _name: &'static str,
315
        len: usize,
316
    ) -> Result<Self::SerializeTupleStruct> {
317
        self.serialize_seq(Some(len))
318
    }
319
320
    #[inline]
321
    fn serialize_tuple_variant(
322
        self,
323
        _name: &'static str,
324
        _variant_index: u32,
325
        variant: &'static str,
326
        len: usize,
327
    ) -> Result<Self::SerializeTupleVariant> {
328
        tri!(self
329
            .formatter
330
            .begin_object(&mut self.writer)
331
            .map_err(Error::io));
332
        tri!(self
333
            .formatter
334
            .begin_object_key(&mut self.writer, true)
335
            .map_err(Error::io));
336
        tri!(self.serialize_str(variant));
337
        tri!(self
338
            .formatter
339
            .end_object_key(&mut self.writer)
340
            .map_err(Error::io));
341
        tri!(self
342
            .formatter
343
            .begin_object_value(&mut self.writer)
344
            .map_err(Error::io));
345
        self.serialize_seq(Some(len))
346
    }
347
348
    #[inline]
349
0
    fn serialize_map(self, len: Option<usize>) -> Result<Self::SerializeMap> {
350
0
        tri!(self
351
0
            .formatter
352
0
            .begin_object(&mut self.writer)
353
0
            .map_err(Error::io));
354
0
        if len == Some(0) {
355
0
            tri!(self
356
0
                .formatter
357
0
                .end_object(&mut self.writer)
358
0
                .map_err(Error::io));
359
0
            Ok(Compound::Map {
360
0
                ser: self,
361
0
                state: State::Empty,
362
0
            })
363
        } else {
364
0
            Ok(Compound::Map {
365
0
                ser: self,
366
0
                state: State::First,
367
0
            })
368
        }
369
0
    }
Unexecuted instantiation: <&mut serde_json::ser::Serializer<&mut <serde_json::value::Value as core::fmt::Display>::fmt::WriterFormatter> as serde_core::ser::Serializer>::serialize_map
Unexecuted instantiation: <&mut serde_json::ser::Serializer<&mut <serde_json::value::Value as core::fmt::Display>::fmt::WriterFormatter, serde_json::ser::PrettyFormatter> as serde_core::ser::Serializer>::serialize_map
370
371
    #[inline]
372
    fn serialize_struct(self, name: &'static str, len: usize) -> Result<Self::SerializeStruct> {
373
        match name {
374
            #[cfg(feature = "arbitrary_precision")]
375
            crate::number::TOKEN => Ok(Compound::Number { ser: self }),
376
            #[cfg(feature = "raw_value")]
377
            crate::raw::TOKEN => Ok(Compound::RawValue { ser: self }),
378
            _ => self.serialize_map(Some(len)),
379
        }
380
    }
381
382
    #[inline]
383
    fn serialize_struct_variant(
384
        self,
385
        _name: &'static str,
386
        _variant_index: u32,
387
        variant: &'static str,
388
        len: usize,
389
    ) -> Result<Self::SerializeStructVariant> {
390
        tri!(self
391
            .formatter
392
            .begin_object(&mut self.writer)
393
            .map_err(Error::io));
394
        tri!(self
395
            .formatter
396
            .begin_object_key(&mut self.writer, true)
397
            .map_err(Error::io));
398
        tri!(self.serialize_str(variant));
399
        tri!(self
400
            .formatter
401
            .end_object_key(&mut self.writer)
402
            .map_err(Error::io));
403
        tri!(self
404
            .formatter
405
            .begin_object_value(&mut self.writer)
406
            .map_err(Error::io));
407
        self.serialize_map(Some(len))
408
    }
409
410
    fn collect_str<T>(self, value: &T) -> Result<()>
411
    where
412
        T: ?Sized + Display,
413
    {
414
        use self::fmt::Write;
415
416
        struct Adapter<'ser, W: 'ser, F: 'ser> {
417
            writer: &'ser mut W,
418
            formatter: &'ser mut F,
419
            error: Option<io::Error>,
420
        }
421
422
        impl<'ser, W, F> Write for Adapter<'ser, W, F>
423
        where
424
            W: io::Write,
425
            F: Formatter,
426
        {
427
            fn write_str(&mut self, s: &str) -> fmt::Result {
428
                debug_assert!(self.error.is_none());
429
                match format_escaped_str_contents(self.writer, self.formatter, s) {
430
                    Ok(()) => Ok(()),
431
                    Err(err) => {
432
                        self.error = Some(err);
433
                        Err(fmt::Error)
434
                    }
435
                }
436
            }
437
        }
438
439
        tri!(self
440
            .formatter
441
            .begin_string(&mut self.writer)
442
            .map_err(Error::io));
443
        let mut adapter = Adapter {
444
            writer: &mut self.writer,
445
            formatter: &mut self.formatter,
446
            error: None,
447
        };
448
        match write!(adapter, "{}", value) {
449
            Ok(()) => debug_assert!(adapter.error.is_none()),
450
            Err(fmt::Error) => {
451
                return Err(Error::io(adapter.error.expect("there should be an error")));
452
            }
453
        }
454
        self.formatter
455
            .end_string(&mut self.writer)
456
            .map_err(Error::io)
457
    }
458
}
459
460
// Not public API. Should be pub(crate).
461
#[doc(hidden)]
462
#[derive(Eq, PartialEq)]
463
pub enum State {
464
    Empty,
465
    First,
466
    Rest,
467
}
468
469
// Not public API. Should be pub(crate).
470
#[doc(hidden)]
471
pub enum Compound<'a, W: 'a, F: 'a> {
472
    Map {
473
        ser: &'a mut Serializer<W, F>,
474
        state: State,
475
    },
476
    #[cfg(feature = "arbitrary_precision")]
477
    Number { ser: &'a mut Serializer<W, F> },
478
    #[cfg(feature = "raw_value")]
479
    RawValue { ser: &'a mut Serializer<W, F> },
480
}
481
482
impl<'a, W, F> ser::SerializeSeq for Compound<'a, W, F>
483
where
484
    W: io::Write,
485
    F: Formatter,
486
{
487
    type Ok = ();
488
    type Error = Error;
489
490
    #[inline]
491
0
    fn serialize_element<T>(&mut self, value: &T) -> Result<()>
492
0
    where
493
0
        T: ?Sized + Serialize,
494
    {
495
0
        match self {
496
0
            Compound::Map { ser, state } => {
497
0
                tri!(ser
498
0
                    .formatter
499
0
                    .begin_array_value(&mut ser.writer, *state == State::First)
500
0
                    .map_err(Error::io));
501
0
                *state = State::Rest;
502
0
                tri!(value.serialize(&mut **ser));
503
0
                ser.formatter
504
0
                    .end_array_value(&mut ser.writer)
505
0
                    .map_err(Error::io)
506
            }
507
            #[cfg(feature = "arbitrary_precision")]
508
            Compound::Number { .. } => unreachable!(),
509
            #[cfg(feature = "raw_value")]
510
            Compound::RawValue { .. } => unreachable!(),
511
        }
512
0
    }
Unexecuted instantiation: <serde_json::ser::Compound<&mut <serde_json::value::Value as core::fmt::Display>::fmt::WriterFormatter, serde_json::ser::PrettyFormatter> as serde_core::ser::SerializeSeq>::serialize_element::<&serde_json::value::Value>
Unexecuted instantiation: <serde_json::ser::Compound<&mut <serde_json::value::Value as core::fmt::Display>::fmt::WriterFormatter, serde_json::ser::CompactFormatter> as serde_core::ser::SerializeSeq>::serialize_element::<&serde_json::value::Value>
513
514
    #[inline]
515
0
    fn end(self) -> Result<()> {
516
0
        match self {
517
0
            Compound::Map { ser, state } => match state {
518
0
                State::Empty => Ok(()),
519
0
                _ => ser.formatter.end_array(&mut ser.writer).map_err(Error::io),
520
            },
521
            #[cfg(feature = "arbitrary_precision")]
522
            Compound::Number { .. } => unreachable!(),
523
            #[cfg(feature = "raw_value")]
524
            Compound::RawValue { .. } => unreachable!(),
525
        }
526
0
    }
Unexecuted instantiation: <serde_json::ser::Compound<&mut <serde_json::value::Value as core::fmt::Display>::fmt::WriterFormatter, serde_json::ser::PrettyFormatter> as serde_core::ser::SerializeSeq>::end
Unexecuted instantiation: <serde_json::ser::Compound<&mut <serde_json::value::Value as core::fmt::Display>::fmt::WriterFormatter, serde_json::ser::CompactFormatter> as serde_core::ser::SerializeSeq>::end
527
}
528
529
impl<'a, W, F> ser::SerializeTuple for Compound<'a, W, F>
530
where
531
    W: io::Write,
532
    F: Formatter,
533
{
534
    type Ok = ();
535
    type Error = Error;
536
537
    #[inline]
538
    fn serialize_element<T>(&mut self, value: &T) -> Result<()>
539
    where
540
        T: ?Sized + Serialize,
541
    {
542
        ser::SerializeSeq::serialize_element(self, value)
543
    }
544
545
    #[inline]
546
    fn end(self) -> Result<()> {
547
        ser::SerializeSeq::end(self)
548
    }
549
}
550
551
impl<'a, W, F> ser::SerializeTupleStruct for Compound<'a, W, F>
552
where
553
    W: io::Write,
554
    F: Formatter,
555
{
556
    type Ok = ();
557
    type Error = Error;
558
559
    #[inline]
560
    fn serialize_field<T>(&mut self, value: &T) -> Result<()>
561
    where
562
        T: ?Sized + Serialize,
563
    {
564
        ser::SerializeSeq::serialize_element(self, value)
565
    }
566
567
    #[inline]
568
    fn end(self) -> Result<()> {
569
        ser::SerializeSeq::end(self)
570
    }
571
}
572
573
impl<'a, W, F> ser::SerializeTupleVariant for Compound<'a, W, F>
574
where
575
    W: io::Write,
576
    F: Formatter,
577
{
578
    type Ok = ();
579
    type Error = Error;
580
581
    #[inline]
582
    fn serialize_field<T>(&mut self, value: &T) -> Result<()>
583
    where
584
        T: ?Sized + Serialize,
585
    {
586
        ser::SerializeSeq::serialize_element(self, value)
587
    }
588
589
    #[inline]
590
    fn end(self) -> Result<()> {
591
        match self {
592
            Compound::Map { ser, state } => {
593
                match state {
594
                    State::Empty => {}
595
                    _ => tri!(ser.formatter.end_array(&mut ser.writer).map_err(Error::io)),
596
                }
597
                tri!(ser
598
                    .formatter
599
                    .end_object_value(&mut ser.writer)
600
                    .map_err(Error::io));
601
                ser.formatter.end_object(&mut ser.writer).map_err(Error::io)
602
            }
603
            #[cfg(feature = "arbitrary_precision")]
604
            Compound::Number { .. } => unreachable!(),
605
            #[cfg(feature = "raw_value")]
606
            Compound::RawValue { .. } => unreachable!(),
607
        }
608
    }
609
}
610
611
impl<'a, W, F> ser::SerializeMap for Compound<'a, W, F>
612
where
613
    W: io::Write,
614
    F: Formatter,
615
{
616
    type Ok = ();
617
    type Error = Error;
618
619
    #[inline]
620
0
    fn serialize_key<T>(&mut self, key: &T) -> Result<()>
621
0
    where
622
0
        T: ?Sized + Serialize,
623
    {
624
0
        match self {
625
0
            Compound::Map { ser, state } => {
626
0
                tri!(ser
627
0
                    .formatter
628
0
                    .begin_object_key(&mut ser.writer, *state == State::First)
629
0
                    .map_err(Error::io));
630
0
                *state = State::Rest;
631
632
0
                tri!(key.serialize(MapKeySerializer { ser: *ser }));
633
634
0
                ser.formatter
635
0
                    .end_object_key(&mut ser.writer)
636
0
                    .map_err(Error::io)
637
            }
638
            #[cfg(feature = "arbitrary_precision")]
639
            Compound::Number { .. } => unreachable!(),
640
            #[cfg(feature = "raw_value")]
641
            Compound::RawValue { .. } => unreachable!(),
642
        }
643
0
    }
Unexecuted instantiation: <serde_json::ser::Compound<&mut <serde_json::value::Value as core::fmt::Display>::fmt::WriterFormatter, serde_json::ser::PrettyFormatter> as serde_core::ser::SerializeMap>::serialize_key::<alloc::string::String>
Unexecuted instantiation: <serde_json::ser::Compound<&mut <serde_json::value::Value as core::fmt::Display>::fmt::WriterFormatter, serde_json::ser::CompactFormatter> as serde_core::ser::SerializeMap>::serialize_key::<alloc::string::String>
644
645
    #[inline]
646
0
    fn serialize_value<T>(&mut self, value: &T) -> Result<()>
647
0
    where
648
0
        T: ?Sized + Serialize,
649
    {
650
0
        match self {
651
0
            Compound::Map { ser, .. } => {
652
0
                tri!(ser
653
0
                    .formatter
654
0
                    .begin_object_value(&mut ser.writer)
655
0
                    .map_err(Error::io));
656
0
                tri!(value.serialize(&mut **ser));
657
0
                ser.formatter
658
0
                    .end_object_value(&mut ser.writer)
659
0
                    .map_err(Error::io)
660
            }
661
            #[cfg(feature = "arbitrary_precision")]
662
            Compound::Number { .. } => unreachable!(),
663
            #[cfg(feature = "raw_value")]
664
            Compound::RawValue { .. } => unreachable!(),
665
        }
666
0
    }
Unexecuted instantiation: <serde_json::ser::Compound<&mut <serde_json::value::Value as core::fmt::Display>::fmt::WriterFormatter, serde_json::ser::PrettyFormatter> as serde_core::ser::SerializeMap>::serialize_value::<serde_json::value::Value>
Unexecuted instantiation: <serde_json::ser::Compound<&mut <serde_json::value::Value as core::fmt::Display>::fmt::WriterFormatter, serde_json::ser::CompactFormatter> as serde_core::ser::SerializeMap>::serialize_value::<serde_json::value::Value>
667
668
    #[inline]
669
0
    fn end(self) -> Result<()> {
670
0
        match self {
671
0
            Compound::Map { ser, state } => match state {
672
0
                State::Empty => Ok(()),
673
0
                _ => ser.formatter.end_object(&mut ser.writer).map_err(Error::io),
674
            },
675
            #[cfg(feature = "arbitrary_precision")]
676
            Compound::Number { .. } => unreachable!(),
677
            #[cfg(feature = "raw_value")]
678
            Compound::RawValue { .. } => unreachable!(),
679
        }
680
0
    }
Unexecuted instantiation: <serde_json::ser::Compound<&mut <serde_json::value::Value as core::fmt::Display>::fmt::WriterFormatter, serde_json::ser::PrettyFormatter> as serde_core::ser::SerializeMap>::end
Unexecuted instantiation: <serde_json::ser::Compound<&mut <serde_json::value::Value as core::fmt::Display>::fmt::WriterFormatter, serde_json::ser::CompactFormatter> as serde_core::ser::SerializeMap>::end
681
}
682
683
impl<'a, W, F> ser::SerializeStruct for Compound<'a, W, F>
684
where
685
    W: io::Write,
686
    F: Formatter,
687
{
688
    type Ok = ();
689
    type Error = Error;
690
691
    #[inline]
692
    fn serialize_field<T>(&mut self, key: &'static str, value: &T) -> Result<()>
693
    where
694
        T: ?Sized + Serialize,
695
    {
696
        match self {
697
            Compound::Map { .. } => ser::SerializeMap::serialize_entry(self, key, value),
698
            #[cfg(feature = "arbitrary_precision")]
699
            Compound::Number { ser, .. } => {
700
                if key == crate::number::TOKEN {
701
                    value.serialize(NumberStrEmitter(ser))
702
                } else {
703
                    Err(invalid_number())
704
                }
705
            }
706
            #[cfg(feature = "raw_value")]
707
            Compound::RawValue { ser, .. } => {
708
                if key == crate::raw::TOKEN {
709
                    value.serialize(RawValueStrEmitter(ser))
710
                } else {
711
                    Err(invalid_raw_value())
712
                }
713
            }
714
        }
715
    }
716
717
    #[inline]
718
    fn end(self) -> Result<()> {
719
        match self {
720
            Compound::Map { .. } => ser::SerializeMap::end(self),
721
            #[cfg(feature = "arbitrary_precision")]
722
            Compound::Number { .. } => Ok(()),
723
            #[cfg(feature = "raw_value")]
724
            Compound::RawValue { .. } => Ok(()),
725
        }
726
    }
727
}
728
729
impl<'a, W, F> ser::SerializeStructVariant for Compound<'a, W, F>
730
where
731
    W: io::Write,
732
    F: Formatter,
733
{
734
    type Ok = ();
735
    type Error = Error;
736
737
    #[inline]
738
    fn serialize_field<T>(&mut self, key: &'static str, value: &T) -> Result<()>
739
    where
740
        T: ?Sized + Serialize,
741
    {
742
        match *self {
743
            Compound::Map { .. } => ser::SerializeStruct::serialize_field(self, key, value),
744
            #[cfg(feature = "arbitrary_precision")]
745
            Compound::Number { .. } => unreachable!(),
746
            #[cfg(feature = "raw_value")]
747
            Compound::RawValue { .. } => unreachable!(),
748
        }
749
    }
750
751
    #[inline]
752
    fn end(self) -> Result<()> {
753
        match self {
754
            Compound::Map { ser, state } => {
755
                match state {
756
                    State::Empty => {}
757
                    _ => tri!(ser.formatter.end_object(&mut ser.writer).map_err(Error::io)),
758
                }
759
                tri!(ser
760
                    .formatter
761
                    .end_object_value(&mut ser.writer)
762
                    .map_err(Error::io));
763
                ser.formatter.end_object(&mut ser.writer).map_err(Error::io)
764
            }
765
            #[cfg(feature = "arbitrary_precision")]
766
            Compound::Number { .. } => unreachable!(),
767
            #[cfg(feature = "raw_value")]
768
            Compound::RawValue { .. } => unreachable!(),
769
        }
770
    }
771
}
772
773
struct MapKeySerializer<'a, W: 'a, F: 'a> {
774
    ser: &'a mut Serializer<W, F>,
775
}
776
777
#[cfg(feature = "arbitrary_precision")]
778
fn invalid_number() -> Error {
779
    Error::syntax(ErrorCode::InvalidNumber, 0, 0)
780
}
781
782
#[cfg(feature = "raw_value")]
783
fn invalid_raw_value() -> Error {
784
    Error::syntax(ErrorCode::ExpectedSomeValue, 0, 0)
785
}
786
787
0
fn key_must_be_a_string() -> Error {
788
0
    Error::syntax(ErrorCode::KeyMustBeAString, 0, 0)
789
0
}
790
791
0
fn float_key_must_be_finite() -> Error {
792
0
    Error::syntax(ErrorCode::FloatKeyMustBeFinite, 0, 0)
793
0
}
794
795
impl<'a, W, F> ser::Serializer for MapKeySerializer<'a, W, F>
796
where
797
    W: io::Write,
798
    F: Formatter,
799
{
800
    type Ok = ();
801
    type Error = Error;
802
803
    #[inline]
804
0
    fn serialize_str(self, value: &str) -> Result<()> {
805
0
        self.ser.serialize_str(value)
806
0
    }
Unexecuted instantiation: <serde_json::ser::MapKeySerializer<&mut <serde_json::value::Value as core::fmt::Display>::fmt::WriterFormatter, serde_json::ser::PrettyFormatter> as serde_core::ser::Serializer>::serialize_str
Unexecuted instantiation: <serde_json::ser::MapKeySerializer<&mut <serde_json::value::Value as core::fmt::Display>::fmt::WriterFormatter, serde_json::ser::CompactFormatter> as serde_core::ser::Serializer>::serialize_str
807
808
    #[inline]
809
    fn serialize_unit_variant(
810
        self,
811
        _name: &'static str,
812
        _variant_index: u32,
813
        variant: &'static str,
814
    ) -> Result<()> {
815
        self.ser.serialize_str(variant)
816
    }
817
818
    #[inline]
819
    fn serialize_newtype_struct<T>(self, _name: &'static str, value: &T) -> Result<()>
820
    where
821
        T: ?Sized + Serialize,
822
    {
823
        value.serialize(self)
824
    }
825
826
    type SerializeSeq = Impossible<(), Error>;
827
    type SerializeTuple = Impossible<(), Error>;
828
    type SerializeTupleStruct = Impossible<(), Error>;
829
    type SerializeTupleVariant = Impossible<(), Error>;
830
    type SerializeMap = Impossible<(), Error>;
831
    type SerializeStruct = Impossible<(), Error>;
832
    type SerializeStructVariant = Impossible<(), Error>;
833
834
    fn serialize_bool(self, value: bool) -> Result<()> {
835
        tri!(self
836
            .ser
837
            .formatter
838
            .begin_string(&mut self.ser.writer)
839
            .map_err(Error::io));
840
        tri!(self
841
            .ser
842
            .formatter
843
            .write_bool(&mut self.ser.writer, value)
844
            .map_err(Error::io));
845
        self.ser
846
            .formatter
847
            .end_string(&mut self.ser.writer)
848
            .map_err(Error::io)
849
    }
850
851
    fn serialize_i8(self, value: i8) -> Result<()> {
852
        tri!(self
853
            .ser
854
            .formatter
855
            .begin_string(&mut self.ser.writer)
856
            .map_err(Error::io));
857
        tri!(self
858
            .ser
859
            .formatter
860
            .write_i8(&mut self.ser.writer, value)
861
            .map_err(Error::io));
862
        self.ser
863
            .formatter
864
            .end_string(&mut self.ser.writer)
865
            .map_err(Error::io)
866
    }
867
868
    fn serialize_i16(self, value: i16) -> Result<()> {
869
        tri!(self
870
            .ser
871
            .formatter
872
            .begin_string(&mut self.ser.writer)
873
            .map_err(Error::io));
874
        tri!(self
875
            .ser
876
            .formatter
877
            .write_i16(&mut self.ser.writer, value)
878
            .map_err(Error::io));
879
        self.ser
880
            .formatter
881
            .end_string(&mut self.ser.writer)
882
            .map_err(Error::io)
883
    }
884
885
    fn serialize_i32(self, value: i32) -> Result<()> {
886
        tri!(self
887
            .ser
888
            .formatter
889
            .begin_string(&mut self.ser.writer)
890
            .map_err(Error::io));
891
        tri!(self
892
            .ser
893
            .formatter
894
            .write_i32(&mut self.ser.writer, value)
895
            .map_err(Error::io));
896
        self.ser
897
            .formatter
898
            .end_string(&mut self.ser.writer)
899
            .map_err(Error::io)
900
    }
901
902
    fn serialize_i64(self, value: i64) -> Result<()> {
903
        tri!(self
904
            .ser
905
            .formatter
906
            .begin_string(&mut self.ser.writer)
907
            .map_err(Error::io));
908
        tri!(self
909
            .ser
910
            .formatter
911
            .write_i64(&mut self.ser.writer, value)
912
            .map_err(Error::io));
913
        self.ser
914
            .formatter
915
            .end_string(&mut self.ser.writer)
916
            .map_err(Error::io)
917
    }
918
919
    fn serialize_i128(self, value: i128) -> Result<()> {
920
        tri!(self
921
            .ser
922
            .formatter
923
            .begin_string(&mut self.ser.writer)
924
            .map_err(Error::io));
925
        tri!(self
926
            .ser
927
            .formatter
928
            .write_i128(&mut self.ser.writer, value)
929
            .map_err(Error::io));
930
        self.ser
931
            .formatter
932
            .end_string(&mut self.ser.writer)
933
            .map_err(Error::io)
934
    }
935
936
    fn serialize_u8(self, value: u8) -> Result<()> {
937
        tri!(self
938
            .ser
939
            .formatter
940
            .begin_string(&mut self.ser.writer)
941
            .map_err(Error::io));
942
        tri!(self
943
            .ser
944
            .formatter
945
            .write_u8(&mut self.ser.writer, value)
946
            .map_err(Error::io));
947
        self.ser
948
            .formatter
949
            .end_string(&mut self.ser.writer)
950
            .map_err(Error::io)
951
    }
952
953
    fn serialize_u16(self, value: u16) -> Result<()> {
954
        tri!(self
955
            .ser
956
            .formatter
957
            .begin_string(&mut self.ser.writer)
958
            .map_err(Error::io));
959
        tri!(self
960
            .ser
961
            .formatter
962
            .write_u16(&mut self.ser.writer, value)
963
            .map_err(Error::io));
964
        self.ser
965
            .formatter
966
            .end_string(&mut self.ser.writer)
967
            .map_err(Error::io)
968
    }
969
970
    fn serialize_u32(self, value: u32) -> Result<()> {
971
        tri!(self
972
            .ser
973
            .formatter
974
            .begin_string(&mut self.ser.writer)
975
            .map_err(Error::io));
976
        tri!(self
977
            .ser
978
            .formatter
979
            .write_u32(&mut self.ser.writer, value)
980
            .map_err(Error::io));
981
        self.ser
982
            .formatter
983
            .end_string(&mut self.ser.writer)
984
            .map_err(Error::io)
985
    }
986
987
    fn serialize_u64(self, value: u64) -> Result<()> {
988
        tri!(self
989
            .ser
990
            .formatter
991
            .begin_string(&mut self.ser.writer)
992
            .map_err(Error::io));
993
        tri!(self
994
            .ser
995
            .formatter
996
            .write_u64(&mut self.ser.writer, value)
997
            .map_err(Error::io));
998
        self.ser
999
            .formatter
1000
            .end_string(&mut self.ser.writer)
1001
            .map_err(Error::io)
1002
    }
1003
1004
    fn serialize_u128(self, value: u128) -> Result<()> {
1005
        tri!(self
1006
            .ser
1007
            .formatter
1008
            .begin_string(&mut self.ser.writer)
1009
            .map_err(Error::io));
1010
        tri!(self
1011
            .ser
1012
            .formatter
1013
            .write_u128(&mut self.ser.writer, value)
1014
            .map_err(Error::io));
1015
        self.ser
1016
            .formatter
1017
            .end_string(&mut self.ser.writer)
1018
            .map_err(Error::io)
1019
    }
1020
1021
    fn serialize_f32(self, value: f32) -> Result<()> {
1022
        if !value.is_finite() {
1023
            return Err(float_key_must_be_finite());
1024
        }
1025
1026
        tri!(self
1027
            .ser
1028
            .formatter
1029
            .begin_string(&mut self.ser.writer)
1030
            .map_err(Error::io));
1031
        tri!(self
1032
            .ser
1033
            .formatter
1034
            .write_f32(&mut self.ser.writer, value)
1035
            .map_err(Error::io));
1036
        self.ser
1037
            .formatter
1038
            .end_string(&mut self.ser.writer)
1039
            .map_err(Error::io)
1040
    }
1041
1042
    fn serialize_f64(self, value: f64) -> Result<()> {
1043
        if !value.is_finite() {
1044
            return Err(float_key_must_be_finite());
1045
        }
1046
1047
        tri!(self
1048
            .ser
1049
            .formatter
1050
            .begin_string(&mut self.ser.writer)
1051
            .map_err(Error::io));
1052
        tri!(self
1053
            .ser
1054
            .formatter
1055
            .write_f64(&mut self.ser.writer, value)
1056
            .map_err(Error::io));
1057
        self.ser
1058
            .formatter
1059
            .end_string(&mut self.ser.writer)
1060
            .map_err(Error::io)
1061
    }
1062
1063
    fn serialize_char(self, value: char) -> Result<()> {
1064
        self.ser.serialize_str(value.encode_utf8(&mut [0u8; 4]))
1065
    }
1066
1067
    fn serialize_bytes(self, _value: &[u8]) -> Result<()> {
1068
        Err(key_must_be_a_string())
1069
    }
1070
1071
    fn serialize_unit(self) -> Result<()> {
1072
        Err(key_must_be_a_string())
1073
    }
1074
1075
    fn serialize_unit_struct(self, _name: &'static str) -> Result<()> {
1076
        Err(key_must_be_a_string())
1077
    }
1078
1079
    fn serialize_newtype_variant<T>(
1080
        self,
1081
        _name: &'static str,
1082
        _variant_index: u32,
1083
        _variant: &'static str,
1084
        _value: &T,
1085
    ) -> Result<()>
1086
    where
1087
        T: ?Sized + Serialize,
1088
    {
1089
        Err(key_must_be_a_string())
1090
    }
1091
1092
    fn serialize_none(self) -> Result<()> {
1093
        Err(key_must_be_a_string())
1094
    }
1095
1096
    fn serialize_some<T>(self, value: &T) -> Result<()>
1097
    where
1098
        T: ?Sized + Serialize,
1099
    {
1100
        value.serialize(self)
1101
    }
1102
1103
    fn serialize_seq(self, _len: Option<usize>) -> Result<Self::SerializeSeq> {
1104
        Err(key_must_be_a_string())
1105
    }
1106
1107
    fn serialize_tuple(self, _len: usize) -> Result<Self::SerializeTuple> {
1108
        Err(key_must_be_a_string())
1109
    }
1110
1111
    fn serialize_tuple_struct(
1112
        self,
1113
        _name: &'static str,
1114
        _len: usize,
1115
    ) -> Result<Self::SerializeTupleStruct> {
1116
        Err(key_must_be_a_string())
1117
    }
1118
1119
    fn serialize_tuple_variant(
1120
        self,
1121
        _name: &'static str,
1122
        _variant_index: u32,
1123
        _variant: &'static str,
1124
        _len: usize,
1125
    ) -> Result<Self::SerializeTupleVariant> {
1126
        Err(key_must_be_a_string())
1127
    }
1128
1129
    fn serialize_map(self, _len: Option<usize>) -> Result<Self::SerializeMap> {
1130
        Err(key_must_be_a_string())
1131
    }
1132
1133
    fn serialize_struct(self, _name: &'static str, _len: usize) -> Result<Self::SerializeStruct> {
1134
        Err(key_must_be_a_string())
1135
    }
1136
1137
    fn serialize_struct_variant(
1138
        self,
1139
        _name: &'static str,
1140
        _variant_index: u32,
1141
        _variant: &'static str,
1142
        _len: usize,
1143
    ) -> Result<Self::SerializeStructVariant> {
1144
        Err(key_must_be_a_string())
1145
    }
1146
1147
    fn collect_str<T>(self, value: &T) -> Result<()>
1148
    where
1149
        T: ?Sized + Display,
1150
    {
1151
        self.ser.collect_str(value)
1152
    }
1153
}
1154
1155
#[cfg(feature = "arbitrary_precision")]
1156
struct NumberStrEmitter<'a, W: 'a + io::Write, F: 'a + Formatter>(&'a mut Serializer<W, F>);
1157
1158
#[cfg(feature = "arbitrary_precision")]
1159
impl<'a, W: io::Write, F: Formatter> ser::Serializer for NumberStrEmitter<'a, W, F> {
1160
    type Ok = ();
1161
    type Error = Error;
1162
1163
    type SerializeSeq = Impossible<(), Error>;
1164
    type SerializeTuple = Impossible<(), Error>;
1165
    type SerializeTupleStruct = Impossible<(), Error>;
1166
    type SerializeTupleVariant = Impossible<(), Error>;
1167
    type SerializeMap = Impossible<(), Error>;
1168
    type SerializeStruct = Impossible<(), Error>;
1169
    type SerializeStructVariant = Impossible<(), Error>;
1170
1171
    fn serialize_bool(self, _v: bool) -> Result<()> {
1172
        Err(invalid_number())
1173
    }
1174
1175
    fn serialize_i8(self, _v: i8) -> Result<()> {
1176
        Err(invalid_number())
1177
    }
1178
1179
    fn serialize_i16(self, _v: i16) -> Result<()> {
1180
        Err(invalid_number())
1181
    }
1182
1183
    fn serialize_i32(self, _v: i32) -> Result<()> {
1184
        Err(invalid_number())
1185
    }
1186
1187
    fn serialize_i64(self, _v: i64) -> Result<()> {
1188
        Err(invalid_number())
1189
    }
1190
1191
    fn serialize_i128(self, _v: i128) -> Result<()> {
1192
        Err(invalid_number())
1193
    }
1194
1195
    fn serialize_u8(self, _v: u8) -> Result<()> {
1196
        Err(invalid_number())
1197
    }
1198
1199
    fn serialize_u16(self, _v: u16) -> Result<()> {
1200
        Err(invalid_number())
1201
    }
1202
1203
    fn serialize_u32(self, _v: u32) -> Result<()> {
1204
        Err(invalid_number())
1205
    }
1206
1207
    fn serialize_u64(self, _v: u64) -> Result<()> {
1208
        Err(invalid_number())
1209
    }
1210
1211
    fn serialize_u128(self, _v: u128) -> Result<()> {
1212
        Err(invalid_number())
1213
    }
1214
1215
    fn serialize_f32(self, _v: f32) -> Result<()> {
1216
        Err(invalid_number())
1217
    }
1218
1219
    fn serialize_f64(self, _v: f64) -> Result<()> {
1220
        Err(invalid_number())
1221
    }
1222
1223
    fn serialize_char(self, _v: char) -> Result<()> {
1224
        Err(invalid_number())
1225
    }
1226
1227
    fn serialize_str(self, value: &str) -> Result<()> {
1228
        let NumberStrEmitter(serializer) = self;
1229
        serializer
1230
            .formatter
1231
            .write_number_str(&mut serializer.writer, value)
1232
            .map_err(Error::io)
1233
    }
1234
1235
    fn serialize_bytes(self, _value: &[u8]) -> Result<()> {
1236
        Err(invalid_number())
1237
    }
1238
1239
    fn serialize_none(self) -> Result<()> {
1240
        Err(invalid_number())
1241
    }
1242
1243
    fn serialize_some<T>(self, _value: &T) -> Result<()>
1244
    where
1245
        T: ?Sized + Serialize,
1246
    {
1247
        Err(invalid_number())
1248
    }
1249
1250
    fn serialize_unit(self) -> Result<()> {
1251
        Err(invalid_number())
1252
    }
1253
1254
    fn serialize_unit_struct(self, _name: &'static str) -> Result<()> {
1255
        Err(invalid_number())
1256
    }
1257
1258
    fn serialize_unit_variant(
1259
        self,
1260
        _name: &'static str,
1261
        _variant_index: u32,
1262
        _variant: &'static str,
1263
    ) -> Result<()> {
1264
        Err(invalid_number())
1265
    }
1266
1267
    fn serialize_newtype_struct<T>(self, _name: &'static str, _value: &T) -> Result<()>
1268
    where
1269
        T: ?Sized + Serialize,
1270
    {
1271
        Err(invalid_number())
1272
    }
1273
1274
    fn serialize_newtype_variant<T>(
1275
        self,
1276
        _name: &'static str,
1277
        _variant_index: u32,
1278
        _variant: &'static str,
1279
        _value: &T,
1280
    ) -> Result<()>
1281
    where
1282
        T: ?Sized + Serialize,
1283
    {
1284
        Err(invalid_number())
1285
    }
1286
1287
    fn serialize_seq(self, _len: Option<usize>) -> Result<Self::SerializeSeq> {
1288
        Err(invalid_number())
1289
    }
1290
1291
    fn serialize_tuple(self, _len: usize) -> Result<Self::SerializeTuple> {
1292
        Err(invalid_number())
1293
    }
1294
1295
    fn serialize_tuple_struct(
1296
        self,
1297
        _name: &'static str,
1298
        _len: usize,
1299
    ) -> Result<Self::SerializeTupleStruct> {
1300
        Err(invalid_number())
1301
    }
1302
1303
    fn serialize_tuple_variant(
1304
        self,
1305
        _name: &'static str,
1306
        _variant_index: u32,
1307
        _variant: &'static str,
1308
        _len: usize,
1309
    ) -> Result<Self::SerializeTupleVariant> {
1310
        Err(invalid_number())
1311
    }
1312
1313
    fn serialize_map(self, _len: Option<usize>) -> Result<Self::SerializeMap> {
1314
        Err(invalid_number())
1315
    }
1316
1317
    fn serialize_struct(self, _name: &'static str, _len: usize) -> Result<Self::SerializeStruct> {
1318
        Err(invalid_number())
1319
    }
1320
1321
    fn serialize_struct_variant(
1322
        self,
1323
        _name: &'static str,
1324
        _variant_index: u32,
1325
        _variant: &'static str,
1326
        _len: usize,
1327
    ) -> Result<Self::SerializeStructVariant> {
1328
        Err(invalid_number())
1329
    }
1330
}
1331
1332
#[cfg(feature = "raw_value")]
1333
struct RawValueStrEmitter<'a, W: 'a + io::Write, F: 'a + Formatter>(&'a mut Serializer<W, F>);
1334
1335
#[cfg(feature = "raw_value")]
1336
impl<'a, W: io::Write, F: Formatter> ser::Serializer for RawValueStrEmitter<'a, W, F> {
1337
    type Ok = ();
1338
    type Error = Error;
1339
1340
    type SerializeSeq = Impossible<(), Error>;
1341
    type SerializeTuple = Impossible<(), Error>;
1342
    type SerializeTupleStruct = Impossible<(), Error>;
1343
    type SerializeTupleVariant = Impossible<(), Error>;
1344
    type SerializeMap = Impossible<(), Error>;
1345
    type SerializeStruct = Impossible<(), Error>;
1346
    type SerializeStructVariant = Impossible<(), Error>;
1347
1348
    fn serialize_bool(self, _v: bool) -> Result<()> {
1349
        Err(ser::Error::custom("expected RawValue"))
1350
    }
1351
1352
    fn serialize_i8(self, _v: i8) -> Result<()> {
1353
        Err(ser::Error::custom("expected RawValue"))
1354
    }
1355
1356
    fn serialize_i16(self, _v: i16) -> Result<()> {
1357
        Err(ser::Error::custom("expected RawValue"))
1358
    }
1359
1360
    fn serialize_i32(self, _v: i32) -> Result<()> {
1361
        Err(ser::Error::custom("expected RawValue"))
1362
    }
1363
1364
    fn serialize_i64(self, _v: i64) -> Result<()> {
1365
        Err(ser::Error::custom("expected RawValue"))
1366
    }
1367
1368
    fn serialize_i128(self, _v: i128) -> Result<()> {
1369
        Err(ser::Error::custom("expected RawValue"))
1370
    }
1371
1372
    fn serialize_u8(self, _v: u8) -> Result<()> {
1373
        Err(ser::Error::custom("expected RawValue"))
1374
    }
1375
1376
    fn serialize_u16(self, _v: u16) -> Result<()> {
1377
        Err(ser::Error::custom("expected RawValue"))
1378
    }
1379
1380
    fn serialize_u32(self, _v: u32) -> Result<()> {
1381
        Err(ser::Error::custom("expected RawValue"))
1382
    }
1383
1384
    fn serialize_u64(self, _v: u64) -> Result<()> {
1385
        Err(ser::Error::custom("expected RawValue"))
1386
    }
1387
1388
    fn serialize_u128(self, _v: u128) -> Result<()> {
1389
        Err(ser::Error::custom("expected RawValue"))
1390
    }
1391
1392
    fn serialize_f32(self, _v: f32) -> Result<()> {
1393
        Err(ser::Error::custom("expected RawValue"))
1394
    }
1395
1396
    fn serialize_f64(self, _v: f64) -> Result<()> {
1397
        Err(ser::Error::custom("expected RawValue"))
1398
    }
1399
1400
    fn serialize_char(self, _v: char) -> Result<()> {
1401
        Err(ser::Error::custom("expected RawValue"))
1402
    }
1403
1404
    fn serialize_str(self, value: &str) -> Result<()> {
1405
        let RawValueStrEmitter(serializer) = self;
1406
        serializer
1407
            .formatter
1408
            .write_raw_fragment(&mut serializer.writer, value)
1409
            .map_err(Error::io)
1410
    }
1411
1412
    fn serialize_bytes(self, _value: &[u8]) -> Result<()> {
1413
        Err(ser::Error::custom("expected RawValue"))
1414
    }
1415
1416
    fn serialize_none(self) -> Result<()> {
1417
        Err(ser::Error::custom("expected RawValue"))
1418
    }
1419
1420
    fn serialize_some<T>(self, _value: &T) -> Result<()>
1421
    where
1422
        T: ?Sized + Serialize,
1423
    {
1424
        Err(ser::Error::custom("expected RawValue"))
1425
    }
1426
1427
    fn serialize_unit(self) -> Result<()> {
1428
        Err(ser::Error::custom("expected RawValue"))
1429
    }
1430
1431
    fn serialize_unit_struct(self, _name: &'static str) -> Result<()> {
1432
        Err(ser::Error::custom("expected RawValue"))
1433
    }
1434
1435
    fn serialize_unit_variant(
1436
        self,
1437
        _name: &'static str,
1438
        _variant_index: u32,
1439
        _variant: &'static str,
1440
    ) -> Result<()> {
1441
        Err(ser::Error::custom("expected RawValue"))
1442
    }
1443
1444
    fn serialize_newtype_struct<T>(self, _name: &'static str, _value: &T) -> Result<()>
1445
    where
1446
        T: ?Sized + Serialize,
1447
    {
1448
        Err(ser::Error::custom("expected RawValue"))
1449
    }
1450
1451
    fn serialize_newtype_variant<T>(
1452
        self,
1453
        _name: &'static str,
1454
        _variant_index: u32,
1455
        _variant: &'static str,
1456
        _value: &T,
1457
    ) -> Result<()>
1458
    where
1459
        T: ?Sized + Serialize,
1460
    {
1461
        Err(ser::Error::custom("expected RawValue"))
1462
    }
1463
1464
    fn serialize_seq(self, _len: Option<usize>) -> Result<Self::SerializeSeq> {
1465
        Err(ser::Error::custom("expected RawValue"))
1466
    }
1467
1468
    fn serialize_tuple(self, _len: usize) -> Result<Self::SerializeTuple> {
1469
        Err(ser::Error::custom("expected RawValue"))
1470
    }
1471
1472
    fn serialize_tuple_struct(
1473
        self,
1474
        _name: &'static str,
1475
        _len: usize,
1476
    ) -> Result<Self::SerializeTupleStruct> {
1477
        Err(ser::Error::custom("expected RawValue"))
1478
    }
1479
1480
    fn serialize_tuple_variant(
1481
        self,
1482
        _name: &'static str,
1483
        _variant_index: u32,
1484
        _variant: &'static str,
1485
        _len: usize,
1486
    ) -> Result<Self::SerializeTupleVariant> {
1487
        Err(ser::Error::custom("expected RawValue"))
1488
    }
1489
1490
    fn serialize_map(self, _len: Option<usize>) -> Result<Self::SerializeMap> {
1491
        Err(ser::Error::custom("expected RawValue"))
1492
    }
1493
1494
    fn serialize_struct(self, _name: &'static str, _len: usize) -> Result<Self::SerializeStruct> {
1495
        Err(ser::Error::custom("expected RawValue"))
1496
    }
1497
1498
    fn serialize_struct_variant(
1499
        self,
1500
        _name: &'static str,
1501
        _variant_index: u32,
1502
        _variant: &'static str,
1503
        _len: usize,
1504
    ) -> Result<Self::SerializeStructVariant> {
1505
        Err(ser::Error::custom("expected RawValue"))
1506
    }
1507
1508
    fn collect_str<T>(self, value: &T) -> Result<Self::Ok>
1509
    where
1510
        T: ?Sized + Display,
1511
    {
1512
        self.serialize_str(&value.to_string())
1513
    }
1514
}
1515
1516
/// Represents a character escape code in a type-safe manner.
1517
pub enum CharEscape {
1518
    /// An escaped quote `"`
1519
    Quote,
1520
    /// An escaped reverse solidus `\`
1521
    ReverseSolidus,
1522
    /// An escaped solidus `/`
1523
    Solidus,
1524
    /// An escaped backspace character (usually escaped as `\b`)
1525
    Backspace,
1526
    /// An escaped form feed character (usually escaped as `\f`)
1527
    FormFeed,
1528
    /// An escaped line feed character (usually escaped as `\n`)
1529
    LineFeed,
1530
    /// An escaped carriage return character (usually escaped as `\r`)
1531
    CarriageReturn,
1532
    /// An escaped tab character (usually escaped as `\t`)
1533
    Tab,
1534
    /// An escaped ASCII plane control character (usually escaped as
1535
    /// `\u00XX` where `XX` are two hex characters)
1536
    AsciiControl(u8),
1537
}
1538
1539
/// This trait abstracts away serializing the JSON control characters, which allows the user to
1540
/// optionally pretty print the JSON output.
1541
pub trait Formatter {
1542
    /// Writes a `null` value to the specified writer.
1543
    #[inline]
1544
0
    fn write_null<W>(&mut self, writer: &mut W) -> io::Result<()>
1545
0
    where
1546
0
        W: ?Sized + io::Write,
1547
    {
1548
0
        writer.write_all(b"null")
1549
0
    }
Unexecuted instantiation: <serde_json::ser::PrettyFormatter as serde_json::ser::Formatter>::write_null::<&mut <serde_json::value::Value as core::fmt::Display>::fmt::WriterFormatter>
Unexecuted instantiation: <serde_json::ser::CompactFormatter as serde_json::ser::Formatter>::write_null::<&mut <serde_json::value::Value as core::fmt::Display>::fmt::WriterFormatter>
1550
1551
    /// Writes a `true` or `false` value to the specified writer.
1552
    #[inline]
1553
0
    fn write_bool<W>(&mut self, writer: &mut W, value: bool) -> io::Result<()>
1554
0
    where
1555
0
        W: ?Sized + io::Write,
1556
    {
1557
0
        let s = if value {
1558
0
            b"true" as &[u8]
1559
        } else {
1560
0
            b"false" as &[u8]
1561
        };
1562
0
        writer.write_all(s)
1563
0
    }
Unexecuted instantiation: <serde_json::ser::PrettyFormatter as serde_json::ser::Formatter>::write_bool::<&mut <serde_json::value::Value as core::fmt::Display>::fmt::WriterFormatter>
Unexecuted instantiation: <serde_json::ser::CompactFormatter as serde_json::ser::Formatter>::write_bool::<&mut <serde_json::value::Value as core::fmt::Display>::fmt::WriterFormatter>
1564
1565
    /// Writes an integer value like `-123` to the specified writer.
1566
    #[inline]
1567
    fn write_i8<W>(&mut self, writer: &mut W, value: i8) -> io::Result<()>
1568
    where
1569
        W: ?Sized + io::Write,
1570
    {
1571
        let mut buffer = itoa::Buffer::new();
1572
        let s = buffer.format(value);
1573
        writer.write_all(s.as_bytes())
1574
    }
1575
1576
    /// Writes an integer value like `-123` to the specified writer.
1577
    #[inline]
1578
    fn write_i16<W>(&mut self, writer: &mut W, value: i16) -> io::Result<()>
1579
    where
1580
        W: ?Sized + io::Write,
1581
    {
1582
        let mut buffer = itoa::Buffer::new();
1583
        let s = buffer.format(value);
1584
        writer.write_all(s.as_bytes())
1585
    }
1586
1587
    /// Writes an integer value like `-123` to the specified writer.
1588
    #[inline]
1589
    fn write_i32<W>(&mut self, writer: &mut W, value: i32) -> io::Result<()>
1590
    where
1591
        W: ?Sized + io::Write,
1592
    {
1593
        let mut buffer = itoa::Buffer::new();
1594
        let s = buffer.format(value);
1595
        writer.write_all(s.as_bytes())
1596
    }
1597
1598
    /// Writes an integer value like `-123` to the specified writer.
1599
    #[inline]
1600
0
    fn write_i64<W>(&mut self, writer: &mut W, value: i64) -> io::Result<()>
1601
0
    where
1602
0
        W: ?Sized + io::Write,
1603
    {
1604
0
        let mut buffer = itoa::Buffer::new();
1605
0
        let s = buffer.format(value);
1606
0
        writer.write_all(s.as_bytes())
1607
0
    }
Unexecuted instantiation: <serde_json::ser::PrettyFormatter as serde_json::ser::Formatter>::write_i64::<&mut <serde_json::value::Value as core::fmt::Display>::fmt::WriterFormatter>
Unexecuted instantiation: <serde_json::ser::CompactFormatter as serde_json::ser::Formatter>::write_i64::<&mut <serde_json::value::Value as core::fmt::Display>::fmt::WriterFormatter>
1608
1609
    /// Writes an integer value like `-123` to the specified writer.
1610
    #[inline]
1611
    fn write_i128<W>(&mut self, writer: &mut W, value: i128) -> io::Result<()>
1612
    where
1613
        W: ?Sized + io::Write,
1614
    {
1615
        let mut buffer = itoa::Buffer::new();
1616
        let s = buffer.format(value);
1617
        writer.write_all(s.as_bytes())
1618
    }
1619
1620
    /// Writes an integer value like `123` to the specified writer.
1621
    #[inline]
1622
    fn write_u8<W>(&mut self, writer: &mut W, value: u8) -> io::Result<()>
1623
    where
1624
        W: ?Sized + io::Write,
1625
    {
1626
        let mut buffer = itoa::Buffer::new();
1627
        let s = buffer.format(value);
1628
        writer.write_all(s.as_bytes())
1629
    }
1630
1631
    /// Writes an integer value like `123` to the specified writer.
1632
    #[inline]
1633
    fn write_u16<W>(&mut self, writer: &mut W, value: u16) -> io::Result<()>
1634
    where
1635
        W: ?Sized + io::Write,
1636
    {
1637
        let mut buffer = itoa::Buffer::new();
1638
        let s = buffer.format(value);
1639
        writer.write_all(s.as_bytes())
1640
    }
1641
1642
    /// Writes an integer value like `123` to the specified writer.
1643
    #[inline]
1644
    fn write_u32<W>(&mut self, writer: &mut W, value: u32) -> io::Result<()>
1645
    where
1646
        W: ?Sized + io::Write,
1647
    {
1648
        let mut buffer = itoa::Buffer::new();
1649
        let s = buffer.format(value);
1650
        writer.write_all(s.as_bytes())
1651
    }
1652
1653
    /// Writes an integer value like `123` to the specified writer.
1654
    #[inline]
1655
0
    fn write_u64<W>(&mut self, writer: &mut W, value: u64) -> io::Result<()>
1656
0
    where
1657
0
        W: ?Sized + io::Write,
1658
    {
1659
0
        let mut buffer = itoa::Buffer::new();
1660
0
        let s = buffer.format(value);
1661
0
        writer.write_all(s.as_bytes())
1662
0
    }
Unexecuted instantiation: <serde_json::ser::PrettyFormatter as serde_json::ser::Formatter>::write_u64::<&mut <serde_json::value::Value as core::fmt::Display>::fmt::WriterFormatter>
Unexecuted instantiation: <serde_json::ser::CompactFormatter as serde_json::ser::Formatter>::write_u64::<&mut <serde_json::value::Value as core::fmt::Display>::fmt::WriterFormatter>
1663
1664
    /// Writes an integer value like `123` to the specified writer.
1665
    #[inline]
1666
    fn write_u128<W>(&mut self, writer: &mut W, value: u128) -> io::Result<()>
1667
    where
1668
        W: ?Sized + io::Write,
1669
    {
1670
        let mut buffer = itoa::Buffer::new();
1671
        let s = buffer.format(value);
1672
        writer.write_all(s.as_bytes())
1673
    }
1674
1675
    /// Writes a floating point value like `-31.26e+12` to the specified writer.
1676
    ///
1677
    /// # Special cases
1678
    ///
1679
    /// This function **does not** check for NaN or infinity. If the input
1680
    /// number is not a finite float, the printed representation will be some
1681
    /// correctly formatted but unspecified numerical value.
1682
    ///
1683
    /// Please check [`is_finite`] yourself before calling this function, or
1684
    /// check [`is_nan`] and [`is_infinite`] and handle those cases yourself
1685
    /// with a different `Formatter` method.
1686
    ///
1687
    /// [`is_finite`]: f32::is_finite
1688
    /// [`is_nan`]: f32::is_nan
1689
    /// [`is_infinite`]: f32::is_infinite
1690
    #[inline]
1691
    fn write_f32<W>(&mut self, writer: &mut W, value: f32) -> io::Result<()>
1692
    where
1693
        W: ?Sized + io::Write,
1694
    {
1695
        let mut buffer = zmij::Buffer::new();
1696
        let s = buffer.format_finite(value);
1697
        writer.write_all(s.as_bytes())
1698
    }
1699
1700
    /// Writes a floating point value like `-31.26e+12` to the specified writer.
1701
    ///
1702
    /// # Special cases
1703
    ///
1704
    /// This function **does not** check for NaN or infinity. If the input
1705
    /// number is not a finite float, the printed representation will be some
1706
    /// correctly formatted but unspecified numerical value.
1707
    ///
1708
    /// Please check [`is_finite`] yourself before calling this function, or
1709
    /// check [`is_nan`] and [`is_infinite`] and handle those cases yourself
1710
    /// with a different `Formatter` method.
1711
    ///
1712
    /// [`is_finite`]: f64::is_finite
1713
    /// [`is_nan`]: f64::is_nan
1714
    /// [`is_infinite`]: f64::is_infinite
1715
    #[inline]
1716
0
    fn write_f64<W>(&mut self, writer: &mut W, value: f64) -> io::Result<()>
1717
0
    where
1718
0
        W: ?Sized + io::Write,
1719
    {
1720
0
        let mut buffer = zmij::Buffer::new();
1721
0
        let s = buffer.format_finite(value);
1722
0
        writer.write_all(s.as_bytes())
1723
0
    }
Unexecuted instantiation: <serde_json::ser::PrettyFormatter as serde_json::ser::Formatter>::write_f64::<&mut <serde_json::value::Value as core::fmt::Display>::fmt::WriterFormatter>
Unexecuted instantiation: <serde_json::ser::CompactFormatter as serde_json::ser::Formatter>::write_f64::<&mut <serde_json::value::Value as core::fmt::Display>::fmt::WriterFormatter>
1724
1725
    /// Writes a number that has already been rendered to a string.
1726
    #[inline]
1727
    fn write_number_str<W>(&mut self, writer: &mut W, value: &str) -> io::Result<()>
1728
    where
1729
        W: ?Sized + io::Write,
1730
    {
1731
        writer.write_all(value.as_bytes())
1732
    }
1733
1734
    /// Called before each series of `write_string_fragment` and
1735
    /// `write_char_escape`.  Writes a `"` to the specified writer.
1736
    #[inline]
1737
0
    fn begin_string<W>(&mut self, writer: &mut W) -> io::Result<()>
1738
0
    where
1739
0
        W: ?Sized + io::Write,
1740
    {
1741
0
        writer.write_all(b"\"")
1742
0
    }
Unexecuted instantiation: <serde_json::ser::PrettyFormatter as serde_json::ser::Formatter>::begin_string::<&mut <serde_json::value::Value as core::fmt::Display>::fmt::WriterFormatter>
Unexecuted instantiation: <serde_json::ser::CompactFormatter as serde_json::ser::Formatter>::begin_string::<&mut <serde_json::value::Value as core::fmt::Display>::fmt::WriterFormatter>
1743
1744
    /// Called after each series of `write_string_fragment` and
1745
    /// `write_char_escape`.  Writes a `"` to the specified writer.
1746
    #[inline]
1747
0
    fn end_string<W>(&mut self, writer: &mut W) -> io::Result<()>
1748
0
    where
1749
0
        W: ?Sized + io::Write,
1750
    {
1751
0
        writer.write_all(b"\"")
1752
0
    }
Unexecuted instantiation: <serde_json::ser::PrettyFormatter as serde_json::ser::Formatter>::end_string::<&mut <serde_json::value::Value as core::fmt::Display>::fmt::WriterFormatter>
Unexecuted instantiation: <serde_json::ser::CompactFormatter as serde_json::ser::Formatter>::end_string::<&mut <serde_json::value::Value as core::fmt::Display>::fmt::WriterFormatter>
1753
1754
    /// Writes a string fragment that doesn't need any escaping to the
1755
    /// specified writer.
1756
    #[inline]
1757
0
    fn write_string_fragment<W>(&mut self, writer: &mut W, fragment: &str) -> io::Result<()>
1758
0
    where
1759
0
        W: ?Sized + io::Write,
1760
    {
1761
0
        writer.write_all(fragment.as_bytes())
1762
0
    }
Unexecuted instantiation: <serde_json::ser::PrettyFormatter as serde_json::ser::Formatter>::write_string_fragment::<&mut <serde_json::value::Value as core::fmt::Display>::fmt::WriterFormatter>
Unexecuted instantiation: <serde_json::ser::CompactFormatter as serde_json::ser::Formatter>::write_string_fragment::<&mut <serde_json::value::Value as core::fmt::Display>::fmt::WriterFormatter>
1763
1764
    /// Writes a character escape code to the specified writer.
1765
    #[inline]
1766
0
    fn write_char_escape<W>(&mut self, writer: &mut W, char_escape: CharEscape) -> io::Result<()>
1767
0
    where
1768
0
        W: ?Sized + io::Write,
1769
    {
1770
        use self::CharEscape::*;
1771
1772
0
        let escape_char = match char_escape {
1773
0
            Quote => b'"',
1774
0
            ReverseSolidus => b'\\',
1775
0
            Solidus => b'/',
1776
0
            Backspace => b'b',
1777
0
            FormFeed => b'f',
1778
0
            LineFeed => b'n',
1779
0
            CarriageReturn => b'r',
1780
0
            Tab => b't',
1781
0
            AsciiControl(_) => b'u',
1782
        };
1783
1784
0
        match char_escape {
1785
0
            AsciiControl(byte) => {
1786
                static HEX_DIGITS: [u8; 16] = *b"0123456789abcdef";
1787
0
                let bytes = &[
1788
0
                    b'\\',
1789
0
                    escape_char,
1790
0
                    b'0',
1791
0
                    b'0',
1792
0
                    HEX_DIGITS[(byte >> 4) as usize],
1793
0
                    HEX_DIGITS[(byte & 0xF) as usize],
1794
0
                ];
1795
0
                writer.write_all(bytes)
1796
            }
1797
0
            _ => writer.write_all(&[b'\\', escape_char]),
1798
        }
1799
0
    }
Unexecuted instantiation: <serde_json::ser::PrettyFormatter as serde_json::ser::Formatter>::write_char_escape::<&mut <serde_json::value::Value as core::fmt::Display>::fmt::WriterFormatter>
Unexecuted instantiation: <serde_json::ser::CompactFormatter as serde_json::ser::Formatter>::write_char_escape::<&mut <serde_json::value::Value as core::fmt::Display>::fmt::WriterFormatter>
1800
1801
    /// Writes the representation of a byte array. Formatters can choose whether
1802
    /// to represent bytes as a JSON array of integers (the default), or some
1803
    /// JSON string encoding like hex or base64.
1804
    fn write_byte_array<W>(&mut self, writer: &mut W, value: &[u8]) -> io::Result<()>
1805
    where
1806
        W: ?Sized + io::Write,
1807
    {
1808
        tri!(self.begin_array(writer));
1809
        let mut first = true;
1810
        for byte in value {
1811
            tri!(self.begin_array_value(writer, first));
1812
            tri!(self.write_u8(writer, *byte));
1813
            tri!(self.end_array_value(writer));
1814
            first = false;
1815
        }
1816
        self.end_array(writer)
1817
    }
1818
1819
    /// Called before every array.  Writes a `[` to the specified
1820
    /// writer.
1821
    #[inline]
1822
0
    fn begin_array<W>(&mut self, writer: &mut W) -> io::Result<()>
1823
0
    where
1824
0
        W: ?Sized + io::Write,
1825
    {
1826
0
        writer.write_all(b"[")
1827
0
    }
1828
1829
    /// Called after every array.  Writes a `]` to the specified
1830
    /// writer.
1831
    #[inline]
1832
0
    fn end_array<W>(&mut self, writer: &mut W) -> io::Result<()>
1833
0
    where
1834
0
        W: ?Sized + io::Write,
1835
    {
1836
0
        writer.write_all(b"]")
1837
0
    }
1838
1839
    /// Called before every array value.  Writes a `,` if needed to
1840
    /// the specified writer.
1841
    #[inline]
1842
0
    fn begin_array_value<W>(&mut self, writer: &mut W, first: bool) -> io::Result<()>
1843
0
    where
1844
0
        W: ?Sized + io::Write,
1845
    {
1846
0
        if first {
1847
0
            Ok(())
1848
        } else {
1849
0
            writer.write_all(b",")
1850
        }
1851
0
    }
1852
1853
    /// Called after every array value.
1854
    #[inline]
1855
0
    fn end_array_value<W>(&mut self, _writer: &mut W) -> io::Result<()>
1856
0
    where
1857
0
        W: ?Sized + io::Write,
1858
    {
1859
0
        Ok(())
1860
0
    }
1861
1862
    /// Called before every object.  Writes a `{` to the specified
1863
    /// writer.
1864
    #[inline]
1865
0
    fn begin_object<W>(&mut self, writer: &mut W) -> io::Result<()>
1866
0
    where
1867
0
        W: ?Sized + io::Write,
1868
    {
1869
0
        writer.write_all(b"{")
1870
0
    }
1871
1872
    /// Called after every object.  Writes a `}` to the specified
1873
    /// writer.
1874
    #[inline]
1875
0
    fn end_object<W>(&mut self, writer: &mut W) -> io::Result<()>
1876
0
    where
1877
0
        W: ?Sized + io::Write,
1878
    {
1879
0
        writer.write_all(b"}")
1880
0
    }
1881
1882
    /// Called before every object key.
1883
    #[inline]
1884
0
    fn begin_object_key<W>(&mut self, writer: &mut W, first: bool) -> io::Result<()>
1885
0
    where
1886
0
        W: ?Sized + io::Write,
1887
    {
1888
0
        if first {
1889
0
            Ok(())
1890
        } else {
1891
0
            writer.write_all(b",")
1892
        }
1893
0
    }
1894
1895
    /// Called after every object key.  A `:` should be written to the
1896
    /// specified writer by either this method or
1897
    /// `begin_object_value`.
1898
    #[inline]
1899
0
    fn end_object_key<W>(&mut self, _writer: &mut W) -> io::Result<()>
1900
0
    where
1901
0
        W: ?Sized + io::Write,
1902
    {
1903
0
        Ok(())
1904
0
    }
Unexecuted instantiation: <serde_json::ser::PrettyFormatter as serde_json::ser::Formatter>::end_object_key::<&mut <serde_json::value::Value as core::fmt::Display>::fmt::WriterFormatter>
Unexecuted instantiation: <serde_json::ser::CompactFormatter as serde_json::ser::Formatter>::end_object_key::<&mut <serde_json::value::Value as core::fmt::Display>::fmt::WriterFormatter>
1905
1906
    /// Called before every object value.  A `:` should be written to
1907
    /// the specified writer by either this method or
1908
    /// `end_object_key`.
1909
    #[inline]
1910
0
    fn begin_object_value<W>(&mut self, writer: &mut W) -> io::Result<()>
1911
0
    where
1912
0
        W: ?Sized + io::Write,
1913
    {
1914
0
        writer.write_all(b":")
1915
0
    }
1916
1917
    /// Called after every object value.
1918
    #[inline]
1919
0
    fn end_object_value<W>(&mut self, _writer: &mut W) -> io::Result<()>
1920
0
    where
1921
0
        W: ?Sized + io::Write,
1922
    {
1923
0
        Ok(())
1924
0
    }
1925
1926
    /// Writes a raw JSON fragment that doesn't need any escaping to the
1927
    /// specified writer.
1928
    #[inline]
1929
    fn write_raw_fragment<W>(&mut self, writer: &mut W, fragment: &str) -> io::Result<()>
1930
    where
1931
        W: ?Sized + io::Write,
1932
    {
1933
        writer.write_all(fragment.as_bytes())
1934
    }
1935
}
1936
1937
/// This structure compacts a JSON value with no extra whitespace.
1938
#[derive(Clone, Debug, Default)]
1939
pub struct CompactFormatter;
1940
1941
impl Formatter for CompactFormatter {}
1942
1943
/// This structure pretty prints a JSON value to make it human readable.
1944
#[derive(Clone, Debug)]
1945
pub struct PrettyFormatter<'a> {
1946
    current_indent: usize,
1947
    has_value: bool,
1948
    indent: &'a [u8],
1949
}
1950
1951
impl<'a> PrettyFormatter<'a> {
1952
    /// Construct a pretty printer formatter that defaults to using two spaces for indentation.
1953
0
    pub fn new() -> Self {
1954
0
        PrettyFormatter::with_indent(b"  ")
1955
0
    }
1956
1957
    /// Construct a pretty printer formatter that uses the `indent` string for indentation.
1958
0
    pub fn with_indent(indent: &'a [u8]) -> Self {
1959
0
        PrettyFormatter {
1960
0
            current_indent: 0,
1961
0
            has_value: false,
1962
0
            indent,
1963
0
        }
1964
0
    }
1965
}
1966
1967
impl<'a> Default for PrettyFormatter<'a> {
1968
0
    fn default() -> Self {
1969
0
        PrettyFormatter::new()
1970
0
    }
1971
}
1972
1973
impl<'a> Formatter for PrettyFormatter<'a> {
1974
    #[inline]
1975
0
    fn begin_array<W>(&mut self, writer: &mut W) -> io::Result<()>
1976
0
    where
1977
0
        W: ?Sized + io::Write,
1978
    {
1979
0
        self.current_indent += 1;
1980
0
        self.has_value = false;
1981
0
        writer.write_all(b"[")
1982
0
    }
1983
1984
    #[inline]
1985
0
    fn end_array<W>(&mut self, writer: &mut W) -> io::Result<()>
1986
0
    where
1987
0
        W: ?Sized + io::Write,
1988
    {
1989
0
        self.current_indent -= 1;
1990
1991
0
        if self.has_value {
1992
0
            tri!(writer.write_all(b"\n"));
1993
0
            tri!(indent(writer, self.current_indent, self.indent));
1994
0
        }
1995
1996
0
        writer.write_all(b"]")
1997
0
    }
1998
1999
    #[inline]
2000
0
    fn begin_array_value<W>(&mut self, writer: &mut W, first: bool) -> io::Result<()>
2001
0
    where
2002
0
        W: ?Sized + io::Write,
2003
    {
2004
0
        tri!(writer.write_all(if first { b"\n" } else { b",\n" }));
2005
0
        indent(writer, self.current_indent, self.indent)
2006
0
    }
2007
2008
    #[inline]
2009
0
    fn end_array_value<W>(&mut self, _writer: &mut W) -> io::Result<()>
2010
0
    where
2011
0
        W: ?Sized + io::Write,
2012
    {
2013
0
        self.has_value = true;
2014
0
        Ok(())
2015
0
    }
2016
2017
    #[inline]
2018
0
    fn begin_object<W>(&mut self, writer: &mut W) -> io::Result<()>
2019
0
    where
2020
0
        W: ?Sized + io::Write,
2021
    {
2022
0
        self.current_indent += 1;
2023
0
        self.has_value = false;
2024
0
        writer.write_all(b"{")
2025
0
    }
2026
2027
    #[inline]
2028
0
    fn end_object<W>(&mut self, writer: &mut W) -> io::Result<()>
2029
0
    where
2030
0
        W: ?Sized + io::Write,
2031
    {
2032
0
        self.current_indent -= 1;
2033
2034
0
        if self.has_value {
2035
0
            tri!(writer.write_all(b"\n"));
2036
0
            tri!(indent(writer, self.current_indent, self.indent));
2037
0
        }
2038
2039
0
        writer.write_all(b"}")
2040
0
    }
2041
2042
    #[inline]
2043
0
    fn begin_object_key<W>(&mut self, writer: &mut W, first: bool) -> io::Result<()>
2044
0
    where
2045
0
        W: ?Sized + io::Write,
2046
    {
2047
0
        tri!(writer.write_all(if first { b"\n" } else { b",\n" }));
2048
0
        indent(writer, self.current_indent, self.indent)
2049
0
    }
2050
2051
    #[inline]
2052
0
    fn begin_object_value<W>(&mut self, writer: &mut W) -> io::Result<()>
2053
0
    where
2054
0
        W: ?Sized + io::Write,
2055
    {
2056
0
        writer.write_all(b": ")
2057
0
    }
2058
2059
    #[inline]
2060
0
    fn end_object_value<W>(&mut self, _writer: &mut W) -> io::Result<()>
2061
0
    where
2062
0
        W: ?Sized + io::Write,
2063
    {
2064
0
        self.has_value = true;
2065
0
        Ok(())
2066
0
    }
2067
}
2068
2069
0
fn format_escaped_str<W, F>(writer: &mut W, formatter: &mut F, value: &str) -> io::Result<()>
2070
0
where
2071
0
    W: ?Sized + io::Write,
2072
0
    F: ?Sized + Formatter,
2073
{
2074
0
    tri!(formatter.begin_string(writer));
2075
0
    tri!(format_escaped_str_contents(writer, formatter, value));
2076
0
    formatter.end_string(writer)
2077
0
}
Unexecuted instantiation: serde_json::ser::format_escaped_str::<&mut <serde_json::value::Value as core::fmt::Display>::fmt::WriterFormatter, serde_json::ser::PrettyFormatter>
Unexecuted instantiation: serde_json::ser::format_escaped_str::<&mut <serde_json::value::Value as core::fmt::Display>::fmt::WriterFormatter, serde_json::ser::CompactFormatter>
2078
2079
0
fn format_escaped_str_contents<W, F>(
2080
0
    writer: &mut W,
2081
0
    formatter: &mut F,
2082
0
    value: &str,
2083
0
) -> io::Result<()>
2084
0
where
2085
0
    W: ?Sized + io::Write,
2086
0
    F: ?Sized + Formatter,
2087
{
2088
0
    let mut bytes = value.as_bytes();
2089
2090
0
    let mut i = 0;
2091
0
    while i < bytes.len() {
2092
0
        let (string_run, rest) = bytes.split_at(i);
2093
0
        let (&byte, rest) = rest.split_first().unwrap();
2094
2095
0
        let escape = ESCAPE[byte as usize];
2096
2097
0
        i += 1;
2098
0
        if escape == 0 {
2099
0
            continue;
2100
0
        }
2101
2102
0
        bytes = rest;
2103
0
        i = 0;
2104
2105
        // Safety: string_run is a valid utf8 string, since we only split on ascii sequences
2106
0
        let string_run = unsafe { str::from_utf8_unchecked(string_run) };
2107
0
        if !string_run.is_empty() {
2108
0
            tri!(formatter.write_string_fragment(writer, string_run));
2109
0
        }
2110
2111
0
        let char_escape = match escape {
2112
0
            self::BB => CharEscape::Backspace,
2113
0
            self::TT => CharEscape::Tab,
2114
0
            self::NN => CharEscape::LineFeed,
2115
0
            self::FF => CharEscape::FormFeed,
2116
0
            self::RR => CharEscape::CarriageReturn,
2117
0
            self::QU => CharEscape::Quote,
2118
0
            self::BS => CharEscape::ReverseSolidus,
2119
0
            self::UU => CharEscape::AsciiControl(byte),
2120
            // Safety: the escape table does not contain any other type of character.
2121
0
            _ => unsafe { hint::unreachable_unchecked() },
2122
        };
2123
0
        tri!(formatter.write_char_escape(writer, char_escape));
2124
    }
2125
2126
    // Safety: bytes is a valid utf8 string, since we only split on ascii sequences
2127
0
    let string_run = unsafe { str::from_utf8_unchecked(bytes) };
2128
0
    if string_run.is_empty() {
2129
0
        return Ok(());
2130
0
    }
2131
2132
0
    formatter.write_string_fragment(writer, string_run)
2133
0
}
Unexecuted instantiation: serde_json::ser::format_escaped_str_contents::<&mut <serde_json::value::Value as core::fmt::Display>::fmt::WriterFormatter, serde_json::ser::PrettyFormatter>
Unexecuted instantiation: serde_json::ser::format_escaped_str_contents::<&mut <serde_json::value::Value as core::fmt::Display>::fmt::WriterFormatter, serde_json::ser::CompactFormatter>
2134
2135
const BB: u8 = b'b'; // \x08
2136
const TT: u8 = b't'; // \x09
2137
const NN: u8 = b'n'; // \x0A
2138
const FF: u8 = b'f'; // \x0C
2139
const RR: u8 = b'r'; // \x0D
2140
const QU: u8 = b'"'; // \x22
2141
const BS: u8 = b'\\'; // \x5C
2142
const UU: u8 = b'u'; // \x00...\x1F except the ones above
2143
const __: u8 = 0;
2144
2145
// Lookup table of escape sequences. A value of b'x' at index i means that byte
2146
// i is escaped as "\x" in JSON. A value of 0 means that byte i is not escaped.
2147
static ESCAPE: [u8; 256] = [
2148
    //   1   2   3   4   5   6   7   8   9   A   B   C   D   E   F
2149
    UU, UU, UU, UU, UU, UU, UU, UU, BB, TT, NN, UU, FF, RR, UU, UU, // 0
2150
    UU, UU, UU, UU, UU, UU, UU, UU, UU, UU, UU, UU, UU, UU, UU, UU, // 1
2151
    __, __, QU, __, __, __, __, __, __, __, __, __, __, __, __, __, // 2
2152
    __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, // 3
2153
    __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, // 4
2154
    __, __, __, __, __, __, __, __, __, __, __, __, BS, __, __, __, // 5
2155
    __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, // 6
2156
    __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, // 7
2157
    __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, // 8
2158
    __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, // 9
2159
    __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, // A
2160
    __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, // B
2161
    __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, // C
2162
    __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, // D
2163
    __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, // E
2164
    __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, // F
2165
];
2166
2167
/// Serialize the given data structure as JSON into the I/O stream.
2168
///
2169
/// Serialization guarantees it only feeds valid UTF-8 sequences to the writer.
2170
///
2171
/// # Errors
2172
///
2173
/// Serialization can fail if `T`'s implementation of `Serialize` decides to
2174
/// fail, or if `T` contains a map with non-string keys.
2175
#[inline]
2176
#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
2177
0
pub fn to_writer<W, T>(writer: W, value: &T) -> Result<()>
2178
0
where
2179
0
    W: io::Write,
2180
0
    T: ?Sized + Serialize,
2181
{
2182
0
    let mut ser = Serializer::new(writer);
2183
0
    value.serialize(&mut ser)
2184
0
}
2185
2186
/// Serialize the given data structure as pretty-printed JSON into the I/O
2187
/// stream.
2188
///
2189
/// Serialization guarantees it only feeds valid UTF-8 sequences to the writer.
2190
///
2191
/// # Errors
2192
///
2193
/// Serialization can fail if `T`'s implementation of `Serialize` decides to
2194
/// fail, or if `T` contains a map with non-string keys.
2195
#[inline]
2196
#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
2197
0
pub fn to_writer_pretty<W, T>(writer: W, value: &T) -> Result<()>
2198
0
where
2199
0
    W: io::Write,
2200
0
    T: ?Sized + Serialize,
2201
{
2202
0
    let mut ser = Serializer::pretty(writer);
2203
0
    value.serialize(&mut ser)
2204
0
}
2205
2206
/// Serialize the given data structure as a JSON byte vector.
2207
///
2208
/// # Errors
2209
///
2210
/// Serialization can fail if `T`'s implementation of `Serialize` decides to
2211
/// fail, or if `T` contains a map with non-string keys.
2212
#[inline]
2213
pub fn to_vec<T>(value: &T) -> Result<Vec<u8>>
2214
where
2215
    T: ?Sized + Serialize,
2216
{
2217
    let mut writer = Vec::with_capacity(128);
2218
    tri!(to_writer(&mut writer, value));
2219
    Ok(writer)
2220
}
2221
2222
/// Serialize the given data structure as a pretty-printed JSON byte vector.
2223
///
2224
/// # Errors
2225
///
2226
/// Serialization can fail if `T`'s implementation of `Serialize` decides to
2227
/// fail, or if `T` contains a map with non-string keys.
2228
#[inline]
2229
pub fn to_vec_pretty<T>(value: &T) -> Result<Vec<u8>>
2230
where
2231
    T: ?Sized + Serialize,
2232
{
2233
    let mut writer = Vec::with_capacity(128);
2234
    tri!(to_writer_pretty(&mut writer, value));
2235
    Ok(writer)
2236
}
2237
2238
/// Serialize the given data structure as a String of JSON.
2239
///
2240
/// # Errors
2241
///
2242
/// Serialization can fail if `T`'s implementation of `Serialize` decides to
2243
/// fail, or if `T` contains a map with non-string keys.
2244
#[inline]
2245
pub fn to_string<T>(value: &T) -> Result<String>
2246
where
2247
    T: ?Sized + Serialize,
2248
{
2249
    let vec = tri!(to_vec(value));
2250
    let string = unsafe {
2251
        // We do not emit invalid UTF-8.
2252
        String::from_utf8_unchecked(vec)
2253
    };
2254
    Ok(string)
2255
}
2256
2257
/// Serialize the given data structure as a pretty-printed String of JSON.
2258
///
2259
/// # Errors
2260
///
2261
/// Serialization can fail if `T`'s implementation of `Serialize` decides to
2262
/// fail, or if `T` contains a map with non-string keys.
2263
#[inline]
2264
pub fn to_string_pretty<T>(value: &T) -> Result<String>
2265
where
2266
    T: ?Sized + Serialize,
2267
{
2268
    let vec = tri!(to_vec_pretty(value));
2269
    let string = unsafe {
2270
        // We do not emit invalid UTF-8.
2271
        String::from_utf8_unchecked(vec)
2272
    };
2273
    Ok(string)
2274
}
2275
2276
0
fn indent<W>(wr: &mut W, n: usize, s: &[u8]) -> io::Result<()>
2277
0
where
2278
0
    W: ?Sized + io::Write,
2279
{
2280
0
    for _ in 0..n {
2281
0
        tri!(wr.write_all(s));
2282
    }
2283
2284
0
    Ok(())
2285
0
}