json.rs 125.8 KB
Newer Older
M
mrec 已提交
1
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 3 4 5 6 7 8 9 10
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

E
Elly Jones 已提交
11 12
// Rust JSON serialization library
// Copyright (c) 2011 Google Inc.
13

14
#![forbid(non_camel_case_types)]
A
Aaron Turon 已提交
15
#![allow(missing_docs)]
E
Elly Jones 已提交
16

S
Steve Klabnik 已提交
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
//! 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 已提交
32
//! * `Object`: equivalent to rust's `BTreeMap<String, json::Json>`
S
Steve Klabnik 已提交
33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
//! * `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 ({ ... }).
//! A simple JSON document encoding a person, his/her age, address and phone numbers could look like
//!
//! ```ignore
//! {
//!     "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.
60 61
//! 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 已提交
62
//! The Rust compiler provides an annotation to automatically generate the code for these traits:
63
//! `#[derive(RustcDecodable, RustcEncodable)]`
S
Steve Klabnik 已提交
64 65 66 67 68 69
//!
//! 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.
//!
70
//! When using `ToJson` the `RustcEncodable` trait implementation is not mandatory.
S
Steve Klabnik 已提交
71 72 73 74 75 76 77 78
//!
//! # 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.
//!
79 80
//! ```notrust
//! // FIXME(#19470): this cannot be ```rust``` because it fails orphan checking at the moment
S
Steve Klabnik 已提交
81 82 83 84
//! extern crate serialize;
//! use serialize::json;
//!
//! // Automatically generate `Decodable` and `Encodable` trait implementations
85
//! #[derive(RustcDecodable, RustcEncodable)]
S
Steve Klabnik 已提交
86 87 88 89 90 91 92 93 94
//! pub struct TestStruct  {
//!     data_int: u8,
//!     data_str: String,
//!     data_vector: Vec<u8>,
//! }
//!
//! fn main() {
//!     let object = TestStruct {
//!         data_int: 1,
B
Barosl Lee 已提交
95
//!         data_str: "homura".to_string(),
S
Steve Klabnik 已提交
96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113
//!         data_vector: vec![2,3,4,5],
//!     };
//!
//!     // Serialize using `json::encode`
//!     let encoded = json::encode(&object);
//!
//!     // Deserialize using `json::decode`
//!     let decoded: TestStruct = json::decode(encoded.as_slice()).unwrap();
//! }
//! ```
//!
//! ## 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
//!
114 115
//! ```notrust
//! // FIXME(#19470): this cannot be ```rust``` because it fails orphan checking at the moment
S
Steve Klabnik 已提交
116
//! extern crate serialize;
117
//! use serialize::json::{self, ToJson, Json};
S
Steve Klabnik 已提交
118 119 120 121 122 123 124 125 126
//!
//! // A custom data structure
//! struct ComplexNum {
//!     a: f64,
//!     b: f64,
//! }
//!
//! // JSON value representation
//! impl ToJson for ComplexNum {
127 128
//!     fn to_json(&self) -> Json {
//!         Json::String(format!("{}+{}i", self.a, self.b))
S
Steve Klabnik 已提交
129 130 131
//!     }
//! }
//!
132
//! // Only generate `RustcEncodable` trait implementation
133
//! #[derive(Encodable)]
S
Steve Klabnik 已提交
134 135 136
//! pub struct ComplexNumRecord {
//!     uid: u8,
//!     dsc: String,
137
//!     val: Json,
S
Steve Klabnik 已提交
138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153
//! }
//!
//! 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(),
//!     });
//!     println!("data: {}", data);
//!     // data: {"uid":1,"dsc":"test","val":"0.0001+12.539j"};
//! }
//! ```
//!
//! ### Verbose example of `ToJson` usage
//!
154 155
//! ```notrust
//! // FIXME(#19470): this cannot be ```rust``` because it fails orphan checking at the moment
S
Steve Klabnik 已提交
156
//! extern crate serialize;
A
Alexis Beingessner 已提交
157
//! use std::collections::BTreeMap;
158
//! use serialize::json::{self, Json, ToJson};
S
Steve Klabnik 已提交
159 160
//!
//! // Only generate `Decodable` trait implementation
161
//! #[derive(Decodable)]
S
Steve Klabnik 已提交
162 163 164 165 166 167 168 169
//! pub struct TestStruct {
//!     data_int: u8,
//!     data_str: String,
//!     data_vector: Vec<u8>,
//! }
//!
//! // Specify encoding method manually
//! impl ToJson for TestStruct {
170
//!     fn to_json(&self) -> Json {
A
Alexis Beingessner 已提交
171
//!         let mut d = BTreeMap::new();
S
Steve Klabnik 已提交
172 173 174 175
//!         // 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());
176
//!         Json::Object(d)
S
Steve Klabnik 已提交
177 178 179 180 181 182 183
//!     }
//! }
//!
//! fn main() {
//!     // Serialize using `ToJson`
//!     let input_data = TestStruct {
//!         data_int: 1,
B
Barosl Lee 已提交
184
//!         data_str: "madoka".to_string(),
S
Steve Klabnik 已提交
185 186
//!         data_vector: vec![2,3,4,5],
//!     };
187
//!     let json_obj: Json = input_data.to_json();
S
Steve Klabnik 已提交
188 189 190 191 192 193
//!     let json_str: String = json_obj.to_string();
//!
//!     // Deserialize like before
//!     let decoded: TestStruct = json::decode(json_str.as_slice()).unwrap();
//! }
//! ```
B
Brian Anderson 已提交
194

195 196 197 198 199
use self::JsonEvent::*;
use self::StackElement::*;
use self::ErrorCode::*;
use self::ParserError::*;
use self::DecoderError::*;
S
Steven Fackler 已提交
200 201 202
use self::ParserState::*;
use self::InternalStackElement::*;

A
Adolfo Ochagavía 已提交
203
use std;
A
Alexis Beingessner 已提交
204
use std::collections::{HashMap, BTreeMap};
A
Adolfo Ochagavía 已提交
205 206
use std::{char, f64, fmt, io, num, str};
use std::mem::{swap, transmute};
T
Tobias Bucher 已提交
207 208 209
use std::num::{Float, Int};
use std::num::FpCategory as Fp;
use std::str::FromStr;
210
use std::string;
211
use std::ops;
A
Alex Crichton 已提交
212 213
use unicode::str as unicode_str;
use unicode::str::Utf16Item;
214

A
Alex Crichton 已提交
215
use Encodable;
E
Elly Jones 已提交
216

217
/// Represents a json value
218
#[derive(Clone, PartialEq, PartialOrd)]
219
pub enum Json {
220 221 222
    I64(i64),
    U64(u64),
    F64(f64),
223
    String(string::String),
B
Ben Striegel 已提交
224
    Boolean(bool),
225 226
    Array(self::Array),
    Object(self::Object),
B
Ben Striegel 已提交
227
    Null,
E
Elly Jones 已提交
228 229
}

230
pub type Array = Vec<Json>;
A
Alexis Beingessner 已提交
231
pub type Object = BTreeMap<string::String, Json>;
232

233 234 235 236 237
pub struct PrettyJson<'a> { inner: &'a Json }

pub struct AsJson<'a, T: 'a> { inner: &'a T }
pub struct AsPrettyJson<'a, T: 'a> { inner: &'a T, indent: Option<uint> }

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

260
#[derive(Clone, Copy, PartialEq, Show)]
261
pub enum ParserError {
S
Sean McArthur 已提交
262
    /// msg, line, col
263 264 265 266 267 268 269
    SyntaxError(ErrorCode, uint, uint),
    IoError(io::IoErrorKind, &'static str),
}

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

270
#[derive(Clone, PartialEq, Show)]
271 272
pub enum DecoderError {
    ParseError(ParserError),
273 274 275 276
    ExpectedError(string::String, string::String),
    MissingFieldError(string::String),
    UnknownVariantError(string::String),
    ApplicationError(string::String)
277 278 279 280
}

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

302 303 304 305 306 307 308 309 310 311 312 313
/// Shortcut function to decode a JSON `&str` into an object
pub fn decode<T: ::Decodable<Decoder, DecoderError>>(s: &str) -> DecodeResult<T> {
    let json = match from_str(s) {
        Ok(x) => x,
        Err(e) => return Err(ParseError(e))
    };

    let mut decoder = Decoder::new(json);
    ::Decodable::decode(&mut decoder)
}

/// Shortcut function to encode a `T` into a JSON `String`
314 315 316 317 318 319 320 321 322
pub fn encode<T>(object: &T) -> string::String
                 where T: for<'a> Encodable<Encoder<'a>, fmt::Error>
{
    let mut s = String::new();
    {
        let mut encoder = Encoder::new(&mut s);
        let _ = object.encode(&mut encoder);
    }
    s
323 324
}

325 326 327 328 329 330 331 332
impl fmt::Show for ErrorCode {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        error_str(*self).fmt(f)
    }
}

fn io_error_to_error(io: io::IoError) -> ParserError {
    IoError(io.kind, io.desc)
333
}
334

335 336 337 338 339
impl std::error::Error for DecoderError {
    fn description(&self) -> &str { "decoder error" }
    fn detail(&self) -> Option<std::string::String> { Some(self.to_string()) }
}

340
pub type EncodeResult = fmt::Result;
341
pub type DecodeResult<T> = Result<T, DecoderError>;
A
Alex Crichton 已提交
342

343
fn escape_str(wr: &mut fmt::Writer, v: &str) -> fmt::Result {
344 345 346 347
    try!(wr.write_str("\""));

    let mut start = 0;

348 349
    for (i, byte) in v.bytes().enumerate() {
        let escaped = match byte {
350 351
            b'"' => "\\\"",
            b'\\' => "\\\\",
R
Rolf Timmermans 已提交
352 353 354 355 356 357 358 359
            b'\x00' => "\\u0000",
            b'\x01' => "\\u0001",
            b'\x02' => "\\u0002",
            b'\x03' => "\\u0003",
            b'\x04' => "\\u0004",
            b'\x05' => "\\u0005",
            b'\x06' => "\\u0006",
            b'\x07' => "\\u0007",
360
            b'\x08' => "\\b",
R
Rolf Timmermans 已提交
361
            b'\t' => "\\t",
362
            b'\n' => "\\n",
R
Rolf Timmermans 已提交
363 364
            b'\x0b' => "\\u000b",
            b'\x0c' => "\\f",
365
            b'\r' => "\\r",
R
Rolf Timmermans 已提交
366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384
            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",
385 386 387 388
            _ => { continue; }
        };

        if start < i {
389
            try!(wr.write_str(v[start..i]));
E
Elly Jones 已提交
390
        }
391 392 393 394

        try!(wr.write_str(escaped));

        start = i + 1;
395
    }
396

397 398
    if start != v.len() {
        try!(wr.write_str(v[start..]));
399 400 401
    }

    wr.write_str("\"")
402 403
}

404
fn escape_char(writer: &mut fmt::Writer, v: char) -> fmt::Result {
405
    let mut buf = [0; 4];
406 407 408
    let n = v.encode_utf8(&mut buf).unwrap();
    let buf = unsafe { str::from_utf8_unchecked(buf[0..n]) };
    escape_str(writer, buf)
409 410
}

411 412
fn spaces(wr: &mut fmt::Writer, mut n: uint) -> fmt::Result {
    const BUF: &'static str = "                ";
413

414 415 416
    while n >= BUF.len() {
        try!(wr.write_str(BUF));
        n -= BUF.len();
417 418 419
    }

    if n > 0 {
420
        wr.write_str(BUF[..n])
421 422
    } else {
        Ok(())
423
    }
E
Elly Jones 已提交
424 425
}

426
fn fmt_number_or_null(v: f64) -> string::String {
M
mrec 已提交
427
    match v.classify() {
T
Tobias Bucher 已提交
428
        Fp::Nan | Fp::Infinite => string::String::from_str("null"),
429 430
        _ if v.fract() != 0f64 => f64::to_str_digits(v, 6u),
        _ => f64::to_str_digits(v, 6u) + ".0",
M
mrec 已提交
431 432 433
    }
}

434
/// A structure for implementing serialization to JSON.
E
Erik Price 已提交
435
pub struct Encoder<'a> {
436
    writer: &'a mut (fmt::Writer+'a),
437 438
}

E
Erik Price 已提交
439
impl<'a> Encoder<'a> {
440 441
    /// Creates a new JSON encoder whose output will be written to the writer
    /// specified.
442
    pub fn new(writer: &'a mut fmt::Writer) -> Encoder<'a> {
A
Adolfo Ochagavía 已提交
443
        Encoder { writer: writer }
444
    }
445 446
}

447
impl<'a> ::Encoder<fmt::Error> for Encoder<'a> {
A
Adolfo Ochagavía 已提交
448
    fn emit_nil(&mut self) -> EncodeResult { write!(self.writer, "null") }
449

450 451 452 453 454
    fn emit_uint(&mut self, v: uint) -> EncodeResult { write!(self.writer, "{}", v) }
    fn emit_u64(&mut self, v: u64) -> EncodeResult { write!(self.writer, "{}", v) }
    fn emit_u32(&mut self, v: u32) -> EncodeResult { write!(self.writer, "{}", v) }
    fn emit_u16(&mut self, v: u16) -> EncodeResult { write!(self.writer, "{}", v) }
    fn emit_u8(&mut self, v: u8) -> EncodeResult { write!(self.writer, "{}", v) }
455

456 457 458 459 460
    fn emit_int(&mut self, v: int) -> EncodeResult { write!(self.writer, "{}", v) }
    fn emit_i64(&mut self, v: i64) -> EncodeResult { write!(self.writer, "{}", v) }
    fn emit_i32(&mut self, v: i32) -> EncodeResult { write!(self.writer, "{}", v) }
    fn emit_i16(&mut self, v: i16) -> EncodeResult { write!(self.writer, "{}", v) }
    fn emit_i8(&mut self, v: i8) -> EncodeResult { write!(self.writer, "{}", v) }
461

S
Sean McArthur 已提交
462
    fn emit_bool(&mut self, v: bool) -> EncodeResult {
463
        if v {
A
Adolfo Ochagavía 已提交
464
            write!(self.writer, "true")
465
        } else {
A
Adolfo Ochagavía 已提交
466
            write!(self.writer, "false")
467 468 469
        }
    }

S
Sean McArthur 已提交
470
    fn emit_f64(&mut self, v: f64) -> EncodeResult {
A
Adolfo Ochagavía 已提交
471
        write!(self.writer, "{}", fmt_number_or_null(v))
A
Alex Crichton 已提交
472
    }
B
Barosl Lee 已提交
473 474 475
    fn emit_f32(&mut self, v: f32) -> EncodeResult {
        self.emit_f64(v as f64)
    }
476

477
    fn emit_char(&mut self, v: char) -> EncodeResult {
478
        escape_char(self.writer, v)
479
    }
S
Sean McArthur 已提交
480
    fn emit_str(&mut self, v: &str) -> EncodeResult {
481
        escape_str(self.writer, v)
A
Alex Crichton 已提交
482
    }
483

484 485 486
    fn emit_enum<F>(&mut self, _name: &str, f: F) -> EncodeResult where
        F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
    {
A
Adolfo Ochagavía 已提交
487 488
        f(self)
    }
489

490 491 492 493 494 495 496
    fn emit_enum_variant<F>(&mut self,
                            name: &str,
                            _id: uint,
                            cnt: uint,
                            f: F) -> EncodeResult where
        F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
    {
497 498 499 500
        // enums are encoded as strings or objects
        // Bunny => "Bunny"
        // Kangaroo(34,"William") => {"variant": "Kangaroo", "fields": [34,"William"]}
        if cnt == 0 {
501
            escape_str(self.writer, name)
502
        } else {
A
Adolfo Ochagavía 已提交
503
            try!(write!(self.writer, "{{\"variant\":"));
504
            try!(escape_str(self.writer, name));
A
Adolfo Ochagavía 已提交
505
            try!(write!(self.writer, ",\"fields\":["));
506
            try!(f(self));
A
Adolfo Ochagavía 已提交
507
            write!(self.writer, "]}}")
508 509
        }
    }
510

511 512 513
    fn emit_enum_variant_arg<F>(&mut self, idx: uint, f: F) -> EncodeResult where
        F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
    {
514
        if idx != 0 {
A
Adolfo Ochagavía 已提交
515
            try!(write!(self.writer, ","));
516
        }
S
Sean McArthur 已提交
517
        f(self)
518 519
    }

520 521 522 523 524 525 526
    fn emit_enum_struct_variant<F>(&mut self,
                                   name: &str,
                                   id: uint,
                                   cnt: uint,
                                   f: F) -> EncodeResult where
        F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
    {
527 528 529
        self.emit_enum_variant(name, id, cnt, f)
    }

530 531 532 533 534 535
    fn emit_enum_struct_variant_field<F>(&mut self,
                                         _: &str,
                                         idx: uint,
                                         f: F) -> EncodeResult where
        F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
    {
536 537 538
        self.emit_enum_variant_arg(idx, f)
    }

539 540 541
    fn emit_struct<F>(&mut self, _: &str, _: uint, f: F) -> EncodeResult where
        F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
    {
A
Adolfo Ochagavía 已提交
542
        try!(write!(self.writer, "{{"));
543
        try!(f(self));
A
Adolfo Ochagavía 已提交
544
        write!(self.writer, "}}")
545
    }
546

547 548 549
    fn emit_struct_field<F>(&mut self, name: &str, idx: uint, f: F) -> EncodeResult where
        F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
    {
A
Adolfo Ochagavía 已提交
550
        if idx != 0 { try!(write!(self.writer, ",")); }
551 552
        try!(escape_str(self.writer, name));
        try!(write!(self.writer, ":"));
S
Sean McArthur 已提交
553
        f(self)
554 555
    }

556 557 558
    fn emit_tuple<F>(&mut self, len: uint, f: F) -> EncodeResult where
        F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
    {
559 560
        self.emit_seq(len, f)
    }
561 562 563
    fn emit_tuple_arg<F>(&mut self, idx: uint, f: F) -> EncodeResult where
        F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
    {
564 565 566
        self.emit_seq_elt(idx, f)
    }

567 568 569
    fn emit_tuple_struct<F>(&mut self, _name: &str, len: uint, f: F) -> EncodeResult where
        F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
    {
570 571
        self.emit_seq(len, f)
    }
572 573 574
    fn emit_tuple_struct_arg<F>(&mut self, idx: uint, f: F) -> EncodeResult where
        F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
    {
575 576 577
        self.emit_seq_elt(idx, f)
    }

578 579 580
    fn emit_option<F>(&mut self, f: F) -> EncodeResult where
        F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
    {
S
Sean McArthur 已提交
581 582 583
        f(self)
    }
    fn emit_option_none(&mut self) -> EncodeResult { self.emit_nil() }
584 585 586
    fn emit_option_some<F>(&mut self, f: F) -> EncodeResult where
        F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
    {
S
Sean McArthur 已提交
587 588
        f(self)
    }
589

590 591 592
    fn emit_seq<F>(&mut self, _len: uint, f: F) -> EncodeResult where
        F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
    {
A
Adolfo Ochagavía 已提交
593
        try!(write!(self.writer, "["));
S
Sean McArthur 已提交
594
        try!(f(self));
A
Adolfo Ochagavía 已提交
595
        write!(self.writer, "]")
596 597
    }

598 599 600
    fn emit_seq_elt<F>(&mut self, idx: uint, f: F) -> EncodeResult where
        F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
    {
601
        if idx != 0 {
A
Adolfo Ochagavía 已提交
602
            try!(write!(self.writer, ","));
603 604 605 606
        }
        f(self)
    }

607 608 609
    fn emit_map<F>(&mut self, _len: uint, f: F) -> EncodeResult where
        F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
    {
A
Adolfo Ochagavía 已提交
610
        try!(write!(self.writer, "{{"));
611
        try!(f(self));
A
Adolfo Ochagavía 已提交
612
        write!(self.writer, "}}")
613
    }
614

615 616 617
    fn emit_map_elt_key<F>(&mut self, idx: uint, mut f: F) -> EncodeResult where
        F: FnMut(&mut Encoder<'a>) -> EncodeResult,
    {
A
Adolfo Ochagavía 已提交
618
        if idx != 0 { try!(write!(self.writer, ",")) }
619 620
        // ref #12967, make sure to wrap a key in double quotes,
        // in the event that its of a type that omits them (eg numbers)
D
Daniel Micay 已提交
621
        let mut buf = Vec::new();
N
Nick Cameron 已提交
622 623 624 625 626
        // FIXME(14302) remove the transmute and unsafe block.
        unsafe {
            let mut check_encoder = Encoder::new(&mut buf);
            try!(f(transmute(&mut check_encoder)));
        }
D
Daniel Micay 已提交
627
        let out = str::from_utf8(buf[]).unwrap();
A
Adolfo Ochagavía 已提交
628 629
        let needs_wrapping = out.char_at(0) != '"' && out.char_at_reverse(out.len()) != '"';
        if needs_wrapping { try!(write!(self.writer, "\"")); }
S
Sean McArthur 已提交
630
        try!(f(self));
A
Adolfo Ochagavía 已提交
631
        if needs_wrapping { try!(write!(self.writer, "\"")); }
S
Sean McArthur 已提交
632
        Ok(())
633 634
    }

635 636 637
    fn emit_map_elt_val<F>(&mut self, _idx: uint, f: F) -> EncodeResult where
        F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
    {
A
Adolfo Ochagavía 已提交
638
        try!(write!(self.writer, ":"));
639 640 641 642
        f(self)
    }
}

643 644
/// Another encoder for JSON, but prints out human-readable JSON instead of
/// compact data
E
Erik Price 已提交
645
pub struct PrettyEncoder<'a> {
646
    writer: &'a mut (fmt::Writer+'a),
647
    curr_indent: uint,
648
    indent: uint,
649 650
}

E
Erik Price 已提交
651
impl<'a> PrettyEncoder<'a> {
652
    /// Creates a new encoder whose output will be written to the specified writer
653
    pub fn new(writer: &'a mut fmt::Writer) -> PrettyEncoder<'a> {
654 655 656 657 658
        PrettyEncoder { writer: writer, curr_indent: 0, indent: 2, }
    }

    /// Set the number of spaces to indent for each level.
    /// This is safe to set during encoding.
N
Niko Matsakis 已提交
659
    pub fn set_indent(&mut self, indent: uint) {
660
        // self.indent very well could be 0 so we need to use checked division.
661
        let level = self.curr_indent.checked_div(self.indent).unwrap_or(0);
662 663
        self.indent = indent;
        self.curr_indent = level * self.indent;
664
    }
665
}
666

667
impl<'a> ::Encoder<fmt::Error> for PrettyEncoder<'a> {
A
Adolfo Ochagavía 已提交
668
    fn emit_nil(&mut self) -> EncodeResult { write!(self.writer, "null") }
669

670 671 672 673 674
    fn emit_uint(&mut self, v: uint) -> EncodeResult { write!(self.writer, "{}", v) }
    fn emit_u64(&mut self, v: u64) -> EncodeResult { write!(self.writer, "{}", v) }
    fn emit_u32(&mut self, v: u32) -> EncodeResult { write!(self.writer, "{}", v) }
    fn emit_u16(&mut self, v: u16) -> EncodeResult { write!(self.writer, "{}", v) }
    fn emit_u8(&mut self, v: u8) -> EncodeResult { write!(self.writer, "{}", v) }
675

676 677 678 679 680
    fn emit_int(&mut self, v: int) -> EncodeResult { write!(self.writer, "{}", v) }
    fn emit_i64(&mut self, v: i64) -> EncodeResult { write!(self.writer, "{}", v) }
    fn emit_i32(&mut self, v: i32) -> EncodeResult { write!(self.writer, "{}", v) }
    fn emit_i16(&mut self, v: i16) -> EncodeResult { write!(self.writer, "{}", v) }
    fn emit_i8(&mut self, v: i8) -> EncodeResult { write!(self.writer, "{}", v) }
681

S
Sean McArthur 已提交
682
    fn emit_bool(&mut self, v: bool) -> EncodeResult {
683
        if v {
A
Adolfo Ochagavía 已提交
684
            write!(self.writer, "true")
685
        } else {
A
Adolfo Ochagavía 已提交
686
            write!(self.writer, "false")
687 688 689
        }
    }

S
Sean McArthur 已提交
690
    fn emit_f64(&mut self, v: f64) -> EncodeResult {
A
Adolfo Ochagavía 已提交
691
        write!(self.writer, "{}", fmt_number_or_null(v))
A
Alex Crichton 已提交
692
    }
693 694 695
    fn emit_f32(&mut self, v: f32) -> EncodeResult {
        self.emit_f64(v as f64)
    }
696

697
    fn emit_char(&mut self, v: char) -> EncodeResult {
698
        escape_char(self.writer, v)
699
    }
S
Sean McArthur 已提交
700
    fn emit_str(&mut self, v: &str) -> EncodeResult {
701
        escape_str(self.writer, v)
A
Alex Crichton 已提交
702
    }
703

704 705 706
    fn emit_enum<F>(&mut self, _name: &str, f: F) -> EncodeResult where
        F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
    {
707 708 709
        f(self)
    }

710 711 712 713 714 715 716 717
    fn emit_enum_variant<F>(&mut self,
                            name: &str,
                            _id: uint,
                            cnt: uint,
                            f: F)
                            -> EncodeResult where
        F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
    {
718
        if cnt == 0 {
719
            escape_str(self.writer, name)
720
        } else {
721
            try!(write!(self.writer, "{{\n"));
722 723
            self.curr_indent += self.indent;
            try!(spaces(self.writer, self.curr_indent));
724
            try!(write!(self.writer, "\"variant\": "));
725 726
            try!(escape_str(self.writer, name));
            try!(write!(self.writer, ",\n"));
727 728 729
            try!(spaces(self.writer, self.curr_indent));
            try!(write!(self.writer, "\"fields\": [\n"));
            self.curr_indent += self.indent;
S
Sean McArthur 已提交
730
            try!(f(self));
731
            self.curr_indent -= self.indent;
732
            try!(write!(self.writer, "\n"));
733
            try!(spaces(self.writer, self.curr_indent));
734 735 736 737
            self.curr_indent -= self.indent;
            try!(write!(self.writer, "]\n"));
            try!(spaces(self.writer, self.curr_indent));
            write!(self.writer, "}}")
738 739 740
        }
    }

741 742 743
    fn emit_enum_variant_arg<F>(&mut self, idx: uint, f: F) -> EncodeResult where
        F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
    {
744
        if idx != 0 {
A
Adolfo Ochagavía 已提交
745
            try!(write!(self.writer, ",\n"));
746
        }
747
        try!(spaces(self.writer, self.curr_indent));
748 749 750
        f(self)
    }

751 752 753 754 755 756 757
    fn emit_enum_struct_variant<F>(&mut self,
                                   name: &str,
                                   id: uint,
                                   cnt: uint,
                                   f: F) -> EncodeResult where
        F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
    {
758 759 760
        self.emit_enum_variant(name, id, cnt, f)
    }

761 762 763 764 765 766
    fn emit_enum_struct_variant_field<F>(&mut self,
                                         _: &str,
                                         idx: uint,
                                         f: F) -> EncodeResult where
        F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
    {
767 768 769 770
        self.emit_enum_variant_arg(idx, f)
    }


771 772 773
    fn emit_struct<F>(&mut self, _: &str, len: uint, f: F) -> EncodeResult where
        F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
    {
774
        if len == 0 {
A
Adolfo Ochagavía 已提交
775
            write!(self.writer, "{{}}")
776
        } else {
A
Adolfo Ochagavía 已提交
777
            try!(write!(self.writer, "{{"));
778
            self.curr_indent += self.indent;
779
            try!(f(self));
780
            self.curr_indent -= self.indent;
781
            try!(write!(self.writer, "\n"));
782
            try!(spaces(self.writer, self.curr_indent));
783
            write!(self.writer, "}}")
784 785
        }
    }
786

787 788 789
    fn emit_struct_field<F>(&mut self, name: &str, idx: uint, f: F) -> EncodeResult where
        F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
    {
790
        if idx == 0 {
A
Adolfo Ochagavía 已提交
791
            try!(write!(self.writer, "\n"));
792
        } else {
A
Adolfo Ochagavía 已提交
793
            try!(write!(self.writer, ",\n"));
794
        }
795
        try!(spaces(self.writer, self.curr_indent));
796 797
        try!(escape_str(self.writer, name));
        try!(write!(self.writer, ": "));
S
Sean McArthur 已提交
798
        f(self)
799 800
    }

801 802 803
    fn emit_tuple<F>(&mut self, len: uint, f: F) -> EncodeResult where
        F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
    {
804 805
        self.emit_seq(len, f)
    }
806 807 808
    fn emit_tuple_arg<F>(&mut self, idx: uint, f: F) -> EncodeResult where
        F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
    {
809 810 811
        self.emit_seq_elt(idx, f)
    }

812 813 814
    fn emit_tuple_struct<F>(&mut self, _: &str, len: uint, f: F) -> EncodeResult where
        F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
    {
815 816
        self.emit_seq(len, f)
    }
817 818 819
    fn emit_tuple_struct_arg<F>(&mut self, idx: uint, f: F) -> EncodeResult where
        F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
    {
820 821 822
        self.emit_seq_elt(idx, f)
    }

823 824 825
    fn emit_option<F>(&mut self, f: F) -> EncodeResult where
        F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
    {
S
Sean McArthur 已提交
826 827 828
        f(self)
    }
    fn emit_option_none(&mut self) -> EncodeResult { self.emit_nil() }
829 830 831
    fn emit_option_some<F>(&mut self, f: F) -> EncodeResult where
        F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
    {
S
Sean McArthur 已提交
832 833
        f(self)
    }
834

835 836 837
    fn emit_seq<F>(&mut self, len: uint, f: F) -> EncodeResult where
        F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
    {
838
        if len == 0 {
A
Adolfo Ochagavía 已提交
839
            write!(self.writer, "[]")
840
        } else {
A
Adolfo Ochagavía 已提交
841
            try!(write!(self.writer, "["));
842
            self.curr_indent += self.indent;
S
Sean McArthur 已提交
843
            try!(f(self));
844
            self.curr_indent -= self.indent;
845
            try!(write!(self.writer, "\n"));
846
            try!(spaces(self.writer, self.curr_indent));
847
            write!(self.writer, "]")
848 849 850
        }
    }

851 852 853
    fn emit_seq_elt<F>(&mut self, idx: uint, f: F) -> EncodeResult where
        F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
    {
854
        if idx == 0 {
A
Adolfo Ochagavía 已提交
855
            try!(write!(self.writer, "\n"));
856
        } else {
A
Adolfo Ochagavía 已提交
857
            try!(write!(self.writer, ",\n"));
858
        }
859
        try!(spaces(self.writer, self.curr_indent));
860 861 862
        f(self)
    }

863 864 865
    fn emit_map<F>(&mut self, len: uint, f: F) -> EncodeResult where
        F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
    {
866
        if len == 0 {
A
Adolfo Ochagavía 已提交
867
            write!(self.writer, "{{}}")
868
        } else {
A
Adolfo Ochagavía 已提交
869
            try!(write!(self.writer, "{{"));
870
            self.curr_indent += self.indent;
871
            try!(f(self));
872
            self.curr_indent -= self.indent;
873
            try!(write!(self.writer, "\n"));
874
            try!(spaces(self.writer, self.curr_indent));
875
            write!(self.writer, "}}")
876 877
        }
    }
878

879 880 881
    fn emit_map_elt_key<F>(&mut self, idx: uint, mut f: F) -> EncodeResult where
        F: FnMut(&mut PrettyEncoder<'a>) -> EncodeResult,
    {
882
        if idx == 0 {
A
Adolfo Ochagavía 已提交
883
            try!(write!(self.writer, "\n"));
884
        } else {
A
Adolfo Ochagavía 已提交
885
            try!(write!(self.writer, ",\n"));
886
        }
887
        try!(spaces(self.writer, self.curr_indent));
888 889
        // ref #12967, make sure to wrap a key in double quotes,
        // in the event that its of a type that omits them (eg numbers)
D
Daniel Micay 已提交
890
        let mut buf = Vec::new();
N
Nick Cameron 已提交
891 892 893 894 895
        // FIXME(14302) remove the transmute and unsafe block.
        unsafe {
            let mut check_encoder = PrettyEncoder::new(&mut buf);
            try!(f(transmute(&mut check_encoder)));
        }
D
Daniel Micay 已提交
896
        let out = str::from_utf8(buf[]).unwrap();
A
Adolfo Ochagavía 已提交
897 898
        let needs_wrapping = out.char_at(0) != '"' && out.char_at_reverse(out.len()) != '"';
        if needs_wrapping { try!(write!(self.writer, "\"")); }
S
Sean McArthur 已提交
899
        try!(f(self));
A
Adolfo Ochagavía 已提交
900
        if needs_wrapping { try!(write!(self.writer, "\"")); }
S
Sean McArthur 已提交
901
        Ok(())
902 903
    }

904 905 906
    fn emit_map_elt_val<F>(&mut self, _idx: uint, f: F) -> EncodeResult where
        F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
    {
A
Adolfo Ochagavía 已提交
907
        try!(write!(self.writer, ": "));
S
Sean McArthur 已提交
908
        f(self)
909 910 911
    }
}

912 913
impl<E: ::Encoder<S>, S> Encodable<E, S> for Json {
    fn encode(&self, e: &mut E) -> Result<(), S> {
914
        match *self {
915 916 917 918 919 920 921 922
            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),
            Json::Null => e.emit_nil(),
923 924 925 926
        }
    }
}

927 928 929 930 931
/// Create an `AsJson` wrapper which can be used to print a value as JSON
/// on-the-fly via `write!`
pub fn as_json<T>(t: &T) -> AsJson<T> {
    AsJson { inner: t }
}
932

933 934 935 936 937
/// Create an `AsPrettyJson` wrapper which can be used to print a value as JSON
/// on-the-fly via `write!`
pub fn as_pretty_json<T>(t: &T) -> AsPrettyJson<T> {
    AsPrettyJson { inner: t, indent: None }
}
938

939 940 941 942 943
impl Json {
    /// Borrow this json object as a pretty object to generate a pretty
    /// representation for it via `Show`.
    pub fn pretty(&self) -> PrettyJson {
        PrettyJson { inner: self }
944
    }
945 946 947

     /// If the Json value is an Object, returns the value associated with the provided key.
    /// Otherwise, returns None.
948 949
    pub fn find<'a>(&'a self, key: &str) -> Option<&'a Json>{
        match self {
950
            &Json::Object(ref map) => map.get(key),
951 952 953 954
            _ => None
        }
    }

955
    /// Attempts to get a nested Json Object for each key in `keys`.
956
    /// If any key is found not to exist, find_path will return None.
957
    /// Otherwise, it will return the Json value associated with the final key.
958
    pub fn find_path<'a>(&'a self, keys: &[&str]) -> Option<&'a Json>{
959 960 961 962 963 964 965 966
        let mut target = self;
        for key in keys.iter() {
            match target.find(*key) {
                Some(t) => { target = t; },
                None => return None
            }
        }
        Some(target)
967 968 969 970 971
    }

    /// 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
    /// or the Json value is not an Object, returns None.
972 973
    pub fn search<'a>(&'a self, key: &str) -> Option<&'a Json> {
        match self {
974
            &Json::Object(ref map) => {
A
Aaron Turon 已提交
975
                match map.get(key) {
976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991
                    Some(json_value) => Some(json_value),
                    None => {
                        for (_, v) in map.iter() {
                            match v.search(key) {
                                x if x.is_some() => return x,
                                _ => ()
                            }
                        }
                        None
                    }
                }
            },
            _ => None
        }
    }

992 993
    /// Returns true if the Json value is an Object. Returns false otherwise.
    pub fn is_object<'a>(&'a self) -> bool {
994
        self.as_object().is_some()
995 996
    }

A
Alexis Beingessner 已提交
997
    /// If the Json value is an Object, returns the associated BTreeMap.
998
    /// Returns None otherwise.
999
    pub fn as_object<'a>(&'a self) -> Option<&'a Object> {
1000
        match self {
1001
            &Json::Object(ref map) => Some(map),
1002 1003 1004 1005
            _ => None
        }
    }

C
Corey Farwell 已提交
1006
    /// Returns true if the Json value is an Array. Returns false otherwise.
C
Corey Farwell 已提交
1007 1008
    pub fn is_array<'a>(&'a self) -> bool {
        self.as_array().is_some()
1009 1010
    }

C
Corey Farwell 已提交
1011
    /// If the Json value is an Array, returns the associated vector.
1012
    /// Returns None otherwise.
1013
    pub fn as_array<'a>(&'a self) -> Option<&'a Array> {
1014
        match self {
1015
            &Json::Array(ref array) => Some(&*array),
1016 1017 1018 1019 1020
            _ => None
        }
    }

    /// Returns true if the Json value is a String. Returns false otherwise.
1021 1022
    pub fn is_string<'a>(&'a self) -> bool {
        self.as_string().is_some()
1023 1024 1025 1026
    }

    /// If the Json value is a String, returns the associated str.
    /// Returns None otherwise.
1027
    pub fn as_string<'a>(&'a self) -> Option<&'a str> {
1028
        match *self {
A
Alex Crichton 已提交
1029
            Json::String(ref s) => Some(s[]),
1030 1031 1032 1033 1034 1035
            _ => None
        }
    }

    /// Returns true if the Json value is a Number. Returns false otherwise.
    pub fn is_number(&self) -> bool {
1036
        match *self {
1037
            Json::I64(_) | Json::U64(_) | Json::F64(_) => true,
1038 1039 1040 1041 1042 1043 1044
            _ => false,
        }
    }

    /// Returns true if the Json value is a i64. Returns false otherwise.
    pub fn is_i64(&self) -> bool {
        match *self {
1045
            Json::I64(_) => true,
1046 1047 1048 1049 1050 1051 1052
            _ => false,
        }
    }

    /// Returns true if the Json value is a u64. Returns false otherwise.
    pub fn is_u64(&self) -> bool {
        match *self {
1053
            Json::U64(_) => true,
1054 1055
            _ => false,
        }
1056 1057
    }

1058 1059 1060
    /// Returns true if the Json value is a f64. Returns false otherwise.
    pub fn is_f64(&self) -> bool {
        match *self {
1061
            Json::F64(_) => true,
1062 1063 1064 1065
            _ => false,
        }
    }

1066
    /// If the Json value is a number, return or cast it to a i64.
1067
    /// Returns None otherwise.
1068 1069
    pub fn as_i64(&self) -> Option<i64> {
        match *self {
1070 1071
            Json::I64(n) => Some(n),
            Json::U64(n) => num::cast(n),
1072 1073 1074 1075 1076 1077 1078 1079
            _ => None
        }
    }

    /// If the Json value is a number, return or cast it to a u64.
    /// Returns None otherwise.
    pub fn as_u64(&self) -> Option<u64> {
        match *self {
1080 1081
            Json::I64(n) => num::cast(n),
            Json::U64(n) => Some(n),
1082 1083 1084 1085
            _ => None
        }
    }

1086
    /// If the Json value is a number, return or cast it to a f64.
1087 1088 1089
    /// Returns None otherwise.
    pub fn as_f64(&self) -> Option<f64> {
        match *self {
1090 1091 1092
            Json::I64(n) => num::cast(n),
            Json::U64(n) => num::cast(n),
            Json::F64(n) => Some(n),
1093 1094 1095 1096 1097 1098
            _ => None
        }
    }

    /// Returns true if the Json value is a Boolean. Returns false otherwise.
    pub fn is_boolean(&self) -> bool {
1099
        self.as_boolean().is_some()
1100 1101 1102 1103 1104 1105
    }

    /// If the Json value is a Boolean, returns the associated bool.
    /// Returns None otherwise.
    pub fn as_boolean(&self) -> Option<bool> {
        match self {
1106
            &Json::Boolean(b) => Some(b),
1107 1108 1109 1110 1111 1112
            _ => None
        }
    }

    /// Returns true if the Json value is a Null. Returns false otherwise.
    pub fn is_null(&self) -> bool {
1113
        self.as_null().is_some()
1114 1115 1116 1117 1118 1119
    }

    /// If the Json value is a Null, returns ().
    /// Returns None otherwise.
    pub fn as_null(&self) -> Option<()> {
        match self {
1120
            &Json::Null => Some(()),
1121 1122 1123
            _ => None
        }
    }
E
Elly Jones 已提交
1124 1125
}

J
Jorge Aparicio 已提交
1126 1127
// NOTE(stage0): remove impl after a snapshot
#[cfg(stage0)]
1128
impl<'a> ops::Index<&'a str, Json>  for Json {
N
Niko Matsakis 已提交
1129
    fn index(&self, idx: & &str) -> &Json {
1130 1131 1132 1133
        self.find(*idx).unwrap()
    }
}

J
Jorge Aparicio 已提交
1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144
#[cfg(not(stage0))]  // NOTE(stage0): remove cfg after a snapshot
impl<'a> ops::Index<&'a str>  for Json {
    type Output = Json;

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

// NOTE(stage0): remove impl after a snapshot
#[cfg(stage0)]
1145 1146 1147
impl ops::Index<uint, Json> for Json {
    fn index<'a>(&'a self, idx: &uint) -> &'a Json {
        match self {
1148
            &Json::Array(ref v) => v.index(idx),
C
Corey Farwell 已提交
1149
            _ => panic!("can only index Json with uint if it is an array")
1150 1151 1152 1153
        }
    }
}

J
Jorge Aparicio 已提交
1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165
#[cfg(not(stage0))]  // NOTE(stage0): remove cfg after a snapshot
impl ops::Index<uint> for Json {
    type Output = Json;

    fn index<'a>(&'a self, idx: &uint) -> &'a Json {
        match self {
            &Json::Array(ref v) => v.index(idx),
            _ => panic!("can only index Json with uint if it is an array")
        }
    }
}

1166
/// The output of the streaming parser.
1167
#[derive(PartialEq, Clone, Show)]
1168 1169 1170
pub enum JsonEvent {
    ObjectStart,
    ObjectEnd,
C
Corey Farwell 已提交
1171 1172
    ArrayStart,
    ArrayEnd,
1173
    BooleanValue(bool),
1174 1175 1176
    I64Value(i64),
    U64Value(u64),
    F64Value(f64),
1177
    StringValue(string::String),
1178 1179 1180 1181
    NullValue,
    Error(ParserError),
}

1182
#[derive(PartialEq, Show)]
1183
enum ParserState {
C
Corey Farwell 已提交
1184
    // Parse a value in an array, true means first element.
1185
    ParseArray(bool),
C
Corey Farwell 已提交
1186
    // Parse ',' or ']' after an element in an array.
C
Corey Farwell 已提交
1187
    ParseArrayComma,
1188 1189 1190 1191
    // 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 已提交
1192
    // Initial state.
1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210
    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.
/// For example foo.bar[3].x
pub struct Stack {
    stack: Vec<InternalStackElement>,
    str_buffer: Vec<u8>,
}

/// StackElements compose a Stack.
/// For example, Key("foo"), Key("bar"), Index(3) and Key("x") are the
/// StackElements compositing the stack that represents foo.bar[3].x
1211
#[derive(PartialEq, Clone, Show)]
1212 1213 1214 1215 1216 1217 1218
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.
1219
#[derive(PartialEq, Clone, Show)]
1220 1221 1222 1223 1224 1225 1226
enum InternalStackElement {
    InternalIndex(u32),
    InternalKey(u16, u16), // start, size
}

impl Stack {
    pub fn new() -> Stack {
A
Adolfo Ochagavía 已提交
1227
        Stack { stack: Vec::new(), str_buffer: Vec::new() }
1228 1229 1230 1231 1232
    }

    /// Returns The number of elements in the Stack.
    pub fn len(&self) -> uint { self.stack.len() }

A
Adolfo Ochagavía 已提交
1233 1234
    /// Returns true if the stack is empty.
    pub fn is_empty(&self) -> bool { self.stack.is_empty() }
1235 1236 1237 1238 1239

    /// 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.
    pub fn get<'l>(&'l self, idx: uint) -> StackElement<'l> {
N
Nick Cameron 已提交
1240
        match self.stack[idx] {
1241
            InternalIndex(i) => Index(i),
A
Adolfo Ochagavía 已提交
1242
            InternalKey(start, size) => {
A
Adolfo Ochagavía 已提交
1243
                Key(str::from_utf8(
1244
                    self.str_buffer[start as uint .. start as uint + size as uint]).unwrap())
A
Adolfo Ochagavía 已提交
1245
            }
1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285
        }
    }

    /// Compares this stack with an array of StackElements.
    pub fn is_equal_to(&self, rhs: &[StackElement]) -> bool {
        if self.stack.len() != rhs.len() { return false; }
        for i in range(0, rhs.len()) {
            if self.get(i) != rhs[i] { return false; }
        }
        return true;
    }

    /// Returns true if the bottom-most elements of this stack are the same as
    /// the ones passed as parameter.
    pub fn starts_with(&self, rhs: &[StackElement]) -> bool {
        if self.stack.len() < rhs.len() { return false; }
        for i in range(0, rhs.len()) {
            if self.get(i) != rhs[i] { return false; }
        }
        return true;
    }

    /// Returns true if the top-most elements of this stack are the same as
    /// the ones passed as parameter.
    pub fn ends_with(&self, rhs: &[StackElement]) -> bool {
        if self.stack.len() < rhs.len() { return false; }
        let offset = self.stack.len() - rhs.len();
        for i in range(0, rhs.len()) {
            if self.get(i + offset) != rhs[i] { return false; }
        }
        return true;
    }

    /// Returns the top-most element (if any).
    pub fn top<'l>(&'l self) -> Option<StackElement<'l>> {
        return match self.stack.last() {
            None => None,
            Some(&InternalIndex(i)) => Some(Index(i)),
            Some(&InternalKey(start, size)) => {
                Some(Key(str::from_utf8(
1286
                    self.str_buffer[start as uint .. (start+size) as uint]
1287 1288 1289 1290 1291 1292
                ).unwrap()))
            }
        }
    }

    // Used by Parser to insert Key elements at the top of the stack.
1293
    fn push_key(&mut self, key: string::String) {
1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310
        self.stack.push(InternalKey(self.str_buffer.len() as u16, key.len() as u16));
        for c in key.as_bytes().iter() {
            self.str_buffer.push(*c);
        }
    }

    // Used by Parser to insert Index elements at the top of the stack.
    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) => {
                let new_size = self.str_buffer.len() - sz as uint;
A
Adolfo Ochagavía 已提交
1311
                self.str_buffer.truncate(new_size);
1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330
            }
            InternalIndex(_) => {}
        }
        self.stack.pop();
    }

    // Used by Parser to test whether the top-most element is an index.
    fn last_is_index(&self) -> bool {
        if self.is_empty() { return false; }
        return match *self.stack.last().unwrap() {
            InternalIndex(_) => true,
            _ => false,
        }
    }

    // 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() {
A
Adolfo Ochagavía 已提交
1331
            InternalIndex(i) => { i + 1 }
S
Steve Klabnik 已提交
1332
            _ => { panic!(); }
1333
        };
1334
        self.stack[len - 1] = InternalIndex(idx);
1335 1336 1337 1338 1339
    }
}

/// A streaming JSON parser implemented as an iterator of JsonEvent, consuming
/// an iterator of char.
G
Gary Linscott 已提交
1340
pub struct Parser<T> {
1341 1342 1343 1344
    rdr: T,
    ch: Option<char>,
    line: uint,
    col: uint,
1345 1346 1347
    // We maintain a stack representing where we are in the logical structure
    // of the JSON stream.
    stack: Stack,
J
Joseph Crail 已提交
1348
    // A state machine is kept to make it possible to interrupt and resume parsing.
1349 1350 1351
    state: ParserState,
}

J
Jorge Aparicio 已提交
1352 1353 1354
impl<T: Iterator<Item=char>> Iterator for Parser<T> {
    type Item = JsonEvent;

1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372
    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));
            }
        }

        return Some(self.parse());
    }
1373 1374
}

J
Jorge Aparicio 已提交
1375
impl<T: Iterator<Item=char>> Parser<T> {
1376
    /// Creates the JSON parser.
1377
    pub fn new(rdr: T) -> Parser<T> {
1378 1379
        let mut p = Parser {
            rdr: rdr,
1380
            ch: Some('\x00'),
1381 1382
            line: 1,
            col: 0,
1383 1384
            stack: Stack::new(),
            state: ParseStart,
1385 1386
        };
        p.bump();
1387
        return p;
1388
    }
E
Elly Jones 已提交
1389

1390 1391 1392
    /// Provides access to the current position in the logical structure of the
    /// JSON stream.
    pub fn stack<'l>(&'l self) -> &'l Stack {
1393
        return &self.stack;
1394
    }
1395

1396 1397
    fn eof(&self) -> bool { self.ch.is_none() }
    fn ch_or_null(&self) -> char { self.ch.unwrap_or('\x00') }
1398
    fn bump(&mut self) {
1399
        self.ch = self.rdr.next();
E
Elly Jones 已提交
1400

1401
        if self.ch_is('\n') {
1402 1403
            self.line += 1u;
            self.col = 1u;
G
Gary Linscott 已提交
1404 1405
        } else {
            self.col += 1u;
E
Elly Jones 已提交
1406
        }
1407 1408
    }

1409
    fn next_char(&mut self) -> Option<char> {
1410 1411 1412
        self.bump();
        self.ch
    }
1413 1414 1415
    fn ch_is(&self, c: char) -> bool {
        self.ch == Some(c)
    }
1416

1417 1418
    fn error<T>(&self, reason: ErrorCode) -> Result<T, ParserError> {
        Err(SyntaxError(reason, self.line, self.col))
1419 1420
    }

1421
    fn parse_whitespace(&mut self) {
1422 1423 1424 1425
        while self.ch_is(' ') ||
              self.ch_is('\n') ||
              self.ch_is('\t') ||
              self.ch_is('\r') { self.bump(); }
1426 1427
    }

1428
    fn parse_number(&mut self) -> JsonEvent {
1429
        let mut neg = false;
1430

1431
        if self.ch_is('-') {
1432
            self.bump();
1433
            neg = true;
E
Elly Jones 已提交
1434
        }
1435

1436
        let res = match self.parse_u64() {
1437 1438 1439
            Ok(res) => res,
            Err(e) => { return Error(e); }
        };
1440

1441 1442
        if self.ch_is('.') || self.ch_is('e') || self.ch_is('E') {
            let mut res = res as f64;
1443

1444 1445 1446 1447 1448 1449
            if self.ch_is('.') {
                res = match self.parse_decimal(res) {
                    Ok(res) => res,
                    Err(e) => { return Error(e); }
                };
            }
1450

1451 1452 1453 1454 1455 1456 1457
            if self.ch_is('e') || self.ch_is('E') {
                res = match self.parse_exponent(res) {
                    Ok(res) => res,
                    Err(e) => { return Error(e); }
                };
            }

1458 1459 1460 1461 1462
            if neg {
                res *= -1.0;
            }

            F64Value(res)
1463
        } else {
1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475
            if neg {
                let res = -(res as i64);

                // Make sure we didn't underflow.
                if res > 0 {
                    Error(SyntaxError(InvalidNumber, self.line, self.col))
                } else {
                    I64Value(res)
                }
            } else {
                U64Value(res)
            }
1476
        }
E
Elly Jones 已提交
1477 1478
    }

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

1483 1484 1485
        match self.ch_or_null() {
            '0' => {
                self.bump();
1486

M
mrec 已提交
1487
                // A leading '0' must be the only digit before the decimal point.
1488
                match self.ch_or_null() {
1489
                    '0' ... '9' => return self.error(InvalidNumber),
1490 1491 1492
                    _ => ()
                }
            },
1493
            '1' ... '9' => {
1494 1495
                while !self.eof() {
                    match self.ch_or_null() {
1496
                        c @ '0' ... '9' => {
1497 1498 1499 1500 1501 1502
                            accum *= 10;
                            accum += (c as u64) - ('0' as u64);

                            // Detect overflow by comparing to the last value.
                            if accum <= last_accum { return self.error(InvalidNumber); }

1503 1504 1505 1506
                            self.bump();
                        }
                        _ => break,
                    }
1507 1508
                }
            }
1509
            _ => return self.error(InvalidNumber),
E
Elly Jones 已提交
1510
        }
1511 1512

        Ok(accum)
E
Elly Jones 已提交
1513 1514
    }

A
Adolfo Ochagavía 已提交
1515
    fn parse_decimal(&mut self, mut res: f64) -> Result<f64, ParserError> {
1516 1517 1518
        self.bump();

        // Make sure a digit follows the decimal place.
1519
        match self.ch_or_null() {
1520
            '0' ... '9' => (),
1521
             _ => return self.error(InvalidNumber)
1522 1523
        }

D
Daniel Micay 已提交
1524
        let mut dec = 1.0;
1525
        while !self.eof() {
1526
            match self.ch_or_null() {
1527
                c @ '0' ... '9' => {
1528 1529 1530 1531 1532
                    dec /= 10.0;
                    res += (((c as int) - ('0' as int)) as f64) * dec;
                    self.bump();
                }
                _ => break,
E
Elly Jones 已提交
1533 1534
            }
        }
1535

1536
        Ok(res)
E
Elly Jones 已提交
1537 1538
    }

1539
    fn parse_exponent(&mut self, mut res: f64) -> Result<f64, ParserError> {
1540 1541
        self.bump();

1542 1543
        let mut exp = 0u;
        let mut neg_exp = false;
1544

1545 1546 1547 1548 1549
        if self.ch_is('+') {
            self.bump();
        } else if self.ch_is('-') {
            self.bump();
            neg_exp = true;
1550 1551 1552
        }

        // Make sure a digit follows the exponent place.
1553
        match self.ch_or_null() {
1554
            '0' ... '9' => (),
1555
            _ => return self.error(InvalidNumber)
1556 1557
        }
        while !self.eof() {
1558
            match self.ch_or_null() {
1559
                c @ '0' ... '9' => {
1560 1561
                    exp *= 10;
                    exp += (c as uint) - ('0' as uint);
1562

1563 1564 1565
                    self.bump();
                }
                _ => break
1566 1567 1568
            }
        }

1569
        let exp = 10_f64.powi(exp as i32);
1570 1571 1572 1573 1574 1575
        if neg_exp {
            res /= exp;
        } else {
            res *= exp;
        }

1576
        Ok(res)
E
Elly Jones 已提交
1577 1578
    }

1579
    fn decode_hex_escape(&mut self) -> Result<u16, ParserError> {
1580 1581
        let mut i = 0u;
        let mut n = 0u16;
A
Adolfo Ochagavía 已提交
1582
        while i < 4 && !self.eof() {
1583 1584
            self.bump();
            n = match self.ch_or_null() {
1585
                c @ '0' ... '9' => n * 16 + ((c as u16) - ('0' as u16)),
A
Adolfo Ochagavía 已提交
1586 1587 1588 1589 1590 1591
                '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,
1592
                _ => return self.error(InvalidEscape)
1593 1594 1595 1596 1597 1598
            };

            i += 1u;
        }

        // Error out if we didn't parse 4 digits.
A
Adolfo Ochagavía 已提交
1599
        if i != 4 {
1600
            return self.error(InvalidEscape);
1601 1602 1603 1604 1605
        }

        Ok(n)
    }

1606
    fn parse_str(&mut self) -> Result<string::String, ParserError> {
1607
        let mut escape = false;
1608
        let mut res = string::String::new();
1609

G
Gary Linscott 已提交
1610
        loop {
1611
            self.bump();
G
Gary Linscott 已提交
1612
            if self.eof() {
1613
                return self.error(EOFWhileParsingString);
G
Gary Linscott 已提交
1614
            }
1615

H
Huon Wilson 已提交
1616
            if escape {
1617
                match self.ch_or_null() {
1618 1619 1620 1621 1622 1623 1624 1625
                    '"' => 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'),
1626
                    'u' => match try!(self.decode_hex_escape()) {
1627 1628 1629
                        0xDC00 ... 0xDFFF => {
                            return self.error(LoneLeadingSurrogateInHexEscape)
                        }
1630 1631 1632

                        // Non-BMP characters are encoded as a sequence of
                        // two hex escapes, representing UTF-16 surrogates.
1633
                        n1 @ 0xD800 ... 0xDBFF => {
A
Adolfo Ochagavía 已提交
1634
                            match (self.next_char(), self.next_char()) {
1635
                                (Some('\\'), Some('u')) => (),
1636
                                _ => return self.error(UnexpectedEndOfHexEscape),
1637
                            }
1638

1639
                            let buf = [n1, try!(self.decode_hex_escape())];
A
Alex Crichton 已提交
1640 1641
                            match unicode_str::utf16_items(&buf).next() {
                                Some(Utf16Item::ScalarValue(c)) => res.push(c),
1642
                                _ => return self.error(LoneLeadingSurrogateInHexEscape),
1643
                            }
1644 1645
                        }

1646
                        n => match char::from_u32(n as u32) {
1647
                            Some(c) => res.push(c),
1648
                            None => return self.error(InvalidUnicodeCodePoint),
1649 1650
                        },
                    },
1651
                    _ => return self.error(InvalidEscape),
1652 1653
                }
                escape = false;
1654
            } else if self.ch_is('\\') {
1655 1656
                escape = true;
            } else {
1657
                match self.ch {
1658 1659
                    Some('"') => {
                        self.bump();
1660
                        return Ok(res);
1661
                    },
1662
                    Some(c) => res.push(c),
1663
                    None => unreachable!()
1664
                }
E
Elly Jones 已提交
1665 1666 1667 1668
            }
        }
    }

1669 1670 1671 1672
    // 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
J
Joseph Crail 已提交
1673
    // stream int the form of a stack that can be queried by the user using the
1674 1675 1676 1677
    // stack() method.
    fn parse(&mut self) -> JsonEvent {
        loop {
            // The only paths where the loop can spin a new iteration
C
Corey Farwell 已提交
1678
            // are in the cases ParseArrayComma and ParseObjectComma if ','
1679
            // is parsed. In these cases the state is set to (respectively)
1680
            // ParseArray(false) and ParseObject(false), which always return,
1681 1682 1683
            // 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();
1684

1685 1686 1687 1688
            match self.state {
                ParseStart => {
                    return self.parse_start();
                }
1689
                ParseArray(first) => {
C
Corey Farwell 已提交
1690
                    return self.parse_array(first);
1691
                }
C
Corey Farwell 已提交
1692 1693
                ParseArrayComma => {
                    match self.parse_array_comma_or_end() {
1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719
                        Some(evt) => { return evt; }
                        None => {}
                    }
                }
                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 {
1720 1721 1722 1723
            Error(_) => ParseFinished,
            ArrayStart => ParseArray(true),
            ObjectStart => ParseObject(true),
            _ => ParseBeforeFinish,
1724 1725 1726
        };
        return val;
    }
1727

C
Corey Farwell 已提交
1728
    fn parse_array(&mut self, first: bool) -> JsonEvent {
1729
        if self.ch_is(']') {
1730
            if !first {
1731
                self.error_event(InvalidSyntax)
1732
            } else {
1733 1734 1735
                self.state = if self.stack.is_empty() {
                    ParseBeforeFinish
                } else if self.stack.last_is_index() {
C
Corey Farwell 已提交
1736
                    ParseArrayComma
1737 1738
                } else {
                    ParseObjectComma
1739 1740 1741
                };
                self.bump();
                ArrayEnd
1742
            }
1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754
        } 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
1755
        }
1756
    }
1757

C
Corey Farwell 已提交
1758
    fn parse_array_comma_or_end(&mut self) -> Option<JsonEvent> {
1759 1760
        if self.ch_is(',') {
            self.stack.bump_index();
1761
            self.state = ParseArray(false);
1762
            self.bump();
1763
            None
1764 1765
        } else if self.ch_is(']') {
            self.stack.pop();
1766 1767 1768 1769
            self.state = if self.stack.is_empty() {
                ParseBeforeFinish
            } else if self.stack.last_is_index() {
                ParseArrayComma
1770
            } else {
1771 1772
                ParseObjectComma
            };
1773
            self.bump();
1774
            Some(ArrayEnd)
1775
        } else if self.eof() {
1776
            Some(self.error_event(EOFWhileParsingArray))
1777
        } else {
1778
            Some(self.error_event(InvalidSyntax))
1779
        }
E
Elly Jones 已提交
1780 1781
    }

1782 1783 1784
    fn parse_object(&mut self, first: bool) -> JsonEvent {
        if self.ch_is('}') {
            if !first {
1785 1786 1787 1788 1789
                if self.stack.is_empty() {
                    return self.error_event(TrailingComma);
                } else {
                    self.stack.pop();
                }
1790
            }
1791 1792 1793 1794
            self.state = if self.stack.is_empty() {
                ParseBeforeFinish
            } else if self.stack.last_is_index() {
                ParseArrayComma
1795
            } else {
1796 1797
                ParseObjectComma
            };
1798 1799 1800 1801 1802 1803 1804 1805 1806 1807
            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() {
1808
            Ok(s) => s,
1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820
            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);
1821 1822 1823
        self.bump();
        self.parse_whitespace();

1824
        let val = self.parse_value();
1825

1826
        self.state = match val {
1827 1828 1829 1830
            Error(_) => ParseFinished,
            ArrayStart => ParseArray(true),
            ObjectStart => ParseObject(true),
            _ => ParseObjectComma,
1831 1832 1833 1834 1835
        };
        return val;
    }

    fn parse_object_end(&mut self) -> JsonEvent {
1836
        if self.ch_is('}') {
1837 1838 1839 1840
            self.state = if self.stack.is_empty() {
                ParseBeforeFinish
            } else if self.stack.last_is_index() {
                ParseArrayComma
1841
            } else {
1842 1843
                ParseObjectComma
            };
1844
            self.bump();
A
Adolfo Ochagavía 已提交
1845
            ObjectEnd
1846
        } else if self.eof() {
A
Adolfo Ochagavía 已提交
1847
            self.error_event(EOFWhileParsingObject)
1848
        } else {
A
Adolfo Ochagavía 已提交
1849
            self.error_event(InvalidSyntax)
1850
        }
1851
    }
1852

1853 1854 1855
    fn parse_value(&mut self) -> JsonEvent {
        if self.eof() { return self.error_event(EOFWhileParsingValue); }
        match self.ch_or_null() {
A
Adolfo Ochagavía 已提交
1856 1857 1858
            'n' => { self.parse_ident("ull", NullValue) }
            't' => { self.parse_ident("rue", BooleanValue(true)) }
            'f' => { self.parse_ident("alse", BooleanValue(false)) }
1859
            '0' ... '9' | '-' => self.parse_number(),
A
Adolfo Ochagavía 已提交
1860
            '"' => match self.parse_str() {
1861 1862 1863 1864 1865
                Ok(s) => StringValue(s),
                Err(e) => Error(e),
            },
            '[' => {
                self.bump();
C
Corey Farwell 已提交
1866
                ArrayStart
1867 1868 1869
            }
            '{' => {
                self.bump();
A
Adolfo Ochagavía 已提交
1870
                ObjectStart
1871
            }
A
Adolfo Ochagavía 已提交
1872
            _ => { self.error_event(InvalidSyntax) }
1873 1874
        }
    }
1875

1876 1877 1878 1879 1880 1881 1882 1883
    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))
        }
    }
1884

1885 1886 1887 1888 1889
    fn error_event(&mut self, reason: ErrorCode) -> JsonEvent {
        self.state = ParseFinished;
        Error(SyntaxError(reason, self.line, self.col))
    }
}
1890

1891 1892 1893 1894 1895
/// A Builder consumes a json::Parser to create a generic Json structure.
pub struct Builder<T> {
    parser: Parser<T>,
    token: Option<JsonEvent>,
}
1896

J
Jorge Aparicio 已提交
1897
impl<T: Iterator<Item=char>> Builder<T> {
1898 1899
    /// Create a JSON Builder.
    pub fn new(src: T) -> Builder<T> {
A
Adolfo Ochagavía 已提交
1900
        Builder { parser: Parser::new(src), token: None, }
1901 1902 1903 1904 1905 1906 1907 1908 1909 1910
    }

    // 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 => {}
            Some(Error(e)) => { return Err(e); }
S
Steve Klabnik 已提交
1911
            ref tok => { panic!("unexpected token {}", tok.clone()); }
1912
        }
A
Adolfo Ochagavía 已提交
1913
        result
1914 1915 1916 1917 1918 1919 1920
    }

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

    fn build_value(&mut self) -> Result<Json, BuilderError> {
1921 1922 1923 1924 1925 1926
        return match self.token {
            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)),
1927
            Some(StringValue(ref mut s)) => {
1928
                let mut temp = string::String::new();
1929
                swap(s, &mut temp);
1930
                Ok(Json::String(temp))
1931
            }
1932 1933 1934 1935 1936 1937
            Some(Error(e)) => Err(e),
            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),
1938 1939
        }
    }
1940

C
Corey Farwell 已提交
1941
    fn build_array(&mut self) -> Result<Json, BuilderError> {
1942 1943 1944 1945
        self.bump();
        let mut values = Vec::new();

        loop {
C
Corey Farwell 已提交
1946
            if self.token == Some(ArrayEnd) {
1947
                return Ok(Json::Array(values.into_iter().collect()));
1948 1949 1950 1951
            }
            match self.build_value() {
                Ok(v) => values.push(v),
                Err(e) => { return Err(e) }
1952
            }
1953
            self.bump();
1954
        }
1955
    }
1956

1957 1958 1959
    fn build_object(&mut self) -> Result<Json, BuilderError> {
        self.bump();

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

A
Adolfo Ochagavía 已提交
1962
        loop {
1963
            match self.token {
1964
                Some(ObjectEnd) => { return Ok(Json::Object(values)); }
1965 1966 1967 1968 1969
                Some(Error(e)) => { return Err(e); }
                None => { break; }
                _ => {}
            }
            let key = match self.parser.stack().top() {
1970
                Some(Key(k)) => { k.to_string() }
S
Steve Klabnik 已提交
1971
                _ => { panic!("invalid state"); }
1972 1973 1974 1975 1976 1977 1978 1979
            };
            match self.build_value() {
                Ok(value) => { values.insert(key, value); }
                Err(e) => { return Err(e); }
            }
            self.bump();
        }
        return self.parser.error(EOFWhileParsingObject);
L
Lenny222 已提交
1980 1981 1982
    }
}

A
Alex Crichton 已提交
1983
/// Decodes a json value from an `&mut io::Reader`
1984
pub fn from_reader(rdr: &mut io::Reader) -> Result<Json, BuilderError> {
A
Alex Crichton 已提交
1985
    let contents = match rdr.read_to_end() {
1986
        Ok(c)  => c,
1987
        Err(e) => return Err(io_error_to_error(e))
A
Alex Crichton 已提交
1988
    };
A
Alex Crichton 已提交
1989
    let s = match str::from_utf8(contents.as_slice()).ok() {
1990 1991
        Some(s) => s,
        _       => return Err(SyntaxError(NotUtf8, 0, 0))
A
Alex Crichton 已提交
1992
    };
1993
    let mut builder = Builder::new(s.chars());
1994
    builder.build()
E
Elly Jones 已提交
1995 1996
}

1997
/// Decodes a json value from a string
1998 1999
pub fn from_str(s: &str) -> Result<Json, BuilderError> {
    let mut builder = Builder::new(s.chars());
A
Adolfo Ochagavía 已提交
2000
    builder.build()
2001 2002
}

2003
/// A structure to decode JSON to values in rust.
2004
pub struct Decoder {
2005
    stack: Vec<Json>,
2006 2007
}

2008 2009
impl Decoder {
    /// Creates a new decoder instance for decoding the specified JSON value.
2010
    pub fn new(json: Json) -> Decoder {
A
Adolfo Ochagavía 已提交
2011
        Decoder { stack: vec![json] }
2012
    }
2013 2014
}

2015
impl Decoder {
S
Sean McArthur 已提交
2016 2017
    fn pop(&mut self) -> Json {
        self.stack.pop().unwrap()
2018 2019 2020
    }
}

2021
macro_rules! expect {
S
Sean McArthur 已提交
2022 2023
    ($e:expr, Null) => ({
        match $e {
2024
            Json::Null => Ok(()),
A
Alex Crichton 已提交
2025
            other => Err(ExpectedError("Null".to_string(),
A
Alex Crichton 已提交
2026
                                       format!("{}", other)))
S
Sean McArthur 已提交
2027 2028 2029 2030
        }
    });
    ($e:expr, $t:ident) => ({
        match $e {
2031
            Json::$t(v) => Ok(v),
2032
            other => {
2033
                Err(ExpectedError(stringify!($t).to_string(),
A
Alex Crichton 已提交
2034
                                  format!("{}", other)))
2035
            }
2036
        }
S
Sean McArthur 已提交
2037
    })
2038
}
S
Sean McArthur 已提交
2039

2040 2041 2042 2043
macro_rules! read_primitive {
    ($name:ident, $ty:ty) => {
        fn $name(&mut self) -> DecodeResult<$ty> {
            match self.pop() {
B
Barosl Lee 已提交
2044 2045
                Json::I64(f) => match num::cast(f) {
                    Some(f) => Ok(f),
A
Alex Crichton 已提交
2046
                    None => Err(ExpectedError("Number".to_string(), format!("{}", f))),
2047
                },
B
Barosl Lee 已提交
2048 2049
                Json::U64(f) => match num::cast(f) {
                    Some(f) => Ok(f),
A
Alex Crichton 已提交
2050
                    None => Err(ExpectedError("Number".to_string(), format!("{}", f))),
B
Barosl Lee 已提交
2051
                },
A
Alex Crichton 已提交
2052
                Json::F64(f) => Err(ExpectedError("Integer".to_string(), format!("{}", f))),
B
Barosl Lee 已提交
2053 2054 2055 2056
                // re: #12967.. a type w/ numeric keys (ie HashMap<uint, V> etc)
                // is going to have a string here, as per JSON spec.
                Json::String(s) => match std::str::from_str(s.as_slice()) {
                    Some(f) => Ok(f),
A
Alex Crichton 已提交
2057
                    None => Err(ExpectedError("Number".to_string(), s)),
2058
                },
A
Alex Crichton 已提交
2059
                value => Err(ExpectedError("Number".to_string(), format!("{}", value))),
2060 2061 2062 2063 2064
            }
        }
    }
}

2065
impl ::Decoder<DecoderError> for Decoder {
S
Sean McArthur 已提交
2066
    fn read_nil(&mut self) -> DecodeResult<()> {
A
Adolfo Ochagavía 已提交
2067
        expect!(self.pop(), Null)
2068 2069
    }

2070 2071 2072 2073 2074 2075 2076 2077 2078 2079
    read_primitive! { read_uint, uint }
    read_primitive! { read_u8, u8 }
    read_primitive! { read_u16, u16 }
    read_primitive! { read_u32, u32 }
    read_primitive! { read_u64, u64 }
    read_primitive! { read_int, int }
    read_primitive! { read_i8, i8 }
    read_primitive! { read_i16, i16 }
    read_primitive! { read_i32, i32 }
    read_primitive! { read_i64, i64 }
2080

2081
    fn read_f32(&mut self) -> DecodeResult<f32> { self.read_f64().map(|x| x as f32) }
2082

S
Sean McArthur 已提交
2083 2084
    fn read_f64(&mut self) -> DecodeResult<f64> {
        match self.pop() {
2085 2086 2087 2088
            Json::I64(f) => Ok(f as f64),
            Json::U64(f) => Ok(f as f64),
            Json::F64(f) => Ok(f),
            Json::String(s) => {
2089
                // re: #12967.. a type w/ numeric keys (ie HashMap<uint, V> etc)
A
Adolfo Ochagavía 已提交
2090
                // is going to have a string here, as per JSON spec.
A
Alex Crichton 已提交
2091
                match s.parse() {
2092
                    Some(f) => Ok(f),
A
Alex Crichton 已提交
2093
                    None => Err(ExpectedError("Number".to_string(), s)),
2094
                }
2095
            },
2096
            Json::Null => Ok(f64::NAN),
A
Alex Crichton 已提交
2097
            value => Err(ExpectedError("Number".to_string(), format!("{}", value)))
2098 2099
        }
    }
2100

2101 2102 2103
    fn read_bool(&mut self) -> DecodeResult<bool> {
        expect!(self.pop(), Boolean)
    }
2104

S
Sean McArthur 已提交
2105 2106
    fn read_char(&mut self) -> DecodeResult<char> {
        let s = try!(self.read_str());
2107
        {
2108
            let mut it = s.chars();
2109 2110
            match (it.next(), it.next()) {
                // exactly one character
S
Sean McArthur 已提交
2111
                (Some(c), None) => return Ok(c),
2112 2113 2114
                _ => ()
            }
        }
A
Alex Crichton 已提交
2115
        Err(ExpectedError("single character string".to_string(), format!("{}", s)))
2116 2117
    }

2118
    fn read_str(&mut self) -> DecodeResult<string::String> {
A
Adolfo Ochagavía 已提交
2119
        expect!(self.pop(), String)
2120 2121
    }

E
Erick Tryzelaar 已提交
2122
    fn read_enum<T, F>(&mut self, _name: &str, f: F) -> DecodeResult<T> where
2123 2124
        F: FnOnce(&mut Decoder) -> DecodeResult<T>,
    {
2125 2126 2127
        f(self)
    }

2128 2129 2130
    fn read_enum_variant<T, F>(&mut self, names: &[&str],
                               mut f: F) -> DecodeResult<T>
        where F: FnMut(&mut Decoder, uint) -> DecodeResult<T>,
2131
    {
S
Sean McArthur 已提交
2132
        let name = match self.pop() {
2133 2134
            Json::String(s) => s,
            Json::Object(mut o) => {
A
Alex Crichton 已提交
2135
                let n = match o.remove(&"variant".to_string()) {
2136
                    Some(Json::String(s)) => s,
2137
                    Some(val) => {
A
Alex Crichton 已提交
2138
                        return Err(ExpectedError("String".to_string(), format!("{}", val)))
2139 2140
                    }
                    None => {
A
Alex Crichton 已提交
2141
                        return Err(MissingFieldError("variant".to_string()))
2142
                    }
2143
                };
A
Alex Crichton 已提交
2144
                match o.remove(&"fields".to_string()) {
2145
                    Some(Json::Array(l)) => {
A
Aaron Turon 已提交
2146
                        for field in l.into_iter().rev() {
A
Adolfo Ochagavía 已提交
2147
                            self.stack.push(field);
2148 2149
                        }
                    },
2150
                    Some(val) => {
A
Alex Crichton 已提交
2151
                        return Err(ExpectedError("Array".to_string(), format!("{}", val)))
2152 2153
                    }
                    None => {
A
Alex Crichton 已提交
2154
                        return Err(MissingFieldError("fields".to_string()))
2155
                    }
2156
                }
2157
                n
2158
            }
2159
            json => {
A
Alex Crichton 已提交
2160
                return Err(ExpectedError("String or Object".to_string(), format!("{}", json)))
2161
            }
2162
        };
A
Alex Crichton 已提交
2163
        let idx = match names.iter().position(|n| *n == name[]) {
2164
            Some(idx) => idx,
S
Sean McArthur 已提交
2165
            None => return Err(UnknownVariantError(name))
2166 2167 2168 2169
        };
        f(self, idx)
    }

E
Erick Tryzelaar 已提交
2170
    fn read_enum_variant_arg<T, F>(&mut self, _idx: uint, f: F) -> DecodeResult<T> where
2171 2172
        F: FnOnce(&mut Decoder) -> DecodeResult<T>,
    {
2173 2174 2175
        f(self)
    }

2176
    fn read_enum_struct_variant<T, F>(&mut self, names: &[&str], f: F) -> DecodeResult<T> where
2177
        F: FnMut(&mut Decoder, uint) -> DecodeResult<T>,
2178
    {
2179 2180 2181 2182
        self.read_enum_variant(names, f)
    }


2183
    fn read_enum_struct_variant_field<T, F>(&mut self,
E
Erick Tryzelaar 已提交
2184
                                         _name: &str,
2185
                                         idx: uint,
2186 2187 2188 2189
                                         f: F)
                                         -> DecodeResult<T> where
        F: FnOnce(&mut Decoder) -> DecodeResult<T>,
    {
2190 2191 2192
        self.read_enum_variant_arg(idx, f)
    }

E
Erick Tryzelaar 已提交
2193
    fn read_struct<T, F>(&mut self, _name: &str, _len: uint, f: F) -> DecodeResult<T> where
2194 2195
        F: FnOnce(&mut Decoder) -> DecodeResult<T>,
    {
S
Sean McArthur 已提交
2196 2197 2198
        let value = try!(f(self));
        self.pop();
        Ok(value)
2199 2200
    }

2201 2202
    fn read_struct_field<T, F>(&mut self,
                               name: &str,
E
Erick Tryzelaar 已提交
2203
                               _idx: uint,
2204 2205 2206 2207
                               f: F)
                               -> DecodeResult<T> where
        F: FnOnce(&mut Decoder) -> DecodeResult<T>,
    {
S
Sean McArthur 已提交
2208 2209
        let mut obj = try!(expect!(self.pop(), Object));

2210
        let value = match obj.remove(&name.to_string()) {
2211 2212 2213
            None => {
                // Add a Null and try to parse it as an Option<_>
                // to get None as a default value.
2214
                self.stack.push(Json::Null);
2215 2216 2217 2218 2219
                match f(self) {
                    Ok(x) => x,
                    Err(_) => return Err(MissingFieldError(name.to_string())),
                }
            },
S
Sean McArthur 已提交
2220 2221 2222
            Some(json) => {
                self.stack.push(json);
                try!(f(self))
2223
            }
S
Sean McArthur 已提交
2224
        };
2225
        self.stack.push(Json::Object(obj));
S
Sean McArthur 已提交
2226
        Ok(value)
2227 2228
    }

2229 2230 2231 2232
    fn read_tuple<T, F>(&mut self, tuple_len: uint, f: F) -> DecodeResult<T> where
        F: FnOnce(&mut Decoder) -> DecodeResult<T>,
    {
        self.read_seq(move |d, len| {
2233 2234 2235 2236 2237
            if len == tuple_len {
                f(d)
            } else {
                Err(ExpectedError(format!("Tuple{}", tuple_len), format!("Tuple{}", len)))
            }
2238
        })
2239 2240
    }

2241 2242 2243
    fn read_tuple_arg<T, F>(&mut self, idx: uint, f: F) -> DecodeResult<T> where
        F: FnOnce(&mut Decoder) -> DecodeResult<T>,
    {
2244 2245 2246
        self.read_seq_elt(idx, f)
    }

2247
    fn read_tuple_struct<T, F>(&mut self,
E
Erick Tryzelaar 已提交
2248
                               _name: &str,
2249 2250 2251 2252 2253
                               len: uint,
                               f: F)
                               -> DecodeResult<T> where
        F: FnOnce(&mut Decoder) -> DecodeResult<T>,
    {
2254
        self.read_tuple(len, f)
2255 2256
    }

2257 2258 2259 2260 2261 2262
    fn read_tuple_struct_arg<T, F>(&mut self,
                                   idx: uint,
                                   f: F)
                                   -> DecodeResult<T> where
        F: FnOnce(&mut Decoder) -> DecodeResult<T>,
    {
2263 2264 2265
        self.read_tuple_arg(idx, f)
    }

2266 2267
    fn read_option<T, F>(&mut self, mut f: F) -> DecodeResult<T> where
        F: FnMut(&mut Decoder, bool) -> DecodeResult<T>,
2268
    {
S
Sean McArthur 已提交
2269
        match self.pop() {
2270
            Json::Null => f(self, false),
2271 2272 2273 2274
            value => { self.stack.push(value); f(self, true) }
        }
    }

2275 2276 2277
    fn read_seq<T, F>(&mut self, f: F) -> DecodeResult<T> where
        F: FnOnce(&mut Decoder, uint) -> DecodeResult<T>,
    {
C
Corey Farwell 已提交
2278 2279 2280
        let array = try!(expect!(self.pop(), Array));
        let len = array.len();
        for v in array.into_iter().rev() {
S
Sean McArthur 已提交
2281 2282
            self.stack.push(v);
        }
2283 2284 2285
        f(self, len)
    }

E
Erick Tryzelaar 已提交
2286
    fn read_seq_elt<T, F>(&mut self, _idx: uint, f: F) -> DecodeResult<T> where
2287 2288
        F: FnOnce(&mut Decoder) -> DecodeResult<T>,
    {
2289 2290 2291
        f(self)
    }

2292 2293 2294
    fn read_map<T, F>(&mut self, f: F) -> DecodeResult<T> where
        F: FnOnce(&mut Decoder, uint) -> DecodeResult<T>,
    {
S
Sean McArthur 已提交
2295 2296
        let obj = try!(expect!(self.pop(), Object));
        let len = obj.len();
A
Aaron Turon 已提交
2297
        for (key, value) in obj.into_iter() {
S
Sean McArthur 已提交
2298
            self.stack.push(value);
2299
            self.stack.push(Json::String(key));
S
Sean McArthur 已提交
2300
        }
2301 2302 2303
        f(self, len)
    }

E
Erick Tryzelaar 已提交
2304
    fn read_map_elt_key<T, F>(&mut self, _idx: uint, f: F) -> DecodeResult<T> where
2305 2306
       F: FnOnce(&mut Decoder) -> DecodeResult<T>,
    {
2307 2308 2309
        f(self)
    }

E
Erick Tryzelaar 已提交
2310
    fn read_map_elt_val<T, F>(&mut self, _idx: uint, f: F) -> DecodeResult<T> where
2311 2312
       F: FnOnce(&mut Decoder) -> DecodeResult<T>,
    {
2313 2314
        f(self)
    }
2315 2316 2317 2318

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

2321
/// A trait for converting values to JSON
J
Jorge Aparicio 已提交
2322
pub trait ToJson for Sized? {
2323 2324 2325
    /// Converts the value of `self` to an instance of JSON
    fn to_json(&self) -> Json;
}
2326

2327
macro_rules! to_json_impl_i64 {
2328 2329
    ($($t:ty), +) => (
        $(impl ToJson for $t {
2330
            fn to_json(&self) -> Json { Json::I64(*self as i64) }
2331 2332
        })+
    )
2333
}
2334

2335
to_json_impl_i64! { int, i8, i16, i32, i64 }
2336

2337
macro_rules! to_json_impl_u64 {
A
Adolfo Ochagavía 已提交
2338 2339
    ($($t:ty), +) => (
        $(impl ToJson for $t {
2340
            fn to_json(&self) -> Json { Json::U64(*self as u64) }
A
Adolfo Ochagavía 已提交
2341 2342
        })+
    )
2343
}
2344

2345
to_json_impl_u64! { uint, u8, u16, u32, u64 }
2346

A
Adolfo Ochagavía 已提交
2347 2348
impl ToJson for Json {
    fn to_json(&self) -> Json { self.clone() }
2349 2350
}

2351
impl ToJson for f32 {
M
mrec 已提交
2352
    fn to_json(&self) -> Json { (*self as f64).to_json() }
2353 2354
}

2355
impl ToJson for f64 {
M
mrec 已提交
2356 2357
    fn to_json(&self) -> Json {
        match self.classify() {
T
Tobias Bucher 已提交
2358
            Fp::Nan | Fp::Infinite => Json::Null,
2359
            _                  => Json::F64(*self)
M
mrec 已提交
2360 2361
        }
    }
2362 2363
}

2364
impl ToJson for () {
2365
    fn to_json(&self) -> Json { Json::Null }
2366 2367
}

2368
impl ToJson for bool {
2369
    fn to_json(&self) -> Json { Json::Boolean(*self) }
2370 2371
}

2372
impl ToJson for str {
A
Alex Crichton 已提交
2373
    fn to_json(&self) -> Json { Json::String(self.to_string()) }
2374 2375
}

2376
impl ToJson for string::String {
2377
    fn to_json(&self) -> Json { Json::String((*self).clone()) }
2378 2379
}

2380 2381 2382 2383 2384 2385 2386 2387 2388
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]
2389
            #[allow(non_snake_case)]
2390 2391
            fn to_json(&self) -> Json {
                match *self {
2392
                    ($(ref $tyvar),*,) => Json::Array(vec![$($tyvar.to_json()),*])
2393
                }
A
Adolfo Ochagavía 已提交
2394
            }
2395
        }
2396 2397 2398
    }
}

2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410
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}
2411

J
Jorge Aparicio 已提交
2412
impl<A: ToJson> ToJson for [A] {
2413
    fn to_json(&self) -> Json { Json::Array(self.iter().map(|elt| elt.to_json()).collect()) }
2414 2415
}

A
Adolfo Ochagavía 已提交
2416
impl<A: ToJson> ToJson for Vec<A> {
2417
    fn to_json(&self) -> Json { Json::Array(self.iter().map(|elt| elt.to_json()).collect()) }
2418 2419
}

A
Alexis Beingessner 已提交
2420
impl<A: ToJson> ToJson for BTreeMap<string::String, A> {
B
Ben Striegel 已提交
2421
    fn to_json(&self) -> Json {
A
Alexis Beingessner 已提交
2422
        let mut d = BTreeMap::new();
D
Daniel Micay 已提交
2423
        for (key, value) in self.iter() {
2424
            d.insert((*key).clone(), value.to_json());
2425
        }
2426
        Json::Object(d)
2427 2428 2429
    }
}

2430
impl<A: ToJson> ToJson for HashMap<string::String, A> {
G
Graydon Hoare 已提交
2431
    fn to_json(&self) -> Json {
A
Alexis Beingessner 已提交
2432
        let mut d = BTreeMap::new();
D
Daniel Micay 已提交
2433
        for (key, value) in self.iter() {
2434
            d.insert((*key).clone(), value.to_json());
G
Graydon Hoare 已提交
2435
        }
2436
        Json::Object(d)
G
Graydon Hoare 已提交
2437 2438 2439
    }
}

2440
impl<A:ToJson> ToJson for Option<A> {
B
Ben Striegel 已提交
2441 2442
    fn to_json(&self) -> Json {
        match *self {
2443
            None => Json::Null,
A
Adolfo Ochagavía 已提交
2444
            Some(ref value) => value.to_json()
2445 2446 2447 2448
        }
    }
}

2449 2450 2451 2452 2453 2454 2455 2456 2457 2458
struct FormatShim<'a, 'b: 'a> {
    inner: &'a mut fmt::Formatter<'b>,
}

impl<'a, 'b> fmt::Writer for FormatShim<'a, 'b> {
    fn write_str(&mut self, s: &str) -> fmt::Result {
        self.inner.write_str(s)
    }
}

2459
impl fmt::Show for Json {
2460
    /// Encodes a json value into a string
2461
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507
        let mut shim = FormatShim { inner: f };
        let mut encoder = Encoder::new(&mut shim);
        self.encode(&mut encoder)
    }
}

impl<'a> fmt::Show for PrettyJson<'a> {
    /// Encodes a json value into a string
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let mut shim = FormatShim { inner: f };
        let mut encoder = PrettyEncoder::new(&mut shim);
        self.inner.encode(&mut encoder)
    }
}

impl<'a, T> fmt::Show for AsJson<'a, T>
    where T: for<'b> Encodable<Encoder<'b>, fmt::Error>
{
    /// Encodes a json value into a string
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let mut shim = FormatShim { inner: f };
        let mut encoder = Encoder::new(&mut shim);
        self.inner.encode(&mut encoder)
    }
}

impl<'a, T> AsPrettyJson<'a, T> {
    /// Set the indentation level for the emitted JSON
    pub fn indent(mut self, indent: uint) -> AsPrettyJson<'a, T> {
        self.indent = Some(indent);
        self
    }
}

impl<'a, T> fmt::Show for AsPrettyJson<'a, T>
    where T: for<'b> Encodable<PrettyEncoder<'b>, fmt::Error>
{
    /// Encodes a json value into a string
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let mut shim = FormatShim { inner: f };
        let mut encoder = PrettyEncoder::new(&mut shim);
        match self.indent {
            Some(n) => encoder.set_indent(n),
            None => {}
        }
        self.inner.encode(&mut encoder)
2508
    }
2509 2510
}

B
Brendan Zabarauskas 已提交
2511
impl FromStr for Json {
A
Adolfo Ochagavía 已提交
2512 2513 2514 2515 2516
    fn from_str(s: &str) -> Option<Json> {
        from_str(s).ok()
    }
}

2517 2518
#[cfg(test)]
mod tests {
2519
    extern crate test;
S
Steven Fackler 已提交
2520 2521
    use self::Animal::*;
    use self::DecodeEnum::*;
2522
    use self::test::Bencher;
A
Alex Crichton 已提交
2523
    use {Encodable, Decodable};
2524 2525 2526 2527 2528 2529
    use super::Json::*;
    use super::ErrorCode::*;
    use super::ParserError::*;
    use super::DecoderError::*;
    use super::JsonEvent::*;
    use super::StackElement::*;
2530 2531 2532
    use super::{Json, from_str, DecodeResult, DecoderError, JsonEvent, Parser,
                StackElement, Stack, Decoder};
    use std::{i64, u64, f32, f64};
A
Alexis Beingessner 已提交
2533
    use std::collections::BTreeMap;
2534
    use std::num::Float;
2535
    use std::string;
2536

2537
    #[derive(RustcDecodable, Eq, PartialEq, Show)]
2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558
    struct OptionData {
        opt: Option<uint>,
    }

    #[test]
    fn test_decode_option_none() {
        let s ="{}";
        let obj: OptionData = super::decode(s).unwrap();
        assert_eq!(obj, OptionData { opt: None });
    }

    #[test]
    fn test_decode_option_some() {
        let s = "{ \"opt\": 10 }";
        let obj: OptionData = super::decode(s).unwrap();
        assert_eq!(obj, OptionData { opt: Some(10u) });
    }

    #[test]
    fn test_decode_option_malformed() {
        check_err::<OptionData>("{ \"opt\": [] }",
A
Alex Crichton 已提交
2559
                                ExpectedError("Number".to_string(), "[]".to_string()));
2560
        check_err::<OptionData>("{ \"opt\": false }",
A
Alex Crichton 已提交
2561
                                ExpectedError("Number".to_string(), "false".to_string()));
2562 2563
    }

2564
    #[derive(PartialEq, RustcEncodable, RustcDecodable, Show)]
2565 2566
    enum Animal {
        Dog,
2567
        Frog(string::String, int)
2568 2569
    }

2570
    #[derive(PartialEq, RustcEncodable, RustcDecodable, Show)]
2571 2572 2573
    struct Inner {
        a: (),
        b: uint,
2574
        c: Vec<string::String>,
2575 2576
    }

2577
    #[derive(PartialEq, RustcEncodable, RustcDecodable, Show)]
2578
    struct Outer {
K
Kevin Ballard 已提交
2579
        inner: Vec<Inner>,
2580 2581
    }

2582
    fn mk_object(items: &[(string::String, Json)]) -> Json {
A
Alexis Beingessner 已提交
2583
        let mut d = BTreeMap::new();
2584

D
Daniel Micay 已提交
2585
        for item in items.iter() {
2586
            match *item {
2587
                (ref key, ref value) => { d.insert((*key).clone(), (*value).clone()); },
2588
            }
2589 2590
        };

L
Luqman Aden 已提交
2591
        Object(d)
2592 2593
    }

A
Adolfo Ochagavía 已提交
2594 2595 2596
    #[test]
    fn test_from_str_trait() {
        let s = "null";
2597
        assert!(s.parse::<Json>().unwrap() == s.parse().unwrap());
A
Adolfo Ochagavía 已提交
2598 2599
    }

2600 2601
    #[test]
    fn test_write_null() {
B
Barosl Lee 已提交
2602
        assert_eq!(Null.to_string(), "null");
2603
        assert_eq!(Null.pretty().to_string(), "null");
2604 2605
    }

2606 2607
    #[test]
    fn test_write_i64() {
B
Barosl Lee 已提交
2608
        assert_eq!(U64(0).to_string(), "0");
2609
        assert_eq!(U64(0).pretty().to_string(), "0");
2610

B
Barosl Lee 已提交
2611
        assert_eq!(U64(1234).to_string(), "1234");
2612
        assert_eq!(U64(1234).pretty().to_string(), "1234");
2613

B
Barosl Lee 已提交
2614
        assert_eq!(I64(-5678).to_string(), "-5678");
2615
        assert_eq!(I64(-5678).pretty().to_string(), "-5678");
2616 2617

        assert_eq!(U64(7650007200025252000).to_string(), "7650007200025252000");
2618
        assert_eq!(U64(7650007200025252000).pretty().to_string(), "7650007200025252000");
2619
    }
2620

2621
    #[test]
2622
    fn test_write_f64() {
B
Barosl Lee 已提交
2623
        assert_eq!(F64(3.0).to_string(), "3.0");
2624
        assert_eq!(F64(3.0).pretty().to_string(), "3.0");
2625

B
Barosl Lee 已提交
2626
        assert_eq!(F64(3.1).to_string(), "3.1");
2627
        assert_eq!(F64(3.1).pretty().to_string(), "3.1");
2628

B
Barosl Lee 已提交
2629
        assert_eq!(F64(-1.5).to_string(), "-1.5");
2630
        assert_eq!(F64(-1.5).pretty().to_string(), "-1.5");
2631

B
Barosl Lee 已提交
2632
        assert_eq!(F64(0.5).to_string(), "0.5");
2633
        assert_eq!(F64(0.5).pretty().to_string(), "0.5");
M
mrec 已提交
2634

B
Barosl Lee 已提交
2635
        assert_eq!(F64(f64::NAN).to_string(), "null");
2636
        assert_eq!(F64(f64::NAN).pretty().to_string(), "null");
M
mrec 已提交
2637

B
Barosl Lee 已提交
2638
        assert_eq!(F64(f64::INFINITY).to_string(), "null");
2639
        assert_eq!(F64(f64::INFINITY).pretty().to_string(), "null");
M
mrec 已提交
2640

B
Barosl Lee 已提交
2641
        assert_eq!(F64(f64::NEG_INFINITY).to_string(), "null");
2642
        assert_eq!(F64(f64::NEG_INFINITY).pretty().to_string(), "null");
2643 2644 2645 2646
    }

    #[test]
    fn test_write_str() {
A
Alex Crichton 已提交
2647
        assert_eq!(String("".to_string()).to_string(), "\"\"");
2648
        assert_eq!(String("".to_string()).pretty().to_string(), "\"\"");
2649

A
Alex Crichton 已提交
2650
        assert_eq!(String("homura".to_string()).to_string(), "\"homura\"");
2651
        assert_eq!(String("madoka".to_string()).pretty().to_string(), "\"madoka\"");
2652 2653 2654 2655
    }

    #[test]
    fn test_write_bool() {
B
Barosl Lee 已提交
2656
        assert_eq!(Boolean(true).to_string(), "true");
2657
        assert_eq!(Boolean(true).pretty().to_string(), "true");
2658

B
Barosl Lee 已提交
2659
        assert_eq!(Boolean(false).to_string(), "false");
2660
        assert_eq!(Boolean(false).pretty().to_string(), "false");
2661 2662 2663
    }

    #[test]
C
Corey Farwell 已提交
2664
    fn test_write_array() {
B
Barosl Lee 已提交
2665
        assert_eq!(Array(vec![]).to_string(), "[]");
2666
        assert_eq!(Array(vec![]).pretty().to_string(), "[]");
2667

B
Barosl Lee 已提交
2668
        assert_eq!(Array(vec![Boolean(true)]).to_string(), "[true]");
2669
        assert_eq!(
2670
            Array(vec![Boolean(true)]).pretty().to_string(),
2671
            "\
2672 2673
            [\n  \
                true\n\
2674
            ]"
2675
        );
2676

C
Corey Farwell 已提交
2677
        let long_test_array = Array(vec![
2678 2679
            Boolean(false),
            Null,
A
Alex Crichton 已提交
2680
            Array(vec![String("foo\nbar".to_string()), F64(3.5)])]);
2681

B
Barosl Lee 已提交
2682
        assert_eq!(long_test_array.to_string(),
2683
            "[false,null,[\"foo\\nbar\",3.5]]");
2684
        assert_eq!(
2685
            long_test_array.pretty().to_string(),
2686
            "\
2687 2688 2689 2690 2691 2692 2693
            [\n  \
                false,\n  \
                null,\n  \
                [\n    \
                    \"foo\\nbar\",\n    \
                    3.5\n  \
                ]\n\
2694
            ]"
2695 2696 2697
        );
    }

2698
    #[test]
2699
    fn test_write_object() {
B
Barosl Lee 已提交
2700
        assert_eq!(mk_object(&[]).to_string(), "{}");
2701
        assert_eq!(mk_object(&[]).pretty().to_string(), "{}");
2702

2703
        assert_eq!(
N
Nick Cameron 已提交
2704
            mk_object(&[
A
Alex Crichton 已提交
2705
                ("a".to_string(), Boolean(true))
B
Barosl Lee 已提交
2706
            ]).to_string(),
2707
            "{\"a\":true}"
2708
        );
2709
        assert_eq!(
2710
            mk_object(&[("a".to_string(), Boolean(true))]).pretty().to_string(),
2711
            "\
2712 2713
            {\n  \
                \"a\": true\n\
2714
            }"
2715 2716
        );

N
Nick Cameron 已提交
2717
        let complex_obj = mk_object(&[
A
Alex Crichton 已提交
2718 2719 2720
                ("b".to_string(), Array(vec![
                    mk_object(&[("c".to_string(), String("\x0c\r".to_string()))]),
                    mk_object(&[("d".to_string(), String("".to_string()))])
2721
                ]))
2722 2723 2724
            ]);

        assert_eq!(
B
Barosl Lee 已提交
2725
            complex_obj.to_string(),
2726
            "{\
2727 2728 2729 2730
                \"b\":[\
                    {\"c\":\"\\f\\r\"},\
                    {\"d\":\"\"}\
                ]\
2731
            }"
2732 2733
        );
        assert_eq!(
2734
            complex_obj.pretty().to_string(),
2735
            "\
2736 2737 2738 2739 2740 2741 2742 2743 2744
            {\n  \
                \"b\": [\n    \
                    {\n      \
                        \"c\": \"\\f\\r\"\n    \
                    },\n    \
                    {\n      \
                        \"d\": \"\"\n    \
                    }\n  \
                ]\n\
2745
            }"
2746
        );
2747

N
Nick Cameron 已提交
2748
        let a = mk_object(&[
A
Alex Crichton 已提交
2749 2750 2751 2752
            ("a".to_string(), Boolean(true)),
            ("b".to_string(), Array(vec![
                mk_object(&[("c".to_string(), String("\x0c\r".to_string()))]),
                mk_object(&[("d".to_string(), String("".to_string()))])
2753
            ]))
G
Graydon Hoare 已提交
2754
        ]);
2755

2756 2757
        // We can't compare the strings directly because the object fields be
        // printed in a different order.
2758 2759
        assert_eq!(a.clone(), a.to_string().parse().unwrap());
        assert_eq!(a.clone(), a.pretty().to_string().parse().unwrap());
A
Alex Crichton 已提交
2760 2761
    }

2762
    #[test]
2763
    fn test_write_enum() {
2764
        let animal = Dog;
2765
        assert_eq!(
2766
            format!("{}", super::as_json(&animal)),
2767
            "\"Dog\""
2768 2769
        );
        assert_eq!(
2770
            format!("{}", super::as_pretty_json(&animal)),
2771
            "\"Dog\""
2772
        );
2773

A
Alex Crichton 已提交
2774
        let animal = Frog("Henry".to_string(), 349);
2775
        assert_eq!(
2776
            format!("{}", super::as_json(&animal)),
2777
            "{\"variant\":\"Frog\",\"fields\":[\"Henry\",349]}"
2778 2779
        );
        assert_eq!(
2780
            format!("{}", super::as_pretty_json(&animal)),
2781 2782 2783 2784 2785 2786
            "{\n  \
               \"variant\": \"Frog\",\n  \
               \"fields\": [\n    \
                 \"Henry\",\n    \
                 349\n  \
               ]\n\
2787
             }"
2788
        );
2789 2790
    }

2791
    macro_rules! check_encoder_for_simple {
2792
        ($value:expr, $expected:expr) => ({
2793
            let s = format!("{}", super::as_json(&$value));
2794 2795
            assert_eq!(s, $expected);

2796
            let s = format!("{}", super::as_pretty_json(&$value));
2797 2798
            assert_eq!(s, $expected);
        })
2799
    }
2800

2801
    #[test]
2802
    fn test_write_some() {
2803
        check_encoder_for_simple!(Some("jodhpurs".to_string()), "\"jodhpurs\"");
2804 2805
    }

2806
    #[test]
2807
    fn test_write_none() {
2808 2809 2810 2811 2812 2813 2814
        check_encoder_for_simple!(None::<string::String>, "null");
    }

    #[test]
    fn test_write_char() {
        check_encoder_for_simple!('a', "\"a\"");
        check_encoder_for_simple!('\t', "\"\\t\"");
2815 2816 2817
        check_encoder_for_simple!('\u{0000}', "\"\\u0000\"");
        check_encoder_for_simple!('\u{001b}', "\"\\u001b\"");
        check_encoder_for_simple!('\u{007f}', "\"\\u007f\"");
2818 2819 2820
        check_encoder_for_simple!('\u{00a0}', "\"\u{00a0}\"");
        check_encoder_for_simple!('\u{abcd}', "\"\u{abcd}\"");
        check_encoder_for_simple!('\u{10ffff}', "\"\u{10ffff}\"");
2821 2822
    }

2823
    #[test]
2824
    fn test_trailing_characters() {
2825 2826 2827 2828 2829 2830
        assert_eq!(from_str("nulla"),  Err(SyntaxError(TrailingCharacters, 1, 5)));
        assert_eq!(from_str("truea"),  Err(SyntaxError(TrailingCharacters, 1, 5)));
        assert_eq!(from_str("falsea"), Err(SyntaxError(TrailingCharacters, 1, 6)));
        assert_eq!(from_str("1a"),     Err(SyntaxError(TrailingCharacters, 1, 2)));
        assert_eq!(from_str("[]a"),    Err(SyntaxError(TrailingCharacters, 1, 3)));
        assert_eq!(from_str("{}a"),    Err(SyntaxError(TrailingCharacters, 1, 3)));
2831 2832 2833 2834
    }

    #[test]
    fn test_read_identifiers() {
2835 2836 2837 2838 2839 2840
        assert_eq!(from_str("n"),    Err(SyntaxError(InvalidSyntax, 1, 2)));
        assert_eq!(from_str("nul"),  Err(SyntaxError(InvalidSyntax, 1, 4)));
        assert_eq!(from_str("t"),    Err(SyntaxError(InvalidSyntax, 1, 2)));
        assert_eq!(from_str("truz"), Err(SyntaxError(InvalidSyntax, 1, 4)));
        assert_eq!(from_str("f"),    Err(SyntaxError(InvalidSyntax, 1, 2)));
        assert_eq!(from_str("faz"),  Err(SyntaxError(InvalidSyntax, 1, 3)));
2841

E
Erick Tryzelaar 已提交
2842 2843 2844 2845 2846 2847
        assert_eq!(from_str("null"), Ok(Null));
        assert_eq!(from_str("true"), Ok(Boolean(true)));
        assert_eq!(from_str("false"), Ok(Boolean(false)));
        assert_eq!(from_str(" null "), Ok(Null));
        assert_eq!(from_str(" true "), Ok(Boolean(true)));
        assert_eq!(from_str(" false "), Ok(Boolean(false)));
2848 2849
    }

2850 2851
    #[test]
    fn test_decode_identifiers() {
2852
        let v: () = super::decode("null").unwrap();
2853 2854
        assert_eq!(v, ());

2855
        let v: bool = super::decode("true").unwrap();
2856 2857
        assert_eq!(v, true);

2858
        let v: bool = super::decode("false").unwrap();
2859 2860 2861
        assert_eq!(v, false);
    }

2862
    #[test]
2863
    fn test_read_number() {
2864 2865
        assert_eq!(from_str("+"),   Err(SyntaxError(InvalidSyntax, 1, 1)));
        assert_eq!(from_str("."),   Err(SyntaxError(InvalidSyntax, 1, 1)));
M
mrec 已提交
2866
        assert_eq!(from_str("NaN"), Err(SyntaxError(InvalidSyntax, 1, 1)));
2867 2868 2869 2870 2871
        assert_eq!(from_str("-"),   Err(SyntaxError(InvalidNumber, 1, 2)));
        assert_eq!(from_str("00"),  Err(SyntaxError(InvalidNumber, 1, 2)));
        assert_eq!(from_str("1."),  Err(SyntaxError(InvalidNumber, 1, 3)));
        assert_eq!(from_str("1e"),  Err(SyntaxError(InvalidNumber, 1, 3)));
        assert_eq!(from_str("1e+"), Err(SyntaxError(InvalidNumber, 1, 4)));
2872

2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887
        assert_eq!(from_str("18446744073709551616"), Err(SyntaxError(InvalidNumber, 1, 20)));
        assert_eq!(from_str("-9223372036854775809"), Err(SyntaxError(InvalidNumber, 1, 21)));

        assert_eq!(from_str("3"), Ok(U64(3)));
        assert_eq!(from_str("3.1"), Ok(F64(3.1)));
        assert_eq!(from_str("-1.2"), Ok(F64(-1.2)));
        assert_eq!(from_str("0.4"), Ok(F64(0.4)));
        assert_eq!(from_str("0.4e5"), Ok(F64(0.4e5)));
        assert_eq!(from_str("0.4e+15"), Ok(F64(0.4e15)));
        assert_eq!(from_str("0.4e-01"), Ok(F64(0.4e-01)));
        assert_eq!(from_str(" 3 "), Ok(U64(3)));

        assert_eq!(from_str("-9223372036854775808"), Ok(I64(i64::MIN)));
        assert_eq!(from_str("9223372036854775807"), Ok(U64(i64::MAX as u64)));
        assert_eq!(from_str("18446744073709551615"), Ok(U64(u64::MAX)));
2888 2889
    }

2890 2891
    #[test]
    fn test_decode_numbers() {
2892
        let v: f64 = super::decode("3").unwrap();
D
Daniel Micay 已提交
2893
        assert_eq!(v, 3.0);
2894

2895
        let v: f64 = super::decode("3.1").unwrap();
D
Daniel Micay 已提交
2896
        assert_eq!(v, 3.1);
2897

2898
        let v: f64 = super::decode("-1.2").unwrap();
D
Daniel Micay 已提交
2899
        assert_eq!(v, -1.2);
2900

2901
        let v: f64 = super::decode("0.4").unwrap();
D
Daniel Micay 已提交
2902
        assert_eq!(v, 0.4);
2903

2904
        let v: f64 = super::decode("0.4e5").unwrap();
D
Daniel Micay 已提交
2905
        assert_eq!(v, 0.4e5);
2906

2907
        let v: f64 = super::decode("0.4e15").unwrap();
D
Daniel Micay 已提交
2908
        assert_eq!(v, 0.4e15);
2909

2910
        let v: f64 = super::decode("0.4e-01").unwrap();
D
Daniel Micay 已提交
2911
        assert_eq!(v, 0.4e-01);
2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923

        let v: u64 = super::decode("0").unwrap();
        assert_eq!(v, 0);

        let v: u64 = super::decode("18446744073709551615").unwrap();
        assert_eq!(v, u64::MAX);

        let v: i64 = super::decode("-9223372036854775808").unwrap();
        assert_eq!(v, i64::MIN);

        let v: i64 = super::decode("9223372036854775807").unwrap();
        assert_eq!(v, i64::MAX);
2924 2925

        let res: DecodeResult<i64> = super::decode("765.25252");
A
Alex Crichton 已提交
2926
        assert_eq!(res, Err(ExpectedError("Integer".to_string(), "765.25252".to_string())));
2927 2928
    }

G
Gary Linscott 已提交
2929
    #[test]
2930
    fn test_read_str() {
2931 2932 2933
        assert_eq!(from_str("\""),    Err(SyntaxError(EOFWhileParsingString, 1, 2)));
        assert_eq!(from_str("\"lol"), Err(SyntaxError(EOFWhileParsingString, 1, 5)));

A
Alex Crichton 已提交
2934 2935 2936 2937 2938 2939 2940 2941 2942 2943
        assert_eq!(from_str("\"\""), Ok(String("".to_string())));
        assert_eq!(from_str("\"foo\""), Ok(String("foo".to_string())));
        assert_eq!(from_str("\"\\\"\""), Ok(String("\"".to_string())));
        assert_eq!(from_str("\"\\b\""), Ok(String("\x08".to_string())));
        assert_eq!(from_str("\"\\n\""), Ok(String("\n".to_string())));
        assert_eq!(from_str("\"\\r\""), Ok(String("\r".to_string())));
        assert_eq!(from_str("\"\\t\""), Ok(String("\t".to_string())));
        assert_eq!(from_str(" \"foo\" "), Ok(String("foo".to_string())));
        assert_eq!(from_str("\"\\u12ab\""), Ok(String("\u{12ab}".to_string())));
        assert_eq!(from_str("\"\\uAB12\""), Ok(String("\u{AB12}".to_string())));
2944 2945
    }

2946
    #[test]
2947
    fn test_decode_str() {
2948 2949 2950 2951 2952 2953 2954
        let s = [("\"\"", ""),
                 ("\"foo\"", "foo"),
                 ("\"\\\"\"", "\""),
                 ("\"\\b\"", "\x08"),
                 ("\"\\n\"", "\n"),
                 ("\"\\r\"", "\r"),
                 ("\"\\t\"", "\t"),
A
Alex Crichton 已提交
2955 2956
                 ("\"\\u12ab\"", "\u{12ab}"),
                 ("\"\\uAB12\"", "\u{AB12}")];
2957 2958

        for &(i, o) in s.iter() {
2959
            let v: string::String = super::decode(i).unwrap();
2960
            assert_eq!(v, o);
2961
        }
2962 2963
    }

2964
    #[test]
C
Corey Farwell 已提交
2965
    fn test_read_array() {
2966
        assert_eq!(from_str("["),     Err(SyntaxError(EOFWhileParsingValue, 1, 2)));
C
Corey Farwell 已提交
2967
        assert_eq!(from_str("[1"),    Err(SyntaxError(EOFWhileParsingArray, 1, 3)));
2968 2969 2970
        assert_eq!(from_str("[1,"),   Err(SyntaxError(EOFWhileParsingValue, 1, 4)));
        assert_eq!(from_str("[1,]"),  Err(SyntaxError(InvalidSyntax,        1, 4)));
        assert_eq!(from_str("[6 7]"), Err(SyntaxError(InvalidSyntax,        1, 4)));
2971

C
Corey Farwell 已提交
2972 2973 2974 2975 2976
        assert_eq!(from_str("[]"), Ok(Array(vec![])));
        assert_eq!(from_str("[ ]"), Ok(Array(vec![])));
        assert_eq!(from_str("[true]"), Ok(Array(vec![Boolean(true)])));
        assert_eq!(from_str("[ false ]"), Ok(Array(vec![Boolean(false)])));
        assert_eq!(from_str("[null]"), Ok(Array(vec![Null])));
E
Erick Tryzelaar 已提交
2977
        assert_eq!(from_str("[3, 1]"),
C
Corey Farwell 已提交
2978
                     Ok(Array(vec![U64(3), U64(1)])));
E
Erick Tryzelaar 已提交
2979
        assert_eq!(from_str("\n[3, 2]\n"),
C
Corey Farwell 已提交
2980
                     Ok(Array(vec![U64(3), U64(2)])));
E
Erick Tryzelaar 已提交
2981
        assert_eq!(from_str("[2, [4, 1]]"),
C
Corey Farwell 已提交
2982
               Ok(Array(vec![U64(2), Array(vec![U64(4), U64(1)])])));
2983 2984
    }

2985
    #[test]
C
Corey Farwell 已提交
2986
    fn test_decode_array() {
2987
        let v: Vec<()> = super::decode("[]").unwrap();
K
Kevin Ballard 已提交
2988
        assert_eq!(v, vec![]);
2989

2990
        let v: Vec<()> = super::decode("[null]").unwrap();
K
Kevin Ballard 已提交
2991
        assert_eq!(v, vec![()]);
2992

2993
        let v: Vec<bool> = super::decode("[true]").unwrap();
K
Kevin Ballard 已提交
2994
        assert_eq!(v, vec![true]);
2995

2996
        let v: Vec<int> = super::decode("[3, 1]").unwrap();
K
Kevin Ballard 已提交
2997
        assert_eq!(v, vec![3, 1]);
2998

2999
        let v: Vec<Vec<uint>> = super::decode("[[3], [1, 2]]").unwrap();
K
Kevin Ballard 已提交
3000
        assert_eq!(v, vec![vec![3], vec![1, 2]]);
3001 3002
    }

3003 3004 3005
    #[test]
    fn test_decode_tuple() {
        let t: (uint, uint, uint) = super::decode("[1, 2, 3]").unwrap();
3006
        assert_eq!(t, (1u, 2, 3));
3007 3008

        let t: (uint, string::String) = super::decode("[1, \"two\"]").unwrap();
A
Alex Crichton 已提交
3009
        assert_eq!(t, (1u, "two".to_string()));
3010 3011 3012 3013 3014 3015 3016 3017 3018
    }

    #[test]
    fn test_decode_tuple_malformed_types() {
        assert!(super::decode::<(uint, string::String)>("[1, 2]").is_err());
    }

    #[test]
    fn test_decode_tuple_malformed_length() {
3019
        assert!(super::decode::<(uint, uint)>("[1, 2, 3]").is_err());
3020 3021
    }

3022
    #[test]
3023
    fn test_read_object() {
3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035
        assert_eq!(from_str("{"),       Err(SyntaxError(EOFWhileParsingObject, 1, 2)));
        assert_eq!(from_str("{ "),      Err(SyntaxError(EOFWhileParsingObject, 1, 3)));
        assert_eq!(from_str("{1"),      Err(SyntaxError(KeyMustBeAString,      1, 2)));
        assert_eq!(from_str("{ \"a\""), Err(SyntaxError(EOFWhileParsingObject, 1, 6)));
        assert_eq!(from_str("{\"a\""),  Err(SyntaxError(EOFWhileParsingObject, 1, 5)));
        assert_eq!(from_str("{\"a\" "), Err(SyntaxError(EOFWhileParsingObject, 1, 6)));

        assert_eq!(from_str("{\"a\" 1"),   Err(SyntaxError(ExpectedColon,         1, 6)));
        assert_eq!(from_str("{\"a\":"),    Err(SyntaxError(EOFWhileParsingValue,  1, 6)));
        assert_eq!(from_str("{\"a\":1"),   Err(SyntaxError(EOFWhileParsingObject, 1, 7)));
        assert_eq!(from_str("{\"a\":1 1"), Err(SyntaxError(InvalidSyntax,         1, 8)));
        assert_eq!(from_str("{\"a\":1,"),  Err(SyntaxError(EOFWhileParsingObject, 1, 8)));
3036

N
Nick Cameron 已提交
3037
        assert_eq!(from_str("{}").unwrap(), mk_object(&[]));
E
Erick Tryzelaar 已提交
3038
        assert_eq!(from_str("{\"a\": 3}").unwrap(),
A
Alex Crichton 已提交
3039
                  mk_object(&[("a".to_string(), U64(3))]));
3040

E
Erick Tryzelaar 已提交
3041 3042
        assert_eq!(from_str(
                      "{ \"a\": null, \"b\" : true }").unwrap(),
N
Nick Cameron 已提交
3043
                  mk_object(&[
A
Alex Crichton 已提交
3044 3045
                      ("a".to_string(), Null),
                      ("b".to_string(), Boolean(true))]));
E
Erick Tryzelaar 已提交
3046
        assert_eq!(from_str("\n{ \"a\": null, \"b\" : true }\n").unwrap(),
N
Nick Cameron 已提交
3047
                  mk_object(&[
A
Alex Crichton 已提交
3048 3049
                      ("a".to_string(), Null),
                      ("b".to_string(), Boolean(true))]));
E
Erick Tryzelaar 已提交
3050 3051
        assert_eq!(from_str(
                      "{\"a\" : 1.0 ,\"b\": [ true ]}").unwrap(),
N
Nick Cameron 已提交
3052
                  mk_object(&[
A
Alex Crichton 已提交
3053 3054
                      ("a".to_string(), F64(1.0)),
                      ("b".to_string(), Array(vec![Boolean(true)]))
3055
                  ]));
E
Erick Tryzelaar 已提交
3056
        assert_eq!(from_str(
3057 3058 3059 3060 3061 3062 3063 3064
                      "{\
                          \"a\": 1.0, \
                          \"b\": [\
                              true,\
                              \"foo\\nbar\", \
                              { \"c\": {\"d\": null} } \
                          ]\
                      }").unwrap(),
N
Nick Cameron 已提交
3065
                  mk_object(&[
A
Alex Crichton 已提交
3066 3067
                      ("a".to_string(), F64(1.0)),
                      ("b".to_string(), Array(vec![
B
Ben Striegel 已提交
3068
                          Boolean(true),
A
Alex Crichton 已提交
3069
                          String("foo\nbar".to_string()),
N
Nick Cameron 已提交
3070
                          mk_object(&[
A
Alex Crichton 已提交
3071
                              ("c".to_string(), mk_object(&[("d".to_string(), Null)]))
3072 3073
                          ])
                      ]))
3074
                  ]));
3075 3076
    }

3077
    #[test]
3078
    fn test_decode_struct() {
3079
        let s = "{
3080 3081 3082
            \"inner\": [
                { \"a\": null, \"b\": 2, \"c\": [\"abc\", \"xyz\"] }
            ]
3083
        }";
3084 3085

        let v: Outer = super::decode(s).unwrap();
3086 3087 3088
        assert_eq!(
            v,
            Outer {
K
Kevin Ballard 已提交
3089
                inner: vec![
A
Alex Crichton 已提交
3090
                    Inner { a: (), b: 2, c: vec!["abc".to_string(), "xyz".to_string()] }
3091 3092 3093 3094 3095
                ]
            }
        );
    }

3096
    #[derive(RustcDecodable)]
M
mrec 已提交
3097 3098 3099 3100 3101 3102
    struct FloatStruct {
        f: f64,
        a: Vec<f64>
    }
    #[test]
    fn test_decode_struct_with_nan() {
3103 3104 3105
        let s = "{\"f\":null,\"a\":[null,123]}";
        let obj: FloatStruct = super::decode(s).unwrap();
        assert!(obj.f.is_nan());
N
NODA, Kai 已提交
3106 3107
        assert!(obj.a[0].is_nan());
        assert_eq!(obj.a[1], 123f64);
M
mrec 已提交
3108 3109
    }

3110 3111
    #[test]
    fn test_decode_option() {
3112
        let value: Option<string::String> = super::decode("null").unwrap();
3113 3114
        assert_eq!(value, None);

3115
        let value: Option<string::String> = super::decode("\"jodhpurs\"").unwrap();
A
Alex Crichton 已提交
3116
        assert_eq!(value, Some("jodhpurs".to_string()));
3117 3118
    }

3119
    #[test]
3120
    fn test_decode_enum() {
3121
        let value: Animal = super::decode("\"Dog\"").unwrap();
3122 3123
        assert_eq!(value, Dog);

3124
        let s = "{\"variant\":\"Frog\",\"fields\":[\"Henry\",349]}";
3125
        let value: Animal = super::decode(s).unwrap();
A
Alex Crichton 已提交
3126
        assert_eq!(value, Frog("Henry".to_string(), 349));
3127 3128
    }

3129
    #[test]
3130
    fn test_decode_map() {
3131
        let s = "{\"a\": \"Dog\", \"b\": {\"variant\":\"Frog\",\
3132
                  \"fields\":[\"Henry\", 349]}}";
A
Alexis Beingessner 已提交
3133
        let mut map: BTreeMap<string::String, Animal> = super::decode(s).unwrap();
3134

A
Alex Crichton 已提交
3135 3136
        assert_eq!(map.remove(&"a".to_string()), Some(Dog));
        assert_eq!(map.remove(&"b".to_string()), Some(Frog("Henry".to_string(), 349)));
3137 3138
    }

3139
    #[test]
3140
    fn test_multiline_errors() {
E
Erick Tryzelaar 已提交
3141
        assert_eq!(from_str("{\n  \"foo\":\n \"bar\""),
3142
            Err(SyntaxError(EOFWhileParsingObject, 3u, 8u)));
3143
    }
3144

3145
    #[derive(RustcDecodable)]
M
mrec 已提交
3146
    #[allow(dead_code)]
3147 3148 3149
    struct DecodeStruct {
        x: f64,
        y: bool,
3150
        z: string::String,
K
Kevin Ballard 已提交
3151
        w: Vec<DecodeStruct>
3152
    }
3153
    #[derive(RustcDecodable)]
3154 3155
    enum DecodeEnum {
        A(f64),
3156
        B(string::String)
3157
    }
3158 3159
    fn check_err<T: Decodable<Decoder, DecoderError>>(to_parse: &'static str,
                                                      expected: DecoderError) {
S
Sean McArthur 已提交
3160
        let res: DecodeResult<T> = match from_str(to_parse) {
3161
            Err(e) => Err(ParseError(e)),
S
Sean McArthur 已提交
3162 3163
            Ok(json) => Decodable::decode(&mut Decoder::new(json))
        };
3164
        match res {
S
Steve Klabnik 已提交
3165
            Ok(_) => panic!("`{}` parsed & decoded ok, expecting error `{}`",
S
Sean McArthur 已提交
3166
                              to_parse, expected),
S
Steve Klabnik 已提交
3167
            Err(ParseError(e)) => panic!("`{}` is not valid json: {}",
S
Sean McArthur 已提交
3168
                                           to_parse, e),
3169
            Err(e) => {
S
Sean McArthur 已提交
3170
                assert_eq!(e, expected);
3171 3172 3173 3174 3175
            }
        }
    }
    #[test]
    fn test_decode_errors_struct() {
A
Alex Crichton 已提交
3176
        check_err::<DecodeStruct>("[]", ExpectedError("Object".to_string(), "[]".to_string()));
3177
        check_err::<DecodeStruct>("{\"x\": true, \"y\": true, \"z\": \"\", \"w\": []}",
A
Alex Crichton 已提交
3178
                                  ExpectedError("Number".to_string(), "true".to_string()));
3179
        check_err::<DecodeStruct>("{\"x\": 1, \"y\": [], \"z\": \"\", \"w\": []}",
A
Alex Crichton 已提交
3180
                                  ExpectedError("Boolean".to_string(), "[]".to_string()));
3181
        check_err::<DecodeStruct>("{\"x\": 1, \"y\": true, \"z\": {}, \"w\": []}",
A
Alex Crichton 已提交
3182
                                  ExpectedError("String".to_string(), "{}".to_string()));
3183
        check_err::<DecodeStruct>("{\"x\": 1, \"y\": true, \"z\": \"\", \"w\": null}",
A
Alex Crichton 已提交
3184
                                  ExpectedError("Array".to_string(), "null".to_string()));
3185
        check_err::<DecodeStruct>("{\"x\": 1, \"y\": true, \"z\": \"\"}",
A
Alex Crichton 已提交
3186
                                  MissingFieldError("w".to_string()));
3187 3188 3189 3190
    }
    #[test]
    fn test_decode_errors_enum() {
        check_err::<DecodeEnum>("{}",
A
Alex Crichton 已提交
3191
                                MissingFieldError("variant".to_string()));
3192
        check_err::<DecodeEnum>("{\"variant\": 1}",
A
Alex Crichton 已提交
3193
                                ExpectedError("String".to_string(), "1".to_string()));
3194
        check_err::<DecodeEnum>("{\"variant\": \"A\"}",
A
Alex Crichton 已提交
3195
                                MissingFieldError("fields".to_string()));
3196
        check_err::<DecodeEnum>("{\"variant\": \"A\", \"fields\": null}",
A
Alex Crichton 已提交
3197
                                ExpectedError("Array".to_string(), "null".to_string()));
3198
        check_err::<DecodeEnum>("{\"variant\": \"C\", \"fields\": []}",
A
Alex Crichton 已提交
3199
                                UnknownVariantError("C".to_string()));
3200
    }
3201 3202 3203 3204

    #[test]
    fn test_find(){
        let json_value = from_str("{\"dog\" : \"cat\"}").unwrap();
3205 3206
        let found_str = json_value.find("dog");
        assert!(found_str.unwrap().as_string().unwrap() == "cat");
3207 3208 3209 3210 3211
    }

    #[test]
    fn test_find_path(){
        let json_value = from_str("{\"dog\":{\"cat\": {\"mouse\" : \"cheese\"}}}").unwrap();
3212 3213
        let found_str = json_value.find_path(&["dog", "cat", "mouse"]);
        assert!(found_str.unwrap().as_string().unwrap() == "cheese");
3214 3215 3216 3217 3218
    }

    #[test]
    fn test_search(){
        let json_value = from_str("{\"dog\":{\"cat\": {\"mouse\" : \"cheese\"}}}").unwrap();
3219
        let found_str = json_value.search("mouse").and_then(|j| j.as_string());
3220
        assert!(found_str.unwrap() == "cheese");
3221 3222
    }

3223 3224 3225
    #[test]
    fn test_index(){
        let json_value = from_str("{\"animals\":[\"dog\",\"cat\",\"mouse\"]}").unwrap();
C
Corey Farwell 已提交
3226 3227 3228 3229
        let ref array = json_value["animals"];
        assert_eq!(array[0].as_string().unwrap(), "dog");
        assert_eq!(array[1].as_string().unwrap(), "cat");
        assert_eq!(array[2].as_string().unwrap(), "mouse");
3230 3231
    }

3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245
    #[test]
    fn test_is_object(){
        let json_value = from_str("{}").unwrap();
        assert!(json_value.is_object());
    }

    #[test]
    fn test_as_object(){
        let json_value = from_str("{}").unwrap();
        let json_object = json_value.as_object();
        assert!(json_object.is_some());
    }

    #[test]
C
Corey Farwell 已提交
3246
    fn test_is_array(){
3247
        let json_value = from_str("[1, 2, 3]").unwrap();
C
Corey Farwell 已提交
3248
        assert!(json_value.is_array());
3249 3250 3251
    }

    #[test]
C
Corey Farwell 已提交
3252
    fn test_as_array(){
3253
        let json_value = from_str("[1, 2, 3]").unwrap();
C
Corey Farwell 已提交
3254
        let json_array = json_value.as_array();
3255
        let expected_length = 3;
C
Corey Farwell 已提交
3256
        assert!(json_array.is_some() && json_array.unwrap().len() == expected_length);
3257 3258 3259
    }

    #[test]
3260
    fn test_is_string(){
3261
        let json_value = from_str("\"dog\"").unwrap();
3262
        assert!(json_value.is_string());
3263 3264 3265
    }

    #[test]
3266
    fn test_as_string(){
3267
        let json_value = from_str("\"dog\"").unwrap();
3268
        let json_str = json_value.as_string();
3269
        let expected_str = "dog";
3270 3271 3272 3273 3274 3275 3276 3277 3278 3279
        assert_eq!(json_str, Some(expected_str));
    }

    #[test]
    fn test_is_number(){
        let json_value = from_str("12").unwrap();
        assert!(json_value.is_number());
    }

    #[test]
3280
    fn test_is_i64(){
3281
        let json_value = from_str("-12").unwrap();
3282 3283
        assert!(json_value.is_i64());

3284 3285 3286
        let json_value = from_str("12").unwrap();
        assert!(!json_value.is_i64());

3287 3288 3289 3290
        let json_value = from_str("12.0").unwrap();
        assert!(!json_value.is_i64());
    }

3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302
    #[test]
    fn test_is_u64(){
        let json_value = from_str("12").unwrap();
        assert!(json_value.is_u64());

        let json_value = from_str("-12").unwrap();
        assert!(!json_value.is_u64());

        let json_value = from_str("12.0").unwrap();
        assert!(!json_value.is_u64());
    }

3303 3304
    #[test]
    fn test_is_f64(){
3305
        let json_value = from_str("12").unwrap();
3306 3307
        assert!(!json_value.is_f64());

3308 3309 3310
        let json_value = from_str("-12").unwrap();
        assert!(!json_value.is_f64());

3311 3312
        let json_value = from_str("12.0").unwrap();
        assert!(json_value.is_f64());
3313 3314 3315

        let json_value = from_str("-12.0").unwrap();
        assert!(json_value.is_f64());
3316 3317 3318 3319
    }

    #[test]
    fn test_as_i64(){
3320
        let json_value = from_str("-12").unwrap();
3321
        let json_num = json_value.as_i64();
3322 3323 3324 3325 3326 3327 3328
        assert_eq!(json_num, Some(-12));
    }

    #[test]
    fn test_as_u64(){
        let json_value = from_str("12").unwrap();
        let json_num = json_value.as_u64();
3329 3330 3331 3332 3333 3334 3335 3336
        assert_eq!(json_num, Some(12));
    }

    #[test]
    fn test_as_f64(){
        let json_value = from_str("12.0").unwrap();
        let json_num = json_value.as_f64();
        assert_eq!(json_num, Some(12f64));
3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365
    }

    #[test]
    fn test_is_boolean(){
        let json_value = from_str("false").unwrap();
        assert!(json_value.is_boolean());
    }

    #[test]
    fn test_as_boolean(){
        let json_value = from_str("false").unwrap();
        let json_bool = json_value.as_boolean();
        let expected_bool = false;
        assert!(json_bool.is_some() && json_bool.unwrap() == expected_bool);
    }

    #[test]
    fn test_is_null(){
        let json_value = from_str("null").unwrap();
        assert!(json_value.is_null());
    }

    #[test]
    fn test_as_null(){
        let json_value = from_str("null").unwrap();
        let json_null = json_value.as_null();
        let expected_null = ();
        assert!(json_null.is_some() && json_null.unwrap() == expected_null);
    }
3366 3367 3368 3369 3370

    #[test]
    fn test_encode_hashmap_with_numeric_key() {
        use std::str::from_utf8;
        use std::io::Writer;
3371
        use std::collections::HashMap;
3372 3373
        let mut hm: HashMap<uint, bool> = HashMap::new();
        hm.insert(1, true);
D
Daniel Micay 已提交
3374
        let mut mem_buf = Vec::new();
3375
        write!(&mut mem_buf, "{}", super::as_pretty_json(&hm)).unwrap();
D
Daniel Micay 已提交
3376
        let json_str = from_utf8(mem_buf[]).unwrap();
3377
        match from_str(json_str) {
S
Steve Klabnik 已提交
3378
            Err(_) => panic!("Unable to parse json_str: {}", json_str),
3379 3380 3381
            _ => {} // it parsed and we are good to go
        }
    }
3382

3383 3384 3385 3386
    #[test]
    fn test_prettyencode_hashmap_with_numeric_key() {
        use std::str::from_utf8;
        use std::io::Writer;
3387
        use std::collections::HashMap;
3388 3389
        let mut hm: HashMap<uint, bool> = HashMap::new();
        hm.insert(1, true);
D
Daniel Micay 已提交
3390
        let mut mem_buf = Vec::new();
3391
        write!(&mut mem_buf, "{}", super::as_pretty_json(&hm)).unwrap();
D
Daniel Micay 已提交
3392
        let json_str = from_utf8(mem_buf[]).unwrap();
3393
        match from_str(json_str) {
S
Steve Klabnik 已提交
3394
            Err(_) => panic!("Unable to parse json_str: {}", json_str),
3395 3396 3397
            _ => {} // it parsed and we are good to go
        }
    }
3398

3399 3400 3401
    #[test]
    fn test_prettyencoder_indent_level_param() {
        use std::str::from_utf8;
A
Alexis Beingessner 已提交
3402
        use std::collections::BTreeMap;
3403

A
Alexis Beingessner 已提交
3404
        let mut tree = BTreeMap::new();
3405

A
Alex Crichton 已提交
3406 3407
        tree.insert("hello".to_string(), String("guten tag".to_string()));
        tree.insert("goodbye".to_string(), String("sayonara".to_string()));
3408

C
Corey Farwell 已提交
3409
        let json = Array(
3410 3411 3412 3413
            // The following layout below should look a lot like
            // the pretty-printed JSON (indent * x)
            vec!
            ( // 0x
A
Alex Crichton 已提交
3414
                String("greetings".to_string()), // 1x
3415 3416
                Object(tree), // 1x + 2x + 2x + 1x
            ) // 0x
C
Corey Farwell 已提交
3417
            // End JSON array (7 lines)
3418 3419 3420 3421
        );

        // Helper function for counting indents
        fn indents(source: &str) -> uint {
3422
            let trimmed = source.trim_left_matches(' ');
3423 3424 3425 3426 3427
            source.len() - trimmed.len()
        }

        // Test up to 4 spaces of indents (more?)
        for i in range(0, 4u) {
D
Daniel Micay 已提交
3428
            let mut writer = Vec::new();
3429 3430
            write!(&mut writer, "{}",
                   super::as_pretty_json(&json).indent(i)).unwrap();
3431

D
Daniel Micay 已提交
3432
            let printed = from_utf8(writer[]).unwrap();
3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450

            // Check for indents at each line
            let lines: Vec<&str> = printed.lines().collect();
            assert_eq!(lines.len(), 7); // JSON should be 7 lines

            assert_eq!(indents(lines[0]), 0 * i); // [
            assert_eq!(indents(lines[1]), 1 * i); //   "greetings",
            assert_eq!(indents(lines[2]), 1 * i); //   {
            assert_eq!(indents(lines[3]), 2 * i); //     "hello": "guten tag",
            assert_eq!(indents(lines[4]), 2 * i); //     "goodbye": "sayonara"
            assert_eq!(indents(lines[5]), 1 * i); //   },
            assert_eq!(indents(lines[6]), 0 * i); // ]

            // Finally, test that the pretty-printed JSON is valid
            from_str(printed).ok().expect("Pretty-printed JSON is invalid!");
        }
    }

3451 3452
    #[test]
    fn test_hashmap_with_numeric_key_can_handle_double_quote_delimited_key() {
3453
        use std::collections::HashMap;
3454 3455 3456
        use Decodable;
        let json_str = "{\"1\":true}";
        let json_obj = match from_str(json_str) {
S
Steve Klabnik 已提交
3457
            Err(_) => panic!("Unable to parse json_str: {}", json_str),
3458 3459 3460
            Ok(o) => o
        };
        let mut decoder = Decoder::new(json_obj);
S
Sean McArthur 已提交
3461
        let _hm: HashMap<uint, bool> = Decodable::decode(&mut decoder).unwrap();
3462
    }
3463

3464 3465 3466 3467 3468 3469
    #[test]
    fn test_hashmap_with_numeric_key_will_error_with_string_keys() {
        use std::collections::HashMap;
        use Decodable;
        let json_str = "{\"a\":true}";
        let json_obj = match from_str(json_str) {
S
Steve Klabnik 已提交
3470
            Err(_) => panic!("Unable to parse json_str: {}", json_str),
3471 3472 3473 3474
            Ok(o) => o
        };
        let mut decoder = Decoder::new(json_obj);
        let result: Result<HashMap<uint, bool>, DecoderError> = Decodable::decode(&mut decoder);
A
Alex Crichton 已提交
3475
        assert_eq!(result, Err(ExpectedError("Number".to_string(), "a".to_string())));
3476 3477
    }

3478 3479
    fn assert_stream_equal(src: &str,
                           expected: Vec<(JsonEvent, Vec<StackElement>)>) {
3480 3481 3482 3483 3484 3485 3486
        let mut parser = Parser::new(src.chars());
        let mut i = 0;
        loop {
            let evt = match parser.next() {
                Some(e) => e,
                None => { break; }
            };
E
Erick Tryzelaar 已提交
3487
            let (ref expected_evt, ref expected_stack) = expected[i];
3488
            if !parser.stack().is_equal_to(expected_stack.as_slice()) {
S
Steve Klabnik 已提交
3489
                panic!("Parser stack is not equal to {}", expected_stack);
3490 3491 3492 3493 3494 3495
            }
            assert_eq!(&evt, expected_evt);
            i+=1;
        }
    }
    #[test]
S
Steven Fackler 已提交
3496
    #[cfg_attr(target_word_size = "32", ignore)] // FIXME(#14064)
3497 3498
    fn test_streaming_parser() {
        assert_stream_equal(
3499
            r#"{ "foo":"bar", "array" : [0, 1, 2, 3, 4, 5], "idents":[null,true,false]}"#,
3500 3501
            vec![
                (ObjectStart,             vec![]),
A
Alex Crichton 已提交
3502
                  (StringValue("bar".to_string()),   vec![Key("foo")]),
C
Corey Farwell 已提交
3503
                  (ArrayStart,            vec![Key("array")]),
3504 3505 3506 3507 3508 3509
                    (U64Value(0),         vec![Key("array"), Index(0)]),
                    (U64Value(1),         vec![Key("array"), Index(1)]),
                    (U64Value(2),         vec![Key("array"), Index(2)]),
                    (U64Value(3),         vec![Key("array"), Index(3)]),
                    (U64Value(4),         vec![Key("array"), Index(4)]),
                    (U64Value(5),         vec![Key("array"), Index(5)]),
C
Corey Farwell 已提交
3510 3511
                  (ArrayEnd,              vec![Key("array")]),
                  (ArrayStart,            vec![Key("idents")]),
3512 3513 3514
                    (NullValue,           vec![Key("idents"), Index(0)]),
                    (BooleanValue(true),  vec![Key("idents"), Index(1)]),
                    (BooleanValue(false), vec![Key("idents"), Index(2)]),
C
Corey Farwell 已提交
3515
                  (ArrayEnd,              vec![Key("idents")]),
3516
                (ObjectEnd,               vec![]),
3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529
            ]
        );
    }
    fn last_event(src: &str) -> JsonEvent {
        let mut parser = Parser::new(src.chars());
        let mut evt = NullValue;
        loop {
            evt = match parser.next() {
                Some(e) => e,
                None => return evt,
            }
        }
    }
3530

3531
    #[test]
S
Steven Fackler 已提交
3532
    #[cfg_attr(target_word_size = "32", ignore)] // FIXME(#14064)
3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544
    fn test_read_object_streaming() {
        assert_eq!(last_event("{ "),      Error(SyntaxError(EOFWhileParsingObject, 1, 3)));
        assert_eq!(last_event("{1"),      Error(SyntaxError(KeyMustBeAString,      1, 2)));
        assert_eq!(last_event("{ \"a\""), Error(SyntaxError(EOFWhileParsingObject, 1, 6)));
        assert_eq!(last_event("{\"a\""),  Error(SyntaxError(EOFWhileParsingObject, 1, 5)));
        assert_eq!(last_event("{\"a\" "), Error(SyntaxError(EOFWhileParsingObject, 1, 6)));

        assert_eq!(last_event("{\"a\" 1"),   Error(SyntaxError(ExpectedColon,         1, 6)));
        assert_eq!(last_event("{\"a\":"),    Error(SyntaxError(EOFWhileParsingValue,  1, 6)));
        assert_eq!(last_event("{\"a\":1"),   Error(SyntaxError(EOFWhileParsingObject, 1, 7)));
        assert_eq!(last_event("{\"a\":1 1"), Error(SyntaxError(InvalidSyntax,         1, 8)));
        assert_eq!(last_event("{\"a\":1,"),  Error(SyntaxError(EOFWhileParsingObject, 1, 8)));
3545
        assert_eq!(last_event("{\"a\":1,}"), Error(SyntaxError(TrailingComma, 1, 8)));
3546 3547 3548

        assert_stream_equal(
            "{}",
3549
            vec![(ObjectStart, vec![]), (ObjectEnd, vec![])]
3550 3551 3552
        );
        assert_stream_equal(
            "{\"a\": 3}",
3553 3554
            vec![
                (ObjectStart,        vec![]),
3555
                  (U64Value(3),      vec![Key("a")]),
3556
                (ObjectEnd,          vec![]),
3557 3558 3559 3560
            ]
        );
        assert_stream_equal(
            "{ \"a\": null, \"b\" : true }",
3561 3562 3563 3564 3565
            vec![
                (ObjectStart,           vec![]),
                  (NullValue,           vec![Key("a")]),
                  (BooleanValue(true),  vec![Key("b")]),
                (ObjectEnd,             vec![]),
3566 3567 3568 3569
            ]
        );
        assert_stream_equal(
            "{\"a\" : 1.0 ,\"b\": [ true ]}",
3570 3571
            vec![
                (ObjectStart,           vec![]),
3572
                  (F64Value(1.0),       vec![Key("a")]),
C
Corey Farwell 已提交
3573
                  (ArrayStart,          vec![Key("b")]),
3574
                    (BooleanValue(true),vec![Key("b"), Index(0)]),
C
Corey Farwell 已提交
3575
                  (ArrayEnd,            vec![Key("b")]),
3576
                (ObjectEnd,             vec![]),
3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587
            ]
        );
        assert_stream_equal(
            r#"{
                "a": 1.0,
                "b": [
                    true,
                    "foo\nbar",
                    { "c": {"d": null} }
                ]
            }"#,
3588 3589
            vec![
                (ObjectStart,                   vec![]),
3590
                  (F64Value(1.0),               vec![Key("a")]),
C
Corey Farwell 已提交
3591
                  (ArrayStart,                  vec![Key("b")]),
3592
                    (BooleanValue(true),        vec![Key("b"), Index(0)]),
A
Alex Crichton 已提交
3593
                    (StringValue("foo\nbar".to_string()),  vec![Key("b"), Index(1)]),
3594 3595 3596 3597 3598
                    (ObjectStart,               vec![Key("b"), Index(2)]),
                      (ObjectStart,             vec![Key("b"), Index(2), Key("c")]),
                        (NullValue,             vec![Key("b"), Index(2), Key("c"), Key("d")]),
                      (ObjectEnd,               vec![Key("b"), Index(2), Key("c")]),
                    (ObjectEnd,                 vec![Key("b"), Index(2)]),
C
Corey Farwell 已提交
3599
                  (ArrayEnd,                    vec![Key("b")]),
3600
                (ObjectEnd,                     vec![]),
3601 3602 3603 3604
            ]
        );
    }
    #[test]
S
Steven Fackler 已提交
3605
    #[cfg_attr(target_word_size = "32", ignore)] // FIXME(#14064)
C
Corey Farwell 已提交
3606
    fn test_read_array_streaming() {
3607 3608
        assert_stream_equal(
            "[]",
3609
            vec![
C
Corey Farwell 已提交
3610 3611
                (ArrayStart, vec![]),
                (ArrayEnd,   vec![]),
3612 3613 3614 3615
            ]
        );
        assert_stream_equal(
            "[ ]",
3616
            vec![
C
Corey Farwell 已提交
3617 3618
                (ArrayStart, vec![]),
                (ArrayEnd,   vec![]),
3619 3620 3621 3622
            ]
        );
        assert_stream_equal(
            "[true]",
3623
            vec![
C
Corey Farwell 已提交
3624
                (ArrayStart,             vec![]),
3625
                    (BooleanValue(true), vec![Index(0)]),
C
Corey Farwell 已提交
3626
                (ArrayEnd,               vec![]),
3627 3628 3629 3630
            ]
        );
        assert_stream_equal(
            "[ false ]",
3631
            vec![
C
Corey Farwell 已提交
3632
                (ArrayStart,              vec![]),
3633
                    (BooleanValue(false), vec![Index(0)]),
C
Corey Farwell 已提交
3634
                (ArrayEnd,                vec![]),
3635 3636 3637 3638
            ]
        );
        assert_stream_equal(
            "[null]",
3639
            vec![
C
Corey Farwell 已提交
3640
                (ArrayStart,    vec![]),
3641
                    (NullValue, vec![Index(0)]),
C
Corey Farwell 已提交
3642
                (ArrayEnd,      vec![]),
3643 3644 3645 3646
            ]
        );
        assert_stream_equal(
            "[3, 1]",
3647
            vec![
C
Corey Farwell 已提交
3648
                (ArrayStart,      vec![]),
3649 3650
                    (U64Value(3), vec![Index(0)]),
                    (U64Value(1), vec![Index(1)]),
C
Corey Farwell 已提交
3651
                (ArrayEnd,        vec![]),
3652 3653 3654 3655
            ]
        );
        assert_stream_equal(
            "\n[3, 2]\n",
3656
            vec![
C
Corey Farwell 已提交
3657
                (ArrayStart,      vec![]),
3658 3659
                    (U64Value(3), vec![Index(0)]),
                    (U64Value(2), vec![Index(1)]),
C
Corey Farwell 已提交
3660
                (ArrayEnd,        vec![]),
3661 3662 3663 3664
            ]
        );
        assert_stream_equal(
            "[2, [4, 1]]",
3665
            vec![
C
Corey Farwell 已提交
3666
                (ArrayStart,           vec![]),
3667
                    (U64Value(2),      vec![Index(0)]),
C
Corey Farwell 已提交
3668
                    (ArrayStart,       vec![Index(1)]),
3669 3670
                        (U64Value(4),  vec![Index(1), Index(0)]),
                        (U64Value(1),  vec![Index(1), Index(1)]),
C
Corey Farwell 已提交
3671 3672
                    (ArrayEnd,         vec![Index(1)]),
                (ArrayEnd,             vec![]),
3673 3674 3675 3676 3677 3678
            ]
        );

        assert_eq!(last_event("["), Error(SyntaxError(EOFWhileParsingValue, 1,  2)));

        assert_eq!(from_str("["),     Err(SyntaxError(EOFWhileParsingValue, 1, 2)));
C
Corey Farwell 已提交
3679
        assert_eq!(from_str("[1"),    Err(SyntaxError(EOFWhileParsingArray, 1, 3)));
3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719
        assert_eq!(from_str("[1,"),   Err(SyntaxError(EOFWhileParsingValue, 1, 4)));
        assert_eq!(from_str("[1,]"),  Err(SyntaxError(InvalidSyntax,        1, 4)));
        assert_eq!(from_str("[6 7]"), Err(SyntaxError(InvalidSyntax,        1, 4)));

    }
    #[test]
    fn test_trailing_characters_streaming() {
        assert_eq!(last_event("nulla"),  Error(SyntaxError(TrailingCharacters, 1, 5)));
        assert_eq!(last_event("truea"),  Error(SyntaxError(TrailingCharacters, 1, 5)));
        assert_eq!(last_event("falsea"), Error(SyntaxError(TrailingCharacters, 1, 6)));
        assert_eq!(last_event("1a"),     Error(SyntaxError(TrailingCharacters, 1, 2)));
        assert_eq!(last_event("[]a"),    Error(SyntaxError(TrailingCharacters, 1, 3)));
        assert_eq!(last_event("{}a"),    Error(SyntaxError(TrailingCharacters, 1, 3)));
    }
    #[test]
    fn test_read_identifiers_streaming() {
        assert_eq!(Parser::new("null".chars()).next(), Some(NullValue));
        assert_eq!(Parser::new("true".chars()).next(), Some(BooleanValue(true)));
        assert_eq!(Parser::new("false".chars()).next(), Some(BooleanValue(false)));

        assert_eq!(last_event("n"),    Error(SyntaxError(InvalidSyntax, 1, 2)));
        assert_eq!(last_event("nul"),  Error(SyntaxError(InvalidSyntax, 1, 4)));
        assert_eq!(last_event("t"),    Error(SyntaxError(InvalidSyntax, 1, 2)));
        assert_eq!(last_event("truz"), Error(SyntaxError(InvalidSyntax, 1, 4)));
        assert_eq!(last_event("f"),    Error(SyntaxError(InvalidSyntax, 1, 2)));
        assert_eq!(last_event("faz"),  Error(SyntaxError(InvalidSyntax, 1, 3)));
    }

    #[test]
    fn test_stack() {
        let mut stack = Stack::new();

        assert!(stack.is_empty());
        assert!(stack.len() == 0);
        assert!(!stack.last_is_index());

        stack.push_index(0);
        stack.bump_index();

        assert!(stack.len() == 1);
N
Nick Cameron 已提交
3720 3721 3722
        assert!(stack.is_equal_to(&[Index(1)]));
        assert!(stack.starts_with(&[Index(1)]));
        assert!(stack.ends_with(&[Index(1)]));
3723 3724 3725
        assert!(stack.last_is_index());
        assert!(stack.get(0) == Index(1));

A
Alex Crichton 已提交
3726
        stack.push_key("foo".to_string());
3727 3728

        assert!(stack.len() == 2);
N
Nick Cameron 已提交
3729 3730 3731 3732 3733
        assert!(stack.is_equal_to(&[Index(1), Key("foo")]));
        assert!(stack.starts_with(&[Index(1), Key("foo")]));
        assert!(stack.starts_with(&[Index(1)]));
        assert!(stack.ends_with(&[Index(1), Key("foo")]));
        assert!(stack.ends_with(&[Key("foo")]));
3734 3735 3736 3737
        assert!(!stack.last_is_index());
        assert!(stack.get(0) == Index(1));
        assert!(stack.get(1) == Key("foo"));

A
Alex Crichton 已提交
3738
        stack.push_key("bar".to_string());
3739 3740

        assert!(stack.len() == 3);
N
Nick Cameron 已提交
3741 3742 3743 3744 3745 3746 3747
        assert!(stack.is_equal_to(&[Index(1), Key("foo"), Key("bar")]));
        assert!(stack.starts_with(&[Index(1)]));
        assert!(stack.starts_with(&[Index(1), Key("foo")]));
        assert!(stack.starts_with(&[Index(1), Key("foo"), Key("bar")]));
        assert!(stack.ends_with(&[Key("bar")]));
        assert!(stack.ends_with(&[Key("foo"), Key("bar")]));
        assert!(stack.ends_with(&[Index(1), Key("foo"), Key("bar")]));
3748 3749 3750 3751 3752 3753 3754 3755
        assert!(!stack.last_is_index());
        assert!(stack.get(0) == Index(1));
        assert!(stack.get(1) == Key("foo"));
        assert!(stack.get(2) == Key("bar"));

        stack.pop();

        assert!(stack.len() == 2);
N
Nick Cameron 已提交
3756 3757 3758 3759 3760
        assert!(stack.is_equal_to(&[Index(1), Key("foo")]));
        assert!(stack.starts_with(&[Index(1), Key("foo")]));
        assert!(stack.starts_with(&[Index(1)]));
        assert!(stack.ends_with(&[Index(1), Key("foo")]));
        assert!(stack.ends_with(&[Key("foo")]));
3761 3762 3763 3764 3765
        assert!(!stack.last_is_index());
        assert!(stack.get(0) == Index(1));
        assert!(stack.get(1) == Key("foo"));
    }

3766 3767
    #[test]
    fn test_to_json() {
A
Alexis Beingessner 已提交
3768
        use std::collections::{HashMap,BTreeMap};
3769 3770
        use super::ToJson;

C
Corey Farwell 已提交
3771 3772
        let array2 = Array(vec!(U64(1), U64(2)));
        let array3 = Array(vec!(U64(1), U64(2), U64(3)));
3773
        let object = {
A
Alexis Beingessner 已提交
3774
            let mut tree_map = BTreeMap::new();
3775 3776
            tree_map.insert("a".to_string(), U64(1));
            tree_map.insert("b".to_string(), U64(2));
A
Adolfo Ochagavía 已提交
3777
            Object(tree_map)
3778 3779
        };

C
Corey Farwell 已提交
3780
        assert_eq!(array2.to_json(), array2);
3781
        assert_eq!(object.to_json(), object);
3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793
        assert_eq!(3_i.to_json(), I64(3));
        assert_eq!(4_i8.to_json(), I64(4));
        assert_eq!(5_i16.to_json(), I64(5));
        assert_eq!(6_i32.to_json(), I64(6));
        assert_eq!(7_i64.to_json(), I64(7));
        assert_eq!(8_u.to_json(), U64(8));
        assert_eq!(9_u8.to_json(), U64(9));
        assert_eq!(10_u16.to_json(), U64(10));
        assert_eq!(11_u32.to_json(), U64(11));
        assert_eq!(12_u64.to_json(), U64(12));
        assert_eq!(13.0_f32.to_json(), F64(13.0_f64));
        assert_eq!(14.0_f64.to_json(), F64(14.0_f64));
3794
        assert_eq!(().to_json(), Null);
M
mrec 已提交
3795 3796
        assert_eq!(f32::INFINITY.to_json(), Null);
        assert_eq!(f64::NAN.to_json(), Null);
3797 3798
        assert_eq!(true.to_json(), Boolean(true));
        assert_eq!(false.to_json(), Boolean(false));
A
Alex Crichton 已提交
3799 3800
        assert_eq!("abc".to_json(), String("abc".to_string()));
        assert_eq!("abc".to_string().to_json(), String("abc".to_string()));
C
Corey Farwell 已提交
3801 3802 3803 3804 3805 3806
        assert_eq!((1u, 2u).to_json(), array2);
        assert_eq!((1u, 2u, 3u).to_json(), array3);
        assert_eq!([1u, 2].to_json(), array2);
        assert_eq!((&[1u, 2, 3]).to_json(), array3);
        assert_eq!((vec![1u, 2]).to_json(), array2);
        assert_eq!(vec!(1u, 2, 3).to_json(), array3);
A
Alexis Beingessner 已提交
3807
        let mut tree_map = BTreeMap::new();
3808 3809
        tree_map.insert("a".to_string(), 1u);
        tree_map.insert("b".to_string(), 2);
3810 3811
        assert_eq!(tree_map.to_json(), object);
        let mut hash_map = HashMap::new();
A
Alex Crichton 已提交
3812 3813
        hash_map.insert("a".to_string(), 1u);
        hash_map.insert("b".to_string(), 2);
3814
        assert_eq!(hash_map.to_json(), object);
3815 3816
        assert_eq!(Some(15i).to_json(), I64(15));
        assert_eq!(Some(15u).to_json(), U64(15));
3817 3818 3819
        assert_eq!(None::<int>.to_json(), Null);
    }

3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854
    #[bench]
    fn bench_streaming_small(b: &mut Bencher) {
        b.iter( || {
            let mut parser = Parser::new(
                r#"{
                    "a": 1.0,
                    "b": [
                        true,
                        "foo\nbar",
                        { "c": {"d": null} }
                    ]
                }"#.chars()
            );
            loop {
                match parser.next() {
                    None => return,
                    _ => {}
                }
            }
        });
    }
    #[bench]
    fn bench_small(b: &mut Bencher) {
        b.iter( || {
            let _ = from_str(r#"{
                "a": 1.0,
                "b": [
                    true,
                    "foo\nbar",
                    { "c": {"d": null} }
                ]
            }"#);
        });
    }

3855
    fn big_json() -> string::String {
A
Alex Crichton 已提交
3856
        let mut src = "[\n".to_string();
3857
        for _ in range(0i, 500) {
3858 3859
            src.push_str(r#"{ "a": true, "b": null, "c":3.1415, "d": "Hello world", "e": \
                            [1,2,3]},"#);
3860
        }
3861
        src.push_str("{}]");
3862 3863 3864 3865 3866 3867 3868
        return src;
    }

    #[bench]
    fn bench_streaming_large(b: &mut Bencher) {
        let src = big_json();
        b.iter( || {
3869
            let mut parser = Parser::new(src.chars());
3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880
            loop {
                match parser.next() {
                    None => return,
                    _ => {}
                }
            }
        });
    }
    #[bench]
    fn bench_large(b: &mut Bencher) {
        let src = big_json();
3881
        b.iter( || { let _ = from_str(src.as_slice()); });
3882
    }
3883
}