json.rs 80.3 KB
Newer Older
1
// Copyright 2012-2013 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 15
#![forbid(non_camel_case_types)]
#![allow(missing_doc)]
E
Elly Jones 已提交
16

M
musitdev 已提交
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
/*!
JSON parsing and serialization

# What is JSON?

JSON (JavaScript Object Notation) is a way to write data in Javascript.
Like XML it allows one to encode structured data in a text format that can be read by humans easily.
Its native compatibility with JavaScript and its simple syntax make it used widely.

Json data are encoded in a form of "key":"value".
Data types that can be encoded are JavaScript types :
boolean (`true` or `false`), number (`f64`), string, array, object, 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:

A
Alex Crichton 已提交
33
```ignore
M
musitdev 已提交
34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
{
    "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.
54 55
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.
M
musitdev 已提交
56 57 58 59 60 61 62
The Rust compiler provides an annotation to automatically generate
the code for these traits: `#[deriving(Decodable, Encodable)]`

To encode using Encodable :

```rust
use std::io;
A
Alex Crichton 已提交
63
use serialize::{json, Encodable};
M
musitdev 已提交
64 65 66 67 68 69 70 71

 #[deriving(Encodable)]
 pub struct TestStruct   {
    data_str: ~str,
 }

fn main() {
    let to_encode_object = TestStruct{data_str:~"example of string to encode"};
72
    let mut m = io::MemWriter::new();
M
musitdev 已提交
73 74
    {
        let mut encoder = json::Encoder::new(&mut m as &mut std::io::Writer);
S
Sean McArthur 已提交
75 76 77 78
        match to_encode_object.encode(&mut encoder) {
            Ok(()) => (),
            Err(e) => fail!("json encoding error: {}", e)
        };
M
musitdev 已提交
79 80 81 82 83 84 85 86
    }
}
```

Two wrapper functions are provided to encode a Encodable object
into a string (~str) or buffer (~[u8]): `str_encode(&m)` and `buffer_encode(&m)`.

```rust
A
Alex Crichton 已提交
87
use serialize::json;
M
musitdev 已提交
88 89 90 91 92 93 94 95 96 97 98 99 100 101
let to_encode_object = ~"example of string to encode";
let encoded_str: ~str = json::Encoder::str_encode(&to_encode_object);
```

JSON API provide an enum `json::Json` and a trait `ToJson` to encode object.
The trait `ToJson` encode object into a container `json::Json` and the API provide writer
to encode them into a stream or a string ...

When using `ToJson` the `Encodable` trait implementation is not mandatory.

A basic `ToJson` example using a TreeMap of attribute name / attribute value:


```rust
A
Alex Crichton 已提交
102
extern crate collections;
A
Alex Crichton 已提交
103
extern crate serialize;
104

A
Alex Crichton 已提交
105 106
use serialize::json;
use serialize::json::ToJson;
107
use collections::TreeMap;
M
musitdev 已提交
108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129

pub struct MyStruct  {
    attr1: u8,
    attr2: ~str,
}

impl ToJson for MyStruct {
    fn to_json( &self ) -> json::Json {
        let mut d = ~TreeMap::new();
        d.insert(~"attr1", self.attr1.to_json());
        d.insert(~"attr2", self.attr2.to_json());
        json::Object(d)
    }
}

fn main() {
    let test2: MyStruct = MyStruct {attr1: 1, attr2:~"test"};
    let tjson: json::Json = test2.to_json();
    let json_str: ~str = tjson.to_str();
}
```

H
Huon Wilson 已提交
130
To decode a JSON string using `Decodable` trait :
M
musitdev 已提交
131 132

```rust
A
Alex Crichton 已提交
133
extern crate serialize;
A
Alex Crichton 已提交
134
use serialize::{json, Decodable};
M
musitdev 已提交
135 136 137 138 139 140 141 142 143 144

#[deriving(Decodable)]
pub struct MyStruct  {
     attr1: u8,
     attr2: ~str,
}

fn main() {
    let json_str_to_decode: ~str =
            ~"{\"attr1\":1,\"attr2\":\"toto\"}";
A
Alex Crichton 已提交
145 146
    let json_object = json::from_str(json_str_to_decode);
    let mut decoder = json::Decoder::new(json_object.unwrap());
S
Sean McArthur 已提交
147 148 149 150
    let decoded_object: MyStruct = match Decodable::decode(&mut decoder) {
        Ok(v) => v,
        Err(e) => fail!("Decoding error: {}", e)
    }; // create the final object
M
musitdev 已提交
151 152 153 154 155 156 157 158 159 160 161
}
```

# Examples of use

## Using Autoserialization

Create a struct called TestStruct1 and serialize and deserialize it to and from JSON
using the serialization API, using the derived serialization code.

```rust
A
Alex Crichton 已提交
162
extern crate serialize;
A
Alex Crichton 已提交
163
use serialize::{json, Encodable, Decodable};
M
musitdev 已提交
164 165 166 167 168 169 170 171 172 173 174 175 176 177 178

 #[deriving(Decodable, Encodable)] //generate Decodable, Encodable impl.
 pub struct TestStruct1  {
    data_int: u8,
    data_str: ~str,
    data_vector: ~[u8],
 }

// To serialize use the `json::str_encode` to encode an object in a string.
// It calls the generated `Encodable` impl.
fn main() {
    let to_encode_object = TestStruct1
         {data_int: 1, data_str:~"toto", data_vector:~[2,3,4,5]};
    let encoded_str: ~str = json::Encoder::str_encode(&to_encode_object);

A
Alex Crichton 已提交
179
    // To deserialize use the `json::from_str` and `json::Decoder`
M
musitdev 已提交
180

A
Alex Crichton 已提交
181
    let json_object = json::from_str(encoded_str);
M
musitdev 已提交
182
    let mut decoder = json::Decoder::new(json_object.unwrap());
S
Sean McArthur 已提交
183
    let decoded1: TestStruct1 = Decodable::decode(&mut decoder).unwrap(); // create the final object
M
musitdev 已提交
184 185 186 187 188
}
```

## Using `ToJson`

H
Huon Wilson 已提交
189
This example use the ToJson impl to deserialize the JSON string.
M
musitdev 已提交
190 191 192
Example of `ToJson` trait implementation for TestStruct1.

```rust
A
Alex Crichton 已提交
193 194
extern crate serialize;
extern crate collections;
195

A
Alex Crichton 已提交
196 197
use serialize::json::ToJson;
use serialize::{json, Encodable, Decodable};
198
use collections::TreeMap;
M
musitdev 已提交
199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217

#[deriving(Decodable, Encodable)] // generate Decodable, Encodable impl.
pub struct TestStruct1  {
    data_int: u8,
    data_str: ~str,
    data_vector: ~[u8],
}

impl ToJson for TestStruct1 {
    fn to_json( &self ) -> json::Json {
        let mut d = ~TreeMap::new();
        d.insert(~"data_int", self.data_int.to_json());
        d.insert(~"data_str", self.data_str.to_json());
        d.insert(~"data_vector", self.data_vector.to_json());
        json::Object(d)
    }
}

fn main() {
H
Huon Wilson 已提交
218
    // Serialization using our impl of to_json
M
musitdev 已提交
219 220 221 222 223

    let test2: TestStruct1 = TestStruct1 {data_int: 1, data_str:~"toto", data_vector:~[2,3,4,5]};
    let tjson: json::Json = test2.to_json();
    let json_str: ~str = tjson.to_str();

H
Huon Wilson 已提交
224
    // Deserialize like before.
M
musitdev 已提交
225 226 227

    let mut decoder = json::Decoder::new(json::from_str(json_str).unwrap());
    // create the final object
S
Sean McArthur 已提交
228
    let decoded2: TestStruct1 = Decodable::decode(&mut decoder).unwrap();
M
musitdev 已提交
229 230 231 232
}
```

*/
B
Brian Anderson 已提交
233

234
use std::char;
D
Daniel Micay 已提交
235
use std::f64;
236
use collections::HashMap;
A
Alex Crichton 已提交
237
use std::io;
A
Alex Crichton 已提交
238
use std::io::MemWriter;
D
Daniel Micay 已提交
239
use std::num;
240
use std::str;
241
use std::fmt;
242

A
Alex Crichton 已提交
243
use Encodable;
244
use collections::TreeMap;
E
Elly Jones 已提交
245

246
/// Represents a json value
247
#[deriving(Clone, Eq)]
248
pub enum Json {
D
Daniel Micay 已提交
249
    Number(f64),
250
    String(~str),
B
Ben Striegel 已提交
251
    Boolean(bool),
252 253
    List(List),
    Object(~Object),
B
Ben Striegel 已提交
254
    Null,
E
Elly Jones 已提交
255 256
}

257
pub type List = ~[Json];
258
pub type Object = TreeMap<~str, Json>;
259

S
Sean McArthur 已提交
260 261 262 263 264 265 266 267
#[deriving(Eq, Show)]
pub enum Error {
    /// msg, line, col
    ParseError(~str, uint, uint),
    ExpectedError(~str, ~str),
    MissingFieldError(~str),
    UnknownVariantError(~str),
    IoError(io::IoError)
268
}
269

S
Sean McArthur 已提交
270 271
pub type EncodeResult = io::IoResult<()>;
pub type DecodeResult<T> = Result<T, Error>;
A
Alex Crichton 已提交
272

273 274
fn escape_str(s: &str) -> ~str {
    let mut escaped = ~"\"";
275
    for c in s.chars() {
276
        match c {
277 278 279 280 281 282 283 284
          '"' => escaped.push_str("\\\""),
          '\\' => escaped.push_str("\\\\"),
          '\x08' => escaped.push_str("\\b"),
          '\x0c' => escaped.push_str("\\f"),
          '\n' => escaped.push_str("\\n"),
          '\r' => escaped.push_str("\\r"),
          '\t' => escaped.push_str("\\t"),
          _ => escaped.push_char(c),
E
Elly Jones 已提交
285
        }
286
    };
287

288
    escaped.push_char('"');
289 290

    escaped
E
Elly Jones 已提交
291 292
}

293 294
fn spaces(n: uint) -> ~str {
    let mut ss = ~"";
B
Brendan Zabarauskas 已提交
295
    for _ in range(0, n) { ss.push_str(" "); }
296 297 298
    return ss;
}

299
/// A structure for implementing serialization to JSON.
E
Erik Price 已提交
300
pub struct Encoder<'a> {
301
    wr: &'a mut io::Writer,
302 303
}

E
Erik Price 已提交
304
impl<'a> Encoder<'a> {
305 306
    /// Creates a new JSON encoder whose output will be written to the writer
    /// specified.
307
    pub fn new<'a>(wr: &'a mut io::Writer) -> Encoder<'a> {
S
Sean McArthur 已提交
308
        Encoder { wr: wr }
309
    }
M
musitdev 已提交
310 311

    /// Encode the specified struct into a json [u8]
S
Sean McArthur 已提交
312
    pub fn buffer_encode<T:Encodable<Encoder<'a>, io::IoError>>(to_encode_object: &T) -> ~[u8]  {
M
musitdev 已提交
313 314 315 316
       //Serialize the object in a string using a writer
        let mut m = MemWriter::new();
        {
            let mut encoder = Encoder::new(&mut m as &mut io::Writer);
S
Sean McArthur 已提交
317 318
            // MemWriter never Errs
            let _ = to_encode_object.encode(&mut encoder);
M
musitdev 已提交
319
        }
320
        m.unwrap()
M
musitdev 已提交
321 322 323
    }

    /// Encode the specified struct into a json str
S
Sean McArthur 已提交
324
    pub fn str_encode<T:Encodable<Encoder<'a>, io::IoError>>(to_encode_object: &T) -> ~str  {
M
musitdev 已提交
325
        let buff:~[u8] = Encoder::buffer_encode(to_encode_object);
326
        str::from_utf8_owned(buff).unwrap()
M
musitdev 已提交
327
    }
328 329
}

S
Sean McArthur 已提交
330 331
impl<'a> ::Encoder<io::IoError> for Encoder<'a> {
    fn emit_nil(&mut self) -> EncodeResult { write!(self.wr, "null") }
332

S
Sean McArthur 已提交
333 334 335 336 337
    fn emit_uint(&mut self, v: uint) -> EncodeResult { self.emit_f64(v as f64) }
    fn emit_u64(&mut self, v: u64) -> EncodeResult { self.emit_f64(v as f64) }
    fn emit_u32(&mut self, v: u32) -> EncodeResult { self.emit_f64(v as f64) }
    fn emit_u16(&mut self, v: u16) -> EncodeResult { self.emit_f64(v as f64) }
    fn emit_u8(&mut self, v: u8) -> EncodeResult  { self.emit_f64(v as f64) }
338

S
Sean McArthur 已提交
339 340 341 342 343
    fn emit_int(&mut self, v: int) -> EncodeResult { self.emit_f64(v as f64) }
    fn emit_i64(&mut self, v: i64) -> EncodeResult { self.emit_f64(v as f64) }
    fn emit_i32(&mut self, v: i32) -> EncodeResult { self.emit_f64(v as f64) }
    fn emit_i16(&mut self, v: i16) -> EncodeResult { self.emit_f64(v as f64) }
    fn emit_i8(&mut self, v: i8) -> EncodeResult  { self.emit_f64(v as f64) }
344

S
Sean McArthur 已提交
345
    fn emit_bool(&mut self, v: bool) -> EncodeResult {
346
        if v {
S
Sean McArthur 已提交
347
            write!(self.wr, "true")
348
        } else {
S
Sean McArthur 已提交
349
            write!(self.wr, "false")
350 351 352
        }
    }

S
Sean McArthur 已提交
353 354
    fn emit_f64(&mut self, v: f64) -> EncodeResult {
        write!(self.wr, "{}", f64::to_str_digits(v, 6u))
A
Alex Crichton 已提交
355
    }
S
Sean McArthur 已提交
356
    fn emit_f32(&mut self, v: f32) -> EncodeResult { self.emit_f64(v as f64) }
357

S
Sean McArthur 已提交
358 359 360
    fn emit_char(&mut self, v: char) -> EncodeResult { self.emit_str(str::from_char(v)) }
    fn emit_str(&mut self, v: &str) -> EncodeResult {
        write!(self.wr, "{}", escape_str(v))
A
Alex Crichton 已提交
361
    }
362

S
Sean McArthur 已提交
363 364 365
    fn emit_enum(&mut self,
                 _name: &str,
                 f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult { f(self) }
366 367 368 369 370

    fn emit_enum_variant(&mut self,
                         name: &str,
                         _id: uint,
                         cnt: uint,
S
Sean McArthur 已提交
371
                         f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
372
        // enums are encoded as strings or objects
373
        // Bunny => "Bunny"
374
        // Kangaroo(34,"William") => {"variant": "Kangaroo", "fields": [34,"William"]}
375
        if cnt == 0 {
S
Sean McArthur 已提交
376
            write!(self.wr, "{}", escape_str(name))
377
        } else {
A
Alex Crichton 已提交
378 379 380
            try!(write!(self.wr, "\\{\"variant\":"));
            try!(write!(self.wr, "{}", escape_str(name)));
            try!(write!(self.wr, ",\"fields\":["));
S
Sean McArthur 已提交
381 382
            try!(f(self));
            write!(self.wr, "]\\}")
383 384 385
        }
    }

S
Sean McArthur 已提交
386 387 388
    fn emit_enum_variant_arg(&mut self,
                             idx: uint,
                             f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
389
        if idx != 0 {
A
Alex Crichton 已提交
390
            try!(write!(self.wr, ","));
391
        }
S
Sean McArthur 已提交
392
        f(self)
393 394 395 396 397 398
    }

    fn emit_enum_struct_variant(&mut self,
                                name: &str,
                                id: uint,
                                cnt: uint,
S
Sean McArthur 已提交
399
                                f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
400 401 402 403 404 405
        self.emit_enum_variant(name, id, cnt, f)
    }

    fn emit_enum_struct_variant_field(&mut self,
                                      _: &str,
                                      idx: uint,
S
Sean McArthur 已提交
406
                                      f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
407 408 409
        self.emit_enum_variant_arg(idx, f)
    }

S
Sean McArthur 已提交
410 411 412 413
    fn emit_struct(&mut self,
                   _: &str,
                   _: uint,
                   f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
A
Alex Crichton 已提交
414
        try!(write!(self.wr, r"\{"));
S
Sean McArthur 已提交
415 416
        try!(f(self));
        write!(self.wr, r"\}")
417 418 419 420 421
    }

    fn emit_struct_field(&mut self,
                         name: &str,
                         idx: uint,
S
Sean McArthur 已提交
422 423
                         f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
        if idx != 0 { try!(write!(self.wr, ",")); }
A
Alex Crichton 已提交
424
        try!(write!(self.wr, "{}:", escape_str(name)));
S
Sean McArthur 已提交
425
        f(self)
426 427
    }

S
Sean McArthur 已提交
428
    fn emit_tuple(&mut self, len: uint, f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
429 430
        self.emit_seq(len, f)
    }
S
Sean McArthur 已提交
431 432 433
    fn emit_tuple_arg(&mut self,
                      idx: uint,
                      f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
434 435 436 437 438 439
        self.emit_seq_elt(idx, f)
    }

    fn emit_tuple_struct(&mut self,
                         _name: &str,
                         len: uint,
S
Sean McArthur 已提交
440
                         f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
441 442
        self.emit_seq(len, f)
    }
S
Sean McArthur 已提交
443 444 445
    fn emit_tuple_struct_arg(&mut self,
                             idx: uint,
                             f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
446 447 448
        self.emit_seq_elt(idx, f)
    }

S
Sean McArthur 已提交
449 450 451 452 453 454 455
    fn emit_option(&mut self, f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
        f(self)
    }
    fn emit_option_none(&mut self) -> EncodeResult { self.emit_nil() }
    fn emit_option_some(&mut self, f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
        f(self)
    }
456

S
Sean McArthur 已提交
457
    fn emit_seq(&mut self, _len: uint, f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
A
Alex Crichton 已提交
458
        try!(write!(self.wr, "["));
S
Sean McArthur 已提交
459 460
        try!(f(self));
        write!(self.wr, "]")
461 462
    }

S
Sean McArthur 已提交
463
    fn emit_seq_elt(&mut self, idx: uint, f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
464
        if idx != 0 {
A
Alex Crichton 已提交
465
            try!(write!(self.wr, ","));
466 467 468 469
        }
        f(self)
    }

S
Sean McArthur 已提交
470
    fn emit_map(&mut self, _len: uint, f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
A
Alex Crichton 已提交
471
        try!(write!(self.wr, r"\{"));
S
Sean McArthur 已提交
472 473
        try!(f(self));
        write!(self.wr, r"\}")
474 475
    }

S
Sean McArthur 已提交
476 477 478
    fn emit_map_elt_key(&mut self,
                        idx: uint,
                        f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
479
        use std::str::from_utf8;
A
Alex Crichton 已提交
480
        if idx != 0 { try!(write!(self.wr, ",")) }
481 482 483 484
        // ref #12967, make sure to wrap a key in double quotes,
        // in the event that its of a type that omits them (eg numbers)
        let mut buf = MemWriter::new();
        let mut check_encoder = Encoder::new(&mut buf);
S
Sean McArthur 已提交
485
        try!(f(&mut check_encoder));
486 487 488 489 490
        let buf = buf.unwrap();
        let out = from_utf8(buf).unwrap();
        let needs_wrapping = out.char_at(0) != '"' &&
            out.char_at_reverse(out.len()) != '"';
        if needs_wrapping { try!(write!(self.wr, "\"")); }
S
Sean McArthur 已提交
491
        try!(f(self));
492
        if needs_wrapping { try!(write!(self.wr, "\"")); }
S
Sean McArthur 已提交
493
        Ok(())
494 495
    }

S
Sean McArthur 已提交
496 497 498
    fn emit_map_elt_val(&mut self,
                        _idx: uint,
                        f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
A
Alex Crichton 已提交
499
        try!(write!(self.wr, ":"));
500 501 502 503
        f(self)
    }
}

504 505
/// Another encoder for JSON, but prints out human-readable JSON instead of
/// compact data
E
Erik Price 已提交
506
pub struct PrettyEncoder<'a> {
507 508
    wr: &'a mut io::Writer,
    indent: uint,
509 510
}

E
Erik Price 已提交
511
impl<'a> PrettyEncoder<'a> {
512
    /// Creates a new encoder whose output will be written to the specified writer
513
    pub fn new<'a>(wr: &'a mut io::Writer) -> PrettyEncoder<'a> {
514 515 516 517
        PrettyEncoder {
            wr: wr,
            indent: 0,
        }
518
    }
519
}
520

S
Sean McArthur 已提交
521 522
impl<'a> ::Encoder<io::IoError> for PrettyEncoder<'a> {
    fn emit_nil(&mut self) -> EncodeResult { write!(self.wr, "null") }
523

S
Sean McArthur 已提交
524 525 526 527 528
    fn emit_uint(&mut self, v: uint) -> EncodeResult { self.emit_f64(v as f64) }
    fn emit_u64(&mut self, v: u64) -> EncodeResult { self.emit_f64(v as f64) }
    fn emit_u32(&mut self, v: u32) -> EncodeResult { self.emit_f64(v as f64) }
    fn emit_u16(&mut self, v: u16) -> EncodeResult { self.emit_f64(v as f64) }
    fn emit_u8(&mut self, v: u8) -> EncodeResult { self.emit_f64(v as f64) }
529

S
Sean McArthur 已提交
530 531 532 533 534
    fn emit_int(&mut self, v: int) -> EncodeResult { self.emit_f64(v as f64) }
    fn emit_i64(&mut self, v: i64) -> EncodeResult { self.emit_f64(v as f64) }
    fn emit_i32(&mut self, v: i32) -> EncodeResult { self.emit_f64(v as f64) }
    fn emit_i16(&mut self, v: i16) -> EncodeResult { self.emit_f64(v as f64) }
    fn emit_i8(&mut self, v: i8) -> EncodeResult { self.emit_f64(v as f64) }
535

S
Sean McArthur 已提交
536
    fn emit_bool(&mut self, v: bool) -> EncodeResult {
537
        if v {
S
Sean McArthur 已提交
538
            write!(self.wr, "true")
539
        } else {
S
Sean McArthur 已提交
540
            write!(self.wr, "false")
541 542 543
        }
    }

S
Sean McArthur 已提交
544 545
    fn emit_f64(&mut self, v: f64) -> EncodeResult {
        write!(self.wr, "{}", f64::to_str_digits(v, 6u))
A
Alex Crichton 已提交
546
    }
S
Sean McArthur 已提交
547
    fn emit_f32(&mut self, v: f32) -> EncodeResult { self.emit_f64(v as f64) }
548

S
Sean McArthur 已提交
549 550 551
    fn emit_char(&mut self, v: char) -> EncodeResult { self.emit_str(str::from_char(v)) }
    fn emit_str(&mut self, v: &str) -> EncodeResult {
        write!(self.wr, "{}", escape_str(v))
A
Alex Crichton 已提交
552
    }
553

S
Sean McArthur 已提交
554 555 556
    fn emit_enum(&mut self,
                 _name: &str,
                 f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
557 558 559 560 561 562 563
        f(self)
    }

    fn emit_enum_variant(&mut self,
                         name: &str,
                         _: uint,
                         cnt: uint,
S
Sean McArthur 已提交
564
                         f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
565
        if cnt == 0 {
S
Sean McArthur 已提交
566
            write!(self.wr, "{}", escape_str(name))
567 568
        } else {
            self.indent += 2;
A
Alex Crichton 已提交
569
            try!(write!(self.wr, "[\n{}{},\n", spaces(self.indent),
A
Alex Crichton 已提交
570
                          escape_str(name)));
S
Sean McArthur 已提交
571
            try!(f(self));
572
            self.indent -= 2;
S
Sean McArthur 已提交
573
            write!(self.wr, "\n{}]", spaces(self.indent))
574 575 576 577 578
        }
    }

    fn emit_enum_variant_arg(&mut self,
                             idx: uint,
S
Sean McArthur 已提交
579
                             f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
580
        if idx != 0 {
A
Alex Crichton 已提交
581
            try!(write!(self.wr, ",\n"));
582
        }
A
Alex Crichton 已提交
583
        try!(write!(self.wr, "{}", spaces(self.indent)));
584 585 586 587 588 589 590
        f(self)
    }

    fn emit_enum_struct_variant(&mut self,
                                name: &str,
                                id: uint,
                                cnt: uint,
S
Sean McArthur 已提交
591
                                f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
592 593 594 595 596 597
        self.emit_enum_variant(name, id, cnt, f)
    }

    fn emit_enum_struct_variant_field(&mut self,
                                      _: &str,
                                      idx: uint,
S
Sean McArthur 已提交
598
                                      f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
599 600 601 602 603 604 605
        self.emit_enum_variant_arg(idx, f)
    }


    fn emit_struct(&mut self,
                   _: &str,
                   len: uint,
S
Sean McArthur 已提交
606
                   f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
607
        if len == 0 {
S
Sean McArthur 已提交
608
            write!(self.wr, "\\{\\}")
609
        } else {
A
Alex Crichton 已提交
610
            try!(write!(self.wr, "\\{"));
611
            self.indent += 2;
S
Sean McArthur 已提交
612
            try!(f(self));
613
            self.indent -= 2;
S
Sean McArthur 已提交
614
            write!(self.wr, "\n{}\\}", spaces(self.indent))
615 616 617 618 619 620
        }
    }

    fn emit_struct_field(&mut self,
                         name: &str,
                         idx: uint,
S
Sean McArthur 已提交
621
                         f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
622
        if idx == 0 {
A
Alex Crichton 已提交
623
            try!(write!(self.wr, "\n"));
624
        } else {
A
Alex Crichton 已提交
625
            try!(write!(self.wr, ",\n"));
626
        }
A
Alex Crichton 已提交
627
        try!(write!(self.wr, "{}{}: ", spaces(self.indent), escape_str(name)));
S
Sean McArthur 已提交
628
        f(self)
629 630
    }

S
Sean McArthur 已提交
631 632 633
    fn emit_tuple(&mut self,
                  len: uint,
                  f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
634 635
        self.emit_seq(len, f)
    }
S
Sean McArthur 已提交
636 637 638
    fn emit_tuple_arg(&mut self,
                      idx: uint,
                      f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
639 640 641 642 643 644
        self.emit_seq_elt(idx, f)
    }

    fn emit_tuple_struct(&mut self,
                         _: &str,
                         len: uint,
S
Sean McArthur 已提交
645
                         f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
646 647 648 649
        self.emit_seq(len, f)
    }
    fn emit_tuple_struct_arg(&mut self,
                             idx: uint,
S
Sean McArthur 已提交
650
                             f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
651 652 653
        self.emit_seq_elt(idx, f)
    }

S
Sean McArthur 已提交
654 655 656 657 658 659 660
    fn emit_option(&mut self, f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
        f(self)
    }
    fn emit_option_none(&mut self) -> EncodeResult { self.emit_nil() }
    fn emit_option_some(&mut self, f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
        f(self)
    }
661

S
Sean McArthur 已提交
662 663 664
    fn emit_seq(&mut self,
                len: uint,
                f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
665
        if len == 0 {
S
Sean McArthur 已提交
666
            write!(self.wr, "[]")
667
        } else {
A
Alex Crichton 已提交
668
            try!(write!(self.wr, "["));
669
            self.indent += 2;
S
Sean McArthur 已提交
670
            try!(f(self));
671
            self.indent -= 2;
S
Sean McArthur 已提交
672
            write!(self.wr, "\n{}]", spaces(self.indent))
673 674 675
        }
    }

S
Sean McArthur 已提交
676 677 678
    fn emit_seq_elt(&mut self,
                    idx: uint,
                    f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
679
        if idx == 0 {
A
Alex Crichton 已提交
680
            try!(write!(self.wr, "\n"));
681
        } else {
A
Alex Crichton 已提交
682
            try!(write!(self.wr, ",\n"));
683
        }
A
Alex Crichton 已提交
684
        try!(write!(self.wr, "{}", spaces(self.indent)));
685 686 687
        f(self)
    }

S
Sean McArthur 已提交
688 689 690
    fn emit_map(&mut self,
                len: uint,
                f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
691
        if len == 0 {
S
Sean McArthur 已提交
692
            write!(self.wr, "\\{\\}")
693
        } else {
A
Alex Crichton 已提交
694
            try!(write!(self.wr, "\\{"));
695
            self.indent += 2;
S
Sean McArthur 已提交
696
            try!(f(self));
697
            self.indent -= 2;
S
Sean McArthur 已提交
698
            write!(self.wr, "\n{}\\}", spaces(self.indent))
699 700 701
        }
    }

S
Sean McArthur 已提交
702 703 704
    fn emit_map_elt_key(&mut self,
                        idx: uint,
                        f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
705
        use std::str::from_utf8;
706
        if idx == 0 {
A
Alex Crichton 已提交
707
            try!(write!(self.wr, "\n"));
708
        } else {
A
Alex Crichton 已提交
709
            try!(write!(self.wr, ",\n"));
710
        }
A
Alex Crichton 已提交
711
        try!(write!(self.wr, "{}", spaces(self.indent)));
712 713 714 715
        // ref #12967, make sure to wrap a key in double quotes,
        // in the event that its of a type that omits them (eg numbers)
        let mut buf = MemWriter::new();
        let mut check_encoder = PrettyEncoder::new(&mut buf);
S
Sean McArthur 已提交
716
        try!(f(&mut check_encoder));
717 718 719 720 721
        let buf = buf.unwrap();
        let out = from_utf8(buf).unwrap();
        let needs_wrapping = out.char_at(0) != '"' &&
            out.char_at_reverse(out.len()) != '"';
        if needs_wrapping { try!(write!(self.wr, "\"")); }
S
Sean McArthur 已提交
722
        try!(f(self));
723
        if needs_wrapping { try!(write!(self.wr, "\"")); }
S
Sean McArthur 已提交
724
        Ok(())
725 726
    }

S
Sean McArthur 已提交
727 728 729
    fn emit_map_elt_val(&mut self,
                        _idx: uint,
                        f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
A
Alex Crichton 已提交
730
        try!(write!(self.wr, ": "));
S
Sean McArthur 已提交
731
        f(self)
732 733 734
    }
}

735 736
impl<E: ::Encoder<S>, S> Encodable<E, S> for Json {
    fn encode(&self, e: &mut E) -> Result<(), S> {
737 738 739 740 741 742 743 744 745 746 747
        match *self {
            Number(v) => v.encode(e),
            String(ref v) => v.encode(e),
            Boolean(v) => v.encode(e),
            List(ref v) => v.encode(e),
            Object(ref v) => v.encode(e),
            Null => e.emit_nil(),
        }
    }
}

748
impl Json {
749
    /// Encodes a json value into a io::writer.  Uses a single line.
S
Sean McArthur 已提交
750
    pub fn to_writer(&self, wr: &mut io::Writer) -> EncodeResult {
751
        let mut encoder = Encoder::new(wr);
S
Sean McArthur 已提交
752
        self.encode(&mut encoder)
753
    }
754

755 756
    /// Encodes a json value into a io::writer.
    /// Pretty-prints in a more readable format.
S
Sean McArthur 已提交
757
    pub fn to_pretty_writer(&self, wr: &mut io::Writer) -> EncodeResult {
758
        let mut encoder = PrettyEncoder::new(wr);
S
Sean McArthur 已提交
759
        self.encode(&mut encoder)
760
    }
761

762 763
    /// Encodes a json value into a string
    pub fn to_pretty_str(&self) -> ~str {
764
        let mut s = MemWriter::new();
A
Alex Crichton 已提交
765
        self.to_pretty_writer(&mut s as &mut io::Writer).unwrap();
766
        str::from_utf8_owned(s.unwrap()).unwrap()
767
    }
768 769 770 771 772 773 774 775 776 777 778

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

    /// Attempts to get a nested Json Object for each key in `keys`.
779
    /// If any key is found not to exist, find_path will return None.
780 781
    /// Otherwise, it will return the Json value associated with the final key.
    pub fn find_path<'a>(&'a self, keys: &[&~str]) -> Option<&'a Json>{
782 783 784 785 786 787 788 789
        let mut target = self;
        for key in keys.iter() {
            match target.find(*key) {
                Some(t) => { target = t; },
                None => return None
            }
        }
        Some(target)
790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817
    }

    /// 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.
    pub fn search<'a>(&'a self, key: &~str) -> Option<&'a Json> {
        match self {
            &Object(ref map) => {
                match map.find(key) {
                    Some(json_value) => Some(json_value),
                    None => {
                        let mut value : Option<&'a Json> = None;
                        for (_, v) in map.iter() {
                            value = v.search(key);
                            if value.is_some() {
                                break;
                            }
                        }
                        value
                    }
                }
            },
            _ => None
        }
    }

    /// Returns true if the Json value is an Object. Returns false otherwise.
    pub fn is_object<'a>(&'a self) -> bool {
818
        self.as_object().is_some()
819 820 821 822 823 824 825 826 827 828 829 830 831
    }

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

    /// Returns true if the Json value is a List. Returns false otherwise.
    pub fn is_list<'a>(&'a self) -> bool {
832
        self.as_list().is_some()
833 834 835 836 837 838 839 840 841 842 843 844
    }

    /// If the Json value is a List, returns the associated vector.
    /// Returns None otherwise.
    pub fn as_list<'a>(&'a self) -> Option<&'a List> {
        match self {
            &List(ref list) => Some(&*list),
            _ => None
        }
    }

    /// Returns true if the Json value is a String. Returns false otherwise.
845 846
    pub fn is_string<'a>(&'a self) -> bool {
        self.as_string().is_some()
847 848 849 850
    }

    /// If the Json value is a String, returns the associated str.
    /// Returns None otherwise.
851
    pub fn as_string<'a>(&'a self) -> Option<&'a str> {
852 853 854 855 856 857 858 859
        match *self {
            String(ref s) => Some(s.as_slice()),
            _ => None
        }
    }

    /// Returns true if the Json value is a Number. Returns false otherwise.
    pub fn is_number(&self) -> bool {
860
        self.as_number().is_some()
861 862 863 864 865 866 867 868 869 870 871 872 873
    }

    /// If the Json value is a Number, returns the associated f64.
    /// Returns None otherwise.
    pub fn as_number(&self) -> Option<f64> {
        match self {
            &Number(n) => Some(n),
            _ => None
        }
    }

    /// Returns true if the Json value is a Boolean. Returns false otherwise.
    pub fn is_boolean(&self) -> bool {
874
        self.as_boolean().is_some()
875 876 877 878 879 880 881 882 883 884 885 886 887
    }

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

    /// Returns true if the Json value is a Null. Returns false otherwise.
    pub fn is_null(&self) -> bool {
888
        self.as_null().is_some()
889 890 891 892 893 894 895 896 897 898
    }

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

G
Gary Linscott 已提交
901
pub struct Parser<T> {
902 903 904 905
    rdr: T,
    ch: Option<char>,
    line: uint,
    col: uint,
906 907
}

908 909
impl<T: Iterator<char>> Parser<T> {
    /// Decode a json value from an Iterator<char>
910
    pub fn new(rdr: T) -> Parser<T> {
911 912
        let mut p = Parser {
            rdr: rdr,
913
            ch: Some('\x00'),
914 915 916 917 918 919
            line: 1,
            col: 0,
        };
        p.bump();
        p
    }
920
}
E
Elly Jones 已提交
921

922
impl<T: Iterator<char>> Parser<T> {
S
Sean McArthur 已提交
923
    pub fn parse(&mut self) -> DecodeResult<Json> {
L
Luqman Aden 已提交
924 925
        match self.parse_value() {
          Ok(value) => {
926 927 928 929
            // Skip trailing whitespaces.
            self.parse_whitespace();
            // Make sure there is no trailing characters.
            if self.eof() {
L
Luqman Aden 已提交
930
                Ok(value)
931 932 933 934
            } else {
                self.error(~"trailing characters")
            }
          }
L
Luqman Aden 已提交
935
          Err(e) => Err(e)
936 937
        }
    }
938 939
}

940
impl<T : Iterator<char>> Parser<T> {
941 942
    fn eof(&self) -> bool { self.ch.is_none() }
    fn ch_or_null(&self) -> char { self.ch.unwrap_or('\x00') }
943
    fn bump(&mut self) {
944
        self.ch = self.rdr.next();
E
Elly Jones 已提交
945

946
        if self.ch_is('\n') {
947 948
            self.line += 1u;
            self.col = 1u;
G
Gary Linscott 已提交
949 950
        } else {
            self.col += 1u;
E
Elly Jones 已提交
951
        }
952 953
    }

954
    fn next_char(&mut self) -> Option<char> {
955 956 957
        self.bump();
        self.ch
    }
958 959 960
    fn ch_is(&self, c: char) -> bool {
        self.ch == Some(c)
    }
961

S
Sean McArthur 已提交
962 963
    fn error<T>(&self, msg: ~str) -> DecodeResult<T> {
        Err(ParseError(msg, self.line, self.col))
E
Elly Jones 已提交
964 965
    }

S
Sean McArthur 已提交
966
    fn parse_value(&mut self) -> DecodeResult<Json> {
967 968
        self.parse_whitespace();

B
Brian Anderson 已提交
969
        if self.eof() { return self.error(~"EOF while parsing value"); }
E
Elly Jones 已提交
970

971 972 973 974 975 976 977 978 979 980
        match self.ch_or_null() {
            'n' => self.parse_ident("ull", Null),
            't' => self.parse_ident("rue", Boolean(true)),
            'f' => self.parse_ident("alse", Boolean(false)),
            '0' .. '9' | '-' => self.parse_number(),
            '"' => {
                match self.parse_str() {
                    Ok(s) => Ok(String(s)),
                    Err(e) => Err(e),
                }
981
            },
982 983 984
            '[' => self.parse_list(),
            '{' => self.parse_object(),
            _ => self.error(~"invalid syntax"),
E
Elly Jones 已提交
985
        }
986 987
    }

988
    fn parse_whitespace(&mut self) {
989 990 991 992
        while self.ch_is(' ') ||
              self.ch_is('\n') ||
              self.ch_is('\t') ||
              self.ch_is('\r') { self.bump(); }
993 994
    }

S
Sean McArthur 已提交
995
    fn parse_ident(&mut self, ident: &str, value: Json) -> DecodeResult<Json> {
996
        if ident.chars().all(|c| Some(c) == self.next_char()) {
997
            self.bump();
L
Luqman Aden 已提交
998
            Ok(value)
999
        } else {
1000
            self.error(~"invalid syntax")
E
Elly Jones 已提交
1001 1002 1003
        }
    }

S
Sean McArthur 已提交
1004
    fn parse_number(&mut self) -> DecodeResult<Json> {
D
Daniel Micay 已提交
1005
        let mut neg = 1.0;
1006

1007
        if self.ch_is('-') {
1008
            self.bump();
D
Daniel Micay 已提交
1009
            neg = -1.0;
E
Elly Jones 已提交
1010
        }
1011

1012
        let mut res = match self.parse_integer() {
1013 1014
          Ok(res) => res,
          Err(e) => return Err(e)
1015 1016
        };

1017
        if self.ch_is('.') {
1018
            match self.parse_decimal(res) {
1019 1020
              Ok(r) => res = r,
              Err(e) => return Err(e)
1021
            }
E
Elly Jones 已提交
1022
        }
1023

1024
        if self.ch_is('e') || self.ch_is('E') {
1025
            match self.parse_exponent(res) {
1026 1027
              Ok(r) => res = r,
              Err(e) => return Err(e)
1028
            }
E
Elly Jones 已提交
1029
        }
1030

1031
        Ok(Number(neg * res))
E
Elly Jones 已提交
1032 1033
    }

S
Sean McArthur 已提交
1034
    fn parse_integer(&mut self) -> DecodeResult<f64> {
D
Daniel Micay 已提交
1035
        let mut res = 0.0;
E
Elly Jones 已提交
1036

1037 1038 1039
        match self.ch_or_null() {
            '0' => {
                self.bump();
1040

1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057
                // There can be only one leading '0'.
                match self.ch_or_null() {
                    '0' .. '9' => return self.error(~"invalid number"),
                    _ => ()
                }
            },
            '1' .. '9' => {
                while !self.eof() {
                    match self.ch_or_null() {
                        c @ '0' .. '9' => {
                            res *= 10.0;
                            res += ((c as int) - ('0' as int)) as f64;

                            self.bump();
                        }
                        _ => break,
                    }
1058 1059
                }
            }
1060
            _ => return self.error(~"invalid number"),
E
Elly Jones 已提交
1061
        }
1062
        Ok(res)
E
Elly Jones 已提交
1063 1064
    }

S
Sean McArthur 已提交
1065
    fn parse_decimal(&mut self, res: f64) -> DecodeResult<f64> {
1066 1067 1068
        self.bump();

        // Make sure a digit follows the decimal place.
1069 1070 1071
        match self.ch_or_null() {
            '0' .. '9' => (),
             _ => return self.error(~"invalid number")
1072 1073
        }

1074
        let mut res = res;
D
Daniel Micay 已提交
1075
        let mut dec = 1.0;
1076
        while !self.eof() {
1077 1078 1079 1080
            match self.ch_or_null() {
                c @ '0' .. '9' => {
                    dec /= 10.0;
                    res += (((c as int) - ('0' as int)) as f64) * dec;
1081

1082 1083 1084
                    self.bump();
                }
                _ => break,
E
Elly Jones 已提交
1085 1086
            }
        }
1087

1088
        Ok(res)
E
Elly Jones 已提交
1089 1090
    }

S
Sean McArthur 已提交
1091
    fn parse_exponent(&mut self, mut res: f64) -> DecodeResult<f64> {
1092 1093
        self.bump();

1094 1095
        let mut exp = 0u;
        let mut neg_exp = false;
1096

1097 1098 1099 1100 1101
        if self.ch_is('+') {
            self.bump();
        } else if self.ch_is('-') {
            self.bump();
            neg_exp = true;
1102 1103 1104
        }

        // Make sure a digit follows the exponent place.
1105 1106 1107
        match self.ch_or_null() {
            '0' .. '9' => (),
            _ => return self.error(~"invalid number")
1108 1109
        }
        while !self.eof() {
1110 1111 1112 1113
            match self.ch_or_null() {
                c @ '0' .. '9' => {
                    exp *= 10;
                    exp += (c as uint) - ('0' as uint);
1114

1115 1116 1117
                    self.bump();
                }
                _ => break
1118 1119 1120
            }
        }

1121
        let exp: f64 = num::pow(10u as f64, exp);
1122 1123 1124 1125 1126 1127
        if neg_exp {
            res /= exp;
        } else {
            res *= exp;
        }

1128
        Ok(res)
E
Elly Jones 已提交
1129 1130
    }

S
Sean McArthur 已提交
1131
    fn parse_str(&mut self) -> DecodeResult<~str> {
1132
        let mut escape = false;
1133
        let mut res = ~"";
1134

G
Gary Linscott 已提交
1135
        loop {
1136
            self.bump();
G
Gary Linscott 已提交
1137 1138 1139
            if self.eof() {
                return self.error(~"EOF while parsing string");
            }
1140

H
Huon Wilson 已提交
1141
            if escape {
1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180
                match self.ch_or_null() {
                    '"' => res.push_char('"'),
                    '\\' => res.push_char('\\'),
                    '/' => res.push_char('/'),
                    'b' => res.push_char('\x08'),
                    'f' => res.push_char('\x0c'),
                    'n' => res.push_char('\n'),
                    'r' => res.push_char('\r'),
                    't' => res.push_char('\t'),
                    'u' => {
                        // Parse \u1234.
                        let mut i = 0u;
                        let mut n = 0u;
                        while i < 4u && !self.eof() {
                            self.bump();
                            n = match self.ch_or_null() {
                                c @ '0' .. '9' => n * 16u + (c as uint) - ('0' as uint),
                                'a' | 'A' => n * 16u + 10u,
                                'b' | 'B' => n * 16u + 11u,
                                'c' | 'C' => n * 16u + 12u,
                                'd' | 'D' => n * 16u + 13u,
                                'e' | 'E' => n * 16u + 14u,
                                'f' | 'F' => n * 16u + 15u,
                                _ => return self.error(
                                    ~"invalid \\u escape (unrecognized hex)")
                            };

                            i += 1u;
                        }

                        // Error out if we didn't parse 4 digits.
                        if i != 4u {
                            return self.error(
                                ~"invalid \\u escape (not four digits)");
                        }

                        res.push_char(char::from_u32(n as u32).unwrap());
                    }
                    _ => return self.error(~"invalid escape"),
1181 1182
                }
                escape = false;
1183
            } else if self.ch_is('\\') {
1184 1185
                escape = true;
            } else {
1186 1187 1188 1189
                match self.ch {
                    Some('"') => { self.bump(); return Ok(res); },
                    Some(c) => res.push_char(c),
                    None => unreachable!()
1190
                }
E
Elly Jones 已提交
1191 1192 1193 1194
            }
        }
    }

S
Sean McArthur 已提交
1195
    fn parse_list(&mut self) -> DecodeResult<Json> {
1196 1197 1198
        self.bump();
        self.parse_whitespace();

1199
        let mut values = ~[];
1200

1201
        if self.ch_is(']') {
1202
            self.bump();
L
Luqman Aden 已提交
1203
            return Ok(List(values));
1204 1205
        }

1206
        loop {
L
Luqman Aden 已提交
1207 1208 1209
            match self.parse_value() {
              Ok(v) => values.push(v),
              Err(e) => return Err(e)
1210 1211 1212
            }

            self.parse_whitespace();
1213
            if self.eof() {
B
Brian Anderson 已提交
1214
                return self.error(~"EOF while parsing list");
1215
            }
1216

1217 1218 1219 1220 1221 1222 1223
            if self.ch_is(',') {
                self.bump();
            } else if self.ch_is(']') {
                self.bump();
                return Ok(List(values));
            } else {
                return self.error(~"expected `,` or `]`")
1224
            }
1225
        };
E
Elly Jones 已提交
1226 1227
    }

S
Sean McArthur 已提交
1228
    fn parse_object(&mut self) -> DecodeResult<Json> {
1229 1230 1231
        self.bump();
        self.parse_whitespace();

1232
        let mut values = ~TreeMap::new();
1233

1234
        if self.ch_is('}') {
1235
          self.bump();
L
Luqman Aden 已提交
1236
          return Ok(Object(values));
1237 1238 1239 1240 1241
        }

        while !self.eof() {
            self.parse_whitespace();

1242
            if !self.ch_is('"') {
B
Brian Anderson 已提交
1243
                return self.error(~"key must be a string");
1244 1245
            }

L
Luqman Aden 已提交
1246 1247 1248
            let key = match self.parse_str() {
              Ok(key) => key,
              Err(e) => return Err(e)
1249 1250 1251 1252
            };

            self.parse_whitespace();

1253
            if !self.ch_is(':') {
1254
                if self.eof() { break; }
B
Brian Anderson 已提交
1255
                return self.error(~"expected `:`");
1256 1257 1258
            }
            self.bump();

L
Luqman Aden 已提交
1259 1260 1261
            match self.parse_value() {
              Ok(value) => { values.insert(key, value); }
              Err(e) => return Err(e)
1262 1263 1264
            }
            self.parse_whitespace();

1265 1266 1267 1268 1269 1270 1271
            match self.ch_or_null() {
                ',' => self.bump(),
                '}' => { self.bump(); return Ok(Object(values)); },
                _ => {
                    if self.eof() { break; }
                    return self.error(~"expected `,` or `}`");
                }
1272 1273 1274
            }
        }

B
Brian Anderson 已提交
1275
        return self.error(~"EOF while parsing object");
L
Lenny222 已提交
1276 1277 1278
    }
}

A
Alex Crichton 已提交
1279
/// Decodes a json value from an `&mut io::Reader`
S
Sean McArthur 已提交
1280
pub fn from_reader(rdr: &mut io::Reader) -> DecodeResult<Json> {
A
Alex Crichton 已提交
1281 1282
    let contents = match rdr.read_to_end() {
        Ok(c) => c,
S
Sean McArthur 已提交
1283
        Err(e) => return Err(IoError(e))
A
Alex Crichton 已提交
1284 1285 1286
    };
    let s = match str::from_utf8_owned(contents) {
        Some(s) => s,
S
Sean McArthur 已提交
1287
        None => return Err(ParseError(~"contents not utf-8", 0, 0))
A
Alex Crichton 已提交
1288
    };
1289
    let mut parser = Parser::new(s.chars());
1290
    parser.parse()
E
Elly Jones 已提交
1291 1292
}

1293
/// Decodes a json value from a string
S
Sean McArthur 已提交
1294
pub fn from_str(s: &str) -> DecodeResult<Json> {
1295
    let mut parser = Parser::new(s.chars());
G
Gary Linscott 已提交
1296
    parser.parse()
1297 1298
}

1299
/// A structure to decode JSON to values in rust.
1300
pub struct Decoder {
1301
    stack: ~[Json],
1302 1303
}

1304 1305
impl Decoder {
    /// Creates a new decoder instance for decoding the specified JSON value.
1306
    pub fn new(json: Json) -> Decoder {
1307 1308 1309
        Decoder {
            stack: ~[json]
        }
1310
    }
1311 1312
}

1313
impl Decoder {
S
Sean McArthur 已提交
1314 1315
    fn pop(&mut self) -> Json {
        self.stack.pop().unwrap()
1316 1317 1318
    }
}

S
Sean McArthur 已提交
1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329
macro_rules! expect(
    ($e:expr, Null) => ({
        match $e {
            Null => Ok(()),
            other => Err(ExpectedError(~"Null", format!("{}", other)))
        }
    });
    ($e:expr, $t:ident) => ({
        match $e {
            $t(v) => Ok(v),
            other => Err(ExpectedError(stringify!($t).to_owned(), format!("{}", other)))
1330
        }
S
Sean McArthur 已提交
1331 1332 1333 1334 1335 1336 1337 1338
    })
)

impl ::Decoder<Error> for Decoder {
    fn read_nil(&mut self) -> DecodeResult<()> {
        debug!("read_nil");
        try!(expect!(self.pop(), Null));
        Ok(())
1339 1340
    }

S
Sean McArthur 已提交
1341 1342 1343 1344 1345
    fn read_u64(&mut self)  -> DecodeResult<u64 > { Ok(try!(self.read_f64()) as u64) }
    fn read_u32(&mut self)  -> DecodeResult<u32 > { Ok(try!(self.read_f64()) as u32) }
    fn read_u16(&mut self)  -> DecodeResult<u16 > { Ok(try!(self.read_f64()) as u16) }
    fn read_u8 (&mut self)  -> DecodeResult<u8  > { Ok(try!(self.read_f64()) as u8) }
    fn read_uint(&mut self) -> DecodeResult<uint> { Ok(try!(self.read_f64()) as uint) }
1346

S
Sean McArthur 已提交
1347 1348 1349 1350 1351
    fn read_i64(&mut self) -> DecodeResult<i64> { Ok(try!(self.read_f64()) as i64) }
    fn read_i32(&mut self) -> DecodeResult<i32> { Ok(try!(self.read_f64()) as i32) }
    fn read_i16(&mut self) -> DecodeResult<i16> { Ok(try!(self.read_f64()) as i16) }
    fn read_i8 (&mut self) -> DecodeResult<i8 > { Ok(try!(self.read_f64()) as i8) }
    fn read_int(&mut self) -> DecodeResult<int> { Ok(try!(self.read_f64()) as int) }
1352

S
Sean McArthur 已提交
1353
    fn read_bool(&mut self) -> DecodeResult<bool> {
1354
        debug!("read_bool");
S
Sean McArthur 已提交
1355
        Ok(try!(expect!(self.pop(), Boolean)))
1356 1357
    }

S
Sean McArthur 已提交
1358
    fn read_f64(&mut self) -> DecodeResult<f64> {
1359
        use std::from_str::FromStr;
1360
        debug!("read_f64");
S
Sean McArthur 已提交
1361 1362
        match self.pop() {
            Number(f) => Ok(f),
1363 1364 1365
            String(s) => {
                // re: #12967.. a type w/ numeric keys (ie HashMap<uint, V> etc)
                // is going to have a string here, as per JSON spec..
S
Sean McArthur 已提交
1366
                Ok(FromStr::from_str(s).unwrap())
1367
            },
S
Sean McArthur 已提交
1368
            value => Err(ExpectedError(~"Number", format!("{}", value)))
1369 1370
        }
    }
1371

S
Sean McArthur 已提交
1372
    fn read_f32(&mut self) -> DecodeResult<f32> { Ok(try!(self.read_f64()) as f32) }
1373

S
Sean McArthur 已提交
1374 1375
    fn read_char(&mut self) -> DecodeResult<char> {
        let s = try!(self.read_str());
1376
        {
1377
            let mut it = s.chars();
1378 1379
            match (it.next(), it.next()) {
                // exactly one character
S
Sean McArthur 已提交
1380
                (Some(c), None) => return Ok(c),
1381 1382 1383
                _ => ()
            }
        }
S
Sean McArthur 已提交
1384
        Err(ExpectedError(~"single character string", format!("{}", s)))
1385 1386
    }

S
Sean McArthur 已提交
1387
    fn read_str(&mut self) -> DecodeResult<~str> {
1388
        debug!("read_str");
S
Sean McArthur 已提交
1389
        Ok(try!(expect!(self.pop(), String)))
1390 1391
    }

S
Sean McArthur 已提交
1392 1393 1394
    fn read_enum<T>(&mut self,
                    name: &str,
                    f: |&mut Decoder| -> DecodeResult<T>) -> DecodeResult<T> {
1395
        debug!("read_enum({})", name);
1396 1397 1398 1399 1400
        f(self)
    }

    fn read_enum_variant<T>(&mut self,
                            names: &[&str],
S
Sean McArthur 已提交
1401 1402
                            f: |&mut Decoder, uint| -> DecodeResult<T>)
                            -> DecodeResult<T> {
1403
        debug!("read_enum_variant(names={:?})", names);
S
Sean McArthur 已提交
1404
        let name = match self.pop() {
1405
            String(s) => s,
1406 1407 1408
            Object(mut o) => {
                let n = match o.pop(&~"variant") {
                    Some(String(s)) => s,
S
Sean McArthur 已提交
1409 1410
                    Some(val) => return Err(ExpectedError(~"String", format!("{}", val))),
                    None => return Err(MissingFieldError(~"variant"))
1411
                };
1412 1413 1414
                match o.pop(&~"fields") {
                    Some(List(l)) => {
                        for field in l.move_rev_iter() {
1415 1416 1417
                            self.stack.push(field.clone());
                        }
                    },
S
Sean McArthur 已提交
1418 1419
                    Some(val) => return Err(ExpectedError(~"List", format!("{}", val))),
                    None => return Err(MissingFieldError(~"fields"))
1420
                }
1421
                n
1422
            }
S
Sean McArthur 已提交
1423
            json => return Err(ExpectedError(~"String or Object", format!("{}", json)))
1424
        };
1425
        let idx = match names.iter().position(|n| str::eq_slice(*n, name)) {
1426
            Some(idx) => idx,
S
Sean McArthur 已提交
1427
            None => return Err(UnknownVariantError(name))
1428 1429 1430 1431
        };
        f(self, idx)
    }

S
Sean McArthur 已提交
1432 1433
    fn read_enum_variant_arg<T>(&mut self, idx: uint, f: |&mut Decoder| -> DecodeResult<T>)
                                -> DecodeResult<T> {
1434
        debug!("read_enum_variant_arg(idx={})", idx);
1435 1436 1437 1438 1439
        f(self)
    }

    fn read_enum_struct_variant<T>(&mut self,
                                   names: &[&str],
S
Sean McArthur 已提交
1440 1441
                                   f: |&mut Decoder, uint| -> DecodeResult<T>)
                                   -> DecodeResult<T> {
1442
        debug!("read_enum_struct_variant(names={:?})", names);
1443 1444 1445 1446 1447 1448 1449
        self.read_enum_variant(names, f)
    }


    fn read_enum_struct_variant_field<T>(&mut self,
                                         name: &str,
                                         idx: uint,
S
Sean McArthur 已提交
1450 1451
                                         f: |&mut Decoder| -> DecodeResult<T>)
                                         -> DecodeResult<T> {
1452
        debug!("read_enum_struct_variant_field(name={}, idx={})", name, idx);
1453 1454 1455 1456 1457 1458
        self.read_enum_variant_arg(idx, f)
    }

    fn read_struct<T>(&mut self,
                      name: &str,
                      len: uint,
S
Sean McArthur 已提交
1459 1460
                      f: |&mut Decoder| -> DecodeResult<T>)
                      -> DecodeResult<T> {
1461
        debug!("read_struct(name={}, len={})", name, len);
S
Sean McArthur 已提交
1462 1463 1464
        let value = try!(f(self));
        self.pop();
        Ok(value)
1465 1466 1467 1468 1469
    }

    fn read_struct_field<T>(&mut self,
                            name: &str,
                            idx: uint,
S
Sean McArthur 已提交
1470 1471
                            f: |&mut Decoder| -> DecodeResult<T>)
                            -> DecodeResult<T> {
1472
        debug!("read_struct_field(name={}, idx={})", name, idx);
S
Sean McArthur 已提交
1473 1474 1475 1476 1477 1478 1479
        let mut obj = try!(expect!(self.pop(), Object));

        let value = match obj.pop(&name.to_owned()) {
            None => return Err(MissingFieldError(name.to_owned())),
            Some(json) => {
                self.stack.push(json);
                try!(f(self))
1480
            }
S
Sean McArthur 已提交
1481 1482 1483
        };
        self.stack.push(Object(obj));
        Ok(value)
1484 1485
    }

S
Sean McArthur 已提交
1486
    fn read_tuple<T>(&mut self, f: |&mut Decoder, uint| -> DecodeResult<T>) -> DecodeResult<T> {
1487
        debug!("read_tuple()");
1488 1489 1490
        self.read_seq(f)
    }

S
Sean McArthur 已提交
1491 1492 1493
    fn read_tuple_arg<T>(&mut self,
                         idx: uint,
                         f: |&mut Decoder| -> DecodeResult<T>) -> DecodeResult<T> {
1494
        debug!("read_tuple_arg(idx={})", idx);
1495 1496 1497 1498 1499
        self.read_seq_elt(idx, f)
    }

    fn read_tuple_struct<T>(&mut self,
                            name: &str,
S
Sean McArthur 已提交
1500 1501
                            f: |&mut Decoder, uint| -> DecodeResult<T>)
                            -> DecodeResult<T> {
1502
        debug!("read_tuple_struct(name={})", name);
1503 1504 1505 1506 1507
        self.read_tuple(f)
    }

    fn read_tuple_struct_arg<T>(&mut self,
                                idx: uint,
S
Sean McArthur 已提交
1508 1509
                                f: |&mut Decoder| -> DecodeResult<T>)
                                -> DecodeResult<T> {
1510
        debug!("read_tuple_struct_arg(idx={})", idx);
1511 1512 1513
        self.read_tuple_arg(idx, f)
    }

S
Sean McArthur 已提交
1514 1515
    fn read_option<T>(&mut self, f: |&mut Decoder, bool| -> DecodeResult<T>) -> DecodeResult<T> {
        match self.pop() {
1516 1517 1518 1519 1520
            Null => f(self, false),
            value => { self.stack.push(value); f(self, true) }
        }
    }

S
Sean McArthur 已提交
1521
    fn read_seq<T>(&mut self, f: |&mut Decoder, uint| -> DecodeResult<T>) -> DecodeResult<T> {
1522
        debug!("read_seq()");
S
Sean McArthur 已提交
1523 1524 1525 1526 1527
        let list = try!(expect!(self.pop(), List));
        let len = list.len();
        for v in list.move_rev_iter() {
            self.stack.push(v);
        }
1528 1529 1530
        f(self, len)
    }

S
Sean McArthur 已提交
1531 1532 1533
    fn read_seq_elt<T>(&mut self,
                       idx: uint,
                       f: |&mut Decoder| -> DecodeResult<T>) -> DecodeResult<T> {
1534
        debug!("read_seq_elt(idx={})", idx);
1535 1536 1537
        f(self)
    }

S
Sean McArthur 已提交
1538
    fn read_map<T>(&mut self, f: |&mut Decoder, uint| -> DecodeResult<T>) -> DecodeResult<T> {
1539
        debug!("read_map()");
S
Sean McArthur 已提交
1540 1541 1542 1543 1544 1545
        let obj = try!(expect!(self.pop(), Object));
        let len = obj.len();
        for (key, value) in obj.move_iter() {
            self.stack.push(value);
            self.stack.push(String(key));
        }
1546 1547 1548
        f(self, len)
    }

S
Sean McArthur 已提交
1549 1550
    fn read_map_elt_key<T>(&mut self, idx: uint, f: |&mut Decoder| -> DecodeResult<T>)
                           -> DecodeResult<T> {
1551
        debug!("read_map_elt_key(idx={})", idx);
1552 1553 1554
        f(self)
    }

S
Sean McArthur 已提交
1555 1556
    fn read_map_elt_val<T>(&mut self, idx: uint, f: |&mut Decoder| -> DecodeResult<T>)
                           -> DecodeResult<T> {
1557
        debug!("read_map_elt_val(idx={})", idx);
1558 1559 1560 1561
        f(self)
    }
}

1562
/// Test if two json values are less than one another
1563
impl Ord for Json {
1564
    fn lt(&self, other: &Json) -> bool {
H
Huon Wilson 已提交
1565
        match *self {
1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589
            Number(f0) => {
                match *other {
                    Number(f1) => f0 < f1,
                    String(_) | Boolean(_) | List(_) | Object(_) |
                    Null => true
                }
            }

            String(ref s0) => {
                match *other {
                    Number(_) => false,
                    String(ref s1) => s0 < s1,
                    Boolean(_) | List(_) | Object(_) | Null => true
                }
            }

            Boolean(b0) => {
                match *other {
                    Number(_) | String(_) => false,
                    Boolean(b1) => b0 < b1,
                    List(_) | Object(_) | Null => true
                }
            }

1590
            List(ref l0) => {
1591 1592
                match *other {
                    Number(_) | String(_) | Boolean(_) => false,
1593
                    List(ref l1) => (*l0) < (*l1),
1594 1595 1596 1597 1598 1599 1600
                    Object(_) | Null => true
                }
            }

            Object(ref d0) => {
                match *other {
                    Number(_) | String(_) | Boolean(_) | List(_) => false,
1601
                    Object(ref d1) => d0 < d1,
1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615
                    Null => true
                }
            }

            Null => {
                match *other {
                    Number(_) | String(_) | Boolean(_) | List(_) |
                    Object(_) =>
                        false,
                    Null => true
                }
            }
        }
    }
1616
}
1617

1618
/// A trait for converting values to JSON
1619
pub trait ToJson {
1620 1621 1622
    /// Converts the value of `self` to an instance of JSON
    fn to_json(&self) -> Json;
}
1623

1624
impl ToJson for Json {
1625
    fn to_json(&self) -> Json { (*self).clone() }
1626 1627
}

1628
impl ToJson for int {
D
Daniel Micay 已提交
1629
    fn to_json(&self) -> Json { Number(*self as f64) }
1630 1631
}

1632
impl ToJson for i8 {
D
Daniel Micay 已提交
1633
    fn to_json(&self) -> Json { Number(*self as f64) }
1634 1635
}

1636
impl ToJson for i16 {
D
Daniel Micay 已提交
1637
    fn to_json(&self) -> Json { Number(*self as f64) }
1638 1639
}

1640
impl ToJson for i32 {
D
Daniel Micay 已提交
1641
    fn to_json(&self) -> Json { Number(*self as f64) }
1642 1643
}

1644
impl ToJson for i64 {
D
Daniel Micay 已提交
1645
    fn to_json(&self) -> Json { Number(*self as f64) }
1646 1647
}

1648
impl ToJson for uint {
D
Daniel Micay 已提交
1649
    fn to_json(&self) -> Json { Number(*self as f64) }
1650 1651
}

1652
impl ToJson for u8 {
D
Daniel Micay 已提交
1653
    fn to_json(&self) -> Json { Number(*self as f64) }
1654 1655
}

1656
impl ToJson for u16 {
D
Daniel Micay 已提交
1657
    fn to_json(&self) -> Json { Number(*self as f64) }
1658 1659
}

1660
impl ToJson for u32 {
D
Daniel Micay 已提交
1661
    fn to_json(&self) -> Json { Number(*self as f64) }
1662 1663
}

1664
impl ToJson for u64 {
D
Daniel Micay 已提交
1665
    fn to_json(&self) -> Json { Number(*self as f64) }
1666 1667
}

1668
impl ToJson for f32 {
D
Daniel Micay 已提交
1669
    fn to_json(&self) -> Json { Number(*self as f64) }
1670 1671
}

1672
impl ToJson for f64 {
D
Daniel Micay 已提交
1673
    fn to_json(&self) -> Json { Number(*self) }
1674 1675
}

1676
impl ToJson for () {
B
Ben Striegel 已提交
1677
    fn to_json(&self) -> Json { Null }
1678 1679
}

1680
impl ToJson for bool {
B
Ben Striegel 已提交
1681
    fn to_json(&self) -> Json { Boolean(*self) }
1682 1683
}

1684
impl ToJson for ~str {
1685
    fn to_json(&self) -> Json { String((*self).clone()) }
1686 1687
}

1688
impl<A:ToJson,B:ToJson> ToJson for (A, B) {
B
Ben Striegel 已提交
1689 1690
    fn to_json(&self) -> Json {
        match *self {
1691
          (ref a, ref b) => {
1692
            List(~[a.to_json(), b.to_json()])
1693 1694
          }
        }
1695 1696 1697
    }
}

1698
impl<A:ToJson,B:ToJson,C:ToJson> ToJson for (A, B, C) {
B
Ben Striegel 已提交
1699 1700
    fn to_json(&self) -> Json {
        match *self {
1701
          (ref a, ref b, ref c) => {
1702
            List(~[a.to_json(), b.to_json(), c.to_json()])
1703 1704
          }
        }
1705 1706 1707
    }
}

1708
impl<A:ToJson> ToJson for ~[A] {
1709
    fn to_json(&self) -> Json { List(self.iter().map(|elt| elt.to_json()).collect()) }
1710 1711
}

1712
impl<A:ToJson> ToJson for TreeMap<~str, A> {
B
Ben Striegel 已提交
1713
    fn to_json(&self) -> Json {
1714
        let mut d = TreeMap::new();
D
Daniel Micay 已提交
1715
        for (key, value) in self.iter() {
1716
            d.insert((*key).clone(), value.to_json());
1717 1718 1719 1720 1721
        }
        Object(~d)
    }
}

1722
impl<A:ToJson> ToJson for HashMap<~str, A> {
G
Graydon Hoare 已提交
1723
    fn to_json(&self) -> Json {
1724
        let mut d = TreeMap::new();
D
Daniel Micay 已提交
1725
        for (key, value) in self.iter() {
1726
            d.insert((*key).clone(), value.to_json());
G
Graydon Hoare 已提交
1727 1728 1729 1730 1731
        }
        Object(~d)
    }
}

1732
impl<A:ToJson> ToJson for Option<A> {
B
Ben Striegel 已提交
1733 1734
    fn to_json(&self) -> Json {
        match *self {
B
Ben Striegel 已提交
1735
          None => Null,
1736
          Some(ref value) => value.to_json()
1737 1738 1739 1740
        }
    }
}

1741
impl fmt::Show for Json {
1742
    /// Encodes a json value into a string
1743 1744
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        self.to_writer(f.buf)
1745
    }
1746 1747
}

1748 1749
#[cfg(test)]
mod tests {
A
Alex Crichton 已提交
1750 1751
    use {Encodable, Decodable};
    use super::{Encoder, Decoder, Error, Boolean, Number, List, String, Null,
S
Sean McArthur 已提交
1752 1753
                PrettyEncoder, Object, Json, from_str, ParseError, ExpectedError,
                MissingFieldError, UnknownVariantError, DecodeResult };
A
Alex Crichton 已提交
1754
    use std::io;
1755
    use collections::TreeMap;
1756

1757
    #[deriving(Eq, Encodable, Decodable, Show)]
1758 1759 1760 1761 1762
    enum Animal {
        Dog,
        Frog(~str, int)
    }

1763
    #[deriving(Eq, Encodable, Decodable, Show)]
1764 1765 1766 1767 1768 1769
    struct Inner {
        a: (),
        b: uint,
        c: ~[~str],
    }

1770
    #[deriving(Eq, Encodable, Decodable, Show)]
1771 1772 1773 1774
    struct Outer {
        inner: ~[Inner],
    }

1775
    fn mk_object(items: &[(~str, Json)]) -> Json {
1776
        let mut d = ~TreeMap::new();
1777

D
Daniel Micay 已提交
1778
        for item in items.iter() {
1779
            match *item {
1780
                (ref key, ref value) => { d.insert((*key).clone(), (*value).clone()); },
1781
            }
1782 1783
        };

L
Luqman Aden 已提交
1784
        Object(d)
1785 1786 1787 1788
    }

    #[test]
    fn test_write_null() {
1789 1790
        assert_eq!(Null.to_str(), ~"null");
        assert_eq!(Null.to_pretty_str(), ~"null");
1791 1792
    }

1793

1794
    #[test]
1795
    fn test_write_number() {
D
Daniel Micay 已提交
1796 1797
        assert_eq!(Number(3.0).to_str(), ~"3");
        assert_eq!(Number(3.0).to_pretty_str(), ~"3");
1798

D
Daniel Micay 已提交
1799 1800
        assert_eq!(Number(3.1).to_str(), ~"3.1");
        assert_eq!(Number(3.1).to_pretty_str(), ~"3.1");
1801

D
Daniel Micay 已提交
1802 1803
        assert_eq!(Number(-1.5).to_str(), ~"-1.5");
        assert_eq!(Number(-1.5).to_pretty_str(), ~"-1.5");
1804

D
Daniel Micay 已提交
1805 1806
        assert_eq!(Number(0.5).to_str(), ~"0.5");
        assert_eq!(Number(0.5).to_pretty_str(), ~"0.5");
1807 1808 1809 1810
    }

    #[test]
    fn test_write_str() {
1811 1812
        assert_eq!(String(~"").to_str(), ~"\"\"");
        assert_eq!(String(~"").to_pretty_str(), ~"\"\"");
1813

1814 1815
        assert_eq!(String(~"foo").to_str(), ~"\"foo\"");
        assert_eq!(String(~"foo").to_pretty_str(), ~"\"foo\"");
1816 1817 1818 1819
    }

    #[test]
    fn test_write_bool() {
1820 1821
        assert_eq!(Boolean(true).to_str(), ~"true");
        assert_eq!(Boolean(true).to_pretty_str(), ~"true");
1822

1823 1824
        assert_eq!(Boolean(false).to_str(), ~"false");
        assert_eq!(Boolean(false).to_pretty_str(), ~"false");
1825 1826 1827 1828
    }

    #[test]
    fn test_write_list() {
1829 1830
        assert_eq!(List(~[]).to_str(), ~"[]");
        assert_eq!(List(~[]).to_pretty_str(), ~"[]");
1831

1832
        assert_eq!(List(~[Boolean(true)]).to_str(), ~"[true]");
1833
        assert_eq!(
1834
            List(~[Boolean(true)]).to_pretty_str(),
1835 1836 1837 1838 1839
            ~"\
            [\n  \
                true\n\
            ]"
        );
1840

1841
        let long_test_list = List(~[
1842 1843
            Boolean(false),
            Null,
D
Daniel Micay 已提交
1844
            List(~[String(~"foo\nbar"), Number(3.5)])]);
1845

1846
        assert_eq!(long_test_list.to_str(),
1847
            ~"[false,null,[\"foo\\nbar\",3.5]]");
1848
        assert_eq!(
1849
            long_test_list.to_pretty_str(),
1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861
            ~"\
            [\n  \
                false,\n  \
                null,\n  \
                [\n    \
                    \"foo\\nbar\",\n    \
                    3.5\n  \
                ]\n\
            ]"
        );
    }

1862
    #[test]
1863
    fn test_write_object() {
1864 1865
        assert_eq!(mk_object([]).to_str(), ~"{}");
        assert_eq!(mk_object([]).to_pretty_str(), ~"{}");
1866

1867
        assert_eq!(
1868
            mk_object([(~"a", Boolean(true))]).to_str(),
1869 1870
            ~"{\"a\":true}"
        );
1871
        assert_eq!(
1872
            mk_object([(~"a", Boolean(true))]).to_pretty_str(),
1873 1874 1875 1876 1877 1878
            ~"\
            {\n  \
                \"a\": true\n\
            }"
        );

1879
        let complex_obj = mk_object([
1880
                (~"b", List(~[
E
Erick Tryzelaar 已提交
1881 1882
                    mk_object([(~"c", String(~"\x0c\r"))]),
                    mk_object([(~"d", String(~""))])
1883
                ]))
1884 1885 1886
            ]);

        assert_eq!(
1887
            complex_obj.to_str(),
1888 1889 1890 1891 1892 1893 1894 1895
            ~"{\
                \"b\":[\
                    {\"c\":\"\\f\\r\"},\
                    {\"d\":\"\"}\
                ]\
            }"
        );
        assert_eq!(
1896
            complex_obj.to_pretty_str(),
1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908
            ~"\
            {\n  \
                \"b\": [\n    \
                    {\n      \
                        \"c\": \"\\f\\r\"\n    \
                    },\n    \
                    {\n      \
                        \"d\": \"\"\n    \
                    }\n  \
                ]\n\
            }"
        );
1909

E
Erick Tryzelaar 已提交
1910
        let a = mk_object([
B
Ben Striegel 已提交
1911
            (~"a", Boolean(true)),
1912
            (~"b", List(~[
E
Erick Tryzelaar 已提交
1913 1914
                mk_object([(~"c", String(~"\x0c\r"))]),
                mk_object([(~"d", String(~""))])
1915
            ]))
G
Graydon Hoare 已提交
1916
        ]);
1917

1918 1919
        // We can't compare the strings directly because the object fields be
        // printed in a different order.
1920 1921
        assert_eq!(a.clone(), from_str(a.to_str()).unwrap());
        assert_eq!(a.clone(), from_str(a.to_pretty_str()).unwrap());
1922 1923
    }

1924
    fn with_str_writer(f: |&mut io::Writer|) -> ~str {
A
Alex Crichton 已提交
1925
        use std::io::MemWriter;
A
Alex Crichton 已提交
1926 1927
        use std::str;

1928 1929
        let mut m = MemWriter::new();
        f(&mut m as &mut io::Writer);
1930
        str::from_utf8_owned(m.unwrap()).unwrap()
A
Alex Crichton 已提交
1931 1932
    }

1933
    #[test]
1934
    fn test_write_enum() {
1935
        let animal = Dog;
1936
        assert_eq!(
1937
            with_str_writer(|wr| {
1938
                let mut encoder = Encoder::new(wr);
S
Sean McArthur 已提交
1939
                animal.encode(&mut encoder).unwrap();
1940
            }),
1941 1942 1943
            ~"\"Dog\""
        );
        assert_eq!(
1944
            with_str_writer(|wr| {
1945
                let mut encoder = PrettyEncoder::new(wr);
S
Sean McArthur 已提交
1946
                animal.encode(&mut encoder).unwrap();
1947
            }),
1948 1949
            ~"\"Dog\""
        );
1950 1951 1952

        let animal = Frog(~"Henry", 349);
        assert_eq!(
1953
            with_str_writer(|wr| {
1954
                let mut encoder = Encoder::new(wr);
S
Sean McArthur 已提交
1955
                animal.encode(&mut encoder).unwrap();
1956
            }),
1957
            ~"{\"variant\":\"Frog\",\"fields\":[\"Henry\",349]}"
1958 1959
        );
        assert_eq!(
1960
            with_str_writer(|wr| {
1961
                let mut encoder = PrettyEncoder::new(wr);
S
Sean McArthur 已提交
1962
                animal.encode(&mut encoder).unwrap();
1963
            }),
1964 1965 1966
            ~"\
            [\n  \
                \"Frog\",\n  \
1967 1968
                \"Henry\",\n  \
                349\n\
1969 1970
            ]"
        );
1971 1972 1973
    }

    #[test]
1974 1975
    fn test_write_some() {
        let value = Some(~"jodhpurs");
1976
        let s = with_str_writer(|wr| {
1977
            let mut encoder = Encoder::new(wr);
S
Sean McArthur 已提交
1978
            value.encode(&mut encoder).unwrap();
1979
        });
1980
        assert_eq!(s, ~"\"jodhpurs\"");
1981

1982
        let value = Some(~"jodhpurs");
1983
        let s = with_str_writer(|wr| {
1984
            let mut encoder = PrettyEncoder::new(wr);
S
Sean McArthur 已提交
1985
            value.encode(&mut encoder).unwrap();
1986
        });
1987 1988 1989
        assert_eq!(s, ~"\"jodhpurs\"");
    }

1990
    #[test]
1991 1992
    fn test_write_none() {
        let value: Option<~str> = None;
1993
        let s = with_str_writer(|wr| {
1994
            let mut encoder = Encoder::new(wr);
S
Sean McArthur 已提交
1995
            value.encode(&mut encoder).unwrap();
1996
        });
1997
        assert_eq!(s, ~"null");
J
John Clements 已提交
1998

1999
        let s = with_str_writer(|wr| {
2000
            let mut encoder = Encoder::new(wr);
S
Sean McArthur 已提交
2001
            value.encode(&mut encoder).unwrap();
2002
        });
2003 2004 2005
        assert_eq!(s, ~"null");
    }

2006
    #[test]
2007
    fn test_trailing_characters() {
E
Erick Tryzelaar 已提交
2008
        assert_eq!(from_str("nulla"),
S
Sean McArthur 已提交
2009
            Err(ParseError(~"trailing characters", 1u, 5u)));
E
Erick Tryzelaar 已提交
2010
        assert_eq!(from_str("truea"),
S
Sean McArthur 已提交
2011
            Err(ParseError(~"trailing characters", 1u, 5u)));
E
Erick Tryzelaar 已提交
2012
        assert_eq!(from_str("falsea"),
S
Sean McArthur 已提交
2013
            Err(ParseError(~"trailing characters", 1u, 6u)));
E
Erick Tryzelaar 已提交
2014
        assert_eq!(from_str("1a"),
S
Sean McArthur 已提交
2015
            Err(ParseError(~"trailing characters", 1u, 2u)));
E
Erick Tryzelaar 已提交
2016
        assert_eq!(from_str("[]a"),
S
Sean McArthur 已提交
2017
            Err(ParseError(~"trailing characters", 1u, 3u)));
E
Erick Tryzelaar 已提交
2018
        assert_eq!(from_str("{}a"),
S
Sean McArthur 已提交
2019
            Err(ParseError(~"trailing characters", 1u, 3u)));
2020 2021 2022 2023
    }

    #[test]
    fn test_read_identifiers() {
E
Erick Tryzelaar 已提交
2024
        assert_eq!(from_str("n"),
S
Sean McArthur 已提交
2025
            Err(ParseError(~"invalid syntax", 1u, 2u)));
E
Erick Tryzelaar 已提交
2026
        assert_eq!(from_str("nul"),
S
Sean McArthur 已提交
2027
            Err(ParseError(~"invalid syntax", 1u, 4u)));
2028

E
Erick Tryzelaar 已提交
2029
        assert_eq!(from_str("t"),
S
Sean McArthur 已提交
2030
            Err(ParseError(~"invalid syntax", 1u, 2u)));
E
Erick Tryzelaar 已提交
2031
        assert_eq!(from_str("truz"),
S
Sean McArthur 已提交
2032
            Err(ParseError(~"invalid syntax", 1u, 4u)));
2033

E
Erick Tryzelaar 已提交
2034
        assert_eq!(from_str("f"),
S
Sean McArthur 已提交
2035
            Err(ParseError(~"invalid syntax", 1u, 2u)));
E
Erick Tryzelaar 已提交
2036
        assert_eq!(from_str("faz"),
S
Sean McArthur 已提交
2037
            Err(ParseError(~"invalid syntax", 1u, 3u)));
2038

E
Erick Tryzelaar 已提交
2039 2040 2041 2042 2043 2044
        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)));
2045 2046
    }

2047 2048
    #[test]
    fn test_decode_identifiers() {
2049
        let mut decoder = Decoder::new(from_str("null").unwrap());
S
Sean McArthur 已提交
2050
        let v: () = Decodable::decode(&mut decoder).unwrap();
2051 2052
        assert_eq!(v, ());

2053
        let mut decoder = Decoder::new(from_str("true").unwrap());
S
Sean McArthur 已提交
2054
        let v: bool = Decodable::decode(&mut decoder).unwrap();
2055 2056
        assert_eq!(v, true);

2057
        let mut decoder = Decoder::new(from_str("false").unwrap());
S
Sean McArthur 已提交
2058
        let v: bool = Decodable::decode(&mut decoder).unwrap();
2059 2060 2061
        assert_eq!(v, false);
    }

2062
    #[test]
2063
    fn test_read_number() {
E
Erick Tryzelaar 已提交
2064
        assert_eq!(from_str("+"),
S
Sean McArthur 已提交
2065
            Err(ParseError(~"invalid syntax", 1u, 1u)));
E
Erick Tryzelaar 已提交
2066
        assert_eq!(from_str("."),
S
Sean McArthur 已提交
2067
            Err(ParseError(~"invalid syntax", 1u, 1u)));
2068

E
Erick Tryzelaar 已提交
2069
        assert_eq!(from_str("-"),
S
Sean McArthur 已提交
2070
            Err(ParseError(~"invalid number", 1u, 2u)));
E
Erick Tryzelaar 已提交
2071
        assert_eq!(from_str("00"),
S
Sean McArthur 已提交
2072
            Err(ParseError(~"invalid number", 1u, 2u)));
E
Erick Tryzelaar 已提交
2073
        assert_eq!(from_str("1."),
S
Sean McArthur 已提交
2074
            Err(ParseError(~"invalid number", 1u, 3u)));
E
Erick Tryzelaar 已提交
2075
        assert_eq!(from_str("1e"),
S
Sean McArthur 已提交
2076
            Err(ParseError(~"invalid number", 1u, 3u)));
E
Erick Tryzelaar 已提交
2077
        assert_eq!(from_str("1e+"),
S
Sean McArthur 已提交
2078
            Err(ParseError(~"invalid number", 1u, 4u)));
2079

D
Daniel Micay 已提交
2080 2081 2082 2083 2084 2085 2086 2087
        assert_eq!(from_str("3"), Ok(Number(3.0)));
        assert_eq!(from_str("3.1"), Ok(Number(3.1)));
        assert_eq!(from_str("-1.2"), Ok(Number(-1.2)));
        assert_eq!(from_str("0.4"), Ok(Number(0.4)));
        assert_eq!(from_str("0.4e5"), Ok(Number(0.4e5)));
        assert_eq!(from_str("0.4e+15"), Ok(Number(0.4e15)));
        assert_eq!(from_str("0.4e-01"), Ok(Number(0.4e-01)));
        assert_eq!(from_str(" 3 "), Ok(Number(3.0)));
2088 2089
    }

2090 2091
    #[test]
    fn test_decode_numbers() {
2092
        let mut decoder = Decoder::new(from_str("3").unwrap());
S
Sean McArthur 已提交
2093
        let v: f64 = Decodable::decode(&mut decoder).unwrap();
D
Daniel Micay 已提交
2094
        assert_eq!(v, 3.0);
2095

2096
        let mut decoder = Decoder::new(from_str("3.1").unwrap());
S
Sean McArthur 已提交
2097
        let v: f64 = Decodable::decode(&mut decoder).unwrap();
D
Daniel Micay 已提交
2098
        assert_eq!(v, 3.1);
2099

2100
        let mut decoder = Decoder::new(from_str("-1.2").unwrap());
S
Sean McArthur 已提交
2101
        let v: f64 = Decodable::decode(&mut decoder).unwrap();
D
Daniel Micay 已提交
2102
        assert_eq!(v, -1.2);
2103

2104
        let mut decoder = Decoder::new(from_str("0.4").unwrap());
S
Sean McArthur 已提交
2105
        let v: f64 = Decodable::decode(&mut decoder).unwrap();
D
Daniel Micay 已提交
2106
        assert_eq!(v, 0.4);
2107

2108
        let mut decoder = Decoder::new(from_str("0.4e5").unwrap());
S
Sean McArthur 已提交
2109
        let v: f64 = Decodable::decode(&mut decoder).unwrap();
D
Daniel Micay 已提交
2110
        assert_eq!(v, 0.4e5);
2111

2112
        let mut decoder = Decoder::new(from_str("0.4e15").unwrap());
S
Sean McArthur 已提交
2113
        let v: f64 = Decodable::decode(&mut decoder).unwrap();
D
Daniel Micay 已提交
2114
        assert_eq!(v, 0.4e15);
2115

2116
        let mut decoder = Decoder::new(from_str("0.4e-01").unwrap());
S
Sean McArthur 已提交
2117
        let v: f64 = Decodable::decode(&mut decoder).unwrap();
D
Daniel Micay 已提交
2118
        assert_eq!(v, 0.4e-01);
2119 2120
    }

G
Gary Linscott 已提交
2121
    #[test]
2122
    fn test_read_str() {
E
Erick Tryzelaar 已提交
2123
        assert_eq!(from_str("\""),
S
Sean McArthur 已提交
2124
            Err(ParseError(~"EOF while parsing string", 1u, 2u)));
E
Erick Tryzelaar 已提交
2125
        assert_eq!(from_str("\"lol"),
S
Sean McArthur 已提交
2126
            Err(ParseError(~"EOF while parsing string", 1u, 5u)));
2127

E
Erick Tryzelaar 已提交
2128 2129 2130 2131 2132 2133 2134 2135 2136 2137
        assert_eq!(from_str("\"\""), Ok(String(~"")));
        assert_eq!(from_str("\"foo\""), Ok(String(~"foo")));
        assert_eq!(from_str("\"\\\"\""), Ok(String(~"\"")));
        assert_eq!(from_str("\"\\b\""), Ok(String(~"\x08")));
        assert_eq!(from_str("\"\\n\""), Ok(String(~"\n")));
        assert_eq!(from_str("\"\\r\""), Ok(String(~"\r")));
        assert_eq!(from_str("\"\\t\""), Ok(String(~"\t")));
        assert_eq!(from_str(" \"foo\" "), Ok(String(~"foo")));
        assert_eq!(from_str("\"\\u12ab\""), Ok(String(~"\u12ab")));
        assert_eq!(from_str("\"\\uAB12\""), Ok(String(~"\uAB12")));
2138 2139
    }

2140
    #[test]
2141
    fn test_decode_str() {
2142
        let mut decoder = Decoder::new(from_str("\"\"").unwrap());
S
Sean McArthur 已提交
2143
        let v: ~str = Decodable::decode(&mut decoder).unwrap();
2144 2145
        assert_eq!(v, ~"");

2146
        let mut decoder = Decoder::new(from_str("\"foo\"").unwrap());
S
Sean McArthur 已提交
2147
        let v: ~str = Decodable::decode(&mut decoder).unwrap();
2148 2149
        assert_eq!(v, ~"foo");

2150
        let mut decoder = Decoder::new(from_str("\"\\\"\"").unwrap());
S
Sean McArthur 已提交
2151
        let v: ~str = Decodable::decode(&mut decoder).unwrap();
2152 2153
        assert_eq!(v, ~"\"");

2154
        let mut decoder = Decoder::new(from_str("\"\\b\"").unwrap());
S
Sean McArthur 已提交
2155
        let v: ~str = Decodable::decode(&mut decoder).unwrap();
2156 2157
        assert_eq!(v, ~"\x08");

2158
        let mut decoder = Decoder::new(from_str("\"\\n\"").unwrap());
S
Sean McArthur 已提交
2159
        let v: ~str = Decodable::decode(&mut decoder).unwrap();
2160 2161
        assert_eq!(v, ~"\n");

2162
        let mut decoder = Decoder::new(from_str("\"\\r\"").unwrap());
S
Sean McArthur 已提交
2163
        let v: ~str = Decodable::decode(&mut decoder).unwrap();
2164 2165
        assert_eq!(v, ~"\r");

2166
        let mut decoder = Decoder::new(from_str("\"\\t\"").unwrap());
S
Sean McArthur 已提交
2167
        let v: ~str = Decodable::decode(&mut decoder).unwrap();
2168 2169
        assert_eq!(v, ~"\t");

2170
        let mut decoder = Decoder::new(from_str("\"\\u12ab\"").unwrap());
S
Sean McArthur 已提交
2171
        let v: ~str = Decodable::decode(&mut decoder).unwrap();
2172 2173
        assert_eq!(v, ~"\u12ab");

2174
        let mut decoder = Decoder::new(from_str("\"\\uAB12\"").unwrap());
S
Sean McArthur 已提交
2175
        let v: ~str = Decodable::decode(&mut decoder).unwrap();
2176
        assert_eq!(v, ~"\uAB12");
2177 2178
    }

2179
    #[test]
2180
    fn test_read_list() {
E
Erick Tryzelaar 已提交
2181
        assert_eq!(from_str("["),
S
Sean McArthur 已提交
2182
            Err(ParseError(~"EOF while parsing value", 1u, 2u)));
E
Erick Tryzelaar 已提交
2183
        assert_eq!(from_str("[1"),
S
Sean McArthur 已提交
2184
            Err(ParseError(~"EOF while parsing list", 1u, 3u)));
E
Erick Tryzelaar 已提交
2185
        assert_eq!(from_str("[1,"),
S
Sean McArthur 已提交
2186
            Err(ParseError(~"EOF while parsing value", 1u, 4u)));
E
Erick Tryzelaar 已提交
2187
        assert_eq!(from_str("[1,]"),
S
Sean McArthur 已提交
2188
            Err(ParseError(~"invalid syntax", 1u, 4u)));
E
Erick Tryzelaar 已提交
2189
        assert_eq!(from_str("[6 7]"),
S
Sean McArthur 已提交
2190
            Err(ParseError(~"expected `,` or `]`", 1u, 4u)));
2191

E
Erick Tryzelaar 已提交
2192 2193 2194 2195 2196 2197
        assert_eq!(from_str("[]"), Ok(List(~[])));
        assert_eq!(from_str("[ ]"), Ok(List(~[])));
        assert_eq!(from_str("[true]"), Ok(List(~[Boolean(true)])));
        assert_eq!(from_str("[ false ]"), Ok(List(~[Boolean(false)])));
        assert_eq!(from_str("[null]"), Ok(List(~[Null])));
        assert_eq!(from_str("[3, 1]"),
D
Daniel Micay 已提交
2198
                     Ok(List(~[Number(3.0), Number(1.0)])));
E
Erick Tryzelaar 已提交
2199
        assert_eq!(from_str("\n[3, 2]\n"),
D
Daniel Micay 已提交
2200
                     Ok(List(~[Number(3.0), Number(2.0)])));
E
Erick Tryzelaar 已提交
2201
        assert_eq!(from_str("[2, [4, 1]]"),
D
Daniel Micay 已提交
2202
               Ok(List(~[Number(2.0), List(~[Number(4.0), Number(1.0)])])));
2203 2204
    }

2205 2206
    #[test]
    fn test_decode_list() {
2207
        let mut decoder = Decoder::new(from_str("[]").unwrap());
S
Sean McArthur 已提交
2208
        let v: ~[()] = Decodable::decode(&mut decoder).unwrap();
2209 2210
        assert_eq!(v, ~[]);

2211
        let mut decoder = Decoder::new(from_str("[null]").unwrap());
S
Sean McArthur 已提交
2212
        let v: ~[()] = Decodable::decode(&mut decoder).unwrap();
2213 2214
        assert_eq!(v, ~[()]);

2215
        let mut decoder = Decoder::new(from_str("[true]").unwrap());
S
Sean McArthur 已提交
2216
        let v: ~[bool] = Decodable::decode(&mut decoder).unwrap();
2217 2218
        assert_eq!(v, ~[true]);

2219
        let mut decoder = Decoder::new(from_str("[true]").unwrap());
S
Sean McArthur 已提交
2220
        let v: ~[bool] = Decodable::decode(&mut decoder).unwrap();
2221 2222
        assert_eq!(v, ~[true]);

2223
        let mut decoder = Decoder::new(from_str("[3, 1]").unwrap());
S
Sean McArthur 已提交
2224
        let v: ~[int] = Decodable::decode(&mut decoder).unwrap();
2225 2226
        assert_eq!(v, ~[3, 1]);

2227
        let mut decoder = Decoder::new(from_str("[[3], [1, 2]]").unwrap());
S
Sean McArthur 已提交
2228
        let v: ~[~[uint]] = Decodable::decode(&mut decoder).unwrap();
2229 2230 2231
        assert_eq!(v, ~[~[3], ~[1, 2]]);
    }

2232
    #[test]
2233
    fn test_read_object() {
E
Erick Tryzelaar 已提交
2234
        assert_eq!(from_str("{"),
S
Sean McArthur 已提交
2235
            Err(ParseError(~"EOF while parsing object", 1u, 2u)));
E
Erick Tryzelaar 已提交
2236
        assert_eq!(from_str("{ "),
S
Sean McArthur 已提交
2237
            Err(ParseError(~"EOF while parsing object", 1u, 3u)));
E
Erick Tryzelaar 已提交
2238
        assert_eq!(from_str("{1"),
S
Sean McArthur 已提交
2239
            Err(ParseError(~"key must be a string", 1u, 2u)));
E
Erick Tryzelaar 已提交
2240
        assert_eq!(from_str("{ \"a\""),
S
Sean McArthur 已提交
2241
            Err(ParseError(~"EOF while parsing object", 1u, 6u)));
E
Erick Tryzelaar 已提交
2242
        assert_eq!(from_str("{\"a\""),
S
Sean McArthur 已提交
2243
            Err(ParseError(~"EOF while parsing object", 1u, 5u)));
E
Erick Tryzelaar 已提交
2244
        assert_eq!(from_str("{\"a\" "),
S
Sean McArthur 已提交
2245
            Err(ParseError(~"EOF while parsing object", 1u, 6u)));
2246

E
Erick Tryzelaar 已提交
2247
        assert_eq!(from_str("{\"a\" 1"),
S
Sean McArthur 已提交
2248
            Err(ParseError(~"expected `:`", 1u, 6u)));
E
Erick Tryzelaar 已提交
2249
        assert_eq!(from_str("{\"a\":"),
S
Sean McArthur 已提交
2250
            Err(ParseError(~"EOF while parsing value", 1u, 6u)));
E
Erick Tryzelaar 已提交
2251
        assert_eq!(from_str("{\"a\":1"),
S
Sean McArthur 已提交
2252
            Err(ParseError(~"EOF while parsing object", 1u, 7u)));
E
Erick Tryzelaar 已提交
2253
        assert_eq!(from_str("{\"a\":1 1"),
S
Sean McArthur 已提交
2254
            Err(ParseError(~"expected `,` or `}`", 1u, 8u)));
E
Erick Tryzelaar 已提交
2255
        assert_eq!(from_str("{\"a\":1,"),
S
Sean McArthur 已提交
2256
            Err(ParseError(~"EOF while parsing object", 1u, 8u)));
2257

E
Erick Tryzelaar 已提交
2258 2259
        assert_eq!(from_str("{}").unwrap(), mk_object([]));
        assert_eq!(from_str("{\"a\": 3}").unwrap(),
D
Daniel Micay 已提交
2260
                  mk_object([(~"a", Number(3.0))]));
2261

E
Erick Tryzelaar 已提交
2262 2263
        assert_eq!(from_str(
                      "{ \"a\": null, \"b\" : true }").unwrap(),
E
Erick Tryzelaar 已提交
2264
                  mk_object([
B
Ben Striegel 已提交
2265
                      (~"a", Null),
2266
                      (~"b", Boolean(true))]));
E
Erick Tryzelaar 已提交
2267
        assert_eq!(from_str("\n{ \"a\": null, \"b\" : true }\n").unwrap(),
E
Erick Tryzelaar 已提交
2268
                  mk_object([
B
Ben Striegel 已提交
2269
                      (~"a", Null),
2270
                      (~"b", Boolean(true))]));
E
Erick Tryzelaar 已提交
2271 2272
        assert_eq!(from_str(
                      "{\"a\" : 1.0 ,\"b\": [ true ]}").unwrap(),
E
Erick Tryzelaar 已提交
2273
                  mk_object([
2274 2275
                      (~"a", Number(1.0)),
                      (~"b", List(~[Boolean(true)]))
2276
                  ]));
E
Erick Tryzelaar 已提交
2277
        assert_eq!(from_str(
2278
                      ~"{" +
2279 2280 2281 2282 2283 2284
                          "\"a\": 1.0, " +
                          "\"b\": [" +
                              "true," +
                              "\"foo\\nbar\", " +
                              "{ \"c\": {\"d\": null} } " +
                          "]" +
E
Erick Tryzelaar 已提交
2285
                      "}").unwrap(),
E
Erick Tryzelaar 已提交
2286
                  mk_object([
D
Daniel Micay 已提交
2287
                      (~"a", Number(1.0)),
2288
                      (~"b", List(~[
B
Ben Striegel 已提交
2289
                          Boolean(true),
2290
                          String(~"foo\nbar"),
E
Erick Tryzelaar 已提交
2291 2292
                          mk_object([
                              (~"c", mk_object([(~"d", Null)]))
2293 2294
                          ])
                      ]))
2295
                  ]));
2296 2297
    }

2298
    #[test]
2299 2300 2301 2302 2303 2304
    fn test_decode_struct() {
        let s = ~"{
            \"inner\": [
                { \"a\": null, \"b\": 2, \"c\": [\"abc\", \"xyz\"] }
            ]
        }";
2305
        let mut decoder = Decoder::new(from_str(s).unwrap());
S
Sean McArthur 已提交
2306
        let v: Outer = Decodable::decode(&mut decoder).unwrap();
2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318
        assert_eq!(
            v,
            Outer {
                inner: ~[
                    Inner { a: (), b: 2, c: ~[~"abc", ~"xyz"] }
                ]
            }
        );
    }

    #[test]
    fn test_decode_option() {
2319
        let mut decoder = Decoder::new(from_str("null").unwrap());
S
Sean McArthur 已提交
2320
        let value: Option<~str> = Decodable::decode(&mut decoder).unwrap();
2321 2322
        assert_eq!(value, None);

2323
        let mut decoder = Decoder::new(from_str("\"jodhpurs\"").unwrap());
S
Sean McArthur 已提交
2324
        let value: Option<~str> = Decodable::decode(&mut decoder).unwrap();
2325 2326 2327
        assert_eq!(value, Some(~"jodhpurs"));
    }

2328
    #[test]
2329
    fn test_decode_enum() {
2330
        let mut decoder = Decoder::new(from_str("\"Dog\"").unwrap());
S
Sean McArthur 已提交
2331
        let value: Animal = Decodable::decode(&mut decoder).unwrap();
2332 2333
        assert_eq!(value, Dog);

2334
        let s = "{\"variant\":\"Frog\",\"fields\":[\"Henry\",349]}";
2335
        let mut decoder = Decoder::new(from_str(s).unwrap());
S
Sean McArthur 已提交
2336
        let value: Animal = Decodable::decode(&mut decoder).unwrap();
2337 2338 2339
        assert_eq!(value, Frog(~"Henry", 349));
    }

2340
    #[test]
2341
    fn test_decode_map() {
2342
        let s = ~"{\"a\": \"Dog\", \"b\": {\"variant\":\"Frog\",\"fields\":[\"Henry\", 349]}}";
2343
        let mut decoder = Decoder::new(from_str(s).unwrap());
S
Sean McArthur 已提交
2344
        let mut map: TreeMap<~str, Animal> = Decodable::decode(&mut decoder).unwrap();
2345

2346 2347
        assert_eq!(map.pop(&~"a"), Some(Dog));
        assert_eq!(map.pop(&~"b"), Some(Frog(~"Henry", 349)));
2348 2349
    }

2350
    #[test]
2351
    fn test_multiline_errors() {
E
Erick Tryzelaar 已提交
2352
        assert_eq!(from_str("{\n  \"foo\":\n \"bar\""),
S
Sean McArthur 已提交
2353
            Err(ParseError(~"EOF while parsing object", 3u, 8u)));
2354
    }
2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367

    #[deriving(Decodable)]
    struct DecodeStruct {
        x: f64,
        y: bool,
        z: ~str,
        w: ~[DecodeStruct]
    }
    #[deriving(Decodable)]
    enum DecodeEnum {
        A(f64),
        B(~str)
    }
S
Sean McArthur 已提交
2368 2369 2370 2371 2372
    fn check_err<T: Decodable<Decoder, Error>>(to_parse: &'static str, expected: Error) {
        let res: DecodeResult<T> = match from_str(to_parse) {
            Err(e) => Err(e),
            Ok(json) => Decodable::decode(&mut Decoder::new(json))
        };
2373
        match res {
S
Sean McArthur 已提交
2374 2375 2376 2377
            Ok(_) => fail!("`{}` parsed & decoded ok, expecting error `{}`",
                              to_parse, expected),
            Err(ParseError(e, _, _)) => fail!("`{}` is not valid json: {}",
                                           to_parse, e),
2378
            Err(e) => {
S
Sean McArthur 已提交
2379
                assert_eq!(e, expected);
2380
            }
S
Sean McArthur 已提交
2381

2382 2383 2384 2385
        }
    }
    #[test]
    fn test_decode_errors_struct() {
S
Sean McArthur 已提交
2386
        check_err::<DecodeStruct>("[]", ExpectedError(~"Object", ~"[]"));
2387
        check_err::<DecodeStruct>("{\"x\": true, \"y\": true, \"z\": \"\", \"w\": []}",
S
Sean McArthur 已提交
2388
                                  ExpectedError(~"Number", ~"true"));
2389
        check_err::<DecodeStruct>("{\"x\": 1, \"y\": [], \"z\": \"\", \"w\": []}",
S
Sean McArthur 已提交
2390
                                  ExpectedError(~"Boolean", ~"[]"));
2391
        check_err::<DecodeStruct>("{\"x\": 1, \"y\": true, \"z\": {}, \"w\": []}",
S
Sean McArthur 已提交
2392
                                  ExpectedError(~"String", ~"{}"));
2393
        check_err::<DecodeStruct>("{\"x\": 1, \"y\": true, \"z\": \"\", \"w\": null}",
S
Sean McArthur 已提交
2394
                                  ExpectedError(~"List", ~"null"));
2395
        check_err::<DecodeStruct>("{\"x\": 1, \"y\": true, \"z\": \"\"}",
S
Sean McArthur 已提交
2396
                                  MissingFieldError(~"w"));
2397 2398 2399 2400
    }
    #[test]
    fn test_decode_errors_enum() {
        check_err::<DecodeEnum>("{}",
S
Sean McArthur 已提交
2401
                                MissingFieldError(~"variant"));
2402
        check_err::<DecodeEnum>("{\"variant\": 1}",
S
Sean McArthur 已提交
2403
                                ExpectedError(~"String", ~"1"));
2404
        check_err::<DecodeEnum>("{\"variant\": \"A\"}",
S
Sean McArthur 已提交
2405
                                MissingFieldError(~"fields"));
2406
        check_err::<DecodeEnum>("{\"variant\": \"A\", \"fields\": null}",
S
Sean McArthur 已提交
2407
                                ExpectedError(~"List", ~"null"));
2408
        check_err::<DecodeEnum>("{\"variant\": \"C\", \"fields\": []}",
S
Sean McArthur 已提交
2409
                                UnknownVariantError(~"C"));
2410
    }
2411 2412 2413 2414 2415

    #[test]
    fn test_find(){
        let json_value = from_str("{\"dog\" : \"cat\"}").unwrap();
        let found_str = json_value.find(&~"dog");
2416
        assert!(found_str.is_some() && found_str.unwrap().as_string().unwrap() == &"cat");
2417 2418 2419 2420 2421 2422
    }

    #[test]
    fn test_find_path(){
        let json_value = from_str("{\"dog\":{\"cat\": {\"mouse\" : \"cheese\"}}}").unwrap();
        let found_str = json_value.find_path(&[&~"dog", &~"cat", &~"mouse"]);
2423
        assert!(found_str.is_some() && found_str.unwrap().as_string().unwrap() == &"cheese");
2424 2425 2426 2427 2428
    }

    #[test]
    fn test_search(){
        let json_value = from_str("{\"dog\":{\"cat\": {\"mouse\" : \"cheese\"}}}").unwrap();
2429
        let found_str = json_value.search(&~"mouse").and_then(|j| j.as_string());
2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461
        assert!(found_str.is_some());
        assert!(found_str.unwrap() == &"cheese");
    }

    #[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]
    fn test_is_list(){
        let json_value = from_str("[1, 2, 3]").unwrap();
        assert!(json_value.is_list());
    }

    #[test]
    fn test_as_list(){
        let json_value = from_str("[1, 2, 3]").unwrap();
        let json_list = json_value.as_list();
        let expected_length = 3;
        assert!(json_list.is_some() && json_list.unwrap().len() == expected_length);
    }

    #[test]
2462
    fn test_is_string(){
2463
        let json_value = from_str("\"dog\"").unwrap();
2464
        assert!(json_value.is_string());
2465 2466 2467
    }

    #[test]
2468
    fn test_as_string(){
2469
        let json_value = from_str("\"dog\"").unwrap();
2470
        let json_str = json_value.as_string();
2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515
        let expected_str = &"dog";
        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]
    fn test_as_number(){
        let json_value = from_str("12").unwrap();
        let json_num = json_value.as_number();
        let expected_num = 12f64;
        assert!(json_num.is_some() && json_num.unwrap() == expected_num);
    }

    #[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);
    }
2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527

    #[test]
    fn test_encode_hashmap_with_numeric_key() {
        use std::str::from_utf8;
        use std::io::Writer;
        use std::io::MemWriter;
        use collections::HashMap;
        let mut hm: HashMap<uint, bool> = HashMap::new();
        hm.insert(1, true);
        let mut mem_buf = MemWriter::new();
        {
            let mut encoder = Encoder::new(&mut mem_buf as &mut io::Writer);
S
Sean McArthur 已提交
2528
            hm.encode(&mut encoder).unwrap();
2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547
        }
        let bytes = mem_buf.unwrap();
        let json_str = from_utf8(bytes).unwrap();
        match from_str(json_str) {
            Err(_) => fail!("Unable to parse json_str: {:?}", json_str),
            _ => {} // it parsed and we are good to go
        }
    }
    #[test]
    fn test_prettyencode_hashmap_with_numeric_key() {
        use std::str::from_utf8;
        use std::io::Writer;
        use std::io::MemWriter;
        use collections::HashMap;
        let mut hm: HashMap<uint, bool> = HashMap::new();
        hm.insert(1, true);
        let mut mem_buf = MemWriter::new();
        {
            let mut encoder = PrettyEncoder::new(&mut mem_buf as &mut io::Writer);
S
Sean McArthur 已提交
2548
            hm.encode(&mut encoder).unwrap();
2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566
        }
        let bytes = mem_buf.unwrap();
        let json_str = from_utf8(bytes).unwrap();
        match from_str(json_str) {
            Err(_) => fail!("Unable to parse json_str: {:?}", json_str),
            _ => {} // it parsed and we are good to go
        }
    }
    #[test]
    fn test_hashmap_with_numeric_key_can_handle_double_quote_delimited_key() {
        use collections::HashMap;
        use Decodable;
        let json_str = "{\"1\":true}";
        let json_obj = match from_str(json_str) {
            Err(_) => fail!("Unable to parse json_str: {:?}", json_str),
            Ok(o) => o
        };
        let mut decoder = Decoder::new(json_obj);
S
Sean McArthur 已提交
2567
        let _hm: HashMap<uint, bool> = Decodable::decode(&mut decoder).unwrap();
2568
    }
2569
}