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