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    ///
1692    /// # Special cases
1693    ///
1694    /// This function **does not** check for NaN or infinity. If the input
1695    /// number is not a finite float, the printed representation will be some
1696    /// correctly formatted but unspecified numerical value.
1697    ///
1698    /// Please check [`is_finite`] yourself before calling this function, or
1699    /// check [`is_nan`] and [`is_infinite`] and handle those cases yourself
1700    /// with a different `Formatter` method.
1701    ///
1702    /// [`is_finite`]: f32::is_finite
1703    /// [`is_nan`]: f32::is_nan
1704    /// [`is_infinite`]: f32::is_infinite
1705    #[inline]
1706    fn write_f32<W>(&mut self, writer: &mut W, value: f32) -> io::Result<()>
1707    where
1708        W: ?Sized + io::Write,
1709    {
1710        let mut buffer = ryu::Buffer::new();
1711        let s = buffer.format_finite(value);
1712        writer.write_all(s.as_bytes())
1713    }
1714
1715    /// Writes a floating point value like `-31.26e+12` to the specified writer.
1716    ///
1717    /// # Special cases
1718    ///
1719    /// This function **does not** check for NaN or infinity. If the input
1720    /// number is not a finite float, the printed representation will be some
1721    /// correctly formatted but unspecified numerical value.
1722    ///
1723    /// Please check [`is_finite`] yourself before calling this function, or
1724    /// check [`is_nan`] and [`is_infinite`] and handle those cases yourself
1725    /// with a different `Formatter` method.
1726    ///
1727    /// [`is_finite`]: f64::is_finite
1728    /// [`is_nan`]: f64::is_nan
1729    /// [`is_infinite`]: f64::is_infinite
1730    #[inline]
1731    fn write_f64<W>(&mut self, writer: &mut W, value: f64) -> io::Result<()>
1732    where
1733        W: ?Sized + io::Write,
1734    {
1735        let mut buffer = ryu::Buffer::new();
1736        let s = buffer.format_finite(value);
1737        writer.write_all(s.as_bytes())
1738    }
1739
1740    /// Writes a number that has already been rendered to a string.
1741    #[inline]
1742    fn write_number_str<W>(&mut self, writer: &mut W, value: &str) -> io::Result<()>
1743    where
1744        W: ?Sized + io::Write,
1745    {
1746        writer.write_all(value.as_bytes())
1747    }
1748
1749    /// Called before each series of `write_string_fragment` and
1750    /// `write_char_escape`.  Writes a `"` to the specified writer.
1751    #[inline]
1752    fn begin_string<W>(&mut self, writer: &mut W) -> io::Result<()>
1753    where
1754        W: ?Sized + io::Write,
1755    {
1756        writer.write_all(b"\"")
1757    }
1758
1759    /// Called after each series of `write_string_fragment` and
1760    /// `write_char_escape`.  Writes a `"` to the specified writer.
1761    #[inline]
1762    fn end_string<W>(&mut self, writer: &mut W) -> io::Result<()>
1763    where
1764        W: ?Sized + io::Write,
1765    {
1766        writer.write_all(b"\"")
1767    }
1768
1769    /// Writes a string fragment that doesn't need any escaping to the
1770    /// specified writer.
1771    #[inline]
1772    fn write_string_fragment<W>(&mut self, writer: &mut W, fragment: &str) -> io::Result<()>
1773    where
1774        W: ?Sized + io::Write,
1775    {
1776        writer.write_all(fragment.as_bytes())
1777    }
1778
1779    /// Writes a character escape code to the specified writer.
1780    #[inline]
1781    fn write_char_escape<W>(&mut self, writer: &mut W, char_escape: CharEscape) -> io::Result<()>
1782    where
1783        W: ?Sized + io::Write,
1784    {
1785        use self::CharEscape::*;
1786
1787        let s = match char_escape {
1788            Quote => b"\\\"",
1789            ReverseSolidus => b"\\\\",
1790            Solidus => b"\\/",
1791            Backspace => b"\\b",
1792            FormFeed => b"\\f",
1793            LineFeed => b"\\n",
1794            CarriageReturn => b"\\r",
1795            Tab => b"\\t",
1796            AsciiControl(byte) => {
1797                static HEX_DIGITS: [u8; 16] = *b"0123456789abcdef";
1798                let bytes = &[
1799                    b'\\',
1800                    b'u',
1801                    b'0',
1802                    b'0',
1803                    HEX_DIGITS[(byte >> 4) as usize],
1804                    HEX_DIGITS[(byte & 0xF) as usize],
1805                ];
1806                return writer.write_all(bytes);
1807            }
1808        };
1809
1810        writer.write_all(s)
1811    }
1812
1813    /// Writes the representation of a byte array. Formatters can choose whether
1814    /// to represent bytes as a JSON array of integers (the default), or some
1815    /// JSON string encoding like hex or base64.
1816    fn write_byte_array<W>(&mut self, writer: &mut W, value: &[u8]) -> io::Result<()>
1817    where
1818        W: ?Sized + io::Write,
1819    {
1820        tri!(self.begin_array(writer));
1821        let mut first = true;
1822        for byte in value {
1823            tri!(self.begin_array_value(writer, first));
1824            tri!(self.write_u8(writer, *byte));
1825            tri!(self.end_array_value(writer));
1826            first = false;
1827        }
1828        self.end_array(writer)
1829    }
1830
1831    /// Called before every array.  Writes a `[` to the specified
1832    /// writer.
1833    #[inline]
1834    fn begin_array<W>(&mut self, writer: &mut W) -> io::Result<()>
1835    where
1836        W: ?Sized + io::Write,
1837    {
1838        writer.write_all(b"[")
1839    }
1840
1841    /// Called after every array.  Writes a `]` to the specified
1842    /// writer.
1843    #[inline]
1844    fn end_array<W>(&mut self, writer: &mut W) -> io::Result<()>
1845    where
1846        W: ?Sized + io::Write,
1847    {
1848        writer.write_all(b"]")
1849    }
1850
1851    /// Called before every array value.  Writes a `,` if needed to
1852    /// the specified writer.
1853    #[inline]
1854    fn begin_array_value<W>(&mut self, writer: &mut W, first: bool) -> io::Result<()>
1855    where
1856        W: ?Sized + io::Write,
1857    {
1858        if first {
1859            Ok(())
1860        } else {
1861            writer.write_all(b",")
1862        }
1863    }
1864
1865    /// Called after every array value.
1866    #[inline]
1867    fn end_array_value<W>(&mut self, _writer: &mut W) -> io::Result<()>
1868    where
1869        W: ?Sized + io::Write,
1870    {
1871        Ok(())
1872    }
1873
1874    /// Called before every object.  Writes a `{` to the specified
1875    /// writer.
1876    #[inline]
1877    fn begin_object<W>(&mut self, writer: &mut W) -> io::Result<()>
1878    where
1879        W: ?Sized + io::Write,
1880    {
1881        writer.write_all(b"{")
1882    }
1883
1884    /// Called after every object.  Writes a `}` to the specified
1885    /// writer.
1886    #[inline]
1887    fn end_object<W>(&mut self, writer: &mut W) -> io::Result<()>
1888    where
1889        W: ?Sized + io::Write,
1890    {
1891        writer.write_all(b"}")
1892    }
1893
1894    /// Called before every object key.
1895    #[inline]
1896    fn begin_object_key<W>(&mut self, writer: &mut W, first: bool) -> io::Result<()>
1897    where
1898        W: ?Sized + io::Write,
1899    {
1900        if first {
1901            Ok(())
1902        } else {
1903            writer.write_all(b",")
1904        }
1905    }
1906
1907    /// Called after every object key.  A `:` should be written to the
1908    /// specified writer by either this method or
1909    /// `begin_object_value`.
1910    #[inline]
1911    fn end_object_key<W>(&mut self, _writer: &mut W) -> io::Result<()>
1912    where
1913        W: ?Sized + io::Write,
1914    {
1915        Ok(())
1916    }
1917
1918    /// Called before every object value.  A `:` should be written to
1919    /// the specified writer by either this method or
1920    /// `end_object_key`.
1921    #[inline]
1922    fn begin_object_value<W>(&mut self, writer: &mut W) -> io::Result<()>
1923    where
1924        W: ?Sized + io::Write,
1925    {
1926        writer.write_all(b":")
1927    }
1928
1929    /// Called after every object value.
1930    #[inline]
1931    fn end_object_value<W>(&mut self, _writer: &mut W) -> io::Result<()>
1932    where
1933        W: ?Sized + io::Write,
1934    {
1935        Ok(())
1936    }
1937
1938    /// Writes a raw JSON fragment that doesn't need any escaping to the
1939    /// specified writer.
1940    #[inline]
1941    fn write_raw_fragment<W>(&mut self, writer: &mut W, fragment: &str) -> io::Result<()>
1942    where
1943        W: ?Sized + io::Write,
1944    {
1945        writer.write_all(fragment.as_bytes())
1946    }
1947}
1948
1949/// This structure compacts a JSON value with no extra whitespace.
1950#[derive(Clone, Debug)]
1951pub struct CompactFormatter;
1952
1953impl Formatter for CompactFormatter {}
1954
1955/// This structure pretty prints a JSON value to make it human readable.
1956#[derive(Clone, Debug)]
1957pub struct PrettyFormatter<'a> {
1958    current_indent: usize,
1959    has_value: bool,
1960    indent: &'a [u8],
1961}
1962
1963impl<'a> PrettyFormatter<'a> {
1964    /// Construct a pretty printer formatter that defaults to using two spaces for indentation.
1965    pub fn new() -> Self {
1966        PrettyFormatter::with_indent(b"  ")
1967    }
1968
1969    /// Construct a pretty printer formatter that uses the `indent` string for indentation.
1970    pub fn with_indent(indent: &'a [u8]) -> Self {
1971        PrettyFormatter {
1972            current_indent: 0,
1973            has_value: false,
1974            indent,
1975        }
1976    }
1977}
1978
1979impl<'a> Default for PrettyFormatter<'a> {
1980    fn default() -> Self {
1981        PrettyFormatter::new()
1982    }
1983}
1984
1985impl<'a> Formatter for PrettyFormatter<'a> {
1986    #[inline]
1987    fn begin_array<W>(&mut self, writer: &mut W) -> io::Result<()>
1988    where
1989        W: ?Sized + io::Write,
1990    {
1991        self.current_indent += 1;
1992        self.has_value = false;
1993        writer.write_all(b"[")
1994    }
1995
1996    #[inline]
1997    fn end_array<W>(&mut self, writer: &mut W) -> io::Result<()>
1998    where
1999        W: ?Sized + io::Write,
2000    {
2001        self.current_indent -= 1;
2002
2003        if self.has_value {
2004            tri!(writer.write_all(b"\n"));
2005            tri!(indent(writer, self.current_indent, self.indent));
2006        }
2007
2008        writer.write_all(b"]")
2009    }
2010
2011    #[inline]
2012    fn begin_array_value<W>(&mut self, writer: &mut W, first: bool) -> io::Result<()>
2013    where
2014        W: ?Sized + io::Write,
2015    {
2016        tri!(writer.write_all(if first { b"\n" } else { b",\n" }));
2017        indent(writer, self.current_indent, self.indent)
2018    }
2019
2020    #[inline]
2021    fn end_array_value<W>(&mut self, _writer: &mut W) -> io::Result<()>
2022    where
2023        W: ?Sized + io::Write,
2024    {
2025        self.has_value = true;
2026        Ok(())
2027    }
2028
2029    #[inline]
2030    fn begin_object<W>(&mut self, writer: &mut W) -> io::Result<()>
2031    where
2032        W: ?Sized + io::Write,
2033    {
2034        self.current_indent += 1;
2035        self.has_value = false;
2036        writer.write_all(b"{")
2037    }
2038
2039    #[inline]
2040    fn end_object<W>(&mut self, writer: &mut W) -> io::Result<()>
2041    where
2042        W: ?Sized + io::Write,
2043    {
2044        self.current_indent -= 1;
2045
2046        if self.has_value {
2047            tri!(writer.write_all(b"\n"));
2048            tri!(indent(writer, self.current_indent, self.indent));
2049        }
2050
2051        writer.write_all(b"}")
2052    }
2053
2054    #[inline]
2055    fn begin_object_key<W>(&mut self, writer: &mut W, first: bool) -> io::Result<()>
2056    where
2057        W: ?Sized + io::Write,
2058    {
2059        tri!(writer.write_all(if first { b"\n" } else { b",\n" }));
2060        indent(writer, self.current_indent, self.indent)
2061    }
2062
2063    #[inline]
2064    fn begin_object_value<W>(&mut self, writer: &mut W) -> io::Result<()>
2065    where
2066        W: ?Sized + io::Write,
2067    {
2068        writer.write_all(b": ")
2069    }
2070
2071    #[inline]
2072    fn end_object_value<W>(&mut self, _writer: &mut W) -> io::Result<()>
2073    where
2074        W: ?Sized + io::Write,
2075    {
2076        self.has_value = true;
2077        Ok(())
2078    }
2079}
2080
2081fn format_escaped_str<W, F>(writer: &mut W, formatter: &mut F, value: &str) -> io::Result<()>
2082where
2083    W: ?Sized + io::Write,
2084    F: ?Sized + Formatter,
2085{
2086    tri!(formatter.begin_string(writer));
2087    tri!(format_escaped_str_contents(writer, formatter, value));
2088    formatter.end_string(writer)
2089}
2090
2091fn format_escaped_str_contents<W, F>(
2092    writer: &mut W,
2093    formatter: &mut F,
2094    value: &str,
2095) -> io::Result<()>
2096where
2097    W: ?Sized + io::Write,
2098    F: ?Sized + Formatter,
2099{
2100    let bytes = value.as_bytes();
2101
2102    let mut start = 0;
2103
2104    for (i, &byte) in bytes.iter().enumerate() {
2105        let escape = ESCAPE[byte as usize];
2106        if escape == 0 {
2107            continue;
2108        }
2109
2110        if start < i {
2111            tri!(formatter.write_string_fragment(writer, &value[start..i]));
2112        }
2113
2114        let char_escape = CharEscape::from_escape_table(escape, byte);
2115        tri!(formatter.write_char_escape(writer, char_escape));
2116
2117        start = i + 1;
2118    }
2119
2120    if start == bytes.len() {
2121        return Ok(());
2122    }
2123
2124    formatter.write_string_fragment(writer, &value[start..])
2125}
2126
2127const BB: u8 = b'b'; // \x08
2128const TT: u8 = b't'; // \x09
2129const NN: u8 = b'n'; // \x0A
2130const FF: u8 = b'f'; // \x0C
2131const RR: u8 = b'r'; // \x0D
2132const QU: u8 = b'"'; // \x22
2133const BS: u8 = b'\\'; // \x5C
2134const UU: u8 = b'u'; // \x00...\x1F except the ones above
2135const __: u8 = 0;
2136
2137// Lookup table of escape sequences. A value of b'x' at index i means that byte
2138// i is escaped as "\x" in JSON. A value of 0 means that byte i is not escaped.
2139static ESCAPE: [u8; 256] = [
2140    //   1   2   3   4   5   6   7   8   9   A   B   C   D   E   F
2141    UU, UU, UU, UU, UU, UU, UU, UU, BB, TT, NN, UU, FF, RR, UU, UU, // 0
2142    UU, UU, UU, UU, UU, UU, UU, UU, UU, UU, UU, UU, UU, UU, UU, UU, // 1
2143    __, __, QU, __, __, __, __, __, __, __, __, __, __, __, __, __, // 2
2144    __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, // 3
2145    __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, // 4
2146    __, __, __, __, __, __, __, __, __, __, __, __, BS, __, __, __, // 5
2147    __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, // 6
2148    __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, // 7
2149    __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, // 8
2150    __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, // 9
2151    __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, // A
2152    __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, // B
2153    __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, // C
2154    __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, // D
2155    __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, // E
2156    __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, // F
2157];
2158
2159/// Serialize the given data structure as JSON into the I/O stream.
2160///
2161/// Serialization guarantees it only feeds valid UTF-8 sequences to the writer.
2162///
2163/// # Errors
2164///
2165/// Serialization can fail if `T`'s implementation of `Serialize` decides to
2166/// fail, or if `T` contains a map with non-string keys.
2167#[inline]
2168#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
2169pub fn to_writer<W, T>(writer: W, value: &T) -> Result<()>
2170where
2171    W: io::Write,
2172    T: ?Sized + Serialize,
2173{
2174    let mut ser = Serializer::new(writer);
2175    value.serialize(&mut ser)
2176}
2177
2178/// Serialize the given data structure as pretty-printed JSON into the I/O
2179/// stream.
2180///
2181/// Serialization guarantees it only feeds valid UTF-8 sequences to the writer.
2182///
2183/// # Errors
2184///
2185/// Serialization can fail if `T`'s implementation of `Serialize` decides to
2186/// fail, or if `T` contains a map with non-string keys.
2187#[inline]
2188#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
2189pub fn to_writer_pretty<W, T>(writer: W, value: &T) -> Result<()>
2190where
2191    W: io::Write,
2192    T: ?Sized + Serialize,
2193{
2194    let mut ser = Serializer::pretty(writer);
2195    value.serialize(&mut ser)
2196}
2197
2198/// Serialize the given data structure as a JSON byte vector.
2199///
2200/// # Errors
2201///
2202/// Serialization can fail if `T`'s implementation of `Serialize` decides to
2203/// fail, or if `T` contains a map with non-string keys.
2204#[inline]
2205pub fn to_vec<T>(value: &T) -> Result<Vec<u8>>
2206where
2207    T: ?Sized + Serialize,
2208{
2209    let mut writer = Vec::with_capacity(128);
2210    tri!(to_writer(&mut writer, value));
2211    Ok(writer)
2212}
2213
2214/// Serialize the given data structure as a pretty-printed JSON byte vector.
2215///
2216/// # Errors
2217///
2218/// Serialization can fail if `T`'s implementation of `Serialize` decides to
2219/// fail, or if `T` contains a map with non-string keys.
2220#[inline]
2221pub fn to_vec_pretty<T>(value: &T) -> Result<Vec<u8>>
2222where
2223    T: ?Sized + Serialize,
2224{
2225    let mut writer = Vec::with_capacity(128);
2226    tri!(to_writer_pretty(&mut writer, value));
2227    Ok(writer)
2228}
2229
2230/// Serialize the given data structure as a String of JSON.
2231///
2232/// # Errors
2233///
2234/// Serialization can fail if `T`'s implementation of `Serialize` decides to
2235/// fail, or if `T` contains a map with non-string keys.
2236#[inline]
2237pub fn to_string<T>(value: &T) -> Result<String>
2238where
2239    T: ?Sized + Serialize,
2240{
2241    let vec = tri!(to_vec(value));
2242    let string = unsafe {
2243        // We do not emit invalid UTF-8.
2244        String::from_utf8_unchecked(vec)
2245    };
2246    Ok(string)
2247}
2248
2249/// Serialize the given data structure as a pretty-printed String of JSON.
2250///
2251/// # Errors
2252///
2253/// Serialization can fail if `T`'s implementation of `Serialize` decides to
2254/// fail, or if `T` contains a map with non-string keys.
2255#[inline]
2256pub fn to_string_pretty<T>(value: &T) -> Result<String>
2257where
2258    T: ?Sized + Serialize,
2259{
2260    let vec = tri!(to_vec_pretty(value));
2261    let string = unsafe {
2262        // We do not emit invalid UTF-8.
2263        String::from_utf8_unchecked(vec)
2264    };
2265    Ok(string)
2266}
2267
2268fn indent<W>(wr: &mut W, n: usize, s: &[u8]) -> io::Result<()>
2269where
2270    W: ?Sized + io::Write,
2271{
2272    for _ in 0..n {
2273        tri!(wr.write_all(s));
2274    }
2275
2276    Ok(())
2277}