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