json.rs 80.0 KB
Newer Older
A
Alexander Regueiro 已提交
1
// Rust JSON serialization library.
E
Elly Jones 已提交
2
// Copyright (c) 2011 Google Inc.
3

4
#![forbid(non_camel_case_types)]
A
Aaron Turon 已提交
5
#![allow(missing_docs)]
E
Elly Jones 已提交
6

S
Steve Klabnik 已提交
7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
//! JSON parsing and serialization
//!
//! # What is JSON?
//!
//! JSON (JavaScript Object Notation) is a way to write data in Javascript.
//! Like XML, it allows to encode structured data in a text format that can be easily read by humans
//! Its simple syntax and native compatibility with JavaScript have made it a widely used format.
//!
//! Data types that can be encoded are JavaScript types (see the `Json` enum for more details):
//!
//! * `Boolean`: equivalent to rust's `bool`
//! * `Number`: equivalent to rust's `f64`
//! * `String`: equivalent to rust's `String`
//! * `Array`: equivalent to rust's `Vec<T>`, but also allowing objects of different types in the
//!   same array
B
Brian J Brennan 已提交
22
//! * `Object`: equivalent to rust's `BTreeMap<String, json::Json>`
S
Steve Klabnik 已提交
23 24 25 26
//! * `Null`
//!
//! An object is a series of string keys mapping to values, in `"key": value` format.
//! 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
S
Steve Klabnik 已提交
28
//!
29
//! ```json
S
Steve Klabnik 已提交
30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
//! {
//!     "FirstName": "John",
//!     "LastName": "Doe",
//!     "Age": 43,
//!     "Address": {
//!         "Street": "Downing Street 10",
//!         "City": "London",
//!         "Country": "Great Britain"
//!     },
//!     "PhoneNumbers": [
//!         "+44 1234567",
//!         "+44 2345678"
//!     ]
//! }
//! ```
//!
//! # Rust Type-based Encoding and Decoding
//!
//! Rust provides a mechanism for low boilerplate encoding & decoding of values to and from JSON via
//! the serialization API.
50 51
//! To be able to encode a piece of data, it must implement the `serialize::RustcEncodable` trait.
//! To be able to decode a piece of data, it must implement the `serialize::RustcDecodable` trait.
S
Steve Klabnik 已提交
52
//! The Rust compiler provides an annotation to automatically generate the code for these traits:
53
//! `#[derive(RustcDecodable, RustcEncodable)]`
S
Steve Klabnik 已提交
54 55 56 57 58 59
//!
//! The JSON API provides an enum `json::Json` and a trait `ToJson` to encode objects.
//! The `ToJson` trait provides a `to_json` method to convert an object into a `json::Json` value.
//! A `json::Json` value can be encoded as a string or buffer using the functions described above.
//! You can also use the `json::Encoder` object, which implements the `Encoder` trait.
//!
60
//! When using `ToJson` the `RustcEncodable` trait implementation is not mandatory.
S
Steve Klabnik 已提交
61 62 63 64 65 66 67 68
//!
//! # Examples of use
//!
//! ## Using Autoserialization
//!
//! Create a struct called `TestStruct` and serialize and deserialize it to and from JSON using the
//! serialization API, using the derived serialization code.
//!
69
//! ```rust
70 71 72
//! # #![feature(rustc_private)]
//! extern crate serialize as rustc_serialize; // for the deriving below
//! use rustc_serialize::json;
S
Steve Klabnik 已提交
73 74
//!
//! // Automatically generate `Decodable` and `Encodable` trait implementations
75
//! #[derive(RustcDecodable, RustcEncodable)]
S
Steve Klabnik 已提交
76 77 78 79 80 81 82 83 84
//! pub struct TestStruct  {
//!     data_int: u8,
//!     data_str: String,
//!     data_vector: Vec<u8>,
//! }
//!
//! fn main() {
//!     let object = TestStruct {
//!         data_int: 1,
B
Barosl Lee 已提交
85
//!         data_str: "homura".to_string(),
S
Steve Klabnik 已提交
86 87 88 89
//!         data_vector: vec![2,3,4,5],
//!     };
//!
//!     // Serialize using `json::encode`
90
//!     let encoded = json::encode(&object).unwrap();
S
Steve Klabnik 已提交
91 92
//!
//!     // Deserialize using `json::decode`
E
Emeliov Dmitrii 已提交
93
//!     let decoded: TestStruct = json::decode(&encoded[..]).unwrap();
S
Steve Klabnik 已提交
94 95 96 97 98 99 100 101 102 103
//! }
//! ```
//!
//! ## Using the `ToJson` trait
//!
//! The examples above use the `ToJson` trait to generate the JSON string, which is required
//! for custom mappings.
//!
//! ### Simple example of `ToJson` usage
//!
104
//! ```rust
105
//! # #![feature(rustc_private)]
106 107
//! extern crate serialize as rustc_serialize;
//! use rustc_serialize::json::{self, ToJson, Json};
S
Steve Klabnik 已提交
108 109 110 111 112 113 114 115 116
//!
//! // A custom data structure
//! struct ComplexNum {
//!     a: f64,
//!     b: f64,
//! }
//!
//! // JSON value representation
//! impl ToJson for ComplexNum {
117 118
//!     fn to_json(&self) -> Json {
//!         Json::String(format!("{}+{}i", self.a, self.b))
S
Steve Klabnik 已提交
119 120 121
//!     }
//! }
//!
122
//! // Only generate `RustcEncodable` trait implementation
123
//! #[derive(RustcEncodable)]
S
Steve Klabnik 已提交
124 125 126
//! pub struct ComplexNumRecord {
//!     uid: u8,
//!     dsc: String,
127
//!     val: Json,
S
Steve Klabnik 已提交
128 129 130 131 132 133 134 135
//! }
//!
//! fn main() {
//!     let num = ComplexNum { a: 0.0001, b: 12.539 };
//!     let data: String = json::encode(&ComplexNumRecord{
//!         uid: 1,
//!         dsc: "test".to_string(),
//!         val: num.to_json(),
136
//!     }).unwrap();
S
Steve Klabnik 已提交
137
//!     println!("data: {}", data);
B
benaryorg 已提交
138
//!     // data: {"uid":1,"dsc":"test","val":"0.0001+12.539i"};
S
Steve Klabnik 已提交
139 140 141 142 143
//! }
//! ```
//!
//! ### Verbose example of `ToJson` usage
//!
144
//! ```rust
145
//! # #![feature(rustc_private)]
146
//! extern crate serialize as rustc_serialize;
A
Alexis Beingessner 已提交
147
//! use std::collections::BTreeMap;
148
//! use rustc_serialize::json::{self, Json, ToJson};
S
Steve Klabnik 已提交
149
//!
150 151
//! // Only generate `RustcDecodable` trait implementation
//! #[derive(RustcDecodable)]
S
Steve Klabnik 已提交
152 153 154 155 156 157 158 159
//! pub struct TestStruct {
//!     data_int: u8,
//!     data_str: String,
//!     data_vector: Vec<u8>,
//! }
//!
//! // Specify encoding method manually
//! impl ToJson for TestStruct {
160
//!     fn to_json(&self) -> Json {
A
Alexis Beingessner 已提交
161
//!         let mut d = BTreeMap::new();
S
Steve Klabnik 已提交
162 163 164 165
//!         // All standard types implement `to_json()`, so use it
//!         d.insert("data_int".to_string(), self.data_int.to_json());
//!         d.insert("data_str".to_string(), self.data_str.to_json());
//!         d.insert("data_vector".to_string(), self.data_vector.to_json());
166
//!         Json::Object(d)
S
Steve Klabnik 已提交
167 168 169 170 171 172 173
//!     }
//! }
//!
//! fn main() {
//!     // Serialize using `ToJson`
//!     let input_data = TestStruct {
//!         data_int: 1,
B
Barosl Lee 已提交
174
//!         data_str: "madoka".to_string(),
S
Steve Klabnik 已提交
175 176
//!         data_vector: vec![2,3,4,5],
//!     };
177
//!     let json_obj: Json = input_data.to_json();
S
Steve Klabnik 已提交
178 179 180
//!     let json_str: String = json_obj.to_string();
//!
//!     // Deserialize like before
181
//!     let decoded: TestStruct = json::decode(&json_str).unwrap();
S
Steve Klabnik 已提交
182 183
//! }
//! ```
B
Brian Anderson 已提交
184

M
Mark Rousskov 已提交
185
use self::DecoderError::*;
186
use self::ErrorCode::*;
M
Mark Rousskov 已提交
187 188
use self::InternalStackElement::*;
use self::JsonEvent::*;
189
use self::ParserError::*;
S
Steven Fackler 已提交
190 191
use self::ParserState::*;

192
use std::borrow::Cow;
M
Mark Rousskov 已提交
193
use std::collections::{BTreeMap, HashMap};
194
use std::io;
M
Mark Rousskov 已提交
195
use std::io::prelude::*;
196
use std::mem::swap;
T
Tobias Bucher 已提交
197
use std::num::FpCategory as Fp;
198
use std::ops::Index;
T
Tobias Bucher 已提交
199
use std::str::FromStr;
200
use std::string;
201
use std::{char, fmt, str};
202

203
use crate::Encodable;
E
Elly Jones 已提交
204

205
/// Represents a json value
J
Jorge Aparicio 已提交
206
#[derive(Clone, PartialEq, PartialOrd, Debug)]
207
pub enum Json {
208 209 210
    I64(i64),
    U64(u64),
    F64(f64),
211
    String(string::String),
B
Ben Striegel 已提交
212
    Boolean(bool),
213 214
    Array(self::Array),
    Object(self::Object),
B
Ben Striegel 已提交
215
    Null,
E
Elly Jones 已提交
216 217
}

218
pub type Array = Vec<Json>;
A
Alexis Beingessner 已提交
219
pub type Object = BTreeMap<string::String, Json>;
220

M
Mark Rousskov 已提交
221 222 223
pub struct PrettyJson<'a> {
    inner: &'a Json,
}
224

M
Mark Rousskov 已提交
225 226 227 228 229 230 231
pub struct AsJson<'a, T> {
    inner: &'a T,
}
pub struct AsPrettyJson<'a, T> {
    inner: &'a T,
    indent: Option<usize>,
}
232

233
/// The errors that can arise while parsing a JSON stream.
J
Jorge Aparicio 已提交
234
#[derive(Clone, Copy, PartialEq, Debug)]
235 236 237 238
pub enum ErrorCode {
    InvalidSyntax,
    InvalidNumber,
    EOFWhileParsingObject,
C
Corey Farwell 已提交
239
    EOFWhileParsingArray,
240 241 242 243 244
    EOFWhileParsingValue,
    EOFWhileParsingString,
    KeyMustBeAString,
    ExpectedColon,
    TrailingCharacters,
245
    TrailingComma,
246 247 248 249 250 251 252 253 254
    InvalidEscape,
    InvalidUnicodeCodePoint,
    LoneLeadingSurrogateInHexEscape,
    UnexpectedEndOfHexEscape,
    UnrecognizedHex,
    NotFourDigit,
    NotUtf8,
}

255
#[derive(Clone, PartialEq, Debug)]
256
pub enum ParserError {
S
Sean McArthur 已提交
257
    /// msg, line, col
258
    SyntaxError(ErrorCode, usize, usize),
259
    IoError(io::ErrorKind, String),
260 261 262 263 264
}

// Builder and Parser have the same errors.
pub type BuilderError = ParserError;

J
Jorge Aparicio 已提交
265
#[derive(Clone, PartialEq, Debug)]
266 267
pub enum DecoderError {
    ParseError(ParserError),
268 269 270
    ExpectedError(string::String, string::String),
    MissingFieldError(string::String),
    UnknownVariantError(string::String),
M
Mark Rousskov 已提交
271
    ApplicationError(string::String),
272 273
}

274
#[derive(Copy, Clone, Debug)]
275 276 277 278 279
pub enum EncoderError {
    FmtError(fmt::Error),
    BadHashmapKey,
}

280 281
/// Returns a readable error string for a given error code.
pub fn error_str(error: ErrorCode) -> &'static str {
282
    match error {
283 284 285
        InvalidSyntax => "invalid syntax",
        InvalidNumber => "invalid number",
        EOFWhileParsingObject => "EOF While parsing object",
C
Corey Farwell 已提交
286
        EOFWhileParsingArray => "EOF While parsing array",
287 288 289 290 291
        EOFWhileParsingValue => "EOF While parsing value",
        EOFWhileParsingString => "EOF While parsing string",
        KeyMustBeAString => "key must be a string",
        ExpectedColon => "expected `:`",
        TrailingCharacters => "trailing characters",
292
        TrailingComma => "trailing comma",
293
        InvalidEscape => "invalid escape",
A
Alex Crichton 已提交
294 295
        UnrecognizedHex => "invalid \\u{ esc}ape (unrecognized hex)",
        NotFourDigit => "invalid \\u{ esc}ape (not four digits)",
296
        NotUtf8 => "contents not utf-8",
297
        InvalidUnicodeCodePoint => "invalid Unicode code point",
298 299 300 301 302
        LoneLeadingSurrogateInHexEscape => "lone leading surrogate in hex escape",
        UnexpectedEndOfHexEscape => "unexpected end of hex escape",
    }
}

303
/// Shortcut function to decode a JSON `&str` into an object
304
pub fn decode<T: crate::Decodable>(s: &str) -> DecodeResult<T> {
305 306
    let json = match from_str(s) {
        Ok(x) => x,
M
Mark Rousskov 已提交
307
        Err(e) => return Err(ParseError(e)),
308 309 310
    };

    let mut decoder = Decoder::new(json);
311
    crate::Decodable::decode(&mut decoder)
312 313 314
}

/// Shortcut function to encode a `T` into a JSON `String`
315
pub fn encode<T: crate::Encodable>(object: &T) -> Result<string::String, EncoderError> {
316 317 318
    let mut s = String::new();
    {
        let mut encoder = Encoder::new(&mut s);
J
Jorge Aparicio 已提交
319
        object.encode(&mut encoder)?;
320
    }
321
    Ok(s)
322 323
}

324
impl fmt::Display for ErrorCode {
325
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
326 327 328 329
        error_str(*self).fmt(f)
    }
}

330 331
fn io_error_to_error(io: io::Error) -> ParserError {
    IoError(io.kind(), io.to_string())
332
}
333

334
impl fmt::Display for ParserError {
335
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
336 337 338 339 340 341
        // FIXME this should be a nicer error
        fmt::Debug::fmt(self, f)
    }
}

impl fmt::Display for DecoderError {
342
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
343 344 345 346 347
        // FIXME this should be a nicer error
        fmt::Debug::fmt(self, f)
    }
}

348
impl std::error::Error for DecoderError {}
349 350

impl fmt::Display for EncoderError {
351
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
352 353 354
        // FIXME this should be a nicer error
        fmt::Debug::fmt(self, f)
    }
355 356
}

357
impl std::error::Error for EncoderError {}
358

359
impl From<fmt::Error> for EncoderError {
J
Jacob 已提交
360
    /// Converts a [`fmt::Error`] into `EncoderError`
361 362
    ///
    /// This conversion does not allocate memory.
M
Mark Rousskov 已提交
363 364 365
    fn from(err: fmt::Error) -> EncoderError {
        EncoderError::FmtError(err)
    }
366 367 368
}

pub type EncodeResult = Result<(), EncoderError>;
369
pub type DecodeResult<T> = Result<T, DecoderError>;
A
Alex Crichton 已提交
370

371
fn escape_str(wr: &mut dyn fmt::Write, v: &str) -> EncodeResult {
J
Jorge Aparicio 已提交
372
    wr.write_str("\"")?;
373 374 375

    let mut start = 0;

376 377
    for (i, byte) in v.bytes().enumerate() {
        let escaped = match byte {
378 379
            b'"' => "\\\"",
            b'\\' => "\\\\",
R
Rolf Timmermans 已提交
380 381 382 383 384 385 386 387
            b'\x00' => "\\u0000",
            b'\x01' => "\\u0001",
            b'\x02' => "\\u0002",
            b'\x03' => "\\u0003",
            b'\x04' => "\\u0004",
            b'\x05' => "\\u0005",
            b'\x06' => "\\u0006",
            b'\x07' => "\\u0007",
388
            b'\x08' => "\\b",
R
Rolf Timmermans 已提交
389
            b'\t' => "\\t",
390
            b'\n' => "\\n",
R
Rolf Timmermans 已提交
391 392
            b'\x0b' => "\\u000b",
            b'\x0c' => "\\f",
393
            b'\r' => "\\r",
R
Rolf Timmermans 已提交
394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412
            b'\x0e' => "\\u000e",
            b'\x0f' => "\\u000f",
            b'\x10' => "\\u0010",
            b'\x11' => "\\u0011",
            b'\x12' => "\\u0012",
            b'\x13' => "\\u0013",
            b'\x14' => "\\u0014",
            b'\x15' => "\\u0015",
            b'\x16' => "\\u0016",
            b'\x17' => "\\u0017",
            b'\x18' => "\\u0018",
            b'\x19' => "\\u0019",
            b'\x1a' => "\\u001a",
            b'\x1b' => "\\u001b",
            b'\x1c' => "\\u001c",
            b'\x1d' => "\\u001d",
            b'\x1e' => "\\u001e",
            b'\x1f' => "\\u001f",
            b'\x7f' => "\\u007f",
M
Mark Rousskov 已提交
413 414 415
            _ => {
                continue;
            }
416 417 418
        };

        if start < i {
J
Jorge Aparicio 已提交
419
            wr.write_str(&v[start..i])?;
E
Elly Jones 已提交
420
        }
421

J
Jorge Aparicio 已提交
422
        wr.write_str(escaped)?;
423 424

        start = i + 1;
425
    }
426

427
    if start != v.len() {
J
Jorge Aparicio 已提交
428
        wr.write_str(&v[start..])?;
429 430
    }

J
Jorge Aparicio 已提交
431
    wr.write_str("\"")?;
432
    Ok(())
433 434
}

435
fn escape_char(writer: &mut dyn fmt::Write, v: char) -> EncodeResult {
436
    escape_str(writer, v.encode_utf8(&mut [0; 4]))
437 438
}

439
fn spaces(wr: &mut dyn fmt::Write, mut n: usize) -> EncodeResult {
440
    const BUF: &str = "                ";
441

442
    while n >= BUF.len() {
J
Jorge Aparicio 已提交
443
        wr.write_str(BUF)?;
444
        n -= BUF.len();
445 446 447
    }

    if n > 0 {
J
Jorge Aparicio 已提交
448
        wr.write_str(&BUF[..n])?;
449
    }
450
    Ok(())
E
Elly Jones 已提交
451 452
}

453
fn fmt_number_or_null(v: f64) -> string::String {
M
mrec 已提交
454
    match v.classify() {
455
        Fp::Nan | Fp::Infinite => string::String::from("null"),
456 457
        _ if v.fract() != 0f64 => v.to_string(),
        _ => v.to_string() + ".0",
M
mrec 已提交
458 459 460
    }
}

461
/// A structure for implementing serialization to JSON.
E
Erik Price 已提交
462
pub struct Encoder<'a> {
M
Mark Rousskov 已提交
463
    writer: &'a mut (dyn fmt::Write + 'a),
464
    is_emitting_map_key: bool,
465 466
}

E
Erik Price 已提交
467
impl<'a> Encoder<'a> {
468 469
    /// Creates a new JSON encoder whose output will be written to the writer
    /// specified.
470
    pub fn new(writer: &'a mut dyn fmt::Write) -> Encoder<'a> {
M
Mark Rousskov 已提交
471
        Encoder { writer, is_emitting_map_key: false }
472 473 474 475
    }
}

macro_rules! emit_enquoted_if_mapkey {
M
Mark Rousskov 已提交
476
    ($enc:ident,$e:expr) => {{
477
        if $enc.is_emitting_map_key {
478
            write!($enc.writer, "\"{}\"", $e)?;
479
        } else {
480
            write!($enc.writer, "{}", $e)?;
481
        }
482
        Ok(())
M
Mark Rousskov 已提交
483
    }};
484 485
}

486
impl<'a> crate::Encoder for Encoder<'a> {
487
    type Error = EncoderError;
488

K
kenta7777 已提交
489
    fn emit_unit(&mut self) -> EncodeResult {
M
Mark Rousskov 已提交
490 491 492
        if self.is_emitting_map_key {
            return Err(EncoderError::BadHashmapKey);
        }
J
Jorge Aparicio 已提交
493
        write!(self.writer, "null")?;
494 495
        Ok(())
    }
496

M
Mark Rousskov 已提交
497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514
    fn emit_usize(&mut self, v: usize) -> EncodeResult {
        emit_enquoted_if_mapkey!(self, v)
    }
    fn emit_u128(&mut self, v: u128) -> EncodeResult {
        emit_enquoted_if_mapkey!(self, v)
    }
    fn emit_u64(&mut self, v: u64) -> EncodeResult {
        emit_enquoted_if_mapkey!(self, v)
    }
    fn emit_u32(&mut self, v: u32) -> EncodeResult {
        emit_enquoted_if_mapkey!(self, v)
    }
    fn emit_u16(&mut self, v: u16) -> EncodeResult {
        emit_enquoted_if_mapkey!(self, v)
    }
    fn emit_u8(&mut self, v: u8) -> EncodeResult {
        emit_enquoted_if_mapkey!(self, v)
    }
515

M
Mark Rousskov 已提交
516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533
    fn emit_isize(&mut self, v: isize) -> EncodeResult {
        emit_enquoted_if_mapkey!(self, v)
    }
    fn emit_i128(&mut self, v: i128) -> EncodeResult {
        emit_enquoted_if_mapkey!(self, v)
    }
    fn emit_i64(&mut self, v: i64) -> EncodeResult {
        emit_enquoted_if_mapkey!(self, v)
    }
    fn emit_i32(&mut self, v: i32) -> EncodeResult {
        emit_enquoted_if_mapkey!(self, v)
    }
    fn emit_i16(&mut self, v: i16) -> EncodeResult {
        emit_enquoted_if_mapkey!(self, v)
    }
    fn emit_i8(&mut self, v: i8) -> EncodeResult {
        emit_enquoted_if_mapkey!(self, v)
    }
534

S
Sean McArthur 已提交
535
    fn emit_bool(&mut self, v: bool) -> EncodeResult {
M
Mark Rousskov 已提交
536 537 538
        if self.is_emitting_map_key {
            return Err(EncoderError::BadHashmapKey);
        }
539
        if v {
J
Jorge Aparicio 已提交
540
            write!(self.writer, "true")?;
541
        } else {
J
Jorge Aparicio 已提交
542
            write!(self.writer, "false")?;
543
        }
544
        Ok(())
545 546
    }

S
Sean McArthur 已提交
547
    fn emit_f64(&mut self, v: f64) -> EncodeResult {
548
        emit_enquoted_if_mapkey!(self, fmt_number_or_null(v))
A
Alex Crichton 已提交
549
    }
B
Barosl Lee 已提交
550
    fn emit_f32(&mut self, v: f32) -> EncodeResult {
I
Igor Matuszewski 已提交
551
        self.emit_f64(f64::from(v))
B
Barosl Lee 已提交
552
    }
553

554
    fn emit_char(&mut self, v: char) -> EncodeResult {
555
        escape_char(self.writer, v)
556
    }
S
Sean McArthur 已提交
557
    fn emit_str(&mut self, v: &str) -> EncodeResult {
558
        escape_str(self.writer, v)
A
Alex Crichton 已提交
559
    }
560

M
Mark Rousskov 已提交
561 562
    fn emit_enum<F>(&mut self, _name: &str, f: F) -> EncodeResult
    where
563 564
        F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
    {
A
Adolfo Ochagavía 已提交
565 566
        f(self)
    }
567

M
Mark Rousskov 已提交
568 569
    fn emit_enum_variant<F>(&mut self, name: &str, _id: usize, cnt: usize, f: F) -> EncodeResult
    where
570 571
        F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
    {
572 573 574 575
        // enums are encoded as strings or objects
        // Bunny => "Bunny"
        // Kangaroo(34,"William") => {"variant": "Kangaroo", "fields": [34,"William"]}
        if cnt == 0 {
576
            escape_str(self.writer, name)
577
        } else {
M
Mark Rousskov 已提交
578 579 580
            if self.is_emitting_map_key {
                return Err(EncoderError::BadHashmapKey);
            }
J
Jorge Aparicio 已提交
581 582 583 584 585
            write!(self.writer, "{{\"variant\":")?;
            escape_str(self.writer, name)?;
            write!(self.writer, ",\"fields\":[")?;
            f(self)?;
            write!(self.writer, "]}}")?;
586
            Ok(())
587 588
        }
    }
589

M
Mark Rousskov 已提交
590 591
    fn emit_enum_variant_arg<F>(&mut self, idx: usize, f: F) -> EncodeResult
    where
592 593
        F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
    {
M
Mark Rousskov 已提交
594 595 596
        if self.is_emitting_map_key {
            return Err(EncoderError::BadHashmapKey);
        }
597
        if idx != 0 {
J
Jorge Aparicio 已提交
598
            write!(self.writer, ",")?;
599
        }
S
Sean McArthur 已提交
600
        f(self)
601 602
    }

M
Mark Rousskov 已提交
603 604 605 606 607 608 609 610
    fn emit_enum_struct_variant<F>(
        &mut self,
        name: &str,
        id: usize,
        cnt: usize,
        f: F,
    ) -> EncodeResult
    where
611 612
        F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
    {
M
Mark Rousskov 已提交
613 614 615
        if self.is_emitting_map_key {
            return Err(EncoderError::BadHashmapKey);
        }
616 617 618
        self.emit_enum_variant(name, id, cnt, f)
    }

M
Mark Rousskov 已提交
619 620
    fn emit_enum_struct_variant_field<F>(&mut self, _: &str, idx: usize, f: F) -> EncodeResult
    where
621 622
        F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
    {
M
Mark Rousskov 已提交
623 624 625
        if self.is_emitting_map_key {
            return Err(EncoderError::BadHashmapKey);
        }
626 627 628
        self.emit_enum_variant_arg(idx, f)
    }

M
Mark Rousskov 已提交
629 630
    fn emit_struct<F>(&mut self, _: &str, _: usize, f: F) -> EncodeResult
    where
631 632
        F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
    {
M
Mark Rousskov 已提交
633 634 635
        if self.is_emitting_map_key {
            return Err(EncoderError::BadHashmapKey);
        }
J
Jorge Aparicio 已提交
636 637 638
        write!(self.writer, "{{")?;
        f(self)?;
        write!(self.writer, "}}")?;
639
        Ok(())
640
    }
641

M
Mark Rousskov 已提交
642 643
    fn emit_struct_field<F>(&mut self, name: &str, idx: usize, f: F) -> EncodeResult
    where
644 645
        F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
    {
M
Mark Rousskov 已提交
646 647 648 649 650 651
        if self.is_emitting_map_key {
            return Err(EncoderError::BadHashmapKey);
        }
        if idx != 0 {
            write!(self.writer, ",")?;
        }
J
Jorge Aparicio 已提交
652 653
        escape_str(self.writer, name)?;
        write!(self.writer, ":")?;
S
Sean McArthur 已提交
654
        f(self)
655 656
    }

M
Mark Rousskov 已提交
657 658
    fn emit_tuple<F>(&mut self, len: usize, f: F) -> EncodeResult
    where
659 660
        F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
    {
M
Mark Rousskov 已提交
661 662 663
        if self.is_emitting_map_key {
            return Err(EncoderError::BadHashmapKey);
        }
664 665
        self.emit_seq(len, f)
    }
M
Mark Rousskov 已提交
666 667
    fn emit_tuple_arg<F>(&mut self, idx: usize, f: F) -> EncodeResult
    where
668 669
        F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
    {
M
Mark Rousskov 已提交
670 671 672
        if self.is_emitting_map_key {
            return Err(EncoderError::BadHashmapKey);
        }
673 674 675
        self.emit_seq_elt(idx, f)
    }

M
Mark Rousskov 已提交
676 677
    fn emit_tuple_struct<F>(&mut self, _name: &str, len: usize, f: F) -> EncodeResult
    where
678 679
        F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
    {
M
Mark Rousskov 已提交
680 681 682
        if self.is_emitting_map_key {
            return Err(EncoderError::BadHashmapKey);
        }
683 684
        self.emit_seq(len, f)
    }
M
Mark Rousskov 已提交
685 686
    fn emit_tuple_struct_arg<F>(&mut self, idx: usize, f: F) -> EncodeResult
    where
687 688
        F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
    {
M
Mark Rousskov 已提交
689 690 691
        if self.is_emitting_map_key {
            return Err(EncoderError::BadHashmapKey);
        }
692 693 694
        self.emit_seq_elt(idx, f)
    }

M
Mark Rousskov 已提交
695 696
    fn emit_option<F>(&mut self, f: F) -> EncodeResult
    where
697 698
        F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
    {
M
Mark Rousskov 已提交
699 700 701
        if self.is_emitting_map_key {
            return Err(EncoderError::BadHashmapKey);
        }
S
Sean McArthur 已提交
702 703
        f(self)
    }
704
    fn emit_option_none(&mut self) -> EncodeResult {
M
Mark Rousskov 已提交
705 706 707
        if self.is_emitting_map_key {
            return Err(EncoderError::BadHashmapKey);
        }
K
kenta7777 已提交
708
        self.emit_unit()
709
    }
M
Mark Rousskov 已提交
710 711
    fn emit_option_some<F>(&mut self, f: F) -> EncodeResult
    where
712 713
        F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
    {
M
Mark Rousskov 已提交
714 715 716
        if self.is_emitting_map_key {
            return Err(EncoderError::BadHashmapKey);
        }
S
Sean McArthur 已提交
717 718
        f(self)
    }
719

M
Mark Rousskov 已提交
720 721
    fn emit_seq<F>(&mut self, _len: usize, f: F) -> EncodeResult
    where
722 723
        F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
    {
M
Mark Rousskov 已提交
724 725 726
        if self.is_emitting_map_key {
            return Err(EncoderError::BadHashmapKey);
        }
J
Jorge Aparicio 已提交
727 728 729
        write!(self.writer, "[")?;
        f(self)?;
        write!(self.writer, "]")?;
730
        Ok(())
731 732
    }

M
Mark Rousskov 已提交
733 734
    fn emit_seq_elt<F>(&mut self, idx: usize, f: F) -> EncodeResult
    where
735 736
        F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
    {
M
Mark Rousskov 已提交
737 738 739
        if self.is_emitting_map_key {
            return Err(EncoderError::BadHashmapKey);
        }
740
        if idx != 0 {
J
Jorge Aparicio 已提交
741
            write!(self.writer, ",")?;
742 743 744 745
        }
        f(self)
    }

M
Mark Rousskov 已提交
746 747
    fn emit_map<F>(&mut self, _len: usize, f: F) -> EncodeResult
    where
748 749
        F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
    {
M
Mark Rousskov 已提交
750 751 752
        if self.is_emitting_map_key {
            return Err(EncoderError::BadHashmapKey);
        }
J
Jorge Aparicio 已提交
753 754 755
        write!(self.writer, "{{")?;
        f(self)?;
        write!(self.writer, "}}")?;
756
        Ok(())
757
    }
758

M
Mark Rousskov 已提交
759 760
    fn emit_map_elt_key<F>(&mut self, idx: usize, f: F) -> EncodeResult
    where
761
        F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
762
    {
M
Mark Rousskov 已提交
763 764 765 766 767 768
        if self.is_emitting_map_key {
            return Err(EncoderError::BadHashmapKey);
        }
        if idx != 0 {
            write!(self.writer, ",")?
        }
769
        self.is_emitting_map_key = true;
J
Jorge Aparicio 已提交
770
        f(self)?;
771
        self.is_emitting_map_key = false;
S
Sean McArthur 已提交
772
        Ok(())
773 774
    }

M
Mark Rousskov 已提交
775 776
    fn emit_map_elt_val<F>(&mut self, _idx: usize, f: F) -> EncodeResult
    where
777 778
        F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
    {
M
Mark Rousskov 已提交
779 780 781
        if self.is_emitting_map_key {
            return Err(EncoderError::BadHashmapKey);
        }
J
Jorge Aparicio 已提交
782
        write!(self.writer, ":")?;
783 784 785 786
        f(self)
    }
}

787 788
/// Another encoder for JSON, but prints out human-readable JSON instead of
/// compact data
E
Erik Price 已提交
789
pub struct PrettyEncoder<'a> {
M
Mark Rousskov 已提交
790
    writer: &'a mut (dyn fmt::Write + 'a),
791 792
    curr_indent: usize,
    indent: usize,
793
    is_emitting_map_key: bool,
794 795
}

E
Erik Price 已提交
796
impl<'a> PrettyEncoder<'a> {
797
    /// Creates a new encoder whose output will be written to the specified writer
798
    pub fn new(writer: &'a mut dyn fmt::Write) -> PrettyEncoder<'a> {
M
Mark Rousskov 已提交
799
        PrettyEncoder { writer, curr_indent: 0, indent: 2, is_emitting_map_key: false }
800 801
    }

A
Alexander Regueiro 已提交
802
    /// Sets the number of spaces to indent for each level.
803
    /// This is safe to set during encoding.
804
    pub fn set_indent(&mut self, indent: usize) {
805
        // self.indent very well could be 0 so we need to use checked division.
806
        let level = self.curr_indent.checked_div(self.indent).unwrap_or(0);
807 808
        self.indent = indent;
        self.curr_indent = level * self.indent;
809
    }
810
}
811

812
impl<'a> crate::Encoder for PrettyEncoder<'a> {
813
    type Error = EncoderError;
814

K
kenta7777 已提交
815
    fn emit_unit(&mut self) -> EncodeResult {
M
Mark Rousskov 已提交
816 817 818
        if self.is_emitting_map_key {
            return Err(EncoderError::BadHashmapKey);
        }
J
Jorge Aparicio 已提交
819
        write!(self.writer, "null")?;
820 821
        Ok(())
    }
822

M
Mark Rousskov 已提交
823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840
    fn emit_usize(&mut self, v: usize) -> EncodeResult {
        emit_enquoted_if_mapkey!(self, v)
    }
    fn emit_u128(&mut self, v: u128) -> EncodeResult {
        emit_enquoted_if_mapkey!(self, v)
    }
    fn emit_u64(&mut self, v: u64) -> EncodeResult {
        emit_enquoted_if_mapkey!(self, v)
    }
    fn emit_u32(&mut self, v: u32) -> EncodeResult {
        emit_enquoted_if_mapkey!(self, v)
    }
    fn emit_u16(&mut self, v: u16) -> EncodeResult {
        emit_enquoted_if_mapkey!(self, v)
    }
    fn emit_u8(&mut self, v: u8) -> EncodeResult {
        emit_enquoted_if_mapkey!(self, v)
    }
841

M
Mark Rousskov 已提交
842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859
    fn emit_isize(&mut self, v: isize) -> EncodeResult {
        emit_enquoted_if_mapkey!(self, v)
    }
    fn emit_i128(&mut self, v: i128) -> EncodeResult {
        emit_enquoted_if_mapkey!(self, v)
    }
    fn emit_i64(&mut self, v: i64) -> EncodeResult {
        emit_enquoted_if_mapkey!(self, v)
    }
    fn emit_i32(&mut self, v: i32) -> EncodeResult {
        emit_enquoted_if_mapkey!(self, v)
    }
    fn emit_i16(&mut self, v: i16) -> EncodeResult {
        emit_enquoted_if_mapkey!(self, v)
    }
    fn emit_i8(&mut self, v: i8) -> EncodeResult {
        emit_enquoted_if_mapkey!(self, v)
    }
860

S
Sean McArthur 已提交
861
    fn emit_bool(&mut self, v: bool) -> EncodeResult {
M
Mark Rousskov 已提交
862 863 864
        if self.is_emitting_map_key {
            return Err(EncoderError::BadHashmapKey);
        }
865
        if v {
J
Jorge Aparicio 已提交
866
            write!(self.writer, "true")?;
867
        } else {
J
Jorge Aparicio 已提交
868
            write!(self.writer, "false")?;
869
        }
870
        Ok(())
871 872
    }

S
Sean McArthur 已提交
873
    fn emit_f64(&mut self, v: f64) -> EncodeResult {
874
        emit_enquoted_if_mapkey!(self, fmt_number_or_null(v))
A
Alex Crichton 已提交
875
    }
876
    fn emit_f32(&mut self, v: f32) -> EncodeResult {
I
Igor Matuszewski 已提交
877
        self.emit_f64(f64::from(v))
878
    }
879

880
    fn emit_char(&mut self, v: char) -> EncodeResult {
881
        escape_char(self.writer, v)
882
    }
S
Sean McArthur 已提交
883
    fn emit_str(&mut self, v: &str) -> EncodeResult {
884
        escape_str(self.writer, v)
A
Alex Crichton 已提交
885
    }
886

M
Mark Rousskov 已提交
887 888
    fn emit_enum<F>(&mut self, _name: &str, f: F) -> EncodeResult
    where
889 890
        F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
    {
891 892 893
        f(self)
    }

M
Mark Rousskov 已提交
894 895
    fn emit_enum_variant<F>(&mut self, name: &str, _id: usize, cnt: usize, f: F) -> EncodeResult
    where
896 897
        F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
    {
898
        if cnt == 0 {
899
            escape_str(self.writer, name)
900
        } else {
M
Mark Rousskov 已提交
901 902 903
            if self.is_emitting_map_key {
                return Err(EncoderError::BadHashmapKey);
            }
904
            writeln!(self.writer, "{{")?;
905
            self.curr_indent += self.indent;
J
Jorge Aparicio 已提交
906 907 908
            spaces(self.writer, self.curr_indent)?;
            write!(self.writer, "\"variant\": ")?;
            escape_str(self.writer, name)?;
909
            writeln!(self.writer, ",")?;
J
Jorge Aparicio 已提交
910
            spaces(self.writer, self.curr_indent)?;
911
            writeln!(self.writer, "\"fields\": [")?;
912
            self.curr_indent += self.indent;
J
Jorge Aparicio 已提交
913
            f(self)?;
914
            self.curr_indent -= self.indent;
915
            writeln!(self.writer)?;
J
Jorge Aparicio 已提交
916
            spaces(self.writer, self.curr_indent)?;
917
            self.curr_indent -= self.indent;
918
            writeln!(self.writer, "]")?;
J
Jorge Aparicio 已提交
919 920
            spaces(self.writer, self.curr_indent)?;
            write!(self.writer, "}}")?;
921
            Ok(())
922 923 924
        }
    }

M
Mark Rousskov 已提交
925 926
    fn emit_enum_variant_arg<F>(&mut self, idx: usize, f: F) -> EncodeResult
    where
927 928
        F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
    {
M
Mark Rousskov 已提交
929 930 931
        if self.is_emitting_map_key {
            return Err(EncoderError::BadHashmapKey);
        }
932
        if idx != 0 {
933
            writeln!(self.writer, ",")?;
934
        }
J
Jorge Aparicio 已提交
935
        spaces(self.writer, self.curr_indent)?;
936 937 938
        f(self)
    }

M
Mark Rousskov 已提交
939 940 941 942 943 944 945 946
    fn emit_enum_struct_variant<F>(
        &mut self,
        name: &str,
        id: usize,
        cnt: usize,
        f: F,
    ) -> EncodeResult
    where
947 948
        F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
    {
M
Mark Rousskov 已提交
949 950 951
        if self.is_emitting_map_key {
            return Err(EncoderError::BadHashmapKey);
        }
952 953 954
        self.emit_enum_variant(name, id, cnt, f)
    }

M
Mark Rousskov 已提交
955 956
    fn emit_enum_struct_variant_field<F>(&mut self, _: &str, idx: usize, f: F) -> EncodeResult
    where
957 958
        F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
    {
M
Mark Rousskov 已提交
959 960 961
        if self.is_emitting_map_key {
            return Err(EncoderError::BadHashmapKey);
        }
962 963 964
        self.emit_enum_variant_arg(idx, f)
    }

M
Mark Rousskov 已提交
965 966
    fn emit_struct<F>(&mut self, _: &str, len: usize, f: F) -> EncodeResult
    where
967 968
        F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
    {
M
Mark Rousskov 已提交
969 970 971
        if self.is_emitting_map_key {
            return Err(EncoderError::BadHashmapKey);
        }
972
        if len == 0 {
J
Jorge Aparicio 已提交
973
            write!(self.writer, "{{}}")?;
974
        } else {
J
Jorge Aparicio 已提交
975
            write!(self.writer, "{{")?;
976
            self.curr_indent += self.indent;
J
Jorge Aparicio 已提交
977
            f(self)?;
978
            self.curr_indent -= self.indent;
979
            writeln!(self.writer)?;
J
Jorge Aparicio 已提交
980 981
            spaces(self.writer, self.curr_indent)?;
            write!(self.writer, "}}")?;
982
        }
983
        Ok(())
984
    }
985

M
Mark Rousskov 已提交
986 987
    fn emit_struct_field<F>(&mut self, name: &str, idx: usize, f: F) -> EncodeResult
    where
988 989
        F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
    {
M
Mark Rousskov 已提交
990 991 992
        if self.is_emitting_map_key {
            return Err(EncoderError::BadHashmapKey);
        }
993
        if idx == 0 {
994
            writeln!(self.writer)?;
995
        } else {
996
            writeln!(self.writer, ",")?;
997
        }
J
Jorge Aparicio 已提交
998 999 1000
        spaces(self.writer, self.curr_indent)?;
        escape_str(self.writer, name)?;
        write!(self.writer, ": ")?;
S
Sean McArthur 已提交
1001
        f(self)
1002 1003
    }

M
Mark Rousskov 已提交
1004 1005
    fn emit_tuple<F>(&mut self, len: usize, f: F) -> EncodeResult
    where
1006 1007
        F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
    {
M
Mark Rousskov 已提交
1008 1009 1010
        if self.is_emitting_map_key {
            return Err(EncoderError::BadHashmapKey);
        }
1011 1012
        self.emit_seq(len, f)
    }
M
Mark Rousskov 已提交
1013 1014
    fn emit_tuple_arg<F>(&mut self, idx: usize, f: F) -> EncodeResult
    where
1015 1016
        F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
    {
M
Mark Rousskov 已提交
1017 1018 1019
        if self.is_emitting_map_key {
            return Err(EncoderError::BadHashmapKey);
        }
1020 1021 1022
        self.emit_seq_elt(idx, f)
    }

M
Mark Rousskov 已提交
1023 1024
    fn emit_tuple_struct<F>(&mut self, _: &str, len: usize, f: F) -> EncodeResult
    where
1025 1026
        F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
    {
M
Mark Rousskov 已提交
1027 1028 1029
        if self.is_emitting_map_key {
            return Err(EncoderError::BadHashmapKey);
        }
1030 1031
        self.emit_seq(len, f)
    }
M
Mark Rousskov 已提交
1032 1033
    fn emit_tuple_struct_arg<F>(&mut self, idx: usize, f: F) -> EncodeResult
    where
1034 1035
        F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
    {
M
Mark Rousskov 已提交
1036 1037 1038
        if self.is_emitting_map_key {
            return Err(EncoderError::BadHashmapKey);
        }
1039 1040 1041
        self.emit_seq_elt(idx, f)
    }

M
Mark Rousskov 已提交
1042 1043
    fn emit_option<F>(&mut self, f: F) -> EncodeResult
    where
1044 1045
        F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
    {
M
Mark Rousskov 已提交
1046 1047 1048
        if self.is_emitting_map_key {
            return Err(EncoderError::BadHashmapKey);
        }
S
Sean McArthur 已提交
1049 1050
        f(self)
    }
1051
    fn emit_option_none(&mut self) -> EncodeResult {
M
Mark Rousskov 已提交
1052 1053 1054
        if self.is_emitting_map_key {
            return Err(EncoderError::BadHashmapKey);
        }
K
kenta7777 已提交
1055
        self.emit_unit()
1056
    }
M
Mark Rousskov 已提交
1057 1058
    fn emit_option_some<F>(&mut self, f: F) -> EncodeResult
    where
1059 1060
        F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
    {
M
Mark Rousskov 已提交
1061 1062 1063
        if self.is_emitting_map_key {
            return Err(EncoderError::BadHashmapKey);
        }
S
Sean McArthur 已提交
1064 1065
        f(self)
    }
1066

M
Mark Rousskov 已提交
1067 1068
    fn emit_seq<F>(&mut self, len: usize, f: F) -> EncodeResult
    where
1069 1070
        F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
    {
M
Mark Rousskov 已提交
1071 1072 1073
        if self.is_emitting_map_key {
            return Err(EncoderError::BadHashmapKey);
        }
1074
        if len == 0 {
J
Jorge Aparicio 已提交
1075
            write!(self.writer, "[]")?;
1076
        } else {
J
Jorge Aparicio 已提交
1077
            write!(self.writer, "[")?;
1078
            self.curr_indent += self.indent;
J
Jorge Aparicio 已提交
1079
            f(self)?;
1080
            self.curr_indent -= self.indent;
1081
            writeln!(self.writer)?;
J
Jorge Aparicio 已提交
1082 1083
            spaces(self.writer, self.curr_indent)?;
            write!(self.writer, "]")?;
1084
        }
1085
        Ok(())
1086 1087
    }

M
Mark Rousskov 已提交
1088 1089
    fn emit_seq_elt<F>(&mut self, idx: usize, f: F) -> EncodeResult
    where
1090 1091
        F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
    {
M
Mark Rousskov 已提交
1092 1093 1094
        if self.is_emitting_map_key {
            return Err(EncoderError::BadHashmapKey);
        }
1095
        if idx == 0 {
1096
            writeln!(self.writer)?;
1097
        } else {
1098
            writeln!(self.writer, ",")?;
1099
        }
J
Jorge Aparicio 已提交
1100
        spaces(self.writer, self.curr_indent)?;
1101 1102 1103
        f(self)
    }

M
Mark Rousskov 已提交
1104 1105
    fn emit_map<F>(&mut self, len: usize, f: F) -> EncodeResult
    where
1106 1107
        F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
    {
M
Mark Rousskov 已提交
1108 1109 1110
        if self.is_emitting_map_key {
            return Err(EncoderError::BadHashmapKey);
        }
1111
        if len == 0 {
J
Jorge Aparicio 已提交
1112
            write!(self.writer, "{{}}")?;
1113
        } else {
J
Jorge Aparicio 已提交
1114
            write!(self.writer, "{{")?;
1115
            self.curr_indent += self.indent;
J
Jorge Aparicio 已提交
1116
            f(self)?;
1117
            self.curr_indent -= self.indent;
1118
            writeln!(self.writer)?;
J
Jorge Aparicio 已提交
1119 1120
            spaces(self.writer, self.curr_indent)?;
            write!(self.writer, "}}")?;
1121
        }
1122
        Ok(())
1123
    }
1124

M
Mark Rousskov 已提交
1125 1126
    fn emit_map_elt_key<F>(&mut self, idx: usize, f: F) -> EncodeResult
    where
1127
        F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
1128
    {
M
Mark Rousskov 已提交
1129 1130 1131
        if self.is_emitting_map_key {
            return Err(EncoderError::BadHashmapKey);
        }
1132
        if idx == 0 {
1133
            writeln!(self.writer)?;
1134
        } else {
1135
            writeln!(self.writer, ",")?;
1136
        }
J
Jorge Aparicio 已提交
1137
        spaces(self.writer, self.curr_indent)?;
1138
        self.is_emitting_map_key = true;
J
Jorge Aparicio 已提交
1139
        f(self)?;
1140
        self.is_emitting_map_key = false;
S
Sean McArthur 已提交
1141
        Ok(())
1142 1143
    }

M
Mark Rousskov 已提交
1144 1145
    fn emit_map_elt_val<F>(&mut self, _idx: usize, f: F) -> EncodeResult
    where
1146 1147
        F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
    {
M
Mark Rousskov 已提交
1148 1149 1150
        if self.is_emitting_map_key {
            return Err(EncoderError::BadHashmapKey);
        }
J
Jorge Aparicio 已提交
1151
        write!(self.writer, ": ")?;
S
Sean McArthur 已提交
1152
        f(self)
1153 1154 1155
    }
}

1156
impl Encodable for Json {
1157
    fn encode<E: crate::Encoder>(&self, e: &mut E) -> Result<(), E::Error> {
1158
        match *self {
1159 1160 1161 1162 1163 1164 1165
            Json::I64(v) => v.encode(e),
            Json::U64(v) => v.encode(e),
            Json::F64(v) => v.encode(e),
            Json::String(ref v) => v.encode(e),
            Json::Boolean(v) => v.encode(e),
            Json::Array(ref v) => v.encode(e),
            Json::Object(ref v) => v.encode(e),
K
kenta7777 已提交
1166
            Json::Null => e.emit_unit(),
1167 1168 1169 1170
        }
    }
}

A
Alexander Regueiro 已提交
1171
/// Creates an `AsJson` wrapper which can be used to print a value as JSON
1172
/// on-the-fly via `write!`
1173
pub fn as_json<T>(t: &T) -> AsJson<'_, T> {
1174 1175
    AsJson { inner: t }
}
1176

A
Alexander Regueiro 已提交
1177
/// Creates an `AsPrettyJson` wrapper which can be used to print a value as JSON
1178
/// on-the-fly via `write!`
1179
pub fn as_pretty_json<T>(t: &T) -> AsPrettyJson<'_, T> {
1180 1181
    AsPrettyJson { inner: t, indent: None }
}
1182

1183 1184
impl Json {
    /// Borrow this json object as a pretty object to generate a pretty
1185
    /// representation for it via `Display`.
1186
    pub fn pretty(&self) -> PrettyJson<'_> {
1187
        PrettyJson { inner: self }
1188
    }
1189

M
Mark Rousskov 已提交
1190
    /// If the Json value is an Object, returns the value associated with the provided key.
1191
    /// Otherwise, returns None.
J
Jeremy Stucki 已提交
1192
    pub fn find(&self, key: &str) -> Option<&Json> {
1193 1194
        match *self {
            Json::Object(ref map) => map.get(key),
M
Mark Rousskov 已提交
1195
            _ => None,
1196 1197 1198
        }
    }

1199
    /// Attempts to get a nested Json Object for each key in `keys`.
A
Alexander Regueiro 已提交
1200
    /// If any key is found not to exist, `find_path` will return `None`.
1201
    /// Otherwise, it will return the Json value associated with the final key.
M
Mark Rousskov 已提交
1202
    pub fn find_path<'a>(&'a self, keys: &[&str]) -> Option<&'a Json> {
1203
        let mut target = self;
1204
        for key in keys {
1205
            target = target.find(*key)?;
1206 1207
        }
        Some(target)
1208 1209 1210 1211
    }

    /// If the Json value is an Object, performs a depth-first search until
    /// a value associated with the provided key is found. If no value is found
A
Alexander Regueiro 已提交
1212
    /// or the Json value is not an Object, returns `None`.
J
Jeremy Stucki 已提交
1213
    pub fn search(&self, key: &str) -> Option<&Json> {
Y
Yuki Okushi 已提交
1214
        match *self {
M
Mark Rousskov 已提交
1215 1216 1217 1218 1219 1220 1221
            Json::Object(ref map) => match map.get(key) {
                Some(json_value) => Some(json_value),
                None => {
                    for v in map.values() {
                        match v.search(key) {
                            x if x.is_some() => return x,
                            _ => (),
1222 1223
                        }
                    }
M
Mark Rousskov 已提交
1224
                    None
1225 1226
                }
            },
M
Mark Rousskov 已提交
1227
            _ => None,
1228 1229 1230
        }
    }

A
Alexander Regueiro 已提交
1231
    /// Returns `true` if the Json value is an `Object`.
1232
    pub fn is_object(&self) -> bool {
1233
        self.as_object().is_some()
1234 1235
    }

A
Alexander Regueiro 已提交
1236 1237
    /// If the Json value is an `Object`, returns the associated `BTreeMap`;
    /// returns `None` otherwise.
1238 1239 1240
    pub fn as_object(&self) -> Option<&Object> {
        match *self {
            Json::Object(ref map) => Some(map),
M
Mark Rousskov 已提交
1241
            _ => None,
1242 1243 1244
        }
    }

A
Alexander Regueiro 已提交
1245
    /// Returns `true` if the Json value is an `Array`.
1246
    pub fn is_array(&self) -> bool {
C
Corey Farwell 已提交
1247
        self.as_array().is_some()
1248 1249
    }

A
Alexander Regueiro 已提交
1250 1251
    /// If the Json value is an `Array`, returns the associated vector;
    /// returns `None` otherwise.
1252 1253 1254
    pub fn as_array(&self) -> Option<&Array> {
        match *self {
            Json::Array(ref array) => Some(&*array),
M
Mark Rousskov 已提交
1255
            _ => None,
1256 1257 1258
        }
    }

A
Alexander Regueiro 已提交
1259
    /// Returns `true` if the Json value is a `String`.
1260
    pub fn is_string(&self) -> bool {
1261
        self.as_string().is_some()
1262 1263
    }

A
Alexander Regueiro 已提交
1264 1265
    /// If the Json value is a `String`, returns the associated `str`;
    /// returns `None` otherwise.
1266
    pub fn as_string(&self) -> Option<&str> {
1267
        match *self {
1268
            Json::String(ref s) => Some(&s[..]),
M
Mark Rousskov 已提交
1269
            _ => None,
1270 1271 1272
        }
    }

A
Alexander Regueiro 已提交
1273
    /// Returns `true` if the Json value is a `Number`.
1274
    pub fn is_number(&self) -> bool {
1275
        match *self {
1276
            Json::I64(_) | Json::U64(_) | Json::F64(_) => true,
1277 1278 1279 1280
            _ => false,
        }
    }

A
Alexander Regueiro 已提交
1281
    /// Returns `true` if the Json value is a `i64`.
1282 1283
    pub fn is_i64(&self) -> bool {
        match *self {
1284
            Json::I64(_) => true,
1285 1286 1287 1288
            _ => false,
        }
    }

A
Alexander Regueiro 已提交
1289
    /// Returns `true` if the Json value is a `u64`.
1290 1291
    pub fn is_u64(&self) -> bool {
        match *self {
1292
            Json::U64(_) => true,
1293 1294
            _ => false,
        }
1295 1296
    }

A
Alexander Regueiro 已提交
1297
    /// Returns `true` if the Json value is a `f64`.
1298 1299
    pub fn is_f64(&self) -> bool {
        match *self {
1300
            Json::F64(_) => true,
1301 1302 1303 1304
            _ => false,
        }
    }

A
Alexander Regueiro 已提交
1305 1306
    /// If the Json value is a number, returns or cast it to a `i64`;
    /// returns `None` otherwise.
1307 1308
    pub fn as_i64(&self) -> Option<i64> {
        match *self {
1309
            Json::I64(n) => Some(n),
1310
            Json::U64(n) => Some(n as i64),
M
Mark Rousskov 已提交
1311
            _ => None,
1312 1313 1314
        }
    }

A
Alexander Regueiro 已提交
1315 1316
    /// If the Json value is a number, returns or cast it to a `u64`;
    /// returns `None` otherwise.
1317 1318
    pub fn as_u64(&self) -> Option<u64> {
        match *self {
1319
            Json::I64(n) => Some(n as u64),
1320
            Json::U64(n) => Some(n),
M
Mark Rousskov 已提交
1321
            _ => None,
1322 1323 1324
        }
    }

A
Alexander Regueiro 已提交
1325 1326
    /// If the Json value is a number, returns or cast it to a `f64`;
    /// returns `None` otherwise.
1327 1328
    pub fn as_f64(&self) -> Option<f64> {
        match *self {
1329 1330
            Json::I64(n) => Some(n as f64),
            Json::U64(n) => Some(n as f64),
1331
            Json::F64(n) => Some(n),
M
Mark Rousskov 已提交
1332
            _ => None,
1333 1334 1335
        }
    }

A
Alexander Regueiro 已提交
1336
    /// Returns `true` if the Json value is a `Boolean`.
1337
    pub fn is_boolean(&self) -> bool {
1338
        self.as_boolean().is_some()
1339 1340
    }

A
Alexander Regueiro 已提交
1341 1342
    /// If the Json value is a `Boolean`, returns the associated `bool`;
    /// returns `None` otherwise.
1343
    pub fn as_boolean(&self) -> Option<bool> {
1344 1345
        match *self {
            Json::Boolean(b) => Some(b),
M
Mark Rousskov 已提交
1346
            _ => None,
1347 1348 1349
        }
    }

A
Alexander Regueiro 已提交
1350
    /// Returns `true` if the Json value is a `Null`.
1351
    pub fn is_null(&self) -> bool {
1352
        self.as_null().is_some()
1353 1354
    }

A
Alexander Regueiro 已提交
1355 1356
    /// If the Json value is a `Null`, returns `()`;
    /// returns `None` otherwise.
1357
    pub fn as_null(&self) -> Option<()> {
1358 1359
        match *self {
            Json::Null => Some(()),
M
Mark Rousskov 已提交
1360
            _ => None,
1361 1362
        }
    }
E
Elly Jones 已提交
1363 1364
}

M
Mark Rousskov 已提交
1365
impl<'a> Index<&'a str> for Json {
1366 1367 1368 1369 1370 1371 1372
    type Output = Json;

    fn index(&self, idx: &'a str) -> &Json {
        self.find(idx).unwrap()
    }
}

1373
impl Index<usize> for Json {
1374 1375
    type Output = Json;

1376
    fn index(&self, idx: usize) -> &Json {
1377 1378
        match *self {
            Json::Array(ref v) => &v[idx],
M
Mark Rousskov 已提交
1379
            _ => panic!("can only index Json with usize if it is an array"),
1380 1381 1382 1383
        }
    }
}

1384
/// The output of the streaming parser.
J
Jorge Aparicio 已提交
1385
#[derive(PartialEq, Clone, Debug)]
1386 1387 1388
pub enum JsonEvent {
    ObjectStart,
    ObjectEnd,
C
Corey Farwell 已提交
1389 1390
    ArrayStart,
    ArrayEnd,
1391
    BooleanValue(bool),
1392 1393 1394
    I64Value(i64),
    U64Value(u64),
    F64Value(f64),
1395
    StringValue(string::String),
1396 1397 1398 1399
    NullValue,
    Error(ParserError),
}

J
Jorge Aparicio 已提交
1400
#[derive(PartialEq, Debug)]
1401
enum ParserState {
C
Corey Farwell 已提交
1402
    // Parse a value in an array, true means first element.
1403
    ParseArray(bool),
C
Corey Farwell 已提交
1404
    // Parse ',' or ']' after an element in an array.
C
Corey Farwell 已提交
1405
    ParseArrayComma,
1406 1407 1408 1409
    // Parse a key:value in an object, true means first element.
    ParseObject(bool),
    // Parse ',' or ']' after an element in an object.
    ParseObjectComma,
J
Joseph Crail 已提交
1410
    // Initial state.
1411 1412 1413 1414 1415 1416 1417 1418 1419
    ParseStart,
    // Expecting the stream to end.
    ParseBeforeFinish,
    // Parsing can't continue.
    ParseFinished,
}

/// A Stack represents the current position of the parser in the logical
/// structure of the JSON stream.
1420 1421
///
/// An example is `foo.bar[3].x`.
1422 1423 1424 1425 1426 1427
pub struct Stack {
    stack: Vec<InternalStackElement>,
    str_buffer: Vec<u8>,
}

/// StackElements compose a Stack.
1428 1429 1430
///
/// As an example, `StackElement::Key("foo")`, `StackElement::Key("bar")`,
/// `StackElement::Index(3)`, and `StackElement::Key("x")` are the
1431
/// StackElements composing the stack that represents `foo.bar[3].x`.
J
Jorge Aparicio 已提交
1432
#[derive(PartialEq, Clone, Debug)]
1433 1434 1435 1436 1437 1438 1439
pub enum StackElement<'l> {
    Index(u32),
    Key(&'l str),
}

// Internally, Key elements are stored as indices in a buffer to avoid
// allocating a string for every member of an object.
J
Jorge Aparicio 已提交
1440
#[derive(PartialEq, Clone, Debug)]
1441 1442 1443 1444 1445 1446 1447
enum InternalStackElement {
    InternalIndex(u32),
    InternalKey(u16, u16), // start, size
}

impl Stack {
    pub fn new() -> Stack {
A
Adolfo Ochagavía 已提交
1448
        Stack { stack: Vec::new(), str_buffer: Vec::new() }
1449 1450 1451
    }

    /// Returns The number of elements in the Stack.
M
Mark Rousskov 已提交
1452 1453 1454
    pub fn len(&self) -> usize {
        self.stack.len()
    }
1455

A
Alexander Regueiro 已提交
1456
    /// Returns `true` if the stack is empty.
M
Mark Rousskov 已提交
1457 1458 1459
    pub fn is_empty(&self) -> bool {
        self.stack.is_empty()
    }
1460 1461 1462 1463

    /// Provides access to the StackElement at a given index.
    /// lower indices are at the bottom of the stack while higher indices are
    /// at the top.
1464
    pub fn get(&self, idx: usize) -> StackElement<'_> {
N
Nick Cameron 已提交
1465
        match self.stack[idx] {
1466
            InternalIndex(i) => StackElement::Index(i),
M
Mark Rousskov 已提交
1467 1468 1469 1470
            InternalKey(start, size) => StackElement::Key(
                str::from_utf8(&self.str_buffer[start as usize..start as usize + size as usize])
                    .unwrap(),
            ),
1471 1472 1473
        }
    }

1474 1475
    /// Compares this stack with an array of StackElement<'_>s.
    pub fn is_equal_to(&self, rhs: &[StackElement<'_>]) -> bool {
M
Mark Rousskov 已提交
1476 1477 1478
        if self.stack.len() != rhs.len() {
            return false;
        }
1479
        for (i, r) in rhs.iter().enumerate() {
M
Mark Rousskov 已提交
1480 1481 1482
            if self.get(i) != *r {
                return false;
            }
1483
        }
1484
        true
1485 1486
    }

A
Alexander Regueiro 已提交
1487
    /// Returns `true` if the bottom-most elements of this stack are the same as
1488
    /// the ones passed as parameter.
1489
    pub fn starts_with(&self, rhs: &[StackElement<'_>]) -> bool {
M
Mark Rousskov 已提交
1490 1491 1492
        if self.stack.len() < rhs.len() {
            return false;
        }
1493
        for (i, r) in rhs.iter().enumerate() {
M
Mark Rousskov 已提交
1494 1495 1496
            if self.get(i) != *r {
                return false;
            }
1497
        }
1498
        true
1499 1500
    }

A
Alexander Regueiro 已提交
1501
    /// Returns `true` if the top-most elements of this stack are the same as
1502
    /// the ones passed as parameter.
1503
    pub fn ends_with(&self, rhs: &[StackElement<'_>]) -> bool {
M
Mark Rousskov 已提交
1504 1505 1506
        if self.stack.len() < rhs.len() {
            return false;
        }
1507
        let offset = self.stack.len() - rhs.len();
1508
        for (i, r) in rhs.iter().enumerate() {
M
Mark Rousskov 已提交
1509 1510 1511
            if self.get(i + offset) != *r {
                return false;
            }
1512
        }
1513
        true
1514 1515 1516
    }

    /// Returns the top-most element (if any).
1517
    pub fn top(&self) -> Option<StackElement<'_>> {
1518
        match self.stack.last() {
1519
            None => None,
1520
            Some(&InternalIndex(i)) => Some(StackElement::Index(i)),
M
Mark Rousskov 已提交
1521 1522 1523
            Some(&InternalKey(start, size)) => Some(StackElement::Key(
                str::from_utf8(&self.str_buffer[start as usize..(start + size) as usize]).unwrap(),
            )),
1524 1525 1526
        }
    }

1527
    // Used by Parser to insert StackElement::Key elements at the top of the stack.
1528
    fn push_key(&mut self, key: string::String) {
1529
        self.stack.push(InternalKey(self.str_buffer.len() as u16, key.len() as u16));
1530
        self.str_buffer.extend(key.as_bytes());
1531 1532
    }

1533
    // Used by Parser to insert StackElement::Index elements at the top of the stack.
1534 1535 1536 1537 1538 1539 1540 1541 1542
    fn push_index(&mut self, index: u32) {
        self.stack.push(InternalIndex(index));
    }

    // Used by Parser to remove the top-most element of the stack.
    fn pop(&mut self) {
        assert!(!self.is_empty());
        match *self.stack.last().unwrap() {
            InternalKey(_, sz) => {
1543
                let new_size = self.str_buffer.len() - sz as usize;
A
Adolfo Ochagavía 已提交
1544
                self.str_buffer.truncate(new_size);
1545 1546 1547 1548 1549 1550 1551 1552
            }
            InternalIndex(_) => {}
        }
        self.stack.pop();
    }

    // Used by Parser to test whether the top-most element is an index.
    fn last_is_index(&self) -> bool {
A
Andre Bogus 已提交
1553 1554 1555
        match self.stack.last() {
            Some(InternalIndex(_)) => true,
            _ => false,
1556 1557 1558 1559 1560 1561 1562
        }
    }

    // Used by Parser to increment the index of the top-most element.
    fn bump_index(&mut self) {
        let len = self.stack.len();
        let idx = match *self.stack.last().unwrap() {
M
Mark Rousskov 已提交
1563 1564 1565 1566
            InternalIndex(i) => i + 1,
            _ => {
                panic!();
            }
1567
        };
1568
        self.stack[len - 1] = InternalIndex(idx);
1569 1570 1571 1572 1573
    }
}

/// A streaming JSON parser implemented as an iterator of JsonEvent, consuming
/// an iterator of char.
G
Gary Linscott 已提交
1574
pub struct Parser<T> {
1575 1576
    rdr: T,
    ch: Option<char>,
1577 1578
    line: usize,
    col: usize,
1579 1580 1581
    // We maintain a stack representing where we are in the logical structure
    // of the JSON stream.
    stack: Stack,
J
Joseph Crail 已提交
1582
    // A state machine is kept to make it possible to interrupt and resume parsing.
1583 1584 1585
    state: ParserState,
}

M
Mark Rousskov 已提交
1586
impl<T: Iterator<Item = char>> Iterator for Parser<T> {
J
Jorge Aparicio 已提交
1587 1588
    type Item = JsonEvent;

1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604
    fn next(&mut self) -> Option<JsonEvent> {
        if self.state == ParseFinished {
            return None;
        }

        if self.state == ParseBeforeFinish {
            self.parse_whitespace();
            // Make sure there is no trailing characters.
            if self.eof() {
                self.state = ParseFinished;
                return None;
            } else {
                return Some(self.error_event(TrailingCharacters));
            }
        }

1605
        Some(self.parse())
1606
    }
1607 1608
}

M
Mark Rousskov 已提交
1609
impl<T: Iterator<Item = char>> Parser<T> {
1610
    /// Creates the JSON parser.
1611
    pub fn new(rdr: T) -> Parser<T> {
1612
        let mut p = Parser {
1613
            rdr,
1614
            ch: Some('\x00'),
1615 1616
            line: 1,
            col: 0,
1617 1618
            stack: Stack::new(),
            state: ParseStart,
1619 1620
        };
        p.bump();
1621
        p
1622
    }
E
Elly Jones 已提交
1623

1624 1625
    /// Provides access to the current position in the logical structure of the
    /// JSON stream.
1626
    pub fn stack(&self) -> &Stack {
1627
        &self.stack
1628
    }
1629

M
Mark Rousskov 已提交
1630 1631 1632 1633 1634 1635
    fn eof(&self) -> bool {
        self.ch.is_none()
    }
    fn ch_or_null(&self) -> char {
        self.ch.unwrap_or('\x00')
    }
1636
    fn bump(&mut self) {
1637
        self.ch = self.rdr.next();
E
Elly Jones 已提交
1638

1639
        if self.ch_is('\n') {
A
Alfie John 已提交
1640 1641
            self.line += 1;
            self.col = 1;
G
Gary Linscott 已提交
1642
        } else {
A
Alfie John 已提交
1643
            self.col += 1;
E
Elly Jones 已提交
1644
        }
1645 1646
    }

1647
    fn next_char(&mut self) -> Option<char> {
1648 1649 1650
        self.bump();
        self.ch
    }
1651 1652 1653
    fn ch_is(&self, c: char) -> bool {
        self.ch == Some(c)
    }
1654

1655
    fn error<U>(&self, reason: ErrorCode) -> Result<U, ParserError> {
1656
        Err(SyntaxError(reason, self.line, self.col))
1657 1658
    }

1659
    fn parse_whitespace(&mut self) {
M
Mark Rousskov 已提交
1660 1661 1662
        while self.ch_is(' ') || self.ch_is('\n') || self.ch_is('\t') || self.ch_is('\r') {
            self.bump();
        }
1663 1664
    }

1665
    fn parse_number(&mut self) -> JsonEvent {
Y
Yuki Okushi 已提交
1666
        let neg = if self.ch_is('-') {
1667
            self.bump();
Y
Yuki Okushi 已提交
1668 1669 1670 1671
            true
        } else {
            false
        };
1672

1673
        let res = match self.parse_u64() {
1674
            Ok(res) => res,
M
Mark Rousskov 已提交
1675 1676 1677
            Err(e) => {
                return Error(e);
            }
1678
        };
1679

1680 1681
        if self.ch_is('.') || self.ch_is('e') || self.ch_is('E') {
            let mut res = res as f64;
1682

1683 1684 1685
            if self.ch_is('.') {
                res = match self.parse_decimal(res) {
                    Ok(res) => res,
M
Mark Rousskov 已提交
1686 1687 1688
                    Err(e) => {
                        return Error(e);
                    }
1689 1690
                };
            }
1691

1692 1693 1694
            if self.ch_is('e') || self.ch_is('E') {
                res = match self.parse_exponent(res) {
                    Ok(res) => res,
M
Mark Rousskov 已提交
1695 1696 1697
                    Err(e) => {
                        return Error(e);
                    }
1698 1699 1700
                };
            }

1701 1702 1703 1704 1705
            if neg {
                res *= -1.0;
            }

            F64Value(res)
1706 1707
        } else if neg {
            let res = (res as i64).wrapping_neg();
1708

1709 1710 1711
            // Make sure we didn't underflow.
            if res > 0 {
                Error(SyntaxError(InvalidNumber, self.line, self.col))
1712
            } else {
1713
                I64Value(res)
1714
            }
1715 1716
        } else {
            U64Value(res)
1717
        }
E
Elly Jones 已提交
1718 1719
    }

1720
    fn parse_u64(&mut self) -> Result<u64, ParserError> {
1721
        let mut accum = 0u64;
1722
        let last_accum = 0; // necessary to detect overflow.
E
Elly Jones 已提交
1723

1724 1725 1726
        match self.ch_or_null() {
            '0' => {
                self.bump();
1727

M
mrec 已提交
1728
                // A leading '0' must be the only digit before the decimal point.
M
Mark Rousskov 已提交
1729 1730
                if let '0'..='9' = self.ch_or_null() {
                    return self.error(InvalidNumber);
1731
                }
M
Mark Rousskov 已提交
1732 1733
            }
            '1'..='9' => {
1734 1735
                while !self.eof() {
                    match self.ch_or_null() {
M
Mark Rousskov 已提交
1736
                        c @ '0'..='9' => {
1737 1738
                            accum = accum.wrapping_mul(10);
                            accum = accum.wrapping_add((c as u64) - ('0' as u64));
1739 1740

                            // Detect overflow by comparing to the last value.
M
Mark Rousskov 已提交
1741 1742 1743
                            if accum <= last_accum {
                                return self.error(InvalidNumber);
                            }
1744

1745 1746 1747 1748
                            self.bump();
                        }
                        _ => break,
                    }
1749 1750
                }
            }
1751
            _ => return self.error(InvalidNumber),
E
Elly Jones 已提交
1752
        }
1753 1754

        Ok(accum)
E
Elly Jones 已提交
1755 1756
    }

A
Adolfo Ochagavía 已提交
1757
    fn parse_decimal(&mut self, mut res: f64) -> Result<f64, ParserError> {
1758 1759 1760
        self.bump();

        // Make sure a digit follows the decimal place.
1761
        match self.ch_or_null() {
M
Mark Rousskov 已提交
1762 1763
            '0'..='9' => (),
            _ => return self.error(InvalidNumber),
1764 1765
        }

D
Daniel Micay 已提交
1766
        let mut dec = 1.0;
1767
        while !self.eof() {
1768
            match self.ch_or_null() {
M
Mark Rousskov 已提交
1769
                c @ '0'..='9' => {
1770
                    dec /= 10.0;
1771
                    res += (((c as isize) - ('0' as isize)) as f64) * dec;
1772 1773 1774
                    self.bump();
                }
                _ => break,
E
Elly Jones 已提交
1775 1776
            }
        }
1777

1778
        Ok(res)
E
Elly Jones 已提交
1779 1780
    }

1781
    fn parse_exponent(&mut self, mut res: f64) -> Result<f64, ParserError> {
1782 1783
        self.bump();

A
Alfie John 已提交
1784
        let mut exp = 0;
1785
        let mut neg_exp = false;
1786

1787 1788 1789 1790 1791
        if self.ch_is('+') {
            self.bump();
        } else if self.ch_is('-') {
            self.bump();
            neg_exp = true;
1792 1793 1794
        }

        // Make sure a digit follows the exponent place.
1795
        match self.ch_or_null() {
M
Mark Rousskov 已提交
1796 1797
            '0'..='9' => (),
            _ => return self.error(InvalidNumber),
1798 1799
        }
        while !self.eof() {
1800
            match self.ch_or_null() {
M
Mark Rousskov 已提交
1801
                c @ '0'..='9' => {
1802
                    exp *= 10;
1803
                    exp += (c as usize) - ('0' as usize);
1804

1805 1806
                    self.bump();
                }
M
Mark Rousskov 已提交
1807
                _ => break,
1808 1809 1810
            }
        }

1811
        let exp = 10_f64.powi(exp as i32);
1812 1813 1814 1815 1816 1817
        if neg_exp {
            res /= exp;
        } else {
            res *= exp;
        }

1818
        Ok(res)
E
Elly Jones 已提交
1819 1820
    }

1821
    fn decode_hex_escape(&mut self) -> Result<u16, ParserError> {
A
Alfie John 已提交
1822
        let mut i = 0;
1823
        let mut n = 0;
A
Adolfo Ochagavía 已提交
1824
        while i < 4 && !self.eof() {
1825 1826
            self.bump();
            n = match self.ch_or_null() {
M
Mark Rousskov 已提交
1827
                c @ '0'..='9' => n * 16 + ((c as u16) - ('0' as u16)),
A
Adolfo Ochagavía 已提交
1828 1829 1830 1831 1832 1833
                'a' | 'A' => n * 16 + 10,
                'b' | 'B' => n * 16 + 11,
                'c' | 'C' => n * 16 + 12,
                'd' | 'D' => n * 16 + 13,
                'e' | 'E' => n * 16 + 14,
                'f' | 'F' => n * 16 + 15,
M
Mark Rousskov 已提交
1834
                _ => return self.error(InvalidEscape),
1835 1836
            };

A
Alfie John 已提交
1837
            i += 1;
1838 1839 1840
        }

        // Error out if we didn't parse 4 digits.
A
Adolfo Ochagavía 已提交
1841
        if i != 4 {
1842
            return self.error(InvalidEscape);
1843 1844 1845 1846 1847
        }

        Ok(n)
    }

1848
    fn parse_str(&mut self) -> Result<string::String, ParserError> {
1849
        let mut escape = false;
1850
        let mut res = string::String::new();
1851

G
Gary Linscott 已提交
1852
        loop {
1853
            self.bump();
G
Gary Linscott 已提交
1854
            if self.eof() {
1855
                return self.error(EOFWhileParsingString);
G
Gary Linscott 已提交
1856
            }
1857

H
Huon Wilson 已提交
1858
            if escape {
1859
                match self.ch_or_null() {
1860 1861 1862 1863 1864 1865 1866 1867
                    '"' => res.push('"'),
                    '\\' => res.push('\\'),
                    '/' => res.push('/'),
                    'b' => res.push('\x08'),
                    'f' => res.push('\x0c'),
                    'n' => res.push('\n'),
                    'r' => res.push('\r'),
                    't' => res.push('\t'),
J
Jorge Aparicio 已提交
1868
                    'u' => match self.decode_hex_escape()? {
M
Mark Rousskov 已提交
1869
                        0xDC00..=0xDFFF => return self.error(LoneLeadingSurrogateInHexEscape),
1870 1871 1872

                        // Non-BMP characters are encoded as a sequence of
                        // two hex escapes, representing UTF-16 surrogates.
M
Mark Rousskov 已提交
1873
                        n1 @ 0xD800..=0xDBFF => {
A
Adolfo Ochagavía 已提交
1874
                            match (self.next_char(), self.next_char()) {
1875
                                (Some('\\'), Some('u')) => (),
1876
                                _ => return self.error(UnexpectedEndOfHexEscape),
1877
                            }
1878

J
Jorge Aparicio 已提交
1879
                            let n2 = self.decode_hex_escape()?;
1880
                            if n2 < 0xDC00 || n2 > 0xDFFF {
M
Mark Rousskov 已提交
1881
                                return self.error(LoneLeadingSurrogateInHexEscape);
1882
                            }
M
Mark Rousskov 已提交
1883 1884
                            let c =
                                (u32::from(n1 - 0xD800) << 10 | u32::from(n2 - 0xDC00)) + 0x1_0000;
1885
                            res.push(char::from_u32(c).unwrap());
1886 1887
                        }

I
Igor Matuszewski 已提交
1888
                        n => match char::from_u32(u32::from(n)) {
1889
                            Some(c) => res.push(c),
1890
                            None => return self.error(InvalidUnicodeCodePoint),
1891 1892
                        },
                    },
1893
                    _ => return self.error(InvalidEscape),
1894 1895
                }
                escape = false;
1896
            } else if self.ch_is('\\') {
1897 1898
                escape = true;
            } else {
1899
                match self.ch {
1900 1901
                    Some('"') => {
                        self.bump();
1902
                        return Ok(res);
M
Mark Rousskov 已提交
1903
                    }
1904
                    Some(c) => res.push(c),
M
Mark Rousskov 已提交
1905
                    None => unreachable!(),
1906
                }
E
Elly Jones 已提交
1907 1908 1909 1910
            }
        }
    }

1911 1912 1913 1914
    // Invoked at each iteration, consumes the stream until it has enough
    // information to return a JsonEvent.
    // Manages an internal state so that parsing can be interrupted and resumed.
    // Also keeps track of the position in the logical structure of the json
1915
    // stream isize the form of a stack that can be queried by the user using the
1916 1917 1918 1919
    // stack() method.
    fn parse(&mut self) -> JsonEvent {
        loop {
            // The only paths where the loop can spin a new iteration
C
Corey Farwell 已提交
1920
            // are in the cases ParseArrayComma and ParseObjectComma if ','
1921
            // is parsed. In these cases the state is set to (respectively)
1922
            // ParseArray(false) and ParseObject(false), which always return,
1923 1924 1925
            // so there is no risk of getting stuck in an infinite loop.
            // All other paths return before the end of the loop's iteration.
            self.parse_whitespace();
1926

1927 1928 1929 1930
            match self.state {
                ParseStart => {
                    return self.parse_start();
                }
1931
                ParseArray(first) => {
C
Corey Farwell 已提交
1932
                    return self.parse_array(first);
1933
                }
C
Corey Farwell 已提交
1934
                ParseArrayComma => {
1935 1936
                    if let Some(evt) = self.parse_array_comma_or_end() {
                        return evt;
1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960
                    }
                }
                ParseObject(first) => {
                    return self.parse_object(first);
                }
                ParseObjectComma => {
                    self.stack.pop();
                    if self.ch_is(',') {
                        self.state = ParseObject(false);
                        self.bump();
                    } else {
                        return self.parse_object_end();
                    }
                }
                _ => {
                    return self.error_event(InvalidSyntax);
                }
            }
        }
    }

    fn parse_start(&mut self) -> JsonEvent {
        let val = self.parse_value();
        self.state = match val {
1961 1962 1963 1964
            Error(_) => ParseFinished,
            ArrayStart => ParseArray(true),
            ObjectStart => ParseObject(true),
            _ => ParseBeforeFinish,
1965
        };
1966
        val
1967
    }
1968

C
Corey Farwell 已提交
1969
    fn parse_array(&mut self, first: bool) -> JsonEvent {
1970
        if self.ch_is(']') {
1971
            if !first {
1972
                self.error_event(InvalidSyntax)
1973
            } else {
1974 1975 1976
                self.state = if self.stack.is_empty() {
                    ParseBeforeFinish
                } else if self.stack.last_is_index() {
C
Corey Farwell 已提交
1977
                    ParseArrayComma
1978 1979
                } else {
                    ParseObjectComma
1980 1981 1982
                };
                self.bump();
                ArrayEnd
1983
            }
1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995
        } else {
            if first {
                self.stack.push_index(0);
            }
            let val = self.parse_value();
            self.state = match val {
                Error(_) => ParseFinished,
                ArrayStart => ParseArray(true),
                ObjectStart => ParseObject(true),
                _ => ParseArrayComma,
            };
            val
1996
        }
1997
    }
1998

C
Corey Farwell 已提交
1999
    fn parse_array_comma_or_end(&mut self) -> Option<JsonEvent> {
2000 2001
        if self.ch_is(',') {
            self.stack.bump_index();
2002
            self.state = ParseArray(false);
2003
            self.bump();
2004
            None
2005 2006
        } else if self.ch_is(']') {
            self.stack.pop();
2007 2008 2009 2010
            self.state = if self.stack.is_empty() {
                ParseBeforeFinish
            } else if self.stack.last_is_index() {
                ParseArrayComma
2011
            } else {
2012 2013
                ParseObjectComma
            };
2014
            self.bump();
2015
            Some(ArrayEnd)
2016
        } else if self.eof() {
2017
            Some(self.error_event(EOFWhileParsingArray))
2018
        } else {
2019
            Some(self.error_event(InvalidSyntax))
2020
        }
E
Elly Jones 已提交
2021 2022
    }

2023 2024 2025
    fn parse_object(&mut self, first: bool) -> JsonEvent {
        if self.ch_is('}') {
            if !first {
2026 2027 2028 2029 2030
                if self.stack.is_empty() {
                    return self.error_event(TrailingComma);
                } else {
                    self.stack.pop();
                }
2031
            }
2032 2033 2034 2035
            self.state = if self.stack.is_empty() {
                ParseBeforeFinish
            } else if self.stack.last_is_index() {
                ParseArrayComma
2036
            } else {
2037 2038
                ParseObjectComma
            };
2039 2040 2041 2042 2043 2044 2045 2046 2047 2048
            self.bump();
            return ObjectEnd;
        }
        if self.eof() {
            return self.error_event(EOFWhileParsingObject);
        }
        if !self.ch_is('"') {
            return self.error_event(KeyMustBeAString);
        }
        let s = match self.parse_str() {
2049
            Ok(s) => s,
2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061
            Err(e) => {
                self.state = ParseFinished;
                return Error(e);
            }
        };
        self.parse_whitespace();
        if self.eof() {
            return self.error_event(EOFWhileParsingObject);
        } else if self.ch_or_null() != ':' {
            return self.error_event(ExpectedColon);
        }
        self.stack.push_key(s);
2062 2063 2064
        self.bump();
        self.parse_whitespace();

2065
        let val = self.parse_value();
2066

2067
        self.state = match val {
2068 2069 2070 2071
            Error(_) => ParseFinished,
            ArrayStart => ParseArray(true),
            ObjectStart => ParseObject(true),
            _ => ParseObjectComma,
2072
        };
2073
        val
2074 2075 2076
    }

    fn parse_object_end(&mut self) -> JsonEvent {
2077
        if self.ch_is('}') {
2078 2079 2080 2081
            self.state = if self.stack.is_empty() {
                ParseBeforeFinish
            } else if self.stack.last_is_index() {
                ParseArrayComma
2082
            } else {
2083 2084
                ParseObjectComma
            };
2085
            self.bump();
A
Adolfo Ochagavía 已提交
2086
            ObjectEnd
2087
        } else if self.eof() {
A
Adolfo Ochagavía 已提交
2088
            self.error_event(EOFWhileParsingObject)
2089
        } else {
A
Adolfo Ochagavía 已提交
2090
            self.error_event(InvalidSyntax)
2091
        }
2092
    }
2093

2094
    fn parse_value(&mut self) -> JsonEvent {
M
Mark Rousskov 已提交
2095 2096 2097
        if self.eof() {
            return self.error_event(EOFWhileParsingValue);
        }
2098
        match self.ch_or_null() {
M
Mark Rousskov 已提交
2099 2100 2101 2102
            'n' => self.parse_ident("ull", NullValue),
            't' => self.parse_ident("rue", BooleanValue(true)),
            'f' => self.parse_ident("alse", BooleanValue(false)),
            '0'..='9' | '-' => self.parse_number(),
A
Adolfo Ochagavía 已提交
2103
            '"' => match self.parse_str() {
2104 2105 2106 2107 2108
                Ok(s) => StringValue(s),
                Err(e) => Error(e),
            },
            '[' => {
                self.bump();
C
Corey Farwell 已提交
2109
                ArrayStart
2110 2111 2112
            }
            '{' => {
                self.bump();
A
Adolfo Ochagavía 已提交
2113
                ObjectStart
2114
            }
M
Mark Rousskov 已提交
2115
            _ => self.error_event(InvalidSyntax),
2116 2117
        }
    }
2118

2119 2120 2121 2122 2123 2124 2125 2126
    fn parse_ident(&mut self, ident: &str, value: JsonEvent) -> JsonEvent {
        if ident.chars().all(|c| Some(c) == self.next_char()) {
            self.bump();
            value
        } else {
            Error(SyntaxError(InvalidSyntax, self.line, self.col))
        }
    }
2127

2128 2129 2130 2131 2132
    fn error_event(&mut self, reason: ErrorCode) -> JsonEvent {
        self.state = ParseFinished;
        Error(SyntaxError(reason, self.line, self.col))
    }
}
2133

2134 2135 2136 2137 2138
/// A Builder consumes a json::Parser to create a generic Json structure.
pub struct Builder<T> {
    parser: Parser<T>,
    token: Option<JsonEvent>,
}
2139

M
Mark Rousskov 已提交
2140
impl<T: Iterator<Item = char>> Builder<T> {
A
Alexander Regueiro 已提交
2141
    /// Creates a JSON Builder.
2142
    pub fn new(src: T) -> Builder<T> {
M
Mark Rousskov 已提交
2143
        Builder { parser: Parser::new(src), token: None }
2144 2145 2146 2147 2148 2149 2150 2151 2152
    }

    // Decode a Json value from a Parser.
    pub fn build(&mut self) -> Result<Json, BuilderError> {
        self.bump();
        let result = self.build_value();
        self.bump();
        match self.token {
            None => {}
M
Mark Rousskov 已提交
2153 2154 2155 2156 2157 2158
            Some(Error(ref e)) => {
                return Err(e.clone());
            }
            ref tok => {
                panic!("unexpected token {:?}", tok.clone());
            }
2159
        }
A
Adolfo Ochagavía 已提交
2160
        result
2161 2162 2163 2164 2165 2166 2167
    }

    fn bump(&mut self) {
        self.token = self.parser.next();
    }

    fn build_value(&mut self) -> Result<Json, BuilderError> {
2168
        match self.token {
2169 2170 2171 2172 2173
            Some(NullValue) => Ok(Json::Null),
            Some(I64Value(n)) => Ok(Json::I64(n)),
            Some(U64Value(n)) => Ok(Json::U64(n)),
            Some(F64Value(n)) => Ok(Json::F64(n)),
            Some(BooleanValue(b)) => Ok(Json::Boolean(b)),
2174
            Some(StringValue(ref mut s)) => {
2175
                let mut temp = string::String::new();
2176
                swap(s, &mut temp);
2177
                Ok(Json::String(temp))
2178
            }
2179
            Some(Error(ref e)) => Err(e.clone()),
2180 2181 2182 2183 2184
            Some(ArrayStart) => self.build_array(),
            Some(ObjectStart) => self.build_object(),
            Some(ObjectEnd) => self.parser.error(InvalidSyntax),
            Some(ArrayEnd) => self.parser.error(InvalidSyntax),
            None => self.parser.error(EOFWhileParsingValue),
2185 2186
        }
    }
2187

C
Corey Farwell 已提交
2188
    fn build_array(&mut self) -> Result<Json, BuilderError> {
2189 2190 2191 2192
        self.bump();
        let mut values = Vec::new();

        loop {
C
Corey Farwell 已提交
2193
            if self.token == Some(ArrayEnd) {
2194
                return Ok(Json::Array(values.into_iter().collect()));
2195 2196 2197
            }
            match self.build_value() {
                Ok(v) => values.push(v),
M
Mark Rousskov 已提交
2198
                Err(e) => return Err(e),
2199
            }
2200
            self.bump();
2201
        }
2202
    }
2203

2204 2205 2206
    fn build_object(&mut self) -> Result<Json, BuilderError> {
        self.bump();

A
Alexis Beingessner 已提交
2207
        let mut values = BTreeMap::new();
2208

A
Adolfo Ochagavía 已提交
2209
        loop {
2210
            match self.token {
M
Mark Rousskov 已提交
2211 2212 2213 2214 2215 2216 2217 2218 2219
                Some(ObjectEnd) => {
                    return Ok(Json::Object(values));
                }
                Some(Error(ref e)) => {
                    return Err(e.clone());
                }
                None => {
                    break;
                }
2220 2221 2222
                _ => {}
            }
            let key = match self.parser.stack().top() {
M
Mark Rousskov 已提交
2223 2224 2225 2226
                Some(StackElement::Key(k)) => k.to_owned(),
                _ => {
                    panic!("invalid state");
                }
2227 2228
            };
            match self.build_value() {
M
Mark Rousskov 已提交
2229 2230 2231 2232 2233 2234
                Ok(value) => {
                    values.insert(key, value);
                }
                Err(e) => {
                    return Err(e);
                }
2235 2236 2237
            }
            self.bump();
        }
2238
        self.parser.error(EOFWhileParsingObject)
L
Lenny222 已提交
2239 2240 2241
    }
}

2242
/// Decodes a json value from an `&mut io::Read`
2243
pub fn from_reader(rdr: &mut dyn Read) -> Result<Json, BuilderError> {
2244 2245
    let mut contents = Vec::new();
    match rdr.read_to_end(&mut contents) {
M
Mark Rousskov 已提交
2246 2247
        Ok(c) => c,
        Err(e) => return Err(io_error_to_error(e)),
A
Alex Crichton 已提交
2248
    };
2249
    let s = match str::from_utf8(&contents).ok() {
2250
        Some(s) => s,
M
Mark Rousskov 已提交
2251
        _ => return Err(SyntaxError(NotUtf8, 0, 0)),
A
Alex Crichton 已提交
2252
    };
2253
    let mut builder = Builder::new(s.chars());
2254
    builder.build()
E
Elly Jones 已提交
2255 2256
}

2257
/// Decodes a json value from a string
2258 2259
pub fn from_str(s: &str) -> Result<Json, BuilderError> {
    let mut builder = Builder::new(s.chars());
A
Adolfo Ochagavía 已提交
2260
    builder.build()
2261 2262
}

2263
/// A structure to decode JSON to values in rust.
2264
pub struct Decoder {
2265
    stack: Vec<Json>,
2266 2267
}

2268 2269
impl Decoder {
    /// Creates a new decoder instance for decoding the specified JSON value.
2270
    pub fn new(json: Json) -> Decoder {
A
Adolfo Ochagavía 已提交
2271
        Decoder { stack: vec![json] }
2272
    }
2273

S
Sean McArthur 已提交
2274 2275
    fn pop(&mut self) -> Json {
        self.stack.pop().unwrap()
2276 2277 2278
    }
}

2279
macro_rules! expect {
M
Mark Rousskov 已提交
2280
    ($e:expr, Null) => {{
S
Sean McArthur 已提交
2281
        match $e {
2282
            Json::Null => Ok(()),
M
Mark Rousskov 已提交
2283
            other => Err(ExpectedError("Null".to_owned(), other.to_string())),
S
Sean McArthur 已提交
2284
        }
M
Mark Rousskov 已提交
2285 2286
    }};
    ($e:expr, $t:ident) => {{
S
Sean McArthur 已提交
2287
        match $e {
2288
            Json::$t(v) => Ok(v),
M
Mark Rousskov 已提交
2289
            other => Err(ExpectedError(stringify!($t).to_owned(), other.to_string())),
2290
        }
M
Mark Rousskov 已提交
2291
    }};
2292
}
S
Sean McArthur 已提交
2293

2294 2295 2296 2297
macro_rules! read_primitive {
    ($name:ident, $ty:ty) => {
        fn $name(&mut self) -> DecodeResult<$ty> {
            match self.pop() {
2298 2299
                Json::I64(f) => Ok(f as $ty),
                Json::U64(f) => Ok(f as $ty),
L
ljedrz 已提交
2300
                Json::F64(f) => Err(ExpectedError("Integer".to_owned(), f.to_string())),
2301
                // re: #12967.. a type w/ numeric keys (ie HashMap<usize, V> etc)
B
Barosl Lee 已提交
2302
                // is going to have a string here, as per JSON spec.
A
Alex Crichton 已提交
2303
                Json::String(s) => match s.parse().ok() {
B
Barosl Lee 已提交
2304
                    Some(f) => Ok(f),
2305
                    None => Err(ExpectedError("Number".to_owned(), s)),
2306
                },
L
ljedrz 已提交
2307
                value => Err(ExpectedError("Number".to_owned(), value.to_string())),
2308 2309
            }
        }
2310
    };
2311 2312
}

2313
impl crate::Decoder for Decoder {
2314 2315
    type Error = DecoderError;

2316
    fn read_nil(&mut self) -> DecodeResult<()> {
A
Adolfo Ochagavía 已提交
2317
        expect!(self.pop(), Null)
2318 2319
    }

2320
    read_primitive! { read_usize, usize }
2321 2322 2323 2324
    read_primitive! { read_u8, u8 }
    read_primitive! { read_u16, u16 }
    read_primitive! { read_u32, u32 }
    read_primitive! { read_u64, u64 }
2325
    read_primitive! { read_u128, u128 }
2326
    read_primitive! { read_isize, isize }
2327 2328 2329 2330
    read_primitive! { read_i8, i8 }
    read_primitive! { read_i16, i16 }
    read_primitive! { read_i32, i32 }
    read_primitive! { read_i64, i64 }
2331
    read_primitive! { read_i128, i128 }
2332

M
Mark Rousskov 已提交
2333 2334 2335
    fn read_f32(&mut self) -> DecodeResult<f32> {
        self.read_f64().map(|x| x as f32)
    }
2336

S
Sean McArthur 已提交
2337 2338
    fn read_f64(&mut self) -> DecodeResult<f64> {
        match self.pop() {
2339 2340 2341 2342
            Json::I64(f) => Ok(f as f64),
            Json::U64(f) => Ok(f as f64),
            Json::F64(f) => Ok(f),
            Json::String(s) => {
2343
                // re: #12967.. a type w/ numeric keys (ie HashMap<usize, V> etc)
A
Adolfo Ochagavía 已提交
2344
                // is going to have a string here, as per JSON spec.
A
Alex Crichton 已提交
2345
                match s.parse().ok() {
2346
                    Some(f) => Ok(f),
2347
                    None => Err(ExpectedError("Number".to_owned(), s)),
2348
                }
M
Mark Rousskov 已提交
2349
            }
2350
            Json::Null => Ok(f64::NAN),
M
Mark Rousskov 已提交
2351
            value => Err(ExpectedError("Number".to_owned(), value.to_string())),
2352 2353
        }
    }
2354

2355 2356 2357
    fn read_bool(&mut self) -> DecodeResult<bool> {
        expect!(self.pop(), Boolean)
    }
2358

S
Sean McArthur 已提交
2359
    fn read_char(&mut self) -> DecodeResult<char> {
J
Jorge Aparicio 已提交
2360
        let s = self.read_str()?;
2361
        {
2362
            let mut it = s.chars();
Y
Yuki Okushi 已提交
2363
            if let (Some(c), None) = (it.next(), it.next()) {
2364
                // exactly one character
Y
Yuki Okushi 已提交
2365
                return Ok(c);
2366 2367
            }
        }
L
ljedrz 已提交
2368
        Err(ExpectedError("single character string".to_owned(), s.to_string()))
2369 2370
    }

2371
    fn read_str(&mut self) -> DecodeResult<Cow<'_, str>> {
2372
        expect!(self.pop(), String).map(Cow::Owned)
2373 2374
    }

M
Mark Rousskov 已提交
2375 2376
    fn read_enum<T, F>(&mut self, _name: &str, f: F) -> DecodeResult<T>
    where
2377 2378
        F: FnOnce(&mut Decoder) -> DecodeResult<T>,
    {
2379 2380 2381
        f(self)
    }

M
Mark Rousskov 已提交
2382 2383 2384
    fn read_enum_variant<T, F>(&mut self, names: &[&str], mut f: F) -> DecodeResult<T>
    where
        F: FnMut(&mut Decoder, usize) -> DecodeResult<T>,
2385
    {
S
Sean McArthur 已提交
2386
        let name = match self.pop() {
2387 2388
            Json::String(s) => s,
            Json::Object(mut o) => {
2389
                let n = match o.remove(&"variant".to_owned()) {
2390
                    Some(Json::String(s)) => s,
M
Mark Rousskov 已提交
2391 2392
                    Some(val) => return Err(ExpectedError("String".to_owned(), val.to_string())),
                    None => return Err(MissingFieldError("variant".to_owned())),
2393
                };
A
Alex Crichton 已提交
2394
                match o.remove(&"fields".to_string()) {
2395
                    Some(Json::Array(l)) => {
2396
                        self.stack.extend(l.into_iter().rev());
2397
                    }
M
Mark Rousskov 已提交
2398 2399
                    Some(val) => return Err(ExpectedError("Array".to_owned(), val.to_string())),
                    None => return Err(MissingFieldError("fields".to_owned())),
2400
                }
2401
                n
2402
            }
M
Mark Rousskov 已提交
2403
            json => return Err(ExpectedError("String or Object".to_owned(), json.to_string())),
2404
        };
2405
        let idx = match names.iter().position(|n| *n == &name[..]) {
2406
            Some(idx) => idx,
M
Mark Rousskov 已提交
2407
            None => return Err(UnknownVariantError(name)),
2408 2409 2410 2411
        };
        f(self, idx)
    }

M
Mark Rousskov 已提交
2412 2413
    fn read_enum_variant_arg<T, F>(&mut self, _idx: usize, f: F) -> DecodeResult<T>
    where
2414 2415
        F: FnOnce(&mut Decoder) -> DecodeResult<T>,
    {
2416 2417 2418
        f(self)
    }

M
Mark Rousskov 已提交
2419 2420
    fn read_enum_struct_variant<T, F>(&mut self, names: &[&str], f: F) -> DecodeResult<T>
    where
2421
        F: FnMut(&mut Decoder, usize) -> DecodeResult<T>,
2422
    {
2423 2424 2425
        self.read_enum_variant(names, f)
    }

M
Mark Rousskov 已提交
2426 2427 2428 2429 2430 2431 2432
    fn read_enum_struct_variant_field<T, F>(
        &mut self,
        _name: &str,
        idx: usize,
        f: F,
    ) -> DecodeResult<T>
    where
2433 2434
        F: FnOnce(&mut Decoder) -> DecodeResult<T>,
    {
2435 2436 2437
        self.read_enum_variant_arg(idx, f)
    }

M
Mark Rousskov 已提交
2438 2439
    fn read_struct<T, F>(&mut self, _name: &str, _len: usize, f: F) -> DecodeResult<T>
    where
2440 2441
        F: FnOnce(&mut Decoder) -> DecodeResult<T>,
    {
J
Jorge Aparicio 已提交
2442
        let value = f(self)?;
S
Sean McArthur 已提交
2443 2444
        self.pop();
        Ok(value)
2445 2446
    }

M
Mark Rousskov 已提交
2447 2448
    fn read_struct_field<T, F>(&mut self, name: &str, _idx: usize, f: F) -> DecodeResult<T>
    where
2449 2450
        F: FnOnce(&mut Decoder) -> DecodeResult<T>,
    {
J
Jorge Aparicio 已提交
2451
        let mut obj = expect!(self.pop(), Object)?;
S
Sean McArthur 已提交
2452

2453
        let value = match obj.remove(&name.to_string()) {
2454 2455 2456
            None => {
                // Add a Null and try to parse it as an Option<_>
                // to get None as a default value.
2457
                self.stack.push(Json::Null);
2458 2459 2460 2461
                match f(self) {
                    Ok(x) => x,
                    Err(_) => return Err(MissingFieldError(name.to_string())),
                }
M
Mark Rousskov 已提交
2462
            }
S
Sean McArthur 已提交
2463 2464
            Some(json) => {
                self.stack.push(json);
J
Jorge Aparicio 已提交
2465
                f(self)?
2466
            }
S
Sean McArthur 已提交
2467
        };
2468
        self.stack.push(Json::Object(obj));
S
Sean McArthur 已提交
2469
        Ok(value)
2470 2471
    }

M
Mark Rousskov 已提交
2472 2473
    fn read_tuple<T, F>(&mut self, tuple_len: usize, f: F) -> DecodeResult<T>
    where
2474 2475 2476
        F: FnOnce(&mut Decoder) -> DecodeResult<T>,
    {
        self.read_seq(move |d, len| {
2477 2478 2479 2480 2481
            if len == tuple_len {
                f(d)
            } else {
                Err(ExpectedError(format!("Tuple{}", tuple_len), format!("Tuple{}", len)))
            }
2482
        })
2483 2484
    }

M
Mark Rousskov 已提交
2485 2486
    fn read_tuple_arg<T, F>(&mut self, idx: usize, f: F) -> DecodeResult<T>
    where
2487 2488
        F: FnOnce(&mut Decoder) -> DecodeResult<T>,
    {
2489 2490 2491
        self.read_seq_elt(idx, f)
    }

M
Mark Rousskov 已提交
2492 2493
    fn read_tuple_struct<T, F>(&mut self, _name: &str, len: usize, f: F) -> DecodeResult<T>
    where
2494 2495
        F: FnOnce(&mut Decoder) -> DecodeResult<T>,
    {
2496
        self.read_tuple(len, f)
2497 2498
    }

M
Mark Rousskov 已提交
2499 2500
    fn read_tuple_struct_arg<T, F>(&mut self, idx: usize, f: F) -> DecodeResult<T>
    where
2501 2502
        F: FnOnce(&mut Decoder) -> DecodeResult<T>,
    {
2503 2504 2505
        self.read_tuple_arg(idx, f)
    }

M
Mark Rousskov 已提交
2506 2507
    fn read_option<T, F>(&mut self, mut f: F) -> DecodeResult<T>
    where
2508
        F: FnMut(&mut Decoder, bool) -> DecodeResult<T>,
2509
    {
S
Sean McArthur 已提交
2510
        match self.pop() {
2511
            Json::Null => f(self, false),
M
Mark Rousskov 已提交
2512 2513 2514 2515
            value => {
                self.stack.push(value);
                f(self, true)
            }
2516 2517 2518
        }
    }

M
Mark Rousskov 已提交
2519 2520
    fn read_seq<T, F>(&mut self, f: F) -> DecodeResult<T>
    where
2521
        F: FnOnce(&mut Decoder, usize) -> DecodeResult<T>,
2522
    {
J
Jorge Aparicio 已提交
2523
        let array = expect!(self.pop(), Array)?;
C
Corey Farwell 已提交
2524
        let len = array.len();
2525
        self.stack.extend(array.into_iter().rev());
2526 2527 2528
        f(self, len)
    }

M
Mark Rousskov 已提交
2529 2530
    fn read_seq_elt<T, F>(&mut self, _idx: usize, f: F) -> DecodeResult<T>
    where
2531 2532
        F: FnOnce(&mut Decoder) -> DecodeResult<T>,
    {
2533 2534 2535
        f(self)
    }

M
Mark Rousskov 已提交
2536 2537
    fn read_map<T, F>(&mut self, f: F) -> DecodeResult<T>
    where
2538
        F: FnOnce(&mut Decoder, usize) -> DecodeResult<T>,
2539
    {
J
Jorge Aparicio 已提交
2540
        let obj = expect!(self.pop(), Object)?;
S
Sean McArthur 已提交
2541
        let len = obj.len();
2542
        for (key, value) in obj {
S
Sean McArthur 已提交
2543
            self.stack.push(value);
2544
            self.stack.push(Json::String(key));
S
Sean McArthur 已提交
2545
        }
2546 2547 2548
        f(self, len)
    }

M
Mark Rousskov 已提交
2549 2550 2551
    fn read_map_elt_key<T, F>(&mut self, _idx: usize, f: F) -> DecodeResult<T>
    where
        F: FnOnce(&mut Decoder) -> DecodeResult<T>,
2552
    {
2553 2554 2555
        f(self)
    }

M
Mark Rousskov 已提交
2556 2557 2558
    fn read_map_elt_val<T, F>(&mut self, _idx: usize, f: F) -> DecodeResult<T>
    where
        F: FnOnce(&mut Decoder) -> DecodeResult<T>,
2559
    {
2560 2561
        f(self)
    }
2562 2563 2564 2565

    fn error(&mut self, err: &str) -> DecoderError {
        ApplicationError(err.to_string())
    }
2566 2567
}

2568
/// A trait for converting values to JSON
2569
pub trait ToJson {
2570 2571 2572
    /// Converts the value of `self` to an instance of JSON
    fn to_json(&self) -> Json;
}
2573

2574
macro_rules! to_json_impl_i64 {
2575 2576
    ($($t:ty), +) => (
        $(impl ToJson for $t {
N
Nick Cameron 已提交
2577 2578 2579
            fn to_json(&self) -> Json {
                Json::I64(*self as i64)
            }
2580 2581
        })+
    )
2582
}
2583

2584
to_json_impl_i64! { isize, i8, i16, i32, i64 }
2585

2586
macro_rules! to_json_impl_u64 {
A
Adolfo Ochagavía 已提交
2587 2588
    ($($t:ty), +) => (
        $(impl ToJson for $t {
N
Nick Cameron 已提交
2589 2590 2591
            fn to_json(&self) -> Json {
                Json::U64(*self as u64)
            }
A
Adolfo Ochagavía 已提交
2592 2593
        })+
    )
2594
}
2595

2596
to_json_impl_u64! { usize, u8, u16, u32, u64 }
2597

A
Adolfo Ochagavía 已提交
2598
impl ToJson for Json {
M
Mark Rousskov 已提交
2599 2600 2601
    fn to_json(&self) -> Json {
        self.clone()
    }
2602 2603
}

2604
impl ToJson for f32 {
M
Mark Rousskov 已提交
2605 2606 2607
    fn to_json(&self) -> Json {
        f64::from(*self).to_json()
    }
2608 2609
}

2610
impl ToJson for f64 {
M
mrec 已提交
2611 2612
    fn to_json(&self) -> Json {
        match self.classify() {
T
Tobias Bucher 已提交
2613
            Fp::Nan | Fp::Infinite => Json::Null,
M
Mark Rousskov 已提交
2614
            _ => Json::F64(*self),
M
mrec 已提交
2615 2616
        }
    }
2617 2618
}

2619
impl ToJson for () {
M
Mark Rousskov 已提交
2620 2621 2622
    fn to_json(&self) -> Json {
        Json::Null
    }
2623 2624
}

2625
impl ToJson for bool {
M
Mark Rousskov 已提交
2626 2627 2628
    fn to_json(&self) -> Json {
        Json::Boolean(*self)
    }
2629 2630
}

2631
impl ToJson for str {
M
Mark Rousskov 已提交
2632 2633 2634
    fn to_json(&self) -> Json {
        Json::String(self.to_string())
    }
2635 2636
}

2637
impl ToJson for string::String {
M
Mark Rousskov 已提交
2638 2639 2640
    fn to_json(&self) -> Json {
        Json::String((*self).clone())
    }
2641 2642
}

2643 2644 2645 2646 2647 2648 2649 2650 2651
macro_rules! tuple_impl {
    // use variables to indicate the arity of the tuple
    ($($tyvar:ident),* ) => {
        // the trailing commas are for the 1 tuple
        impl<
            $( $tyvar : ToJson ),*
            > ToJson for ( $( $tyvar ),* , ) {

            #[inline]
2652
            #[allow(non_snake_case)]
2653 2654
            fn to_json(&self) -> Json {
                match *self {
2655
                    ($(ref $tyvar),*,) => Json::Array(vec![$($tyvar.to_json()),*])
2656
                }
A
Adolfo Ochagavía 已提交
2657
            }
2658
        }
2659 2660 2661
    }
}

M
Mark Rousskov 已提交
2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673
tuple_impl! {A}
tuple_impl! {A, B}
tuple_impl! {A, B, C}
tuple_impl! {A, B, C, D}
tuple_impl! {A, B, C, D, E}
tuple_impl! {A, B, C, D, E, F}
tuple_impl! {A, B, C, D, E, F, G}
tuple_impl! {A, B, C, D, E, F, G, H}
tuple_impl! {A, B, C, D, E, F, G, H, I}
tuple_impl! {A, B, C, D, E, F, G, H, I, J}
tuple_impl! {A, B, C, D, E, F, G, H, I, J, K}
tuple_impl! {A, B, C, D, E, F, G, H, I, J, K, L}
2674

J
Jorge Aparicio 已提交
2675
impl<A: ToJson> ToJson for [A] {
M
Mark Rousskov 已提交
2676 2677 2678
    fn to_json(&self) -> Json {
        Json::Array(self.iter().map(|elt| elt.to_json()).collect())
    }
2679 2680
}

A
Adolfo Ochagavía 已提交
2681
impl<A: ToJson> ToJson for Vec<A> {
M
Mark Rousskov 已提交
2682 2683 2684
    fn to_json(&self) -> Json {
        Json::Array(self.iter().map(|elt| elt.to_json()).collect())
    }
2685 2686
}

A
Alexis Beingessner 已提交
2687
impl<A: ToJson> ToJson for BTreeMap<string::String, A> {
B
Ben Striegel 已提交
2688
    fn to_json(&self) -> Json {
A
Alexis Beingessner 已提交
2689
        let mut d = BTreeMap::new();
2690
        for (key, value) in self {
2691
            d.insert((*key).clone(), value.to_json());
2692
        }
2693
        Json::Object(d)
2694 2695 2696
    }
}

2697
impl<A: ToJson> ToJson for HashMap<string::String, A> {
G
Graydon Hoare 已提交
2698
    fn to_json(&self) -> Json {
A
Alexis Beingessner 已提交
2699
        let mut d = BTreeMap::new();
2700
        for (key, value) in self {
2701
            d.insert((*key).clone(), value.to_json());
G
Graydon Hoare 已提交
2702
        }
2703
        Json::Object(d)
G
Graydon Hoare 已提交
2704 2705 2706
    }
}

M
Mark Rousskov 已提交
2707
impl<A: ToJson> ToJson for Option<A> {
B
Ben Striegel 已提交
2708 2709
    fn to_json(&self) -> Json {
        match *self {
2710
            None => Json::Null,
M
Mark Rousskov 已提交
2711
            Some(ref value) => value.to_json(),
2712 2713 2714 2715
        }
    }
}

2716
struct FormatShim<'a, 'b> {
2717 2718 2719
    inner: &'a mut fmt::Formatter<'b>,
}

2720
impl<'a, 'b> fmt::Write for FormatShim<'a, 'b> {
2721
    fn write_str(&mut self, s: &str) -> fmt::Result {
2722 2723
        match self.inner.write_str(s) {
            Ok(_) => Ok(()),
M
Mark Rousskov 已提交
2724
            Err(_) => Err(fmt::Error),
2725
        }
2726 2727 2728
    }
}

2729
impl fmt::Display for Json {
2730
    /// Encodes a json value into a string
2731
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2732 2733
        let mut shim = FormatShim { inner: f };
        let mut encoder = Encoder::new(&mut shim);
2734 2735
        match self.encode(&mut encoder) {
            Ok(_) => Ok(()),
M
Mark Rousskov 已提交
2736
            Err(_) => Err(fmt::Error),
2737
        }
2738 2739 2740
    }
}

2741
impl<'a> fmt::Display for PrettyJson<'a> {
2742
    /// Encodes a json value into a string
2743
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2744 2745
        let mut shim = FormatShim { inner: f };
        let mut encoder = PrettyEncoder::new(&mut shim);
2746 2747
        match self.inner.encode(&mut encoder) {
            Ok(_) => Ok(()),
M
Mark Rousskov 已提交
2748
            Err(_) => Err(fmt::Error),
2749
        }
2750 2751 2752
    }
}

2753
impl<'a, T: Encodable> fmt::Display for AsJson<'a, T> {
2754
    /// Encodes a json value into a string
2755
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2756 2757
        let mut shim = FormatShim { inner: f };
        let mut encoder = Encoder::new(&mut shim);
2758 2759
        match self.inner.encode(&mut encoder) {
            Ok(_) => Ok(()),
M
Mark Rousskov 已提交
2760
            Err(_) => Err(fmt::Error),
2761
        }
2762 2763 2764 2765
    }
}

impl<'a, T> AsPrettyJson<'a, T> {
A
Alexander Regueiro 已提交
2766
    /// Sets the indentation level for the emitted JSON
2767
    pub fn indent(mut self, indent: usize) -> AsPrettyJson<'a, T> {
2768 2769 2770 2771 2772
        self.indent = Some(indent);
        self
    }
}

2773
impl<'a, T: Encodable> fmt::Display for AsPrettyJson<'a, T> {
2774
    /// Encodes a json value into a string
2775
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2776 2777
        let mut shim = FormatShim { inner: f };
        let mut encoder = PrettyEncoder::new(&mut shim);
2778 2779
        if let Some(n) = self.indent {
            encoder.set_indent(n);
2780
        }
2781 2782
        match self.inner.encode(&mut encoder) {
            Ok(_) => Ok(()),
M
Mark Rousskov 已提交
2783
            Err(_) => Err(fmt::Error),
2784
        }
2785
    }
2786 2787
}

B
Brendan Zabarauskas 已提交
2788
impl FromStr for Json {
A
Alex Crichton 已提交
2789 2790 2791
    type Err = BuilderError;
    fn from_str(s: &str) -> Result<Json, BuilderError> {
        from_str(s)
A
Adolfo Ochagavía 已提交
2792 2793 2794
    }
}

2795
#[cfg(test)]
C
chansuke 已提交
2796
mod tests;