Coverage Report

Created: 2025-07-02 06:18

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