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