serde_json/
ser.rs

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