1 // Copyright 2017 Serde Developers
3 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
4 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
5 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
6 // option. This file may not be copied, modified, or distributed
7 // except according to those terms.
9 //! Serialize a Rust data structure into JSON data.
13 use std
::num
::FpCategory
;
16 use serde
::ser
::{self, Impossible}
;
17 use super::error
::{Error, ErrorCode, Result}
;
22 /// A structure for serializing Rust values into JSON.
23 pub struct Serializer
<W
, F
= CompactFormatter
> {
32 /// Creates a new JSON serializer.
34 pub fn new(writer
: W
) -> Self {
35 Serializer
::with_formatter(writer
, CompactFormatter
)
39 impl<'a
, W
> Serializer
<W
, PrettyFormatter
<'a
>>
43 /// Creates a new JSON pretty print serializer.
45 pub fn pretty(writer
: W
) -> Self {
46 Serializer
::with_formatter(writer
, PrettyFormatter
::new())
50 impl<W
, F
> Serializer
<W
, F
>
55 /// Creates a new JSON visitor whose output will be written to the writer
58 pub fn with_formatter(writer
: W
, formatter
: F
) -> Self {
65 /// Unwrap the `Writer` from the `Serializer`.
67 pub fn into_inner(self) -> W
{
72 impl<'a
, W
, F
> ser
::Serializer
for &'a
mut Serializer
<W
, F
>
80 type SerializeSeq
= Compound
<'a
, W
, F
>;
81 type SerializeTuple
= Compound
<'a
, W
, F
>;
82 type SerializeTupleStruct
= Compound
<'a
, W
, F
>;
83 type SerializeTupleVariant
= Compound
<'a
, W
, F
>;
84 type SerializeMap
= Compound
<'a
, W
, F
>;
85 type SerializeStruct
= Compound
<'a
, W
, F
>;
86 type SerializeStructVariant
= Compound
<'a
, W
, F
>;
89 fn serialize_bool(self, value
: bool
) -> Result
<()> {
92 .write_bool(&mut self.writer
, value
)
99 fn serialize_i8(self, value
: i8) -> Result
<()> {
102 .write_i8(&mut self.writer
, value
)
109 fn serialize_i16(self, value
: i16) -> Result
<()> {
112 .write_i16(&mut self.writer
, value
)
119 fn serialize_i32(self, value
: i32) -> Result
<()> {
122 .write_i32(&mut self.writer
, value
)
129 fn serialize_i64(self, value
: i64) -> Result
<()> {
132 .write_i64(&mut self.writer
, value
)
139 fn serialize_u8(self, value
: u8) -> Result
<()> {
142 .write_u8(&mut self.writer
, value
)
149 fn serialize_u16(self, value
: u16) -> Result
<()> {
152 .write_u16(&mut self.writer
, value
)
159 fn serialize_u32(self, value
: u32) -> Result
<()> {
162 .write_u32(&mut self.writer
, value
)
169 fn serialize_u64(self, value
: u64) -> Result
<()> {
172 .write_u64(&mut self.writer
, value
)
179 fn serialize_f32(self, value
: f32) -> Result
<()> {
180 match value
.classify() {
181 FpCategory
::Nan
| FpCategory
::Infinite
=> {
184 .write_null(&mut self.writer
)
191 .write_f32(&mut self.writer
, value
)
200 fn serialize_f64(self, value
: f64) -> Result
<()> {
201 match value
.classify() {
202 FpCategory
::Nan
| FpCategory
::Infinite
=> {
205 .write_null(&mut self.writer
)
212 .write_f64(&mut self.writer
, value
)
221 fn serialize_char(self, value
: char) -> Result
<()> {
222 try
!(format_escaped_char(&mut self.writer
, &mut self.formatter
, value
).map_err(Error
::io
));
227 fn serialize_str(self, value
: &str) -> Result
<()> {
228 try
!(format_escaped_str(&mut self.writer
, &mut self.formatter
, value
).map_err(Error
::io
));
233 fn serialize_bytes(self, value
: &[u8]) -> Result
<()> {
234 use serde
::ser
::SerializeSeq
;
235 let mut seq
= try
!(self.serialize_seq(Some(value
.len())));
237 try
!(seq
.serialize_element(byte
));
243 fn serialize_unit(self) -> Result
<()> {
246 .write_null(&mut self.writer
)
253 fn serialize_unit_struct(self, _name
: &'
static str) -> Result
<()> {
254 self.serialize_unit()
258 fn serialize_unit_variant(
262 variant
: &'
static str,
264 self.serialize_str(variant
)
267 /// Serialize newtypes without an object wrapper.
269 fn serialize_newtype_struct
<T
: ?Sized
>(self, _name
: &'
static str, value
: &T
) -> Result
<()>
273 value
.serialize(self)
277 fn serialize_newtype_variant
<T
: ?Sized
>(
281 variant
: &'
static str,
289 .begin_object(&mut self.writer
)
294 .begin_object_key(&mut self.writer
, true)
297 try
!(self.serialize_str(variant
));
300 .end_object_key(&mut self.writer
)
305 .begin_object_value(&mut self.writer
)
308 try
!(value
.serialize(&mut *self));
311 .end_object_value(&mut self.writer
)
316 .end_object(&mut self.writer
)
323 fn serialize_none(self) -> Result
<()> {
324 self.serialize_unit()
328 fn serialize_some
<T
: ?Sized
>(self, value
: &T
) -> Result
<()>
332 value
.serialize(self)
336 fn serialize_seq(self, len
: Option
<usize>) -> Result
<Self::SerializeSeq
> {
340 .begin_array(&mut self.writer
)
345 .end_array(&mut self.writer
)
357 .begin_array(&mut self.writer
)
370 fn serialize_tuple(self, len
: usize) -> Result
<Self::SerializeTuple
> {
371 self.serialize_seq(Some(len
))
375 fn serialize_tuple_struct(
379 ) -> Result
<Self::SerializeTupleStruct
> {
380 self.serialize_seq(Some(len
))
384 fn serialize_tuple_variant(
388 variant
: &'
static str,
390 ) -> Result
<Self::SerializeTupleVariant
> {
393 .begin_object(&mut self.writer
)
398 .begin_object_key(&mut self.writer
, true)
401 try
!(self.serialize_str(variant
));
404 .end_object_key(&mut self.writer
)
409 .begin_object_value(&mut self.writer
)
412 self.serialize_seq(Some(len
))
416 fn serialize_map(self, len
: Option
<usize>) -> Result
<Self::SerializeMap
> {
420 .begin_object(&mut self.writer
)
425 .end_object(&mut self.writer
)
437 .begin_object(&mut self.writer
)
450 fn serialize_struct(self, _name
: &'
static str, len
: usize) -> Result
<Self::SerializeStruct
> {
451 self.serialize_map(Some(len
))
455 fn serialize_struct_variant(
459 variant
: &'
static str,
461 ) -> Result
<Self::SerializeStructVariant
> {
464 .begin_object(&mut self.writer
)
469 .begin_object_key(&mut self.writer
, true)
472 try
!(self.serialize_str(variant
));
475 .end_object_key(&mut self.writer
)
480 .begin_object_value(&mut self.writer
)
483 self.serialize_map(Some(len
))
486 fn collect_str
<T
: ?Sized
>(self, value
: &T
) -> Result
<Self::Ok
>
492 struct Adapter
<'ser
, W
: 'ser
, F
: 'ser
> {
494 formatter
: &'ser
mut F
,
495 error
: Option
<io
::Error
>,
498 impl<'ser
, W
, F
> Write
for Adapter
<'ser
, W
, F
>
503 fn write_str(&mut self, s
: &str) -> fmt
::Result
{
504 assert
!(self.error
.is_none());
505 match format_escaped_str_contents(self.writer
, self.formatter
, s
) {
508 self.error
= Some(err
);
517 .begin_string(&mut self.writer
)
521 let mut adapter
= Adapter
{
522 writer
: &mut self.writer
,
523 formatter
: &mut self.formatter
,
526 match write
!(adapter
, "{}", value
) {
527 Ok(()) => assert
!(adapter
.error
.is_none()),
529 return Err(Error
::io(adapter
.error
.expect("there should be an error")));
535 .end_string(&mut self.writer
)
543 #[derive(Eq, PartialEq)]
551 pub struct Compound
<'a
, W
: 'a
, F
: 'a
> {
552 ser
: &'a
mut Serializer
<W
, F
>,
556 impl<'a
, W
, F
> ser
::SerializeSeq
for Compound
<'a
, W
, F
>
565 fn serialize_element
<T
: ?Sized
>(&mut self, value
: &T
) -> Result
<()>
572 .begin_array_value(&mut self.ser
.writer
, self.state
== State
::First
)
575 self.state
= State
::Rest
;
576 try
!(value
.serialize(&mut *self.ser
));
580 .end_array_value(&mut self.ser
.writer
)
587 fn end(self) -> Result
<()> {
594 .end_array(&mut self.ser
.writer
)
603 impl<'a
, W
, F
> ser
::SerializeTuple
for Compound
<'a
, W
, F
>
612 fn serialize_element
<T
: ?Sized
>(&mut self, value
: &T
) -> Result
<()>
616 ser
::SerializeSeq
::serialize_element(self, value
)
620 fn end(self) -> Result
<()> {
621 ser
::SerializeSeq
::end(self)
625 impl<'a
, W
, F
> ser
::SerializeTupleStruct
for Compound
<'a
, W
, F
>
634 fn serialize_field
<T
: ?Sized
>(&mut self, value
: &T
) -> Result
<()>
638 ser
::SerializeSeq
::serialize_element(self, value
)
642 fn end(self) -> Result
<()> {
643 ser
::SerializeSeq
::end(self)
647 impl<'a
, W
, F
> ser
::SerializeTupleVariant
for Compound
<'a
, W
, F
>
656 fn serialize_field
<T
: ?Sized
>(&mut self, value
: &T
) -> Result
<()>
660 ser
::SerializeSeq
::serialize_element(self, value
)
664 fn end(self) -> Result
<()> {
671 .end_array(&mut self.ser
.writer
)
679 .end_object_value(&mut self.ser
.writer
)
685 .end_object(&mut self.ser
.writer
)
692 impl<'a
, W
, F
> ser
::SerializeMap
for Compound
<'a
, W
, F
>
701 fn serialize_key
<T
: ?Sized
>(&mut self, key
: &T
) -> Result
<()>
708 .begin_object_key(&mut self.ser
.writer
, self.state
== State
::First
)
711 self.state
= State
::Rest
;
713 try
!(key
.serialize(MapKeySerializer { ser: self.ser }
));
718 .end_object_key(&mut self.ser
.writer
)
725 fn serialize_value
<T
: ?Sized
>(&mut self, value
: &T
) -> Result
<()>
732 .begin_object_value(&mut self.ser
.writer
)
735 try
!(value
.serialize(&mut *self.ser
));
739 .end_object_value(&mut self.ser
.writer
)
746 fn end(self) -> Result
<()> {
753 .end_object(&mut self.ser
.writer
)
762 impl<'a
, W
, F
> ser
::SerializeStruct
for Compound
<'a
, W
, F
>
771 fn serialize_field
<T
: ?Sized
>(&mut self, key
: &'
static str, value
: &T
) -> Result
<()>
775 try
!(ser
::SerializeMap
::serialize_key(self, key
));
776 ser
::SerializeMap
::serialize_value(self, value
)
780 fn end(self) -> Result
<()> {
781 ser
::SerializeMap
::end(self)
785 impl<'a
, W
, F
> ser
::SerializeStructVariant
for Compound
<'a
, W
, F
>
794 fn serialize_field
<T
: ?Sized
>(&mut self, key
: &'
static str, value
: &T
) -> Result
<()>
798 ser
::SerializeStruct
::serialize_field(self, key
, value
)
802 fn end(self) -> Result
<()> {
809 .end_object(&mut self.ser
.writer
)
817 .end_object_value(&mut self.ser
.writer
)
823 .end_object(&mut self.ser
.writer
)
830 struct MapKeySerializer
<'a
, W
: 'a
, F
: 'a
> {
831 ser
: &'a
mut Serializer
<W
, F
>,
834 fn key_must_be_a_string() -> Error
{
835 Error
::syntax(ErrorCode
::KeyMustBeAString
, 0, 0)
838 impl<'a
, W
, F
> ser
::Serializer
for MapKeySerializer
<'a
, W
, F
>
847 fn serialize_str(self, value
: &str) -> Result
<()> {
848 self.ser
.serialize_str(value
)
852 fn serialize_unit_variant(
856 variant
: &'
static str,
858 self.ser
.serialize_str(variant
)
862 fn serialize_newtype_struct
<T
: ?Sized
>(self, _name
: &'
static str, value
: &T
) -> Result
<()>
866 value
.serialize(self)
869 type SerializeSeq
= Impossible
<(), Error
>;
870 type SerializeTuple
= Impossible
<(), Error
>;
871 type SerializeTupleStruct
= Impossible
<(), Error
>;
872 type SerializeTupleVariant
= Impossible
<(), Error
>;
873 type SerializeMap
= Impossible
<(), Error
>;
874 type SerializeStruct
= Impossible
<(), Error
>;
875 type SerializeStructVariant
= Impossible
<(), Error
>;
877 fn serialize_bool(self, _value
: bool
) -> Result
<()> {
878 Err(key_must_be_a_string())
881 fn serialize_i8(self, value
: i8) -> Result
<()> {
885 .begin_string(&mut self.ser
.writer
)
891 .write_i8(&mut self.ser
.writer
, value
)
897 .end_string(&mut self.ser
.writer
)
903 fn serialize_i16(self, value
: i16) -> Result
<()> {
907 .begin_string(&mut self.ser
.writer
)
913 .write_i16(&mut self.ser
.writer
, value
)
919 .end_string(&mut self.ser
.writer
)
925 fn serialize_i32(self, value
: i32) -> Result
<()> {
929 .begin_string(&mut self.ser
.writer
)
935 .write_i32(&mut self.ser
.writer
, value
)
941 .end_string(&mut self.ser
.writer
)
947 fn serialize_i64(self, value
: i64) -> Result
<()> {
951 .begin_string(&mut self.ser
.writer
)
957 .write_i64(&mut self.ser
.writer
, value
)
963 .end_string(&mut self.ser
.writer
)
969 fn serialize_u8(self, value
: u8) -> Result
<()> {
973 .begin_string(&mut self.ser
.writer
)
979 .write_u8(&mut self.ser
.writer
, value
)
985 .end_string(&mut self.ser
.writer
)
991 fn serialize_u16(self, value
: u16) -> Result
<()> {
995 .begin_string(&mut self.ser
.writer
)
1001 .write_u16(&mut self.ser
.writer
, value
)
1007 .end_string(&mut self.ser
.writer
)
1013 fn serialize_u32(self, value
: u32) -> Result
<()> {
1017 .begin_string(&mut self.ser
.writer
)
1023 .write_u32(&mut self.ser
.writer
, value
)
1029 .end_string(&mut self.ser
.writer
)
1035 fn serialize_u64(self, value
: u64) -> Result
<()> {
1039 .begin_string(&mut self.ser
.writer
)
1045 .write_u64(&mut self.ser
.writer
, value
)
1051 .end_string(&mut self.ser
.writer
)
1057 fn serialize_f32(self, _value
: f32) -> Result
<()> {
1058 Err(key_must_be_a_string())
1061 fn serialize_f64(self, _value
: f64) -> Result
<()> {
1062 Err(key_must_be_a_string())
1065 fn serialize_char(self, _value
: char) -> Result
<()> {
1066 Err(key_must_be_a_string())
1069 fn serialize_bytes(self, _value
: &[u8]) -> Result
<()> {
1070 Err(key_must_be_a_string())
1073 fn serialize_unit(self) -> Result
<()> {
1074 Err(key_must_be_a_string())
1077 fn serialize_unit_struct(self, _name
: &'
static str) -> Result
<()> {
1078 Err(key_must_be_a_string())
1081 fn serialize_newtype_variant
<T
: ?Sized
>(
1083 _name
: &'
static str,
1084 _variant_index
: u32,
1085 _variant
: &'
static str,
1091 Err(key_must_be_a_string())
1094 fn serialize_none(self) -> Result
<()> {
1095 Err(key_must_be_a_string())
1098 fn serialize_some
<T
: ?Sized
>(self, _value
: &T
) -> Result
<()>
1102 Err(key_must_be_a_string())
1105 fn serialize_seq(self, _len
: Option
<usize>) -> Result
<Self::SerializeSeq
> {
1106 Err(key_must_be_a_string())
1109 fn serialize_tuple(self, _len
: usize) -> Result
<Self::SerializeTuple
> {
1110 Err(key_must_be_a_string())
1113 fn serialize_tuple_struct(
1115 _name
: &'
static str,
1117 ) -> Result
<Self::SerializeTupleStruct
> {
1118 Err(key_must_be_a_string())
1121 fn serialize_tuple_variant(
1123 _name
: &'
static str,
1124 _variant_index
: u32,
1125 _variant
: &'
static str,
1127 ) -> Result
<Self::SerializeTupleVariant
> {
1128 Err(key_must_be_a_string())
1131 fn serialize_map(self, _len
: Option
<usize>) -> Result
<Self::SerializeMap
> {
1132 Err(key_must_be_a_string())
1135 fn serialize_struct(self, _name
: &'
static str, _len
: usize) -> Result
<Self::SerializeStruct
> {
1136 Err(key_must_be_a_string())
1139 fn serialize_struct_variant(
1141 _name
: &'
static str,
1142 _variant_index
: u32,
1143 _variant
: &'
static str,
1145 ) -> Result
<Self::SerializeStructVariant
> {
1146 Err(key_must_be_a_string())
1150 /// Represents a character escape code in a type-safe manner.
1151 pub enum CharEscape
{
1152 /// An escaped quote `"`
1154 /// An escaped reverse solidus `\`
1156 /// An escaped solidus `/`
1158 /// An escaped backspace character (usually escaped as `\b`)
1160 /// An escaped form feed character (usually escaped as `\f`)
1162 /// An escaped line feed character (usually escaped as `\n`)
1164 /// An escaped carriage return character (usually escaped as `\r`)
1166 /// An escaped tab character (usually escaped as `\t`)
1168 /// An escaped ASCII plane control character (usually escaped as
1169 /// `\u00XX` where `XX` are two hex characters)
1175 fn from_escape_table(escape
: u8, byte
: u8) -> CharEscape
{
1177 self::BB
=> CharEscape
::Backspace
,
1178 self::TT
=> CharEscape
::Tab
,
1179 self::NN
=> CharEscape
::LineFeed
,
1180 self::FF
=> CharEscape
::FormFeed
,
1181 self::RR
=> CharEscape
::CarriageReturn
,
1182 self::QU
=> CharEscape
::Quote
,
1183 self::BS
=> CharEscape
::ReverseSolidus
,
1184 self::U
=> CharEscape
::AsciiControl(byte
),
1185 _
=> unreachable
!(),
1190 /// This trait abstracts away serializing the JSON control characters, which allows the user to
1191 /// optionally pretty print the JSON output.
1192 pub trait Formatter
{
1193 /// Writes a `null` value to the specified writer.
1195 fn write_null
<W
: ?Sized
>(&mut self, writer
: &mut W
) -> io
::Result
<()>
1199 writer
.write_all(b
"null")
1202 /// Writes a `true` or `false` value to the specified writer.
1204 fn write_bool
<W
: ?Sized
>(&mut self, writer
: &mut W
, value
: bool
) -> io
::Result
<()>
1216 /// Writes an integer value like `-123` to the specified writer.
1218 fn write_i8
<W
: ?Sized
>(&mut self, writer
: &mut W
, value
: i8) -> io
::Result
<()>
1222 itoa
::write(writer
, value
).map(|_
| ())
1225 /// Writes an integer value like `-123` to the specified writer.
1227 fn write_i16
<W
: ?Sized
>(&mut self, writer
: &mut W
, value
: i16) -> io
::Result
<()>
1231 itoa
::write(writer
, value
).map(|_
| ())
1234 /// Writes an integer value like `-123` to the specified writer.
1236 fn write_i32
<W
: ?Sized
>(&mut self, writer
: &mut W
, value
: i32) -> io
::Result
<()>
1240 itoa
::write(writer
, value
).map(|_
| ())
1243 /// Writes an integer value like `-123` to the specified writer.
1245 fn write_i64
<W
: ?Sized
>(&mut self, writer
: &mut W
, value
: i64) -> io
::Result
<()>
1249 itoa
::write(writer
, value
).map(|_
| ())
1252 /// Writes an integer value like `123` to the specified writer.
1254 fn write_u8
<W
: ?Sized
>(&mut self, writer
: &mut W
, value
: u8) -> io
::Result
<()>
1258 itoa
::write(writer
, value
).map(|_
| ())
1261 /// Writes an integer value like `123` to the specified writer.
1263 fn write_u16
<W
: ?Sized
>(&mut self, writer
: &mut W
, value
: u16) -> io
::Result
<()>
1267 itoa
::write(writer
, value
).map(|_
| ())
1270 /// Writes an integer value like `123` to the specified writer.
1272 fn write_u32
<W
: ?Sized
>(&mut self, writer
: &mut W
, value
: u32) -> io
::Result
<()>
1276 itoa
::write(writer
, value
).map(|_
| ())
1279 /// Writes an integer value like `123` to the specified writer.
1281 fn write_u64
<W
: ?Sized
>(&mut self, writer
: &mut W
, value
: u64) -> io
::Result
<()>
1285 itoa
::write(writer
, value
).map(|_
| ())
1288 /// Writes a floating point value like `-31.26e+12` to the specified writer.
1290 fn write_f32
<W
: ?Sized
>(&mut self, writer
: &mut W
, value
: f32) -> io
::Result
<()>
1294 dtoa
::write(writer
, value
).map(|_
| ())
1297 /// Writes a floating point value like `-31.26e+12` to the specified writer.
1299 fn write_f64
<W
: ?Sized
>(&mut self, writer
: &mut W
, value
: f64) -> io
::Result
<()>
1303 dtoa
::write(writer
, value
).map(|_
| ())
1306 /// Called before each series of `write_string_fragment` and
1307 /// `write_char_escape`. Writes a `"` to the specified writer.
1309 fn begin_string
<W
: ?Sized
>(&mut self, writer
: &mut W
) -> io
::Result
<()>
1313 writer
.write_all(b
"\"")
1316 /// Called after each series of `write_string_fragment` and
1317 /// `write_char_escape`. Writes a `"` to the specified writer.
1319 fn end_string
<W
: ?Sized
>(&mut self, writer
: &mut W
) -> io
::Result
<()>
1323 writer
.write_all(b
"\"")
1326 /// Writes a string fragment that doesn't need any escaping to the
1327 /// specified writer.
1329 fn write_string_fragment
<W
: ?Sized
>(&mut self, writer
: &mut W
, fragment
: &str) -> io
::Result
<()>
1333 writer
.write_all(fragment
.as_bytes())
1336 /// Writes a character escape code to the specified writer.
1338 fn write_char_escape
<W
: ?Sized
>(
1341 char_escape
: CharEscape
,
1346 use self::CharEscape
::*;
1348 let s
= match char_escape
{
1350 ReverseSolidus
=> b
"\\\\",
1352 Backspace
=> b
"\\b",
1355 CarriageReturn
=> b
"\\r",
1357 AsciiControl(byte
) => {
1358 static HEX_DIGITS
: [u8; 16] = *b
"0123456789abcdef";
1364 HEX_DIGITS
[(byte
>> 4) as usize],
1365 HEX_DIGITS
[(byte
& 0xF) as usize],
1367 return writer
.write_all(bytes
);
1374 /// Called before every array. Writes a `[` to the specified
1377 fn begin_array
<W
: ?Sized
>(&mut self, writer
: &mut W
) -> io
::Result
<()>
1381 writer
.write_all(b
"[")
1384 /// Called after every array. Writes a `]` to the specified
1387 fn end_array
<W
: ?Sized
>(&mut self, writer
: &mut W
) -> io
::Result
<()>
1391 writer
.write_all(b
"]")
1394 /// Called before every array value. Writes a `,` if needed to
1395 /// the specified writer.
1397 fn begin_array_value
<W
: ?Sized
>(&mut self, writer
: &mut W
, first
: bool
) -> io
::Result
<()>
1404 writer
.write_all(b
",")
1408 /// Called after every array value.
1410 fn end_array_value
<W
: ?Sized
>(&mut self, _writer
: &mut W
) -> io
::Result
<()>
1417 /// Called before every object. Writes a `{` to the specified
1420 fn begin_object
<W
: ?Sized
>(&mut self, writer
: &mut W
) -> io
::Result
<()>
1424 writer
.write_all(b
"{")
1427 /// Called after every object. Writes a `}` to the specified
1430 fn end_object
<W
: ?Sized
>(&mut self, writer
: &mut W
) -> io
::Result
<()>
1434 writer
.write_all(b
"}")
1437 /// Called before every object key.
1439 fn begin_object_key
<W
: ?Sized
>(&mut self, writer
: &mut W
, first
: bool
) -> io
::Result
<()>
1446 writer
.write_all(b
",")
1450 /// Called after every object key. A `:` should be written to the
1451 /// specified writer by either this method or
1452 /// `begin_object_value`.
1454 fn end_object_key
<W
: ?Sized
>(&mut self, _writer
: &mut W
) -> io
::Result
<()>
1461 /// Called before every object value. A `:` should be written to
1462 /// the specified writer by either this method or
1463 /// `end_object_key`.
1465 fn begin_object_value
<W
: ?Sized
>(&mut self, writer
: &mut W
) -> io
::Result
<()>
1469 writer
.write_all(b
":")
1472 /// Called after every object value.
1474 fn end_object_value
<W
: ?Sized
>(&mut self, _writer
: &mut W
) -> io
::Result
<()>
1482 /// This structure compacts a JSON value with no extra whitespace.
1483 #[derive(Clone, Debug)]
1484 pub struct CompactFormatter
;
1486 impl Formatter
for CompactFormatter {}
1488 /// This structure pretty prints a JSON value to make it human readable.
1489 #[derive(Clone, Debug)]
1490 pub struct PrettyFormatter
<'a
> {
1491 current_indent
: usize,
1496 impl<'a
> PrettyFormatter
<'a
> {
1497 /// Construct a pretty printer formatter that defaults to using two spaces for indentation.
1498 pub fn new() -> Self {
1499 PrettyFormatter
::with_indent(b
" ")
1502 /// Construct a pretty printer formatter that uses the `indent` string for indentation.
1503 pub fn with_indent(indent
: &'a
[u8]) -> Self {
1512 impl<'a
> Default
for PrettyFormatter
<'a
> {
1513 fn default() -> Self {
1514 PrettyFormatter
::new()
1518 impl<'a
> Formatter
for PrettyFormatter
<'a
> {
1520 fn begin_array
<W
: ?Sized
>(&mut self, writer
: &mut W
) -> io
::Result
<()>
1524 self.current_indent
+= 1;
1525 self.has_value
= false;
1526 writer
.write_all(b
"[")
1530 fn end_array
<W
: ?Sized
>(&mut self, writer
: &mut W
) -> io
::Result
<()>
1534 self.current_indent
-= 1;
1537 try
!(writer
.write_all(b
"\n"));
1538 try
!(indent(writer
, self.current_indent
, self.indent
));
1541 writer
.write_all(b
"]")
1545 fn begin_array_value
<W
: ?Sized
>(&mut self, writer
: &mut W
, first
: bool
) -> io
::Result
<()>
1550 try
!(writer
.write_all(b
"\n"));
1552 try
!(writer
.write_all(b
",\n"));
1554 try
!(indent(writer
, self.current_indent
, self.indent
));
1559 fn end_array_value
<W
: ?Sized
>(&mut self, _writer
: &mut W
) -> io
::Result
<()>
1563 self.has_value
= true;
1568 fn begin_object
<W
: ?Sized
>(&mut self, writer
: &mut W
) -> io
::Result
<()>
1572 self.current_indent
+= 1;
1573 self.has_value
= false;
1574 writer
.write_all(b
"{")
1578 fn end_object
<W
: ?Sized
>(&mut self, writer
: &mut W
) -> io
::Result
<()>
1582 self.current_indent
-= 1;
1585 try
!(writer
.write_all(b
"\n"));
1586 try
!(indent(writer
, self.current_indent
, self.indent
));
1589 writer
.write_all(b
"}")
1593 fn begin_object_key
<W
: ?Sized
>(&mut self, writer
: &mut W
, first
: bool
) -> io
::Result
<()>
1598 try
!(writer
.write_all(b
"\n"));
1600 try
!(writer
.write_all(b
",\n"));
1602 indent(writer
, self.current_indent
, self.indent
)
1606 fn begin_object_value
<W
: ?Sized
>(&mut self, writer
: &mut W
) -> io
::Result
<()>
1610 writer
.write_all(b
": ")
1614 fn end_object_value
<W
: ?Sized
>(&mut self, _writer
: &mut W
) -> io
::Result
<()>
1618 self.has_value
= true;
1623 fn format_escaped_str
<W
: ?Sized
, F
: ?Sized
>(
1632 try
!(formatter
.begin_string(writer
));
1633 try
!(format_escaped_str_contents(writer
, formatter
, value
));
1634 try
!(formatter
.end_string(writer
));
1638 fn format_escaped_str_contents
<W
: ?Sized
, F
: ?Sized
>(
1647 let bytes
= value
.as_bytes();
1651 for (i
, &byte
) in bytes
.iter().enumerate() {
1652 let escape
= ESCAPE
[byte
as usize];
1658 try
!(formatter
.write_string_fragment(writer
, &value
[start
..i
]));
1661 let char_escape
= CharEscape
::from_escape_table(escape
, byte
);
1662 try
!(formatter
.write_char_escape(writer
, char_escape
));
1667 if start
!= bytes
.len() {
1668 try
!(formatter
.write_string_fragment(writer
, &value
[start
..]));
1674 const BB
: u8 = b'b'
; // \x08
1675 const TT
: u8 = b't'
; // \x09
1676 const NN
: u8 = b'n'
; // \x0A
1677 const FF
: u8 = b'f'
; // \x0C
1678 const RR
: u8 = b'r'
; // \x0D
1679 const QU
: u8 = b'
"'; // \x22
1680 const BS: u8 = b'\\'; // \x5C
1681 const U: u8 = b'u'; // \x00...\x1F except the ones above
1683 // Lookup table of escape sequences. A value of b'x' at index i means that byte
1684 // i is escaped as "\x
" in JSON. A value of 0 means that byte i is not escaped.
1685 #[cfg_attr(rustfmt, rustfmt_skip)]
1686 static ESCAPE: [u8; 256] = [
1687 // 1 2 3 4 5 6 7 8 9 A B C D E F
1688 U, U, U, U, U, U, U, U, BB, TT, NN, U, FF, RR, U, U, // 0
1689 U, U, U, U, U, U, U, U, U, U, U, U, U, U, U, U, // 1
1690 0, 0, QU, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 2
1691 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 3
1692 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 4
1693 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, BS, 0, 0, 0, // 5
1694 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 6
1695 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 7
1696 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 8
1697 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 9
1698 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // A
1699 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // B
1700 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // C
1701 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // D
1702 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // E
1703 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // F
1707 fn format_escaped_char<W: ?Sized, F: ?Sized>(
1717 // A char encoded as UTF-8 takes 4 bytes at most.
1718 let mut buf = [0; 4];
1719 write!(&mut buf[..], "{}
", value).expect("write
char to
4-byte buffer
");
1720 // Writing a char successfully always produce valid UTF-8.
1721 // Once we do not support Rust <1.15 we will be able to just use
1722 // the method `char::encode_utf8`.
1723 // See https://github.com/serde-rs/json/issues/270.
1724 let slice = unsafe { str::from_utf8_unchecked(&buf[0..value.len_utf8()]) };
1725 format_escaped_str(wr, formatter, slice)
1728 /// Serialize the given data structure as JSON into the IO stream.
1732 /// Serialization can fail if `T`'s implementation of `Serialize` decides to
1733 /// fail, or if `T` contains a map with non-string keys.
1735 pub fn to_writer<W, T: ?Sized>(writer: W, value: &T) -> Result<()>
1740 let mut ser = Serializer::new(writer);
1741 try!(value.serialize(&mut ser));
1745 /// Serialize the given data structure as pretty-printed JSON into the IO
1750 /// Serialization can fail if `T`'s implementation of `Serialize` decides to
1751 /// fail, or if `T` contains a map with non-string keys.
1753 pub fn to_writer_pretty<W, T: ?Sized>(writer: W, value: &T) -> Result<()>
1758 let mut ser = Serializer::pretty(writer);
1759 try!(value.serialize(&mut ser));
1763 /// Serialize the given data structure as a JSON byte vector.
1767 /// Serialization can fail if `T`'s implementation of `Serialize` decides to
1768 /// fail, or if `T` contains a map with non-string keys.
1770 pub fn to_vec<T: ?Sized>(value: &T) -> Result<Vec<u8>>
1774 let mut writer = Vec::with_capacity(128);
1775 try!(to_writer(&mut writer, value));
1779 /// Serialize the given data structure as a pretty-printed JSON byte vector.
1783 /// Serialization can fail if `T`'s implementation of `Serialize` decides to
1784 /// fail, or if `T` contains a map with non-string keys.
1786 pub fn to_vec_pretty<T: ?Sized>(value: &T) -> Result<Vec<u8>>
1790 let mut writer = Vec::with_capacity(128);
1791 try!(to_writer_pretty(&mut writer, value));
1795 /// Serialize the given data structure as a String of JSON.
1799 /// Serialization can fail if `T`'s implementation of `Serialize` decides to
1800 /// fail, or if `T` contains a map with non-string keys.
1802 pub fn to_string<T: ?Sized>(value: &T) -> Result<String>
1806 let vec = try!(to_vec(value));
1807 let string = unsafe {
1808 // We do not emit invalid UTF-8.
1809 String::from_utf8_unchecked(vec)
1814 /// Serialize the given data structure as a pretty-printed String of JSON.
1818 /// Serialization can fail if `T`'s implementation of `Serialize` decides to
1819 /// fail, or if `T` contains a map with non-string keys.
1821 pub fn to_string_pretty<T: ?Sized>(value: &T) -> Result<String>
1825 let vec = try!(to_vec_pretty(value));
1826 let string = unsafe {
1827 // We do not emit invalid UTF-8.
1828 String::from_utf8_unchecked(vec)
1833 fn indent<W: ?Sized>(wr: &mut W, n: usize, s: &[u8]) -> io::Result<()>
1838 try!(wr.write_all(s));