]> git.lizzy.rs Git - rust.git/blob - src/librustc_serialize/json.rs
Rollup merge of #75482 - GuillaumeGomez:cleanup-e0752, r=pickfire
[rust.git] / src / librustc_serialize / json.rs
1 // Rust JSON serialization library.
2 // Copyright (c) 2011 Google Inc.
3
4 #![forbid(non_camel_case_types)]
5 #![allow(missing_docs)]
6
7 //! JSON parsing and serialization
8 //!
9 //! # What is JSON?
10 //!
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.
14 //!
15 //! Data types that can be encoded are JavaScript types (see the `Json` enum for more details):
16 //!
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
21 //!   same array
22 //! * `Object`: equivalent to rust's `BTreeMap<String, json::Json>`
23 //! * `Null`
24 //!
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
28 //!
29 //! ```json
30 //! {
31 //!     "FirstName": "John",
32 //!     "LastName": "Doe",
33 //!     "Age": 43,
34 //!     "Address": {
35 //!         "Street": "Downing Street 10",
36 //!         "City": "London",
37 //!         "Country": "Great Britain"
38 //!     },
39 //!     "PhoneNumbers": [
40 //!         "+44 1234567",
41 //!         "+44 2345678"
42 //!     ]
43 //! }
44 //! ```
45 //!
46 //! # Rust Type-based Encoding and Decoding
47 //!
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::RustcEncodable` trait.
51 //! To be able to decode a piece of data, it must implement the `serialize::RustcDecodable` trait.
52 //! The Rust compiler provides an annotation to automatically generate the code for these traits:
53 //! `#[derive(RustcDecodable, RustcEncodable)]`
54 //!
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.
59 //!
60 //! When using `ToJson` the `RustcEncodable` trait implementation is not mandatory.
61 //!
62 //! # Examples of use
63 //!
64 //! ## Using Autoserialization
65 //!
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.
68 //!
69 //! ```rust
70 //! # #![feature(rustc_private)]
71 //! use rustc_serialize::json;
72 //!
73 //! // Automatically generate `Decodable` and `Encodable` trait implementations
74 //! #[derive(RustcDecodable, RustcEncodable)]
75 //! pub struct TestStruct  {
76 //!     data_int: u8,
77 //!     data_str: String,
78 //!     data_vector: Vec<u8>,
79 //! }
80 //!
81 //! let object = TestStruct {
82 //!     data_int: 1,
83 //!     data_str: "homura".to_string(),
84 //!     data_vector: vec![2,3,4,5],
85 //! };
86 //!
87 //! // Serialize using `json::encode`
88 //! let encoded = json::encode(&object).unwrap();
89 //!
90 //! // Deserialize using `json::decode`
91 //! let decoded: TestStruct = json::decode(&encoded[..]).unwrap();
92 //! ```
93 //!
94 //! ## Using the `ToJson` trait
95 //!
96 //! The examples above use the `ToJson` trait to generate the JSON string, which is required
97 //! for custom mappings.
98 //!
99 //! ### Simple example of `ToJson` usage
100 //!
101 //! ```rust
102 //! # #![feature(rustc_private)]
103 //! use rustc_serialize::json::{self, ToJson, Json};
104 //!
105 //! // A custom data structure
106 //! struct ComplexNum {
107 //!     a: f64,
108 //!     b: f64,
109 //! }
110 //!
111 //! // JSON value representation
112 //! impl ToJson for ComplexNum {
113 //!     fn to_json(&self) -> Json {
114 //!         Json::String(format!("{}+{}i", self.a, self.b))
115 //!     }
116 //! }
117 //!
118 //! // Only generate `RustcEncodable` trait implementation
119 //! #[derive(RustcEncodable)]
120 //! pub struct ComplexNumRecord {
121 //!     uid: u8,
122 //!     dsc: String,
123 //!     val: Json,
124 //! }
125 //!
126 //! let num = ComplexNum { a: 0.0001, b: 12.539 };
127 //! let data: String = json::encode(&ComplexNumRecord{
128 //!     uid: 1,
129 //!     dsc: "test".to_string(),
130 //!     val: num.to_json(),
131 //! }).unwrap();
132 //! println!("data: {}", data);
133 //! // data: {"uid":1,"dsc":"test","val":"0.0001+12.539i"};
134 //! ```
135 //!
136 //! ### Verbose example of `ToJson` usage
137 //!
138 //! ```rust
139 //! # #![feature(rustc_private)]
140 //! use std::collections::BTreeMap;
141 //! use rustc_serialize::json::{self, Json, ToJson};
142 //!
143 //! // Only generate `RustcDecodable` trait implementation
144 //! #[derive(RustcDecodable)]
145 //! pub struct TestStruct {
146 //!     data_int: u8,
147 //!     data_str: String,
148 //!     data_vector: Vec<u8>,
149 //! }
150 //!
151 //! // Specify encoding method manually
152 //! impl ToJson for TestStruct {
153 //!     fn to_json(&self) -> Json {
154 //!         let mut d = BTreeMap::new();
155 //!         // All standard types implement `to_json()`, so use it
156 //!         d.insert("data_int".to_string(), self.data_int.to_json());
157 //!         d.insert("data_str".to_string(), self.data_str.to_json());
158 //!         d.insert("data_vector".to_string(), self.data_vector.to_json());
159 //!         Json::Object(d)
160 //!     }
161 //! }
162 //!
163 //! // Serialize using `ToJson`
164 //! let input_data = TestStruct {
165 //!     data_int: 1,
166 //!     data_str: "madoka".to_string(),
167 //!     data_vector: vec![2,3,4,5],
168 //! };
169 //! let json_obj: Json = input_data.to_json();
170 //! let json_str: String = json_obj.to_string();
171 //!
172 //! // Deserialize like before
173 //! let decoded: TestStruct = json::decode(&json_str).unwrap();
174 //! ```
175
176 use self::DecoderError::*;
177 use self::ErrorCode::*;
178 use self::InternalStackElement::*;
179 use self::JsonEvent::*;
180 use self::ParserError::*;
181 use self::ParserState::*;
182
183 use std::borrow::Cow;
184 use std::collections::{BTreeMap, HashMap};
185 use std::io;
186 use std::io::prelude::*;
187 use std::mem::swap;
188 use std::num::FpCategory as Fp;
189 use std::ops::Index;
190 use std::str::FromStr;
191 use std::string;
192 use std::{char, fmt, str};
193
194 use crate::Encodable;
195
196 /// Represents a json value
197 #[derive(Clone, PartialEq, PartialOrd, Debug)]
198 pub enum Json {
199     I64(i64),
200     U64(u64),
201     F64(f64),
202     String(string::String),
203     Boolean(bool),
204     Array(self::Array),
205     Object(self::Object),
206     Null,
207 }
208
209 pub type Array = Vec<Json>;
210 pub type Object = BTreeMap<string::String, Json>;
211
212 pub struct PrettyJson<'a> {
213     inner: &'a Json,
214 }
215
216 pub struct AsJson<'a, T> {
217     inner: &'a T,
218 }
219 pub struct AsPrettyJson<'a, T> {
220     inner: &'a T,
221     indent: Option<usize>,
222 }
223
224 /// The errors that can arise while parsing a JSON stream.
225 #[derive(Clone, Copy, PartialEq, Debug)]
226 pub enum ErrorCode {
227     InvalidSyntax,
228     InvalidNumber,
229     EOFWhileParsingObject,
230     EOFWhileParsingArray,
231     EOFWhileParsingValue,
232     EOFWhileParsingString,
233     KeyMustBeAString,
234     ExpectedColon,
235     TrailingCharacters,
236     TrailingComma,
237     InvalidEscape,
238     InvalidUnicodeCodePoint,
239     LoneLeadingSurrogateInHexEscape,
240     UnexpectedEndOfHexEscape,
241     UnrecognizedHex,
242     NotFourDigit,
243     NotUtf8,
244 }
245
246 #[derive(Clone, PartialEq, Debug)]
247 pub enum ParserError {
248     /// msg, line, col
249     SyntaxError(ErrorCode, usize, usize),
250     IoError(io::ErrorKind, String),
251 }
252
253 // Builder and Parser have the same errors.
254 pub type BuilderError = ParserError;
255
256 #[derive(Clone, PartialEq, Debug)]
257 pub enum DecoderError {
258     ParseError(ParserError),
259     ExpectedError(string::String, string::String),
260     MissingFieldError(string::String),
261     UnknownVariantError(string::String),
262     ApplicationError(string::String),
263 }
264
265 #[derive(Copy, Clone, Debug)]
266 pub enum EncoderError {
267     FmtError(fmt::Error),
268     BadHashmapKey,
269 }
270
271 /// Returns a readable error string for a given error code.
272 pub fn error_str(error: ErrorCode) -> &'static str {
273     match error {
274         InvalidSyntax => "invalid syntax",
275         InvalidNumber => "invalid number",
276         EOFWhileParsingObject => "EOF While parsing object",
277         EOFWhileParsingArray => "EOF While parsing array",
278         EOFWhileParsingValue => "EOF While parsing value",
279         EOFWhileParsingString => "EOF While parsing string",
280         KeyMustBeAString => "key must be a string",
281         ExpectedColon => "expected `:`",
282         TrailingCharacters => "trailing characters",
283         TrailingComma => "trailing comma",
284         InvalidEscape => "invalid escape",
285         UnrecognizedHex => "invalid \\u{ esc}ape (unrecognized hex)",
286         NotFourDigit => "invalid \\u{ esc}ape (not four digits)",
287         NotUtf8 => "contents not utf-8",
288         InvalidUnicodeCodePoint => "invalid Unicode code point",
289         LoneLeadingSurrogateInHexEscape => "lone leading surrogate in hex escape",
290         UnexpectedEndOfHexEscape => "unexpected end of hex escape",
291     }
292 }
293
294 /// Shortcut function to decode a JSON `&str` into an object
295 pub fn decode<T: crate::Decodable>(s: &str) -> DecodeResult<T> {
296     let json = match from_str(s) {
297         Ok(x) => x,
298         Err(e) => return Err(ParseError(e)),
299     };
300
301     let mut decoder = Decoder::new(json);
302     crate::Decodable::decode(&mut decoder)
303 }
304
305 /// Shortcut function to encode a `T` into a JSON `String`
306 pub fn encode<T: crate::Encodable>(object: &T) -> Result<string::String, EncoderError> {
307     let mut s = String::new();
308     {
309         let mut encoder = Encoder::new(&mut s);
310         object.encode(&mut encoder)?;
311     }
312     Ok(s)
313 }
314
315 impl fmt::Display for ErrorCode {
316     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
317         error_str(*self).fmt(f)
318     }
319 }
320
321 fn io_error_to_error(io: io::Error) -> ParserError {
322     IoError(io.kind(), io.to_string())
323 }
324
325 impl fmt::Display for ParserError {
326     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
327         // FIXME this should be a nicer error
328         fmt::Debug::fmt(self, f)
329     }
330 }
331
332 impl fmt::Display for DecoderError {
333     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
334         // FIXME this should be a nicer error
335         fmt::Debug::fmt(self, f)
336     }
337 }
338
339 impl std::error::Error for DecoderError {}
340
341 impl fmt::Display for EncoderError {
342     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
343         // FIXME this should be a nicer error
344         fmt::Debug::fmt(self, f)
345     }
346 }
347
348 impl std::error::Error for EncoderError {}
349
350 impl From<fmt::Error> for EncoderError {
351     /// Converts a [`fmt::Error`] into `EncoderError`
352     ///
353     /// This conversion does not allocate memory.
354     fn from(err: fmt::Error) -> EncoderError {
355         EncoderError::FmtError(err)
356     }
357 }
358
359 pub type EncodeResult = Result<(), EncoderError>;
360 pub type DecodeResult<T> = Result<T, DecoderError>;
361
362 fn escape_str(wr: &mut dyn fmt::Write, v: &str) -> EncodeResult {
363     wr.write_str("\"")?;
364
365     let mut start = 0;
366
367     for (i, byte) in v.bytes().enumerate() {
368         let escaped = match byte {
369             b'"' => "\\\"",
370             b'\\' => "\\\\",
371             b'\x00' => "\\u0000",
372             b'\x01' => "\\u0001",
373             b'\x02' => "\\u0002",
374             b'\x03' => "\\u0003",
375             b'\x04' => "\\u0004",
376             b'\x05' => "\\u0005",
377             b'\x06' => "\\u0006",
378             b'\x07' => "\\u0007",
379             b'\x08' => "\\b",
380             b'\t' => "\\t",
381             b'\n' => "\\n",
382             b'\x0b' => "\\u000b",
383             b'\x0c' => "\\f",
384             b'\r' => "\\r",
385             b'\x0e' => "\\u000e",
386             b'\x0f' => "\\u000f",
387             b'\x10' => "\\u0010",
388             b'\x11' => "\\u0011",
389             b'\x12' => "\\u0012",
390             b'\x13' => "\\u0013",
391             b'\x14' => "\\u0014",
392             b'\x15' => "\\u0015",
393             b'\x16' => "\\u0016",
394             b'\x17' => "\\u0017",
395             b'\x18' => "\\u0018",
396             b'\x19' => "\\u0019",
397             b'\x1a' => "\\u001a",
398             b'\x1b' => "\\u001b",
399             b'\x1c' => "\\u001c",
400             b'\x1d' => "\\u001d",
401             b'\x1e' => "\\u001e",
402             b'\x1f' => "\\u001f",
403             b'\x7f' => "\\u007f",
404             _ => {
405                 continue;
406             }
407         };
408
409         if start < i {
410             wr.write_str(&v[start..i])?;
411         }
412
413         wr.write_str(escaped)?;
414
415         start = i + 1;
416     }
417
418     if start != v.len() {
419         wr.write_str(&v[start..])?;
420     }
421
422     wr.write_str("\"")?;
423     Ok(())
424 }
425
426 fn escape_char(writer: &mut dyn fmt::Write, v: char) -> EncodeResult {
427     escape_str(writer, v.encode_utf8(&mut [0; 4]))
428 }
429
430 fn spaces(wr: &mut dyn fmt::Write, mut n: usize) -> EncodeResult {
431     const BUF: &str = "                ";
432
433     while n >= BUF.len() {
434         wr.write_str(BUF)?;
435         n -= BUF.len();
436     }
437
438     if n > 0 {
439         wr.write_str(&BUF[..n])?;
440     }
441     Ok(())
442 }
443
444 fn fmt_number_or_null(v: f64) -> string::String {
445     match v.classify() {
446         Fp::Nan | Fp::Infinite => string::String::from("null"),
447         _ if v.fract() != 0f64 => v.to_string(),
448         _ => v.to_string() + ".0",
449     }
450 }
451
452 /// A structure for implementing serialization to JSON.
453 pub struct Encoder<'a> {
454     writer: &'a mut (dyn fmt::Write + 'a),
455     is_emitting_map_key: bool,
456 }
457
458 impl<'a> Encoder<'a> {
459     /// Creates a new JSON encoder whose output will be written to the writer
460     /// specified.
461     pub fn new(writer: &'a mut dyn fmt::Write) -> Encoder<'a> {
462         Encoder { writer, is_emitting_map_key: false }
463     }
464 }
465
466 macro_rules! emit_enquoted_if_mapkey {
467     ($enc:ident,$e:expr) => {{
468         if $enc.is_emitting_map_key {
469             write!($enc.writer, "\"{}\"", $e)?;
470         } else {
471             write!($enc.writer, "{}", $e)?;
472         }
473         Ok(())
474     }};
475 }
476
477 impl<'a> crate::Encoder for Encoder<'a> {
478     type Error = EncoderError;
479
480     fn emit_unit(&mut self) -> EncodeResult {
481         if self.is_emitting_map_key {
482             return Err(EncoderError::BadHashmapKey);
483         }
484         write!(self.writer, "null")?;
485         Ok(())
486     }
487
488     fn emit_usize(&mut self, v: usize) -> EncodeResult {
489         emit_enquoted_if_mapkey!(self, v)
490     }
491     fn emit_u128(&mut self, v: u128) -> EncodeResult {
492         emit_enquoted_if_mapkey!(self, v)
493     }
494     fn emit_u64(&mut self, v: u64) -> EncodeResult {
495         emit_enquoted_if_mapkey!(self, v)
496     }
497     fn emit_u32(&mut self, v: u32) -> EncodeResult {
498         emit_enquoted_if_mapkey!(self, v)
499     }
500     fn emit_u16(&mut self, v: u16) -> EncodeResult {
501         emit_enquoted_if_mapkey!(self, v)
502     }
503     fn emit_u8(&mut self, v: u8) -> EncodeResult {
504         emit_enquoted_if_mapkey!(self, v)
505     }
506
507     fn emit_isize(&mut self, v: isize) -> EncodeResult {
508         emit_enquoted_if_mapkey!(self, v)
509     }
510     fn emit_i128(&mut self, v: i128) -> EncodeResult {
511         emit_enquoted_if_mapkey!(self, v)
512     }
513     fn emit_i64(&mut self, v: i64) -> EncodeResult {
514         emit_enquoted_if_mapkey!(self, v)
515     }
516     fn emit_i32(&mut self, v: i32) -> EncodeResult {
517         emit_enquoted_if_mapkey!(self, v)
518     }
519     fn emit_i16(&mut self, v: i16) -> EncodeResult {
520         emit_enquoted_if_mapkey!(self, v)
521     }
522     fn emit_i8(&mut self, v: i8) -> EncodeResult {
523         emit_enquoted_if_mapkey!(self, v)
524     }
525
526     fn emit_bool(&mut self, v: bool) -> EncodeResult {
527         if self.is_emitting_map_key {
528             return Err(EncoderError::BadHashmapKey);
529         }
530         if v {
531             write!(self.writer, "true")?;
532         } else {
533             write!(self.writer, "false")?;
534         }
535         Ok(())
536     }
537
538     fn emit_f64(&mut self, v: f64) -> EncodeResult {
539         emit_enquoted_if_mapkey!(self, fmt_number_or_null(v))
540     }
541     fn emit_f32(&mut self, v: f32) -> EncodeResult {
542         self.emit_f64(f64::from(v))
543     }
544
545     fn emit_char(&mut self, v: char) -> EncodeResult {
546         escape_char(self.writer, v)
547     }
548     fn emit_str(&mut self, v: &str) -> EncodeResult {
549         escape_str(self.writer, v)
550     }
551
552     fn emit_enum<F>(&mut self, _name: &str, f: F) -> EncodeResult
553     where
554         F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
555     {
556         f(self)
557     }
558
559     fn emit_enum_variant<F>(&mut self, name: &str, _id: usize, cnt: usize, f: F) -> EncodeResult
560     where
561         F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
562     {
563         // enums are encoded as strings or objects
564         // Bunny => "Bunny"
565         // Kangaroo(34,"William") => {"variant": "Kangaroo", "fields": [34,"William"]}
566         if cnt == 0 {
567             escape_str(self.writer, name)
568         } else {
569             if self.is_emitting_map_key {
570                 return Err(EncoderError::BadHashmapKey);
571             }
572             write!(self.writer, "{{\"variant\":")?;
573             escape_str(self.writer, name)?;
574             write!(self.writer, ",\"fields\":[")?;
575             f(self)?;
576             write!(self.writer, "]}}")?;
577             Ok(())
578         }
579     }
580
581     fn emit_enum_variant_arg<F>(&mut self, idx: usize, f: F) -> EncodeResult
582     where
583         F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
584     {
585         if self.is_emitting_map_key {
586             return Err(EncoderError::BadHashmapKey);
587         }
588         if idx != 0 {
589             write!(self.writer, ",")?;
590         }
591         f(self)
592     }
593
594     fn emit_enum_struct_variant<F>(
595         &mut self,
596         name: &str,
597         id: usize,
598         cnt: usize,
599         f: F,
600     ) -> EncodeResult
601     where
602         F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
603     {
604         if self.is_emitting_map_key {
605             return Err(EncoderError::BadHashmapKey);
606         }
607         self.emit_enum_variant(name, id, cnt, f)
608     }
609
610     fn emit_enum_struct_variant_field<F>(&mut self, _: &str, idx: usize, f: F) -> EncodeResult
611     where
612         F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
613     {
614         if self.is_emitting_map_key {
615             return Err(EncoderError::BadHashmapKey);
616         }
617         self.emit_enum_variant_arg(idx, f)
618     }
619
620     fn emit_struct<F>(&mut self, _: &str, _: usize, f: F) -> EncodeResult
621     where
622         F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
623     {
624         if self.is_emitting_map_key {
625             return Err(EncoderError::BadHashmapKey);
626         }
627         write!(self.writer, "{{")?;
628         f(self)?;
629         write!(self.writer, "}}")?;
630         Ok(())
631     }
632
633     fn emit_struct_field<F>(&mut self, name: &str, idx: usize, f: F) -> EncodeResult
634     where
635         F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
636     {
637         if self.is_emitting_map_key {
638             return Err(EncoderError::BadHashmapKey);
639         }
640         if idx != 0 {
641             write!(self.writer, ",")?;
642         }
643         escape_str(self.writer, name)?;
644         write!(self.writer, ":")?;
645         f(self)
646     }
647
648     fn emit_tuple<F>(&mut self, len: usize, f: F) -> EncodeResult
649     where
650         F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
651     {
652         if self.is_emitting_map_key {
653             return Err(EncoderError::BadHashmapKey);
654         }
655         self.emit_seq(len, f)
656     }
657     fn emit_tuple_arg<F>(&mut self, idx: usize, f: F) -> EncodeResult
658     where
659         F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
660     {
661         if self.is_emitting_map_key {
662             return Err(EncoderError::BadHashmapKey);
663         }
664         self.emit_seq_elt(idx, f)
665     }
666
667     fn emit_tuple_struct<F>(&mut self, _name: &str, len: usize, f: F) -> EncodeResult
668     where
669         F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
670     {
671         if self.is_emitting_map_key {
672             return Err(EncoderError::BadHashmapKey);
673         }
674         self.emit_seq(len, f)
675     }
676     fn emit_tuple_struct_arg<F>(&mut self, idx: usize, f: F) -> EncodeResult
677     where
678         F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
679     {
680         if self.is_emitting_map_key {
681             return Err(EncoderError::BadHashmapKey);
682         }
683         self.emit_seq_elt(idx, f)
684     }
685
686     fn emit_option<F>(&mut self, f: F) -> EncodeResult
687     where
688         F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
689     {
690         if self.is_emitting_map_key {
691             return Err(EncoderError::BadHashmapKey);
692         }
693         f(self)
694     }
695     fn emit_option_none(&mut self) -> EncodeResult {
696         if self.is_emitting_map_key {
697             return Err(EncoderError::BadHashmapKey);
698         }
699         self.emit_unit()
700     }
701     fn emit_option_some<F>(&mut self, f: F) -> EncodeResult
702     where
703         F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
704     {
705         if self.is_emitting_map_key {
706             return Err(EncoderError::BadHashmapKey);
707         }
708         f(self)
709     }
710
711     fn emit_seq<F>(&mut self, _len: usize, f: F) -> EncodeResult
712     where
713         F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
714     {
715         if self.is_emitting_map_key {
716             return Err(EncoderError::BadHashmapKey);
717         }
718         write!(self.writer, "[")?;
719         f(self)?;
720         write!(self.writer, "]")?;
721         Ok(())
722     }
723
724     fn emit_seq_elt<F>(&mut self, idx: usize, f: F) -> EncodeResult
725     where
726         F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
727     {
728         if self.is_emitting_map_key {
729             return Err(EncoderError::BadHashmapKey);
730         }
731         if idx != 0 {
732             write!(self.writer, ",")?;
733         }
734         f(self)
735     }
736
737     fn emit_map<F>(&mut self, _len: usize, f: F) -> EncodeResult
738     where
739         F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
740     {
741         if self.is_emitting_map_key {
742             return Err(EncoderError::BadHashmapKey);
743         }
744         write!(self.writer, "{{")?;
745         f(self)?;
746         write!(self.writer, "}}")?;
747         Ok(())
748     }
749
750     fn emit_map_elt_key<F>(&mut self, idx: usize, f: F) -> EncodeResult
751     where
752         F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
753     {
754         if self.is_emitting_map_key {
755             return Err(EncoderError::BadHashmapKey);
756         }
757         if idx != 0 {
758             write!(self.writer, ",")?
759         }
760         self.is_emitting_map_key = true;
761         f(self)?;
762         self.is_emitting_map_key = false;
763         Ok(())
764     }
765
766     fn emit_map_elt_val<F>(&mut self, _idx: usize, f: F) -> EncodeResult
767     where
768         F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
769     {
770         if self.is_emitting_map_key {
771             return Err(EncoderError::BadHashmapKey);
772         }
773         write!(self.writer, ":")?;
774         f(self)
775     }
776 }
777
778 /// Another encoder for JSON, but prints out human-readable JSON instead of
779 /// compact data
780 pub struct PrettyEncoder<'a> {
781     writer: &'a mut (dyn fmt::Write + 'a),
782     curr_indent: usize,
783     indent: usize,
784     is_emitting_map_key: bool,
785 }
786
787 impl<'a> PrettyEncoder<'a> {
788     /// Creates a new encoder whose output will be written to the specified writer
789     pub fn new(writer: &'a mut dyn fmt::Write) -> PrettyEncoder<'a> {
790         PrettyEncoder { writer, curr_indent: 0, indent: 2, is_emitting_map_key: false }
791     }
792
793     /// Sets the number of spaces to indent for each level.
794     /// This is safe to set during encoding.
795     pub fn set_indent(&mut self, indent: usize) {
796         // self.indent very well could be 0 so we need to use checked division.
797         let level = self.curr_indent.checked_div(self.indent).unwrap_or(0);
798         self.indent = indent;
799         self.curr_indent = level * self.indent;
800     }
801 }
802
803 impl<'a> crate::Encoder for PrettyEncoder<'a> {
804     type Error = EncoderError;
805
806     fn emit_unit(&mut self) -> EncodeResult {
807         if self.is_emitting_map_key {
808             return Err(EncoderError::BadHashmapKey);
809         }
810         write!(self.writer, "null")?;
811         Ok(())
812     }
813
814     fn emit_usize(&mut self, v: usize) -> EncodeResult {
815         emit_enquoted_if_mapkey!(self, v)
816     }
817     fn emit_u128(&mut self, v: u128) -> EncodeResult {
818         emit_enquoted_if_mapkey!(self, v)
819     }
820     fn emit_u64(&mut self, v: u64) -> EncodeResult {
821         emit_enquoted_if_mapkey!(self, v)
822     }
823     fn emit_u32(&mut self, v: u32) -> EncodeResult {
824         emit_enquoted_if_mapkey!(self, v)
825     }
826     fn emit_u16(&mut self, v: u16) -> EncodeResult {
827         emit_enquoted_if_mapkey!(self, v)
828     }
829     fn emit_u8(&mut self, v: u8) -> EncodeResult {
830         emit_enquoted_if_mapkey!(self, v)
831     }
832
833     fn emit_isize(&mut self, v: isize) -> EncodeResult {
834         emit_enquoted_if_mapkey!(self, v)
835     }
836     fn emit_i128(&mut self, v: i128) -> EncodeResult {
837         emit_enquoted_if_mapkey!(self, v)
838     }
839     fn emit_i64(&mut self, v: i64) -> EncodeResult {
840         emit_enquoted_if_mapkey!(self, v)
841     }
842     fn emit_i32(&mut self, v: i32) -> EncodeResult {
843         emit_enquoted_if_mapkey!(self, v)
844     }
845     fn emit_i16(&mut self, v: i16) -> EncodeResult {
846         emit_enquoted_if_mapkey!(self, v)
847     }
848     fn emit_i8(&mut self, v: i8) -> EncodeResult {
849         emit_enquoted_if_mapkey!(self, v)
850     }
851
852     fn emit_bool(&mut self, v: bool) -> EncodeResult {
853         if self.is_emitting_map_key {
854             return Err(EncoderError::BadHashmapKey);
855         }
856         if v {
857             write!(self.writer, "true")?;
858         } else {
859             write!(self.writer, "false")?;
860         }
861         Ok(())
862     }
863
864     fn emit_f64(&mut self, v: f64) -> EncodeResult {
865         emit_enquoted_if_mapkey!(self, fmt_number_or_null(v))
866     }
867     fn emit_f32(&mut self, v: f32) -> EncodeResult {
868         self.emit_f64(f64::from(v))
869     }
870
871     fn emit_char(&mut self, v: char) -> EncodeResult {
872         escape_char(self.writer, v)
873     }
874     fn emit_str(&mut self, v: &str) -> EncodeResult {
875         escape_str(self.writer, v)
876     }
877
878     fn emit_enum<F>(&mut self, _name: &str, f: F) -> EncodeResult
879     where
880         F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
881     {
882         f(self)
883     }
884
885     fn emit_enum_variant<F>(&mut self, name: &str, _id: usize, cnt: usize, f: F) -> EncodeResult
886     where
887         F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
888     {
889         if cnt == 0 {
890             escape_str(self.writer, name)
891         } else {
892             if self.is_emitting_map_key {
893                 return Err(EncoderError::BadHashmapKey);
894             }
895             writeln!(self.writer, "{{")?;
896             self.curr_indent += self.indent;
897             spaces(self.writer, self.curr_indent)?;
898             write!(self.writer, "\"variant\": ")?;
899             escape_str(self.writer, name)?;
900             writeln!(self.writer, ",")?;
901             spaces(self.writer, self.curr_indent)?;
902             writeln!(self.writer, "\"fields\": [")?;
903             self.curr_indent += self.indent;
904             f(self)?;
905             self.curr_indent -= self.indent;
906             writeln!(self.writer)?;
907             spaces(self.writer, self.curr_indent)?;
908             self.curr_indent -= self.indent;
909             writeln!(self.writer, "]")?;
910             spaces(self.writer, self.curr_indent)?;
911             write!(self.writer, "}}")?;
912             Ok(())
913         }
914     }
915
916     fn emit_enum_variant_arg<F>(&mut self, idx: usize, f: F) -> EncodeResult
917     where
918         F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
919     {
920         if self.is_emitting_map_key {
921             return Err(EncoderError::BadHashmapKey);
922         }
923         if idx != 0 {
924             writeln!(self.writer, ",")?;
925         }
926         spaces(self.writer, self.curr_indent)?;
927         f(self)
928     }
929
930     fn emit_enum_struct_variant<F>(
931         &mut self,
932         name: &str,
933         id: usize,
934         cnt: usize,
935         f: F,
936     ) -> EncodeResult
937     where
938         F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
939     {
940         if self.is_emitting_map_key {
941             return Err(EncoderError::BadHashmapKey);
942         }
943         self.emit_enum_variant(name, id, cnt, f)
944     }
945
946     fn emit_enum_struct_variant_field<F>(&mut self, _: &str, idx: usize, f: F) -> EncodeResult
947     where
948         F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
949     {
950         if self.is_emitting_map_key {
951             return Err(EncoderError::BadHashmapKey);
952         }
953         self.emit_enum_variant_arg(idx, f)
954     }
955
956     fn emit_struct<F>(&mut self, _: &str, len: usize, f: F) -> EncodeResult
957     where
958         F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
959     {
960         if self.is_emitting_map_key {
961             return Err(EncoderError::BadHashmapKey);
962         }
963         if len == 0 {
964             write!(self.writer, "{{}}")?;
965         } else {
966             write!(self.writer, "{{")?;
967             self.curr_indent += self.indent;
968             f(self)?;
969             self.curr_indent -= self.indent;
970             writeln!(self.writer)?;
971             spaces(self.writer, self.curr_indent)?;
972             write!(self.writer, "}}")?;
973         }
974         Ok(())
975     }
976
977     fn emit_struct_field<F>(&mut self, name: &str, idx: usize, f: F) -> EncodeResult
978     where
979         F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
980     {
981         if self.is_emitting_map_key {
982             return Err(EncoderError::BadHashmapKey);
983         }
984         if idx == 0 {
985             writeln!(self.writer)?;
986         } else {
987             writeln!(self.writer, ",")?;
988         }
989         spaces(self.writer, self.curr_indent)?;
990         escape_str(self.writer, name)?;
991         write!(self.writer, ": ")?;
992         f(self)
993     }
994
995     fn emit_tuple<F>(&mut self, len: usize, f: F) -> EncodeResult
996     where
997         F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
998     {
999         if self.is_emitting_map_key {
1000             return Err(EncoderError::BadHashmapKey);
1001         }
1002         self.emit_seq(len, f)
1003     }
1004     fn emit_tuple_arg<F>(&mut self, idx: usize, f: F) -> EncodeResult
1005     where
1006         F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
1007     {
1008         if self.is_emitting_map_key {
1009             return Err(EncoderError::BadHashmapKey);
1010         }
1011         self.emit_seq_elt(idx, f)
1012     }
1013
1014     fn emit_tuple_struct<F>(&mut self, _: &str, len: usize, f: F) -> EncodeResult
1015     where
1016         F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
1017     {
1018         if self.is_emitting_map_key {
1019             return Err(EncoderError::BadHashmapKey);
1020         }
1021         self.emit_seq(len, f)
1022     }
1023     fn emit_tuple_struct_arg<F>(&mut self, idx: usize, f: F) -> EncodeResult
1024     where
1025         F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
1026     {
1027         if self.is_emitting_map_key {
1028             return Err(EncoderError::BadHashmapKey);
1029         }
1030         self.emit_seq_elt(idx, f)
1031     }
1032
1033     fn emit_option<F>(&mut self, f: F) -> EncodeResult
1034     where
1035         F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
1036     {
1037         if self.is_emitting_map_key {
1038             return Err(EncoderError::BadHashmapKey);
1039         }
1040         f(self)
1041     }
1042     fn emit_option_none(&mut self) -> EncodeResult {
1043         if self.is_emitting_map_key {
1044             return Err(EncoderError::BadHashmapKey);
1045         }
1046         self.emit_unit()
1047     }
1048     fn emit_option_some<F>(&mut self, f: F) -> EncodeResult
1049     where
1050         F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
1051     {
1052         if self.is_emitting_map_key {
1053             return Err(EncoderError::BadHashmapKey);
1054         }
1055         f(self)
1056     }
1057
1058     fn emit_seq<F>(&mut self, len: usize, f: F) -> EncodeResult
1059     where
1060         F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
1061     {
1062         if self.is_emitting_map_key {
1063             return Err(EncoderError::BadHashmapKey);
1064         }
1065         if len == 0 {
1066             write!(self.writer, "[]")?;
1067         } else {
1068             write!(self.writer, "[")?;
1069             self.curr_indent += self.indent;
1070             f(self)?;
1071             self.curr_indent -= self.indent;
1072             writeln!(self.writer)?;
1073             spaces(self.writer, self.curr_indent)?;
1074             write!(self.writer, "]")?;
1075         }
1076         Ok(())
1077     }
1078
1079     fn emit_seq_elt<F>(&mut self, idx: usize, f: F) -> EncodeResult
1080     where
1081         F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
1082     {
1083         if self.is_emitting_map_key {
1084             return Err(EncoderError::BadHashmapKey);
1085         }
1086         if idx == 0 {
1087             writeln!(self.writer)?;
1088         } else {
1089             writeln!(self.writer, ",")?;
1090         }
1091         spaces(self.writer, self.curr_indent)?;
1092         f(self)
1093     }
1094
1095     fn emit_map<F>(&mut self, len: usize, f: F) -> EncodeResult
1096     where
1097         F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
1098     {
1099         if self.is_emitting_map_key {
1100             return Err(EncoderError::BadHashmapKey);
1101         }
1102         if len == 0 {
1103             write!(self.writer, "{{}}")?;
1104         } else {
1105             write!(self.writer, "{{")?;
1106             self.curr_indent += self.indent;
1107             f(self)?;
1108             self.curr_indent -= self.indent;
1109             writeln!(self.writer)?;
1110             spaces(self.writer, self.curr_indent)?;
1111             write!(self.writer, "}}")?;
1112         }
1113         Ok(())
1114     }
1115
1116     fn emit_map_elt_key<F>(&mut self, idx: usize, f: F) -> EncodeResult
1117     where
1118         F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
1119     {
1120         if self.is_emitting_map_key {
1121             return Err(EncoderError::BadHashmapKey);
1122         }
1123         if idx == 0 {
1124             writeln!(self.writer)?;
1125         } else {
1126             writeln!(self.writer, ",")?;
1127         }
1128         spaces(self.writer, self.curr_indent)?;
1129         self.is_emitting_map_key = true;
1130         f(self)?;
1131         self.is_emitting_map_key = false;
1132         Ok(())
1133     }
1134
1135     fn emit_map_elt_val<F>(&mut self, _idx: usize, f: F) -> EncodeResult
1136     where
1137         F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
1138     {
1139         if self.is_emitting_map_key {
1140             return Err(EncoderError::BadHashmapKey);
1141         }
1142         write!(self.writer, ": ")?;
1143         f(self)
1144     }
1145 }
1146
1147 impl Encodable for Json {
1148     fn encode<E: crate::Encoder>(&self, e: &mut E) -> Result<(), E::Error> {
1149         match *self {
1150             Json::I64(v) => v.encode(e),
1151             Json::U64(v) => v.encode(e),
1152             Json::F64(v) => v.encode(e),
1153             Json::String(ref v) => v.encode(e),
1154             Json::Boolean(v) => v.encode(e),
1155             Json::Array(ref v) => v.encode(e),
1156             Json::Object(ref v) => v.encode(e),
1157             Json::Null => e.emit_unit(),
1158         }
1159     }
1160 }
1161
1162 /// Creates an `AsJson` wrapper which can be used to print a value as JSON
1163 /// on-the-fly via `write!`
1164 pub fn as_json<T>(t: &T) -> AsJson<'_, T> {
1165     AsJson { inner: t }
1166 }
1167
1168 /// Creates an `AsPrettyJson` wrapper which can be used to print a value as JSON
1169 /// on-the-fly via `write!`
1170 pub fn as_pretty_json<T>(t: &T) -> AsPrettyJson<'_, T> {
1171     AsPrettyJson { inner: t, indent: None }
1172 }
1173
1174 impl Json {
1175     /// Borrow this json object as a pretty object to generate a pretty
1176     /// representation for it via `Display`.
1177     pub fn pretty(&self) -> PrettyJson<'_> {
1178         PrettyJson { inner: self }
1179     }
1180
1181     /// If the Json value is an Object, returns the value associated with the provided key.
1182     /// Otherwise, returns None.
1183     pub fn find(&self, key: &str) -> Option<&Json> {
1184         match *self {
1185             Json::Object(ref map) => map.get(key),
1186             _ => None,
1187         }
1188     }
1189
1190     /// Attempts to get a nested Json Object for each key in `keys`.
1191     /// If any key is found not to exist, `find_path` will return `None`.
1192     /// Otherwise, it will return the Json value associated with the final key.
1193     pub fn find_path<'a>(&'a self, keys: &[&str]) -> Option<&'a Json> {
1194         let mut target = self;
1195         for key in keys {
1196             target = target.find(*key)?;
1197         }
1198         Some(target)
1199     }
1200
1201     /// If the Json value is an Object, performs a depth-first search until
1202     /// a value associated with the provided key is found. If no value is found
1203     /// or the Json value is not an Object, returns `None`.
1204     pub fn search(&self, key: &str) -> Option<&Json> {
1205         match *self {
1206             Json::Object(ref map) => match map.get(key) {
1207                 Some(json_value) => Some(json_value),
1208                 None => {
1209                     for v in map.values() {
1210                         match v.search(key) {
1211                             x if x.is_some() => return x,
1212                             _ => (),
1213                         }
1214                     }
1215                     None
1216                 }
1217             },
1218             _ => None,
1219         }
1220     }
1221
1222     /// Returns `true` if the Json value is an `Object`.
1223     pub fn is_object(&self) -> bool {
1224         self.as_object().is_some()
1225     }
1226
1227     /// If the Json value is an `Object`, returns the associated `BTreeMap`;
1228     /// returns `None` otherwise.
1229     pub fn as_object(&self) -> Option<&Object> {
1230         match *self {
1231             Json::Object(ref map) => Some(map),
1232             _ => None,
1233         }
1234     }
1235
1236     /// Returns `true` if the Json value is an `Array`.
1237     pub fn is_array(&self) -> bool {
1238         self.as_array().is_some()
1239     }
1240
1241     /// If the Json value is an `Array`, returns the associated vector;
1242     /// returns `None` otherwise.
1243     pub fn as_array(&self) -> Option<&Array> {
1244         match *self {
1245             Json::Array(ref array) => Some(&*array),
1246             _ => None,
1247         }
1248     }
1249
1250     /// Returns `true` if the Json value is a `String`.
1251     pub fn is_string(&self) -> bool {
1252         self.as_string().is_some()
1253     }
1254
1255     /// If the Json value is a `String`, returns the associated `str`;
1256     /// returns `None` otherwise.
1257     pub fn as_string(&self) -> Option<&str> {
1258         match *self {
1259             Json::String(ref s) => Some(&s[..]),
1260             _ => None,
1261         }
1262     }
1263
1264     /// Returns `true` if the Json value is a `Number`.
1265     pub fn is_number(&self) -> bool {
1266         matches!(*self, Json::I64(_) | Json::U64(_) | Json::F64(_))
1267     }
1268
1269     /// Returns `true` if the Json value is a `i64`.
1270     pub fn is_i64(&self) -> bool {
1271         matches!(*self, Json::I64(_))
1272     }
1273
1274     /// Returns `true` if the Json value is a `u64`.
1275     pub fn is_u64(&self) -> bool {
1276         matches!(*self, Json::U64(_))
1277     }
1278
1279     /// Returns `true` if the Json value is a `f64`.
1280     pub fn is_f64(&self) -> bool {
1281         matches!(*self, Json::F64(_))
1282     }
1283
1284     /// If the Json value is a number, returns or cast it to a `i64`;
1285     /// returns `None` otherwise.
1286     pub fn as_i64(&self) -> Option<i64> {
1287         match *self {
1288             Json::I64(n) => Some(n),
1289             Json::U64(n) => Some(n as i64),
1290             _ => None,
1291         }
1292     }
1293
1294     /// If the Json value is a number, returns or cast it to a `u64`;
1295     /// returns `None` otherwise.
1296     pub fn as_u64(&self) -> Option<u64> {
1297         match *self {
1298             Json::I64(n) => Some(n as u64),
1299             Json::U64(n) => Some(n),
1300             _ => None,
1301         }
1302     }
1303
1304     /// If the Json value is a number, returns or cast it to a `f64`;
1305     /// returns `None` otherwise.
1306     pub fn as_f64(&self) -> Option<f64> {
1307         match *self {
1308             Json::I64(n) => Some(n as f64),
1309             Json::U64(n) => Some(n as f64),
1310             Json::F64(n) => Some(n),
1311             _ => None,
1312         }
1313     }
1314
1315     /// Returns `true` if the Json value is a `Boolean`.
1316     pub fn is_boolean(&self) -> bool {
1317         self.as_boolean().is_some()
1318     }
1319
1320     /// If the Json value is a `Boolean`, returns the associated `bool`;
1321     /// returns `None` otherwise.
1322     pub fn as_boolean(&self) -> Option<bool> {
1323         match *self {
1324             Json::Boolean(b) => Some(b),
1325             _ => None,
1326         }
1327     }
1328
1329     /// Returns `true` if the Json value is a `Null`.
1330     pub fn is_null(&self) -> bool {
1331         self.as_null().is_some()
1332     }
1333
1334     /// If the Json value is a `Null`, returns `()`;
1335     /// returns `None` otherwise.
1336     pub fn as_null(&self) -> Option<()> {
1337         match *self {
1338             Json::Null => Some(()),
1339             _ => None,
1340         }
1341     }
1342 }
1343
1344 impl<'a> Index<&'a str> for Json {
1345     type Output = Json;
1346
1347     fn index(&self, idx: &'a str) -> &Json {
1348         self.find(idx).unwrap()
1349     }
1350 }
1351
1352 impl Index<usize> for Json {
1353     type Output = Json;
1354
1355     fn index(&self, idx: usize) -> &Json {
1356         match *self {
1357             Json::Array(ref v) => &v[idx],
1358             _ => panic!("can only index Json with usize if it is an array"),
1359         }
1360     }
1361 }
1362
1363 /// The output of the streaming parser.
1364 #[derive(PartialEq, Clone, Debug)]
1365 pub enum JsonEvent {
1366     ObjectStart,
1367     ObjectEnd,
1368     ArrayStart,
1369     ArrayEnd,
1370     BooleanValue(bool),
1371     I64Value(i64),
1372     U64Value(u64),
1373     F64Value(f64),
1374     StringValue(string::String),
1375     NullValue,
1376     Error(ParserError),
1377 }
1378
1379 #[derive(PartialEq, Debug)]
1380 enum ParserState {
1381     // Parse a value in an array, true means first element.
1382     ParseArray(bool),
1383     // Parse ',' or ']' after an element in an array.
1384     ParseArrayComma,
1385     // Parse a key:value in an object, true means first element.
1386     ParseObject(bool),
1387     // Parse ',' or ']' after an element in an object.
1388     ParseObjectComma,
1389     // Initial state.
1390     ParseStart,
1391     // Expecting the stream to end.
1392     ParseBeforeFinish,
1393     // Parsing can't continue.
1394     ParseFinished,
1395 }
1396
1397 /// A Stack represents the current position of the parser in the logical
1398 /// structure of the JSON stream.
1399 ///
1400 /// An example is `foo.bar[3].x`.
1401 #[derive(Default)]
1402 pub struct Stack {
1403     stack: Vec<InternalStackElement>,
1404     str_buffer: Vec<u8>,
1405 }
1406
1407 /// StackElements compose a Stack.
1408 ///
1409 /// As an example, `StackElement::Key("foo")`, `StackElement::Key("bar")`,
1410 /// `StackElement::Index(3)`, and `StackElement::Key("x")` are the
1411 /// StackElements composing the stack that represents `foo.bar[3].x`.
1412 #[derive(PartialEq, Clone, Debug)]
1413 pub enum StackElement<'l> {
1414     Index(u32),
1415     Key(&'l str),
1416 }
1417
1418 // Internally, Key elements are stored as indices in a buffer to avoid
1419 // allocating a string for every member of an object.
1420 #[derive(PartialEq, Clone, Debug)]
1421 enum InternalStackElement {
1422     InternalIndex(u32),
1423     InternalKey(u16, u16), // start, size
1424 }
1425
1426 impl Stack {
1427     pub fn new() -> Stack {
1428         Self::default()
1429     }
1430
1431     /// Returns The number of elements in the Stack.
1432     pub fn len(&self) -> usize {
1433         self.stack.len()
1434     }
1435
1436     /// Returns `true` if the stack is empty.
1437     pub fn is_empty(&self) -> bool {
1438         self.stack.is_empty()
1439     }
1440
1441     /// Provides access to the StackElement at a given index.
1442     /// lower indices are at the bottom of the stack while higher indices are
1443     /// at the top.
1444     pub fn get(&self, idx: usize) -> StackElement<'_> {
1445         match self.stack[idx] {
1446             InternalIndex(i) => StackElement::Index(i),
1447             InternalKey(start, size) => StackElement::Key(
1448                 str::from_utf8(&self.str_buffer[start as usize..start as usize + size as usize])
1449                     .unwrap(),
1450             ),
1451         }
1452     }
1453
1454     /// Compares this stack with an array of StackElement<'_>s.
1455     pub fn is_equal_to(&self, rhs: &[StackElement<'_>]) -> bool {
1456         if self.stack.len() != rhs.len() {
1457             return false;
1458         }
1459         for (i, r) in rhs.iter().enumerate() {
1460             if self.get(i) != *r {
1461                 return false;
1462             }
1463         }
1464         true
1465     }
1466
1467     /// Returns `true` if the bottom-most elements of this stack are the same as
1468     /// the ones passed as parameter.
1469     pub fn starts_with(&self, rhs: &[StackElement<'_>]) -> bool {
1470         if self.stack.len() < rhs.len() {
1471             return false;
1472         }
1473         for (i, r) in rhs.iter().enumerate() {
1474             if self.get(i) != *r {
1475                 return false;
1476             }
1477         }
1478         true
1479     }
1480
1481     /// Returns `true` if the top-most elements of this stack are the same as
1482     /// the ones passed as parameter.
1483     pub fn ends_with(&self, rhs: &[StackElement<'_>]) -> bool {
1484         if self.stack.len() < rhs.len() {
1485             return false;
1486         }
1487         let offset = self.stack.len() - rhs.len();
1488         for (i, r) in rhs.iter().enumerate() {
1489             if self.get(i + offset) != *r {
1490                 return false;
1491             }
1492         }
1493         true
1494     }
1495
1496     /// Returns the top-most element (if any).
1497     pub fn top(&self) -> Option<StackElement<'_>> {
1498         match self.stack.last() {
1499             None => None,
1500             Some(&InternalIndex(i)) => Some(StackElement::Index(i)),
1501             Some(&InternalKey(start, size)) => Some(StackElement::Key(
1502                 str::from_utf8(&self.str_buffer[start as usize..(start + size) as usize]).unwrap(),
1503             )),
1504         }
1505     }
1506
1507     // Used by Parser to insert StackElement::Key elements at the top of the stack.
1508     fn push_key(&mut self, key: string::String) {
1509         self.stack.push(InternalKey(self.str_buffer.len() as u16, key.len() as u16));
1510         self.str_buffer.extend(key.as_bytes());
1511     }
1512
1513     // Used by Parser to insert StackElement::Index elements at the top of the stack.
1514     fn push_index(&mut self, index: u32) {
1515         self.stack.push(InternalIndex(index));
1516     }
1517
1518     // Used by Parser to remove the top-most element of the stack.
1519     fn pop(&mut self) {
1520         assert!(!self.is_empty());
1521         match *self.stack.last().unwrap() {
1522             InternalKey(_, sz) => {
1523                 let new_size = self.str_buffer.len() - sz as usize;
1524                 self.str_buffer.truncate(new_size);
1525             }
1526             InternalIndex(_) => {}
1527         }
1528         self.stack.pop();
1529     }
1530
1531     // Used by Parser to test whether the top-most element is an index.
1532     fn last_is_index(&self) -> bool {
1533         matches!(self.stack.last(), Some(InternalIndex(_)))
1534     }
1535
1536     // Used by Parser to increment the index of the top-most element.
1537     fn bump_index(&mut self) {
1538         let len = self.stack.len();
1539         let idx = match *self.stack.last().unwrap() {
1540             InternalIndex(i) => i + 1,
1541             _ => {
1542                 panic!();
1543             }
1544         };
1545         self.stack[len - 1] = InternalIndex(idx);
1546     }
1547 }
1548
1549 /// A streaming JSON parser implemented as an iterator of JsonEvent, consuming
1550 /// an iterator of char.
1551 pub struct Parser<T> {
1552     rdr: T,
1553     ch: Option<char>,
1554     line: usize,
1555     col: usize,
1556     // We maintain a stack representing where we are in the logical structure
1557     // of the JSON stream.
1558     stack: Stack,
1559     // A state machine is kept to make it possible to interrupt and resume parsing.
1560     state: ParserState,
1561 }
1562
1563 impl<T: Iterator<Item = char>> Iterator for Parser<T> {
1564     type Item = JsonEvent;
1565
1566     fn next(&mut self) -> Option<JsonEvent> {
1567         if self.state == ParseFinished {
1568             return None;
1569         }
1570
1571         if self.state == ParseBeforeFinish {
1572             self.parse_whitespace();
1573             // Make sure there is no trailing characters.
1574             if self.eof() {
1575                 self.state = ParseFinished;
1576                 return None;
1577             } else {
1578                 return Some(self.error_event(TrailingCharacters));
1579             }
1580         }
1581
1582         Some(self.parse())
1583     }
1584 }
1585
1586 impl<T: Iterator<Item = char>> Parser<T> {
1587     /// Creates the JSON parser.
1588     pub fn new(rdr: T) -> Parser<T> {
1589         let mut p = Parser {
1590             rdr,
1591             ch: Some('\x00'),
1592             line: 1,
1593             col: 0,
1594             stack: Stack::new(),
1595             state: ParseStart,
1596         };
1597         p.bump();
1598         p
1599     }
1600
1601     /// Provides access to the current position in the logical structure of the
1602     /// JSON stream.
1603     pub fn stack(&self) -> &Stack {
1604         &self.stack
1605     }
1606
1607     fn eof(&self) -> bool {
1608         self.ch.is_none()
1609     }
1610     fn ch_or_null(&self) -> char {
1611         self.ch.unwrap_or('\x00')
1612     }
1613     fn bump(&mut self) {
1614         self.ch = self.rdr.next();
1615
1616         if self.ch_is('\n') {
1617             self.line += 1;
1618             self.col = 1;
1619         } else {
1620             self.col += 1;
1621         }
1622     }
1623
1624     fn next_char(&mut self) -> Option<char> {
1625         self.bump();
1626         self.ch
1627     }
1628     fn ch_is(&self, c: char) -> bool {
1629         self.ch == Some(c)
1630     }
1631
1632     fn error<U>(&self, reason: ErrorCode) -> Result<U, ParserError> {
1633         Err(SyntaxError(reason, self.line, self.col))
1634     }
1635
1636     fn parse_whitespace(&mut self) {
1637         while self.ch_is(' ') || self.ch_is('\n') || self.ch_is('\t') || self.ch_is('\r') {
1638             self.bump();
1639         }
1640     }
1641
1642     fn parse_number(&mut self) -> JsonEvent {
1643         let neg = if self.ch_is('-') {
1644             self.bump();
1645             true
1646         } else {
1647             false
1648         };
1649
1650         let res = match self.parse_u64() {
1651             Ok(res) => res,
1652             Err(e) => {
1653                 return Error(e);
1654             }
1655         };
1656
1657         if self.ch_is('.') || self.ch_is('e') || self.ch_is('E') {
1658             let mut res = res as f64;
1659
1660             if self.ch_is('.') {
1661                 res = match self.parse_decimal(res) {
1662                     Ok(res) => res,
1663                     Err(e) => {
1664                         return Error(e);
1665                     }
1666                 };
1667             }
1668
1669             if self.ch_is('e') || self.ch_is('E') {
1670                 res = match self.parse_exponent(res) {
1671                     Ok(res) => res,
1672                     Err(e) => {
1673                         return Error(e);
1674                     }
1675                 };
1676             }
1677
1678             if neg {
1679                 res *= -1.0;
1680             }
1681
1682             F64Value(res)
1683         } else if neg {
1684             let res = (res as i64).wrapping_neg();
1685
1686             // Make sure we didn't underflow.
1687             if res > 0 {
1688                 Error(SyntaxError(InvalidNumber, self.line, self.col))
1689             } else {
1690                 I64Value(res)
1691             }
1692         } else {
1693             U64Value(res)
1694         }
1695     }
1696
1697     fn parse_u64(&mut self) -> Result<u64, ParserError> {
1698         let mut accum = 0u64;
1699         let last_accum = 0; // necessary to detect overflow.
1700
1701         match self.ch_or_null() {
1702             '0' => {
1703                 self.bump();
1704
1705                 // A leading '0' must be the only digit before the decimal point.
1706                 if let '0'..='9' = self.ch_or_null() {
1707                     return self.error(InvalidNumber);
1708                 }
1709             }
1710             '1'..='9' => {
1711                 while !self.eof() {
1712                     match self.ch_or_null() {
1713                         c @ '0'..='9' => {
1714                             accum = accum.wrapping_mul(10);
1715                             accum = accum.wrapping_add((c as u64) - ('0' as u64));
1716
1717                             // Detect overflow by comparing to the last value.
1718                             if accum <= last_accum {
1719                                 return self.error(InvalidNumber);
1720                             }
1721
1722                             self.bump();
1723                         }
1724                         _ => break,
1725                     }
1726                 }
1727             }
1728             _ => return self.error(InvalidNumber),
1729         }
1730
1731         Ok(accum)
1732     }
1733
1734     fn parse_decimal(&mut self, mut res: f64) -> Result<f64, ParserError> {
1735         self.bump();
1736
1737         // Make sure a digit follows the decimal place.
1738         match self.ch_or_null() {
1739             '0'..='9' => (),
1740             _ => return self.error(InvalidNumber),
1741         }
1742
1743         let mut dec = 1.0;
1744         while !self.eof() {
1745             match self.ch_or_null() {
1746                 c @ '0'..='9' => {
1747                     dec /= 10.0;
1748                     res += (((c as isize) - ('0' as isize)) as f64) * dec;
1749                     self.bump();
1750                 }
1751                 _ => break,
1752             }
1753         }
1754
1755         Ok(res)
1756     }
1757
1758     fn parse_exponent(&mut self, mut res: f64) -> Result<f64, ParserError> {
1759         self.bump();
1760
1761         let mut exp = 0;
1762         let mut neg_exp = false;
1763
1764         if self.ch_is('+') {
1765             self.bump();
1766         } else if self.ch_is('-') {
1767             self.bump();
1768             neg_exp = true;
1769         }
1770
1771         // Make sure a digit follows the exponent place.
1772         match self.ch_or_null() {
1773             '0'..='9' => (),
1774             _ => return self.error(InvalidNumber),
1775         }
1776         while !self.eof() {
1777             match self.ch_or_null() {
1778                 c @ '0'..='9' => {
1779                     exp *= 10;
1780                     exp += (c as usize) - ('0' as usize);
1781
1782                     self.bump();
1783                 }
1784                 _ => break,
1785             }
1786         }
1787
1788         let exp = 10_f64.powi(exp as i32);
1789         if neg_exp {
1790             res /= exp;
1791         } else {
1792             res *= exp;
1793         }
1794
1795         Ok(res)
1796     }
1797
1798     fn decode_hex_escape(&mut self) -> Result<u16, ParserError> {
1799         let mut i = 0;
1800         let mut n = 0;
1801         while i < 4 && !self.eof() {
1802             self.bump();
1803             n = match self.ch_or_null() {
1804                 c @ '0'..='9' => n * 16 + ((c as u16) - ('0' as u16)),
1805                 'a' | 'A' => n * 16 + 10,
1806                 'b' | 'B' => n * 16 + 11,
1807                 'c' | 'C' => n * 16 + 12,
1808                 'd' | 'D' => n * 16 + 13,
1809                 'e' | 'E' => n * 16 + 14,
1810                 'f' | 'F' => n * 16 + 15,
1811                 _ => return self.error(InvalidEscape),
1812             };
1813
1814             i += 1;
1815         }
1816
1817         // Error out if we didn't parse 4 digits.
1818         if i != 4 {
1819             return self.error(InvalidEscape);
1820         }
1821
1822         Ok(n)
1823     }
1824
1825     fn parse_str(&mut self) -> Result<string::String, ParserError> {
1826         let mut escape = false;
1827         let mut res = string::String::new();
1828
1829         loop {
1830             self.bump();
1831             if self.eof() {
1832                 return self.error(EOFWhileParsingString);
1833             }
1834
1835             if escape {
1836                 match self.ch_or_null() {
1837                     '"' => res.push('"'),
1838                     '\\' => res.push('\\'),
1839                     '/' => res.push('/'),
1840                     'b' => res.push('\x08'),
1841                     'f' => res.push('\x0c'),
1842                     'n' => res.push('\n'),
1843                     'r' => res.push('\r'),
1844                     't' => res.push('\t'),
1845                     'u' => match self.decode_hex_escape()? {
1846                         0xDC00..=0xDFFF => return self.error(LoneLeadingSurrogateInHexEscape),
1847
1848                         // Non-BMP characters are encoded as a sequence of
1849                         // two hex escapes, representing UTF-16 surrogates.
1850                         n1 @ 0xD800..=0xDBFF => {
1851                             match (self.next_char(), self.next_char()) {
1852                                 (Some('\\'), Some('u')) => (),
1853                                 _ => return self.error(UnexpectedEndOfHexEscape),
1854                             }
1855
1856                             let n2 = self.decode_hex_escape()?;
1857                             if n2 < 0xDC00 || n2 > 0xDFFF {
1858                                 return self.error(LoneLeadingSurrogateInHexEscape);
1859                             }
1860                             let c =
1861                                 (u32::from(n1 - 0xD800) << 10 | u32::from(n2 - 0xDC00)) + 0x1_0000;
1862                             res.push(char::from_u32(c).unwrap());
1863                         }
1864
1865                         n => match char::from_u32(u32::from(n)) {
1866                             Some(c) => res.push(c),
1867                             None => return self.error(InvalidUnicodeCodePoint),
1868                         },
1869                     },
1870                     _ => return self.error(InvalidEscape),
1871                 }
1872                 escape = false;
1873             } else if self.ch_is('\\') {
1874                 escape = true;
1875             } else {
1876                 match self.ch {
1877                     Some('"') => {
1878                         self.bump();
1879                         return Ok(res);
1880                     }
1881                     Some(c) => res.push(c),
1882                     None => unreachable!(),
1883                 }
1884             }
1885         }
1886     }
1887
1888     // Invoked at each iteration, consumes the stream until it has enough
1889     // information to return a JsonEvent.
1890     // Manages an internal state so that parsing can be interrupted and resumed.
1891     // Also keeps track of the position in the logical structure of the json
1892     // stream isize the form of a stack that can be queried by the user using the
1893     // stack() method.
1894     fn parse(&mut self) -> JsonEvent {
1895         loop {
1896             // The only paths where the loop can spin a new iteration
1897             // are in the cases ParseArrayComma and ParseObjectComma if ','
1898             // is parsed. In these cases the state is set to (respectively)
1899             // ParseArray(false) and ParseObject(false), which always return,
1900             // so there is no risk of getting stuck in an infinite loop.
1901             // All other paths return before the end of the loop's iteration.
1902             self.parse_whitespace();
1903
1904             match self.state {
1905                 ParseStart => {
1906                     return self.parse_start();
1907                 }
1908                 ParseArray(first) => {
1909                     return self.parse_array(first);
1910                 }
1911                 ParseArrayComma => {
1912                     if let Some(evt) = self.parse_array_comma_or_end() {
1913                         return evt;
1914                     }
1915                 }
1916                 ParseObject(first) => {
1917                     return self.parse_object(first);
1918                 }
1919                 ParseObjectComma => {
1920                     self.stack.pop();
1921                     if self.ch_is(',') {
1922                         self.state = ParseObject(false);
1923                         self.bump();
1924                     } else {
1925                         return self.parse_object_end();
1926                     }
1927                 }
1928                 _ => {
1929                     return self.error_event(InvalidSyntax);
1930                 }
1931             }
1932         }
1933     }
1934
1935     fn parse_start(&mut self) -> JsonEvent {
1936         let val = self.parse_value();
1937         self.state = match val {
1938             Error(_) => ParseFinished,
1939             ArrayStart => ParseArray(true),
1940             ObjectStart => ParseObject(true),
1941             _ => ParseBeforeFinish,
1942         };
1943         val
1944     }
1945
1946     fn parse_array(&mut self, first: bool) -> JsonEvent {
1947         if self.ch_is(']') {
1948             if !first {
1949                 self.error_event(InvalidSyntax)
1950             } else {
1951                 self.state = if self.stack.is_empty() {
1952                     ParseBeforeFinish
1953                 } else if self.stack.last_is_index() {
1954                     ParseArrayComma
1955                 } else {
1956                     ParseObjectComma
1957                 };
1958                 self.bump();
1959                 ArrayEnd
1960             }
1961         } else {
1962             if first {
1963                 self.stack.push_index(0);
1964             }
1965             let val = self.parse_value();
1966             self.state = match val {
1967                 Error(_) => ParseFinished,
1968                 ArrayStart => ParseArray(true),
1969                 ObjectStart => ParseObject(true),
1970                 _ => ParseArrayComma,
1971             };
1972             val
1973         }
1974     }
1975
1976     fn parse_array_comma_or_end(&mut self) -> Option<JsonEvent> {
1977         if self.ch_is(',') {
1978             self.stack.bump_index();
1979             self.state = ParseArray(false);
1980             self.bump();
1981             None
1982         } else if self.ch_is(']') {
1983             self.stack.pop();
1984             self.state = if self.stack.is_empty() {
1985                 ParseBeforeFinish
1986             } else if self.stack.last_is_index() {
1987                 ParseArrayComma
1988             } else {
1989                 ParseObjectComma
1990             };
1991             self.bump();
1992             Some(ArrayEnd)
1993         } else if self.eof() {
1994             Some(self.error_event(EOFWhileParsingArray))
1995         } else {
1996             Some(self.error_event(InvalidSyntax))
1997         }
1998     }
1999
2000     fn parse_object(&mut self, first: bool) -> JsonEvent {
2001         if self.ch_is('}') {
2002             if !first {
2003                 if self.stack.is_empty() {
2004                     return self.error_event(TrailingComma);
2005                 } else {
2006                     self.stack.pop();
2007                 }
2008             }
2009             self.state = if self.stack.is_empty() {
2010                 ParseBeforeFinish
2011             } else if self.stack.last_is_index() {
2012                 ParseArrayComma
2013             } else {
2014                 ParseObjectComma
2015             };
2016             self.bump();
2017             return ObjectEnd;
2018         }
2019         if self.eof() {
2020             return self.error_event(EOFWhileParsingObject);
2021         }
2022         if !self.ch_is('"') {
2023             return self.error_event(KeyMustBeAString);
2024         }
2025         let s = match self.parse_str() {
2026             Ok(s) => s,
2027             Err(e) => {
2028                 self.state = ParseFinished;
2029                 return Error(e);
2030             }
2031         };
2032         self.parse_whitespace();
2033         if self.eof() {
2034             return self.error_event(EOFWhileParsingObject);
2035         } else if self.ch_or_null() != ':' {
2036             return self.error_event(ExpectedColon);
2037         }
2038         self.stack.push_key(s);
2039         self.bump();
2040         self.parse_whitespace();
2041
2042         let val = self.parse_value();
2043
2044         self.state = match val {
2045             Error(_) => ParseFinished,
2046             ArrayStart => ParseArray(true),
2047             ObjectStart => ParseObject(true),
2048             _ => ParseObjectComma,
2049         };
2050         val
2051     }
2052
2053     fn parse_object_end(&mut self) -> JsonEvent {
2054         if self.ch_is('}') {
2055             self.state = if self.stack.is_empty() {
2056                 ParseBeforeFinish
2057             } else if self.stack.last_is_index() {
2058                 ParseArrayComma
2059             } else {
2060                 ParseObjectComma
2061             };
2062             self.bump();
2063             ObjectEnd
2064         } else if self.eof() {
2065             self.error_event(EOFWhileParsingObject)
2066         } else {
2067             self.error_event(InvalidSyntax)
2068         }
2069     }
2070
2071     fn parse_value(&mut self) -> JsonEvent {
2072         if self.eof() {
2073             return self.error_event(EOFWhileParsingValue);
2074         }
2075         match self.ch_or_null() {
2076             'n' => self.parse_ident("ull", NullValue),
2077             't' => self.parse_ident("rue", BooleanValue(true)),
2078             'f' => self.parse_ident("alse", BooleanValue(false)),
2079             '0'..='9' | '-' => self.parse_number(),
2080             '"' => match self.parse_str() {
2081                 Ok(s) => StringValue(s),
2082                 Err(e) => Error(e),
2083             },
2084             '[' => {
2085                 self.bump();
2086                 ArrayStart
2087             }
2088             '{' => {
2089                 self.bump();
2090                 ObjectStart
2091             }
2092             _ => self.error_event(InvalidSyntax),
2093         }
2094     }
2095
2096     fn parse_ident(&mut self, ident: &str, value: JsonEvent) -> JsonEvent {
2097         if ident.chars().all(|c| Some(c) == self.next_char()) {
2098             self.bump();
2099             value
2100         } else {
2101             Error(SyntaxError(InvalidSyntax, self.line, self.col))
2102         }
2103     }
2104
2105     fn error_event(&mut self, reason: ErrorCode) -> JsonEvent {
2106         self.state = ParseFinished;
2107         Error(SyntaxError(reason, self.line, self.col))
2108     }
2109 }
2110
2111 /// A Builder consumes a json::Parser to create a generic Json structure.
2112 pub struct Builder<T> {
2113     parser: Parser<T>,
2114     token: Option<JsonEvent>,
2115 }
2116
2117 impl<T: Iterator<Item = char>> Builder<T> {
2118     /// Creates a JSON Builder.
2119     pub fn new(src: T) -> Builder<T> {
2120         Builder { parser: Parser::new(src), token: None }
2121     }
2122
2123     // Decode a Json value from a Parser.
2124     pub fn build(&mut self) -> Result<Json, BuilderError> {
2125         self.bump();
2126         let result = self.build_value();
2127         self.bump();
2128         match self.token {
2129             None => {}
2130             Some(Error(ref e)) => {
2131                 return Err(e.clone());
2132             }
2133             ref tok => {
2134                 panic!("unexpected token {:?}", tok.clone());
2135             }
2136         }
2137         result
2138     }
2139
2140     fn bump(&mut self) {
2141         self.token = self.parser.next();
2142     }
2143
2144     fn build_value(&mut self) -> Result<Json, BuilderError> {
2145         match self.token {
2146             Some(NullValue) => Ok(Json::Null),
2147             Some(I64Value(n)) => Ok(Json::I64(n)),
2148             Some(U64Value(n)) => Ok(Json::U64(n)),
2149             Some(F64Value(n)) => Ok(Json::F64(n)),
2150             Some(BooleanValue(b)) => Ok(Json::Boolean(b)),
2151             Some(StringValue(ref mut s)) => {
2152                 let mut temp = string::String::new();
2153                 swap(s, &mut temp);
2154                 Ok(Json::String(temp))
2155             }
2156             Some(Error(ref e)) => Err(e.clone()),
2157             Some(ArrayStart) => self.build_array(),
2158             Some(ObjectStart) => self.build_object(),
2159             Some(ObjectEnd) => self.parser.error(InvalidSyntax),
2160             Some(ArrayEnd) => self.parser.error(InvalidSyntax),
2161             None => self.parser.error(EOFWhileParsingValue),
2162         }
2163     }
2164
2165     fn build_array(&mut self) -> Result<Json, BuilderError> {
2166         self.bump();
2167         let mut values = Vec::new();
2168
2169         loop {
2170             if self.token == Some(ArrayEnd) {
2171                 return Ok(Json::Array(values.into_iter().collect()));
2172             }
2173             match self.build_value() {
2174                 Ok(v) => values.push(v),
2175                 Err(e) => return Err(e),
2176             }
2177             self.bump();
2178         }
2179     }
2180
2181     fn build_object(&mut self) -> Result<Json, BuilderError> {
2182         self.bump();
2183
2184         let mut values = BTreeMap::new();
2185
2186         loop {
2187             match self.token {
2188                 Some(ObjectEnd) => {
2189                     return Ok(Json::Object(values));
2190                 }
2191                 Some(Error(ref e)) => {
2192                     return Err(e.clone());
2193                 }
2194                 None => {
2195                     break;
2196                 }
2197                 _ => {}
2198             }
2199             let key = match self.parser.stack().top() {
2200                 Some(StackElement::Key(k)) => k.to_owned(),
2201                 _ => {
2202                     panic!("invalid state");
2203                 }
2204             };
2205             match self.build_value() {
2206                 Ok(value) => {
2207                     values.insert(key, value);
2208                 }
2209                 Err(e) => {
2210                     return Err(e);
2211                 }
2212             }
2213             self.bump();
2214         }
2215         self.parser.error(EOFWhileParsingObject)
2216     }
2217 }
2218
2219 /// Decodes a json value from an `&mut io::Read`
2220 pub fn from_reader(rdr: &mut dyn Read) -> Result<Json, BuilderError> {
2221     let mut contents = Vec::new();
2222     match rdr.read_to_end(&mut contents) {
2223         Ok(c) => c,
2224         Err(e) => return Err(io_error_to_error(e)),
2225     };
2226     let s = match str::from_utf8(&contents).ok() {
2227         Some(s) => s,
2228         _ => return Err(SyntaxError(NotUtf8, 0, 0)),
2229     };
2230     let mut builder = Builder::new(s.chars());
2231     builder.build()
2232 }
2233
2234 /// Decodes a json value from a string
2235 pub fn from_str(s: &str) -> Result<Json, BuilderError> {
2236     let mut builder = Builder::new(s.chars());
2237     builder.build()
2238 }
2239
2240 /// A structure to decode JSON to values in rust.
2241 pub struct Decoder {
2242     stack: Vec<Json>,
2243 }
2244
2245 impl Decoder {
2246     /// Creates a new decoder instance for decoding the specified JSON value.
2247     pub fn new(json: Json) -> Decoder {
2248         Decoder { stack: vec![json] }
2249     }
2250
2251     fn pop(&mut self) -> Json {
2252         self.stack.pop().unwrap()
2253     }
2254 }
2255
2256 macro_rules! expect {
2257     ($e:expr, Null) => {{
2258         match $e {
2259             Json::Null => Ok(()),
2260             other => Err(ExpectedError("Null".to_owned(), other.to_string())),
2261         }
2262     }};
2263     ($e:expr, $t:ident) => {{
2264         match $e {
2265             Json::$t(v) => Ok(v),
2266             other => Err(ExpectedError(stringify!($t).to_owned(), other.to_string())),
2267         }
2268     }};
2269 }
2270
2271 macro_rules! read_primitive {
2272     ($name:ident, $ty:ty) => {
2273         fn $name(&mut self) -> DecodeResult<$ty> {
2274             match self.pop() {
2275                 Json::I64(f) => Ok(f as $ty),
2276                 Json::U64(f) => Ok(f as $ty),
2277                 Json::F64(f) => Err(ExpectedError("Integer".to_owned(), f.to_string())),
2278                 // re: #12967.. a type w/ numeric keys (ie HashMap<usize, V> etc)
2279                 // is going to have a string here, as per JSON spec.
2280                 Json::String(s) => match s.parse().ok() {
2281                     Some(f) => Ok(f),
2282                     None => Err(ExpectedError("Number".to_owned(), s)),
2283                 },
2284                 value => Err(ExpectedError("Number".to_owned(), value.to_string())),
2285             }
2286         }
2287     };
2288 }
2289
2290 impl crate::Decoder for Decoder {
2291     type Error = DecoderError;
2292
2293     fn read_nil(&mut self) -> DecodeResult<()> {
2294         expect!(self.pop(), Null)
2295     }
2296
2297     read_primitive! { read_usize, usize }
2298     read_primitive! { read_u8, u8 }
2299     read_primitive! { read_u16, u16 }
2300     read_primitive! { read_u32, u32 }
2301     read_primitive! { read_u64, u64 }
2302     read_primitive! { read_u128, u128 }
2303     read_primitive! { read_isize, isize }
2304     read_primitive! { read_i8, i8 }
2305     read_primitive! { read_i16, i16 }
2306     read_primitive! { read_i32, i32 }
2307     read_primitive! { read_i64, i64 }
2308     read_primitive! { read_i128, i128 }
2309
2310     fn read_f32(&mut self) -> DecodeResult<f32> {
2311         self.read_f64().map(|x| x as f32)
2312     }
2313
2314     fn read_f64(&mut self) -> DecodeResult<f64> {
2315         match self.pop() {
2316             Json::I64(f) => Ok(f as f64),
2317             Json::U64(f) => Ok(f as f64),
2318             Json::F64(f) => Ok(f),
2319             Json::String(s) => {
2320                 // re: #12967.. a type w/ numeric keys (ie HashMap<usize, V> etc)
2321                 // is going to have a string here, as per JSON spec.
2322                 match s.parse().ok() {
2323                     Some(f) => Ok(f),
2324                     None => Err(ExpectedError("Number".to_owned(), s)),
2325                 }
2326             }
2327             Json::Null => Ok(f64::NAN),
2328             value => Err(ExpectedError("Number".to_owned(), value.to_string())),
2329         }
2330     }
2331
2332     fn read_bool(&mut self) -> DecodeResult<bool> {
2333         expect!(self.pop(), Boolean)
2334     }
2335
2336     fn read_char(&mut self) -> DecodeResult<char> {
2337         let s = self.read_str()?;
2338         {
2339             let mut it = s.chars();
2340             if let (Some(c), None) = (it.next(), it.next()) {
2341                 // exactly one character
2342                 return Ok(c);
2343             }
2344         }
2345         Err(ExpectedError("single character string".to_owned(), s.to_string()))
2346     }
2347
2348     fn read_str(&mut self) -> DecodeResult<Cow<'_, str>> {
2349         expect!(self.pop(), String).map(Cow::Owned)
2350     }
2351
2352     fn read_enum<T, F>(&mut self, _name: &str, f: F) -> DecodeResult<T>
2353     where
2354         F: FnOnce(&mut Decoder) -> DecodeResult<T>,
2355     {
2356         f(self)
2357     }
2358
2359     fn read_enum_variant<T, F>(&mut self, names: &[&str], mut f: F) -> DecodeResult<T>
2360     where
2361         F: FnMut(&mut Decoder, usize) -> DecodeResult<T>,
2362     {
2363         let name = match self.pop() {
2364             Json::String(s) => s,
2365             Json::Object(mut o) => {
2366                 let n = match o.remove(&"variant".to_owned()) {
2367                     Some(Json::String(s)) => s,
2368                     Some(val) => return Err(ExpectedError("String".to_owned(), val.to_string())),
2369                     None => return Err(MissingFieldError("variant".to_owned())),
2370                 };
2371                 match o.remove(&"fields".to_string()) {
2372                     Some(Json::Array(l)) => {
2373                         self.stack.extend(l.into_iter().rev());
2374                     }
2375                     Some(val) => return Err(ExpectedError("Array".to_owned(), val.to_string())),
2376                     None => return Err(MissingFieldError("fields".to_owned())),
2377                 }
2378                 n
2379             }
2380             json => return Err(ExpectedError("String or Object".to_owned(), json.to_string())),
2381         };
2382         let idx = match names.iter().position(|n| *n == &name[..]) {
2383             Some(idx) => idx,
2384             None => return Err(UnknownVariantError(name)),
2385         };
2386         f(self, idx)
2387     }
2388
2389     fn read_enum_variant_arg<T, F>(&mut self, _idx: usize, f: F) -> DecodeResult<T>
2390     where
2391         F: FnOnce(&mut Decoder) -> DecodeResult<T>,
2392     {
2393         f(self)
2394     }
2395
2396     fn read_enum_struct_variant<T, F>(&mut self, names: &[&str], f: F) -> DecodeResult<T>
2397     where
2398         F: FnMut(&mut Decoder, usize) -> DecodeResult<T>,
2399     {
2400         self.read_enum_variant(names, f)
2401     }
2402
2403     fn read_enum_struct_variant_field<T, F>(
2404         &mut self,
2405         _name: &str,
2406         idx: usize,
2407         f: F,
2408     ) -> DecodeResult<T>
2409     where
2410         F: FnOnce(&mut Decoder) -> DecodeResult<T>,
2411     {
2412         self.read_enum_variant_arg(idx, f)
2413     }
2414
2415     fn read_struct<T, F>(&mut self, _name: &str, _len: usize, f: F) -> DecodeResult<T>
2416     where
2417         F: FnOnce(&mut Decoder) -> DecodeResult<T>,
2418     {
2419         let value = f(self)?;
2420         self.pop();
2421         Ok(value)
2422     }
2423
2424     fn read_struct_field<T, F>(&mut self, name: &str, _idx: usize, f: F) -> DecodeResult<T>
2425     where
2426         F: FnOnce(&mut Decoder) -> DecodeResult<T>,
2427     {
2428         let mut obj = expect!(self.pop(), Object)?;
2429
2430         let value = match obj.remove(&name.to_string()) {
2431             None => {
2432                 // Add a Null and try to parse it as an Option<_>
2433                 // to get None as a default value.
2434                 self.stack.push(Json::Null);
2435                 match f(self) {
2436                     Ok(x) => x,
2437                     Err(_) => return Err(MissingFieldError(name.to_string())),
2438                 }
2439             }
2440             Some(json) => {
2441                 self.stack.push(json);
2442                 f(self)?
2443             }
2444         };
2445         self.stack.push(Json::Object(obj));
2446         Ok(value)
2447     }
2448
2449     fn read_tuple<T, F>(&mut self, tuple_len: usize, f: F) -> DecodeResult<T>
2450     where
2451         F: FnOnce(&mut Decoder) -> DecodeResult<T>,
2452     {
2453         self.read_seq(move |d, len| {
2454             if len == tuple_len {
2455                 f(d)
2456             } else {
2457                 Err(ExpectedError(format!("Tuple{}", tuple_len), format!("Tuple{}", len)))
2458             }
2459         })
2460     }
2461
2462     fn read_tuple_arg<T, F>(&mut self, idx: usize, f: F) -> DecodeResult<T>
2463     where
2464         F: FnOnce(&mut Decoder) -> DecodeResult<T>,
2465     {
2466         self.read_seq_elt(idx, f)
2467     }
2468
2469     fn read_tuple_struct<T, F>(&mut self, _name: &str, len: usize, f: F) -> DecodeResult<T>
2470     where
2471         F: FnOnce(&mut Decoder) -> DecodeResult<T>,
2472     {
2473         self.read_tuple(len, f)
2474     }
2475
2476     fn read_tuple_struct_arg<T, F>(&mut self, idx: usize, f: F) -> DecodeResult<T>
2477     where
2478         F: FnOnce(&mut Decoder) -> DecodeResult<T>,
2479     {
2480         self.read_tuple_arg(idx, f)
2481     }
2482
2483     fn read_option<T, F>(&mut self, mut f: F) -> DecodeResult<T>
2484     where
2485         F: FnMut(&mut Decoder, bool) -> DecodeResult<T>,
2486     {
2487         match self.pop() {
2488             Json::Null => f(self, false),
2489             value => {
2490                 self.stack.push(value);
2491                 f(self, true)
2492             }
2493         }
2494     }
2495
2496     fn read_seq<T, F>(&mut self, f: F) -> DecodeResult<T>
2497     where
2498         F: FnOnce(&mut Decoder, usize) -> DecodeResult<T>,
2499     {
2500         let array = expect!(self.pop(), Array)?;
2501         let len = array.len();
2502         self.stack.extend(array.into_iter().rev());
2503         f(self, len)
2504     }
2505
2506     fn read_seq_elt<T, F>(&mut self, _idx: usize, f: F) -> DecodeResult<T>
2507     where
2508         F: FnOnce(&mut Decoder) -> DecodeResult<T>,
2509     {
2510         f(self)
2511     }
2512
2513     fn read_map<T, F>(&mut self, f: F) -> DecodeResult<T>
2514     where
2515         F: FnOnce(&mut Decoder, usize) -> DecodeResult<T>,
2516     {
2517         let obj = expect!(self.pop(), Object)?;
2518         let len = obj.len();
2519         for (key, value) in obj {
2520             self.stack.push(value);
2521             self.stack.push(Json::String(key));
2522         }
2523         f(self, len)
2524     }
2525
2526     fn read_map_elt_key<T, F>(&mut self, _idx: usize, f: F) -> DecodeResult<T>
2527     where
2528         F: FnOnce(&mut Decoder) -> DecodeResult<T>,
2529     {
2530         f(self)
2531     }
2532
2533     fn read_map_elt_val<T, F>(&mut self, _idx: usize, f: F) -> DecodeResult<T>
2534     where
2535         F: FnOnce(&mut Decoder) -> DecodeResult<T>,
2536     {
2537         f(self)
2538     }
2539
2540     fn error(&mut self, err: &str) -> DecoderError {
2541         ApplicationError(err.to_string())
2542     }
2543 }
2544
2545 /// A trait for converting values to JSON
2546 pub trait ToJson {
2547     /// Converts the value of `self` to an instance of JSON
2548     fn to_json(&self) -> Json;
2549 }
2550
2551 macro_rules! to_json_impl_i64 {
2552     ($($t:ty), +) => (
2553         $(impl ToJson for $t {
2554             fn to_json(&self) -> Json {
2555                 Json::I64(*self as i64)
2556             }
2557         })+
2558     )
2559 }
2560
2561 to_json_impl_i64! { isize, i8, i16, i32, i64 }
2562
2563 macro_rules! to_json_impl_u64 {
2564     ($($t:ty), +) => (
2565         $(impl ToJson for $t {
2566             fn to_json(&self) -> Json {
2567                 Json::U64(*self as u64)
2568             }
2569         })+
2570     )
2571 }
2572
2573 to_json_impl_u64! { usize, u8, u16, u32, u64 }
2574
2575 impl ToJson for Json {
2576     fn to_json(&self) -> Json {
2577         self.clone()
2578     }
2579 }
2580
2581 impl ToJson for f32 {
2582     fn to_json(&self) -> Json {
2583         f64::from(*self).to_json()
2584     }
2585 }
2586
2587 impl ToJson for f64 {
2588     fn to_json(&self) -> Json {
2589         match self.classify() {
2590             Fp::Nan | Fp::Infinite => Json::Null,
2591             _ => Json::F64(*self),
2592         }
2593     }
2594 }
2595
2596 impl ToJson for () {
2597     fn to_json(&self) -> Json {
2598         Json::Null
2599     }
2600 }
2601
2602 impl ToJson for bool {
2603     fn to_json(&self) -> Json {
2604         Json::Boolean(*self)
2605     }
2606 }
2607
2608 impl ToJson for str {
2609     fn to_json(&self) -> Json {
2610         Json::String(self.to_string())
2611     }
2612 }
2613
2614 impl ToJson for string::String {
2615     fn to_json(&self) -> Json {
2616         Json::String((*self).clone())
2617     }
2618 }
2619
2620 macro_rules! tuple_impl {
2621     // use variables to indicate the arity of the tuple
2622     ($($tyvar:ident),* ) => {
2623         // the trailing commas are for the 1 tuple
2624         impl<
2625             $( $tyvar : ToJson ),*
2626             > ToJson for ( $( $tyvar ),* , ) {
2627
2628             #[inline]
2629             #[allow(non_snake_case)]
2630             fn to_json(&self) -> Json {
2631                 match *self {
2632                     ($(ref $tyvar),*,) => Json::Array(vec![$($tyvar.to_json()),*])
2633                 }
2634             }
2635         }
2636     }
2637 }
2638
2639 tuple_impl! {A}
2640 tuple_impl! {A, B}
2641 tuple_impl! {A, B, C}
2642 tuple_impl! {A, B, C, D}
2643 tuple_impl! {A, B, C, D, E}
2644 tuple_impl! {A, B, C, D, E, F}
2645 tuple_impl! {A, B, C, D, E, F, G}
2646 tuple_impl! {A, B, C, D, E, F, G, H}
2647 tuple_impl! {A, B, C, D, E, F, G, H, I}
2648 tuple_impl! {A, B, C, D, E, F, G, H, I, J}
2649 tuple_impl! {A, B, C, D, E, F, G, H, I, J, K}
2650 tuple_impl! {A, B, C, D, E, F, G, H, I, J, K, L}
2651
2652 impl<A: ToJson> ToJson for [A] {
2653     fn to_json(&self) -> Json {
2654         Json::Array(self.iter().map(|elt| elt.to_json()).collect())
2655     }
2656 }
2657
2658 impl<A: ToJson> ToJson for Vec<A> {
2659     fn to_json(&self) -> Json {
2660         Json::Array(self.iter().map(|elt| elt.to_json()).collect())
2661     }
2662 }
2663
2664 impl<T: ToString, A: ToJson> ToJson for BTreeMap<T, A> {
2665     fn to_json(&self) -> Json {
2666         let mut d = BTreeMap::new();
2667         for (key, value) in self {
2668             d.insert(key.to_string(), value.to_json());
2669         }
2670         Json::Object(d)
2671     }
2672 }
2673
2674 impl<A: ToJson> ToJson for HashMap<string::String, A> {
2675     fn to_json(&self) -> Json {
2676         let mut d = BTreeMap::new();
2677         for (key, value) in self {
2678             d.insert((*key).clone(), value.to_json());
2679         }
2680         Json::Object(d)
2681     }
2682 }
2683
2684 impl<A: ToJson> ToJson for Option<A> {
2685     fn to_json(&self) -> Json {
2686         match *self {
2687             None => Json::Null,
2688             Some(ref value) => value.to_json(),
2689         }
2690     }
2691 }
2692
2693 struct FormatShim<'a, 'b> {
2694     inner: &'a mut fmt::Formatter<'b>,
2695 }
2696
2697 impl<'a, 'b> fmt::Write for FormatShim<'a, 'b> {
2698     fn write_str(&mut self, s: &str) -> fmt::Result {
2699         match self.inner.write_str(s) {
2700             Ok(_) => Ok(()),
2701             Err(_) => Err(fmt::Error),
2702         }
2703     }
2704 }
2705
2706 impl fmt::Display for Json {
2707     /// Encodes a json value into a string
2708     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2709         let mut shim = FormatShim { inner: f };
2710         let mut encoder = Encoder::new(&mut shim);
2711         match self.encode(&mut encoder) {
2712             Ok(_) => Ok(()),
2713             Err(_) => Err(fmt::Error),
2714         }
2715     }
2716 }
2717
2718 impl<'a> fmt::Display for PrettyJson<'a> {
2719     /// Encodes a json value into a string
2720     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2721         let mut shim = FormatShim { inner: f };
2722         let mut encoder = PrettyEncoder::new(&mut shim);
2723         match self.inner.encode(&mut encoder) {
2724             Ok(_) => Ok(()),
2725             Err(_) => Err(fmt::Error),
2726         }
2727     }
2728 }
2729
2730 impl<'a, T: Encodable> fmt::Display for AsJson<'a, T> {
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.inner.encode(&mut encoder) {
2736             Ok(_) => Ok(()),
2737             Err(_) => Err(fmt::Error),
2738         }
2739     }
2740 }
2741
2742 impl<'a, T> AsPrettyJson<'a, T> {
2743     /// Sets the indentation level for the emitted JSON
2744     pub fn indent(mut self, indent: usize) -> AsPrettyJson<'a, T> {
2745         self.indent = Some(indent);
2746         self
2747     }
2748 }
2749
2750 impl<'a, T: Encodable> fmt::Display for AsPrettyJson<'a, T> {
2751     /// Encodes a json value into a string
2752     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2753         let mut shim = FormatShim { inner: f };
2754         let mut encoder = PrettyEncoder::new(&mut shim);
2755         if let Some(n) = self.indent {
2756             encoder.set_indent(n);
2757         }
2758         match self.inner.encode(&mut encoder) {
2759             Ok(_) => Ok(()),
2760             Err(_) => Err(fmt::Error),
2761         }
2762     }
2763 }
2764
2765 impl FromStr for Json {
2766     type Err = BuilderError;
2767     fn from_str(s: &str) -> Result<Json, BuilderError> {
2768         from_str(s)
2769     }
2770 }
2771
2772 #[cfg(test)]
2773 mod tests;