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