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