1 //! Serialize a Rust data structure into JSON data.
5 use std
::num
::FpCategory
;
8 use super::error
::{Error, ErrorCode, Result}
;
9 use serde
::ser
::{self, Impossible, Serialize}
;
14 /// A structure for serializing Rust values into JSON.
15 pub struct Serializer
<W
, F
= CompactFormatter
> {
24 /// Creates a new JSON serializer.
26 pub fn new(writer
: W
) -> Self {
27 Serializer
::with_formatter(writer
, CompactFormatter
)
31 impl<'a
, W
> Serializer
<W
, PrettyFormatter
<'a
>>
35 /// Creates a new JSON pretty print serializer.
37 pub fn pretty(writer
: W
) -> Self {
38 Serializer
::with_formatter(writer
, PrettyFormatter
::new())
42 impl<W
, F
> Serializer
<W
, F
>
47 /// Creates a new JSON visitor whose output will be written to the writer
50 pub fn with_formatter(writer
: W
, formatter
: F
) -> Self {
57 /// Unwrap the `Writer` from the `Serializer`.
59 pub fn into_inner(self) -> W
{
64 impl<'a
, W
, F
> ser
::Serializer
for &'a
mut Serializer
<W
, F
>
72 type SerializeSeq
= Compound
<'a
, W
, F
>;
73 type SerializeTuple
= Compound
<'a
, W
, F
>;
74 type SerializeTupleStruct
= Compound
<'a
, W
, F
>;
75 type SerializeTupleVariant
= Compound
<'a
, W
, F
>;
76 type SerializeMap
= Compound
<'a
, W
, F
>;
77 type SerializeStruct
= Compound
<'a
, W
, F
>;
78 type SerializeStructVariant
= Compound
<'a
, W
, F
>;
81 fn serialize_bool(self, value
: bool
) -> Result
<()> {
84 .write_bool(&mut self.writer
, value
)
90 fn serialize_i8(self, value
: i8) -> Result
<()> {
93 .write_i8(&mut self.writer
, value
)
99 fn serialize_i16(self, value
: i16) -> Result
<()> {
102 .write_i16(&mut self.writer
, value
)
103 .map_err(Error
::io
));
108 fn serialize_i32(self, value
: i32) -> Result
<()> {
111 .write_i32(&mut self.writer
, value
)
112 .map_err(Error
::io
));
117 fn serialize_i64(self, value
: i64) -> Result
<()> {
120 .write_i64(&mut self.writer
, value
)
121 .map_err(Error
::io
));
125 serde_if_integer128
! {
126 fn serialize_i128(self, value
: i128
) -> Result
<()> {
128 .write_number_str(&mut self.writer
, &value
.to_string())
134 fn serialize_u8(self, value
: u8) -> Result
<()> {
137 .write_u8(&mut self.writer
, value
)
138 .map_err(Error
::io
));
143 fn serialize_u16(self, value
: u16) -> Result
<()> {
146 .write_u16(&mut self.writer
, value
)
147 .map_err(Error
::io
));
152 fn serialize_u32(self, value
: u32) -> Result
<()> {
155 .write_u32(&mut self.writer
, value
)
156 .map_err(Error
::io
));
161 fn serialize_u64(self, value
: u64) -> Result
<()> {
164 .write_u64(&mut self.writer
, value
)
165 .map_err(Error
::io
));
169 serde_if_integer128
! {
170 fn serialize_u128(self, value
: u128
) -> Result
<()> {
172 .write_number_str(&mut self.writer
, &value
.to_string())
178 fn serialize_f32(self, value
: f32) -> Result
<()> {
179 match value
.classify() {
180 FpCategory
::Nan
| FpCategory
::Infinite
=> {
183 .write_null(&mut self.writer
)
184 .map_err(Error
::io
));
189 .write_f32(&mut self.writer
, value
)
190 .map_err(Error
::io
));
197 fn serialize_f64(self, value
: f64) -> Result
<()> {
198 match value
.classify() {
199 FpCategory
::Nan
| FpCategory
::Infinite
=> {
202 .write_null(&mut self.writer
)
203 .map_err(Error
::io
));
208 .write_f64(&mut self.writer
, value
)
209 .map_err(Error
::io
));
216 fn serialize_char(self, value
: char) -> Result
<()> {
217 // A char encoded as UTF-8 takes 4 bytes at most.
218 let mut buf
= [0; 4];
219 self.serialize_str(value
.encode_utf8(&mut buf
))
223 fn serialize_str(self, value
: &str) -> Result
<()> {
224 try
!(format_escaped_str(&mut self.writer
, &mut self.formatter
, value
).map_err(Error
::io
));
229 fn serialize_bytes(self, value
: &[u8]) -> Result
<()> {
230 use serde
::ser
::SerializeSeq
;
231 let mut seq
= try
!(self.serialize_seq(Some(value
.len())));
233 try
!(seq
.serialize_element(byte
));
239 fn serialize_unit(self) -> Result
<()> {
242 .write_null(&mut self.writer
)
243 .map_err(Error
::io
));
248 fn serialize_unit_struct(self, _name
: &'
static str) -> Result
<()> {
249 self.serialize_unit()
253 fn serialize_unit_variant(
257 variant
: &'
static str,
259 self.serialize_str(variant
)
262 /// Serialize newtypes without an object wrapper.
264 fn serialize_newtype_struct
<T
: ?Sized
>(self, _name
: &'
static str, value
: &T
) -> Result
<()>
268 value
.serialize(self)
272 fn serialize_newtype_variant
<T
: ?Sized
>(
276 variant
: &'
static str,
284 .begin_object(&mut self.writer
)
285 .map_err(Error
::io
));
288 .begin_object_key(&mut self.writer
, true)
289 .map_err(Error
::io
));
290 try
!(self.serialize_str(variant
));
293 .end_object_key(&mut self.writer
)
294 .map_err(Error
::io
));
297 .begin_object_value(&mut self.writer
)
298 .map_err(Error
::io
));
299 try
!(value
.serialize(&mut *self));
302 .end_object_value(&mut self.writer
)
303 .map_err(Error
::io
));
306 .end_object(&mut self.writer
)
307 .map_err(Error
::io
));
312 fn serialize_none(self) -> Result
<()> {
313 self.serialize_unit()
317 fn serialize_some
<T
: ?Sized
>(self, value
: &T
) -> Result
<()>
321 value
.serialize(self)
325 fn serialize_seq(self, len
: Option
<usize>) -> Result
<Self::SerializeSeq
> {
329 .begin_array(&mut self.writer
)
330 .map_err(Error
::io
));
333 .end_array(&mut self.writer
)
334 .map_err(Error
::io
));
342 .begin_array(&mut self.writer
)
343 .map_err(Error
::io
));
352 fn serialize_tuple(self, len
: usize) -> Result
<Self::SerializeTuple
> {
353 self.serialize_seq(Some(len
))
357 fn serialize_tuple_struct(
361 ) -> Result
<Self::SerializeTupleStruct
> {
362 self.serialize_seq(Some(len
))
366 fn serialize_tuple_variant(
370 variant
: &'
static str,
372 ) -> Result
<Self::SerializeTupleVariant
> {
375 .begin_object(&mut self.writer
)
376 .map_err(Error
::io
));
379 .begin_object_key(&mut self.writer
, true)
380 .map_err(Error
::io
));
381 try
!(self.serialize_str(variant
));
384 .end_object_key(&mut self.writer
)
385 .map_err(Error
::io
));
388 .begin_object_value(&mut self.writer
)
389 .map_err(Error
::io
));
390 self.serialize_seq(Some(len
))
394 fn serialize_map(self, len
: Option
<usize>) -> Result
<Self::SerializeMap
> {
398 .begin_object(&mut self.writer
)
399 .map_err(Error
::io
));
402 .end_object(&mut self.writer
)
403 .map_err(Error
::io
));
411 .begin_object(&mut self.writer
)
412 .map_err(Error
::io
));
421 fn serialize_struct(self, name
: &'
static str, len
: usize) -> Result
<Self::SerializeStruct
> {
423 #[cfg(feature = "arbitrary_precision")]
424 ::number
::TOKEN
=> Ok(Compound
::Number { ser: self }
),
425 #[cfg(feature = "raw_value")]
426 ::raw
::TOKEN
=> Ok(Compound
::RawValue { ser: self }
),
427 _
=> self.serialize_map(Some(len
)),
432 fn serialize_struct_variant(
436 variant
: &'
static str,
438 ) -> Result
<Self::SerializeStructVariant
> {
441 .begin_object(&mut self.writer
)
442 .map_err(Error
::io
));
445 .begin_object_key(&mut self.writer
, true)
446 .map_err(Error
::io
));
447 try
!(self.serialize_str(variant
));
450 .end_object_key(&mut self.writer
)
451 .map_err(Error
::io
));
454 .begin_object_value(&mut self.writer
)
455 .map_err(Error
::io
));
456 self.serialize_map(Some(len
))
459 fn collect_str
<T
: ?Sized
>(self, value
: &T
) -> Result
<Self::Ok
>
465 struct Adapter
<'ser
, W
: 'ser
, F
: 'ser
> {
467 formatter
: &'ser
mut F
,
468 error
: Option
<io
::Error
>,
471 impl<'ser
, W
, F
> Write
for Adapter
<'ser
, W
, F
>
476 fn write_str(&mut self, s
: &str) -> fmt
::Result
{
477 assert
!(self.error
.is_none());
478 match format_escaped_str_contents(self.writer
, self.formatter
, s
) {
481 self.error
= Some(err
);
490 .begin_string(&mut self.writer
)
491 .map_err(Error
::io
));
493 let mut adapter
= Adapter
{
494 writer
: &mut self.writer
,
495 formatter
: &mut self.formatter
,
498 match write
!(adapter
, "{}", value
) {
499 Ok(()) => assert
!(adapter
.error
.is_none()),
501 return Err(Error
::io(adapter
.error
.expect("there should be an error")));
507 .end_string(&mut self.writer
)
508 .map_err(Error
::io
));
513 #[derive(Eq, PartialEq)]
514 /// Not public API. Should be pub(crate).
522 /// Not public API. Should be pub(crate).
524 pub enum Compound
<'a
, W
: 'a
, F
: 'a
> {
526 ser
: &'a
mut Serializer
<W
, F
>,
529 #[cfg(feature = "arbitrary_precision")]
530 Number { ser: &'a mut Serializer<W, F> }
,
531 #[cfg(feature = "raw_value")]
532 RawValue { ser: &'a mut Serializer<W, F> }
,
535 impl<'a
, W
, F
> ser
::SerializeSeq
for Compound
<'a
, W
, F
>
544 fn serialize_element
<T
: ?Sized
>(&mut self, value
: &T
) -> Result
<()>
555 .begin_array_value(&mut ser
.writer
, *state
== State
::First
)
556 .map_err(Error
::io
));
557 *state
= State
::Rest
;
558 try
!(value
.serialize(&mut **ser
));
561 .end_array_value(&mut ser
.writer
)
562 .map_err(Error
::io
));
565 #[cfg(feature = "arbitrary_precision")]
566 Compound
::Number { .. }
=> unreachable
!(),
567 #[cfg(feature = "raw_value")]
568 Compound
::RawValue { .. }
=> unreachable
!(),
573 fn end(self) -> Result
<()> {
575 Compound
::Map { ser, state }
=> {
578 _
=> try
!(ser
.formatter
.end_array(&mut ser
.writer
).map_err(Error
::io
)),
582 #[cfg(feature = "arbitrary_precision")]
583 Compound
::Number { .. }
=> unreachable
!(),
584 #[cfg(feature = "raw_value")]
585 Compound
::RawValue { .. }
=> unreachable
!(),
590 impl<'a
, W
, F
> ser
::SerializeTuple
for Compound
<'a
, W
, F
>
599 fn serialize_element
<T
: ?Sized
>(&mut self, value
: &T
) -> Result
<()>
603 ser
::SerializeSeq
::serialize_element(self, value
)
607 fn end(self) -> Result
<()> {
608 ser
::SerializeSeq
::end(self)
612 impl<'a
, W
, F
> ser
::SerializeTupleStruct
for Compound
<'a
, W
, F
>
621 fn serialize_field
<T
: ?Sized
>(&mut self, value
: &T
) -> Result
<()>
625 ser
::SerializeSeq
::serialize_element(self, value
)
629 fn end(self) -> Result
<()> {
630 ser
::SerializeSeq
::end(self)
634 impl<'a
, W
, F
> ser
::SerializeTupleVariant
for Compound
<'a
, W
, F
>
643 fn serialize_field
<T
: ?Sized
>(&mut self, value
: &T
) -> Result
<()>
647 ser
::SerializeSeq
::serialize_element(self, value
)
651 fn end(self) -> Result
<()> {
653 Compound
::Map { ser, state }
=> {
656 _
=> try
!(ser
.formatter
.end_array(&mut ser
.writer
).map_err(Error
::io
)),
660 .end_object_value(&mut ser
.writer
)
661 .map_err(Error
::io
));
662 try
!(ser
.formatter
.end_object(&mut ser
.writer
).map_err(Error
::io
));
665 #[cfg(feature = "arbitrary_precision")]
666 Compound
::Number { .. }
=> unreachable
!(),
667 #[cfg(feature = "raw_value")]
668 Compound
::RawValue { .. }
=> unreachable
!(),
673 impl<'a
, W
, F
> ser
::SerializeMap
for Compound
<'a
, W
, F
>
682 fn serialize_key
<T
: ?Sized
>(&mut self, key
: &T
) -> Result
<()>
693 .begin_object_key(&mut ser
.writer
, *state
== State
::First
)
694 .map_err(Error
::io
));
695 *state
= State
::Rest
;
697 try
!(key
.serialize(MapKeySerializer { ser: *ser }
));
701 .end_object_key(&mut ser
.writer
)
702 .map_err(Error
::io
));
705 #[cfg(feature = "arbitrary_precision")]
706 Compound
::Number { .. }
=> unreachable
!(),
707 #[cfg(feature = "raw_value")]
708 Compound
::RawValue { .. }
=> unreachable
!(),
713 fn serialize_value
<T
: ?Sized
>(&mut self, value
: &T
) -> Result
<()>
718 Compound
::Map { ref mut ser, .. }
=> {
721 .begin_object_value(&mut ser
.writer
)
722 .map_err(Error
::io
));
723 try
!(value
.serialize(&mut **ser
));
726 .end_object_value(&mut ser
.writer
)
727 .map_err(Error
::io
));
730 #[cfg(feature = "arbitrary_precision")]
731 Compound
::Number { .. }
=> unreachable
!(),
732 #[cfg(feature = "raw_value")]
733 Compound
::RawValue { .. }
=> unreachable
!(),
738 fn end(self) -> Result
<()> {
740 Compound
::Map { ser, state }
=> {
743 _
=> try
!(ser
.formatter
.end_object(&mut ser
.writer
).map_err(Error
::io
)),
747 #[cfg(feature = "arbitrary_precision")]
748 Compound
::Number { .. }
=> unreachable
!(),
749 #[cfg(feature = "raw_value")]
750 Compound
::RawValue { .. }
=> unreachable
!(),
755 impl<'a
, W
, F
> ser
::SerializeStruct
for Compound
<'a
, W
, F
>
764 fn serialize_field
<T
: ?Sized
>(&mut self, key
: &'
static str, value
: &T
) -> Result
<()>
769 Compound
::Map { .. }
=> {
770 try
!(ser
::SerializeMap
::serialize_key(self, key
));
771 ser
::SerializeMap
::serialize_value(self, value
)
773 #[cfg(feature = "arbitrary_precision")]
774 Compound
::Number { ref mut ser, .. }
=> {
775 if key
== ::number
::TOKEN
{
776 try
!(value
.serialize(NumberStrEmitter(&mut *ser
)));
779 Err(invalid_number())
782 #[cfg(feature = "raw_value")]
783 Compound
::RawValue { ref mut ser, .. }
=> {
784 if key
== ::raw
::TOKEN
{
785 try
!(value
.serialize(RawValueStrEmitter(&mut *ser
)));
788 Err(invalid_raw_value())
795 fn end(self) -> Result
<()> {
797 Compound
::Map { .. }
=> ser
::SerializeMap
::end(self),
798 #[cfg(feature = "arbitrary_precision")]
799 Compound
::Number { .. }
=> Ok(()),
800 #[cfg(feature = "raw_value")]
801 Compound
::RawValue { .. }
=> Ok(()),
806 impl<'a
, W
, F
> ser
::SerializeStructVariant
for Compound
<'a
, W
, F
>
815 fn serialize_field
<T
: ?Sized
>(&mut self, key
: &'
static str, value
: &T
) -> Result
<()>
820 Compound
::Map { .. }
=> ser
::SerializeStruct
::serialize_field(self, key
, value
),
821 #[cfg(feature = "arbitrary_precision")]
822 Compound
::Number { .. }
=> unreachable
!(),
823 #[cfg(feature = "raw_value")]
824 Compound
::RawValue { .. }
=> unreachable
!(),
829 fn end(self) -> Result
<()> {
831 Compound
::Map { ser, state }
=> {
834 _
=> try
!(ser
.formatter
.end_object(&mut ser
.writer
).map_err(Error
::io
)),
838 .end_object_value(&mut ser
.writer
)
839 .map_err(Error
::io
));
840 try
!(ser
.formatter
.end_object(&mut ser
.writer
).map_err(Error
::io
));
843 #[cfg(feature = "arbitrary_precision")]
844 Compound
::Number { .. }
=> unreachable
!(),
845 #[cfg(feature = "raw_value")]
846 Compound
::RawValue { .. }
=> unreachable
!(),
851 struct MapKeySerializer
<'a
, W
: 'a
, F
: 'a
> {
852 ser
: &'a
mut Serializer
<W
, F
>,
855 #[cfg(feature = "arbitrary_precision")]
856 fn invalid_number() -> Error
{
857 Error
::syntax(ErrorCode
::InvalidNumber
, 0, 0)
860 #[cfg(feature = "raw_value")]
861 fn invalid_raw_value() -> Error
{
862 Error
::syntax(ErrorCode
::ExpectedSomeValue
, 0, 0)
865 fn key_must_be_a_string() -> Error
{
866 Error
::syntax(ErrorCode
::KeyMustBeAString
, 0, 0)
869 impl<'a
, W
, F
> ser
::Serializer
for MapKeySerializer
<'a
, W
, F
>
878 fn serialize_str(self, value
: &str) -> Result
<()> {
879 self.ser
.serialize_str(value
)
883 fn serialize_unit_variant(
887 variant
: &'
static str,
889 self.ser
.serialize_str(variant
)
893 fn serialize_newtype_struct
<T
: ?Sized
>(self, _name
: &'
static str, value
: &T
) -> Result
<()>
897 value
.serialize(self)
900 type SerializeSeq
= Impossible
<(), Error
>;
901 type SerializeTuple
= Impossible
<(), Error
>;
902 type SerializeTupleStruct
= Impossible
<(), Error
>;
903 type SerializeTupleVariant
= Impossible
<(), Error
>;
904 type SerializeMap
= Impossible
<(), Error
>;
905 type SerializeStruct
= Impossible
<(), Error
>;
906 type SerializeStructVariant
= Impossible
<(), Error
>;
908 fn serialize_bool(self, _value
: bool
) -> Result
<()> {
909 Err(key_must_be_a_string())
912 fn serialize_i8(self, value
: i8) -> Result
<()> {
916 .begin_string(&mut self.ser
.writer
)
917 .map_err(Error
::io
));
921 .write_i8(&mut self.ser
.writer
, value
)
922 .map_err(Error
::io
));
926 .end_string(&mut self.ser
.writer
)
927 .map_err(Error
::io
));
931 fn serialize_i16(self, value
: i16) -> Result
<()> {
935 .begin_string(&mut self.ser
.writer
)
936 .map_err(Error
::io
));
940 .write_i16(&mut self.ser
.writer
, value
)
941 .map_err(Error
::io
));
945 .end_string(&mut self.ser
.writer
)
946 .map_err(Error
::io
));
950 fn serialize_i32(self, value
: i32) -> Result
<()> {
954 .begin_string(&mut self.ser
.writer
)
955 .map_err(Error
::io
));
959 .write_i32(&mut self.ser
.writer
, value
)
960 .map_err(Error
::io
));
964 .end_string(&mut self.ser
.writer
)
965 .map_err(Error
::io
));
969 fn serialize_i64(self, value
: i64) -> Result
<()> {
973 .begin_string(&mut self.ser
.writer
)
974 .map_err(Error
::io
));
978 .write_i64(&mut self.ser
.writer
, value
)
979 .map_err(Error
::io
));
983 .end_string(&mut self.ser
.writer
)
984 .map_err(Error
::io
));
988 serde_if_integer128
! {
989 fn serialize_i128(self, value
: i128
) -> Result
<()> {
993 .begin_string(&mut self.ser
.writer
)
994 .map_err(Error
::io
));
998 .write_number_str(&mut self.ser
.writer
, &value
.to_string())
999 .map_err(Error
::io
));
1003 .end_string(&mut self.ser
.writer
)
1004 .map_err(Error
::io
));
1009 fn serialize_u8(self, value
: u8) -> Result
<()> {
1013 .begin_string(&mut self.ser
.writer
)
1014 .map_err(Error
::io
));
1018 .write_u8(&mut self.ser
.writer
, value
)
1019 .map_err(Error
::io
));
1023 .end_string(&mut self.ser
.writer
)
1024 .map_err(Error
::io
));
1028 fn serialize_u16(self, value
: u16) -> Result
<()> {
1032 .begin_string(&mut self.ser
.writer
)
1033 .map_err(Error
::io
));
1037 .write_u16(&mut self.ser
.writer
, value
)
1038 .map_err(Error
::io
));
1042 .end_string(&mut self.ser
.writer
)
1043 .map_err(Error
::io
));
1047 fn serialize_u32(self, value
: u32) -> Result
<()> {
1051 .begin_string(&mut self.ser
.writer
)
1052 .map_err(Error
::io
));
1056 .write_u32(&mut self.ser
.writer
, value
)
1057 .map_err(Error
::io
));
1061 .end_string(&mut self.ser
.writer
)
1062 .map_err(Error
::io
));
1066 fn serialize_u64(self, value
: u64) -> Result
<()> {
1070 .begin_string(&mut self.ser
.writer
)
1071 .map_err(Error
::io
));
1075 .write_u64(&mut self.ser
.writer
, value
)
1076 .map_err(Error
::io
));
1080 .end_string(&mut self.ser
.writer
)
1081 .map_err(Error
::io
));
1085 serde_if_integer128
! {
1086 fn serialize_u128(self, value
: u128
) -> Result
<()> {
1090 .begin_string(&mut self.ser
.writer
)
1091 .map_err(Error
::io
));
1095 .write_number_str(&mut self.ser
.writer
, &value
.to_string())
1096 .map_err(Error
::io
));
1100 .end_string(&mut self.ser
.writer
)
1101 .map_err(Error
::io
));
1106 fn serialize_f32(self, _value
: f32) -> Result
<()> {
1107 Err(key_must_be_a_string())
1110 fn serialize_f64(self, _value
: f64) -> Result
<()> {
1111 Err(key_must_be_a_string())
1114 fn serialize_char(self, value
: char) -> Result
<()> {
1115 self.ser
.serialize_str(&value
.to_string())
1118 fn serialize_bytes(self, _value
: &[u8]) -> Result
<()> {
1119 Err(key_must_be_a_string())
1122 fn serialize_unit(self) -> Result
<()> {
1123 Err(key_must_be_a_string())
1126 fn serialize_unit_struct(self, _name
: &'
static str) -> Result
<()> {
1127 Err(key_must_be_a_string())
1130 fn serialize_newtype_variant
<T
: ?Sized
>(
1132 _name
: &'
static str,
1133 _variant_index
: u32,
1134 _variant
: &'
static str,
1140 Err(key_must_be_a_string())
1143 fn serialize_none(self) -> Result
<()> {
1144 Err(key_must_be_a_string())
1147 fn serialize_some
<T
: ?Sized
>(self, _value
: &T
) -> Result
<()>
1151 Err(key_must_be_a_string())
1154 fn serialize_seq(self, _len
: Option
<usize>) -> Result
<Self::SerializeSeq
> {
1155 Err(key_must_be_a_string())
1158 fn serialize_tuple(self, _len
: usize) -> Result
<Self::SerializeTuple
> {
1159 Err(key_must_be_a_string())
1162 fn serialize_tuple_struct(
1164 _name
: &'
static str,
1166 ) -> Result
<Self::SerializeTupleStruct
> {
1167 Err(key_must_be_a_string())
1170 fn serialize_tuple_variant(
1172 _name
: &'
static str,
1173 _variant_index
: u32,
1174 _variant
: &'
static str,
1176 ) -> Result
<Self::SerializeTupleVariant
> {
1177 Err(key_must_be_a_string())
1180 fn serialize_map(self, _len
: Option
<usize>) -> Result
<Self::SerializeMap
> {
1181 Err(key_must_be_a_string())
1184 fn serialize_struct(self, _name
: &'
static str, _len
: usize) -> Result
<Self::SerializeStruct
> {
1185 Err(key_must_be_a_string())
1188 fn serialize_struct_variant(
1190 _name
: &'
static str,
1191 _variant_index
: u32,
1192 _variant
: &'
static str,
1194 ) -> Result
<Self::SerializeStructVariant
> {
1195 Err(key_must_be_a_string())
1199 #[cfg(feature = "arbitrary_precision")]
1200 struct NumberStrEmitter
<'a
, W
: 'a
+ io
::Write
, F
: 'a
+ Formatter
>(&'a
mut Serializer
<W
, F
>);
1202 #[cfg(feature = "arbitrary_precision")]
1203 impl<'a
, W
: io
::Write
, F
: Formatter
> ser
::Serializer
for NumberStrEmitter
<'a
, W
, F
> {
1207 type SerializeSeq
= Impossible
<(), Error
>;
1208 type SerializeTuple
= Impossible
<(), Error
>;
1209 type SerializeTupleStruct
= Impossible
<(), Error
>;
1210 type SerializeTupleVariant
= Impossible
<(), Error
>;
1211 type SerializeMap
= Impossible
<(), Error
>;
1212 type SerializeStruct
= Impossible
<(), Error
>;
1213 type SerializeStructVariant
= Impossible
<(), Error
>;
1215 fn serialize_bool(self, _v
: bool
) -> Result
<Self::Ok
> {
1216 Err(invalid_number())
1219 fn serialize_i8(self, _v
: i8) -> Result
<Self::Ok
> {
1220 Err(invalid_number())
1223 fn serialize_i16(self, _v
: i16) -> Result
<Self::Ok
> {
1224 Err(invalid_number())
1227 fn serialize_i32(self, _v
: i32) -> Result
<Self::Ok
> {
1228 Err(invalid_number())
1231 fn serialize_i64(self, _v
: i64) -> Result
<Self::Ok
> {
1232 Err(invalid_number())
1235 serde_if_integer128
! {
1236 fn serialize_i128(self, _v
: i128
) -> Result
<Self::Ok
> {
1237 Err(invalid_number())
1241 fn serialize_u8(self, _v
: u8) -> Result
<Self::Ok
> {
1242 Err(invalid_number())
1245 fn serialize_u16(self, _v
: u16) -> Result
<Self::Ok
> {
1246 Err(invalid_number())
1249 fn serialize_u32(self, _v
: u32) -> Result
<Self::Ok
> {
1250 Err(invalid_number())
1253 fn serialize_u64(self, _v
: u64) -> Result
<Self::Ok
> {
1254 Err(invalid_number())
1257 serde_if_integer128
! {
1258 fn serialize_u128(self, _v
: u128
) -> Result
<Self::Ok
> {
1259 Err(invalid_number())
1263 fn serialize_f32(self, _v
: f32) -> Result
<Self::Ok
> {
1264 Err(invalid_number())
1267 fn serialize_f64(self, _v
: f64) -> Result
<Self::Ok
> {
1268 Err(invalid_number())
1271 fn serialize_char(self, _v
: char) -> Result
<Self::Ok
> {
1272 Err(invalid_number())
1275 fn serialize_str(self, value
: &str) -> Result
<Self::Ok
> {
1276 let NumberStrEmitter(serializer
) = self;
1279 .write_number_str(&mut serializer
.writer
, value
)
1283 fn serialize_bytes(self, _value
: &[u8]) -> Result
<Self::Ok
> {
1284 Err(invalid_number())
1287 fn serialize_none(self) -> Result
<Self::Ok
> {
1288 Err(invalid_number())
1291 fn serialize_some
<T
: ?Sized
>(self, _value
: &T
) -> Result
<Self::Ok
>
1295 Err(invalid_number())
1298 fn serialize_unit(self) -> Result
<Self::Ok
> {
1299 Err(invalid_number())
1302 fn serialize_unit_struct(self, _name
: &'
static str) -> Result
<Self::Ok
> {
1303 Err(invalid_number())
1306 fn serialize_unit_variant(
1308 _name
: &'
static str,
1309 _variant_index
: u32,
1310 _variant
: &'
static str,
1311 ) -> Result
<Self::Ok
> {
1312 Err(invalid_number())
1315 fn serialize_newtype_struct
<T
: ?Sized
>(
1317 _name
: &'
static str,
1319 ) -> Result
<Self::Ok
>
1323 Err(invalid_number())
1326 fn serialize_newtype_variant
<T
: ?Sized
>(
1328 _name
: &'
static str,
1329 _variant_index
: u32,
1330 _variant
: &'
static str,
1332 ) -> Result
<Self::Ok
>
1336 Err(invalid_number())
1339 fn serialize_seq(self, _len
: Option
<usize>) -> Result
<Self::SerializeSeq
> {
1340 Err(invalid_number())
1343 fn serialize_tuple(self, _len
: usize) -> Result
<Self::SerializeTuple
> {
1344 Err(invalid_number())
1347 fn serialize_tuple_struct(
1349 _name
: &'
static str,
1351 ) -> Result
<Self::SerializeTupleStruct
> {
1352 Err(invalid_number())
1355 fn serialize_tuple_variant(
1357 _name
: &'
static str,
1358 _variant_index
: u32,
1359 _variant
: &'
static str,
1361 ) -> Result
<Self::SerializeTupleVariant
> {
1362 Err(invalid_number())
1365 fn serialize_map(self, _len
: Option
<usize>) -> Result
<Self::SerializeMap
> {
1366 Err(invalid_number())
1369 fn serialize_struct(self, _name
: &'
static str, _len
: usize) -> Result
<Self::SerializeStruct
> {
1370 Err(invalid_number())
1373 fn serialize_struct_variant(
1375 _name
: &'
static str,
1376 _variant_index
: u32,
1377 _variant
: &'
static str,
1379 ) -> Result
<Self::SerializeStructVariant
> {
1380 Err(invalid_number())
1384 #[cfg(feature = "raw_value")]
1385 struct RawValueStrEmitter
<'a
, W
: 'a
+ io
::Write
, F
: 'a
+ Formatter
>(&'a
mut Serializer
<W
, F
>);
1387 #[cfg(feature = "raw_value")]
1388 impl<'a
, W
: io
::Write
, F
: Formatter
> ser
::Serializer
for RawValueStrEmitter
<'a
, W
, F
> {
1392 type SerializeSeq
= Impossible
<(), Error
>;
1393 type SerializeTuple
= Impossible
<(), Error
>;
1394 type SerializeTupleStruct
= Impossible
<(), Error
>;
1395 type SerializeTupleVariant
= Impossible
<(), Error
>;
1396 type SerializeMap
= Impossible
<(), Error
>;
1397 type SerializeStruct
= Impossible
<(), Error
>;
1398 type SerializeStructVariant
= Impossible
<(), Error
>;
1400 fn serialize_bool(self, _v
: bool
) -> Result
<Self::Ok
> {
1401 Err(ser
::Error
::custom("expected RawValue"))
1404 fn serialize_i8(self, _v
: i8) -> Result
<Self::Ok
> {
1405 Err(ser
::Error
::custom("expected RawValue"))
1408 fn serialize_i16(self, _v
: i16) -> Result
<Self::Ok
> {
1409 Err(ser
::Error
::custom("expected RawValue"))
1412 fn serialize_i32(self, _v
: i32) -> Result
<Self::Ok
> {
1413 Err(ser
::Error
::custom("expected RawValue"))
1416 fn serialize_i64(self, _v
: i64) -> Result
<Self::Ok
> {
1417 Err(ser
::Error
::custom("expected RawValue"))
1420 serde_if_integer128
! {
1421 fn serialize_i128(self, _v
: i128
) -> Result
<Self::Ok
> {
1422 Err(ser
::Error
::custom("expected RawValue"))
1426 fn serialize_u8(self, _v
: u8) -> Result
<Self::Ok
> {
1427 Err(ser
::Error
::custom("expected RawValue"))
1430 fn serialize_u16(self, _v
: u16) -> Result
<Self::Ok
> {
1431 Err(ser
::Error
::custom("expected RawValue"))
1434 fn serialize_u32(self, _v
: u32) -> Result
<Self::Ok
> {
1435 Err(ser
::Error
::custom("expected RawValue"))
1438 fn serialize_u64(self, _v
: u64) -> Result
<Self::Ok
> {
1439 Err(ser
::Error
::custom("expected RawValue"))
1442 serde_if_integer128
! {
1443 fn serialize_u128(self, _v
: u128
) -> Result
<Self::Ok
> {
1444 Err(ser
::Error
::custom("expected RawValue"))
1448 fn serialize_f32(self, _v
: f32) -> Result
<Self::Ok
> {
1449 Err(ser
::Error
::custom("expected RawValue"))
1452 fn serialize_f64(self, _v
: f64) -> Result
<Self::Ok
> {
1453 Err(ser
::Error
::custom("expected RawValue"))
1456 fn serialize_char(self, _v
: char) -> Result
<Self::Ok
> {
1457 Err(ser
::Error
::custom("expected RawValue"))
1460 fn serialize_str(self, value
: &str) -> Result
<Self::Ok
> {
1461 let RawValueStrEmitter(serializer
) = self;
1464 .write_raw_fragment(&mut serializer
.writer
, value
)
1468 fn serialize_bytes(self, _value
: &[u8]) -> Result
<Self::Ok
> {
1469 Err(ser
::Error
::custom("expected RawValue"))
1472 fn serialize_none(self) -> Result
<Self::Ok
> {
1473 Err(ser
::Error
::custom("expected RawValue"))
1476 fn serialize_some
<T
: ?Sized
>(self, _value
: &T
) -> Result
<Self::Ok
>
1480 Err(ser
::Error
::custom("expected RawValue"))
1483 fn serialize_unit(self) -> Result
<Self::Ok
> {
1484 Err(ser
::Error
::custom("expected RawValue"))
1487 fn serialize_unit_struct(self, _name
: &'
static str) -> Result
<Self::Ok
> {
1488 Err(ser
::Error
::custom("expected RawValue"))
1491 fn serialize_unit_variant(
1493 _name
: &'
static str,
1494 _variant_index
: u32,
1495 _variant
: &'
static str,
1496 ) -> Result
<Self::Ok
> {
1497 Err(ser
::Error
::custom("expected RawValue"))
1500 fn serialize_newtype_struct
<T
: ?Sized
>(
1502 _name
: &'
static str,
1504 ) -> Result
<Self::Ok
>
1508 Err(ser
::Error
::custom("expected RawValue"))
1511 fn serialize_newtype_variant
<T
: ?Sized
>(
1513 _name
: &'
static str,
1514 _variant_index
: u32,
1515 _variant
: &'
static str,
1517 ) -> Result
<Self::Ok
>
1521 Err(ser
::Error
::custom("expected RawValue"))
1524 fn serialize_seq(self, _len
: Option
<usize>) -> Result
<Self::SerializeSeq
> {
1525 Err(ser
::Error
::custom("expected RawValue"))
1528 fn serialize_tuple(self, _len
: usize) -> Result
<Self::SerializeTuple
> {
1529 Err(ser
::Error
::custom("expected RawValue"))
1532 fn serialize_tuple_struct(
1534 _name
: &'
static str,
1536 ) -> Result
<Self::SerializeTupleStruct
> {
1537 Err(ser
::Error
::custom("expected RawValue"))
1540 fn serialize_tuple_variant(
1542 _name
: &'
static str,
1543 _variant_index
: u32,
1544 _variant
: &'
static str,
1546 ) -> Result
<Self::SerializeTupleVariant
> {
1547 Err(ser
::Error
::custom("expected RawValue"))
1550 fn serialize_map(self, _len
: Option
<usize>) -> Result
<Self::SerializeMap
> {
1551 Err(ser
::Error
::custom("expected RawValue"))
1554 fn serialize_struct(self, _name
: &'
static str, _len
: usize) -> Result
<Self::SerializeStruct
> {
1555 Err(ser
::Error
::custom("expected RawValue"))
1558 fn serialize_struct_variant(
1560 _name
: &'
static str,
1561 _variant_index
: u32,
1562 _variant
: &'
static str,
1564 ) -> Result
<Self::SerializeStructVariant
> {
1565 Err(ser
::Error
::custom("expected RawValue"))
1569 /// Represents a character escape code in a type-safe manner.
1570 pub enum CharEscape
{
1571 /// An escaped quote `"`
1573 /// An escaped reverse solidus `\`
1575 /// An escaped solidus `/`
1577 /// An escaped backspace character (usually escaped as `\b`)
1579 /// An escaped form feed character (usually escaped as `\f`)
1581 /// An escaped line feed character (usually escaped as `\n`)
1583 /// An escaped carriage return character (usually escaped as `\r`)
1585 /// An escaped tab character (usually escaped as `\t`)
1587 /// An escaped ASCII plane control character (usually escaped as
1588 /// `\u00XX` where `XX` are two hex characters)
1594 fn from_escape_table(escape
: u8, byte
: u8) -> CharEscape
{
1596 self::BB
=> CharEscape
::Backspace
,
1597 self::TT
=> CharEscape
::Tab
,
1598 self::NN
=> CharEscape
::LineFeed
,
1599 self::FF
=> CharEscape
::FormFeed
,
1600 self::RR
=> CharEscape
::CarriageReturn
,
1601 self::QU
=> CharEscape
::Quote
,
1602 self::BS
=> CharEscape
::ReverseSolidus
,
1603 self::UU
=> CharEscape
::AsciiControl(byte
),
1604 _
=> unreachable
!(),
1609 /// This trait abstracts away serializing the JSON control characters, which allows the user to
1610 /// optionally pretty print the JSON output.
1611 pub trait Formatter
{
1612 /// Writes a `null` value to the specified writer.
1614 fn write_null
<W
: ?Sized
>(&mut self, writer
: &mut W
) -> io
::Result
<()>
1618 writer
.write_all(b
"null")
1621 /// Writes a `true` or `false` value to the specified writer.
1623 fn write_bool
<W
: ?Sized
>(&mut self, writer
: &mut W
, value
: bool
) -> io
::Result
<()>
1635 /// Writes an integer value like `-123` to the specified writer.
1637 fn write_i8
<W
: ?Sized
>(&mut self, writer
: &mut W
, value
: i8) -> io
::Result
<()>
1641 itoa
::write(writer
, value
).map(drop
)
1644 /// Writes an integer value like `-123` to the specified writer.
1646 fn write_i16
<W
: ?Sized
>(&mut self, writer
: &mut W
, value
: i16) -> io
::Result
<()>
1650 itoa
::write(writer
, value
).map(drop
)
1653 /// Writes an integer value like `-123` to the specified writer.
1655 fn write_i32
<W
: ?Sized
>(&mut self, writer
: &mut W
, value
: i32) -> io
::Result
<()>
1659 itoa
::write(writer
, value
).map(drop
)
1662 /// Writes an integer value like `-123` to the specified writer.
1664 fn write_i64
<W
: ?Sized
>(&mut self, writer
: &mut W
, value
: i64) -> io
::Result
<()>
1668 itoa
::write(writer
, value
).map(drop
)
1671 /// Writes an integer value like `123` to the specified writer.
1673 fn write_u8
<W
: ?Sized
>(&mut self, writer
: &mut W
, value
: u8) -> io
::Result
<()>
1677 itoa
::write(writer
, value
).map(drop
)
1680 /// Writes an integer value like `123` to the specified writer.
1682 fn write_u16
<W
: ?Sized
>(&mut self, writer
: &mut W
, value
: u16) -> io
::Result
<()>
1686 itoa
::write(writer
, value
).map(drop
)
1689 /// Writes an integer value like `123` to the specified writer.
1691 fn write_u32
<W
: ?Sized
>(&mut self, writer
: &mut W
, value
: u32) -> io
::Result
<()>
1695 itoa
::write(writer
, value
).map(drop
)
1698 /// Writes an integer value like `123` to the specified writer.
1700 fn write_u64
<W
: ?Sized
>(&mut self, writer
: &mut W
, value
: u64) -> io
::Result
<()>
1704 itoa
::write(writer
, value
).map(drop
)
1707 /// Writes a floating point value like `-31.26e+12` to the specified writer.
1709 fn write_f32
<W
: ?Sized
>(&mut self, writer
: &mut W
, value
: f32) -> io
::Result
<()>
1713 let mut buffer
= ryu
::Buffer
::new();
1714 let s
= buffer
.format_finite(value
);
1715 writer
.write_all(s
.as_bytes())
1718 /// Writes a floating point value like `-31.26e+12` to the specified writer.
1720 fn write_f64
<W
: ?Sized
>(&mut self, writer
: &mut W
, value
: f64) -> io
::Result
<()>
1724 let mut buffer
= ryu
::Buffer
::new();
1725 let s
= buffer
.format_finite(value
);
1726 writer
.write_all(s
.as_bytes())
1729 /// Writes a number that has already been rendered to a string.
1731 fn write_number_str
<W
: ?Sized
>(&mut self, writer
: &mut W
, value
: &str) -> io
::Result
<()>
1735 writer
.write_all(value
.as_bytes())
1738 /// Called before each series of `write_string_fragment` and
1739 /// `write_char_escape`. Writes a `"` to the specified writer.
1741 fn begin_string
<W
: ?Sized
>(&mut self, writer
: &mut W
) -> io
::Result
<()>
1745 writer
.write_all(b
"\"")
1748 /// Called after each series of `write_string_fragment` and
1749 /// `write_char_escape`. Writes a `"` to the specified writer.
1751 fn end_string
<W
: ?Sized
>(&mut self, writer
: &mut W
) -> io
::Result
<()>
1755 writer
.write_all(b
"\"")
1758 /// Writes a string fragment that doesn't need any escaping to the
1759 /// specified writer.
1761 fn write_string_fragment
<W
: ?Sized
>(&mut self, writer
: &mut W
, fragment
: &str) -> io
::Result
<()>
1765 writer
.write_all(fragment
.as_bytes())
1768 /// Writes a character escape code to the specified writer.
1770 fn write_char_escape
<W
: ?Sized
>(
1773 char_escape
: CharEscape
,
1778 use self::CharEscape
::*;
1780 let s
= match char_escape
{
1782 ReverseSolidus
=> b
"\\\\",
1784 Backspace
=> b
"\\b",
1787 CarriageReturn
=> b
"\\r",
1789 AsciiControl(byte
) => {
1790 static HEX_DIGITS
: [u8; 16] = *b
"0123456789abcdef";
1796 HEX_DIGITS
[(byte
>> 4) as usize],
1797 HEX_DIGITS
[(byte
& 0xF) as usize],
1799 return writer
.write_all(bytes
);
1806 /// Called before every array. Writes a `[` to the specified
1809 fn begin_array
<W
: ?Sized
>(&mut self, writer
: &mut W
) -> io
::Result
<()>
1813 writer
.write_all(b
"[")
1816 /// Called after every array. Writes a `]` to the specified
1819 fn end_array
<W
: ?Sized
>(&mut self, writer
: &mut W
) -> io
::Result
<()>
1823 writer
.write_all(b
"]")
1826 /// Called before every array value. Writes a `,` if needed to
1827 /// the specified writer.
1829 fn begin_array_value
<W
: ?Sized
>(&mut self, writer
: &mut W
, first
: bool
) -> io
::Result
<()>
1836 writer
.write_all(b
",")
1840 /// Called after every array value.
1842 fn end_array_value
<W
: ?Sized
>(&mut self, _writer
: &mut W
) -> io
::Result
<()>
1849 /// Called before every object. Writes a `{` to the specified
1852 fn begin_object
<W
: ?Sized
>(&mut self, writer
: &mut W
) -> io
::Result
<()>
1856 writer
.write_all(b
"{")
1859 /// Called after every object. Writes a `}` to the specified
1862 fn end_object
<W
: ?Sized
>(&mut self, writer
: &mut W
) -> io
::Result
<()>
1866 writer
.write_all(b
"}")
1869 /// Called before every object key.
1871 fn begin_object_key
<W
: ?Sized
>(&mut self, writer
: &mut W
, first
: bool
) -> io
::Result
<()>
1878 writer
.write_all(b
",")
1882 /// Called after every object key. A `:` should be written to the
1883 /// specified writer by either this method or
1884 /// `begin_object_value`.
1886 fn end_object_key
<W
: ?Sized
>(&mut self, _writer
: &mut W
) -> io
::Result
<()>
1893 /// Called before every object value. A `:` should be written to
1894 /// the specified writer by either this method or
1895 /// `end_object_key`.
1897 fn begin_object_value
<W
: ?Sized
>(&mut self, writer
: &mut W
) -> io
::Result
<()>
1901 writer
.write_all(b
":")
1904 /// Called after every object value.
1906 fn end_object_value
<W
: ?Sized
>(&mut self, _writer
: &mut W
) -> io
::Result
<()>
1913 /// Writes a raw JSON fragment that doesn't need any escaping to the
1914 /// specified writer.
1916 fn write_raw_fragment
<W
: ?Sized
>(&mut self, writer
: &mut W
, fragment
: &str) -> io
::Result
<()>
1920 writer
.write_all(fragment
.as_bytes())
1924 /// This structure compacts a JSON value with no extra whitespace.
1925 #[derive(Clone, Debug)]
1926 pub struct CompactFormatter
;
1928 impl Formatter
for CompactFormatter {}
1930 /// This structure pretty prints a JSON value to make it human readable.
1931 #[derive(Clone, Debug)]
1932 pub struct PrettyFormatter
<'a
> {
1933 current_indent
: usize,
1938 impl<'a
> PrettyFormatter
<'a
> {
1939 /// Construct a pretty printer formatter that defaults to using two spaces for indentation.
1940 pub fn new() -> Self {
1941 PrettyFormatter
::with_indent(b
" ")
1944 /// Construct a pretty printer formatter that uses the `indent` string for indentation.
1945 pub fn with_indent(indent
: &'a
[u8]) -> Self {
1954 impl<'a
> Default
for PrettyFormatter
<'a
> {
1955 fn default() -> Self {
1956 PrettyFormatter
::new()
1960 impl<'a
> Formatter
for PrettyFormatter
<'a
> {
1962 fn begin_array
<W
: ?Sized
>(&mut self, writer
: &mut W
) -> io
::Result
<()>
1966 self.current_indent
+= 1;
1967 self.has_value
= false;
1968 writer
.write_all(b
"[")
1972 fn end_array
<W
: ?Sized
>(&mut self, writer
: &mut W
) -> io
::Result
<()>
1976 self.current_indent
-= 1;
1979 try
!(writer
.write_all(b
"\n"));
1980 try
!(indent(writer
, self.current_indent
, self.indent
));
1983 writer
.write_all(b
"]")
1987 fn begin_array_value
<W
: ?Sized
>(&mut self, writer
: &mut W
, first
: bool
) -> io
::Result
<()>
1992 try
!(writer
.write_all(b
"\n"));
1994 try
!(writer
.write_all(b
",\n"));
1996 try
!(indent(writer
, self.current_indent
, self.indent
));
2001 fn end_array_value
<W
: ?Sized
>(&mut self, _writer
: &mut W
) -> io
::Result
<()>
2005 self.has_value
= true;
2010 fn begin_object
<W
: ?Sized
>(&mut self, writer
: &mut W
) -> io
::Result
<()>
2014 self.current_indent
+= 1;
2015 self.has_value
= false;
2016 writer
.write_all(b
"{")
2020 fn end_object
<W
: ?Sized
>(&mut self, writer
: &mut W
) -> io
::Result
<()>
2024 self.current_indent
-= 1;
2027 try
!(writer
.write_all(b
"\n"));
2028 try
!(indent(writer
, self.current_indent
, self.indent
));
2031 writer
.write_all(b
"}")
2035 fn begin_object_key
<W
: ?Sized
>(&mut self, writer
: &mut W
, first
: bool
) -> io
::Result
<()>
2040 try
!(writer
.write_all(b
"\n"));
2042 try
!(writer
.write_all(b
",\n"));
2044 indent(writer
, self.current_indent
, self.indent
)
2048 fn begin_object_value
<W
: ?Sized
>(&mut self, writer
: &mut W
) -> io
::Result
<()>
2052 writer
.write_all(b
": ")
2056 fn end_object_value
<W
: ?Sized
>(&mut self, _writer
: &mut W
) -> io
::Result
<()>
2060 self.has_value
= true;
2065 fn format_escaped_str
<W
: ?Sized
, F
: ?Sized
>(
2074 try
!(formatter
.begin_string(writer
));
2075 try
!(format_escaped_str_contents(writer
, formatter
, value
));
2076 try
!(formatter
.end_string(writer
));
2080 fn format_escaped_str_contents
<W
: ?Sized
, F
: ?Sized
>(
2089 let bytes
= value
.as_bytes();
2093 for (i
, &byte
) in bytes
.iter().enumerate() {
2094 let escape
= ESCAPE
[byte
as usize];
2100 try
!(formatter
.write_string_fragment(writer
, &value
[start
..i
]));
2103 let char_escape
= CharEscape
::from_escape_table(escape
, byte
);
2104 try
!(formatter
.write_char_escape(writer
, char_escape
));
2109 if start
!= bytes
.len() {
2110 try
!(formatter
.write_string_fragment(writer
, &value
[start
..]));
2116 const BB
: u8 = b'b'
; // \x08
2117 const TT
: u8 = b't'
; // \x09
2118 const NN
: u8 = b'n'
; // \x0A
2119 const FF
: u8 = b'f'
; // \x0C
2120 const RR
: u8 = b'r'
; // \x0D
2121 const QU
: u8 = b'
"'; // \x22
2122 const BS: u8 = b'\\'; // \x5C
2123 const UU: u8 = b'u'; // \x00...\x1F except the ones above
2126 // Lookup table of escape sequences. A value of b'x' at index i means that byte
2127 // i is escaped as "\x
" in JSON. A value of 0 means that byte i is not escaped.
2128 static ESCAPE: [u8; 256] = [
2129 // 1 2 3 4 5 6 7 8 9 A B C D E F
2130 UU, UU, UU, UU, UU, UU, UU, UU, BB, TT, NN, UU, FF, RR, UU, UU, // 0
2131 UU, UU, UU, UU, UU, UU, UU, UU, UU, UU, UU, UU, UU, UU, UU, UU, // 1
2132 __, __, QU, __, __, __, __, __, __, __, __, __, __, __, __, __, // 2
2133 __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, // 3
2134 __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, // 4
2135 __, __, __, __, __, __, __, __, __, __, __, __, BS, __, __, __, // 5
2136 __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, // 6
2137 __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, // 7
2138 __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, // 8
2139 __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, // 9
2140 __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, // A
2141 __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, // B
2142 __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, // C
2143 __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, // D
2144 __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, // E
2145 __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, // F
2148 /// Serialize the given data structure as JSON into the IO stream.
2152 /// Serialization can fail if `T`'s implementation of `Serialize` decides to
2153 /// fail, or if `T` contains a map with non-string keys.
2155 pub fn to_writer<W, T: ?Sized>(writer: W, value: &T) -> Result<()>
2160 let mut ser = Serializer::new(writer);
2161 try!(value.serialize(&mut ser));
2165 /// Serialize the given data structure as pretty-printed JSON into the IO
2170 /// Serialization can fail if `T`'s implementation of `Serialize` decides to
2171 /// fail, or if `T` contains a map with non-string keys.
2173 pub fn to_writer_pretty<W, T: ?Sized>(writer: W, value: &T) -> Result<()>
2178 let mut ser = Serializer::pretty(writer);
2179 try!(value.serialize(&mut ser));
2183 /// Serialize the given data structure as a JSON byte vector.
2187 /// Serialization can fail if `T`'s implementation of `Serialize` decides to
2188 /// fail, or if `T` contains a map with non-string keys.
2190 pub fn to_vec<T: ?Sized>(value: &T) -> Result<Vec<u8>>
2194 let mut writer = Vec::with_capacity(128);
2195 try!(to_writer(&mut writer, value));
2199 /// Serialize the given data structure as a pretty-printed JSON byte vector.
2203 /// Serialization can fail if `T`'s implementation of `Serialize` decides to
2204 /// fail, or if `T` contains a map with non-string keys.
2206 pub fn to_vec_pretty<T: ?Sized>(value: &T) -> Result<Vec<u8>>
2210 let mut writer = Vec::with_capacity(128);
2211 try!(to_writer_pretty(&mut writer, value));
2215 /// Serialize the given data structure as a String of JSON.
2219 /// Serialization can fail if `T`'s implementation of `Serialize` decides to
2220 /// fail, or if `T` contains a map with non-string keys.
2222 pub fn to_string<T: ?Sized>(value: &T) -> Result<String>
2226 let vec = try!(to_vec(value));
2227 let string = unsafe {
2228 // We do not emit invalid UTF-8.
2229 String::from_utf8_unchecked(vec)
2234 /// Serialize the given data structure as a pretty-printed String of JSON.
2238 /// Serialization can fail if `T`'s implementation of `Serialize` decides to
2239 /// fail, or if `T` contains a map with non-string keys.
2241 pub fn to_string_pretty<T: ?Sized>(value: &T) -> Result<String>
2245 let vec = try!(to_vec_pretty(value));
2246 let string = unsafe {
2247 // We do not emit invalid UTF-8.
2248 String::from_utf8_unchecked(vec)
2253 fn indent<W: ?Sized>(wr: &mut W, n: usize, s: &[u8]) -> io::Result<()>
2258 try!(wr.write_all(s));