1 // Rust JSON serialization library.
2 // Copyright (c) 2011 Google Inc.
4 #![forbid(non_camel_case_types)]
5 #![allow(missing_docs)]
7 //! JSON parsing and serialization
11 //! JSON (JavaScript Object Notation) is a way to write data in Javascript.
12 //! Like XML, it allows to encode structured data in a text format that can be easily read by humans
13 //! Its simple syntax and native compatibility with JavaScript have made it a widely used format.
15 //! Data types that can be encoded are JavaScript types (see the `Json` enum for more details):
17 //! * `Boolean`: equivalent to rust's `bool`
18 //! * `Number`: equivalent to rust's `f64`
19 //! * `String`: equivalent to rust's `String`
20 //! * `Array`: equivalent to rust's `Vec<T>`, but also allowing objects of different types in the
22 //! * `Object`: equivalent to rust's `BTreeMap<String, json::Json>`
25 //! An object is a series of string keys mapping to values, in `"key": value` format.
26 //! Arrays are enclosed in square brackets ([ ... ]) and objects in curly brackets ({ ... }).
27 //! A simple JSON document encoding a person, their age, address and phone numbers could look like
31 //! "FirstName": "John",
32 //! "LastName": "Doe",
35 //! "Street": "Downing Street 10",
37 //! "Country": "Great Britain"
46 //! # Rust Type-based Encoding and Decoding
48 //! Rust provides a mechanism for low boilerplate encoding & decoding of values to and from JSON via
49 //! the serialization API.
50 //! To be able to encode a piece of data, it must implement the `serialize::Encodable` trait.
51 //! To be able to decode a piece of data, it must implement the `serialize::Decodable` trait.
52 //! The Rust compiler provides an annotation to automatically generate the code for these traits:
53 //! `#[derive(Decodable, Encodable)]`
55 //! The JSON API provides an enum `json::Json` and a trait `ToJson` to encode objects.
56 //! The `ToJson` trait provides a `to_json` method to convert an object into a `json::Json` value.
57 //! A `json::Json` value can be encoded as a string or buffer using the functions described above.
58 //! You can also use the `json::Encoder` object, which implements the `Encoder` trait.
60 //! When using `ToJson` the `Encodable` trait implementation is not mandatory.
64 //! ## Using Autoserialization
66 //! Create a struct called `TestStruct` and serialize and deserialize it to and from JSON using the
67 //! serialization API, using the derived serialization code.
70 //! # #![feature(rustc_private)]
71 //! use rustc_macros::{Decodable, Encodable};
72 //! use rustc_serialize::json;
74 //! // Automatically generate `Decodable` and `Encodable` trait implementations
75 //! #[derive(Decodable, Encodable)]
76 //! pub struct TestStruct {
79 //! data_vector: Vec<u8>,
82 //! let object = TestStruct {
84 //! data_str: "homura".to_string(),
85 //! data_vector: vec![2,3,4,5],
88 //! // Serialize using `json::encode`
89 //! let encoded = json::encode(&object).unwrap();
91 //! // Deserialize using `json::decode`
92 //! let decoded: TestStruct = json::decode(&encoded[..]).unwrap();
95 //! ## Using the `ToJson` trait
97 //! The examples above use the `ToJson` trait to generate the JSON string, which is required
98 //! for custom mappings.
100 //! ### Simple example of `ToJson` usage
103 //! # #![feature(rustc_private)]
104 //! use rustc_macros::Encodable;
105 //! use rustc_serialize::json::{self, ToJson, Json};
107 //! // A custom data structure
108 //! struct ComplexNum {
113 //! // JSON value representation
114 //! impl ToJson for ComplexNum {
115 //! fn to_json(&self) -> Json {
116 //! Json::String(format!("{}+{}i", self.a, self.b))
120 //! // Only generate `Encodable` trait implementation
121 //! #[derive(Encodable)]
122 //! pub struct ComplexNumRecord {
128 //! let num = ComplexNum { a: 0.0001, b: 12.539 };
129 //! let data: String = json::encode(&ComplexNumRecord{
131 //! dsc: "test".to_string(),
132 //! val: num.to_json(),
134 //! println!("data: {}", data);
135 //! // data: {"uid":1,"dsc":"test","val":"0.0001+12.539i"};
138 //! ### Verbose example of `ToJson` usage
141 //! # #![feature(rustc_private)]
142 //! use rustc_macros::Decodable;
143 //! use std::collections::BTreeMap;
144 //! use rustc_serialize::json::{self, Json, ToJson};
146 //! // Only generate `Decodable` trait implementation
147 //! #[derive(Decodable)]
148 //! pub struct TestStruct {
150 //! data_str: String,
151 //! data_vector: Vec<u8>,
154 //! // Specify encoding method manually
155 //! impl ToJson for TestStruct {
156 //! fn to_json(&self) -> Json {
157 //! let mut d = BTreeMap::new();
158 //! // All standard types implement `to_json()`, so use it
159 //! d.insert("data_int".to_string(), self.data_int.to_json());
160 //! d.insert("data_str".to_string(), self.data_str.to_json());
161 //! d.insert("data_vector".to_string(), self.data_vector.to_json());
166 //! // Serialize using `ToJson`
167 //! let input_data = TestStruct {
169 //! data_str: "madoka".to_string(),
170 //! data_vector: vec![2,3,4,5],
172 //! let json_obj: Json = input_data.to_json();
173 //! let json_str: String = json_obj.to_string();
175 //! // Deserialize like before
176 //! let decoded: TestStruct = json::decode(&json_str).unwrap();
179 use self::DecoderError
::*;
180 use self::ErrorCode
::*;
181 use self::InternalStackElement
::*;
182 use self::JsonEvent
::*;
183 use self::ParserError
::*;
184 use self::ParserState
::*;
186 use std
::borrow
::Cow
;
187 use std
::collections
::{BTreeMap, HashMap}
;
189 use std
::io
::prelude
::*;
191 use std
::num
::FpCategory
as Fp
;
193 use std
::str::FromStr
;
195 use std
::{char, fmt, str}
;
197 use crate::Encodable
;
199 /// Represents a json value
200 #[derive(Clone, PartialEq, PartialOrd, Debug)]
205 String(string
::String
),
208 Object(self::Object
),
212 pub type Array
= Vec
<Json
>;
213 pub type Object
= BTreeMap
<string
::String
, Json
>;
215 pub struct PrettyJson
<'a
> {
219 pub struct AsJson
<'a
, T
> {
222 pub struct AsPrettyJson
<'a
, T
> {
224 indent
: Option
<usize>,
227 /// The errors that can arise while parsing a JSON stream.
228 #[derive(Clone, Copy, PartialEq, Debug)]
232 EOFWhileParsingObject
,
233 EOFWhileParsingArray
,
234 EOFWhileParsingValue
,
235 EOFWhileParsingString
,
241 InvalidUnicodeCodePoint
,
242 LoneLeadingSurrogateInHexEscape
,
243 UnexpectedEndOfHexEscape
,
249 #[derive(Clone, PartialEq, Debug)]
250 pub enum ParserError
{
252 SyntaxError(ErrorCode
, usize, usize),
253 IoError(io
::ErrorKind
, String
),
256 // Builder and Parser have the same errors.
257 pub type BuilderError
= ParserError
;
259 #[derive(Clone, PartialEq, Debug)]
260 pub enum DecoderError
{
261 ParseError(ParserError
),
262 ExpectedError(string
::String
, string
::String
),
263 MissingFieldError(string
::String
),
264 UnknownVariantError(string
::String
),
265 ApplicationError(string
::String
),
268 #[derive(Copy, Clone, Debug)]
269 pub enum EncoderError
{
270 FmtError(fmt
::Error
),
274 /// Returns a readable error string for a given error code.
275 pub fn error_str(error
: ErrorCode
) -> &'
static str {
277 InvalidSyntax
=> "invalid syntax",
278 InvalidNumber
=> "invalid number",
279 EOFWhileParsingObject
=> "EOF While parsing object",
280 EOFWhileParsingArray
=> "EOF While parsing array",
281 EOFWhileParsingValue
=> "EOF While parsing value",
282 EOFWhileParsingString
=> "EOF While parsing string",
283 KeyMustBeAString
=> "key must be a string",
284 ExpectedColon
=> "expected `:`",
285 TrailingCharacters
=> "trailing characters",
286 TrailingComma
=> "trailing comma",
287 InvalidEscape
=> "invalid escape",
288 UnrecognizedHex
=> "invalid \\u{ esc}ape (unrecognized hex)",
289 NotFourDigit
=> "invalid \\u{ esc}ape (not four digits)",
290 NotUtf8
=> "contents not utf-8",
291 InvalidUnicodeCodePoint
=> "invalid Unicode code point",
292 LoneLeadingSurrogateInHexEscape
=> "lone leading surrogate in hex escape",
293 UnexpectedEndOfHexEscape
=> "unexpected end of hex escape",
297 /// Shortcut function to decode a JSON `&str` into an object
298 pub fn decode
<T
: crate::Decodable
<Decoder
>>(s
: &str) -> DecodeResult
<T
> {
299 let json
= match from_str(s
) {
301 Err(e
) => return Err(ParseError(e
)),
304 let mut decoder
= Decoder
::new(json
);
305 crate::Decodable
::decode(&mut decoder
)
308 /// Shortcut function to encode a `T` into a JSON `String`
309 pub fn encode
<T
: for<'r
> crate::Encodable
<Encoder
<'r
>>>(
311 ) -> Result
<string
::String
, EncoderError
> {
312 let mut s
= String
::new();
314 let mut encoder
= Encoder
::new(&mut s
);
315 object
.encode(&mut encoder
)?
;
320 impl fmt
::Display
for ErrorCode
{
321 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
322 error_str(*self).fmt(f
)
326 fn io_error_to_error(io
: io
::Error
) -> ParserError
{
327 IoError(io
.kind(), io
.to_string())
330 impl fmt
::Display
for ParserError
{
331 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
332 // FIXME this should be a nicer error
333 fmt
::Debug
::fmt(self, f
)
337 impl fmt
::Display
for DecoderError
{
338 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
339 // FIXME this should be a nicer error
340 fmt
::Debug
::fmt(self, f
)
344 impl std
::error
::Error
for DecoderError {}
346 impl fmt
::Display
for EncoderError
{
347 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
348 // FIXME this should be a nicer error
349 fmt
::Debug
::fmt(self, f
)
353 impl std
::error
::Error
for EncoderError {}
355 impl From
<fmt
::Error
> for EncoderError
{
356 /// Converts a [`fmt::Error`] into `EncoderError`
358 /// This conversion does not allocate memory.
359 fn from(err
: fmt
::Error
) -> EncoderError
{
360 EncoderError
::FmtError(err
)
364 pub type EncodeResult
= Result
<(), EncoderError
>;
365 pub type DecodeResult
<T
> = Result
<T
, DecoderError
>;
367 fn escape_str(wr
: &mut dyn fmt
::Write
, v
: &str) -> EncodeResult
{
372 for (i
, byte
) in v
.bytes().enumerate() {
373 let escaped
= match byte
{
376 b'\x00' => "\\u0000
",
377 b'\x01' => "\\u0001
",
378 b'\x02' => "\\u0002
",
379 b'\x03' => "\\u0003
",
380 b'\x04' => "\\u0004
",
381 b'\x05' => "\\u0005
",
382 b'\x06' => "\\u0006
",
383 b'\x07' => "\\u0007
",
387 b'\x0b' => "\\u000b
",
390 b'\x0e' => "\\u000e
",
391 b'\x0f' => "\\u000f
",
392 b'\x10' => "\\u0010
",
393 b'\x11' => "\\u0011
",
394 b'\x12' => "\\u0012
",
395 b'\x13' => "\\u0013
",
396 b'\x14' => "\\u0014
",
397 b'\x15' => "\\u0015
",
398 b'\x16' => "\\u0016
",
399 b'\x17' => "\\u0017
",
400 b'\x18' => "\\u0018
",
401 b'\x19' => "\\u0019
",
402 b'\x1a' => "\\u001a
",
403 b'\x1b' => "\\u001b
",
404 b'\x1c' => "\\u001c
",
405 b'\x1d' => "\\u001d
",
406 b'\x1e' => "\\u001e
",
407 b'\x1f' => "\\u001f
",
408 b'\x7f' => "\\u007f
",
415 wr.write_str(&v[start..i])?;
418 wr.write_str(escaped)?;
423 if start != v.len() {
424 wr.write_str(&v[start..])?;
431 fn escape_char(writer: &mut dyn fmt::Write, v: char) -> EncodeResult {
432 escape_str(writer, v.encode_utf8(&mut [0; 4]))
435 fn spaces(wr: &mut dyn fmt::Write, mut n: usize) -> EncodeResult {
436 const BUF: &str = " ";
438 while n >= BUF.len() {
444 wr.write_str(&BUF[..n])?;
449 fn fmt_number_or_null(v: f64) -> string::String {
451 Fp::Nan | Fp::Infinite => string::String::from("null
"),
452 _ if v.fract() != 0f64 => v.to_string(),
453 _ => v.to_string() + ".0",
457 /// A structure for implementing serialization to JSON.
458 pub struct Encoder<'a> {
459 writer: &'a mut (dyn fmt::Write + 'a),
460 is_emitting_map_key: bool,
463 impl<'a> Encoder<'a> {
464 /// Creates a new JSON encoder whose output will be written to the writer
466 pub fn new(writer: &'a mut dyn fmt::Write) -> Encoder<'a> {
467 Encoder { writer, is_emitting_map_key: false }
471 macro_rules! emit_enquoted_if_mapkey {
472 ($enc:ident,$e:expr) => {{
473 if $enc.is_emitting_map_key {
474 write!($enc.writer, "\"{}
\"", $e)?;
476 write!($enc.writer, "{}
", $e)?;
482 impl<'a> crate::Encoder for Encoder<'a> {
483 type Error = EncoderError;
485 fn emit_unit(&mut self) -> EncodeResult {
486 if self.is_emitting_map_key {
487 return Err(EncoderError::BadHashmapKey);
489 write!(self.writer, "null
")?;
493 fn emit_usize(&mut self, v: usize) -> EncodeResult {
494 emit_enquoted_if_mapkey!(self, v)
496 fn emit_u128(&mut self, v: u128) -> EncodeResult {
497 emit_enquoted_if_mapkey!(self, v)
499 fn emit_u64(&mut self, v: u64) -> EncodeResult {
500 emit_enquoted_if_mapkey!(self, v)
502 fn emit_u32(&mut self, v: u32) -> EncodeResult {
503 emit_enquoted_if_mapkey!(self, v)
505 fn emit_u16(&mut self, v: u16) -> EncodeResult {
506 emit_enquoted_if_mapkey!(self, v)
508 fn emit_u8(&mut self, v: u8) -> EncodeResult {
509 emit_enquoted_if_mapkey!(self, v)
512 fn emit_isize(&mut self, v: isize) -> EncodeResult {
513 emit_enquoted_if_mapkey!(self, v)
515 fn emit_i128(&mut self, v: i128) -> EncodeResult {
516 emit_enquoted_if_mapkey!(self, v)
518 fn emit_i64(&mut self, v: i64) -> EncodeResult {
519 emit_enquoted_if_mapkey!(self, v)
521 fn emit_i32(&mut self, v: i32) -> EncodeResult {
522 emit_enquoted_if_mapkey!(self, v)
524 fn emit_i16(&mut self, v: i16) -> EncodeResult {
525 emit_enquoted_if_mapkey!(self, v)
527 fn emit_i8(&mut self, v: i8) -> EncodeResult {
528 emit_enquoted_if_mapkey!(self, v)
531 fn emit_bool(&mut self, v: bool) -> EncodeResult {
532 if self.is_emitting_map_key {
533 return Err(EncoderError::BadHashmapKey);
536 write!(self.writer, "true")?;
538 write!(self.writer, "false")?;
543 fn emit_f64(&mut self, v: f64) -> EncodeResult {
544 emit_enquoted_if_mapkey!(self, fmt_number_or_null(v))
546 fn emit_f32(&mut self, v: f32) -> EncodeResult {
547 self.emit_f64(f64::from(v))
550 fn emit_char(&mut self, v: char) -> EncodeResult {
551 escape_char(self.writer, v)
553 fn emit_str(&mut self, v: &str) -> EncodeResult {
554 escape_str(self.writer, v)
556 fn emit_raw_bytes(&mut self, s: &[u8]) -> Result<(), Self::Error> {
563 fn emit_enum<F>(&mut self, _name: &str, f: F) -> EncodeResult
565 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
570 fn emit_enum_variant<F>(&mut self, name: &str, _id: usize, cnt: usize, f: F) -> EncodeResult
572 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
574 // enums are encoded as strings or objects
576 // Kangaroo(34,"William
") => {"variant": "Kangaroo", "fields": [34,"William"]}
578 escape_str(self.writer, name)
580 if self.is_emitting_map_key {
581 return Err(EncoderError::BadHashmapKey);
583 write!(self.writer, "{{\"variant
\":")?;
584 escape_str(self.writer, name)?;
585 write!(self.writer, ",\"fields
\":[")?;
587 write!(self.writer, "]}}")?;
592 fn emit_enum_variant_arg<F>(&mut self, idx: usize, f: F) -> EncodeResult
594 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
596 if self.is_emitting_map_key {
597 return Err(EncoderError::BadHashmapKey);
600 write!(self.writer, ",")?;
605 fn emit_enum_struct_variant<F>(
613 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
615 if self.is_emitting_map_key {
616 return Err(EncoderError::BadHashmapKey);
618 self.emit_enum_variant(name, id, cnt, f)
621 fn emit_enum_struct_variant_field<F>(&mut self, _: &str, idx: usize, f: F) -> EncodeResult
623 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
625 if self.is_emitting_map_key {
626 return Err(EncoderError::BadHashmapKey);
628 self.emit_enum_variant_arg(idx, f)
631 fn emit_struct<F>(&mut self, _: &str, _: usize, f: F) -> EncodeResult
633 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
635 if self.is_emitting_map_key {
636 return Err(EncoderError::BadHashmapKey);
638 write!(self.writer, "{{")?;
640 write!(self.writer, "}}")?;
644 fn emit_struct_field<F>(&mut self, name: &str, idx: usize, f: F) -> EncodeResult
646 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
648 if self.is_emitting_map_key {
649 return Err(EncoderError::BadHashmapKey);
652 write!(self.writer, ",")?;
654 escape_str(self.writer, name)?;
655 write!(self.writer, ":")?;
659 fn emit_tuple<F>(&mut self, len: usize, f: F) -> EncodeResult
661 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
663 if self.is_emitting_map_key {
664 return Err(EncoderError::BadHashmapKey);
666 self.emit_seq(len, f)
668 fn emit_tuple_arg<F>(&mut self, idx: usize, f: F) -> EncodeResult
670 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
672 if self.is_emitting_map_key {
673 return Err(EncoderError::BadHashmapKey);
675 self.emit_seq_elt(idx, f)
678 fn emit_tuple_struct<F>(&mut self, _name: &str, len: usize, f: F) -> EncodeResult
680 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
682 if self.is_emitting_map_key {
683 return Err(EncoderError::BadHashmapKey);
685 self.emit_seq(len, f)
687 fn emit_tuple_struct_arg<F>(&mut self, idx: usize, f: F) -> EncodeResult
689 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
691 if self.is_emitting_map_key {
692 return Err(EncoderError::BadHashmapKey);
694 self.emit_seq_elt(idx, f)
697 fn emit_option<F>(&mut self, f: F) -> EncodeResult
699 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
701 if self.is_emitting_map_key {
702 return Err(EncoderError::BadHashmapKey);
706 fn emit_option_none(&mut self) -> EncodeResult {
707 if self.is_emitting_map_key {
708 return Err(EncoderError::BadHashmapKey);
712 fn emit_option_some<F>(&mut self, f: F) -> EncodeResult
714 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
716 if self.is_emitting_map_key {
717 return Err(EncoderError::BadHashmapKey);
722 fn emit_seq<F>(&mut self, _len: usize, f: F) -> EncodeResult
724 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
726 if self.is_emitting_map_key {
727 return Err(EncoderError::BadHashmapKey);
729 write!(self.writer, "[")?;
731 write!(self.writer, "]")?;
735 fn emit_seq_elt<F>(&mut self, idx: usize, f: F) -> EncodeResult
737 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
739 if self.is_emitting_map_key {
740 return Err(EncoderError::BadHashmapKey);
743 write!(self.writer, ",")?;
748 fn emit_map<F>(&mut self, _len: usize, f: F) -> EncodeResult
750 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
752 if self.is_emitting_map_key {
753 return Err(EncoderError::BadHashmapKey);
755 write!(self.writer, "{{")?;
757 write!(self.writer, "}}")?;
761 fn emit_map_elt_key<F>(&mut self, idx: usize, f: F) -> EncodeResult
763 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
765 if self.is_emitting_map_key {
766 return Err(EncoderError::BadHashmapKey);
769 write!(self.writer, ",")?
771 self.is_emitting_map_key = true;
773 self.is_emitting_map_key = false;
777 fn emit_map_elt_val<F>(&mut self, _idx: usize, f: F) -> EncodeResult
779 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
781 if self.is_emitting_map_key {
782 return Err(EncoderError::BadHashmapKey);
784 write!(self.writer, ":")?;
789 /// Another encoder for JSON, but prints out human-readable JSON instead of
791 pub struct PrettyEncoder<'a> {
792 writer: &'a mut (dyn fmt::Write + 'a),
795 is_emitting_map_key: bool,
798 impl<'a> PrettyEncoder<'a> {
799 /// Creates a new encoder whose output will be written to the specified writer
800 pub fn new(writer: &'a mut dyn fmt::Write) -> PrettyEncoder<'a> {
801 PrettyEncoder { writer, curr_indent: 0, indent: 2, is_emitting_map_key: false }
804 /// Sets the number of spaces to indent for each level.
805 /// This is safe to set during encoding.
806 pub fn set_indent(&mut self, indent: usize) {
807 // self.indent very well could be 0 so we need to use checked division.
808 let level = self.curr_indent.checked_div(self.indent).unwrap_or(0);
809 self.indent = indent;
810 self.curr_indent = level * self.indent;
814 impl<'a> crate::Encoder for PrettyEncoder<'a> {
815 type Error = EncoderError;
817 fn emit_unit(&mut self) -> EncodeResult {
818 if self.is_emitting_map_key {
819 return Err(EncoderError::BadHashmapKey);
821 write!(self.writer, "null
")?;
825 fn emit_usize(&mut self, v: usize) -> EncodeResult {
826 emit_enquoted_if_mapkey!(self, v)
828 fn emit_u128(&mut self, v: u128) -> EncodeResult {
829 emit_enquoted_if_mapkey!(self, v)
831 fn emit_u64(&mut self, v: u64) -> EncodeResult {
832 emit_enquoted_if_mapkey!(self, v)
834 fn emit_u32(&mut self, v: u32) -> EncodeResult {
835 emit_enquoted_if_mapkey!(self, v)
837 fn emit_u16(&mut self, v: u16) -> EncodeResult {
838 emit_enquoted_if_mapkey!(self, v)
840 fn emit_u8(&mut self, v: u8) -> EncodeResult {
841 emit_enquoted_if_mapkey!(self, v)
844 fn emit_isize(&mut self, v: isize) -> EncodeResult {
845 emit_enquoted_if_mapkey!(self, v)
847 fn emit_i128(&mut self, v: i128) -> EncodeResult {
848 emit_enquoted_if_mapkey!(self, v)
850 fn emit_i64(&mut self, v: i64) -> EncodeResult {
851 emit_enquoted_if_mapkey!(self, v)
853 fn emit_i32(&mut self, v: i32) -> EncodeResult {
854 emit_enquoted_if_mapkey!(self, v)
856 fn emit_i16(&mut self, v: i16) -> EncodeResult {
857 emit_enquoted_if_mapkey!(self, v)
859 fn emit_i8(&mut self, v: i8) -> EncodeResult {
860 emit_enquoted_if_mapkey!(self, v)
863 fn emit_bool(&mut self, v: bool) -> EncodeResult {
864 if self.is_emitting_map_key {
865 return Err(EncoderError::BadHashmapKey);
868 write!(self.writer, "true")?;
870 write!(self.writer, "false")?;
875 fn emit_f64(&mut self, v: f64) -> EncodeResult {
876 emit_enquoted_if_mapkey!(self, fmt_number_or_null(v))
878 fn emit_f32(&mut self, v: f32) -> EncodeResult {
879 self.emit_f64(f64::from(v))
882 fn emit_char(&mut self, v: char) -> EncodeResult {
883 escape_char(self.writer, v)
885 fn emit_str(&mut self, v: &str) -> EncodeResult {
886 escape_str(self.writer, v)
888 fn emit_raw_bytes(&mut self, s: &[u8]) -> Result<(), Self::Error> {
895 fn emit_enum<F>(&mut self, _name: &str, f: F) -> EncodeResult
897 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
902 fn emit_enum_variant<F>(&mut self, name: &str, _id: usize, cnt: usize, f: F) -> EncodeResult
904 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
907 escape_str(self.writer, name)
909 if self.is_emitting_map_key {
910 return Err(EncoderError::BadHashmapKey);
912 writeln!(self.writer, "{{")?;
913 self.curr_indent += self.indent;
914 spaces(self.writer, self.curr_indent)?;
915 write!(self.writer, "\"variant
\": ")?;
916 escape_str(self.writer, name)?;
917 writeln!(self.writer, ",")?;
918 spaces(self.writer, self.curr_indent)?;
919 writeln!(self.writer, "\"fields
\": [")?;
920 self.curr_indent += self.indent;
922 self.curr_indent -= self.indent;
923 writeln!(self.writer)?;
924 spaces(self.writer, self.curr_indent)?;
925 self.curr_indent -= self.indent;
926 writeln!(self.writer, "]")?;
927 spaces(self.writer, self.curr_indent)?;
928 write!(self.writer, "}}")?;
933 fn emit_enum_variant_arg<F>(&mut self, idx: usize, f: F) -> EncodeResult
935 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
937 if self.is_emitting_map_key {
938 return Err(EncoderError::BadHashmapKey);
941 writeln!(self.writer, ",")?;
943 spaces(self.writer, self.curr_indent)?;
947 fn emit_enum_struct_variant<F>(
955 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
957 if self.is_emitting_map_key {
958 return Err(EncoderError::BadHashmapKey);
960 self.emit_enum_variant(name, id, cnt, f)
963 fn emit_enum_struct_variant_field<F>(&mut self, _: &str, idx: usize, f: F) -> EncodeResult
965 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
967 if self.is_emitting_map_key {
968 return Err(EncoderError::BadHashmapKey);
970 self.emit_enum_variant_arg(idx, f)
973 fn emit_struct<F>(&mut self, _: &str, len: usize, f: F) -> EncodeResult
975 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
977 if self.is_emitting_map_key {
978 return Err(EncoderError::BadHashmapKey);
981 write!(self.writer, "{{}
}")?;
983 write!(self.writer, "{{")?;
984 self.curr_indent += self.indent;
986 self.curr_indent -= self.indent;
987 writeln!(self.writer)?;
988 spaces(self.writer, self.curr_indent)?;
989 write!(self.writer, "}}")?;
994 fn emit_struct_field<F>(&mut self, name: &str, idx: usize, f: F) -> EncodeResult
996 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
998 if self.is_emitting_map_key {
999 return Err(EncoderError::BadHashmapKey);
1002 writeln!(self.writer)?;
1004 writeln!(self.writer, ",")?;
1006 spaces(self.writer, self.curr_indent)?;
1007 escape_str(self.writer, name)?;
1008 write!(self.writer, ": ")?;
1012 fn emit_tuple<F>(&mut self, len: usize, f: F) -> EncodeResult
1014 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
1016 if self.is_emitting_map_key {
1017 return Err(EncoderError::BadHashmapKey);
1019 self.emit_seq(len, f)
1021 fn emit_tuple_arg<F>(&mut self, idx: usize, f: F) -> EncodeResult
1023 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
1025 if self.is_emitting_map_key {
1026 return Err(EncoderError::BadHashmapKey);
1028 self.emit_seq_elt(idx, f)
1031 fn emit_tuple_struct<F>(&mut self, _: &str, len: usize, f: F) -> EncodeResult
1033 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
1035 if self.is_emitting_map_key {
1036 return Err(EncoderError::BadHashmapKey);
1038 self.emit_seq(len, f)
1040 fn emit_tuple_struct_arg<F>(&mut self, idx: usize, f: F) -> EncodeResult
1042 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
1044 if self.is_emitting_map_key {
1045 return Err(EncoderError::BadHashmapKey);
1047 self.emit_seq_elt(idx, f)
1050 fn emit_option<F>(&mut self, f: F) -> EncodeResult
1052 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
1054 if self.is_emitting_map_key {
1055 return Err(EncoderError::BadHashmapKey);
1059 fn emit_option_none(&mut self) -> EncodeResult {
1060 if self.is_emitting_map_key {
1061 return Err(EncoderError::BadHashmapKey);
1065 fn emit_option_some<F>(&mut self, f: F) -> EncodeResult
1067 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
1069 if self.is_emitting_map_key {
1070 return Err(EncoderError::BadHashmapKey);
1075 fn emit_seq<F>(&mut self, len: usize, f: F) -> EncodeResult
1077 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
1079 if self.is_emitting_map_key {
1080 return Err(EncoderError::BadHashmapKey);
1083 write!(self.writer, "[]")?;
1085 write!(self.writer, "[")?;
1086 self.curr_indent += self.indent;
1088 self.curr_indent -= self.indent;
1089 writeln!(self.writer)?;
1090 spaces(self.writer, self.curr_indent)?;
1091 write!(self.writer, "]")?;
1096 fn emit_seq_elt<F>(&mut self, idx: usize, f: F) -> EncodeResult
1098 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
1100 if self.is_emitting_map_key {
1101 return Err(EncoderError::BadHashmapKey);
1104 writeln!(self.writer)?;
1106 writeln!(self.writer, ",")?;
1108 spaces(self.writer, self.curr_indent)?;
1112 fn emit_map<F>(&mut self, len: usize, f: F) -> EncodeResult
1114 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
1116 if self.is_emitting_map_key {
1117 return Err(EncoderError::BadHashmapKey);
1120 write!(self.writer, "{{}
}")?;
1122 write!(self.writer, "{{")?;
1123 self.curr_indent += self.indent;
1125 self.curr_indent -= self.indent;
1126 writeln!(self.writer)?;
1127 spaces(self.writer, self.curr_indent)?;
1128 write!(self.writer, "}}")?;
1133 fn emit_map_elt_key<F>(&mut self, idx: usize, f: F) -> EncodeResult
1135 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
1137 if self.is_emitting_map_key {
1138 return Err(EncoderError::BadHashmapKey);
1141 writeln!(self.writer)?;
1143 writeln!(self.writer, ",")?;
1145 spaces(self.writer, self.curr_indent)?;
1146 self.is_emitting_map_key = true;
1148 self.is_emitting_map_key = false;
1152 fn emit_map_elt_val<F>(&mut self, _idx: usize, f: F) -> EncodeResult
1154 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
1156 if self.is_emitting_map_key {
1157 return Err(EncoderError::BadHashmapKey);
1159 write!(self.writer, ": ")?;
1164 impl<E: crate::Encoder> Encodable<E> for Json {
1165 fn encode(&self, e: &mut E) -> Result<(), E::Error> {
1167 Json::I64(v) => v.encode(e),
1168 Json::U64(v) => v.encode(e),
1169 Json::F64(v) => v.encode(e),
1170 Json::String(ref v) => v.encode(e),
1171 Json::Boolean(v) => v.encode(e),
1172 Json::Array(ref v) => v.encode(e),
1173 Json::Object(ref v) => v.encode(e),
1174 Json::Null => e.emit_unit(),
1179 /// Creates an `AsJson` wrapper which can be used to print a value as JSON
1180 /// on-the-fly via `write!`
1181 pub fn as_json<T>(t: &T) -> AsJson<'_, T> {
1185 /// Creates an `AsPrettyJson` wrapper which can be used to print a value as JSON
1186 /// on-the-fly via `write!`
1187 pub fn as_pretty_json<T>(t: &T) -> AsPrettyJson<'_, T> {
1188 AsPrettyJson { inner: t, indent: None }
1192 /// Borrow this json object as a pretty object to generate a pretty
1193 /// representation for it via `Display`.
1194 pub fn pretty(&self) -> PrettyJson<'_> {
1195 PrettyJson { inner: self }
1198 /// If the Json value is an Object, returns the value associated with the provided key.
1199 /// Otherwise, returns None.
1200 pub fn find(&self, key: &str) -> Option<&Json> {
1202 Json::Object(ref map) => map.get(key),
1207 /// Attempts to get a nested Json Object for each key in `keys`.
1208 /// If any key is found not to exist, `find_path` will return `None`.
1209 /// Otherwise, it will return the Json value associated with the final key.
1210 pub fn find_path<'a>(&'a self, keys: &[&str]) -> Option<&'a Json> {
1211 let mut target = self;
1213 target = target.find(*key)?;
1218 /// If the Json value is an Object, performs a depth-first search until
1219 /// a value associated with the provided key is found. If no value is found
1220 /// or the Json value is not an Object, returns `None`.
1221 pub fn search(&self, key: &str) -> Option<&Json> {
1223 Json::Object(ref map) => match map.get(key) {
1224 Some(json_value) => Some(json_value),
1226 for v in map.values() {
1227 match v.search(key) {
1228 x if x.is_some() => return x,
1239 /// Returns `true` if the Json value is an `Object`.
1240 pub fn is_object(&self) -> bool {
1241 self.as_object().is_some()
1244 /// If the Json value is an `Object`, returns the associated `BTreeMap`;
1245 /// returns `None` otherwise.
1246 pub fn as_object(&self) -> Option<&Object> {
1248 Json::Object(ref map) => Some(map),
1253 /// Returns `true` if the Json value is an `Array`.
1254 pub fn is_array(&self) -> bool {
1255 self.as_array().is_some()
1258 /// If the Json value is an `Array`, returns the associated vector;
1259 /// returns `None` otherwise.
1260 pub fn as_array(&self) -> Option<&Array> {
1262 Json::Array(ref array) => Some(&*array),
1267 /// Returns `true` if the Json value is a `String`.
1268 pub fn is_string(&self) -> bool {
1269 self.as_string().is_some()
1272 /// If the Json value is a `String`, returns the associated `str`;
1273 /// returns `None` otherwise.
1274 pub fn as_string(&self) -> Option<&str> {
1276 Json::String(ref s) => Some(&s[..]),
1281 /// Returns `true` if the Json value is a `Number`.
1282 pub fn is_number(&self) -> bool {
1283 matches!(*self, Json::I64(_) | Json::U64(_) | Json::F64(_))
1286 /// Returns `true` if the Json value is a `i64`.
1287 pub fn is_i64(&self) -> bool {
1288 matches!(*self, Json::I64(_))
1291 /// Returns `true` if the Json value is a `u64`.
1292 pub fn is_u64(&self) -> bool {
1293 matches!(*self, Json::U64(_))
1296 /// Returns `true` if the Json value is a `f64`.
1297 pub fn is_f64(&self) -> bool {
1298 matches!(*self, Json::F64(_))
1301 /// If the Json value is a number, returns or cast it to a `i64`;
1302 /// returns `None` otherwise.
1303 pub fn as_i64(&self) -> Option<i64> {
1305 Json::I64(n) => Some(n),
1306 Json::U64(n) => Some(n as i64),
1311 /// If the Json value is a number, returns or cast it to a `u64`;
1312 /// returns `None` otherwise.
1313 pub fn as_u64(&self) -> Option<u64> {
1315 Json::I64(n) => Some(n as u64),
1316 Json::U64(n) => Some(n),
1321 /// If the Json value is a number, returns or cast it to a `f64`;
1322 /// returns `None` otherwise.
1323 pub fn as_f64(&self) -> Option<f64> {
1325 Json::I64(n) => Some(n as f64),
1326 Json::U64(n) => Some(n as f64),
1327 Json::F64(n) => Some(n),
1332 /// Returns `true` if the Json value is a `Boolean`.
1333 pub fn is_boolean(&self) -> bool {
1334 self.as_boolean().is_some()
1337 /// If the Json value is a `Boolean`, returns the associated `bool`;
1338 /// returns `None` otherwise.
1339 pub fn as_boolean(&self) -> Option<bool> {
1341 Json::Boolean(b) => Some(b),
1346 /// Returns `true` if the Json value is a `Null`.
1347 pub fn is_null(&self) -> bool {
1348 self.as_null().is_some()
1351 /// If the Json value is a `Null`, returns `()`;
1352 /// returns `None` otherwise.
1353 pub fn as_null(&self) -> Option<()> {
1355 Json::Null => Some(()),
1361 impl<'a> Index<&'a str> for Json {
1364 fn index(&self, idx: &'a str) -> &Json {
1365 self.find(idx).unwrap()
1369 impl Index<usize> for Json {
1372 fn index(&self, idx: usize) -> &Json {
1374 Json::Array(ref v) => &v[idx],
1375 _ => panic!("can only index Json with
usize if it is an array
"),
1380 /// The output of the streaming parser.
1381 #[derive(PartialEq, Clone, Debug)]
1382 pub enum JsonEvent {
1391 StringValue(string::String),
1396 #[derive(PartialEq, Debug)]
1398 // Parse a value in an array, true means first element.
1400 // Parse ',' or ']' after an element in an array.
1402 // Parse a key:value in an object, true means first element.
1404 // Parse ',' or ']' after an element in an object.
1408 // Expecting the stream to end.
1410 // Parsing can't continue.
1414 /// A Stack represents the current position of the parser in the logical
1415 /// structure of the JSON stream.
1417 /// An example is `foo.bar[3].x`.
1420 stack: Vec<InternalStackElement>,
1421 str_buffer: Vec<u8>,
1424 /// StackElements compose a Stack.
1426 /// As an example, `StackElement::Key("foo
")`, `StackElement::Key("bar
")`,
1427 /// `StackElement::Index(3)`, and `StackElement::Key("x
")` are the
1428 /// StackElements composing the stack that represents `foo.bar[3].x`.
1429 #[derive(PartialEq, Clone, Debug)]
1430 pub enum StackElement<'l> {
1435 // Internally, Key elements are stored as indices in a buffer to avoid
1436 // allocating a string for every member of an object.
1437 #[derive(PartialEq, Clone, Debug)]
1438 enum InternalStackElement {
1440 InternalKey(u16, u16), // start, size
1444 pub fn new() -> Stack {
1448 /// Returns The number of elements in the Stack.
1449 pub fn len(&self) -> usize {
1453 /// Returns `true` if the stack is empty.
1454 pub fn is_empty(&self) -> bool {
1455 self.stack.is_empty()
1458 /// Provides access to the StackElement at a given index.
1459 /// lower indices are at the bottom of the stack while higher indices are
1461 pub fn get(&self, idx: usize) -> StackElement<'_> {
1462 match self.stack[idx] {
1463 InternalIndex(i) => StackElement::Index(i),
1464 InternalKey(start, size) => StackElement::Key(
1465 str::from_utf8(&self.str_buffer[start as usize..start as usize + size as usize])
1471 /// Compares this stack with an array of StackElement<'_>s.
1472 pub fn is_equal_to(&self, rhs: &[StackElement<'_>]) -> bool {
1473 if self.stack.len() != rhs.len() {
1476 for (i, r) in rhs.iter().enumerate() {
1477 if self.get(i) != *r {
1484 /// Returns `true` if the bottom-most elements of this stack are the same as
1485 /// the ones passed as parameter.
1486 pub fn starts_with(&self, rhs: &[StackElement<'_>]) -> bool {
1487 if self.stack.len() < rhs.len() {
1490 for (i, r) in rhs.iter().enumerate() {
1491 if self.get(i) != *r {
1498 /// Returns `true` if the top-most elements of this stack are the same as
1499 /// the ones passed as parameter.
1500 pub fn ends_with(&self, rhs: &[StackElement<'_>]) -> bool {
1501 if self.stack.len() < rhs.len() {
1504 let offset = self.stack.len() - rhs.len();
1505 for (i, r) in rhs.iter().enumerate() {
1506 if self.get(i + offset) != *r {
1513 /// Returns the top-most element (if any).
1514 pub fn top(&self) -> Option<StackElement<'_>> {
1515 match self.stack.last() {
1517 Some(&InternalIndex(i)) => Some(StackElement::Index(i)),
1518 Some(&InternalKey(start, size)) => Some(StackElement::Key(
1519 str::from_utf8(&self.str_buffer[start as usize..(start + size) as usize]).unwrap(),
1524 // Used by Parser to insert StackElement::Key elements at the top of the stack.
1525 fn push_key(&mut self, key: string::String) {
1526 self.stack.push(InternalKey(self.str_buffer.len() as u16, key.len() as u16));
1527 self.str_buffer.extend(key.as_bytes());
1530 // Used by Parser to insert StackElement::Index elements at the top of the stack.
1531 fn push_index(&mut self, index: u32) {
1532 self.stack.push(InternalIndex(index));
1535 // Used by Parser to remove the top-most element of the stack.
1537 assert!(!self.is_empty());
1538 match *self.stack.last().unwrap() {
1539 InternalKey(_, sz) => {
1540 let new_size = self.str_buffer.len() - sz as usize;
1541 self.str_buffer.truncate(new_size);
1543 InternalIndex(_) => {}
1548 // Used by Parser to test whether the top-most element is an index.
1549 fn last_is_index(&self) -> bool {
1550 matches!(self.stack.last(), Some(InternalIndex(_)))
1553 // Used by Parser to increment the index of the top-most element.
1554 fn bump_index(&mut self) {
1555 let len = self.stack.len();
1556 let idx = match *self.stack.last().unwrap() {
1557 InternalIndex(i) => i + 1,
1562 self.stack[len - 1] = InternalIndex(idx);
1566 /// A streaming JSON parser implemented as an iterator of JsonEvent, consuming
1567 /// an iterator of char.
1568 pub struct Parser<T> {
1573 // We maintain a stack representing where we are in the logical structure
1574 // of the JSON stream.
1576 // A state machine is kept to make it possible to interrupt and resume parsing.
1580 impl<T: Iterator<Item = char>> Iterator for Parser<T> {
1581 type Item = JsonEvent;
1583 fn next(&mut self) -> Option<JsonEvent> {
1584 if self.state == ParseFinished {
1588 if self.state == ParseBeforeFinish {
1589 self.parse_whitespace();
1590 // Make sure there is no trailing characters.
1592 self.state = ParseFinished;
1595 return Some(self.error_event(TrailingCharacters));
1603 impl<T: Iterator<Item = char>> Parser<T> {
1604 /// Creates the JSON parser.
1605 pub fn new(rdr: T) -> Parser<T> {
1606 let mut p = Parser {
1611 stack: Stack::new(),
1618 /// Provides access to the current position in the logical structure of the
1620 pub fn stack(&self) -> &Stack {
1624 fn eof(&self) -> bool {
1627 fn ch_or_null(&self) -> char {
1628 self.ch.unwrap_or('\x00')
1630 fn bump(&mut self) {
1631 self.ch = self.rdr.next();
1633 if self.ch_is('\n') {
1641 fn next_char(&mut self) -> Option<char> {
1645 fn ch_is(&self, c: char) -> bool {
1649 fn error<U>(&self, reason: ErrorCode) -> Result<U, ParserError> {
1650 Err(SyntaxError(reason, self.line, self.col))
1653 fn parse_whitespace(&mut self) {
1654 while self.ch_is(' ') || self.ch_is('\n') || self.ch_is('\t') || self.ch_is('\r') {
1659 fn parse_number(&mut self) -> JsonEvent {
1660 let neg = if self.ch_is('-') {
1667 let res = match self.parse_u64() {
1674 if self.ch_is('.') || self.ch_is('e') || self.ch_is('E') {
1675 let mut res = res as f64;
1677 if self.ch_is('.') {
1678 res = match self.parse_decimal(res) {
1686 if self.ch_is('e') || self.ch_is('E') {
1687 res = match self.parse_exponent(res) {
1701 let res = (res as i64).wrapping_neg();
1703 // Make sure we didn't underflow.
1705 Error(SyntaxError(InvalidNumber, self.line, self.col))
1714 fn parse_u64(&mut self) -> Result<u64, ParserError> {
1715 let mut accum = 0u64;
1716 let last_accum = 0; // necessary to detect overflow.
1718 match self.ch_or_null() {
1722 // A leading '0' must be the only digit before the decimal point.
1723 if let '0'..='9' = self.ch_or_null() {
1724 return self.error(InvalidNumber);
1729 match self.ch_or_null() {
1731 accum = accum.wrapping_mul(10);
1732 accum = accum.wrapping_add((c as u64) - ('0' as u64));
1734 // Detect overflow by comparing to the last value.
1735 if accum <= last_accum {
1736 return self.error(InvalidNumber);
1745 _ => return self.error(InvalidNumber),
1751 fn parse_decimal(&mut self, mut res: f64) -> Result<f64, ParserError> {
1754 // Make sure a digit follows the decimal place.
1755 match self.ch_or_null() {
1757 _ => return self.error(InvalidNumber),
1762 match self.ch_or_null() {
1765 res += (((c as isize) - ('0' as isize)) as f64) * dec;
1775 fn parse_exponent(&mut self, mut res: f64) -> Result<f64, ParserError> {
1779 let mut neg_exp = false;
1781 if self.ch_is('+') {
1783 } else if self.ch_is('-') {
1788 // Make sure a digit follows the exponent place.
1789 match self.ch_or_null() {
1791 _ => return self.error(InvalidNumber),
1794 match self.ch_or_null() {
1797 exp += (c as usize) - ('0' as usize);
1805 let exp = 10_f64.powi(exp as i32);
1815 fn decode_hex_escape(&mut self) -> Result<u16, ParserError> {
1818 while i < 4 && !self.eof() {
1820 n = match self.ch_or_null() {
1821 c @ '0'..='9' => n * 16 + ((c as u16) - ('0' as u16)),
1822 'a' | 'A' => n * 16 + 10,
1823 'b' | 'B' => n * 16 + 11,
1824 'c' | 'C' => n * 16 + 12,
1825 'd' | 'D' => n * 16 + 13,
1826 'e' | 'E' => n * 16 + 14,
1827 'f' | 'F' => n * 16 + 15,
1828 _ => return self.error(InvalidEscape),
1834 // Error out if we didn't parse 4 digits.
1836 return self.error(InvalidEscape);
1842 fn parse_str(&mut self) -> Result<string::String, ParserError> {
1843 let mut escape = false;
1844 let mut res = string::String::new();
1849 return self.error(EOFWhileParsingString);
1853 match self.ch_or_null() {
1854 '"'
=> res
.push('
"'),
1855 '\\' => res.push('\\'),
1856 '/' => res.push('/'),
1857 'b' => res.push('\x08'),
1858 'f' => res.push('\x0c'),
1859 'n' => res.push('\n'),
1860 'r' => res.push('\r'),
1861 't' => res.push('\t'),
1862 'u' => match self.decode_hex_escape()? {
1863 0xDC00..=0xDFFF => return self.error(LoneLeadingSurrogateInHexEscape),
1865 // Non-BMP characters are encoded as a sequence of
1866 // two hex escapes, representing UTF-16 surrogates.
1867 n1 @ 0xD800..=0xDBFF => {
1868 match (self.next_char(), self.next_char()) {
1869 (Some('\\'), Some('u')) => (),
1870 _ => return self.error(UnexpectedEndOfHexEscape),
1873 let n2 = self.decode_hex_escape()?;
1874 if !(0xDC00..=0xDFFF).contains(&n2) {
1875 return self.error(LoneLeadingSurrogateInHexEscape);
1878 (u32::from(n1 - 0xD800) << 10 | u32::from(n2 - 0xDC00)) + 0x1_0000;
1879 res.push(char::from_u32(c).unwrap());
1882 n => match char::from_u32(u32::from(n)) {
1883 Some(c) => res.push(c),
1884 None => return self.error(InvalidUnicodeCodePoint),
1887 _ => return self.error(InvalidEscape),
1890 } else if self.ch_is('\\') {
1898 Some(c
) => res
.push(c
),
1899 None
=> unreachable
!(),
1905 // Invoked at each iteration, consumes the stream until it has enough
1906 // information to return a JsonEvent.
1907 // Manages an internal state so that parsing can be interrupted and resumed.
1908 // Also keeps track of the position in the logical structure of the json
1909 // stream isize the form of a stack that can be queried by the user using the
1911 fn parse(&mut self) -> JsonEvent
{
1913 // The only paths where the loop can spin a new iteration
1914 // are in the cases ParseArrayComma and ParseObjectComma if ','
1915 // is parsed. In these cases the state is set to (respectively)
1916 // ParseArray(false) and ParseObject(false), which always return,
1917 // so there is no risk of getting stuck in an infinite loop.
1918 // All other paths return before the end of the loop's iteration.
1919 self.parse_whitespace();
1923 return self.parse_start();
1925 ParseArray(first
) => {
1926 return self.parse_array(first
);
1928 ParseArrayComma
=> {
1929 if let Some(evt
) = self.parse_array_comma_or_end() {
1933 ParseObject(first
) => {
1934 return self.parse_object(first
);
1936 ParseObjectComma
=> {
1938 if self.ch_is('
,'
) {
1939 self.state
= ParseObject(false);
1942 return self.parse_object_end();
1946 return self.error_event(InvalidSyntax
);
1952 fn parse_start(&mut self) -> JsonEvent
{
1953 let val
= self.parse_value();
1954 self.state
= match val
{
1955 Error(_
) => ParseFinished
,
1956 ArrayStart
=> ParseArray(true),
1957 ObjectStart
=> ParseObject(true),
1958 _
=> ParseBeforeFinish
,
1963 fn parse_array(&mut self, first
: bool
) -> JsonEvent
{
1964 if self.ch_is('
]'
) {
1966 self.error_event(InvalidSyntax
)
1968 self.state
= if self.stack
.is_empty() {
1970 } else if self.stack
.last_is_index() {
1980 self.stack
.push_index(0);
1982 let val
= self.parse_value();
1983 self.state
= match val
{
1984 Error(_
) => ParseFinished
,
1985 ArrayStart
=> ParseArray(true),
1986 ObjectStart
=> ParseObject(true),
1987 _
=> ParseArrayComma
,
1993 fn parse_array_comma_or_end(&mut self) -> Option
<JsonEvent
> {
1994 if self.ch_is('
,'
) {
1995 self.stack
.bump_index();
1996 self.state
= ParseArray(false);
1999 } else if self.ch_is('
]'
) {
2001 self.state
= if self.stack
.is_empty() {
2003 } else if self.stack
.last_is_index() {
2010 } else if self.eof() {
2011 Some(self.error_event(EOFWhileParsingArray
))
2013 Some(self.error_event(InvalidSyntax
))
2017 fn parse_object(&mut self, first
: bool
) -> JsonEvent
{
2018 if self.ch_is('
}'
) {
2020 if self.stack
.is_empty() {
2021 return self.error_event(TrailingComma
);
2026 self.state
= if self.stack
.is_empty() {
2028 } else if self.stack
.last_is_index() {
2037 return self.error_event(EOFWhileParsingObject
);
2039 if !self.ch_is('
"') {
2040 return self.error_event(KeyMustBeAString);
2042 let s = match self.parse_str() {
2045 self.state = ParseFinished;
2049 self.parse_whitespace();
2051 return self.error_event(EOFWhileParsingObject);
2052 } else if self.ch_or_null() != ':' {
2053 return self.error_event(ExpectedColon);
2055 self.stack.push_key(s);
2057 self.parse_whitespace();
2059 let val = self.parse_value();
2061 self.state = match val {
2062 Error(_) => ParseFinished,
2063 ArrayStart => ParseArray(true),
2064 ObjectStart => ParseObject(true),
2065 _ => ParseObjectComma,
2070 fn parse_object_end(&mut self) -> JsonEvent {
2071 if self.ch_is('}') {
2072 self.state = if self.stack.is_empty() {
2074 } else if self.stack.last_is_index() {
2081 } else if self.eof() {
2082 self.error_event(EOFWhileParsingObject)
2084 self.error_event(InvalidSyntax)
2088 fn parse_value(&mut self) -> JsonEvent {
2090 return self.error_event(EOFWhileParsingValue);
2092 match self.ch_or_null() {
2093 'n' => self.parse_ident("ull
", NullValue),
2094 't' => self.parse_ident("rue
", BooleanValue(true)),
2095 'f' => self.parse_ident("alse
", BooleanValue(false)),
2096 '0'..='9' | '-' => self.parse_number(),
2097 '"'
=> match self.parse_str() {
2098 Ok(s
) => StringValue(s
),
2109 _
=> self.error_event(InvalidSyntax
),
2113 fn parse_ident(&mut self, ident
: &str, value
: JsonEvent
) -> JsonEvent
{
2114 if ident
.chars().all(|c
| Some(c
) == self.next_char()) {
2118 Error(SyntaxError(InvalidSyntax
, self.line
, self.col
))
2122 fn error_event(&mut self, reason
: ErrorCode
) -> JsonEvent
{
2123 self.state
= ParseFinished
;
2124 Error(SyntaxError(reason
, self.line
, self.col
))
2128 /// A Builder consumes a json::Parser to create a generic Json structure.
2129 pub struct Builder
<T
> {
2131 token
: Option
<JsonEvent
>,
2134 impl<T
: Iterator
<Item
= char>> Builder
<T
> {
2135 /// Creates a JSON Builder.
2136 pub fn new(src
: T
) -> Builder
<T
> {
2137 Builder { parser: Parser::new(src), token: None }
2140 // Decode a Json value from a Parser.
2141 pub fn build(&mut self) -> Result
<Json
, BuilderError
> {
2143 let result
= self.build_value();
2147 Some(Error(ref e
)) => {
2148 return Err(e
.clone());
2151 panic
!("unexpected token {:?}", tok
.clone());
2157 fn bump(&mut self) {
2158 self.token
= self.parser
.next();
2161 fn build_value(&mut self) -> Result
<Json
, BuilderError
> {
2163 Some(NullValue
) => Ok(Json
::Null
),
2164 Some(I64Value(n
)) => Ok(Json
::I64(n
)),
2165 Some(U64Value(n
)) => Ok(Json
::U64(n
)),
2166 Some(F64Value(n
)) => Ok(Json
::F64(n
)),
2167 Some(BooleanValue(b
)) => Ok(Json
::Boolean(b
)),
2168 Some(StringValue(ref mut s
)) => {
2169 let mut temp
= string
::String
::new();
2171 Ok(Json
::String(temp
))
2173 Some(Error(ref e
)) => Err(e
.clone()),
2174 Some(ArrayStart
) => self.build_array(),
2175 Some(ObjectStart
) => self.build_object(),
2176 Some(ObjectEnd
) => self.parser
.error(InvalidSyntax
),
2177 Some(ArrayEnd
) => self.parser
.error(InvalidSyntax
),
2178 None
=> self.parser
.error(EOFWhileParsingValue
),
2182 fn build_array(&mut self) -> Result
<Json
, BuilderError
> {
2184 let mut values
= Vec
::new();
2187 if self.token
== Some(ArrayEnd
) {
2188 return Ok(Json
::Array(values
.into_iter().collect()));
2190 match self.build_value() {
2191 Ok(v
) => values
.push(v
),
2192 Err(e
) => return Err(e
),
2198 fn build_object(&mut self) -> Result
<Json
, BuilderError
> {
2201 let mut values
= BTreeMap
::new();
2205 Some(ObjectEnd
) => {
2206 return Ok(Json
::Object(values
));
2208 Some(Error(ref e
)) => {
2209 return Err(e
.clone());
2216 let key
= match self.parser
.stack().top() {
2217 Some(StackElement
::Key(k
)) => k
.to_owned(),
2219 panic
!("invalid state");
2222 match self.build_value() {
2224 values
.insert(key
, value
);
2232 self.parser
.error(EOFWhileParsingObject
)
2236 /// Decodes a json value from an `&mut io::Read`
2237 pub fn from_reader(rdr
: &mut dyn Read
) -> Result
<Json
, BuilderError
> {
2238 let mut contents
= Vec
::new();
2239 match rdr
.read_to_end(&mut contents
) {
2241 Err(e
) => return Err(io_error_to_error(e
)),
2243 let s
= match str::from_utf8(&contents
).ok() {
2245 _
=> return Err(SyntaxError(NotUtf8
, 0, 0)),
2247 let mut builder
= Builder
::new(s
.chars());
2251 /// Decodes a json value from a string
2252 pub fn from_str(s
: &str) -> Result
<Json
, BuilderError
> {
2253 let mut builder
= Builder
::new(s
.chars());
2257 /// A structure to decode JSON to values in rust.
2258 pub struct Decoder
{
2263 /// Creates a new decoder instance for decoding the specified JSON value.
2264 pub fn new(json
: Json
) -> Decoder
{
2265 Decoder { stack: vec![json] }
2268 fn pop(&mut self) -> Json
{
2269 self.stack
.pop().unwrap()
2273 macro_rules
! expect
{
2274 ($e
:expr
, Null
) => {{
2276 Json
::Null
=> Ok(()),
2277 other
=> Err(ExpectedError("Null".to_owned(), other
.to_string())),
2280 ($e
:expr
, $t
:ident
) => {{
2282 Json
::$
t(v
) => Ok(v
),
2283 other
=> Err(ExpectedError(stringify
!($t
).to_owned(), other
.to_string())),
2288 macro_rules
! read_primitive
{
2289 ($name
:ident
, $ty
:ty
) => {
2290 fn $
name(&mut self) -> DecodeResult
<$ty
> {
2292 Json
::I64(f
) => Ok(f
as $ty
),
2293 Json
::U64(f
) => Ok(f
as $ty
),
2294 Json
::F64(f
) => Err(ExpectedError("Integer".to_owned(), f
.to_string())),
2295 // re: #12967.. a type w/ numeric keys (ie HashMap<usize, V> etc)
2296 // is going to have a string here, as per JSON spec.
2297 Json
::String(s
) => match s
.parse().ok() {
2299 None
=> Err(ExpectedError("Number".to_owned(), s
)),
2301 value
=> Err(ExpectedError("Number".to_owned(), value
.to_string())),
2307 impl crate::Decoder
for Decoder
{
2308 type Error
= DecoderError
;
2310 fn read_nil(&mut self) -> DecodeResult
<()> {
2311 expect
!(self.pop(), Null
)
2314 read_primitive
! { read_usize, usize }
2315 read_primitive
! { read_u8, u8 }
2316 read_primitive
! { read_u16, u16 }
2317 read_primitive
! { read_u32, u32 }
2318 read_primitive
! { read_u64, u64 }
2319 read_primitive
! { read_u128, u128 }
2320 read_primitive
! { read_isize, isize }
2321 read_primitive
! { read_i8, i8 }
2322 read_primitive
! { read_i16, i16 }
2323 read_primitive
! { read_i32, i32 }
2324 read_primitive
! { read_i64, i64 }
2325 read_primitive
! { read_i128, i128 }
2327 fn read_f32(&mut self) -> DecodeResult
<f32> {
2328 self.read_f64().map(|x
| x
as f32)
2331 fn read_f64(&mut self) -> DecodeResult
<f64> {
2333 Json
::I64(f
) => Ok(f
as f64),
2334 Json
::U64(f
) => Ok(f
as f64),
2335 Json
::F64(f
) => Ok(f
),
2336 Json
::String(s
) => {
2337 // re: #12967.. a type w/ numeric keys (ie HashMap<usize, V> etc)
2338 // is going to have a string here, as per JSON spec.
2339 match s
.parse().ok() {
2341 None
=> Err(ExpectedError("Number".to_owned(), s
)),
2344 Json
::Null
=> Ok(f64::NAN
),
2345 value
=> Err(ExpectedError("Number".to_owned(), value
.to_string())),
2349 fn read_bool(&mut self) -> DecodeResult
<bool
> {
2350 expect
!(self.pop(), Boolean
)
2353 fn read_char(&mut self) -> DecodeResult
<char> {
2354 let s
= self.read_str()?
;
2356 let mut it
= s
.chars();
2357 if let (Some(c
), None
) = (it
.next(), it
.next()) {
2358 // exactly one character
2362 Err(ExpectedError("single character string".to_owned(), s
.to_string()))
2365 fn read_str(&mut self) -> DecodeResult
<Cow
<'_
, str>> {
2366 expect
!(self.pop(), String
).map(Cow
::Owned
)
2369 fn read_raw_bytes_into(&mut self, s
: &mut [u8]) -> Result
<(), Self::Error
> {
2370 for c
in s
.iter_mut() {
2371 *c
= self.read_u8()?
;
2376 fn read_enum
<T
, F
>(&mut self, _name
: &str, f
: F
) -> DecodeResult
<T
>
2378 F
: FnOnce(&mut Decoder
) -> DecodeResult
<T
>,
2383 fn read_enum_variant
<T
, F
>(&mut self, names
: &[&str], mut f
: F
) -> DecodeResult
<T
>
2385 F
: FnMut(&mut Decoder
, usize) -> DecodeResult
<T
>,
2387 let name
= match self.pop() {
2388 Json
::String(s
) => s
,
2389 Json
::Object(mut o
) => {
2390 let n
= match o
.remove(&"variant".to_owned()) {
2391 Some(Json
::String(s
)) => s
,
2392 Some(val
) => return Err(ExpectedError("String".to_owned(), val
.to_string())),
2393 None
=> return Err(MissingFieldError("variant".to_owned())),
2395 match o
.remove(&"fields".to_string()) {
2396 Some(Json
::Array(l
)) => {
2397 self.stack
.extend(l
.into_iter().rev());
2399 Some(val
) => return Err(ExpectedError("Array".to_owned(), val
.to_string())),
2400 None
=> return Err(MissingFieldError("fields".to_owned())),
2404 json
=> return Err(ExpectedError("String or Object".to_owned(), json
.to_string())),
2406 let idx
= match names
.iter().position(|n
| *n
== &name
[..]) {
2408 None
=> return Err(UnknownVariantError(name
)),
2413 fn read_enum_variant_arg
<T
, F
>(&mut self, _idx
: usize, f
: F
) -> DecodeResult
<T
>
2415 F
: FnOnce(&mut Decoder
) -> DecodeResult
<T
>,
2420 fn read_enum_struct_variant
<T
, F
>(&mut self, names
: &[&str], f
: F
) -> DecodeResult
<T
>
2422 F
: FnMut(&mut Decoder
, usize) -> DecodeResult
<T
>,
2424 self.read_enum_variant(names
, f
)
2427 fn read_enum_struct_variant_field
<T
, F
>(
2432 ) -> DecodeResult
<T
>
2434 F
: FnOnce(&mut Decoder
) -> DecodeResult
<T
>,
2436 self.read_enum_variant_arg(idx
, f
)
2439 fn read_struct
<T
, F
>(&mut self, _name
: &str, _len
: usize, f
: F
) -> DecodeResult
<T
>
2441 F
: FnOnce(&mut Decoder
) -> DecodeResult
<T
>,
2443 let value
= f(self)?
;
2448 fn read_struct_field
<T
, F
>(&mut self, name
: &str, _idx
: usize, f
: F
) -> DecodeResult
<T
>
2450 F
: FnOnce(&mut Decoder
) -> DecodeResult
<T
>,
2452 let mut obj
= expect
!(self.pop(), Object
)?
;
2454 let value
= match obj
.remove(&name
.to_string()) {
2456 // Add a Null and try to parse it as an Option<_>
2457 // to get None as a default value.
2458 self.stack
.push(Json
::Null
);
2461 Err(_
) => return Err(MissingFieldError(name
.to_string())),
2465 self.stack
.push(json
);
2469 self.stack
.push(Json
::Object(obj
));
2473 fn read_tuple
<T
, F
>(&mut self, tuple_len
: usize, f
: F
) -> DecodeResult
<T
>
2475 F
: FnOnce(&mut Decoder
) -> DecodeResult
<T
>,
2477 self.read_seq(move |d
, len
| {
2478 if len
== tuple_len
{
2481 Err(ExpectedError(format
!("Tuple{}", tuple_len
), format
!("Tuple{}", len
)))
2486 fn read_tuple_arg
<T
, F
>(&mut self, idx
: usize, f
: F
) -> DecodeResult
<T
>
2488 F
: FnOnce(&mut Decoder
) -> DecodeResult
<T
>,
2490 self.read_seq_elt(idx
, f
)
2493 fn read_tuple_struct
<T
, F
>(&mut self, _name
: &str, len
: usize, f
: F
) -> DecodeResult
<T
>
2495 F
: FnOnce(&mut Decoder
) -> DecodeResult
<T
>,
2497 self.read_tuple(len
, f
)
2500 fn read_tuple_struct_arg
<T
, F
>(&mut self, idx
: usize, f
: F
) -> DecodeResult
<T
>
2502 F
: FnOnce(&mut Decoder
) -> DecodeResult
<T
>,
2504 self.read_tuple_arg(idx
, f
)
2507 fn read_option
<T
, F
>(&mut self, mut f
: F
) -> DecodeResult
<T
>
2509 F
: FnMut(&mut Decoder
, bool
) -> DecodeResult
<T
>,
2512 Json
::Null
=> f(self, false),
2514 self.stack
.push(value
);
2520 fn read_seq
<T
, F
>(&mut self, f
: F
) -> DecodeResult
<T
>
2522 F
: FnOnce(&mut Decoder
, usize) -> DecodeResult
<T
>,
2524 let array
= expect
!(self.pop(), Array
)?
;
2525 let len
= array
.len();
2526 self.stack
.extend(array
.into_iter().rev());
2530 fn read_seq_elt
<T
, F
>(&mut self, _idx
: usize, f
: F
) -> DecodeResult
<T
>
2532 F
: FnOnce(&mut Decoder
) -> DecodeResult
<T
>,
2537 fn read_map
<T
, F
>(&mut self, f
: F
) -> DecodeResult
<T
>
2539 F
: FnOnce(&mut Decoder
, usize) -> DecodeResult
<T
>,
2541 let obj
= expect
!(self.pop(), Object
)?
;
2542 let len
= obj
.len();
2543 for (key
, value
) in obj
{
2544 self.stack
.push(value
);
2545 self.stack
.push(Json
::String(key
));
2550 fn read_map_elt_key
<T
, F
>(&mut self, _idx
: usize, f
: F
) -> DecodeResult
<T
>
2552 F
: FnOnce(&mut Decoder
) -> DecodeResult
<T
>,
2557 fn read_map_elt_val
<T
, F
>(&mut self, _idx
: usize, f
: F
) -> DecodeResult
<T
>
2559 F
: FnOnce(&mut Decoder
) -> DecodeResult
<T
>,
2564 fn error(&mut self, err
: &str) -> DecoderError
{
2565 ApplicationError(err
.to_string())
2569 /// A trait for converting values to JSON
2571 /// Converts the value of `self` to an instance of JSON
2572 fn to_json(&self) -> Json
;
2575 macro_rules
! to_json_impl_i64
{
2577 $
(impl ToJson
for $t
{
2578 fn to_json(&self) -> Json
{
2579 Json
::I64(*self as i64)
2585 to_json_impl_i64
! { isize, i8, i16, i32, i64 }
2587 macro_rules
! to_json_impl_u64
{
2589 $
(impl ToJson
for $t
{
2590 fn to_json(&self) -> Json
{
2591 Json
::U64(*self as u64)
2597 to_json_impl_u64
! { usize, u8, u16, u32, u64 }
2599 impl ToJson
for Json
{
2600 fn to_json(&self) -> Json
{
2605 impl ToJson
for f32 {
2606 fn to_json(&self) -> Json
{
2607 f64::from(*self).to_json()
2611 impl ToJson
for f64 {
2612 fn to_json(&self) -> Json
{
2613 match self.classify() {
2614 Fp
::Nan
| Fp
::Infinite
=> Json
::Null
,
2615 _
=> Json
::F64(*self),
2620 impl ToJson
for () {
2621 fn to_json(&self) -> Json
{
2626 impl ToJson
for bool
{
2627 fn to_json(&self) -> Json
{
2628 Json
::Boolean(*self)
2632 impl ToJson
for str {
2633 fn to_json(&self) -> Json
{
2634 Json
::String(self.to_string())
2638 impl ToJson
for string
::String
{
2639 fn to_json(&self) -> Json
{
2640 Json
::String((*self).clone())
2644 macro_rules
! tuple_impl
{
2645 // use variables to indicate the arity of the tuple
2646 ($
($tyvar
:ident
),* ) => {
2647 // the trailing commas are for the 1 tuple
2649 $
( $tyvar
: ToJson
),*
2650 > ToJson
for ( $
( $tyvar
),* , ) {
2653 #[allow(non_snake_case)]
2654 fn to_json(&self) -> Json
{
2656 ($
(ref $tyvar
),*,) => Json
::Array(vec
![$
($tyvar
.to_json()),*])
2665 tuple_impl
! {A, B, C}
2666 tuple_impl
! {A, B, C, D}
2667 tuple_impl
! {A, B, C, D, E}
2668 tuple_impl
! {A, B, C, D, E, F}
2669 tuple_impl
! {A, B, C, D, E, F, G}
2670 tuple_impl
! {A, B, C, D, E, F, G, H}
2671 tuple_impl
! {A, B, C, D, E, F, G, H, I}
2672 tuple_impl
! {A, B, C, D, E, F, G, H, I, J}
2673 tuple_impl
! {A, B, C, D, E, F, G, H, I, J, K}
2674 tuple_impl
! {A, B, C, D, E, F, G, H, I, J, K, L}
2676 impl<A
: ToJson
> ToJson
for [A
] {
2677 fn to_json(&self) -> Json
{
2678 Json
::Array(self.iter().map(|elt
| elt
.to_json()).collect())
2682 impl<A
: ToJson
> ToJson
for Vec
<A
> {
2683 fn to_json(&self) -> Json
{
2684 Json
::Array(self.iter().map(|elt
| elt
.to_json()).collect())
2688 impl<T
: ToString
, A
: ToJson
> ToJson
for BTreeMap
<T
, A
> {
2689 fn to_json(&self) -> Json
{
2690 let mut d
= BTreeMap
::new();
2691 for (key
, value
) in self {
2692 d
.insert(key
.to_string(), value
.to_json());
2698 impl<A
: ToJson
> ToJson
for HashMap
<string
::String
, A
> {
2699 fn to_json(&self) -> Json
{
2700 let mut d
= BTreeMap
::new();
2701 for (key
, value
) in self {
2702 d
.insert((*key
).clone(), value
.to_json());
2708 impl<A
: ToJson
> ToJson
for Option
<A
> {
2709 fn to_json(&self) -> Json
{
2712 Some(ref value
) => value
.to_json(),
2717 struct FormatShim
<'a
, 'b
> {
2718 inner
: &'a
mut fmt
::Formatter
<'b
>,
2721 impl<'a
, 'b
> fmt
::Write
for FormatShim
<'a
, 'b
> {
2722 fn write_str(&mut self, s
: &str) -> fmt
::Result
{
2723 match self.inner
.write_str(s
) {
2725 Err(_
) => Err(fmt
::Error
),
2730 impl fmt
::Display
for Json
{
2731 /// Encodes a json value into a string
2732 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
2733 let mut shim
= FormatShim { inner: f }
;
2734 let mut encoder
= Encoder
::new(&mut shim
);
2735 match self.encode(&mut encoder
) {
2737 Err(_
) => Err(fmt
::Error
),
2742 impl<'a
> fmt
::Display
for PrettyJson
<'a
> {
2743 /// Encodes a json value into a string
2744 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
2745 let mut shim
= FormatShim { inner: f }
;
2746 let mut encoder
= PrettyEncoder
::new(&mut shim
);
2747 match self.inner
.encode(&mut encoder
) {
2749 Err(_
) => Err(fmt
::Error
),
2754 impl<'a
, T
: for<'r
> Encodable
<Encoder
<'r
>>> fmt
::Display
for AsJson
<'a
, T
> {
2755 /// Encodes a json value into a string
2756 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
2757 let mut shim
= FormatShim { inner: f }
;
2758 let mut encoder
= Encoder
::new(&mut shim
);
2759 match self.inner
.encode(&mut encoder
) {
2761 Err(_
) => Err(fmt
::Error
),
2766 impl<'a
, T
> AsPrettyJson
<'a
, T
> {
2767 /// Sets the indentation level for the emitted JSON
2768 pub fn indent(mut self, indent
: usize) -> AsPrettyJson
<'a
, T
> {
2769 self.indent
= Some(indent
);
2774 impl<'a
, T
: for<'x
> Encodable
<PrettyEncoder
<'x
>>> fmt
::Display
for AsPrettyJson
<'a
, T
> {
2775 /// Encodes a json value into a string
2776 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
2777 let mut shim
= FormatShim { inner: f }
;
2778 let mut encoder
= PrettyEncoder
::new(&mut shim
);
2779 if let Some(n
) = self.indent
{
2780 encoder
.set_indent(n
);
2782 match self.inner
.encode(&mut encoder
) {
2784 Err(_
) => Err(fmt
::Error
),
2789 impl FromStr
for Json
{
2790 type Err
= BuilderError
;
2791 fn from_str(s
: &str) -> Result
<Json
, BuilderError
> {