json.rs 124.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 32 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 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93
//! 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
//! * `Object`: equivalent to rust's `Treemap<String, json::Json>`
//! * `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.
//! To be able to encode a piece of data, it must implement the `serialize::Encodable` trait.
//! To be able to decode a piece of data, it must implement the `serialize::Decodable` trait.
//! The Rust compiler provides an annotation to automatically generate the code for these traits:
//! `#[deriving(Decodable, Encodable)]`
//!
//! 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.
//!
//! When using `ToJson` the `Encodable` trait implementation is not mandatory.
//!
//! # 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.
//!
//! ```rust
//! extern crate serialize;
//! use serialize::json;
//!
//! // Automatically generate `Decodable` and `Encodable` trait implementations
//! #[deriving(Decodable, Encodable)]
//! pub struct TestStruct  {
//!     data_int: u8,
//!     data_str: String,
//!     data_vector: Vec<u8>,
//! }
//!
//! fn main() {
//!     let object = TestStruct {
//!         data_int: 1,
B
Barosl Lee 已提交
94
//!         data_str: "homura".to_string(),
S
Steve Klabnik 已提交
95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114
//!         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
//!
//! ```rust
//! extern crate serialize;
115
//! use serialize::json::{mod, ToJson, Json};
S
Steve Klabnik 已提交
116 117 118 119 120 121 122 123 124
//!
//! // A custom data structure
//! struct ComplexNum {
//!     a: f64,
//!     b: f64,
//! }
//!
//! // JSON value representation
//! impl ToJson for ComplexNum {
125 126
//!     fn to_json(&self) -> Json {
//!         Json::String(format!("{}+{}i", self.a, self.b))
S
Steve Klabnik 已提交
127 128 129 130 131 132 133 134
//!     }
//! }
//!
//! // Only generate `Encodable` trait implementation
//! #[deriving(Encodable)]
//! pub struct ComplexNumRecord {
//!     uid: u8,
//!     dsc: String,
135
//!     val: Json,
S
Steve Klabnik 已提交
136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154
//! }
//!
//! 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
//!
//! ```rust
//! extern crate serialize;
//! use std::collections::TreeMap;
155
//! use serialize::json::{mod, Json, ToJson};
S
Steve Klabnik 已提交
156 157 158 159 160 161 162 163 164 165 166
//!
//! // Only generate `Decodable` trait implementation
//! #[deriving(Decodable)]
//! pub struct TestStruct {
//!     data_int: u8,
//!     data_str: String,
//!     data_vector: Vec<u8>,
//! }
//!
//! // Specify encoding method manually
//! impl ToJson for TestStruct {
167
//!     fn to_json(&self) -> Json {
S
Steve Klabnik 已提交
168 169 170 171 172
//!         let mut d = TreeMap::new();
//!         // 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());
173
//!         Json::Object(d)
S
Steve Klabnik 已提交
174 175 176 177 178 179 180
//!     }
//! }
//!
//! fn main() {
//!     // Serialize using `ToJson`
//!     let input_data = TestStruct {
//!         data_int: 1,
B
Barosl Lee 已提交
181
//!         data_str: "madoka".to_string(),
S
Steve Klabnik 已提交
182 183
//!         data_vector: vec![2,3,4,5],
//!     };
184
//!     let json_obj: Json = input_data.to_json();
S
Steve Klabnik 已提交
185 186 187 188 189 190
//!     let json_str: String = json_obj.to_string();
//!
//!     // Deserialize like before
//!     let decoded: TestStruct = json::decode(json_str.as_slice()).unwrap();
//! }
//! ```
B
Brian Anderson 已提交
191

192 193 194 195 196
use self::JsonEvent::*;
use self::StackElement::*;
use self::ErrorCode::*;
use self::ParserError::*;
use self::DecoderError::*;
S
Steven Fackler 已提交
197 198 199
use self::ParserState::*;
use self::InternalStackElement::*;

A
Adolfo Ochagavía 已提交
200
use std;
201
use std::collections::{HashMap, TreeMap};
A
Adolfo Ochagavía 已提交
202 203
use std::{char, f64, fmt, io, num, str};
use std::mem::{swap, transmute};
204
use std::num::{Float, FPNaN, FPInfinite, Int};
B
Brendan Zabarauskas 已提交
205
use std::str::{FromStr, ScalarValue};
206
use std::string;
207
use std::vec::Vec;
208
use std::ops;
209

A
Alex Crichton 已提交
210
use Encodable;
E
Elly Jones 已提交
211

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

225 226
pub type Array = Vec<Json>;
pub type Object = TreeMap<string::String, Json>;
227

228
/// The errors that can arise while parsing a JSON stream.
229
#[deriving(Clone, PartialEq)]
230 231 232 233
pub enum ErrorCode {
    InvalidSyntax,
    InvalidNumber,
    EOFWhileParsingObject,
C
Corey Farwell 已提交
234
    EOFWhileParsingArray,
235 236 237 238 239
    EOFWhileParsingValue,
    EOFWhileParsingString,
    KeyMustBeAString,
    ExpectedColon,
    TrailingCharacters,
240
    TrailingComma,
241 242 243 244 245 246 247 248 249
    InvalidEscape,
    InvalidUnicodeCodePoint,
    LoneLeadingSurrogateInHexEscape,
    UnexpectedEndOfHexEscape,
    UnrecognizedHex,
    NotFourDigit,
    NotUtf8,
}

N
Niko Matsakis 已提交
250 251
impl Copy for ErrorCode {}

252
#[deriving(Clone, PartialEq, Show)]
253
pub enum ParserError {
S
Sean McArthur 已提交
254
    /// msg, line, col
255 256 257 258
    SyntaxError(ErrorCode, uint, uint),
    IoError(io::IoErrorKind, &'static str),
}

N
Niko Matsakis 已提交
259 260
impl Copy for ParserError {}

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

264
#[deriving(Clone, PartialEq, Show)]
265 266
pub enum DecoderError {
    ParseError(ParserError),
267 268 269 270
    ExpectedError(string::String, string::String),
    MissingFieldError(string::String),
    UnknownVariantError(string::String),
    ApplicationError(string::String)
271 272 273 274
}

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

296 297 298 299 300 301 302 303 304 305 306 307
/// 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`
308
pub fn encode<'a, T: Encodable<Encoder<'a>, io::IoError>>(object: &T) -> string::String {
309
    let buff = Encoder::buffer_encode(object);
310
    string::String::from_utf8(buff).unwrap()
311 312
}

313 314 315 316 317 318 319 320
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)
321
}
322

323 324 325 326 327
impl std::error::Error for DecoderError {
    fn description(&self) -> &str { "decoder error" }
    fn detail(&self) -> Option<std::string::String> { Some(self.to_string()) }
}

S
Sean McArthur 已提交
328
pub type EncodeResult = io::IoResult<()>;
329
pub type DecodeResult<T> = Result<T, DecoderError>;
A
Alex Crichton 已提交
330

331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348
pub fn escape_bytes(wr: &mut io::Writer, bytes: &[u8]) -> Result<(), io::IoError> {
    try!(wr.write_str("\""));

    let mut start = 0;

    for (i, byte) in bytes.iter().enumerate() {
        let escaped = match *byte {
            b'"' => "\\\"",
            b'\\' => "\\\\",
            b'\x08' => "\\b",
            b'\x0c' => "\\f",
            b'\n' => "\\n",
            b'\r' => "\\r",
            b'\t' => "\\t",
            _ => { continue; }
        };

        if start < i {
349
            try!(wr.write(bytes[start..i]));
E
Elly Jones 已提交
350
        }
351 352 353 354

        try!(wr.write_str(escaped));

        start = i + 1;
355
    }
356 357

    if start != bytes.len() {
358
        try!(wr.write(bytes[start..]));
359 360 361
    }

    wr.write_str("\"")
362 363 364 365 366 367 368 369
}

fn escape_str(writer: &mut io::Writer, v: &str) -> Result<(), io::IoError> {
    escape_bytes(writer, v.as_bytes())
}

fn escape_char(writer: &mut io::Writer, v: char) -> Result<(), io::IoError> {
    let mut buf = [0, .. 4];
N
Nick Cameron 已提交
370 371
    v.encode_utf8(&mut buf);
    escape_bytes(writer, &mut buf)
372 373
}

374
fn spaces(wr: &mut io::Writer, mut n: uint) -> Result<(), io::IoError> {
375 376 377 378
    const LEN: uint = 16;
    static BUF: [u8, ..LEN] = [b' ', ..LEN];

    while n >= LEN {
N
Nick Cameron 已提交
379
        try!(wr.write(&BUF));
380
        n -= LEN;
381 382 383
    }

    if n > 0 {
384
        wr.write(BUF[..n])
385 386
    } else {
        Ok(())
387
    }
E
Elly Jones 已提交
388 389
}

390
fn fmt_number_or_null(v: f64) -> string::String {
M
mrec 已提交
391
    match v.classify() {
392
        FPNaN | FPInfinite => string::String::from_str("null"),
393 394
        _ if v.fract() != 0f64 => f64::to_str_digits(v, 6u),
        _ => f64::to_str_digits(v, 6u) + ".0",
M
mrec 已提交
395 396 397
    }
}

398
/// A structure for implementing serialization to JSON.
E
Erik Price 已提交
399
pub struct Encoder<'a> {
400
    writer: &'a mut (io::Writer+'a),
401 402
}

E
Erik Price 已提交
403
impl<'a> Encoder<'a> {
404 405
    /// Creates a new JSON encoder whose output will be written to the writer
    /// specified.
A
Adolfo Ochagavía 已提交
406 407
    pub fn new(writer: &'a mut io::Writer) -> Encoder<'a> {
        Encoder { writer: writer }
408
    }
M
musitdev 已提交
409 410

    /// Encode the specified struct into a json [u8]
A
Adolfo Ochagavía 已提交
411 412
    pub fn buffer_encode<T:Encodable<Encoder<'a>, io::IoError>>(object: &T) -> Vec<u8>  {
        //Serialize the object in a string using a writer
D
Daniel Micay 已提交
413
        let mut m = Vec::new();
N
Nick Cameron 已提交
414 415
        // FIXME(14302) remove the transmute and unsafe block.
        unsafe {
M
musitdev 已提交
416
            let mut encoder = Encoder::new(&mut m as &mut io::Writer);
D
Daniel Micay 已提交
417
            // Vec<u8> never Errs
A
Adolfo Ochagavía 已提交
418
            let _ = object.encode(transmute(&mut encoder));
M
musitdev 已提交
419
        }
D
Daniel Micay 已提交
420
        m
M
musitdev 已提交
421
    }
422 423
}

S
Sean McArthur 已提交
424
impl<'a> ::Encoder<io::IoError> for Encoder<'a> {
A
Adolfo Ochagavía 已提交
425
    fn emit_nil(&mut self) -> EncodeResult { write!(self.writer, "null") }
426

427 428 429 430 431
    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) }
432

433 434 435 436 437
    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) }
438

S
Sean McArthur 已提交
439
    fn emit_bool(&mut self, v: bool) -> EncodeResult {
440
        if v {
A
Adolfo Ochagavía 已提交
441
            write!(self.writer, "true")
442
        } else {
A
Adolfo Ochagavía 已提交
443
            write!(self.writer, "false")
444 445 446
        }
    }

S
Sean McArthur 已提交
447
    fn emit_f64(&mut self, v: f64) -> EncodeResult {
A
Adolfo Ochagavía 已提交
448
        write!(self.writer, "{}", fmt_number_or_null(v))
A
Alex Crichton 已提交
449
    }
B
Barosl Lee 已提交
450 451 452
    fn emit_f32(&mut self, v: f32) -> EncodeResult {
        self.emit_f64(v as f64)
    }
453

454
    fn emit_char(&mut self, v: char) -> EncodeResult {
455
        escape_char(self.writer, v)
456
    }
S
Sean McArthur 已提交
457
    fn emit_str(&mut self, v: &str) -> EncodeResult {
458
        escape_str(self.writer, v)
A
Alex Crichton 已提交
459
    }
460

461 462 463
    fn emit_enum<F>(&mut self, _name: &str, f: F) -> EncodeResult where
        F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
    {
A
Adolfo Ochagavía 已提交
464 465
        f(self)
    }
466

467 468 469 470 471 472 473
    fn emit_enum_variant<F>(&mut self,
                            name: &str,
                            _id: uint,
                            cnt: uint,
                            f: F) -> EncodeResult where
        F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
    {
474 475 476 477
        // enums are encoded as strings or objects
        // Bunny => "Bunny"
        // Kangaroo(34,"William") => {"variant": "Kangaroo", "fields": [34,"William"]}
        if cnt == 0 {
478
            escape_str(self.writer, name)
479
        } else {
A
Adolfo Ochagavía 已提交
480
            try!(write!(self.writer, "{{\"variant\":"));
481
            try!(escape_str(self.writer, name));
A
Adolfo Ochagavía 已提交
482
            try!(write!(self.writer, ",\"fields\":["));
483
            try!(f(self));
A
Adolfo Ochagavía 已提交
484
            write!(self.writer, "]}}")
485 486
        }
    }
487

488 489 490
    fn emit_enum_variant_arg<F>(&mut self, idx: uint, f: F) -> EncodeResult where
        F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
    {
491
        if idx != 0 {
A
Adolfo Ochagavía 已提交
492
            try!(write!(self.writer, ","));
493
        }
S
Sean McArthur 已提交
494
        f(self)
495 496
    }

497 498 499 500 501 502 503
    fn emit_enum_struct_variant<F>(&mut self,
                                   name: &str,
                                   id: uint,
                                   cnt: uint,
                                   f: F) -> EncodeResult where
        F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
    {
504 505 506
        self.emit_enum_variant(name, id, cnt, f)
    }

507 508 509 510 511 512
    fn emit_enum_struct_variant_field<F>(&mut self,
                                         _: &str,
                                         idx: uint,
                                         f: F) -> EncodeResult where
        F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
    {
513 514 515
        self.emit_enum_variant_arg(idx, f)
    }

516 517 518
    fn emit_struct<F>(&mut self, _: &str, _: uint, f: F) -> EncodeResult where
        F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
    {
A
Adolfo Ochagavía 已提交
519
        try!(write!(self.writer, "{{"));
520
        try!(f(self));
A
Adolfo Ochagavía 已提交
521
        write!(self.writer, "}}")
522
    }
523

524 525 526
    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 已提交
527
        if idx != 0 { try!(write!(self.writer, ",")); }
528 529
        try!(escape_str(self.writer, name));
        try!(write!(self.writer, ":"));
S
Sean McArthur 已提交
530
        f(self)
531 532
    }

533 534 535
    fn emit_tuple<F>(&mut self, len: uint, f: F) -> EncodeResult where
        F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
    {
536 537
        self.emit_seq(len, f)
    }
538 539 540
    fn emit_tuple_arg<F>(&mut self, idx: uint, f: F) -> EncodeResult where
        F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
    {
541 542 543
        self.emit_seq_elt(idx, f)
    }

544 545 546
    fn emit_tuple_struct<F>(&mut self, _name: &str, len: uint, f: F) -> EncodeResult where
        F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
    {
547 548
        self.emit_seq(len, f)
    }
549 550 551
    fn emit_tuple_struct_arg<F>(&mut self, idx: uint, f: F) -> EncodeResult where
        F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
    {
552 553 554
        self.emit_seq_elt(idx, f)
    }

555 556 557
    fn emit_option<F>(&mut self, f: F) -> EncodeResult where
        F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
    {
S
Sean McArthur 已提交
558 559 560
        f(self)
    }
    fn emit_option_none(&mut self) -> EncodeResult { self.emit_nil() }
561 562 563
    fn emit_option_some<F>(&mut self, f: F) -> EncodeResult where
        F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
    {
S
Sean McArthur 已提交
564 565
        f(self)
    }
566

567 568 569
    fn emit_seq<F>(&mut self, _len: uint, f: F) -> EncodeResult where
        F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
    {
A
Adolfo Ochagavía 已提交
570
        try!(write!(self.writer, "["));
S
Sean McArthur 已提交
571
        try!(f(self));
A
Adolfo Ochagavía 已提交
572
        write!(self.writer, "]")
573 574
    }

575 576 577
    fn emit_seq_elt<F>(&mut self, idx: uint, f: F) -> EncodeResult where
        F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
    {
578
        if idx != 0 {
A
Adolfo Ochagavía 已提交
579
            try!(write!(self.writer, ","));
580 581 582 583
        }
        f(self)
    }

584 585 586
    fn emit_map<F>(&mut self, _len: uint, f: F) -> EncodeResult where
        F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
    {
A
Adolfo Ochagavía 已提交
587
        try!(write!(self.writer, "{{"));
588
        try!(f(self));
A
Adolfo Ochagavía 已提交
589
        write!(self.writer, "}}")
590
    }
591

592 593 594
    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 已提交
595
        if idx != 0 { try!(write!(self.writer, ",")) }
596 597
        // 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 已提交
598
        let mut buf = Vec::new();
N
Nick Cameron 已提交
599 600 601 602 603
        // 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 已提交
604
        let out = str::from_utf8(buf[]).unwrap();
A
Adolfo Ochagavía 已提交
605 606
        let needs_wrapping = out.char_at(0) != '"' && out.char_at_reverse(out.len()) != '"';
        if needs_wrapping { try!(write!(self.writer, "\"")); }
S
Sean McArthur 已提交
607
        try!(f(self));
A
Adolfo Ochagavía 已提交
608
        if needs_wrapping { try!(write!(self.writer, "\"")); }
S
Sean McArthur 已提交
609
        Ok(())
610 611
    }

612 613 614
    fn emit_map_elt_val<F>(&mut self, _idx: uint, f: F) -> EncodeResult where
        F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
    {
A
Adolfo Ochagavía 已提交
615
        try!(write!(self.writer, ":"));
616 617 618 619
        f(self)
    }
}

620 621
/// Another encoder for JSON, but prints out human-readable JSON instead of
/// compact data
E
Erik Price 已提交
622
pub struct PrettyEncoder<'a> {
623
    writer: &'a mut (io::Writer+'a),
624
    curr_indent: uint,
625
    indent: uint,
626 627
}

E
Erik Price 已提交
628
impl<'a> PrettyEncoder<'a> {
629
    /// Creates a new encoder whose output will be written to the specified writer
A
Adolfo Ochagavía 已提交
630
    pub fn new<'a>(writer: &'a mut io::Writer) -> PrettyEncoder<'a> {
631 632 633 634 635 636 637
        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.
    pub fn set_indent<'a>(&mut self, indent: uint) {
        // self.indent very well could be 0 so we need to use checked division.
638
        let level = self.curr_indent.checked_div(self.indent).unwrap_or(0);
639 640
        self.indent = indent;
        self.curr_indent = level * self.indent;
641
    }
642
}
643

S
Sean McArthur 已提交
644
impl<'a> ::Encoder<io::IoError> for PrettyEncoder<'a> {
A
Adolfo Ochagavía 已提交
645
    fn emit_nil(&mut self) -> EncodeResult { write!(self.writer, "null") }
646

647 648 649 650 651
    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) }
652

653 654 655 656 657
    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) }
658

S
Sean McArthur 已提交
659
    fn emit_bool(&mut self, v: bool) -> EncodeResult {
660
        if v {
A
Adolfo Ochagavía 已提交
661
            write!(self.writer, "true")
662
        } else {
A
Adolfo Ochagavía 已提交
663
            write!(self.writer, "false")
664 665 666
        }
    }

S
Sean McArthur 已提交
667
    fn emit_f64(&mut self, v: f64) -> EncodeResult {
A
Adolfo Ochagavía 已提交
668
        write!(self.writer, "{}", fmt_number_or_null(v))
A
Alex Crichton 已提交
669
    }
670 671 672
    fn emit_f32(&mut self, v: f32) -> EncodeResult {
        self.emit_f64(v as f64)
    }
673

674
    fn emit_char(&mut self, v: char) -> EncodeResult {
675
        escape_char(self.writer, v)
676
    }
S
Sean McArthur 已提交
677
    fn emit_str(&mut self, v: &str) -> EncodeResult {
678
        escape_str(self.writer, v)
A
Alex Crichton 已提交
679
    }
680

681 682 683
    fn emit_enum<F>(&mut self, _name: &str, f: F) -> EncodeResult where
        F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
    {
684 685 686
        f(self)
    }

687 688 689 690 691 692 693 694
    fn emit_enum_variant<F>(&mut self,
                            name: &str,
                            _id: uint,
                            cnt: uint,
                            f: F)
                            -> EncodeResult where
        F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
    {
695
        if cnt == 0 {
696
            escape_str(self.writer, name)
697
        } else {
698
            try!(write!(self.writer, "{{\n"));
699 700
            self.curr_indent += self.indent;
            try!(spaces(self.writer, self.curr_indent));
701
            try!(write!(self.writer, "\"variant\": "));
702 703
            try!(escape_str(self.writer, name));
            try!(write!(self.writer, ",\n"));
704 705 706
            try!(spaces(self.writer, self.curr_indent));
            try!(write!(self.writer, "\"fields\": [\n"));
            self.curr_indent += self.indent;
S
Sean McArthur 已提交
707
            try!(f(self));
708
            self.curr_indent -= self.indent;
709
            try!(write!(self.writer, "\n"));
710
            try!(spaces(self.writer, self.curr_indent));
711 712 713 714
            self.curr_indent -= self.indent;
            try!(write!(self.writer, "]\n"));
            try!(spaces(self.writer, self.curr_indent));
            write!(self.writer, "}}")
715 716 717
        }
    }

718 719 720
    fn emit_enum_variant_arg<F>(&mut self, idx: uint, f: F) -> EncodeResult where
        F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
    {
721
        if idx != 0 {
A
Adolfo Ochagavía 已提交
722
            try!(write!(self.writer, ",\n"));
723
        }
724
        try!(spaces(self.writer, self.curr_indent));
725 726 727
        f(self)
    }

728 729 730 731 732 733 734
    fn emit_enum_struct_variant<F>(&mut self,
                                   name: &str,
                                   id: uint,
                                   cnt: uint,
                                   f: F) -> EncodeResult where
        F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
    {
735 736 737
        self.emit_enum_variant(name, id, cnt, f)
    }

738 739 740 741 742 743
    fn emit_enum_struct_variant_field<F>(&mut self,
                                         _: &str,
                                         idx: uint,
                                         f: F) -> EncodeResult where
        F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
    {
744 745 746 747
        self.emit_enum_variant_arg(idx, f)
    }


748 749 750
    fn emit_struct<F>(&mut self, _: &str, len: uint, f: F) -> EncodeResult where
        F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
    {
751
        if len == 0 {
A
Adolfo Ochagavía 已提交
752
            write!(self.writer, "{{}}")
753
        } else {
A
Adolfo Ochagavía 已提交
754
            try!(write!(self.writer, "{{"));
755
            self.curr_indent += self.indent;
756
            try!(f(self));
757
            self.curr_indent -= self.indent;
758
            try!(write!(self.writer, "\n"));
759
            try!(spaces(self.writer, self.curr_indent));
760
            write!(self.writer, "}}")
761 762
        }
    }
763

764 765 766
    fn emit_struct_field<F>(&mut self, name: &str, idx: uint, f: F) -> EncodeResult where
        F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
    {
767
        if idx == 0 {
A
Adolfo Ochagavía 已提交
768
            try!(write!(self.writer, "\n"));
769
        } else {
A
Adolfo Ochagavía 已提交
770
            try!(write!(self.writer, ",\n"));
771
        }
772
        try!(spaces(self.writer, self.curr_indent));
773 774
        try!(escape_str(self.writer, name));
        try!(write!(self.writer, ": "));
S
Sean McArthur 已提交
775
        f(self)
776 777
    }

778 779 780
    fn emit_tuple<F>(&mut self, len: uint, f: F) -> EncodeResult where
        F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
    {
781 782
        self.emit_seq(len, f)
    }
783 784 785
    fn emit_tuple_arg<F>(&mut self, idx: uint, f: F) -> EncodeResult where
        F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
    {
786 787 788
        self.emit_seq_elt(idx, f)
    }

789 790 791
    fn emit_tuple_struct<F>(&mut self, _: &str, len: uint, f: F) -> EncodeResult where
        F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
    {
792 793
        self.emit_seq(len, f)
    }
794 795 796
    fn emit_tuple_struct_arg<F>(&mut self, idx: uint, f: F) -> EncodeResult where
        F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
    {
797 798 799
        self.emit_seq_elt(idx, f)
    }

800 801 802
    fn emit_option<F>(&mut self, f: F) -> EncodeResult where
        F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
    {
S
Sean McArthur 已提交
803 804 805
        f(self)
    }
    fn emit_option_none(&mut self) -> EncodeResult { self.emit_nil() }
806 807 808
    fn emit_option_some<F>(&mut self, f: F) -> EncodeResult where
        F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
    {
S
Sean McArthur 已提交
809 810
        f(self)
    }
811

812 813 814
    fn emit_seq<F>(&mut self, len: uint, f: F) -> EncodeResult where
        F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
    {
815
        if len == 0 {
A
Adolfo Ochagavía 已提交
816
            write!(self.writer, "[]")
817
        } else {
A
Adolfo Ochagavía 已提交
818
            try!(write!(self.writer, "["));
819
            self.curr_indent += self.indent;
S
Sean McArthur 已提交
820
            try!(f(self));
821
            self.curr_indent -= self.indent;
822
            try!(write!(self.writer, "\n"));
823
            try!(spaces(self.writer, self.curr_indent));
824
            write!(self.writer, "]")
825 826 827
        }
    }

828 829 830
    fn emit_seq_elt<F>(&mut self, idx: uint, f: F) -> EncodeResult where
        F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
    {
831
        if idx == 0 {
A
Adolfo Ochagavía 已提交
832
            try!(write!(self.writer, "\n"));
833
        } else {
A
Adolfo Ochagavía 已提交
834
            try!(write!(self.writer, ",\n"));
835
        }
836
        try!(spaces(self.writer, self.curr_indent));
837 838 839
        f(self)
    }

840 841 842
    fn emit_map<F>(&mut self, len: uint, f: F) -> EncodeResult where
        F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
    {
843
        if len == 0 {
A
Adolfo Ochagavía 已提交
844
            write!(self.writer, "{{}}")
845
        } else {
A
Adolfo Ochagavía 已提交
846
            try!(write!(self.writer, "{{"));
847
            self.curr_indent += self.indent;
848
            try!(f(self));
849
            self.curr_indent -= self.indent;
850
            try!(write!(self.writer, "\n"));
851
            try!(spaces(self.writer, self.curr_indent));
852
            write!(self.writer, "}}")
853 854
        }
    }
855

856 857 858
    fn emit_map_elt_key<F>(&mut self, idx: uint, mut f: F) -> EncodeResult where
        F: FnMut(&mut PrettyEncoder<'a>) -> EncodeResult,
    {
859
        if idx == 0 {
A
Adolfo Ochagavía 已提交
860
            try!(write!(self.writer, "\n"));
861
        } else {
A
Adolfo Ochagavía 已提交
862
            try!(write!(self.writer, ",\n"));
863
        }
864
        try!(spaces(self.writer, self.curr_indent));
865 866
        // 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 已提交
867
        let mut buf = Vec::new();
N
Nick Cameron 已提交
868 869 870 871 872
        // 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 已提交
873
        let out = str::from_utf8(buf[]).unwrap();
A
Adolfo Ochagavía 已提交
874 875
        let needs_wrapping = out.char_at(0) != '"' && out.char_at_reverse(out.len()) != '"';
        if needs_wrapping { try!(write!(self.writer, "\"")); }
S
Sean McArthur 已提交
876
        try!(f(self));
A
Adolfo Ochagavía 已提交
877
        if needs_wrapping { try!(write!(self.writer, "\"")); }
S
Sean McArthur 已提交
878
        Ok(())
879 880
    }

881 882 883
    fn emit_map_elt_val<F>(&mut self, _idx: uint, f: F) -> EncodeResult where
        F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
    {
A
Adolfo Ochagavía 已提交
884
        try!(write!(self.writer, ": "));
S
Sean McArthur 已提交
885
        f(self)
886 887 888
    }
}

889 890
impl<E: ::Encoder<S>, S> Encodable<E, S> for Json {
    fn encode(&self, e: &mut E) -> Result<(), S> {
891
        match *self {
892 893 894 895 896 897 898 899
            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(),
900 901 902 903
        }
    }
}

904
impl Json {
A
Adolfo Ochagavía 已提交
905 906 907
    /// Encodes a json value into an io::writer. Uses a single line.
    pub fn to_writer(&self, writer: &mut io::Writer) -> EncodeResult {
        let mut encoder = Encoder::new(writer);
S
Sean McArthur 已提交
908
        self.encode(&mut encoder)
909
    }
910

J
Jorge Aparicio 已提交
911
    /// Encodes a json value into an io::writer.
912
    /// Pretty-prints in a more readable format.
A
Adolfo Ochagavía 已提交
913 914
    pub fn to_pretty_writer(&self, writer: &mut io::Writer) -> EncodeResult {
        let mut encoder = PrettyEncoder::new(writer);
S
Sean McArthur 已提交
915
        self.encode(&mut encoder)
916
    }
917

918
    /// Encodes a json value into a string
919
    pub fn to_pretty_str(&self) -> string::String {
D
Daniel Micay 已提交
920
        let mut s = Vec::new();
A
Alex Crichton 已提交
921
        self.to_pretty_writer(&mut s as &mut io::Writer).unwrap();
D
Daniel Micay 已提交
922
        string::String::from_utf8(s).unwrap()
923
    }
924 925 926

     /// If the Json value is an Object, returns the value associated with the provided key.
    /// Otherwise, returns None.
927 928
    pub fn find<'a>(&'a self, key: &str) -> Option<&'a Json>{
        match self {
929
            &Json::Object(ref map) => map.get(key),
930 931 932 933
            _ => None
        }
    }

934
    /// Attempts to get a nested Json Object for each key in `keys`.
935
    /// If any key is found not to exist, find_path will return None.
936
    /// Otherwise, it will return the Json value associated with the final key.
937
    pub fn find_path<'a>(&'a self, keys: &[&str]) -> Option<&'a Json>{
938 939 940 941 942 943 944 945
        let mut target = self;
        for key in keys.iter() {
            match target.find(*key) {
                Some(t) => { target = t; },
                None => return None
            }
        }
        Some(target)
946 947 948 949 950
    }

    /// 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.
951 952
    pub fn search<'a>(&'a self, key: &str) -> Option<&'a Json> {
        match self {
953
            &Json::Object(ref map) => {
A
Aaron Turon 已提交
954
                match map.get(key) {
955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970
                    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
        }
    }

971 972
    /// Returns true if the Json value is an Object. Returns false otherwise.
    pub fn is_object<'a>(&'a self) -> bool {
973
        self.as_object().is_some()
974 975 976 977
    }

    /// If the Json value is an Object, returns the associated TreeMap.
    /// Returns None otherwise.
978
    pub fn as_object<'a>(&'a self) -> Option<&'a Object> {
979
        match self {
980
            &Json::Object(ref map) => Some(map),
981 982 983 984
            _ => None
        }
    }

C
Corey Farwell 已提交
985
    /// Returns true if the Json value is an Array. Returns false otherwise.
C
Corey Farwell 已提交
986 987
    pub fn is_array<'a>(&'a self) -> bool {
        self.as_array().is_some()
988 989
    }

C
Corey Farwell 已提交
990
    /// If the Json value is an Array, returns the associated vector.
991
    /// Returns None otherwise.
992
    pub fn as_array<'a>(&'a self) -> Option<&'a Array> {
993
        match self {
994
            &Json::Array(ref array) => Some(&*array),
995 996 997 998 999
            _ => None
        }
    }

    /// Returns true if the Json value is a String. Returns false otherwise.
1000 1001
    pub fn is_string<'a>(&'a self) -> bool {
        self.as_string().is_some()
1002 1003 1004 1005
    }

    /// If the Json value is a String, returns the associated str.
    /// Returns None otherwise.
1006
    pub fn as_string<'a>(&'a self) -> Option<&'a str> {
1007
        match *self {
1008
            Json::String(ref s) => Some(s.as_slice()),
1009 1010 1011 1012 1013 1014
            _ => None
        }
    }

    /// Returns true if the Json value is a Number. Returns false otherwise.
    pub fn is_number(&self) -> bool {
1015
        match *self {
1016
            Json::I64(_) | Json::U64(_) | Json::F64(_) => true,
1017 1018 1019 1020 1021 1022 1023
            _ => false,
        }
    }

    /// Returns true if the Json value is a i64. Returns false otherwise.
    pub fn is_i64(&self) -> bool {
        match *self {
1024
            Json::I64(_) => true,
1025 1026 1027 1028 1029 1030 1031
            _ => false,
        }
    }

    /// Returns true if the Json value is a u64. Returns false otherwise.
    pub fn is_u64(&self) -> bool {
        match *self {
1032
            Json::U64(_) => true,
1033 1034
            _ => false,
        }
1035 1036
    }

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

1045
    /// If the Json value is a number, return or cast it to a i64.
1046
    /// Returns None otherwise.
1047 1048
    pub fn as_i64(&self) -> Option<i64> {
        match *self {
1049 1050
            Json::I64(n) => Some(n),
            Json::U64(n) => num::cast(n),
1051 1052 1053 1054 1055 1056 1057 1058
            _ => 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 {
1059 1060
            Json::I64(n) => num::cast(n),
            Json::U64(n) => Some(n),
1061 1062 1063 1064
            _ => None
        }
    }

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

    /// Returns true if the Json value is a Boolean. Returns false otherwise.
    pub fn is_boolean(&self) -> bool {
1078
        self.as_boolean().is_some()
1079 1080 1081 1082 1083 1084
    }

    /// If the Json value is a Boolean, returns the associated bool.
    /// Returns None otherwise.
    pub fn as_boolean(&self) -> Option<bool> {
        match self {
1085
            &Json::Boolean(b) => Some(b),
1086 1087 1088 1089 1090 1091
            _ => None
        }
    }

    /// Returns true if the Json value is a Null. Returns false otherwise.
    pub fn is_null(&self) -> bool {
1092
        self.as_null().is_some()
1093 1094 1095 1096 1097 1098
    }

    /// If the Json value is a Null, returns ().
    /// Returns None otherwise.
    pub fn as_null(&self) -> Option<()> {
        match self {
1099
            &Json::Null => Some(()),
1100 1101 1102
            _ => None
        }
    }
E
Elly Jones 已提交
1103 1104
}

1105 1106 1107 1108 1109 1110 1111 1112 1113
impl<'a> ops::Index<&'a str, Json>  for Json {
    fn index<'a>(&'a self, idx: & &str) -> &'a Json {
        self.find(*idx).unwrap()
    }
}

impl ops::Index<uint, Json> for Json {
    fn index<'a>(&'a self, idx: &uint) -> &'a Json {
        match self {
1114
            &Json::Array(ref v) => v.index(idx),
C
Corey Farwell 已提交
1115
            _ => panic!("can only index Json with uint if it is an array")
1116 1117 1118 1119
        }
    }
}

1120
/// The output of the streaming parser.
1121
#[deriving(PartialEq, Clone, Show)]
1122 1123 1124
pub enum JsonEvent {
    ObjectStart,
    ObjectEnd,
C
Corey Farwell 已提交
1125 1126
    ArrayStart,
    ArrayEnd,
1127
    BooleanValue(bool),
1128 1129 1130
    I64Value(i64),
    U64Value(u64),
    F64Value(f64),
1131
    StringValue(string::String),
1132 1133 1134 1135
    NullValue,
    Error(ParserError),
}

1136
#[deriving(PartialEq, Show)]
1137
enum ParserState {
C
Corey Farwell 已提交
1138
    // Parse a value in an array, true means first element.
1139
    ParseArray(bool),
C
Corey Farwell 已提交
1140
    // Parse ',' or ']' after an element in an array.
C
Corey Farwell 已提交
1141
    ParseArrayComma,
1142 1143 1144 1145
    // 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 已提交
1146
    // Initial state.
1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164
    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
1165
#[deriving(PartialEq, Clone, Show)]
1166 1167 1168 1169 1170 1171 1172
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.
1173
#[deriving(PartialEq, Clone, Show)]
1174 1175 1176 1177 1178 1179 1180
enum InternalStackElement {
    InternalIndex(u32),
    InternalKey(u16, u16), // start, size
}

impl Stack {
    pub fn new() -> Stack {
A
Adolfo Ochagavía 已提交
1181
        Stack { stack: Vec::new(), str_buffer: Vec::new() }
1182 1183 1184 1185 1186
    }

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

A
Adolfo Ochagavía 已提交
1187 1188
    /// Returns true if the stack is empty.
    pub fn is_empty(&self) -> bool { self.stack.is_empty() }
1189 1190 1191 1192 1193

    /// 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 已提交
1194
        match self.stack[idx] {
1195
            InternalIndex(i) => Index(i),
A
Adolfo Ochagavía 已提交
1196
            InternalKey(start, size) => {
A
Adolfo Ochagavía 已提交
1197
                Key(str::from_utf8(
1198
                    self.str_buffer[start as uint .. start as uint + size as uint]).unwrap())
A
Adolfo Ochagavía 已提交
1199
            }
1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239
        }
    }

    /// 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(
1240
                    self.str_buffer[start as uint .. (start+size) as uint]
1241 1242 1243 1244 1245 1246
                ).unwrap()))
            }
        }
    }

    // Used by Parser to insert Key elements at the top of the stack.
1247
    fn push_key(&mut self, key: string::String) {
1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264
        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 已提交
1265
                self.str_buffer.truncate(new_size);
1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284
            }
            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 已提交
1285
            InternalIndex(i) => { i + 1 }
S
Steve Klabnik 已提交
1286
            _ => { panic!(); }
1287
        };
1288
        self.stack[len - 1] = InternalIndex(idx);
1289 1290 1291 1292 1293
    }
}

/// A streaming JSON parser implemented as an iterator of JsonEvent, consuming
/// an iterator of char.
G
Gary Linscott 已提交
1294
pub struct Parser<T> {
1295 1296 1297 1298
    rdr: T,
    ch: Option<char>,
    line: uint,
    col: uint,
1299 1300 1301
    // We maintain a stack representing where we are in the logical structure
    // of the JSON stream.
    stack: Stack,
J
Joseph Crail 已提交
1302
    // A state machine is kept to make it possible to interrupt and resume parsing.
1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324
    state: ParserState,
}

impl<T: Iterator<char>> Iterator<JsonEvent> for Parser<T> {
    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());
    }
1325 1326
}

1327
impl<T: Iterator<char>> Parser<T> {
1328
    /// Creates the JSON parser.
1329
    pub fn new(rdr: T) -> Parser<T> {
1330 1331
        let mut p = Parser {
            rdr: rdr,
1332
            ch: Some('\x00'),
1333 1334
            line: 1,
            col: 0,
1335 1336
            stack: Stack::new(),
            state: ParseStart,
1337 1338
        };
        p.bump();
1339
        return p;
1340
    }
E
Elly Jones 已提交
1341

1342 1343 1344
    /// Provides access to the current position in the logical structure of the
    /// JSON stream.
    pub fn stack<'l>(&'l self) -> &'l Stack {
1345
        return &self.stack;
1346
    }
1347

1348 1349
    fn eof(&self) -> bool { self.ch.is_none() }
    fn ch_or_null(&self) -> char { self.ch.unwrap_or('\x00') }
1350
    fn bump(&mut self) {
1351
        self.ch = self.rdr.next();
E
Elly Jones 已提交
1352

1353
        if self.ch_is('\n') {
1354 1355
            self.line += 1u;
            self.col = 1u;
G
Gary Linscott 已提交
1356 1357
        } else {
            self.col += 1u;
E
Elly Jones 已提交
1358
        }
1359 1360
    }

1361
    fn next_char(&mut self) -> Option<char> {
1362 1363 1364
        self.bump();
        self.ch
    }
1365 1366 1367
    fn ch_is(&self, c: char) -> bool {
        self.ch == Some(c)
    }
1368

1369 1370
    fn error<T>(&self, reason: ErrorCode) -> Result<T, ParserError> {
        Err(SyntaxError(reason, self.line, self.col))
1371 1372
    }

1373
    fn parse_whitespace(&mut self) {
1374 1375 1376 1377
        while self.ch_is(' ') ||
              self.ch_is('\n') ||
              self.ch_is('\t') ||
              self.ch_is('\r') { self.bump(); }
1378 1379
    }

1380
    fn parse_number(&mut self) -> JsonEvent {
1381
        let mut neg = false;
1382

1383
        if self.ch_is('-') {
1384
            self.bump();
1385
            neg = true;
E
Elly Jones 已提交
1386
        }
1387

1388
        let res = match self.parse_u64() {
1389 1390 1391
            Ok(res) => res,
            Err(e) => { return Error(e); }
        };
1392

1393 1394
        if self.ch_is('.') || self.ch_is('e') || self.ch_is('E') {
            let mut res = res as f64;
1395

1396 1397 1398 1399 1400 1401
            if self.ch_is('.') {
                res = match self.parse_decimal(res) {
                    Ok(res) => res,
                    Err(e) => { return Error(e); }
                };
            }
1402

1403 1404 1405 1406 1407 1408 1409
            if self.ch_is('e') || self.ch_is('E') {
                res = match self.parse_exponent(res) {
                    Ok(res) => res,
                    Err(e) => { return Error(e); }
                };
            }

1410 1411 1412 1413 1414
            if neg {
                res *= -1.0;
            }

            F64Value(res)
1415
        } else {
1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427
            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)
            }
1428
        }
E
Elly Jones 已提交
1429 1430
    }

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

1435 1436 1437
        match self.ch_or_null() {
            '0' => {
                self.bump();
1438

M
mrec 已提交
1439
                // A leading '0' must be the only digit before the decimal point.
1440
                match self.ch_or_null() {
1441
                    '0' ... '9' => return self.error(InvalidNumber),
1442 1443 1444
                    _ => ()
                }
            },
1445
            '1' ... '9' => {
1446 1447
                while !self.eof() {
                    match self.ch_or_null() {
1448
                        c @ '0' ... '9' => {
1449 1450 1451 1452 1453 1454
                            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); }

1455 1456 1457 1458
                            self.bump();
                        }
                        _ => break,
                    }
1459 1460
                }
            }
1461
            _ => return self.error(InvalidNumber),
E
Elly Jones 已提交
1462
        }
1463 1464

        Ok(accum)
E
Elly Jones 已提交
1465 1466
    }

A
Adolfo Ochagavía 已提交
1467
    fn parse_decimal(&mut self, mut res: f64) -> Result<f64, ParserError> {
1468 1469 1470
        self.bump();

        // Make sure a digit follows the decimal place.
1471
        match self.ch_or_null() {
1472
            '0' ... '9' => (),
1473
             _ => return self.error(InvalidNumber)
1474 1475
        }

D
Daniel Micay 已提交
1476
        let mut dec = 1.0;
1477
        while !self.eof() {
1478
            match self.ch_or_null() {
1479
                c @ '0' ... '9' => {
1480 1481 1482 1483 1484
                    dec /= 10.0;
                    res += (((c as int) - ('0' as int)) as f64) * dec;
                    self.bump();
                }
                _ => break,
E
Elly Jones 已提交
1485 1486
            }
        }
1487

1488
        Ok(res)
E
Elly Jones 已提交
1489 1490
    }

1491
    fn parse_exponent(&mut self, mut res: f64) -> Result<f64, ParserError> {
1492 1493
        self.bump();

1494 1495
        let mut exp = 0u;
        let mut neg_exp = false;
1496

1497 1498 1499 1500 1501
        if self.ch_is('+') {
            self.bump();
        } else if self.ch_is('-') {
            self.bump();
            neg_exp = true;
1502 1503 1504
        }

        // Make sure a digit follows the exponent place.
1505
        match self.ch_or_null() {
1506
            '0' ... '9' => (),
1507
            _ => return self.error(InvalidNumber)
1508 1509
        }
        while !self.eof() {
1510
            match self.ch_or_null() {
1511
                c @ '0' ... '9' => {
1512 1513
                    exp *= 10;
                    exp += (c as uint) - ('0' as uint);
1514

1515 1516 1517
                    self.bump();
                }
                _ => break
1518 1519 1520
            }
        }

1521
        let exp = 10_f64.powi(exp as i32);
1522 1523 1524 1525 1526 1527
        if neg_exp {
            res /= exp;
        } else {
            res *= exp;
        }

1528
        Ok(res)
E
Elly Jones 已提交
1529 1530
    }

1531
    fn decode_hex_escape(&mut self) -> Result<u16, ParserError> {
1532 1533
        let mut i = 0u;
        let mut n = 0u16;
A
Adolfo Ochagavía 已提交
1534
        while i < 4 && !self.eof() {
1535 1536
            self.bump();
            n = match self.ch_or_null() {
1537
                c @ '0' ... '9' => n * 16 + ((c as u16) - ('0' as u16)),
A
Adolfo Ochagavía 已提交
1538 1539 1540 1541 1542 1543
                '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,
1544
                _ => return self.error(InvalidEscape)
1545 1546 1547 1548 1549 1550
            };

            i += 1u;
        }

        // Error out if we didn't parse 4 digits.
A
Adolfo Ochagavía 已提交
1551
        if i != 4 {
1552
            return self.error(InvalidEscape);
1553 1554 1555 1556 1557
        }

        Ok(n)
    }

1558
    fn parse_str(&mut self) -> Result<string::String, ParserError> {
1559
        let mut escape = false;
1560
        let mut res = string::String::new();
1561

G
Gary Linscott 已提交
1562
        loop {
1563
            self.bump();
G
Gary Linscott 已提交
1564
            if self.eof() {
1565
                return self.error(EOFWhileParsingString);
G
Gary Linscott 已提交
1566
            }
1567

H
Huon Wilson 已提交
1568
            if escape {
1569
                match self.ch_or_null() {
1570 1571 1572 1573 1574 1575 1576 1577
                    '"' => 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'),
1578
                    'u' => match try!(self.decode_hex_escape()) {
1579 1580 1581
                        0xDC00 ... 0xDFFF => {
                            return self.error(LoneLeadingSurrogateInHexEscape)
                        }
1582 1583 1584

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

1591 1592
                            let buf = [n1, try!(self.decode_hex_escape())];
                            match str::utf16_items(buf.as_slice()).next() {
1593
                                Some(ScalarValue(c)) => res.push(c),
1594
                                _ => return self.error(LoneLeadingSurrogateInHexEscape),
1595
                            }
1596 1597
                        }

1598
                        n => match char::from_u32(n as u32) {
1599
                            Some(c) => res.push(c),
1600
                            None => return self.error(InvalidUnicodeCodePoint),
1601 1602
                        },
                    },
1603
                    _ => return self.error(InvalidEscape),
1604 1605
                }
                escape = false;
1606
            } else if self.ch_is('\\') {
1607 1608
                escape = true;
            } else {
1609
                match self.ch {
1610 1611
                    Some('"') => {
                        self.bump();
1612
                        return Ok(res);
1613
                    },
1614
                    Some(c) => res.push(c),
1615
                    None => unreachable!()
1616
                }
E
Elly Jones 已提交
1617 1618 1619 1620
            }
        }
    }

1621 1622 1623 1624
    // 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 已提交
1625
    // stream int the form of a stack that can be queried by the user using the
1626 1627 1628 1629
    // stack() method.
    fn parse(&mut self) -> JsonEvent {
        loop {
            // The only paths where the loop can spin a new iteration
C
Corey Farwell 已提交
1630
            // are in the cases ParseArrayComma and ParseObjectComma if ','
1631
            // is parsed. In these cases the state is set to (respectively)
1632
            // ParseArray(false) and ParseObject(false), which always return,
1633 1634 1635
            // 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();
1636

1637 1638 1639 1640
            match self.state {
                ParseStart => {
                    return self.parse_start();
                }
1641
                ParseArray(first) => {
C
Corey Farwell 已提交
1642
                    return self.parse_array(first);
1643
                }
C
Corey Farwell 已提交
1644 1645
                ParseArrayComma => {
                    match self.parse_array_comma_or_end() {
1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671
                        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 {
1672 1673 1674 1675
            Error(_) => ParseFinished,
            ArrayStart => ParseArray(true),
            ObjectStart => ParseObject(true),
            _ => ParseBeforeFinish,
1676 1677 1678
        };
        return val;
    }
1679

C
Corey Farwell 已提交
1680
    fn parse_array(&mut self, first: bool) -> JsonEvent {
1681
        if self.ch_is(']') {
1682
            if !first {
1683
                self.error_event(InvalidSyntax)
1684
            } else {
1685 1686 1687
                self.state = if self.stack.is_empty() {
                    ParseBeforeFinish
                } else if self.stack.last_is_index() {
C
Corey Farwell 已提交
1688
                    ParseArrayComma
1689 1690
                } else {
                    ParseObjectComma
1691 1692 1693
                };
                self.bump();
                ArrayEnd
1694
            }
1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706
        } 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
1707
        }
1708
    }
1709

C
Corey Farwell 已提交
1710
    fn parse_array_comma_or_end(&mut self) -> Option<JsonEvent> {
1711 1712
        if self.ch_is(',') {
            self.stack.bump_index();
1713
            self.state = ParseArray(false);
1714
            self.bump();
1715
            None
1716 1717
        } else if self.ch_is(']') {
            self.stack.pop();
1718 1719 1720 1721
            self.state = if self.stack.is_empty() {
                ParseBeforeFinish
            } else if self.stack.last_is_index() {
                ParseArrayComma
1722
            } else {
1723 1724
                ParseObjectComma
            };
1725
            self.bump();
1726
            Some(ArrayEnd)
1727
        } else if self.eof() {
1728
            Some(self.error_event(EOFWhileParsingArray))
1729
        } else {
1730
            Some(self.error_event(InvalidSyntax))
1731
        }
E
Elly Jones 已提交
1732 1733
    }

1734 1735 1736
    fn parse_object(&mut self, first: bool) -> JsonEvent {
        if self.ch_is('}') {
            if !first {
1737 1738 1739 1740 1741
                if self.stack.is_empty() {
                    return self.error_event(TrailingComma);
                } else {
                    self.stack.pop();
                }
1742
            }
1743 1744 1745 1746
            self.state = if self.stack.is_empty() {
                ParseBeforeFinish
            } else if self.stack.last_is_index() {
                ParseArrayComma
1747
            } else {
1748 1749
                ParseObjectComma
            };
1750 1751 1752 1753 1754 1755 1756 1757 1758 1759
            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() {
1760
            Ok(s) => s,
1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772
            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);
1773 1774 1775
        self.bump();
        self.parse_whitespace();

1776
        let val = self.parse_value();
1777

1778
        self.state = match val {
1779 1780 1781 1782
            Error(_) => ParseFinished,
            ArrayStart => ParseArray(true),
            ObjectStart => ParseObject(true),
            _ => ParseObjectComma,
1783 1784 1785 1786 1787
        };
        return val;
    }

    fn parse_object_end(&mut self) -> JsonEvent {
1788
        if self.ch_is('}') {
1789 1790 1791 1792
            self.state = if self.stack.is_empty() {
                ParseBeforeFinish
            } else if self.stack.last_is_index() {
                ParseArrayComma
1793
            } else {
1794 1795
                ParseObjectComma
            };
1796
            self.bump();
A
Adolfo Ochagavía 已提交
1797
            ObjectEnd
1798
        } else if self.eof() {
A
Adolfo Ochagavía 已提交
1799
            self.error_event(EOFWhileParsingObject)
1800
        } else {
A
Adolfo Ochagavía 已提交
1801
            self.error_event(InvalidSyntax)
1802
        }
1803
    }
1804

1805 1806 1807
    fn parse_value(&mut self) -> JsonEvent {
        if self.eof() { return self.error_event(EOFWhileParsingValue); }
        match self.ch_or_null() {
A
Adolfo Ochagavía 已提交
1808 1809 1810
            'n' => { self.parse_ident("ull", NullValue) }
            't' => { self.parse_ident("rue", BooleanValue(true)) }
            'f' => { self.parse_ident("alse", BooleanValue(false)) }
1811
            '0' ... '9' | '-' => self.parse_number(),
A
Adolfo Ochagavía 已提交
1812
            '"' => match self.parse_str() {
1813 1814 1815 1816 1817
                Ok(s) => StringValue(s),
                Err(e) => Error(e),
            },
            '[' => {
                self.bump();
C
Corey Farwell 已提交
1818
                ArrayStart
1819 1820 1821
            }
            '{' => {
                self.bump();
A
Adolfo Ochagavía 已提交
1822
                ObjectStart
1823
            }
A
Adolfo Ochagavía 已提交
1824
            _ => { self.error_event(InvalidSyntax) }
1825 1826
        }
    }
1827

1828 1829 1830 1831 1832 1833 1834 1835
    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))
        }
    }
1836

1837 1838 1839 1840 1841
    fn error_event(&mut self, reason: ErrorCode) -> JsonEvent {
        self.state = ParseFinished;
        Error(SyntaxError(reason, self.line, self.col))
    }
}
1842

1843 1844 1845 1846 1847
/// A Builder consumes a json::Parser to create a generic Json structure.
pub struct Builder<T> {
    parser: Parser<T>,
    token: Option<JsonEvent>,
}
1848

1849 1850 1851
impl<T: Iterator<char>> Builder<T> {
    /// Create a JSON Builder.
    pub fn new(src: T) -> Builder<T> {
A
Adolfo Ochagavía 已提交
1852
        Builder { parser: Parser::new(src), token: None, }
1853 1854 1855 1856 1857 1858 1859 1860 1861 1862
    }

    // 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 已提交
1863
            ref tok => { panic!("unexpected token {}", tok.clone()); }
1864
        }
A
Adolfo Ochagavía 已提交
1865
        result
1866 1867 1868 1869 1870 1871 1872
    }

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

    fn build_value(&mut self) -> Result<Json, BuilderError> {
1873 1874 1875 1876 1877 1878
        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)),
1879
            Some(StringValue(ref mut s)) => {
1880
                let mut temp = string::String::new();
1881
                swap(s, &mut temp);
1882
                Ok(Json::String(temp))
1883
            }
1884 1885 1886 1887 1888 1889
            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),
1890 1891
        }
    }
1892

C
Corey Farwell 已提交
1893
    fn build_array(&mut self) -> Result<Json, BuilderError> {
1894 1895 1896 1897
        self.bump();
        let mut values = Vec::new();

        loop {
C
Corey Farwell 已提交
1898
            if self.token == Some(ArrayEnd) {
1899
                return Ok(Json::Array(values.into_iter().collect()));
1900 1901 1902 1903
            }
            match self.build_value() {
                Ok(v) => values.push(v),
                Err(e) => { return Err(e) }
1904
            }
1905
            self.bump();
1906
        }
1907
    }
1908

1909 1910 1911
    fn build_object(&mut self) -> Result<Json, BuilderError> {
        self.bump();

A
Adolfo Ochagavía 已提交
1912
        let mut values = TreeMap::new();
1913

A
Adolfo Ochagavía 已提交
1914
        loop {
1915
            match self.token {
1916
                Some(ObjectEnd) => { return Ok(Json::Object(values)); }
1917 1918 1919 1920 1921
                Some(Error(e)) => { return Err(e); }
                None => { break; }
                _ => {}
            }
            let key = match self.parser.stack().top() {
1922
                Some(Key(k)) => { k.to_string() }
S
Steve Klabnik 已提交
1923
                _ => { panic!("invalid state"); }
1924 1925 1926 1927 1928 1929 1930 1931
            };
            match self.build_value() {
                Ok(value) => { values.insert(key, value); }
                Err(e) => { return Err(e); }
            }
            self.bump();
        }
        return self.parser.error(EOFWhileParsingObject);
L
Lenny222 已提交
1932 1933 1934
    }
}

A
Alex Crichton 已提交
1935
/// Decodes a json value from an `&mut io::Reader`
1936
pub fn from_reader(rdr: &mut io::Reader) -> Result<Json, BuilderError> {
A
Alex Crichton 已提交
1937
    let contents = match rdr.read_to_end() {
1938
        Ok(c)  => c,
1939
        Err(e) => return Err(io_error_to_error(e))
A
Alex Crichton 已提交
1940
    };
1941 1942 1943
    let s = match str::from_utf8(contents.as_slice()) {
        Some(s) => s,
        _       => return Err(SyntaxError(NotUtf8, 0, 0))
A
Alex Crichton 已提交
1944
    };
1945
    let mut builder = Builder::new(s.chars());
1946
    builder.build()
E
Elly Jones 已提交
1947 1948
}

1949
/// Decodes a json value from a string
1950 1951
pub fn from_str(s: &str) -> Result<Json, BuilderError> {
    let mut builder = Builder::new(s.chars());
A
Adolfo Ochagavía 已提交
1952
    builder.build()
1953 1954
}

1955
/// A structure to decode JSON to values in rust.
1956
pub struct Decoder {
1957
    stack: Vec<Json>,
1958 1959
}

1960 1961
impl Decoder {
    /// Creates a new decoder instance for decoding the specified JSON value.
1962
    pub fn new(json: Json) -> Decoder {
A
Adolfo Ochagavía 已提交
1963
        Decoder { stack: vec![json] }
1964
    }
1965 1966
}

1967
impl Decoder {
S
Sean McArthur 已提交
1968 1969
    fn pop(&mut self) -> Json {
        self.stack.pop().unwrap()
1970 1971 1972
    }
}

S
Sean McArthur 已提交
1973 1974 1975
macro_rules! expect(
    ($e:expr, Null) => ({
        match $e {
1976
            Json::Null => Ok(()),
1977
            other => Err(ExpectedError("Null".into_string(),
A
Alex Crichton 已提交
1978
                                       format!("{}", other)))
S
Sean McArthur 已提交
1979 1980 1981 1982
        }
    });
    ($e:expr, $t:ident) => ({
        match $e {
1983
            Json::$t(v) => Ok(v),
1984
            other => {
1985
                Err(ExpectedError(stringify!($t).to_string(),
A
Alex Crichton 已提交
1986
                                  format!("{}", other)))
1987
            }
1988
        }
S
Sean McArthur 已提交
1989 1990 1991
    })
)

1992 1993 1994 1995
macro_rules! read_primitive {
    ($name:ident, $ty:ty) => {
        fn $name(&mut self) -> DecodeResult<$ty> {
            match self.pop() {
B
Barosl Lee 已提交
1996 1997
                Json::I64(f) => match num::cast(f) {
                    Some(f) => Ok(f),
1998
                    None => Err(ExpectedError("Number".into_string(), format!("{}", f))),
1999
                },
B
Barosl Lee 已提交
2000 2001
                Json::U64(f) => match num::cast(f) {
                    Some(f) => Ok(f),
2002
                    None => Err(ExpectedError("Number".into_string(), format!("{}", f))),
B
Barosl Lee 已提交
2003
                },
2004
                Json::F64(f) => Err(ExpectedError("Integer".into_string(), format!("{}", f))),
B
Barosl Lee 已提交
2005 2006 2007 2008
                // 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),
2009
                    None => Err(ExpectedError("Number".into_string(), s)),
2010
                },
2011
                value => Err(ExpectedError("Number".into_string(), format!("{}", value))),
2012 2013 2014 2015 2016
            }
        }
    }
}

2017
impl ::Decoder<DecoderError> for Decoder {
S
Sean McArthur 已提交
2018 2019
    fn read_nil(&mut self) -> DecodeResult<()> {
        debug!("read_nil");
A
Adolfo Ochagavía 已提交
2020
        expect!(self.pop(), Null)
2021 2022
    }

2023 2024 2025 2026 2027 2028 2029 2030 2031 2032
    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)
2033

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

S
Sean McArthur 已提交
2036
    fn read_f64(&mut self) -> DecodeResult<f64> {
2037
        debug!("read_f64");
S
Sean McArthur 已提交
2038
        match self.pop() {
2039 2040 2041 2042
            Json::I64(f) => Ok(f as f64),
            Json::U64(f) => Ok(f as f64),
            Json::F64(f) => Ok(f),
            Json::String(s) => {
2043
                // re: #12967.. a type w/ numeric keys (ie HashMap<uint, V> etc)
A
Adolfo Ochagavía 已提交
2044
                // is going to have a string here, as per JSON spec.
B
Brendan Zabarauskas 已提交
2045
                match std::str::from_str(s.as_slice()) {
2046
                    Some(f) => Ok(f),
2047
                    None => Err(ExpectedError("Number".into_string(), s)),
2048
                }
2049
            },
2050
            Json::Null => Ok(f64::NAN),
2051
            value => Err(ExpectedError("Number".into_string(), format!("{}", value)))
2052 2053
        }
    }
2054

2055 2056 2057 2058
    fn read_bool(&mut self) -> DecodeResult<bool> {
        debug!("read_bool");
        expect!(self.pop(), Boolean)
    }
2059

S
Sean McArthur 已提交
2060 2061
    fn read_char(&mut self) -> DecodeResult<char> {
        let s = try!(self.read_str());
2062
        {
2063
            let mut it = s.chars();
2064 2065
            match (it.next(), it.next()) {
                // exactly one character
S
Sean McArthur 已提交
2066
                (Some(c), None) => return Ok(c),
2067 2068 2069
                _ => ()
            }
        }
2070
        Err(ExpectedError("single character string".into_string(), format!("{}", s)))
2071 2072
    }

2073
    fn read_str(&mut self) -> DecodeResult<string::String> {
2074
        debug!("read_str");
A
Adolfo Ochagavía 已提交
2075
        expect!(self.pop(), String)
2076 2077
    }

2078 2079 2080
    fn read_enum<T, F>(&mut self, name: &str, f: F) -> DecodeResult<T> where
        F: FnOnce(&mut Decoder) -> DecodeResult<T>,
    {
2081
        debug!("read_enum({})", name);
2082 2083 2084
        f(self)
    }

2085 2086 2087
    fn read_enum_variant<T, F>(&mut self, names: &[&str], f: F) -> DecodeResult<T> where
        F: FnOnce(&mut Decoder, uint) -> DecodeResult<T>,
    {
2088
        debug!("read_enum_variant(names={})", names);
S
Sean McArthur 已提交
2089
        let name = match self.pop() {
2090 2091
            Json::String(s) => s,
            Json::Object(mut o) => {
2092
                let n = match o.remove(&"variant".into_string()) {
2093
                    Some(Json::String(s)) => s,
2094
                    Some(val) => {
2095
                        return Err(ExpectedError("String".into_string(), format!("{}", val)))
2096 2097
                    }
                    None => {
2098
                        return Err(MissingFieldError("variant".into_string()))
2099
                    }
2100
                };
2101
                match o.remove(&"fields".into_string()) {
2102
                    Some(Json::Array(l)) => {
A
Aaron Turon 已提交
2103
                        for field in l.into_iter().rev() {
A
Adolfo Ochagavía 已提交
2104
                            self.stack.push(field);
2105 2106
                        }
                    },
2107
                    Some(val) => {
2108
                        return Err(ExpectedError("Array".into_string(), format!("{}", val)))
2109 2110
                    }
                    None => {
2111
                        return Err(MissingFieldError("fields".into_string()))
2112
                    }
2113
                }
2114
                n
2115
            }
2116
            json => {
2117
                return Err(ExpectedError("String or Object".into_string(), format!("{}", json)))
2118
            }
2119
        };
2120
        let idx = match names.iter()
A
Adolfo Ochagavía 已提交
2121
                             .position(|n| str::eq_slice(*n, name.as_slice())) {
2122
            Some(idx) => idx,
S
Sean McArthur 已提交
2123
            None => return Err(UnknownVariantError(name))
2124 2125 2126 2127
        };
        f(self, idx)
    }

2128 2129 2130
    fn read_enum_variant_arg<T, F>(&mut self, idx: uint, f: F) -> DecodeResult<T> where
        F: FnOnce(&mut Decoder) -> DecodeResult<T>,
    {
2131
        debug!("read_enum_variant_arg(idx={})", idx);
2132 2133 2134
        f(self)
    }

2135 2136 2137
    fn read_enum_struct_variant<T, F>(&mut self, names: &[&str], f: F) -> DecodeResult<T> where
        F: FnOnce(&mut Decoder, uint) -> DecodeResult<T>,
    {
2138
        debug!("read_enum_struct_variant(names={})", names);
2139 2140 2141 2142
        self.read_enum_variant(names, f)
    }


2143
    fn read_enum_struct_variant_field<T, F>(&mut self,
2144 2145
                                         name: &str,
                                         idx: uint,
2146 2147 2148 2149
                                         f: F)
                                         -> DecodeResult<T> where
        F: FnOnce(&mut Decoder) -> DecodeResult<T>,
    {
2150
        debug!("read_enum_struct_variant_field(name={}, idx={})", name, idx);
2151 2152 2153
        self.read_enum_variant_arg(idx, f)
    }

2154 2155 2156
    fn read_struct<T, F>(&mut self, name: &str, len: uint, f: F) -> DecodeResult<T> where
        F: FnOnce(&mut Decoder) -> DecodeResult<T>,
    {
2157
        debug!("read_struct(name={}, len={})", name, len);
S
Sean McArthur 已提交
2158 2159 2160
        let value = try!(f(self));
        self.pop();
        Ok(value)
2161 2162
    }

2163 2164 2165 2166 2167 2168 2169
    fn read_struct_field<T, F>(&mut self,
                               name: &str,
                               idx: uint,
                               f: F)
                               -> DecodeResult<T> where
        F: FnOnce(&mut Decoder) -> DecodeResult<T>,
    {
2170
        debug!("read_struct_field(name={}, idx={})", name, idx);
S
Sean McArthur 已提交
2171 2172
        let mut obj = try!(expect!(self.pop(), Object));

2173
        let value = match obj.remove(&name.to_string()) {
2174 2175 2176
            None => {
                // Add a Null and try to parse it as an Option<_>
                // to get None as a default value.
2177
                self.stack.push(Json::Null);
2178 2179 2180 2181 2182
                match f(self) {
                    Ok(x) => x,
                    Err(_) => return Err(MissingFieldError(name.to_string())),
                }
            },
S
Sean McArthur 已提交
2183 2184 2185
            Some(json) => {
                self.stack.push(json);
                try!(f(self))
2186
            }
S
Sean McArthur 已提交
2187
        };
2188
        self.stack.push(Json::Object(obj));
S
Sean McArthur 已提交
2189
        Ok(value)
2190 2191
    }

2192 2193 2194
    fn read_tuple<T, F>(&mut self, tuple_len: uint, f: F) -> DecodeResult<T> where
        F: FnOnce(&mut Decoder) -> DecodeResult<T>,
    {
2195
        debug!("read_tuple()");
2196
        self.read_seq(move |d, len| {
2197 2198 2199 2200 2201
            if len == tuple_len {
                f(d)
            } else {
                Err(ExpectedError(format!("Tuple{}", tuple_len), format!("Tuple{}", len)))
            }
2202
        })
2203 2204
    }

2205 2206 2207
    fn read_tuple_arg<T, F>(&mut self, idx: uint, f: F) -> DecodeResult<T> where
        F: FnOnce(&mut Decoder) -> DecodeResult<T>,
    {
2208
        debug!("read_tuple_arg(idx={})", idx);
2209 2210 2211
        self.read_seq_elt(idx, f)
    }

2212 2213 2214 2215 2216 2217 2218
    fn read_tuple_struct<T, F>(&mut self,
                               name: &str,
                               len: uint,
                               f: F)
                               -> DecodeResult<T> where
        F: FnOnce(&mut Decoder) -> DecodeResult<T>,
    {
2219
        debug!("read_tuple_struct(name={})", name);
2220
        self.read_tuple(len, f)
2221 2222
    }

2223 2224 2225 2226 2227 2228
    fn read_tuple_struct_arg<T, F>(&mut self,
                                   idx: uint,
                                   f: F)
                                   -> DecodeResult<T> where
        F: FnOnce(&mut Decoder) -> DecodeResult<T>,
    {
2229
        debug!("read_tuple_struct_arg(idx={})", idx);
2230 2231 2232
        self.read_tuple_arg(idx, f)
    }

2233 2234 2235
    fn read_option<T, F>(&mut self, f: F) -> DecodeResult<T> where
        F: FnOnce(&mut Decoder, bool) -> DecodeResult<T>,
    {
2236
        debug!("read_option()");
S
Sean McArthur 已提交
2237
        match self.pop() {
2238
            Json::Null => f(self, false),
2239 2240 2241 2242
            value => { self.stack.push(value); f(self, true) }
        }
    }

2243 2244 2245
    fn read_seq<T, F>(&mut self, f: F) -> DecodeResult<T> where
        F: FnOnce(&mut Decoder, uint) -> DecodeResult<T>,
    {
2246
        debug!("read_seq()");
C
Corey Farwell 已提交
2247 2248 2249
        let array = try!(expect!(self.pop(), Array));
        let len = array.len();
        for v in array.into_iter().rev() {
S
Sean McArthur 已提交
2250 2251
            self.stack.push(v);
        }
2252 2253 2254
        f(self, len)
    }

2255 2256 2257
    fn read_seq_elt<T, F>(&mut self, idx: uint, f: F) -> DecodeResult<T> where
        F: FnOnce(&mut Decoder) -> DecodeResult<T>,
    {
2258
        debug!("read_seq_elt(idx={})", idx);
2259 2260 2261
        f(self)
    }

2262 2263 2264
    fn read_map<T, F>(&mut self, f: F) -> DecodeResult<T> where
        F: FnOnce(&mut Decoder, uint) -> DecodeResult<T>,
    {
2265
        debug!("read_map()");
S
Sean McArthur 已提交
2266 2267
        let obj = try!(expect!(self.pop(), Object));
        let len = obj.len();
A
Aaron Turon 已提交
2268
        for (key, value) in obj.into_iter() {
S
Sean McArthur 已提交
2269
            self.stack.push(value);
2270
            self.stack.push(Json::String(key));
S
Sean McArthur 已提交
2271
        }
2272 2273 2274
        f(self, len)
    }

2275 2276 2277
    fn read_map_elt_key<T, F>(&mut self, idx: uint, f: F) -> DecodeResult<T> where
       F: FnOnce(&mut Decoder) -> DecodeResult<T>,
    {
2278
        debug!("read_map_elt_key(idx={})", idx);
2279 2280 2281
        f(self)
    }

2282 2283 2284
    fn read_map_elt_val<T, F>(&mut self, idx: uint, f: F) -> DecodeResult<T> where
       F: FnOnce(&mut Decoder) -> DecodeResult<T>,
    {
2285
        debug!("read_map_elt_val(idx={})", idx);
2286 2287
        f(self)
    }
2288 2289 2290 2291

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

2294
/// A trait for converting values to JSON
J
Jorge Aparicio 已提交
2295
pub trait ToJson for Sized? {
2296 2297 2298
    /// Converts the value of `self` to an instance of JSON
    fn to_json(&self) -> Json;
}
2299

2300 2301 2302
macro_rules! to_json_impl_i64(
    ($($t:ty), +) => (
        $(impl ToJson for $t {
2303
            fn to_json(&self) -> Json { Json::I64(*self as i64) }
2304 2305 2306 2307 2308 2309 2310
        })+
    )
)

to_json_impl_i64!(int, i8, i16, i32, i64)

macro_rules! to_json_impl_u64(
A
Adolfo Ochagavía 已提交
2311 2312
    ($($t:ty), +) => (
        $(impl ToJson for $t {
2313
            fn to_json(&self) -> Json { Json::U64(*self as u64) }
A
Adolfo Ochagavía 已提交
2314 2315 2316
        })+
    )
)
2317

2318
to_json_impl_u64!(uint, u8, u16, u32, u64)
2319

A
Adolfo Ochagavía 已提交
2320 2321
impl ToJson for Json {
    fn to_json(&self) -> Json { self.clone() }
2322 2323
}

2324
impl ToJson for f32 {
M
mrec 已提交
2325
    fn to_json(&self) -> Json { (*self as f64).to_json() }
2326 2327
}

2328
impl ToJson for f64 {
M
mrec 已提交
2329 2330
    fn to_json(&self) -> Json {
        match self.classify() {
2331 2332
            FPNaN | FPInfinite => Json::Null,
            _                  => Json::F64(*self)
M
mrec 已提交
2333 2334
        }
    }
2335 2336
}

2337
impl ToJson for () {
2338
    fn to_json(&self) -> Json { Json::Null }
2339 2340
}

2341
impl ToJson for bool {
2342
    fn to_json(&self) -> Json { Json::Boolean(*self) }
2343 2344
}

2345
impl ToJson for str {
2346
    fn to_json(&self) -> Json { Json::String(self.into_string()) }
2347 2348
}

2349
impl ToJson for string::String {
2350
    fn to_json(&self) -> Json { Json::String((*self).clone()) }
2351 2352
}

2353 2354 2355 2356 2357 2358 2359 2360 2361
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]
2362
            #[allow(non_snake_case)]
2363 2364
            fn to_json(&self) -> Json {
                match *self {
2365
                    ($(ref $tyvar),*,) => Json::Array(vec![$($tyvar.to_json()),*])
2366
                }
A
Adolfo Ochagavía 已提交
2367
            }
2368
        }
2369 2370 2371
    }
}

2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383
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}
2384

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

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

2393
impl<A: ToJson> ToJson for TreeMap<string::String, A> {
B
Ben Striegel 已提交
2394
    fn to_json(&self) -> Json {
2395
        let mut d = TreeMap::new();
D
Daniel Micay 已提交
2396
        for (key, value) in self.iter() {
2397
            d.insert((*key).clone(), value.to_json());
2398
        }
2399
        Json::Object(d)
2400 2401 2402
    }
}

2403
impl<A: ToJson> ToJson for HashMap<string::String, A> {
G
Graydon Hoare 已提交
2404
    fn to_json(&self) -> Json {
2405
        let mut d = TreeMap::new();
D
Daniel Micay 已提交
2406
        for (key, value) in self.iter() {
2407
            d.insert((*key).clone(), value.to_json());
G
Graydon Hoare 已提交
2408
        }
2409
        Json::Object(d)
G
Graydon Hoare 已提交
2410 2411 2412
    }
}

2413
impl<A:ToJson> ToJson for Option<A> {
B
Ben Striegel 已提交
2414 2415
    fn to_json(&self) -> Json {
        match *self {
2416
            None => Json::Null,
A
Adolfo Ochagavía 已提交
2417
            Some(ref value) => value.to_json()
2418 2419 2420 2421
        }
    }
}

2422
impl fmt::Show for Json {
2423
    /// Encodes a json value into a string
2424
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
A
Alex Crichton 已提交
2425
        self.to_writer(f).map_err(|_| fmt::Error)
2426
    }
2427 2428
}

B
Brendan Zabarauskas 已提交
2429
impl FromStr for Json {
A
Adolfo Ochagavía 已提交
2430 2431 2432 2433 2434
    fn from_str(s: &str) -> Option<Json> {
        from_str(s).ok()
    }
}

2435 2436
#[cfg(test)]
mod tests {
2437
    extern crate test;
S
Steven Fackler 已提交
2438 2439
    use self::Animal::*;
    use self::DecodeEnum::*;
2440
    use self::test::Bencher;
A
Alex Crichton 已提交
2441
    use {Encodable, Decodable};
2442 2443 2444 2445 2446 2447 2448 2449 2450 2451
    use super::Json::*;
    use super::ErrorCode::*;
    use super::ParserError::*;
    use super::DecoderError::*;
    use super::JsonEvent::*;
    use super::ParserState::*;
    use super::StackElement::*;
    use super::InternalStackElement::*;
    use super::{PrettyEncoder, Json, from_str, DecodeResult, DecoderError, JsonEvent, Parser,
                StackElement, Stack, Encoder, Decoder};
2452
    use std::{i64, u64, f32, f64, io};
2453
    use std::collections::TreeMap;
2454
    use std::num::Float;
2455
    use std::string;
2456

2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478
    #[deriving(Decodable, Eq, PartialEq, Show)]
    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\": [] }",
2479
                                ExpectedError("Number".into_string(), "[]".into_string()));
2480
        check_err::<OptionData>("{ \"opt\": false }",
2481
                                ExpectedError("Number".into_string(), "false".into_string()));
2482 2483
    }

2484
    #[deriving(PartialEq, Encodable, Decodable, Show)]
2485 2486
    enum Animal {
        Dog,
2487
        Frog(string::String, int)
2488 2489
    }

2490
    #[deriving(PartialEq, Encodable, Decodable, Show)]
2491 2492 2493
    struct Inner {
        a: (),
        b: uint,
2494
        c: Vec<string::String>,
2495 2496
    }

2497
    #[deriving(PartialEq, Encodable, Decodable, Show)]
2498
    struct Outer {
K
Kevin Ballard 已提交
2499
        inner: Vec<Inner>,
2500 2501
    }

2502
    fn mk_object(items: &[(string::String, Json)]) -> Json {
A
Adolfo Ochagavía 已提交
2503
        let mut d = TreeMap::new();
2504

D
Daniel Micay 已提交
2505
        for item in items.iter() {
2506
            match *item {
2507
                (ref key, ref value) => { d.insert((*key).clone(), (*value).clone()); },
2508
            }
2509 2510
        };

L
Luqman Aden 已提交
2511
        Object(d)
2512 2513
    }

A
Adolfo Ochagavía 已提交
2514 2515 2516
    #[test]
    fn test_from_str_trait() {
        let s = "null";
B
Brendan Zabarauskas 已提交
2517
        assert!(::std::str::from_str::<Json>(s).unwrap() == from_str(s).unwrap());
A
Adolfo Ochagavía 已提交
2518 2519
    }

2520 2521
    #[test]
    fn test_write_null() {
B
Barosl Lee 已提交
2522 2523
        assert_eq!(Null.to_string(), "null");
        assert_eq!(Null.to_pretty_str(), "null");
2524 2525
    }

2526 2527
    #[test]
    fn test_write_i64() {
B
Barosl Lee 已提交
2528 2529
        assert_eq!(U64(0).to_string(), "0");
        assert_eq!(U64(0).to_pretty_str(), "0");
2530

B
Barosl Lee 已提交
2531 2532
        assert_eq!(U64(1234).to_string(), "1234");
        assert_eq!(U64(1234).to_pretty_str(), "1234");
2533

B
Barosl Lee 已提交
2534 2535
        assert_eq!(I64(-5678).to_string(), "-5678");
        assert_eq!(I64(-5678).to_pretty_str(), "-5678");
2536 2537 2538

        assert_eq!(U64(7650007200025252000).to_string(), "7650007200025252000");
        assert_eq!(U64(7650007200025252000).to_pretty_str(), "7650007200025252000");
2539
    }
2540

2541
    #[test]
2542
    fn test_write_f64() {
B
Barosl Lee 已提交
2543 2544
        assert_eq!(F64(3.0).to_string(), "3.0");
        assert_eq!(F64(3.0).to_pretty_str(), "3.0");
2545

B
Barosl Lee 已提交
2546 2547
        assert_eq!(F64(3.1).to_string(), "3.1");
        assert_eq!(F64(3.1).to_pretty_str(), "3.1");
2548

B
Barosl Lee 已提交
2549 2550
        assert_eq!(F64(-1.5).to_string(), "-1.5");
        assert_eq!(F64(-1.5).to_pretty_str(), "-1.5");
2551

B
Barosl Lee 已提交
2552 2553
        assert_eq!(F64(0.5).to_string(), "0.5");
        assert_eq!(F64(0.5).to_pretty_str(), "0.5");
M
mrec 已提交
2554

B
Barosl Lee 已提交
2555 2556
        assert_eq!(F64(f64::NAN).to_string(), "null");
        assert_eq!(F64(f64::NAN).to_pretty_str(), "null");
M
mrec 已提交
2557

B
Barosl Lee 已提交
2558 2559
        assert_eq!(F64(f64::INFINITY).to_string(), "null");
        assert_eq!(F64(f64::INFINITY).to_pretty_str(), "null");
M
mrec 已提交
2560

B
Barosl Lee 已提交
2561 2562
        assert_eq!(F64(f64::NEG_INFINITY).to_string(), "null");
        assert_eq!(F64(f64::NEG_INFINITY).to_pretty_str(), "null");
2563 2564 2565 2566
    }

    #[test]
    fn test_write_str() {
2567 2568
        assert_eq!(String("".into_string()).to_string(), "\"\"");
        assert_eq!(String("".into_string()).to_pretty_str(), "\"\"");
2569

2570 2571
        assert_eq!(String("homura".into_string()).to_string(), "\"homura\"");
        assert_eq!(String("madoka".into_string()).to_pretty_str(), "\"madoka\"");
2572 2573 2574 2575
    }

    #[test]
    fn test_write_bool() {
B
Barosl Lee 已提交
2576 2577
        assert_eq!(Boolean(true).to_string(), "true");
        assert_eq!(Boolean(true).to_pretty_str(), "true");
2578

B
Barosl Lee 已提交
2579 2580
        assert_eq!(Boolean(false).to_string(), "false");
        assert_eq!(Boolean(false).to_pretty_str(), "false");
2581 2582 2583
    }

    #[test]
C
Corey Farwell 已提交
2584
    fn test_write_array() {
B
Barosl Lee 已提交
2585 2586
        assert_eq!(Array(vec![]).to_string(), "[]");
        assert_eq!(Array(vec![]).to_pretty_str(), "[]");
2587

B
Barosl Lee 已提交
2588
        assert_eq!(Array(vec![Boolean(true)]).to_string(), "[true]");
2589
        assert_eq!(
B
Barosl Lee 已提交
2590
            Array(vec![Boolean(true)]).to_pretty_str(),
2591
            "\
2592 2593
            [\n  \
                true\n\
2594
            ]"
2595
        );
2596

C
Corey Farwell 已提交
2597
        let long_test_array = Array(vec![
2598 2599
            Boolean(false),
            Null,
2600
            Array(vec![String("foo\nbar".into_string()), F64(3.5)])]);
2601

B
Barosl Lee 已提交
2602
        assert_eq!(long_test_array.to_string(),
2603
            "[false,null,[\"foo\\nbar\",3.5]]");
2604
        assert_eq!(
B
Barosl Lee 已提交
2605
            long_test_array.to_pretty_str(),
2606
            "\
2607 2608 2609 2610 2611 2612 2613
            [\n  \
                false,\n  \
                null,\n  \
                [\n    \
                    \"foo\\nbar\",\n    \
                    3.5\n  \
                ]\n\
2614
            ]"
2615 2616 2617
        );
    }

2618
    #[test]
2619
    fn test_write_object() {
B
Barosl Lee 已提交
2620 2621
        assert_eq!(mk_object(&[]).to_string(), "{}");
        assert_eq!(mk_object(&[]).to_pretty_str(), "{}");
2622

2623
        assert_eq!(
N
Nick Cameron 已提交
2624
            mk_object(&[
2625
                ("a".into_string(), Boolean(true))
B
Barosl Lee 已提交
2626
            ]).to_string(),
2627
            "{\"a\":true}"
2628
        );
2629
        assert_eq!(
2630
            mk_object(&[("a".into_string(), Boolean(true))]).to_pretty_str(),
2631
            "\
2632 2633
            {\n  \
                \"a\": true\n\
2634
            }"
2635 2636
        );

N
Nick Cameron 已提交
2637
        let complex_obj = mk_object(&[
2638 2639 2640
                ("b".into_string(), Array(vec![
                    mk_object(&[("c".into_string(), String("\x0c\r".into_string()))]),
                    mk_object(&[("d".into_string(), String("".into_string()))])
2641
                ]))
2642 2643 2644
            ]);

        assert_eq!(
B
Barosl Lee 已提交
2645
            complex_obj.to_string(),
2646
            "{\
2647 2648 2649 2650
                \"b\":[\
                    {\"c\":\"\\f\\r\"},\
                    {\"d\":\"\"}\
                ]\
2651
            }"
2652 2653
        );
        assert_eq!(
B
Barosl Lee 已提交
2654
            complex_obj.to_pretty_str(),
2655
            "\
2656 2657 2658 2659 2660 2661 2662 2663 2664
            {\n  \
                \"b\": [\n    \
                    {\n      \
                        \"c\": \"\\f\\r\"\n    \
                    },\n    \
                    {\n      \
                        \"d\": \"\"\n    \
                    }\n  \
                ]\n\
2665
            }"
2666
        );
2667

N
Nick Cameron 已提交
2668
        let a = mk_object(&[
2669 2670 2671 2672
            ("a".into_string(), Boolean(true)),
            ("b".into_string(), Array(vec![
                mk_object(&[("c".into_string(), String("\x0c\r".into_string()))]),
                mk_object(&[("d".into_string(), String("".into_string()))])
2673
            ]))
G
Graydon Hoare 已提交
2674
        ]);
2675

2676 2677
        // We can't compare the strings directly because the object fields be
        // printed in a different order.
2678
        assert_eq!(a.clone(), from_str(a.to_string().as_slice()).unwrap());
2679 2680
        assert_eq!(a.clone(),
                   from_str(a.to_pretty_str().as_slice()).unwrap());
2681 2682
    }

2683
    fn with_str_writer<F>(f: F) -> string::String where F: FnOnce(&mut io::Writer){
A
Alex Crichton 已提交
2684 2685
        use std::str;

D
Daniel Micay 已提交
2686
        let mut m = Vec::new();
2687
        f(&mut m as &mut io::Writer);
D
Daniel Micay 已提交
2688
        string::String::from_utf8(m).unwrap()
A
Alex Crichton 已提交
2689 2690
    }

2691
    #[test]
2692
    fn test_write_enum() {
2693
        let animal = Dog;
2694
        assert_eq!(
A
Adolfo Ochagavía 已提交
2695 2696
            with_str_writer(|writer| {
                let mut encoder = Encoder::new(writer);
S
Sean McArthur 已提交
2697
                animal.encode(&mut encoder).unwrap();
2698
            }),
2699
            "\"Dog\""
2700 2701
        );
        assert_eq!(
A
Adolfo Ochagavía 已提交
2702 2703
            with_str_writer(|writer| {
                let mut encoder = PrettyEncoder::new(writer);
S
Sean McArthur 已提交
2704
                animal.encode(&mut encoder).unwrap();
2705
            }),
2706
            "\"Dog\""
2707
        );
2708

2709
        let animal = Frog("Henry".into_string(), 349);
2710
        assert_eq!(
A
Adolfo Ochagavía 已提交
2711 2712
            with_str_writer(|writer| {
                let mut encoder = Encoder::new(writer);
S
Sean McArthur 已提交
2713
                animal.encode(&mut encoder).unwrap();
2714
            }),
2715
            "{\"variant\":\"Frog\",\"fields\":[\"Henry\",349]}"
2716 2717
        );
        assert_eq!(
A
Adolfo Ochagavía 已提交
2718 2719
            with_str_writer(|writer| {
                let mut encoder = PrettyEncoder::new(writer);
S
Sean McArthur 已提交
2720
                animal.encode(&mut encoder).unwrap();
2721
            }),
2722 2723 2724 2725 2726 2727
            "{\n  \
               \"variant\": \"Frog\",\n  \
               \"fields\": [\n    \
                 \"Henry\",\n    \
                 349\n  \
               ]\n\
2728
             }"
2729
        );
2730 2731 2732
    }

    #[test]
2733
    fn test_write_some() {
2734
        let value = Some("jodhpurs".into_string());
A
Adolfo Ochagavía 已提交
2735 2736
        let s = with_str_writer(|writer| {
            let mut encoder = Encoder::new(writer);
S
Sean McArthur 已提交
2737
            value.encode(&mut encoder).unwrap();
2738
        });
2739
        assert_eq!(s, "\"jodhpurs\"");
2740

2741
        let value = Some("jodhpurs".into_string());
A
Adolfo Ochagavía 已提交
2742 2743
        let s = with_str_writer(|writer| {
            let mut encoder = PrettyEncoder::new(writer);
S
Sean McArthur 已提交
2744
            value.encode(&mut encoder).unwrap();
2745
        });
2746
        assert_eq!(s, "\"jodhpurs\"");
2747 2748
    }

2749
    #[test]
2750
    fn test_write_none() {
2751
        let value: Option<string::String> = None;
A
Adolfo Ochagavía 已提交
2752 2753
        let s = with_str_writer(|writer| {
            let mut encoder = Encoder::new(writer);
S
Sean McArthur 已提交
2754
            value.encode(&mut encoder).unwrap();
2755
        });
2756
        assert_eq!(s, "null");
J
John Clements 已提交
2757

A
Adolfo Ochagavía 已提交
2758 2759
        let s = with_str_writer(|writer| {
            let mut encoder = Encoder::new(writer);
S
Sean McArthur 已提交
2760
            value.encode(&mut encoder).unwrap();
2761
        });
2762
        assert_eq!(s, "null");
2763 2764
    }

2765
    #[test]
2766
    fn test_trailing_characters() {
2767 2768 2769 2770 2771 2772
        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)));
2773 2774 2775 2776
    }

    #[test]
    fn test_read_identifiers() {
2777 2778 2779 2780 2781 2782
        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)));
2783

E
Erick Tryzelaar 已提交
2784 2785 2786 2787 2788 2789
        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)));
2790 2791
    }

2792 2793
    #[test]
    fn test_decode_identifiers() {
2794
        let v: () = super::decode("null").unwrap();
2795 2796
        assert_eq!(v, ());

2797
        let v: bool = super::decode("true").unwrap();
2798 2799
        assert_eq!(v, true);

2800
        let v: bool = super::decode("false").unwrap();
2801 2802 2803
        assert_eq!(v, false);
    }

2804
    #[test]
2805
    fn test_read_number() {
2806 2807
        assert_eq!(from_str("+"),   Err(SyntaxError(InvalidSyntax, 1, 1)));
        assert_eq!(from_str("."),   Err(SyntaxError(InvalidSyntax, 1, 1)));
M
mrec 已提交
2808
        assert_eq!(from_str("NaN"), Err(SyntaxError(InvalidSyntax, 1, 1)));
2809 2810 2811 2812 2813
        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)));
2814

2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829
        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)));
2830 2831
    }

2832 2833
    #[test]
    fn test_decode_numbers() {
2834
        let v: f64 = super::decode("3").unwrap();
D
Daniel Micay 已提交
2835
        assert_eq!(v, 3.0);
2836

2837
        let v: f64 = super::decode("3.1").unwrap();
D
Daniel Micay 已提交
2838
        assert_eq!(v, 3.1);
2839

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

2843
        let v: f64 = super::decode("0.4").unwrap();
D
Daniel Micay 已提交
2844
        assert_eq!(v, 0.4);
2845

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

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

2852
        let v: f64 = super::decode("0.4e-01").unwrap();
D
Daniel Micay 已提交
2853
        assert_eq!(v, 0.4e-01);
2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865

        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);
2866 2867 2868

        let res: DecodeResult<i64> = super::decode("765.25252");
        assert_eq!(res, Err(ExpectedError("Integer".into_string(), "765.25252".into_string())));
2869 2870
    }

G
Gary Linscott 已提交
2871
    #[test]
2872
    fn test_read_str() {
2873 2874 2875
        assert_eq!(from_str("\""),    Err(SyntaxError(EOFWhileParsingString, 1, 2)));
        assert_eq!(from_str("\"lol"), Err(SyntaxError(EOFWhileParsingString, 1, 5)));

2876 2877 2878 2879 2880 2881 2882 2883
        assert_eq!(from_str("\"\""), Ok(String("".into_string())));
        assert_eq!(from_str("\"foo\""), Ok(String("foo".into_string())));
        assert_eq!(from_str("\"\\\"\""), Ok(String("\"".into_string())));
        assert_eq!(from_str("\"\\b\""), Ok(String("\x08".into_string())));
        assert_eq!(from_str("\"\\n\""), Ok(String("\n".into_string())));
        assert_eq!(from_str("\"\\r\""), Ok(String("\r".into_string())));
        assert_eq!(from_str("\"\\t\""), Ok(String("\t".into_string())));
        assert_eq!(from_str(" \"foo\" "), Ok(String("foo".into_string())));
A
Alex Crichton 已提交
2884 2885
        assert_eq!(from_str("\"\\u12ab\""), Ok(String("\u{12ab}".into_string())));
        assert_eq!(from_str("\"\\uAB12\""), Ok(String("\u{AB12}".into_string())));
2886 2887
    }

2888
    #[test]
2889
    fn test_decode_str() {
2890 2891 2892 2893 2894 2895 2896
        let s = [("\"\"", ""),
                 ("\"foo\"", "foo"),
                 ("\"\\\"\"", "\""),
                 ("\"\\b\"", "\x08"),
                 ("\"\\n\"", "\n"),
                 ("\"\\r\"", "\r"),
                 ("\"\\t\"", "\t"),
A
Alex Crichton 已提交
2897 2898
                 ("\"\\u12ab\"", "\u{12ab}"),
                 ("\"\\uAB12\"", "\u{AB12}")];
2899 2900

        for &(i, o) in s.iter() {
2901
            let v: string::String = super::decode(i).unwrap();
2902
            assert_eq!(v, o);
2903
        }
2904 2905
    }

2906
    #[test]
C
Corey Farwell 已提交
2907
    fn test_read_array() {
2908
        assert_eq!(from_str("["),     Err(SyntaxError(EOFWhileParsingValue, 1, 2)));
C
Corey Farwell 已提交
2909
        assert_eq!(from_str("[1"),    Err(SyntaxError(EOFWhileParsingArray, 1, 3)));
2910 2911 2912
        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)));
2913

C
Corey Farwell 已提交
2914 2915 2916 2917 2918
        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 已提交
2919
        assert_eq!(from_str("[3, 1]"),
C
Corey Farwell 已提交
2920
                     Ok(Array(vec![U64(3), U64(1)])));
E
Erick Tryzelaar 已提交
2921
        assert_eq!(from_str("\n[3, 2]\n"),
C
Corey Farwell 已提交
2922
                     Ok(Array(vec![U64(3), U64(2)])));
E
Erick Tryzelaar 已提交
2923
        assert_eq!(from_str("[2, [4, 1]]"),
C
Corey Farwell 已提交
2924
               Ok(Array(vec![U64(2), Array(vec![U64(4), U64(1)])])));
2925 2926
    }

2927
    #[test]
C
Corey Farwell 已提交
2928
    fn test_decode_array() {
2929
        let v: Vec<()> = super::decode("[]").unwrap();
K
Kevin Ballard 已提交
2930
        assert_eq!(v, vec![]);
2931

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

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

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

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

2945 2946 2947 2948 2949 2950
    #[test]
    fn test_decode_tuple() {
        let t: (uint, uint, uint) = super::decode("[1, 2, 3]").unwrap();
        assert_eq!(t, (1u, 2, 3))

        let t: (uint, string::String) = super::decode("[1, \"two\"]").unwrap();
2951
        assert_eq!(t, (1u, "two".into_string()));
2952 2953 2954 2955 2956 2957 2958 2959 2960
    }

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

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

2964
    #[test]
2965
    fn test_read_object() {
2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977
        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)));
2978

N
Nick Cameron 已提交
2979
        assert_eq!(from_str("{}").unwrap(), mk_object(&[]));
E
Erick Tryzelaar 已提交
2980
        assert_eq!(from_str("{\"a\": 3}").unwrap(),
2981
                  mk_object(&[("a".into_string(), U64(3))]));
2982

E
Erick Tryzelaar 已提交
2983 2984
        assert_eq!(from_str(
                      "{ \"a\": null, \"b\" : true }").unwrap(),
N
Nick Cameron 已提交
2985
                  mk_object(&[
2986 2987
                      ("a".into_string(), Null),
                      ("b".into_string(), Boolean(true))]));
E
Erick Tryzelaar 已提交
2988
        assert_eq!(from_str("\n{ \"a\": null, \"b\" : true }\n").unwrap(),
N
Nick Cameron 已提交
2989
                  mk_object(&[
2990 2991
                      ("a".into_string(), Null),
                      ("b".into_string(), Boolean(true))]));
E
Erick Tryzelaar 已提交
2992 2993
        assert_eq!(from_str(
                      "{\"a\" : 1.0 ,\"b\": [ true ]}").unwrap(),
N
Nick Cameron 已提交
2994
                  mk_object(&[
2995 2996
                      ("a".into_string(), F64(1.0)),
                      ("b".into_string(), Array(vec![Boolean(true)]))
2997
                  ]));
E
Erick Tryzelaar 已提交
2998
        assert_eq!(from_str(
2999 3000 3001 3002 3003 3004 3005 3006
                      "{\
                          \"a\": 1.0, \
                          \"b\": [\
                              true,\
                              \"foo\\nbar\", \
                              { \"c\": {\"d\": null} } \
                          ]\
                      }").unwrap(),
N
Nick Cameron 已提交
3007
                  mk_object(&[
3008 3009
                      ("a".into_string(), F64(1.0)),
                      ("b".into_string(), Array(vec![
B
Ben Striegel 已提交
3010
                          Boolean(true),
3011
                          String("foo\nbar".into_string()),
N
Nick Cameron 已提交
3012
                          mk_object(&[
3013
                              ("c".into_string(), mk_object(&[("d".into_string(), Null)]))
3014 3015
                          ])
                      ]))
3016
                  ]));
3017 3018
    }

3019
    #[test]
3020
    fn test_decode_struct() {
3021
        let s = "{
3022 3023 3024
            \"inner\": [
                { \"a\": null, \"b\": 2, \"c\": [\"abc\", \"xyz\"] }
            ]
3025
        }";
3026 3027

        let v: Outer = super::decode(s).unwrap();
3028 3029 3030
        assert_eq!(
            v,
            Outer {
K
Kevin Ballard 已提交
3031
                inner: vec![
3032
                    Inner { a: (), b: 2, c: vec!["abc".into_string(), "xyz".into_string()] }
3033 3034 3035 3036 3037
                ]
            }
        );
    }

M
mrec 已提交
3038 3039 3040 3041 3042 3043 3044
    #[deriving(Decodable)]
    struct FloatStruct {
        f: f64,
        a: Vec<f64>
    }
    #[test]
    fn test_decode_struct_with_nan() {
3045 3046 3047
        let s = "{\"f\":null,\"a\":[null,123]}";
        let obj: FloatStruct = super::decode(s).unwrap();
        assert!(obj.f.is_nan());
N
NODA, Kai 已提交
3048 3049
        assert!(obj.a[0].is_nan());
        assert_eq!(obj.a[1], 123f64);
M
mrec 已提交
3050 3051
    }

3052 3053
    #[test]
    fn test_decode_option() {
3054
        let value: Option<string::String> = super::decode("null").unwrap();
3055 3056
        assert_eq!(value, None);

3057
        let value: Option<string::String> = super::decode("\"jodhpurs\"").unwrap();
3058
        assert_eq!(value, Some("jodhpurs".into_string()));
3059 3060
    }

3061
    #[test]
3062
    fn test_decode_enum() {
3063
        let value: Animal = super::decode("\"Dog\"").unwrap();
3064 3065
        assert_eq!(value, Dog);

3066
        let s = "{\"variant\":\"Frog\",\"fields\":[\"Henry\",349]}";
3067
        let value: Animal = super::decode(s).unwrap();
3068
        assert_eq!(value, Frog("Henry".into_string(), 349));
3069 3070
    }

3071
    #[test]
3072
    fn test_decode_map() {
3073
        let s = "{\"a\": \"Dog\", \"b\": {\"variant\":\"Frog\",\
3074
                  \"fields\":[\"Henry\", 349]}}";
3075
        let mut map: TreeMap<string::String, Animal> = super::decode(s).unwrap();
3076

3077 3078
        assert_eq!(map.remove(&"a".into_string()), Some(Dog));
        assert_eq!(map.remove(&"b".into_string()), Some(Frog("Henry".into_string(), 349)));
3079 3080
    }

3081
    #[test]
3082
    fn test_multiline_errors() {
E
Erick Tryzelaar 已提交
3083
        assert_eq!(from_str("{\n  \"foo\":\n \"bar\""),
3084
            Err(SyntaxError(EOFWhileParsingObject, 3u, 8u)));
3085
    }
3086 3087

    #[deriving(Decodable)]
M
mrec 已提交
3088
    #[allow(dead_code)]
3089 3090 3091
    struct DecodeStruct {
        x: f64,
        y: bool,
3092
        z: string::String,
K
Kevin Ballard 已提交
3093
        w: Vec<DecodeStruct>
3094 3095 3096 3097
    }
    #[deriving(Decodable)]
    enum DecodeEnum {
        A(f64),
3098
        B(string::String)
3099
    }
3100 3101
    fn check_err<T: Decodable<Decoder, DecoderError>>(to_parse: &'static str,
                                                      expected: DecoderError) {
S
Sean McArthur 已提交
3102
        let res: DecodeResult<T> = match from_str(to_parse) {
3103
            Err(e) => Err(ParseError(e)),
S
Sean McArthur 已提交
3104 3105
            Ok(json) => Decodable::decode(&mut Decoder::new(json))
        };
3106
        match res {
S
Steve Klabnik 已提交
3107
            Ok(_) => panic!("`{}` parsed & decoded ok, expecting error `{}`",
S
Sean McArthur 已提交
3108
                              to_parse, expected),
S
Steve Klabnik 已提交
3109
            Err(ParseError(e)) => panic!("`{}` is not valid json: {}",
S
Sean McArthur 已提交
3110
                                           to_parse, e),
3111
            Err(e) => {
S
Sean McArthur 已提交
3112
                assert_eq!(e, expected);
3113 3114 3115 3116 3117
            }
        }
    }
    #[test]
    fn test_decode_errors_struct() {
3118
        check_err::<DecodeStruct>("[]", ExpectedError("Object".into_string(), "[]".into_string()));
3119
        check_err::<DecodeStruct>("{\"x\": true, \"y\": true, \"z\": \"\", \"w\": []}",
3120
                                  ExpectedError("Number".into_string(), "true".into_string()));
3121
        check_err::<DecodeStruct>("{\"x\": 1, \"y\": [], \"z\": \"\", \"w\": []}",
3122
                                  ExpectedError("Boolean".into_string(), "[]".into_string()));
3123
        check_err::<DecodeStruct>("{\"x\": 1, \"y\": true, \"z\": {}, \"w\": []}",
3124
                                  ExpectedError("String".into_string(), "{}".into_string()));
3125
        check_err::<DecodeStruct>("{\"x\": 1, \"y\": true, \"z\": \"\", \"w\": null}",
3126
                                  ExpectedError("Array".into_string(), "null".into_string()));
3127
        check_err::<DecodeStruct>("{\"x\": 1, \"y\": true, \"z\": \"\"}",
3128
                                  MissingFieldError("w".into_string()));
3129 3130 3131 3132
    }
    #[test]
    fn test_decode_errors_enum() {
        check_err::<DecodeEnum>("{}",
3133
                                MissingFieldError("variant".into_string()));
3134
        check_err::<DecodeEnum>("{\"variant\": 1}",
3135
                                ExpectedError("String".into_string(), "1".into_string()));
3136
        check_err::<DecodeEnum>("{\"variant\": \"A\"}",
3137
                                MissingFieldError("fields".into_string()));
3138
        check_err::<DecodeEnum>("{\"variant\": \"A\", \"fields\": null}",
3139
                                ExpectedError("Array".into_string(), "null".into_string()));
3140
        check_err::<DecodeEnum>("{\"variant\": \"C\", \"fields\": []}",
3141
                                UnknownVariantError("C".into_string()));
3142
    }
3143 3144 3145 3146

    #[test]
    fn test_find(){
        let json_value = from_str("{\"dog\" : \"cat\"}").unwrap();
3147 3148
        let found_str = json_value.find("dog");
        assert!(found_str.unwrap().as_string().unwrap() == "cat");
3149 3150 3151 3152 3153
    }

    #[test]
    fn test_find_path(){
        let json_value = from_str("{\"dog\":{\"cat\": {\"mouse\" : \"cheese\"}}}").unwrap();
3154 3155
        let found_str = json_value.find_path(&["dog", "cat", "mouse"]);
        assert!(found_str.unwrap().as_string().unwrap() == "cheese");
3156 3157 3158 3159 3160
    }

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

3165 3166 3167
    #[test]
    fn test_index(){
        let json_value = from_str("{\"animals\":[\"dog\",\"cat\",\"mouse\"]}").unwrap();
C
Corey Farwell 已提交
3168 3169 3170 3171
        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");
3172 3173
    }

3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187
    #[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 已提交
3188
    fn test_is_array(){
3189
        let json_value = from_str("[1, 2, 3]").unwrap();
C
Corey Farwell 已提交
3190
        assert!(json_value.is_array());
3191 3192 3193
    }

    #[test]
C
Corey Farwell 已提交
3194
    fn test_as_array(){
3195
        let json_value = from_str("[1, 2, 3]").unwrap();
C
Corey Farwell 已提交
3196
        let json_array = json_value.as_array();
3197
        let expected_length = 3;
C
Corey Farwell 已提交
3198
        assert!(json_array.is_some() && json_array.unwrap().len() == expected_length);
3199 3200 3201
    }

    #[test]
3202
    fn test_is_string(){
3203
        let json_value = from_str("\"dog\"").unwrap();
3204
        assert!(json_value.is_string());
3205 3206 3207
    }

    #[test]
3208
    fn test_as_string(){
3209
        let json_value = from_str("\"dog\"").unwrap();
3210
        let json_str = json_value.as_string();
3211
        let expected_str = "dog";
3212 3213 3214 3215 3216 3217 3218 3219 3220 3221
        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]
3222
    fn test_is_i64(){
3223
        let json_value = from_str("-12").unwrap();
3224 3225
        assert!(json_value.is_i64());

3226 3227 3228
        let json_value = from_str("12").unwrap();
        assert!(!json_value.is_i64());

3229 3230 3231 3232
        let json_value = from_str("12.0").unwrap();
        assert!(!json_value.is_i64());
    }

3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244
    #[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());
    }

3245 3246
    #[test]
    fn test_is_f64(){
3247
        let json_value = from_str("12").unwrap();
3248 3249
        assert!(!json_value.is_f64());

3250 3251 3252
        let json_value = from_str("-12").unwrap();
        assert!(!json_value.is_f64());

3253 3254
        let json_value = from_str("12.0").unwrap();
        assert!(json_value.is_f64());
3255 3256 3257

        let json_value = from_str("-12.0").unwrap();
        assert!(json_value.is_f64());
3258 3259 3260 3261
    }

    #[test]
    fn test_as_i64(){
3262
        let json_value = from_str("-12").unwrap();
3263
        let json_num = json_value.as_i64();
3264 3265 3266 3267 3268 3269 3270
        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();
3271 3272 3273 3274 3275 3276 3277 3278
        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));
3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307
    }

    #[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);
    }
3308 3309 3310 3311 3312

    #[test]
    fn test_encode_hashmap_with_numeric_key() {
        use std::str::from_utf8;
        use std::io::Writer;
3313
        use std::collections::HashMap;
3314 3315
        let mut hm: HashMap<uint, bool> = HashMap::new();
        hm.insert(1, true);
D
Daniel Micay 已提交
3316
        let mut mem_buf = Vec::new();
3317 3318
        {
            let mut encoder = Encoder::new(&mut mem_buf as &mut io::Writer);
S
Sean McArthur 已提交
3319
            hm.encode(&mut encoder).unwrap();
3320
        }
D
Daniel Micay 已提交
3321
        let json_str = from_utf8(mem_buf[]).unwrap();
3322
        match from_str(json_str) {
S
Steve Klabnik 已提交
3323
            Err(_) => panic!("Unable to parse json_str: {}", json_str),
3324 3325 3326
            _ => {} // it parsed and we are good to go
        }
    }
3327

3328 3329 3330 3331
    #[test]
    fn test_prettyencode_hashmap_with_numeric_key() {
        use std::str::from_utf8;
        use std::io::Writer;
3332
        use std::collections::HashMap;
3333 3334
        let mut hm: HashMap<uint, bool> = HashMap::new();
        hm.insert(1, true);
D
Daniel Micay 已提交
3335
        let mut mem_buf = Vec::new();
3336 3337
        {
            let mut encoder = PrettyEncoder::new(&mut mem_buf as &mut io::Writer);
3338
            hm.encode(&mut encoder).unwrap()
3339
        }
D
Daniel Micay 已提交
3340
        let json_str = from_utf8(mem_buf[]).unwrap();
3341
        match from_str(json_str) {
S
Steve Klabnik 已提交
3342
            Err(_) => panic!("Unable to parse json_str: {}", json_str),
3343 3344 3345
            _ => {} // it parsed and we are good to go
        }
    }
3346

3347 3348 3349 3350 3351 3352 3353 3354 3355 3356
    #[test]
    fn test_prettyencoder_indent_level_param() {
        use std::str::from_utf8;
        use std::collections::TreeMap;

        let mut tree = TreeMap::new();

        tree.insert("hello".into_string(), String("guten tag".into_string()));
        tree.insert("goodbye".into_string(), String("sayonara".into_string()));

C
Corey Farwell 已提交
3357
        let json = Array(
3358 3359 3360 3361 3362 3363 3364
            // The following layout below should look a lot like
            // the pretty-printed JSON (indent * x)
            vec!
            ( // 0x
                String("greetings".into_string()), // 1x
                Object(tree), // 1x + 2x + 2x + 1x
            ) // 0x
C
Corey Farwell 已提交
3365
            // End JSON array (7 lines)
3366 3367 3368 3369 3370 3371 3372 3373 3374 3375
        );

        // Helper function for counting indents
        fn indents(source: &str) -> uint {
            let trimmed = source.trim_left_chars(' ');
            source.len() - trimmed.len()
        }

        // Test up to 4 spaces of indents (more?)
        for i in range(0, 4u) {
D
Daniel Micay 已提交
3376
            let mut writer = Vec::new();
3377 3378 3379 3380 3381 3382
            {
                let ref mut encoder = PrettyEncoder::new(&mut writer);
                encoder.set_indent(i);
                json.encode(encoder).unwrap();
            }

D
Daniel Micay 已提交
3383
            let printed = from_utf8(writer[]).unwrap();
3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401

            // 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!");
        }
    }

3402 3403
    #[test]
    fn test_hashmap_with_numeric_key_can_handle_double_quote_delimited_key() {
3404
        use std::collections::HashMap;
3405 3406 3407
        use Decodable;
        let json_str = "{\"1\":true}";
        let json_obj = match from_str(json_str) {
S
Steve Klabnik 已提交
3408
            Err(_) => panic!("Unable to parse json_str: {}", json_str),
3409 3410 3411
            Ok(o) => o
        };
        let mut decoder = Decoder::new(json_obj);
S
Sean McArthur 已提交
3412
        let _hm: HashMap<uint, bool> = Decodable::decode(&mut decoder).unwrap();
3413
    }
3414

3415 3416 3417 3418 3419 3420
    #[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 已提交
3421
            Err(_) => panic!("Unable to parse json_str: {}", json_str),
3422 3423 3424 3425
            Ok(o) => o
        };
        let mut decoder = Decoder::new(json_obj);
        let result: Result<HashMap<uint, bool>, DecoderError> = Decodable::decode(&mut decoder);
3426
        assert_eq!(result, Err(ExpectedError("Number".into_string(), "a".into_string())));
3427 3428
    }

3429 3430
    fn assert_stream_equal(src: &str,
                           expected: Vec<(JsonEvent, Vec<StackElement>)>) {
3431 3432 3433 3434 3435 3436 3437
        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 已提交
3438
            let (ref expected_evt, ref expected_stack) = expected[i];
3439
            if !parser.stack().is_equal_to(expected_stack.as_slice()) {
S
Steve Klabnik 已提交
3440
                panic!("Parser stack is not equal to {}", expected_stack);
3441 3442 3443 3444 3445 3446
            }
            assert_eq!(&evt, expected_evt);
            i+=1;
        }
    }
    #[test]
S
Steven Fackler 已提交
3447
    #[cfg_attr(target_word_size = "32", ignore)] // FIXME(#14064)
3448 3449
    fn test_streaming_parser() {
        assert_stream_equal(
3450
            r#"{ "foo":"bar", "array" : [0, 1, 2, 3, 4, 5], "idents":[null,true,false]}"#,
3451 3452
            vec![
                (ObjectStart,             vec![]),
3453
                  (StringValue("bar".into_string()),   vec![Key("foo")]),
C
Corey Farwell 已提交
3454
                  (ArrayStart,            vec![Key("array")]),
3455 3456 3457 3458 3459 3460
                    (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 已提交
3461 3462
                  (ArrayEnd,              vec![Key("array")]),
                  (ArrayStart,            vec![Key("idents")]),
3463 3464 3465
                    (NullValue,           vec![Key("idents"), Index(0)]),
                    (BooleanValue(true),  vec![Key("idents"), Index(1)]),
                    (BooleanValue(false), vec![Key("idents"), Index(2)]),
C
Corey Farwell 已提交
3466
                  (ArrayEnd,              vec![Key("idents")]),
3467
                (ObjectEnd,               vec![]),
3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480
            ]
        );
    }
    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,
            }
        }
    }
3481

3482
    #[test]
S
Steven Fackler 已提交
3483
    #[cfg_attr(target_word_size = "32", ignore)] // FIXME(#14064)
3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495
    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)));
3496
        assert_eq!(last_event("{\"a\":1,}"), Error(SyntaxError(TrailingComma, 1, 8)));
3497 3498 3499

        assert_stream_equal(
            "{}",
3500
            vec![(ObjectStart, vec![]), (ObjectEnd, vec![])]
3501 3502 3503
        );
        assert_stream_equal(
            "{\"a\": 3}",
3504 3505
            vec![
                (ObjectStart,        vec![]),
3506
                  (U64Value(3),      vec![Key("a")]),
3507
                (ObjectEnd,          vec![]),
3508 3509 3510 3511
            ]
        );
        assert_stream_equal(
            "{ \"a\": null, \"b\" : true }",
3512 3513 3514 3515 3516
            vec![
                (ObjectStart,           vec![]),
                  (NullValue,           vec![Key("a")]),
                  (BooleanValue(true),  vec![Key("b")]),
                (ObjectEnd,             vec![]),
3517 3518 3519 3520
            ]
        );
        assert_stream_equal(
            "{\"a\" : 1.0 ,\"b\": [ true ]}",
3521 3522
            vec![
                (ObjectStart,           vec![]),
3523
                  (F64Value(1.0),       vec![Key("a")]),
C
Corey Farwell 已提交
3524
                  (ArrayStart,          vec![Key("b")]),
3525
                    (BooleanValue(true),vec![Key("b"), Index(0)]),
C
Corey Farwell 已提交
3526
                  (ArrayEnd,            vec![Key("b")]),
3527
                (ObjectEnd,             vec![]),
3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538
            ]
        );
        assert_stream_equal(
            r#"{
                "a": 1.0,
                "b": [
                    true,
                    "foo\nbar",
                    { "c": {"d": null} }
                ]
            }"#,
3539 3540
            vec![
                (ObjectStart,                   vec![]),
3541
                  (F64Value(1.0),               vec![Key("a")]),
C
Corey Farwell 已提交
3542
                  (ArrayStart,                  vec![Key("b")]),
3543
                    (BooleanValue(true),        vec![Key("b"), Index(0)]),
3544
                    (StringValue("foo\nbar".into_string()),  vec![Key("b"), Index(1)]),
3545 3546 3547 3548 3549
                    (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 已提交
3550
                  (ArrayEnd,                    vec![Key("b")]),
3551
                (ObjectEnd,                     vec![]),
3552 3553 3554 3555
            ]
        );
    }
    #[test]
S
Steven Fackler 已提交
3556
    #[cfg_attr(target_word_size = "32", ignore)] // FIXME(#14064)
C
Corey Farwell 已提交
3557
    fn test_read_array_streaming() {
3558 3559
        assert_stream_equal(
            "[]",
3560
            vec![
C
Corey Farwell 已提交
3561 3562
                (ArrayStart, vec![]),
                (ArrayEnd,   vec![]),
3563 3564 3565 3566
            ]
        );
        assert_stream_equal(
            "[ ]",
3567
            vec![
C
Corey Farwell 已提交
3568 3569
                (ArrayStart, vec![]),
                (ArrayEnd,   vec![]),
3570 3571 3572 3573
            ]
        );
        assert_stream_equal(
            "[true]",
3574
            vec![
C
Corey Farwell 已提交
3575
                (ArrayStart,             vec![]),
3576
                    (BooleanValue(true), vec![Index(0)]),
C
Corey Farwell 已提交
3577
                (ArrayEnd,               vec![]),
3578 3579 3580 3581
            ]
        );
        assert_stream_equal(
            "[ false ]",
3582
            vec![
C
Corey Farwell 已提交
3583
                (ArrayStart,              vec![]),
3584
                    (BooleanValue(false), vec![Index(0)]),
C
Corey Farwell 已提交
3585
                (ArrayEnd,                vec![]),
3586 3587 3588 3589
            ]
        );
        assert_stream_equal(
            "[null]",
3590
            vec![
C
Corey Farwell 已提交
3591
                (ArrayStart,    vec![]),
3592
                    (NullValue, vec![Index(0)]),
C
Corey Farwell 已提交
3593
                (ArrayEnd,      vec![]),
3594 3595 3596 3597
            ]
        );
        assert_stream_equal(
            "[3, 1]",
3598
            vec![
C
Corey Farwell 已提交
3599
                (ArrayStart,      vec![]),
3600 3601
                    (U64Value(3), vec![Index(0)]),
                    (U64Value(1), vec![Index(1)]),
C
Corey Farwell 已提交
3602
                (ArrayEnd,        vec![]),
3603 3604 3605 3606
            ]
        );
        assert_stream_equal(
            "\n[3, 2]\n",
3607
            vec![
C
Corey Farwell 已提交
3608
                (ArrayStart,      vec![]),
3609 3610
                    (U64Value(3), vec![Index(0)]),
                    (U64Value(2), vec![Index(1)]),
C
Corey Farwell 已提交
3611
                (ArrayEnd,        vec![]),
3612 3613 3614 3615
            ]
        );
        assert_stream_equal(
            "[2, [4, 1]]",
3616
            vec![
C
Corey Farwell 已提交
3617
                (ArrayStart,           vec![]),
3618
                    (U64Value(2),      vec![Index(0)]),
C
Corey Farwell 已提交
3619
                    (ArrayStart,       vec![Index(1)]),
3620 3621
                        (U64Value(4),  vec![Index(1), Index(0)]),
                        (U64Value(1),  vec![Index(1), Index(1)]),
C
Corey Farwell 已提交
3622 3623
                    (ArrayEnd,         vec![Index(1)]),
                (ArrayEnd,             vec![]),
3624 3625 3626 3627 3628 3629
            ]
        );

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

        assert_eq!(from_str("["),     Err(SyntaxError(EOFWhileParsingValue, 1, 2)));
C
Corey Farwell 已提交
3630
        assert_eq!(from_str("[1"),    Err(SyntaxError(EOFWhileParsingArray, 1, 3)));
3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670
        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 已提交
3671 3672 3673
        assert!(stack.is_equal_to(&[Index(1)]));
        assert!(stack.starts_with(&[Index(1)]));
        assert!(stack.ends_with(&[Index(1)]));
3674 3675 3676
        assert!(stack.last_is_index());
        assert!(stack.get(0) == Index(1));

3677
        stack.push_key("foo".into_string());
3678 3679

        assert!(stack.len() == 2);
N
Nick Cameron 已提交
3680 3681 3682 3683 3684
        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")]));
3685 3686 3687 3688
        assert!(!stack.last_is_index());
        assert!(stack.get(0) == Index(1));
        assert!(stack.get(1) == Key("foo"));

3689
        stack.push_key("bar".into_string());
3690 3691

        assert!(stack.len() == 3);
N
Nick Cameron 已提交
3692 3693 3694 3695 3696 3697 3698
        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")]));
3699 3700 3701 3702 3703 3704 3705 3706
        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 已提交
3707 3708 3709 3710 3711
        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")]));
3712 3713 3714 3715 3716
        assert!(!stack.last_is_index());
        assert!(stack.get(0) == Index(1));
        assert!(stack.get(1) == Key("foo"));
    }

3717 3718
    #[test]
    fn test_to_json() {
3719
        use std::collections::{HashMap,TreeMap};
3720 3721
        use super::ToJson;

C
Corey Farwell 已提交
3722 3723
        let array2 = Array(vec!(U64(1), U64(2)));
        let array3 = Array(vec!(U64(1), U64(2), U64(3)));
3724 3725
        let object = {
            let mut tree_map = TreeMap::new();
3726 3727
            tree_map.insert("a".into_string(), U64(1));
            tree_map.insert("b".into_string(), U64(2));
A
Adolfo Ochagavía 已提交
3728
            Object(tree_map)
3729 3730
        };

C
Corey Farwell 已提交
3731
        assert_eq!(array2.to_json(), array2);
3732
        assert_eq!(object.to_json(), object);
3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744
        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));
3745
        assert_eq!(().to_json(), Null);
M
mrec 已提交
3746 3747
        assert_eq!(f32::INFINITY.to_json(), Null);
        assert_eq!(f64::NAN.to_json(), Null);
3748 3749
        assert_eq!(true.to_json(), Boolean(true));
        assert_eq!(false.to_json(), Boolean(false));
3750 3751
        assert_eq!("abc".to_json(), String("abc".into_string()));
        assert_eq!("abc".into_string().to_json(), String("abc".into_string()));
C
Corey Farwell 已提交
3752 3753 3754 3755 3756 3757
        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);
3758
        let mut tree_map = TreeMap::new();
3759 3760
        tree_map.insert("a".into_string(), 1u);
        tree_map.insert("b".into_string(), 2);
3761 3762
        assert_eq!(tree_map.to_json(), object);
        let mut hash_map = HashMap::new();
3763 3764
        hash_map.insert("a".into_string(), 1u);
        hash_map.insert("b".into_string(), 2);
3765
        assert_eq!(hash_map.to_json(), object);
3766 3767
        assert_eq!(Some(15i).to_json(), I64(15));
        assert_eq!(Some(15u).to_json(), U64(15));
3768 3769 3770
        assert_eq!(None::<int>.to_json(), Null);
    }

3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805
    #[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} }
                ]
            }"#);
        });
    }

3806
    fn big_json() -> string::String {
3807
        let mut src = "[\n".into_string();
3808
        for _ in range(0i, 500) {
3809 3810
            src.push_str(r#"{ "a": true, "b": null, "c":3.1415, "d": "Hello world", "e": \
                            [1,2,3]},"#);
3811
        }
3812
        src.push_str("{}]");
3813 3814 3815 3816 3817 3818 3819
        return src;
    }

    #[bench]
    fn bench_streaming_large(b: &mut Bencher) {
        let src = big_json();
        b.iter( || {
3820
            let mut parser = Parser::new(src.chars());
3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831
            loop {
                match parser.next() {
                    None => return,
                    _ => {}
                }
            }
        });
    }
    #[bench]
    fn bench_large(b: &mut Bencher) {
        let src = big_json();
3832
        b.iter( || { let _ = from_str(src.as_slice()); });
3833
    }
3834
}