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