]> git.lizzy.rs Git - rust.git/blob - src/libserialize/json.rs
41499b5ae0efed34bafe3b29191c5db904c957f0
[rust.git] / src / libserialize / json.rs
1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 // Rust JSON serialization library
12 // Copyright (c) 2011 Google Inc.
13
14 #![forbid(non_camel_case_types)]
15 #![allow(missing_docs)]
16
17 //! JSON parsing and serialization
18 //!
19 //! # What is JSON?
20 //!
21 //! JSON (JavaScript Object Notation) is a way to write data in Javascript.
22 //! Like XML, it allows to encode structured data in a text format that can be easily read by humans
23 //! Its simple syntax and native compatibility with JavaScript have made it a widely used format.
24 //!
25 //! Data types that can be encoded are JavaScript types (see the `Json` enum for more details):
26 //!
27 //! * `Boolean`: equivalent to rust's `bool`
28 //! * `Number`: equivalent to rust's `f64`
29 //! * `String`: equivalent to rust's `String`
30 //! * `Array`: equivalent to rust's `Vec<T>`, but also allowing objects of different types in the
31 //!   same array
32 //! * `Object`: equivalent to rust's `BTreeMap<String, json::Json>`
33 //! * `Null`
34 //!
35 //! An object is a series of string keys mapping to values, in `"key": value` format.
36 //! Arrays are enclosed in square brackets ([ ... ]) and objects in curly brackets ({ ... }).
37 //! A simple JSON document encoding a person, his/her age, address and phone numbers could look like
38 //!
39 //! ```ignore
40 //! {
41 //!     "FirstName": "John",
42 //!     "LastName": "Doe",
43 //!     "Age": 43,
44 //!     "Address": {
45 //!         "Street": "Downing Street 10",
46 //!         "City": "London",
47 //!         "Country": "Great Britain"
48 //!     },
49 //!     "PhoneNumbers": [
50 //!         "+44 1234567",
51 //!         "+44 2345678"
52 //!     ]
53 //! }
54 //! ```
55 //!
56 //! # Rust Type-based Encoding and Decoding
57 //!
58 //! Rust provides a mechanism for low boilerplate encoding & decoding of values to and from JSON via
59 //! the serialization API.
60 //! To be able to encode a piece of data, it must implement the `serialize::RustcEncodable` trait.
61 //! To be able to decode a piece of data, it must implement the `serialize::RustcDecodable` trait.
62 //! The Rust compiler provides an annotation to automatically generate the code for these traits:
63 //! `#[derive(RustcDecodable, RustcEncodable)]`
64 //!
65 //! The JSON API provides an enum `json::Json` and a trait `ToJson` to encode objects.
66 //! The `ToJson` trait provides a `to_json` method to convert an object into a `json::Json` value.
67 //! A `json::Json` value can be encoded as a string or buffer using the functions described above.
68 //! You can also use the `json::Encoder` object, which implements the `Encoder` trait.
69 //!
70 //! When using `ToJson` the `RustcEncodable` trait implementation is not mandatory.
71 //!
72 //! # Examples of use
73 //!
74 //! ## Using Autoserialization
75 //!
76 //! Create a struct called `TestStruct` and serialize and deserialize it to and from JSON using the
77 //! serialization API, using the derived serialization code.
78 //!
79 //! ```notrust
80 //! // FIXME(#19470): this cannot be ```rust``` because it fails orphan checking at the moment
81 //! extern crate serialize;
82 //! use serialize::json;
83 //!
84 //! // Automatically generate `Decodable` and `Encodable` trait implementations
85 //! #[derive(RustcDecodable, RustcEncodable)]
86 //! pub struct TestStruct  {
87 //!     data_int: u8,
88 //!     data_str: String,
89 //!     data_vector: Vec<u8>,
90 //! }
91 //!
92 //! fn main() {
93 //!     let object = TestStruct {
94 //!         data_int: 1,
95 //!         data_str: "homura".to_string(),
96 //!         data_vector: vec![2,3,4,5],
97 //!     };
98 //!
99 //!     // Serialize using `json::encode`
100 //!     let encoded = json::encode(&object);
101 //!
102 //!     // Deserialize using `json::decode`
103 //!     let decoded: TestStruct = json::decode(encoded.as_slice()).unwrap();
104 //! }
105 //! ```
106 //!
107 //! ## Using the `ToJson` trait
108 //!
109 //! The examples above use the `ToJson` trait to generate the JSON string, which is required
110 //! for custom mappings.
111 //!
112 //! ### Simple example of `ToJson` usage
113 //!
114 //! ```notrust
115 //! // FIXME(#19470): this cannot be ```rust``` because it fails orphan checking at the moment
116 //! extern crate serialize;
117 //! use serialize::json::{self, ToJson, Json};
118 //!
119 //! // A custom data structure
120 //! struct ComplexNum {
121 //!     a: f64,
122 //!     b: f64,
123 //! }
124 //!
125 //! // JSON value representation
126 //! impl ToJson for ComplexNum {
127 //!     fn to_json(&self) -> Json {
128 //!         Json::String(format!("{}+{}i", self.a, self.b))
129 //!     }
130 //! }
131 //!
132 //! // Only generate `RustcEncodable` trait implementation
133 //! #[derive(Encodable)]
134 //! pub struct ComplexNumRecord {
135 //!     uid: u8,
136 //!     dsc: String,
137 //!     val: Json,
138 //! }
139 //!
140 //! fn main() {
141 //!     let num = ComplexNum { a: 0.0001, b: 12.539 };
142 //!     let data: String = json::encode(&ComplexNumRecord{
143 //!         uid: 1,
144 //!         dsc: "test".to_string(),
145 //!         val: num.to_json(),
146 //!     });
147 //!     println!("data: {}", data);
148 //!     // data: {"uid":1,"dsc":"test","val":"0.0001+12.539j"};
149 //! }
150 //! ```
151 //!
152 //! ### Verbose example of `ToJson` usage
153 //!
154 //! ```notrust
155 //! // FIXME(#19470): this cannot be ```rust``` because it fails orphan checking at the moment
156 //! extern crate serialize;
157 //! use std::collections::BTreeMap;
158 //! use serialize::json::{self, Json, ToJson};
159 //!
160 //! // Only generate `Decodable` trait implementation
161 //! #[derive(Decodable)]
162 //! pub struct TestStruct {
163 //!     data_int: u8,
164 //!     data_str: String,
165 //!     data_vector: Vec<u8>,
166 //! }
167 //!
168 //! // Specify encoding method manually
169 //! impl ToJson for TestStruct {
170 //!     fn to_json(&self) -> Json {
171 //!         let mut d = BTreeMap::new();
172 //!         // All standard types implement `to_json()`, so use it
173 //!         d.insert("data_int".to_string(), self.data_int.to_json());
174 //!         d.insert("data_str".to_string(), self.data_str.to_json());
175 //!         d.insert("data_vector".to_string(), self.data_vector.to_json());
176 //!         Json::Object(d)
177 //!     }
178 //! }
179 //!
180 //! fn main() {
181 //!     // Serialize using `ToJson`
182 //!     let input_data = TestStruct {
183 //!         data_int: 1,
184 //!         data_str: "madoka".to_string(),
185 //!         data_vector: vec![2,3,4,5],
186 //!     };
187 //!     let json_obj: Json = input_data.to_json();
188 //!     let json_str: String = json_obj.to_string();
189 //!
190 //!     // Deserialize like before
191 //!     let decoded: TestStruct = json::decode(json_str.as_slice()).unwrap();
192 //! }
193 //! ```
194
195 use self::JsonEvent::*;
196 use self::ErrorCode::*;
197 use self::ParserError::*;
198 use self::DecoderError::*;
199 use self::ParserState::*;
200 use self::InternalStackElement::*;
201
202 use std;
203 use std::collections::{HashMap, BTreeMap};
204 use std::{char, f64, fmt, io, num, str};
205 use std::mem::{swap, transmute};
206 use std::num::{Float, Int};
207 use std::num::FpCategory as Fp;
208 use std::str::FromStr;
209 use std::string;
210 use std::ops::Index;
211 use unicode::str as unicode_str;
212 use unicode::str::Utf16Item;
213
214 use Encodable;
215
216 /// Represents a json value
217 #[derive(Clone, PartialEq, PartialOrd, Show)]
218 pub enum Json {
219     I64(i64),
220     U64(u64),
221     F64(f64),
222     String(string::String),
223     Boolean(bool),
224     Array(self::Array),
225     Object(self::Object),
226     Null,
227 }
228
229 pub type Array = Vec<Json>;
230 pub type Object = BTreeMap<string::String, Json>;
231
232 pub struct PrettyJson<'a> { inner: &'a Json }
233
234 pub struct AsJson<'a, T: 'a> { inner: &'a T }
235 pub struct AsPrettyJson<'a, T: 'a> { inner: &'a T, indent: Option<uint> }
236
237 /// The errors that can arise while parsing a JSON stream.
238 #[derive(Clone, Copy, PartialEq)]
239 pub enum ErrorCode {
240     InvalidSyntax,
241     InvalidNumber,
242     EOFWhileParsingObject,
243     EOFWhileParsingArray,
244     EOFWhileParsingValue,
245     EOFWhileParsingString,
246     KeyMustBeAString,
247     ExpectedColon,
248     TrailingCharacters,
249     TrailingComma,
250     InvalidEscape,
251     InvalidUnicodeCodePoint,
252     LoneLeadingSurrogateInHexEscape,
253     UnexpectedEndOfHexEscape,
254     UnrecognizedHex,
255     NotFourDigit,
256     NotUtf8,
257 }
258
259 #[derive(Clone, Copy, PartialEq, Show)]
260 pub enum ParserError {
261     /// msg, line, col
262     SyntaxError(ErrorCode, uint, uint),
263     IoError(io::IoErrorKind, &'static str),
264 }
265
266 // Builder and Parser have the same errors.
267 pub type BuilderError = ParserError;
268
269 #[derive(Clone, PartialEq, Show)]
270 pub enum DecoderError {
271     ParseError(ParserError),
272     ExpectedError(string::String, string::String),
273     MissingFieldError(string::String),
274     UnknownVariantError(string::String),
275     ApplicationError(string::String)
276 }
277
278 /// Returns a readable error string for a given error code.
279 pub fn error_str(error: ErrorCode) -> &'static str {
280     match error {
281         InvalidSyntax => "invalid syntax",
282         InvalidNumber => "invalid number",
283         EOFWhileParsingObject => "EOF While parsing object",
284         EOFWhileParsingArray => "EOF While parsing array",
285         EOFWhileParsingValue => "EOF While parsing value",
286         EOFWhileParsingString => "EOF While parsing string",
287         KeyMustBeAString => "key must be a string",
288         ExpectedColon => "expected `:`",
289         TrailingCharacters => "trailing characters",
290         TrailingComma => "trailing comma",
291         InvalidEscape => "invalid escape",
292         UnrecognizedHex => "invalid \\u{ esc}ape (unrecognized hex)",
293         NotFourDigit => "invalid \\u{ esc}ape (not four digits)",
294         NotUtf8 => "contents not utf-8",
295         InvalidUnicodeCodePoint => "invalid Unicode code point",
296         LoneLeadingSurrogateInHexEscape => "lone leading surrogate in hex escape",
297         UnexpectedEndOfHexEscape => "unexpected end of hex escape",
298     }
299 }
300
301 /// Shortcut function to decode a JSON `&str` into an object
302 pub fn decode<T: ::Decodable>(s: &str) -> DecodeResult<T> {
303     let json = match from_str(s) {
304         Ok(x) => x,
305         Err(e) => return Err(ParseError(e))
306     };
307
308     let mut decoder = Decoder::new(json);
309     ::Decodable::decode(&mut decoder)
310 }
311
312 /// Shortcut function to encode a `T` into a JSON `String`
313 pub fn encode<T: ::Encodable>(object: &T) -> string::String {
314     let mut s = String::new();
315     {
316         let mut encoder = Encoder::new(&mut s);
317         let _ = object.encode(&mut encoder);
318     }
319     s
320 }
321
322 impl fmt::Show for ErrorCode {
323     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
324         error_str(*self).fmt(f)
325     }
326 }
327
328 fn io_error_to_error(io: io::IoError) -> ParserError {
329     IoError(io.kind, io.desc)
330 }
331
332 impl std::error::Error for DecoderError {
333     fn description(&self) -> &str { "decoder error" }
334     fn detail(&self) -> Option<std::string::String> { Some(format!("{:?}", self)) }
335 }
336
337 pub type EncodeResult = fmt::Result;
338 pub type DecodeResult<T> = Result<T, DecoderError>;
339
340 fn escape_str(wr: &mut fmt::Writer, v: &str) -> fmt::Result {
341     try!(wr.write_str("\""));
342
343     let mut start = 0;
344
345     for (i, byte) in v.bytes().enumerate() {
346         let escaped = match byte {
347             b'"' => "\\\"",
348             b'\\' => "\\\\",
349             b'\x00' => "\\u0000",
350             b'\x01' => "\\u0001",
351             b'\x02' => "\\u0002",
352             b'\x03' => "\\u0003",
353             b'\x04' => "\\u0004",
354             b'\x05' => "\\u0005",
355             b'\x06' => "\\u0006",
356             b'\x07' => "\\u0007",
357             b'\x08' => "\\b",
358             b'\t' => "\\t",
359             b'\n' => "\\n",
360             b'\x0b' => "\\u000b",
361             b'\x0c' => "\\f",
362             b'\r' => "\\r",
363             b'\x0e' => "\\u000e",
364             b'\x0f' => "\\u000f",
365             b'\x10' => "\\u0010",
366             b'\x11' => "\\u0011",
367             b'\x12' => "\\u0012",
368             b'\x13' => "\\u0013",
369             b'\x14' => "\\u0014",
370             b'\x15' => "\\u0015",
371             b'\x16' => "\\u0016",
372             b'\x17' => "\\u0017",
373             b'\x18' => "\\u0018",
374             b'\x19' => "\\u0019",
375             b'\x1a' => "\\u001a",
376             b'\x1b' => "\\u001b",
377             b'\x1c' => "\\u001c",
378             b'\x1d' => "\\u001d",
379             b'\x1e' => "\\u001e",
380             b'\x1f' => "\\u001f",
381             b'\x7f' => "\\u007f",
382             _ => { continue; }
383         };
384
385         if start < i {
386             try!(wr.write_str(&v[start..i]));
387         }
388
389         try!(wr.write_str(escaped));
390
391         start = i + 1;
392     }
393
394     if start != v.len() {
395         try!(wr.write_str(&v[start..]));
396     }
397
398     wr.write_str("\"")
399 }
400
401 fn escape_char(writer: &mut fmt::Writer, v: char) -> fmt::Result {
402     let mut buf = [0; 4];
403     let n = v.encode_utf8(&mut buf).unwrap();
404     let buf = unsafe { str::from_utf8_unchecked(&buf[..n]) };
405     escape_str(writer, buf)
406 }
407
408 fn spaces(wr: &mut fmt::Writer, mut n: uint) -> fmt::Result {
409     const BUF: &'static str = "                ";
410
411     while n >= BUF.len() {
412         try!(wr.write_str(BUF));
413         n -= BUF.len();
414     }
415
416     if n > 0 {
417         wr.write_str(&BUF[..n])
418     } else {
419         Ok(())
420     }
421 }
422
423 fn fmt_number_or_null(v: f64) -> string::String {
424     match v.classify() {
425         Fp::Nan | Fp::Infinite => string::String::from_str("null"),
426         _ if v.fract() != 0f64 => f64::to_str_digits(v, 6u),
427         _ => f64::to_str_digits(v, 6u) + ".0",
428     }
429 }
430
431 /// A structure for implementing serialization to JSON.
432 pub struct Encoder<'a> {
433     writer: &'a mut (fmt::Writer+'a),
434 }
435
436 impl<'a> Encoder<'a> {
437     /// Creates a new JSON encoder whose output will be written to the writer
438     /// specified.
439     pub fn new(writer: &'a mut fmt::Writer) -> Encoder<'a> {
440         Encoder { writer: writer }
441     }
442 }
443
444 impl<'a> ::Encoder for Encoder<'a> {
445     type Error = fmt::Error;
446
447     fn emit_nil(&mut self) -> EncodeResult { write!(self.writer, "null") }
448
449     fn emit_uint(&mut self, v: uint) -> EncodeResult { write!(self.writer, "{}", v) }
450     fn emit_u64(&mut self, v: u64) -> EncodeResult { write!(self.writer, "{}", v) }
451     fn emit_u32(&mut self, v: u32) -> EncodeResult { write!(self.writer, "{}", v) }
452     fn emit_u16(&mut self, v: u16) -> EncodeResult { write!(self.writer, "{}", v) }
453     fn emit_u8(&mut self, v: u8) -> EncodeResult { write!(self.writer, "{}", v) }
454
455     fn emit_int(&mut self, v: int) -> EncodeResult { write!(self.writer, "{}", v) }
456     fn emit_i64(&mut self, v: i64) -> EncodeResult { write!(self.writer, "{}", v) }
457     fn emit_i32(&mut self, v: i32) -> EncodeResult { write!(self.writer, "{}", v) }
458     fn emit_i16(&mut self, v: i16) -> EncodeResult { write!(self.writer, "{}", v) }
459     fn emit_i8(&mut self, v: i8) -> EncodeResult { write!(self.writer, "{}", v) }
460
461     fn emit_bool(&mut self, v: bool) -> EncodeResult {
462         if v {
463             write!(self.writer, "true")
464         } else {
465             write!(self.writer, "false")
466         }
467     }
468
469     fn emit_f64(&mut self, v: f64) -> EncodeResult {
470         write!(self.writer, "{}", fmt_number_or_null(v))
471     }
472     fn emit_f32(&mut self, v: f32) -> EncodeResult {
473         self.emit_f64(v as f64)
474     }
475
476     fn emit_char(&mut self, v: char) -> EncodeResult {
477         escape_char(self.writer, v)
478     }
479     fn emit_str(&mut self, v: &str) -> EncodeResult {
480         escape_str(self.writer, v)
481     }
482
483     fn emit_enum<F>(&mut self, _name: &str, f: F) -> EncodeResult where
484         F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
485     {
486         f(self)
487     }
488
489     fn emit_enum_variant<F>(&mut self,
490                             name: &str,
491                             _id: uint,
492                             cnt: uint,
493                             f: F) -> EncodeResult where
494         F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
495     {
496         // enums are encoded as strings or objects
497         // Bunny => "Bunny"
498         // Kangaroo(34,"William") => {"variant": "Kangaroo", "fields": [34,"William"]}
499         if cnt == 0 {
500             escape_str(self.writer, name)
501         } else {
502             try!(write!(self.writer, "{{\"variant\":"));
503             try!(escape_str(self.writer, name));
504             try!(write!(self.writer, ",\"fields\":["));
505             try!(f(self));
506             write!(self.writer, "]}}")
507         }
508     }
509
510     fn emit_enum_variant_arg<F>(&mut self, idx: uint, f: F) -> EncodeResult where
511         F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
512     {
513         if idx != 0 {
514             try!(write!(self.writer, ","));
515         }
516         f(self)
517     }
518
519     fn emit_enum_struct_variant<F>(&mut self,
520                                    name: &str,
521                                    id: uint,
522                                    cnt: uint,
523                                    f: F) -> EncodeResult where
524         F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
525     {
526         self.emit_enum_variant(name, id, cnt, f)
527     }
528
529     fn emit_enum_struct_variant_field<F>(&mut self,
530                                          _: &str,
531                                          idx: uint,
532                                          f: F) -> EncodeResult where
533         F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
534     {
535         self.emit_enum_variant_arg(idx, f)
536     }
537
538     fn emit_struct<F>(&mut self, _: &str, _: uint, f: F) -> EncodeResult where
539         F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
540     {
541         try!(write!(self.writer, "{{"));
542         try!(f(self));
543         write!(self.writer, "}}")
544     }
545
546     fn emit_struct_field<F>(&mut self, name: &str, idx: uint, f: F) -> EncodeResult where
547         F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
548     {
549         if idx != 0 { try!(write!(self.writer, ",")); }
550         try!(escape_str(self.writer, name));
551         try!(write!(self.writer, ":"));
552         f(self)
553     }
554
555     fn emit_tuple<F>(&mut self, len: uint, f: F) -> EncodeResult where
556         F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
557     {
558         self.emit_seq(len, f)
559     }
560     fn emit_tuple_arg<F>(&mut self, idx: uint, f: F) -> EncodeResult where
561         F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
562     {
563         self.emit_seq_elt(idx, f)
564     }
565
566     fn emit_tuple_struct<F>(&mut self, _name: &str, len: uint, f: F) -> EncodeResult where
567         F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
568     {
569         self.emit_seq(len, f)
570     }
571     fn emit_tuple_struct_arg<F>(&mut self, idx: uint, f: F) -> EncodeResult where
572         F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
573     {
574         self.emit_seq_elt(idx, f)
575     }
576
577     fn emit_option<F>(&mut self, f: F) -> EncodeResult where
578         F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
579     {
580         f(self)
581     }
582     fn emit_option_none(&mut self) -> EncodeResult { self.emit_nil() }
583     fn emit_option_some<F>(&mut self, f: F) -> EncodeResult where
584         F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
585     {
586         f(self)
587     }
588
589     fn emit_seq<F>(&mut self, _len: uint, f: F) -> EncodeResult where
590         F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
591     {
592         try!(write!(self.writer, "["));
593         try!(f(self));
594         write!(self.writer, "]")
595     }
596
597     fn emit_seq_elt<F>(&mut self, idx: uint, f: F) -> EncodeResult where
598         F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
599     {
600         if idx != 0 {
601             try!(write!(self.writer, ","));
602         }
603         f(self)
604     }
605
606     fn emit_map<F>(&mut self, _len: uint, f: F) -> EncodeResult where
607         F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
608     {
609         try!(write!(self.writer, "{{"));
610         try!(f(self));
611         write!(self.writer, "}}")
612     }
613
614     fn emit_map_elt_key<F>(&mut self, idx: uint, mut f: F) -> EncodeResult where
615         F: FnMut(&mut Encoder<'a>) -> EncodeResult,
616     {
617         if idx != 0 { try!(write!(self.writer, ",")) }
618         // ref #12967, make sure to wrap a key in double quotes,
619         // in the event that its of a type that omits them (eg numbers)
620         let mut buf = Vec::new();
621         // FIXME(14302) remove the transmute and unsafe block.
622         unsafe {
623             let mut check_encoder = Encoder::new(&mut buf);
624             try!(f(transmute(&mut check_encoder)));
625         }
626         let out = str::from_utf8(&buf[]).unwrap();
627         let needs_wrapping = out.char_at(0) != '"' && out.char_at_reverse(out.len()) != '"';
628         if needs_wrapping { try!(write!(self.writer, "\"")); }
629         try!(f(self));
630         if needs_wrapping { try!(write!(self.writer, "\"")); }
631         Ok(())
632     }
633
634     fn emit_map_elt_val<F>(&mut self, _idx: uint, f: F) -> EncodeResult where
635         F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
636     {
637         try!(write!(self.writer, ":"));
638         f(self)
639     }
640 }
641
642 /// Another encoder for JSON, but prints out human-readable JSON instead of
643 /// compact data
644 pub struct PrettyEncoder<'a> {
645     writer: &'a mut (fmt::Writer+'a),
646     curr_indent: uint,
647     indent: uint,
648 }
649
650 impl<'a> PrettyEncoder<'a> {
651     /// Creates a new encoder whose output will be written to the specified writer
652     pub fn new(writer: &'a mut fmt::Writer) -> PrettyEncoder<'a> {
653         PrettyEncoder { writer: writer, curr_indent: 0, indent: 2, }
654     }
655
656     /// Set the number of spaces to indent for each level.
657     /// This is safe to set during encoding.
658     pub fn set_indent(&mut self, indent: uint) {
659         // self.indent very well could be 0 so we need to use checked division.
660         let level = self.curr_indent.checked_div(self.indent).unwrap_or(0);
661         self.indent = indent;
662         self.curr_indent = level * self.indent;
663     }
664 }
665
666 impl<'a> ::Encoder for PrettyEncoder<'a> {
667     type Error = fmt::Error;
668
669     fn emit_nil(&mut self) -> EncodeResult { write!(self.writer, "null") }
670
671     fn emit_uint(&mut self, v: uint) -> EncodeResult { write!(self.writer, "{}", v) }
672     fn emit_u64(&mut self, v: u64) -> EncodeResult { write!(self.writer, "{}", v) }
673     fn emit_u32(&mut self, v: u32) -> EncodeResult { write!(self.writer, "{}", v) }
674     fn emit_u16(&mut self, v: u16) -> EncodeResult { write!(self.writer, "{}", v) }
675     fn emit_u8(&mut self, v: u8) -> EncodeResult { write!(self.writer, "{}", v) }
676
677     fn emit_int(&mut self, v: int) -> EncodeResult { write!(self.writer, "{}", v) }
678     fn emit_i64(&mut self, v: i64) -> EncodeResult { write!(self.writer, "{}", v) }
679     fn emit_i32(&mut self, v: i32) -> EncodeResult { write!(self.writer, "{}", v) }
680     fn emit_i16(&mut self, v: i16) -> EncodeResult { write!(self.writer, "{}", v) }
681     fn emit_i8(&mut self, v: i8) -> EncodeResult { write!(self.writer, "{}", v) }
682
683     fn emit_bool(&mut self, v: bool) -> EncodeResult {
684         if v {
685             write!(self.writer, "true")
686         } else {
687             write!(self.writer, "false")
688         }
689     }
690
691     fn emit_f64(&mut self, v: f64) -> EncodeResult {
692         write!(self.writer, "{}", fmt_number_or_null(v))
693     }
694     fn emit_f32(&mut self, v: f32) -> EncodeResult {
695         self.emit_f64(v as f64)
696     }
697
698     fn emit_char(&mut self, v: char) -> EncodeResult {
699         escape_char(self.writer, v)
700     }
701     fn emit_str(&mut self, v: &str) -> EncodeResult {
702         escape_str(self.writer, v)
703     }
704
705     fn emit_enum<F>(&mut self, _name: &str, f: F) -> EncodeResult where
706         F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
707     {
708         f(self)
709     }
710
711     fn emit_enum_variant<F>(&mut self,
712                             name: &str,
713                             _id: uint,
714                             cnt: uint,
715                             f: F)
716                             -> EncodeResult where
717         F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
718     {
719         if cnt == 0 {
720             escape_str(self.writer, name)
721         } else {
722             try!(write!(self.writer, "{{\n"));
723             self.curr_indent += self.indent;
724             try!(spaces(self.writer, self.curr_indent));
725             try!(write!(self.writer, "\"variant\": "));
726             try!(escape_str(self.writer, name));
727             try!(write!(self.writer, ",\n"));
728             try!(spaces(self.writer, self.curr_indent));
729             try!(write!(self.writer, "\"fields\": [\n"));
730             self.curr_indent += self.indent;
731             try!(f(self));
732             self.curr_indent -= self.indent;
733             try!(write!(self.writer, "\n"));
734             try!(spaces(self.writer, self.curr_indent));
735             self.curr_indent -= self.indent;
736             try!(write!(self.writer, "]\n"));
737             try!(spaces(self.writer, self.curr_indent));
738             write!(self.writer, "}}")
739         }
740     }
741
742     fn emit_enum_variant_arg<F>(&mut self, idx: uint, f: F) -> EncodeResult where
743         F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
744     {
745         if idx != 0 {
746             try!(write!(self.writer, ",\n"));
747         }
748         try!(spaces(self.writer, self.curr_indent));
749         f(self)
750     }
751
752     fn emit_enum_struct_variant<F>(&mut self,
753                                    name: &str,
754                                    id: uint,
755                                    cnt: uint,
756                                    f: F) -> EncodeResult where
757         F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
758     {
759         self.emit_enum_variant(name, id, cnt, f)
760     }
761
762     fn emit_enum_struct_variant_field<F>(&mut self,
763                                          _: &str,
764                                          idx: uint,
765                                          f: F) -> EncodeResult where
766         F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
767     {
768         self.emit_enum_variant_arg(idx, f)
769     }
770
771
772     fn emit_struct<F>(&mut self, _: &str, len: uint, f: F) -> EncodeResult where
773         F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
774     {
775         if len == 0 {
776             write!(self.writer, "{{}}")
777         } else {
778             try!(write!(self.writer, "{{"));
779             self.curr_indent += self.indent;
780             try!(f(self));
781             self.curr_indent -= self.indent;
782             try!(write!(self.writer, "\n"));
783             try!(spaces(self.writer, self.curr_indent));
784             write!(self.writer, "}}")
785         }
786     }
787
788     fn emit_struct_field<F>(&mut self, name: &str, idx: uint, f: F) -> EncodeResult where
789         F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
790     {
791         if idx == 0 {
792             try!(write!(self.writer, "\n"));
793         } else {
794             try!(write!(self.writer, ",\n"));
795         }
796         try!(spaces(self.writer, self.curr_indent));
797         try!(escape_str(self.writer, name));
798         try!(write!(self.writer, ": "));
799         f(self)
800     }
801
802     fn emit_tuple<F>(&mut self, len: uint, f: F) -> EncodeResult where
803         F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
804     {
805         self.emit_seq(len, f)
806     }
807     fn emit_tuple_arg<F>(&mut self, idx: uint, f: F) -> EncodeResult where
808         F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
809     {
810         self.emit_seq_elt(idx, f)
811     }
812
813     fn emit_tuple_struct<F>(&mut self, _: &str, len: uint, f: F) -> EncodeResult where
814         F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
815     {
816         self.emit_seq(len, f)
817     }
818     fn emit_tuple_struct_arg<F>(&mut self, idx: uint, f: F) -> EncodeResult where
819         F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
820     {
821         self.emit_seq_elt(idx, f)
822     }
823
824     fn emit_option<F>(&mut self, f: F) -> EncodeResult where
825         F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
826     {
827         f(self)
828     }
829     fn emit_option_none(&mut self) -> EncodeResult { self.emit_nil() }
830     fn emit_option_some<F>(&mut self, f: F) -> EncodeResult where
831         F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
832     {
833         f(self)
834     }
835
836     fn emit_seq<F>(&mut self, len: uint, f: F) -> EncodeResult where
837         F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
838     {
839         if len == 0 {
840             write!(self.writer, "[]")
841         } else {
842             try!(write!(self.writer, "["));
843             self.curr_indent += self.indent;
844             try!(f(self));
845             self.curr_indent -= self.indent;
846             try!(write!(self.writer, "\n"));
847             try!(spaces(self.writer, self.curr_indent));
848             write!(self.writer, "]")
849         }
850     }
851
852     fn emit_seq_elt<F>(&mut self, idx: uint, f: F) -> EncodeResult where
853         F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
854     {
855         if idx == 0 {
856             try!(write!(self.writer, "\n"));
857         } else {
858             try!(write!(self.writer, ",\n"));
859         }
860         try!(spaces(self.writer, self.curr_indent));
861         f(self)
862     }
863
864     fn emit_map<F>(&mut self, len: uint, f: F) -> EncodeResult where
865         F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
866     {
867         if len == 0 {
868             write!(self.writer, "{{}}")
869         } else {
870             try!(write!(self.writer, "{{"));
871             self.curr_indent += self.indent;
872             try!(f(self));
873             self.curr_indent -= self.indent;
874             try!(write!(self.writer, "\n"));
875             try!(spaces(self.writer, self.curr_indent));
876             write!(self.writer, "}}")
877         }
878     }
879
880     fn emit_map_elt_key<F>(&mut self, idx: uint, mut f: F) -> EncodeResult where
881         F: FnMut(&mut PrettyEncoder<'a>) -> EncodeResult,
882     {
883         if idx == 0 {
884             try!(write!(self.writer, "\n"));
885         } else {
886             try!(write!(self.writer, ",\n"));
887         }
888         try!(spaces(self.writer, self.curr_indent));
889         // ref #12967, make sure to wrap a key in double quotes,
890         // in the event that its of a type that omits them (eg numbers)
891         let mut buf = Vec::new();
892         // FIXME(14302) remove the transmute and unsafe block.
893         unsafe {
894             let mut check_encoder = PrettyEncoder::new(&mut buf);
895             try!(f(transmute(&mut check_encoder)));
896         }
897         let out = str::from_utf8(&buf[]).unwrap();
898         let needs_wrapping = out.char_at(0) != '"' && out.char_at_reverse(out.len()) != '"';
899         if needs_wrapping { try!(write!(self.writer, "\"")); }
900         try!(f(self));
901         if needs_wrapping { try!(write!(self.writer, "\"")); }
902         Ok(())
903     }
904
905     fn emit_map_elt_val<F>(&mut self, _idx: uint, f: F) -> EncodeResult where
906         F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
907     {
908         try!(write!(self.writer, ": "));
909         f(self)
910     }
911 }
912
913 impl Encodable for Json {
914     fn encode<E: ::Encoder>(&self, e: &mut E) -> Result<(), E::Error> {
915         match *self {
916             Json::I64(v) => v.encode(e),
917             Json::U64(v) => v.encode(e),
918             Json::F64(v) => v.encode(e),
919             Json::String(ref v) => v.encode(e),
920             Json::Boolean(v) => v.encode(e),
921             Json::Array(ref v) => v.encode(e),
922             Json::Object(ref v) => v.encode(e),
923             Json::Null => e.emit_nil(),
924         }
925     }
926 }
927
928 /// Create an `AsJson` wrapper which can be used to print a value as JSON
929 /// on-the-fly via `write!`
930 pub fn as_json<T>(t: &T) -> AsJson<T> {
931     AsJson { inner: t }
932 }
933
934 /// Create an `AsPrettyJson` wrapper which can be used to print a value as JSON
935 /// on-the-fly via `write!`
936 pub fn as_pretty_json<T>(t: &T) -> AsPrettyJson<T> {
937     AsPrettyJson { inner: t, indent: None }
938 }
939
940 impl Json {
941     /// Borrow this json object as a pretty object to generate a pretty
942     /// representation for it via `Show`.
943     pub fn pretty(&self) -> PrettyJson {
944         PrettyJson { inner: self }
945     }
946
947      /// If the Json value is an Object, returns the value associated with the provided key.
948     /// Otherwise, returns None.
949     pub fn find<'a>(&'a self, key: &str) -> Option<&'a Json>{
950         match self {
951             &Json::Object(ref map) => map.get(key),
952             _ => None
953         }
954     }
955
956     /// Attempts to get a nested Json Object for each key in `keys`.
957     /// If any key is found not to exist, find_path will return None.
958     /// Otherwise, it will return the Json value associated with the final key.
959     pub fn find_path<'a>(&'a self, keys: &[&str]) -> Option<&'a Json>{
960         let mut target = self;
961         for key in keys.iter() {
962             match target.find(*key) {
963                 Some(t) => { target = t; },
964                 None => return None
965             }
966         }
967         Some(target)
968     }
969
970     /// If the Json value is an Object, performs a depth-first search until
971     /// a value associated with the provided key is found. If no value is found
972     /// or the Json value is not an Object, returns None.
973     pub fn search<'a>(&'a self, key: &str) -> Option<&'a Json> {
974         match self {
975             &Json::Object(ref map) => {
976                 match map.get(key) {
977                     Some(json_value) => Some(json_value),
978                     None => {
979                         for (_, v) in map.iter() {
980                             match v.search(key) {
981                                 x if x.is_some() => return x,
982                                 _ => ()
983                             }
984                         }
985                         None
986                     }
987                 }
988             },
989             _ => None
990         }
991     }
992
993     /// Returns true if the Json value is an Object. Returns false otherwise.
994     pub fn is_object<'a>(&'a self) -> bool {
995         self.as_object().is_some()
996     }
997
998     /// If the Json value is an Object, returns the associated BTreeMap.
999     /// Returns None otherwise.
1000     pub fn as_object<'a>(&'a self) -> Option<&'a Object> {
1001         match self {
1002             &Json::Object(ref map) => Some(map),
1003             _ => None
1004         }
1005     }
1006
1007     /// Returns true if the Json value is an Array. Returns false otherwise.
1008     pub fn is_array<'a>(&'a self) -> bool {
1009         self.as_array().is_some()
1010     }
1011
1012     /// If the Json value is an Array, returns the associated vector.
1013     /// Returns None otherwise.
1014     pub fn as_array<'a>(&'a self) -> Option<&'a Array> {
1015         match self {
1016             &Json::Array(ref array) => Some(&*array),
1017             _ => None
1018         }
1019     }
1020
1021     /// Returns true if the Json value is a String. Returns false otherwise.
1022     pub fn is_string<'a>(&'a self) -> bool {
1023         self.as_string().is_some()
1024     }
1025
1026     /// If the Json value is a String, returns the associated str.
1027     /// Returns None otherwise.
1028     pub fn as_string<'a>(&'a self) -> Option<&'a str> {
1029         match *self {
1030             Json::String(ref s) => Some(&s[]),
1031             _ => None
1032         }
1033     }
1034
1035     /// Returns true if the Json value is a Number. Returns false otherwise.
1036     pub fn is_number(&self) -> bool {
1037         match *self {
1038             Json::I64(_) | Json::U64(_) | Json::F64(_) => true,
1039             _ => false,
1040         }
1041     }
1042
1043     /// Returns true if the Json value is a i64. Returns false otherwise.
1044     pub fn is_i64(&self) -> bool {
1045         match *self {
1046             Json::I64(_) => true,
1047             _ => false,
1048         }
1049     }
1050
1051     /// Returns true if the Json value is a u64. Returns false otherwise.
1052     pub fn is_u64(&self) -> bool {
1053         match *self {
1054             Json::U64(_) => true,
1055             _ => false,
1056         }
1057     }
1058
1059     /// Returns true if the Json value is a f64. Returns false otherwise.
1060     pub fn is_f64(&self) -> bool {
1061         match *self {
1062             Json::F64(_) => true,
1063             _ => false,
1064         }
1065     }
1066
1067     /// If the Json value is a number, return or cast it to a i64.
1068     /// Returns None otherwise.
1069     pub fn as_i64(&self) -> Option<i64> {
1070         match *self {
1071             Json::I64(n) => Some(n),
1072             Json::U64(n) => num::cast(n),
1073             _ => None
1074         }
1075     }
1076
1077     /// If the Json value is a number, return or cast it to a u64.
1078     /// Returns None otherwise.
1079     pub fn as_u64(&self) -> Option<u64> {
1080         match *self {
1081             Json::I64(n) => num::cast(n),
1082             Json::U64(n) => Some(n),
1083             _ => None
1084         }
1085     }
1086
1087     /// If the Json value is a number, return or cast it to a f64.
1088     /// Returns None otherwise.
1089     pub fn as_f64(&self) -> Option<f64> {
1090         match *self {
1091             Json::I64(n) => num::cast(n),
1092             Json::U64(n) => num::cast(n),
1093             Json::F64(n) => Some(n),
1094             _ => None
1095         }
1096     }
1097
1098     /// Returns true if the Json value is a Boolean. Returns false otherwise.
1099     pub fn is_boolean(&self) -> bool {
1100         self.as_boolean().is_some()
1101     }
1102
1103     /// If the Json value is a Boolean, returns the associated bool.
1104     /// Returns None otherwise.
1105     pub fn as_boolean(&self) -> Option<bool> {
1106         match self {
1107             &Json::Boolean(b) => Some(b),
1108             _ => None
1109         }
1110     }
1111
1112     /// Returns true if the Json value is a Null. Returns false otherwise.
1113     pub fn is_null(&self) -> bool {
1114         self.as_null().is_some()
1115     }
1116
1117     /// If the Json value is a Null, returns ().
1118     /// Returns None otherwise.
1119     pub fn as_null(&self) -> Option<()> {
1120         match self {
1121             &Json::Null => Some(()),
1122             _ => None
1123         }
1124     }
1125 }
1126
1127 impl<'a> Index<&'a str>  for Json {
1128     type Output = Json;
1129
1130     fn index(&self, idx: & &str) -> &Json {
1131         self.find(*idx).unwrap()
1132     }
1133 }
1134
1135 impl Index<uint> for Json {
1136     type Output = Json;
1137
1138     fn index<'a>(&'a self, idx: &uint) -> &'a Json {
1139         match self {
1140             &Json::Array(ref v) => &v[*idx],
1141             _ => panic!("can only index Json with uint if it is an array")
1142         }
1143     }
1144 }
1145
1146 /// The output of the streaming parser.
1147 #[derive(PartialEq, Clone, Show)]
1148 pub enum JsonEvent {
1149     ObjectStart,
1150     ObjectEnd,
1151     ArrayStart,
1152     ArrayEnd,
1153     BooleanValue(bool),
1154     I64Value(i64),
1155     U64Value(u64),
1156     F64Value(f64),
1157     StringValue(string::String),
1158     NullValue,
1159     Error(ParserError),
1160 }
1161
1162 #[derive(PartialEq, Show)]
1163 enum ParserState {
1164     // Parse a value in an array, true means first element.
1165     ParseArray(bool),
1166     // Parse ',' or ']' after an element in an array.
1167     ParseArrayComma,
1168     // Parse a key:value in an object, true means first element.
1169     ParseObject(bool),
1170     // Parse ',' or ']' after an element in an object.
1171     ParseObjectComma,
1172     // Initial state.
1173     ParseStart,
1174     // Expecting the stream to end.
1175     ParseBeforeFinish,
1176     // Parsing can't continue.
1177     ParseFinished,
1178 }
1179
1180 /// A Stack represents the current position of the parser in the logical
1181 /// structure of the JSON stream.
1182 /// For example foo.bar[3].x
1183 pub struct Stack {
1184     stack: Vec<InternalStackElement>,
1185     str_buffer: Vec<u8>,
1186 }
1187
1188 /// StackElements compose a Stack.
1189 /// For example, StackElement::Key("foo"), StackElement::Key("bar"),
1190 /// StackElement::Index(3) and StackElement::Key("x") are the
1191 /// StackElements compositing the stack that represents foo.bar[3].x
1192 #[derive(PartialEq, Clone, Show)]
1193 pub enum StackElement<'l> {
1194     Index(u32),
1195     Key(&'l str),
1196 }
1197
1198 // Internally, Key elements are stored as indices in a buffer to avoid
1199 // allocating a string for every member of an object.
1200 #[derive(PartialEq, Clone, Show)]
1201 enum InternalStackElement {
1202     InternalIndex(u32),
1203     InternalKey(u16, u16), // start, size
1204 }
1205
1206 impl Stack {
1207     pub fn new() -> Stack {
1208         Stack { stack: Vec::new(), str_buffer: Vec::new() }
1209     }
1210
1211     /// Returns The number of elements in the Stack.
1212     pub fn len(&self) -> uint { self.stack.len() }
1213
1214     /// Returns true if the stack is empty.
1215     pub fn is_empty(&self) -> bool { self.stack.is_empty() }
1216
1217     /// Provides access to the StackElement at a given index.
1218     /// lower indices are at the bottom of the stack while higher indices are
1219     /// at the top.
1220     pub fn get<'l>(&'l self, idx: uint) -> StackElement<'l> {
1221         match self.stack[idx] {
1222             InternalIndex(i) => StackElement::Index(i),
1223             InternalKey(start, size) => {
1224                 StackElement::Key(str::from_utf8(
1225                     &self.str_buffer[(start as uint) .. (start as uint + size as uint)])
1226                         .unwrap())
1227             }
1228         }
1229     }
1230
1231     /// Compares this stack with an array of StackElements.
1232     pub fn is_equal_to(&self, rhs: &[StackElement]) -> bool {
1233         if self.stack.len() != rhs.len() { return false; }
1234         for i in range(0, rhs.len()) {
1235             if self.get(i) != rhs[i] { return false; }
1236         }
1237         return true;
1238     }
1239
1240     /// Returns true if the bottom-most elements of this stack are the same as
1241     /// the ones passed as parameter.
1242     pub fn starts_with(&self, rhs: &[StackElement]) -> bool {
1243         if self.stack.len() < rhs.len() { return false; }
1244         for i in range(0, rhs.len()) {
1245             if self.get(i) != rhs[i] { return false; }
1246         }
1247         return true;
1248     }
1249
1250     /// Returns true if the top-most elements of this stack are the same as
1251     /// the ones passed as parameter.
1252     pub fn ends_with(&self, rhs: &[StackElement]) -> bool {
1253         if self.stack.len() < rhs.len() { return false; }
1254         let offset = self.stack.len() - rhs.len();
1255         for i in range(0, rhs.len()) {
1256             if self.get(i + offset) != rhs[i] { return false; }
1257         }
1258         return true;
1259     }
1260
1261     /// Returns the top-most element (if any).
1262     pub fn top<'l>(&'l self) -> Option<StackElement<'l>> {
1263         return match self.stack.last() {
1264             None => None,
1265             Some(&InternalIndex(i)) => Some(StackElement::Index(i)),
1266             Some(&InternalKey(start, size)) => {
1267                 Some(StackElement::Key(str::from_utf8(
1268                     &self.str_buffer[(start as uint) .. (start+size) as uint]
1269                 ).unwrap()))
1270             }
1271         }
1272     }
1273
1274     // Used by Parser to insert StackElement::Key elements at the top of the stack.
1275     fn push_key(&mut self, key: string::String) {
1276         self.stack.push(InternalKey(self.str_buffer.len() as u16, key.len() as u16));
1277         for c in key.as_bytes().iter() {
1278             self.str_buffer.push(*c);
1279         }
1280     }
1281
1282     // Used by Parser to insert StackElement::Index elements at the top of the stack.
1283     fn push_index(&mut self, index: u32) {
1284         self.stack.push(InternalIndex(index));
1285     }
1286
1287     // Used by Parser to remove the top-most element of the stack.
1288     fn pop(&mut self) {
1289         assert!(!self.is_empty());
1290         match *self.stack.last().unwrap() {
1291             InternalKey(_, sz) => {
1292                 let new_size = self.str_buffer.len() - sz as uint;
1293                 self.str_buffer.truncate(new_size);
1294             }
1295             InternalIndex(_) => {}
1296         }
1297         self.stack.pop();
1298     }
1299
1300     // Used by Parser to test whether the top-most element is an index.
1301     fn last_is_index(&self) -> bool {
1302         if self.is_empty() { return false; }
1303         return match *self.stack.last().unwrap() {
1304             InternalIndex(_) => true,
1305             _ => false,
1306         }
1307     }
1308
1309     // Used by Parser to increment the index of the top-most element.
1310     fn bump_index(&mut self) {
1311         let len = self.stack.len();
1312         let idx = match *self.stack.last().unwrap() {
1313             InternalIndex(i) => { i + 1 }
1314             _ => { panic!(); }
1315         };
1316         self.stack[len - 1] = InternalIndex(idx);
1317     }
1318 }
1319
1320 /// A streaming JSON parser implemented as an iterator of JsonEvent, consuming
1321 /// an iterator of char.
1322 pub struct Parser<T> {
1323     rdr: T,
1324     ch: Option<char>,
1325     line: uint,
1326     col: uint,
1327     // We maintain a stack representing where we are in the logical structure
1328     // of the JSON stream.
1329     stack: Stack,
1330     // A state machine is kept to make it possible to interrupt and resume parsing.
1331     state: ParserState,
1332 }
1333
1334 impl<T: Iterator<Item=char>> Iterator for Parser<T> {
1335     type Item = JsonEvent;
1336
1337     fn next(&mut self) -> Option<JsonEvent> {
1338         if self.state == ParseFinished {
1339             return None;
1340         }
1341
1342         if self.state == ParseBeforeFinish {
1343             self.parse_whitespace();
1344             // Make sure there is no trailing characters.
1345             if self.eof() {
1346                 self.state = ParseFinished;
1347                 return None;
1348             } else {
1349                 return Some(self.error_event(TrailingCharacters));
1350             }
1351         }
1352
1353         return Some(self.parse());
1354     }
1355 }
1356
1357 impl<T: Iterator<Item=char>> Parser<T> {
1358     /// Creates the JSON parser.
1359     pub fn new(rdr: T) -> Parser<T> {
1360         let mut p = Parser {
1361             rdr: rdr,
1362             ch: Some('\x00'),
1363             line: 1,
1364             col: 0,
1365             stack: Stack::new(),
1366             state: ParseStart,
1367         };
1368         p.bump();
1369         return p;
1370     }
1371
1372     /// Provides access to the current position in the logical structure of the
1373     /// JSON stream.
1374     pub fn stack<'l>(&'l self) -> &'l Stack {
1375         return &self.stack;
1376     }
1377
1378     fn eof(&self) -> bool { self.ch.is_none() }
1379     fn ch_or_null(&self) -> char { self.ch.unwrap_or('\x00') }
1380     fn bump(&mut self) {
1381         self.ch = self.rdr.next();
1382
1383         if self.ch_is('\n') {
1384             self.line += 1u;
1385             self.col = 1u;
1386         } else {
1387             self.col += 1u;
1388         }
1389     }
1390
1391     fn next_char(&mut self) -> Option<char> {
1392         self.bump();
1393         self.ch
1394     }
1395     fn ch_is(&self, c: char) -> bool {
1396         self.ch == Some(c)
1397     }
1398
1399     fn error<U>(&self, reason: ErrorCode) -> Result<U, ParserError> {
1400         Err(SyntaxError(reason, self.line, self.col))
1401     }
1402
1403     fn parse_whitespace(&mut self) {
1404         while self.ch_is(' ') ||
1405               self.ch_is('\n') ||
1406               self.ch_is('\t') ||
1407               self.ch_is('\r') { self.bump(); }
1408     }
1409
1410     fn parse_number(&mut self) -> JsonEvent {
1411         let mut neg = false;
1412
1413         if self.ch_is('-') {
1414             self.bump();
1415             neg = true;
1416         }
1417
1418         let res = match self.parse_u64() {
1419             Ok(res) => res,
1420             Err(e) => { return Error(e); }
1421         };
1422
1423         if self.ch_is('.') || self.ch_is('e') || self.ch_is('E') {
1424             let mut res = res as f64;
1425
1426             if self.ch_is('.') {
1427                 res = match self.parse_decimal(res) {
1428                     Ok(res) => res,
1429                     Err(e) => { return Error(e); }
1430                 };
1431             }
1432
1433             if self.ch_is('e') || self.ch_is('E') {
1434                 res = match self.parse_exponent(res) {
1435                     Ok(res) => res,
1436                     Err(e) => { return Error(e); }
1437                 };
1438             }
1439
1440             if neg {
1441                 res *= -1.0;
1442             }
1443
1444             F64Value(res)
1445         } else {
1446             if neg {
1447                 let res = -(res as i64);
1448
1449                 // Make sure we didn't underflow.
1450                 if res > 0 {
1451                     Error(SyntaxError(InvalidNumber, self.line, self.col))
1452                 } else {
1453                     I64Value(res)
1454                 }
1455             } else {
1456                 U64Value(res)
1457             }
1458         }
1459     }
1460
1461     fn parse_u64(&mut self) -> Result<u64, ParserError> {
1462         let mut accum = 0;
1463         let last_accum = 0; // necessary to detect overflow.
1464
1465         match self.ch_or_null() {
1466             '0' => {
1467                 self.bump();
1468
1469                 // A leading '0' must be the only digit before the decimal point.
1470                 match self.ch_or_null() {
1471                     '0' ... '9' => return self.error(InvalidNumber),
1472                     _ => ()
1473                 }
1474             },
1475             '1' ... '9' => {
1476                 while !self.eof() {
1477                     match self.ch_or_null() {
1478                         c @ '0' ... '9' => {
1479                             accum *= 10;
1480                             accum += (c as u64) - ('0' as u64);
1481
1482                             // Detect overflow by comparing to the last value.
1483                             if accum <= last_accum { return self.error(InvalidNumber); }
1484
1485                             self.bump();
1486                         }
1487                         _ => break,
1488                     }
1489                 }
1490             }
1491             _ => return self.error(InvalidNumber),
1492         }
1493
1494         Ok(accum)
1495     }
1496
1497     fn parse_decimal(&mut self, mut res: f64) -> Result<f64, ParserError> {
1498         self.bump();
1499
1500         // Make sure a digit follows the decimal place.
1501         match self.ch_or_null() {
1502             '0' ... '9' => (),
1503              _ => return self.error(InvalidNumber)
1504         }
1505
1506         let mut dec = 1.0;
1507         while !self.eof() {
1508             match self.ch_or_null() {
1509                 c @ '0' ... '9' => {
1510                     dec /= 10.0;
1511                     res += (((c as int) - ('0' as int)) as f64) * dec;
1512                     self.bump();
1513                 }
1514                 _ => break,
1515             }
1516         }
1517
1518         Ok(res)
1519     }
1520
1521     fn parse_exponent(&mut self, mut res: f64) -> Result<f64, ParserError> {
1522         self.bump();
1523
1524         let mut exp = 0u;
1525         let mut neg_exp = false;
1526
1527         if self.ch_is('+') {
1528             self.bump();
1529         } else if self.ch_is('-') {
1530             self.bump();
1531             neg_exp = true;
1532         }
1533
1534         // Make sure a digit follows the exponent place.
1535         match self.ch_or_null() {
1536             '0' ... '9' => (),
1537             _ => return self.error(InvalidNumber)
1538         }
1539         while !self.eof() {
1540             match self.ch_or_null() {
1541                 c @ '0' ... '9' => {
1542                     exp *= 10;
1543                     exp += (c as uint) - ('0' as uint);
1544
1545                     self.bump();
1546                 }
1547                 _ => break
1548             }
1549         }
1550
1551         let exp = 10_f64.powi(exp as i32);
1552         if neg_exp {
1553             res /= exp;
1554         } else {
1555             res *= exp;
1556         }
1557
1558         Ok(res)
1559     }
1560
1561     fn decode_hex_escape(&mut self) -> Result<u16, ParserError> {
1562         let mut i = 0u;
1563         let mut n = 0u16;
1564         while i < 4 && !self.eof() {
1565             self.bump();
1566             n = match self.ch_or_null() {
1567                 c @ '0' ... '9' => n * 16 + ((c as u16) - ('0' as u16)),
1568                 'a' | 'A' => n * 16 + 10,
1569                 'b' | 'B' => n * 16 + 11,
1570                 'c' | 'C' => n * 16 + 12,
1571                 'd' | 'D' => n * 16 + 13,
1572                 'e' | 'E' => n * 16 + 14,
1573                 'f' | 'F' => n * 16 + 15,
1574                 _ => return self.error(InvalidEscape)
1575             };
1576
1577             i += 1u;
1578         }
1579
1580         // Error out if we didn't parse 4 digits.
1581         if i != 4 {
1582             return self.error(InvalidEscape);
1583         }
1584
1585         Ok(n)
1586     }
1587
1588     fn parse_str(&mut self) -> Result<string::String, ParserError> {
1589         let mut escape = false;
1590         let mut res = string::String::new();
1591
1592         loop {
1593             self.bump();
1594             if self.eof() {
1595                 return self.error(EOFWhileParsingString);
1596             }
1597
1598             if escape {
1599                 match self.ch_or_null() {
1600                     '"' => res.push('"'),
1601                     '\\' => res.push('\\'),
1602                     '/' => res.push('/'),
1603                     'b' => res.push('\x08'),
1604                     'f' => res.push('\x0c'),
1605                     'n' => res.push('\n'),
1606                     'r' => res.push('\r'),
1607                     't' => res.push('\t'),
1608                     'u' => match try!(self.decode_hex_escape()) {
1609                         0xDC00 ... 0xDFFF => {
1610                             return self.error(LoneLeadingSurrogateInHexEscape)
1611                         }
1612
1613                         // Non-BMP characters are encoded as a sequence of
1614                         // two hex escapes, representing UTF-16 surrogates.
1615                         n1 @ 0xD800 ... 0xDBFF => {
1616                             match (self.next_char(), self.next_char()) {
1617                                 (Some('\\'), Some('u')) => (),
1618                                 _ => return self.error(UnexpectedEndOfHexEscape),
1619                             }
1620
1621                             let buf = [n1, try!(self.decode_hex_escape())];
1622                             match unicode_str::utf16_items(&buf).next() {
1623                                 Some(Utf16Item::ScalarValue(c)) => res.push(c),
1624                                 _ => return self.error(LoneLeadingSurrogateInHexEscape),
1625                             }
1626                         }
1627
1628                         n => match char::from_u32(n as u32) {
1629                             Some(c) => res.push(c),
1630                             None => return self.error(InvalidUnicodeCodePoint),
1631                         },
1632                     },
1633                     _ => return self.error(InvalidEscape),
1634                 }
1635                 escape = false;
1636             } else if self.ch_is('\\') {
1637                 escape = true;
1638             } else {
1639                 match self.ch {
1640                     Some('"') => {
1641                         self.bump();
1642                         return Ok(res);
1643                     },
1644                     Some(c) => res.push(c),
1645                     None => unreachable!()
1646                 }
1647             }
1648         }
1649     }
1650
1651     // Invoked at each iteration, consumes the stream until it has enough
1652     // information to return a JsonEvent.
1653     // Manages an internal state so that parsing can be interrupted and resumed.
1654     // Also keeps track of the position in the logical structure of the json
1655     // stream int the form of a stack that can be queried by the user using the
1656     // stack() method.
1657     fn parse(&mut self) -> JsonEvent {
1658         loop {
1659             // The only paths where the loop can spin a new iteration
1660             // are in the cases ParseArrayComma and ParseObjectComma if ','
1661             // is parsed. In these cases the state is set to (respectively)
1662             // ParseArray(false) and ParseObject(false), which always return,
1663             // so there is no risk of getting stuck in an infinite loop.
1664             // All other paths return before the end of the loop's iteration.
1665             self.parse_whitespace();
1666
1667             match self.state {
1668                 ParseStart => {
1669                     return self.parse_start();
1670                 }
1671                 ParseArray(first) => {
1672                     return self.parse_array(first);
1673                 }
1674                 ParseArrayComma => {
1675                     match self.parse_array_comma_or_end() {
1676                         Some(evt) => { return evt; }
1677                         None => {}
1678                     }
1679                 }
1680                 ParseObject(first) => {
1681                     return self.parse_object(first);
1682                 }
1683                 ParseObjectComma => {
1684                     self.stack.pop();
1685                     if self.ch_is(',') {
1686                         self.state = ParseObject(false);
1687                         self.bump();
1688                     } else {
1689                         return self.parse_object_end();
1690                     }
1691                 }
1692                 _ => {
1693                     return self.error_event(InvalidSyntax);
1694                 }
1695             }
1696         }
1697     }
1698
1699     fn parse_start(&mut self) -> JsonEvent {
1700         let val = self.parse_value();
1701         self.state = match val {
1702             Error(_) => ParseFinished,
1703             ArrayStart => ParseArray(true),
1704             ObjectStart => ParseObject(true),
1705             _ => ParseBeforeFinish,
1706         };
1707         return val;
1708     }
1709
1710     fn parse_array(&mut self, first: bool) -> JsonEvent {
1711         if self.ch_is(']') {
1712             if !first {
1713                 self.error_event(InvalidSyntax)
1714             } else {
1715                 self.state = if self.stack.is_empty() {
1716                     ParseBeforeFinish
1717                 } else if self.stack.last_is_index() {
1718                     ParseArrayComma
1719                 } else {
1720                     ParseObjectComma
1721                 };
1722                 self.bump();
1723                 ArrayEnd
1724             }
1725         } else {
1726             if first {
1727                 self.stack.push_index(0);
1728             }
1729             let val = self.parse_value();
1730             self.state = match val {
1731                 Error(_) => ParseFinished,
1732                 ArrayStart => ParseArray(true),
1733                 ObjectStart => ParseObject(true),
1734                 _ => ParseArrayComma,
1735             };
1736             val
1737         }
1738     }
1739
1740     fn parse_array_comma_or_end(&mut self) -> Option<JsonEvent> {
1741         if self.ch_is(',') {
1742             self.stack.bump_index();
1743             self.state = ParseArray(false);
1744             self.bump();
1745             None
1746         } else if self.ch_is(']') {
1747             self.stack.pop();
1748             self.state = if self.stack.is_empty() {
1749                 ParseBeforeFinish
1750             } else if self.stack.last_is_index() {
1751                 ParseArrayComma
1752             } else {
1753                 ParseObjectComma
1754             };
1755             self.bump();
1756             Some(ArrayEnd)
1757         } else if self.eof() {
1758             Some(self.error_event(EOFWhileParsingArray))
1759         } else {
1760             Some(self.error_event(InvalidSyntax))
1761         }
1762     }
1763
1764     fn parse_object(&mut self, first: bool) -> JsonEvent {
1765         if self.ch_is('}') {
1766             if !first {
1767                 if self.stack.is_empty() {
1768                     return self.error_event(TrailingComma);
1769                 } else {
1770                     self.stack.pop();
1771                 }
1772             }
1773             self.state = if self.stack.is_empty() {
1774                 ParseBeforeFinish
1775             } else if self.stack.last_is_index() {
1776                 ParseArrayComma
1777             } else {
1778                 ParseObjectComma
1779             };
1780             self.bump();
1781             return ObjectEnd;
1782         }
1783         if self.eof() {
1784             return self.error_event(EOFWhileParsingObject);
1785         }
1786         if !self.ch_is('"') {
1787             return self.error_event(KeyMustBeAString);
1788         }
1789         let s = match self.parse_str() {
1790             Ok(s) => s,
1791             Err(e) => {
1792                 self.state = ParseFinished;
1793                 return Error(e);
1794             }
1795         };
1796         self.parse_whitespace();
1797         if self.eof() {
1798             return self.error_event(EOFWhileParsingObject);
1799         } else if self.ch_or_null() != ':' {
1800             return self.error_event(ExpectedColon);
1801         }
1802         self.stack.push_key(s);
1803         self.bump();
1804         self.parse_whitespace();
1805
1806         let val = self.parse_value();
1807
1808         self.state = match val {
1809             Error(_) => ParseFinished,
1810             ArrayStart => ParseArray(true),
1811             ObjectStart => ParseObject(true),
1812             _ => ParseObjectComma,
1813         };
1814         return val;
1815     }
1816
1817     fn parse_object_end(&mut self) -> JsonEvent {
1818         if self.ch_is('}') {
1819             self.state = if self.stack.is_empty() {
1820                 ParseBeforeFinish
1821             } else if self.stack.last_is_index() {
1822                 ParseArrayComma
1823             } else {
1824                 ParseObjectComma
1825             };
1826             self.bump();
1827             ObjectEnd
1828         } else if self.eof() {
1829             self.error_event(EOFWhileParsingObject)
1830         } else {
1831             self.error_event(InvalidSyntax)
1832         }
1833     }
1834
1835     fn parse_value(&mut self) -> JsonEvent {
1836         if self.eof() { return self.error_event(EOFWhileParsingValue); }
1837         match self.ch_or_null() {
1838             'n' => { self.parse_ident("ull", NullValue) }
1839             't' => { self.parse_ident("rue", BooleanValue(true)) }
1840             'f' => { self.parse_ident("alse", BooleanValue(false)) }
1841             '0' ... '9' | '-' => self.parse_number(),
1842             '"' => match self.parse_str() {
1843                 Ok(s) => StringValue(s),
1844                 Err(e) => Error(e),
1845             },
1846             '[' => {
1847                 self.bump();
1848                 ArrayStart
1849             }
1850             '{' => {
1851                 self.bump();
1852                 ObjectStart
1853             }
1854             _ => { self.error_event(InvalidSyntax) }
1855         }
1856     }
1857
1858     fn parse_ident(&mut self, ident: &str, value: JsonEvent) -> JsonEvent {
1859         if ident.chars().all(|c| Some(c) == self.next_char()) {
1860             self.bump();
1861             value
1862         } else {
1863             Error(SyntaxError(InvalidSyntax, self.line, self.col))
1864         }
1865     }
1866
1867     fn error_event(&mut self, reason: ErrorCode) -> JsonEvent {
1868         self.state = ParseFinished;
1869         Error(SyntaxError(reason, self.line, self.col))
1870     }
1871 }
1872
1873 /// A Builder consumes a json::Parser to create a generic Json structure.
1874 pub struct Builder<T> {
1875     parser: Parser<T>,
1876     token: Option<JsonEvent>,
1877 }
1878
1879 impl<T: Iterator<Item=char>> Builder<T> {
1880     /// Create a JSON Builder.
1881     pub fn new(src: T) -> Builder<T> {
1882         Builder { parser: Parser::new(src), token: None, }
1883     }
1884
1885     // Decode a Json value from a Parser.
1886     pub fn build(&mut self) -> Result<Json, BuilderError> {
1887         self.bump();
1888         let result = self.build_value();
1889         self.bump();
1890         match self.token {
1891             None => {}
1892             Some(Error(e)) => { return Err(e); }
1893             ref tok => { panic!("unexpected token {:?}", tok.clone()); }
1894         }
1895         result
1896     }
1897
1898     fn bump(&mut self) {
1899         self.token = self.parser.next();
1900     }
1901
1902     fn build_value(&mut self) -> Result<Json, BuilderError> {
1903         return match self.token {
1904             Some(NullValue) => Ok(Json::Null),
1905             Some(I64Value(n)) => Ok(Json::I64(n)),
1906             Some(U64Value(n)) => Ok(Json::U64(n)),
1907             Some(F64Value(n)) => Ok(Json::F64(n)),
1908             Some(BooleanValue(b)) => Ok(Json::Boolean(b)),
1909             Some(StringValue(ref mut s)) => {
1910                 let mut temp = string::String::new();
1911                 swap(s, &mut temp);
1912                 Ok(Json::String(temp))
1913             }
1914             Some(Error(e)) => Err(e),
1915             Some(ArrayStart) => self.build_array(),
1916             Some(ObjectStart) => self.build_object(),
1917             Some(ObjectEnd) => self.parser.error(InvalidSyntax),
1918             Some(ArrayEnd) => self.parser.error(InvalidSyntax),
1919             None => self.parser.error(EOFWhileParsingValue),
1920         }
1921     }
1922
1923     fn build_array(&mut self) -> Result<Json, BuilderError> {
1924         self.bump();
1925         let mut values = Vec::new();
1926
1927         loop {
1928             if self.token == Some(ArrayEnd) {
1929                 return Ok(Json::Array(values.into_iter().collect()));
1930             }
1931             match self.build_value() {
1932                 Ok(v) => values.push(v),
1933                 Err(e) => { return Err(e) }
1934             }
1935             self.bump();
1936         }
1937     }
1938
1939     fn build_object(&mut self) -> Result<Json, BuilderError> {
1940         self.bump();
1941
1942         let mut values = BTreeMap::new();
1943
1944         loop {
1945             match self.token {
1946                 Some(ObjectEnd) => { return Ok(Json::Object(values)); }
1947                 Some(Error(e)) => { return Err(e); }
1948                 None => { break; }
1949                 _ => {}
1950             }
1951             let key = match self.parser.stack().top() {
1952                 Some(StackElement::Key(k)) => { k.to_string() }
1953                 _ => { panic!("invalid state"); }
1954             };
1955             match self.build_value() {
1956                 Ok(value) => { values.insert(key, value); }
1957                 Err(e) => { return Err(e); }
1958             }
1959             self.bump();
1960         }
1961         return self.parser.error(EOFWhileParsingObject);
1962     }
1963 }
1964
1965 /// Decodes a json value from an `&mut io::Reader`
1966 pub fn from_reader(rdr: &mut io::Reader) -> Result<Json, BuilderError> {
1967     let contents = match rdr.read_to_end() {
1968         Ok(c)  => c,
1969         Err(e) => return Err(io_error_to_error(e))
1970     };
1971     let s = match str::from_utf8(contents.as_slice()).ok() {
1972         Some(s) => s,
1973         _       => return Err(SyntaxError(NotUtf8, 0, 0))
1974     };
1975     let mut builder = Builder::new(s.chars());
1976     builder.build()
1977 }
1978
1979 /// Decodes a json value from a string
1980 pub fn from_str(s: &str) -> Result<Json, BuilderError> {
1981     let mut builder = Builder::new(s.chars());
1982     builder.build()
1983 }
1984
1985 /// A structure to decode JSON to values in rust.
1986 pub struct Decoder {
1987     stack: Vec<Json>,
1988 }
1989
1990 impl Decoder {
1991     /// Creates a new decoder instance for decoding the specified JSON value.
1992     pub fn new(json: Json) -> Decoder {
1993         Decoder { stack: vec![json] }
1994     }
1995 }
1996
1997 impl Decoder {
1998     fn pop(&mut self) -> Json {
1999         self.stack.pop().unwrap()
2000     }
2001 }
2002
2003 macro_rules! expect {
2004     ($e:expr, Null) => ({
2005         match $e {
2006             Json::Null => Ok(()),
2007             other => Err(ExpectedError("Null".to_string(),
2008                                        format!("{}", other)))
2009         }
2010     });
2011     ($e:expr, $t:ident) => ({
2012         match $e {
2013             Json::$t(v) => Ok(v),
2014             other => {
2015                 Err(ExpectedError(stringify!($t).to_string(),
2016                                   format!("{}", other)))
2017             }
2018         }
2019     })
2020 }
2021
2022 macro_rules! read_primitive {
2023     ($name:ident, $ty:ty) => {
2024         fn $name(&mut self) -> DecodeResult<$ty> {
2025             match self.pop() {
2026                 Json::I64(f) => match num::cast(f) {
2027                     Some(f) => Ok(f),
2028                     None => Err(ExpectedError("Number".to_string(), format!("{}", f))),
2029                 },
2030                 Json::U64(f) => match num::cast(f) {
2031                     Some(f) => Ok(f),
2032                     None => Err(ExpectedError("Number".to_string(), format!("{}", f))),
2033                 },
2034                 Json::F64(f) => Err(ExpectedError("Integer".to_string(), format!("{}", f))),
2035                 // re: #12967.. a type w/ numeric keys (ie HashMap<uint, V> etc)
2036                 // is going to have a string here, as per JSON spec.
2037                 Json::String(s) => match s.parse() {
2038                     Some(f) => Ok(f),
2039                     None => Err(ExpectedError("Number".to_string(), s)),
2040                 },
2041                 value => Err(ExpectedError("Number".to_string(), format!("{}", value))),
2042             }
2043         }
2044     }
2045 }
2046
2047 impl ::Decoder for Decoder {
2048     type Error = DecoderError;
2049
2050     fn read_nil(&mut self) -> DecodeResult<()> {
2051         expect!(self.pop(), Null)
2052     }
2053
2054     read_primitive! { read_uint, uint }
2055     read_primitive! { read_u8, u8 }
2056     read_primitive! { read_u16, u16 }
2057     read_primitive! { read_u32, u32 }
2058     read_primitive! { read_u64, u64 }
2059     read_primitive! { read_int, int }
2060     read_primitive! { read_i8, i8 }
2061     read_primitive! { read_i16, i16 }
2062     read_primitive! { read_i32, i32 }
2063     read_primitive! { read_i64, i64 }
2064
2065     fn read_f32(&mut self) -> DecodeResult<f32> { self.read_f64().map(|x| x as f32) }
2066
2067     fn read_f64(&mut self) -> DecodeResult<f64> {
2068         match self.pop() {
2069             Json::I64(f) => Ok(f as f64),
2070             Json::U64(f) => Ok(f as f64),
2071             Json::F64(f) => Ok(f),
2072             Json::String(s) => {
2073                 // re: #12967.. a type w/ numeric keys (ie HashMap<uint, V> etc)
2074                 // is going to have a string here, as per JSON spec.
2075                 match s.parse() {
2076                     Some(f) => Ok(f),
2077                     None => Err(ExpectedError("Number".to_string(), s)),
2078                 }
2079             },
2080             Json::Null => Ok(f64::NAN),
2081             value => Err(ExpectedError("Number".to_string(), format!("{}", value)))
2082         }
2083     }
2084
2085     fn read_bool(&mut self) -> DecodeResult<bool> {
2086         expect!(self.pop(), Boolean)
2087     }
2088
2089     fn read_char(&mut self) -> DecodeResult<char> {
2090         let s = try!(self.read_str());
2091         {
2092             let mut it = s.chars();
2093             match (it.next(), it.next()) {
2094                 // exactly one character
2095                 (Some(c), None) => return Ok(c),
2096                 _ => ()
2097             }
2098         }
2099         Err(ExpectedError("single character string".to_string(), format!("{}", s)))
2100     }
2101
2102     fn read_str(&mut self) -> DecodeResult<string::String> {
2103         expect!(self.pop(), String)
2104     }
2105
2106     fn read_enum<T, F>(&mut self, _name: &str, f: F) -> DecodeResult<T> where
2107         F: FnOnce(&mut Decoder) -> DecodeResult<T>,
2108     {
2109         f(self)
2110     }
2111
2112     fn read_enum_variant<T, F>(&mut self, names: &[&str],
2113                                mut f: F) -> DecodeResult<T>
2114         where F: FnMut(&mut Decoder, uint) -> DecodeResult<T>,
2115     {
2116         let name = match self.pop() {
2117             Json::String(s) => s,
2118             Json::Object(mut o) => {
2119                 let n = match o.remove(&"variant".to_string()) {
2120                     Some(Json::String(s)) => s,
2121                     Some(val) => {
2122                         return Err(ExpectedError("String".to_string(), format!("{}", val)))
2123                     }
2124                     None => {
2125                         return Err(MissingFieldError("variant".to_string()))
2126                     }
2127                 };
2128                 match o.remove(&"fields".to_string()) {
2129                     Some(Json::Array(l)) => {
2130                         for field in l.into_iter().rev() {
2131                             self.stack.push(field);
2132                         }
2133                     },
2134                     Some(val) => {
2135                         return Err(ExpectedError("Array".to_string(), format!("{}", val)))
2136                     }
2137                     None => {
2138                         return Err(MissingFieldError("fields".to_string()))
2139                     }
2140                 }
2141                 n
2142             }
2143             json => {
2144                 return Err(ExpectedError("String or Object".to_string(), format!("{}", json)))
2145             }
2146         };
2147         let idx = match names.iter().position(|n| *n == &name[]) {
2148             Some(idx) => idx,
2149             None => return Err(UnknownVariantError(name))
2150         };
2151         f(self, idx)
2152     }
2153
2154     fn read_enum_variant_arg<T, F>(&mut self, _idx: uint, f: F) -> DecodeResult<T> where
2155         F: FnOnce(&mut Decoder) -> DecodeResult<T>,
2156     {
2157         f(self)
2158     }
2159
2160     fn read_enum_struct_variant<T, F>(&mut self, names: &[&str], f: F) -> DecodeResult<T> where
2161         F: FnMut(&mut Decoder, uint) -> DecodeResult<T>,
2162     {
2163         self.read_enum_variant(names, f)
2164     }
2165
2166
2167     fn read_enum_struct_variant_field<T, F>(&mut self,
2168                                          _name: &str,
2169                                          idx: uint,
2170                                          f: F)
2171                                          -> DecodeResult<T> where
2172         F: FnOnce(&mut Decoder) -> DecodeResult<T>,
2173     {
2174         self.read_enum_variant_arg(idx, f)
2175     }
2176
2177     fn read_struct<T, F>(&mut self, _name: &str, _len: uint, f: F) -> DecodeResult<T> where
2178         F: FnOnce(&mut Decoder) -> DecodeResult<T>,
2179     {
2180         let value = try!(f(self));
2181         self.pop();
2182         Ok(value)
2183     }
2184
2185     fn read_struct_field<T, F>(&mut self,
2186                                name: &str,
2187                                _idx: uint,
2188                                f: F)
2189                                -> DecodeResult<T> where
2190         F: FnOnce(&mut Decoder) -> DecodeResult<T>,
2191     {
2192         let mut obj = try!(expect!(self.pop(), Object));
2193
2194         let value = match obj.remove(&name.to_string()) {
2195             None => {
2196                 // Add a Null and try to parse it as an Option<_>
2197                 // to get None as a default value.
2198                 self.stack.push(Json::Null);
2199                 match f(self) {
2200                     Ok(x) => x,
2201                     Err(_) => return Err(MissingFieldError(name.to_string())),
2202                 }
2203             },
2204             Some(json) => {
2205                 self.stack.push(json);
2206                 try!(f(self))
2207             }
2208         };
2209         self.stack.push(Json::Object(obj));
2210         Ok(value)
2211     }
2212
2213     fn read_tuple<T, F>(&mut self, tuple_len: uint, f: F) -> DecodeResult<T> where
2214         F: FnOnce(&mut Decoder) -> DecodeResult<T>,
2215     {
2216         self.read_seq(move |d, len| {
2217             if len == tuple_len {
2218                 f(d)
2219             } else {
2220                 Err(ExpectedError(format!("Tuple{}", tuple_len), format!("Tuple{}", len)))
2221             }
2222         })
2223     }
2224
2225     fn read_tuple_arg<T, F>(&mut self, idx: uint, f: F) -> DecodeResult<T> where
2226         F: FnOnce(&mut Decoder) -> DecodeResult<T>,
2227     {
2228         self.read_seq_elt(idx, f)
2229     }
2230
2231     fn read_tuple_struct<T, F>(&mut self,
2232                                _name: &str,
2233                                len: uint,
2234                                f: F)
2235                                -> DecodeResult<T> where
2236         F: FnOnce(&mut Decoder) -> DecodeResult<T>,
2237     {
2238         self.read_tuple(len, f)
2239     }
2240
2241     fn read_tuple_struct_arg<T, F>(&mut self,
2242                                    idx: uint,
2243                                    f: F)
2244                                    -> DecodeResult<T> where
2245         F: FnOnce(&mut Decoder) -> DecodeResult<T>,
2246     {
2247         self.read_tuple_arg(idx, f)
2248     }
2249
2250     fn read_option<T, F>(&mut self, mut f: F) -> DecodeResult<T> where
2251         F: FnMut(&mut Decoder, bool) -> DecodeResult<T>,
2252     {
2253         match self.pop() {
2254             Json::Null => f(self, false),
2255             value => { self.stack.push(value); f(self, true) }
2256         }
2257     }
2258
2259     fn read_seq<T, F>(&mut self, f: F) -> DecodeResult<T> where
2260         F: FnOnce(&mut Decoder, uint) -> DecodeResult<T>,
2261     {
2262         let array = try!(expect!(self.pop(), Array));
2263         let len = array.len();
2264         for v in array.into_iter().rev() {
2265             self.stack.push(v);
2266         }
2267         f(self, len)
2268     }
2269
2270     fn read_seq_elt<T, F>(&mut self, _idx: uint, f: F) -> DecodeResult<T> where
2271         F: FnOnce(&mut Decoder) -> DecodeResult<T>,
2272     {
2273         f(self)
2274     }
2275
2276     fn read_map<T, F>(&mut self, f: F) -> DecodeResult<T> where
2277         F: FnOnce(&mut Decoder, uint) -> DecodeResult<T>,
2278     {
2279         let obj = try!(expect!(self.pop(), Object));
2280         let len = obj.len();
2281         for (key, value) in obj.into_iter() {
2282             self.stack.push(value);
2283             self.stack.push(Json::String(key));
2284         }
2285         f(self, len)
2286     }
2287
2288     fn read_map_elt_key<T, F>(&mut self, _idx: uint, f: F) -> DecodeResult<T> where
2289        F: FnOnce(&mut Decoder) -> DecodeResult<T>,
2290     {
2291         f(self)
2292     }
2293
2294     fn read_map_elt_val<T, F>(&mut self, _idx: uint, f: F) -> DecodeResult<T> where
2295        F: FnOnce(&mut Decoder) -> DecodeResult<T>,
2296     {
2297         f(self)
2298     }
2299
2300     fn error(&mut self, err: &str) -> DecoderError {
2301         ApplicationError(err.to_string())
2302     }
2303 }
2304
2305 /// A trait for converting values to JSON
2306 pub trait ToJson {
2307     /// Converts the value of `self` to an instance of JSON
2308     fn to_json(&self) -> Json;
2309 }
2310
2311 macro_rules! to_json_impl_i64 {
2312     ($($t:ty), +) => (
2313         $(impl ToJson for $t {
2314             fn to_json(&self) -> Json { Json::I64(*self as i64) }
2315         })+
2316     )
2317 }
2318
2319 to_json_impl_i64! { int, i8, i16, i32, i64 }
2320
2321 macro_rules! to_json_impl_u64 {
2322     ($($t:ty), +) => (
2323         $(impl ToJson for $t {
2324             fn to_json(&self) -> Json { Json::U64(*self as u64) }
2325         })+
2326     )
2327 }
2328
2329 to_json_impl_u64! { uint, u8, u16, u32, u64 }
2330
2331 impl ToJson for Json {
2332     fn to_json(&self) -> Json { self.clone() }
2333 }
2334
2335 impl ToJson for f32 {
2336     fn to_json(&self) -> Json { (*self as f64).to_json() }
2337 }
2338
2339 impl ToJson for f64 {
2340     fn to_json(&self) -> Json {
2341         match self.classify() {
2342             Fp::Nan | Fp::Infinite => Json::Null,
2343             _                  => Json::F64(*self)
2344         }
2345     }
2346 }
2347
2348 impl ToJson for () {
2349     fn to_json(&self) -> Json { Json::Null }
2350 }
2351
2352 impl ToJson for bool {
2353     fn to_json(&self) -> Json { Json::Boolean(*self) }
2354 }
2355
2356 impl ToJson for str {
2357     fn to_json(&self) -> Json { Json::String(self.to_string()) }
2358 }
2359
2360 impl ToJson for string::String {
2361     fn to_json(&self) -> Json { Json::String((*self).clone()) }
2362 }
2363
2364 macro_rules! tuple_impl {
2365     // use variables to indicate the arity of the tuple
2366     ($($tyvar:ident),* ) => {
2367         // the trailing commas are for the 1 tuple
2368         impl<
2369             $( $tyvar : ToJson ),*
2370             > ToJson for ( $( $tyvar ),* , ) {
2371
2372             #[inline]
2373             #[allow(non_snake_case)]
2374             fn to_json(&self) -> Json {
2375                 match *self {
2376                     ($(ref $tyvar),*,) => Json::Array(vec![$($tyvar.to_json()),*])
2377                 }
2378             }
2379         }
2380     }
2381 }
2382
2383 tuple_impl!{A}
2384 tuple_impl!{A, B}
2385 tuple_impl!{A, B, C}
2386 tuple_impl!{A, B, C, D}
2387 tuple_impl!{A, B, C, D, E}
2388 tuple_impl!{A, B, C, D, E, F}
2389 tuple_impl!{A, B, C, D, E, F, G}
2390 tuple_impl!{A, B, C, D, E, F, G, H}
2391 tuple_impl!{A, B, C, D, E, F, G, H, I}
2392 tuple_impl!{A, B, C, D, E, F, G, H, I, J}
2393 tuple_impl!{A, B, C, D, E, F, G, H, I, J, K}
2394 tuple_impl!{A, B, C, D, E, F, G, H, I, J, K, L}
2395
2396 impl<A: ToJson> ToJson for [A] {
2397     fn to_json(&self) -> Json { Json::Array(self.iter().map(|elt| elt.to_json()).collect()) }
2398 }
2399
2400 impl<A: ToJson> ToJson for Vec<A> {
2401     fn to_json(&self) -> Json { Json::Array(self.iter().map(|elt| elt.to_json()).collect()) }
2402 }
2403
2404 impl<A: ToJson> ToJson for BTreeMap<string::String, A> {
2405     fn to_json(&self) -> Json {
2406         let mut d = BTreeMap::new();
2407         for (key, value) in self.iter() {
2408             d.insert((*key).clone(), value.to_json());
2409         }
2410         Json::Object(d)
2411     }
2412 }
2413
2414 impl<A: ToJson> ToJson for HashMap<string::String, A> {
2415     fn to_json(&self) -> Json {
2416         let mut d = BTreeMap::new();
2417         for (key, value) in self.iter() {
2418             d.insert((*key).clone(), value.to_json());
2419         }
2420         Json::Object(d)
2421     }
2422 }
2423
2424 impl<A:ToJson> ToJson for Option<A> {
2425     fn to_json(&self) -> Json {
2426         match *self {
2427             None => Json::Null,
2428             Some(ref value) => value.to_json()
2429         }
2430     }
2431 }
2432
2433 struct FormatShim<'a, 'b: 'a> {
2434     inner: &'a mut fmt::Formatter<'b>,
2435 }
2436
2437 impl<'a, 'b> fmt::Writer for FormatShim<'a, 'b> {
2438     fn write_str(&mut self, s: &str) -> fmt::Result {
2439         self.inner.write_str(s)
2440     }
2441 }
2442
2443 impl fmt::String for Json {
2444     /// Encodes a json value into a string
2445     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2446         let mut shim = FormatShim { inner: f };
2447         let mut encoder = Encoder::new(&mut shim);
2448         self.encode(&mut encoder)
2449     }
2450 }
2451
2452 impl<'a> fmt::String for PrettyJson<'a> {
2453     /// Encodes a json value into a string
2454     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2455         let mut shim = FormatShim { inner: f };
2456         let mut encoder = PrettyEncoder::new(&mut shim);
2457         self.inner.encode(&mut encoder)
2458     }
2459 }
2460
2461 impl<'a, T: Encodable> fmt::String for AsJson<'a, T> {
2462     /// Encodes a json value into a string
2463     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2464         let mut shim = FormatShim { inner: f };
2465         let mut encoder = Encoder::new(&mut shim);
2466         self.inner.encode(&mut encoder)
2467     }
2468 }
2469
2470 impl<'a, T> AsPrettyJson<'a, T> {
2471     /// Set the indentation level for the emitted JSON
2472     pub fn indent(mut self, indent: uint) -> AsPrettyJson<'a, T> {
2473         self.indent = Some(indent);
2474         self
2475     }
2476 }
2477
2478 impl<'a, T: Encodable> fmt::String for AsPrettyJson<'a, T> {
2479     /// Encodes a json value into a string
2480     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2481         let mut shim = FormatShim { inner: f };
2482         let mut encoder = PrettyEncoder::new(&mut shim);
2483         match self.indent {
2484             Some(n) => encoder.set_indent(n),
2485             None => {}
2486         }
2487         self.inner.encode(&mut encoder)
2488     }
2489 }
2490
2491 impl FromStr for Json {
2492     fn from_str(s: &str) -> Option<Json> {
2493         from_str(s).ok()
2494     }
2495 }
2496
2497 #[cfg(test)]
2498 mod tests {
2499     extern crate test;
2500     use self::Animal::*;
2501     use self::DecodeEnum::*;
2502     use self::test::Bencher;
2503     use {Encodable, Decodable};
2504     use super::Json::*;
2505     use super::ErrorCode::*;
2506     use super::ParserError::*;
2507     use super::DecoderError::*;
2508     use super::JsonEvent::*;
2509     use super::{Json, from_str, DecodeResult, DecoderError, JsonEvent, Parser,
2510                 StackElement, Stack, Decoder};
2511     use std::{i64, u64, f32, f64, io};
2512     use std::collections::BTreeMap;
2513     use std::num::Float;
2514     use std::string;
2515
2516     #[derive(RustcDecodable, Eq, PartialEq, Show)]
2517     struct OptionData {
2518         opt: Option<uint>,
2519     }
2520
2521     #[test]
2522     fn test_decode_option_none() {
2523         let s ="{}";
2524         let obj: OptionData = super::decode(s).unwrap();
2525         assert_eq!(obj, OptionData { opt: None });
2526     }
2527
2528     #[test]
2529     fn test_decode_option_some() {
2530         let s = "{ \"opt\": 10 }";
2531         let obj: OptionData = super::decode(s).unwrap();
2532         assert_eq!(obj, OptionData { opt: Some(10u) });
2533     }
2534
2535     #[test]
2536     fn test_decode_option_malformed() {
2537         check_err::<OptionData>("{ \"opt\": [] }",
2538                                 ExpectedError("Number".to_string(), "[]".to_string()));
2539         check_err::<OptionData>("{ \"opt\": false }",
2540                                 ExpectedError("Number".to_string(), "false".to_string()));
2541     }
2542
2543     #[derive(PartialEq, RustcEncodable, RustcDecodable, Show)]
2544     enum Animal {
2545         Dog,
2546         Frog(string::String, int)
2547     }
2548
2549     #[derive(PartialEq, RustcEncodable, RustcDecodable, Show)]
2550     struct Inner {
2551         a: (),
2552         b: uint,
2553         c: Vec<string::String>,
2554     }
2555
2556     #[derive(PartialEq, RustcEncodable, RustcDecodable, Show)]
2557     struct Outer {
2558         inner: Vec<Inner>,
2559     }
2560
2561     fn mk_object(items: &[(string::String, Json)]) -> Json {
2562         let mut d = BTreeMap::new();
2563
2564         for item in items.iter() {
2565             match *item {
2566                 (ref key, ref value) => { d.insert((*key).clone(), (*value).clone()); },
2567             }
2568         };
2569
2570         Object(d)
2571     }
2572
2573     #[test]
2574     fn test_from_str_trait() {
2575         let s = "null";
2576         assert!(s.parse::<Json>().unwrap() == s.parse().unwrap());
2577     }
2578
2579     #[test]
2580     fn test_write_null() {
2581         assert_eq!(Null.to_string(), "null");
2582         assert_eq!(Null.pretty().to_string(), "null");
2583     }
2584
2585     #[test]
2586     fn test_write_i64() {
2587         assert_eq!(U64(0).to_string(), "0");
2588         assert_eq!(U64(0).pretty().to_string(), "0");
2589
2590         assert_eq!(U64(1234).to_string(), "1234");
2591         assert_eq!(U64(1234).pretty().to_string(), "1234");
2592
2593         assert_eq!(I64(-5678).to_string(), "-5678");
2594         assert_eq!(I64(-5678).pretty().to_string(), "-5678");
2595
2596         assert_eq!(U64(7650007200025252000).to_string(), "7650007200025252000");
2597         assert_eq!(U64(7650007200025252000).pretty().to_string(), "7650007200025252000");
2598     }
2599
2600     #[test]
2601     fn test_write_f64() {
2602         assert_eq!(F64(3.0).to_string(), "3.0");
2603         assert_eq!(F64(3.0).pretty().to_string(), "3.0");
2604
2605         assert_eq!(F64(3.1).to_string(), "3.1");
2606         assert_eq!(F64(3.1).pretty().to_string(), "3.1");
2607
2608         assert_eq!(F64(-1.5).to_string(), "-1.5");
2609         assert_eq!(F64(-1.5).pretty().to_string(), "-1.5");
2610
2611         assert_eq!(F64(0.5).to_string(), "0.5");
2612         assert_eq!(F64(0.5).pretty().to_string(), "0.5");
2613
2614         assert_eq!(F64(f64::NAN).to_string(), "null");
2615         assert_eq!(F64(f64::NAN).pretty().to_string(), "null");
2616
2617         assert_eq!(F64(f64::INFINITY).to_string(), "null");
2618         assert_eq!(F64(f64::INFINITY).pretty().to_string(), "null");
2619
2620         assert_eq!(F64(f64::NEG_INFINITY).to_string(), "null");
2621         assert_eq!(F64(f64::NEG_INFINITY).pretty().to_string(), "null");
2622     }
2623
2624     #[test]
2625     fn test_write_str() {
2626         assert_eq!(String("".to_string()).to_string(), "\"\"");
2627         assert_eq!(String("".to_string()).pretty().to_string(), "\"\"");
2628
2629         assert_eq!(String("homura".to_string()).to_string(), "\"homura\"");
2630         assert_eq!(String("madoka".to_string()).pretty().to_string(), "\"madoka\"");
2631     }
2632
2633     #[test]
2634     fn test_write_bool() {
2635         assert_eq!(Boolean(true).to_string(), "true");
2636         assert_eq!(Boolean(true).pretty().to_string(), "true");
2637
2638         assert_eq!(Boolean(false).to_string(), "false");
2639         assert_eq!(Boolean(false).pretty().to_string(), "false");
2640     }
2641
2642     #[test]
2643     fn test_write_array() {
2644         assert_eq!(Array(vec![]).to_string(), "[]");
2645         assert_eq!(Array(vec![]).pretty().to_string(), "[]");
2646
2647         assert_eq!(Array(vec![Boolean(true)]).to_string(), "[true]");
2648         assert_eq!(
2649             Array(vec![Boolean(true)]).pretty().to_string(),
2650             "\
2651             [\n  \
2652                 true\n\
2653             ]"
2654         );
2655
2656         let long_test_array = Array(vec![
2657             Boolean(false),
2658             Null,
2659             Array(vec![String("foo\nbar".to_string()), F64(3.5)])]);
2660
2661         assert_eq!(long_test_array.to_string(),
2662             "[false,null,[\"foo\\nbar\",3.5]]");
2663         assert_eq!(
2664             long_test_array.pretty().to_string(),
2665             "\
2666             [\n  \
2667                 false,\n  \
2668                 null,\n  \
2669                 [\n    \
2670                     \"foo\\nbar\",\n    \
2671                     3.5\n  \
2672                 ]\n\
2673             ]"
2674         );
2675     }
2676
2677     #[test]
2678     fn test_write_object() {
2679         assert_eq!(mk_object(&[]).to_string(), "{}");
2680         assert_eq!(mk_object(&[]).pretty().to_string(), "{}");
2681
2682         assert_eq!(
2683             mk_object(&[
2684                 ("a".to_string(), Boolean(true))
2685             ]).to_string(),
2686             "{\"a\":true}"
2687         );
2688         assert_eq!(
2689             mk_object(&[("a".to_string(), Boolean(true))]).pretty().to_string(),
2690             "\
2691             {\n  \
2692                 \"a\": true\n\
2693             }"
2694         );
2695
2696         let complex_obj = mk_object(&[
2697                 ("b".to_string(), Array(vec![
2698                     mk_object(&[("c".to_string(), String("\x0c\r".to_string()))]),
2699                     mk_object(&[("d".to_string(), String("".to_string()))])
2700                 ]))
2701             ]);
2702
2703         assert_eq!(
2704             complex_obj.to_string(),
2705             "{\
2706                 \"b\":[\
2707                     {\"c\":\"\\f\\r\"},\
2708                     {\"d\":\"\"}\
2709                 ]\
2710             }"
2711         );
2712         assert_eq!(
2713             complex_obj.pretty().to_string(),
2714             "\
2715             {\n  \
2716                 \"b\": [\n    \
2717                     {\n      \
2718                         \"c\": \"\\f\\r\"\n    \
2719                     },\n    \
2720                     {\n      \
2721                         \"d\": \"\"\n    \
2722                     }\n  \
2723                 ]\n\
2724             }"
2725         );
2726
2727         let a = mk_object(&[
2728             ("a".to_string(), Boolean(true)),
2729             ("b".to_string(), Array(vec![
2730                 mk_object(&[("c".to_string(), String("\x0c\r".to_string()))]),
2731                 mk_object(&[("d".to_string(), String("".to_string()))])
2732             ]))
2733         ]);
2734
2735         // We can't compare the strings directly because the object fields be
2736         // printed in a different order.
2737         assert_eq!(a.clone(), a.to_string().parse().unwrap());
2738         assert_eq!(a.clone(), a.pretty().to_string().parse().unwrap());
2739     }
2740
2741     #[test]
2742     fn test_write_enum() {
2743         let animal = Dog;
2744         assert_eq!(
2745             format!("{}", super::as_json(&animal)),
2746             "\"Dog\""
2747         );
2748         assert_eq!(
2749             format!("{}", super::as_pretty_json(&animal)),
2750             "\"Dog\""
2751         );
2752
2753         let animal = Frog("Henry".to_string(), 349);
2754         assert_eq!(
2755             format!("{}", super::as_json(&animal)),
2756             "{\"variant\":\"Frog\",\"fields\":[\"Henry\",349]}"
2757         );
2758         assert_eq!(
2759             format!("{}", super::as_pretty_json(&animal)),
2760             "{\n  \
2761                \"variant\": \"Frog\",\n  \
2762                \"fields\": [\n    \
2763                  \"Henry\",\n    \
2764                  349\n  \
2765                ]\n\
2766              }"
2767         );
2768     }
2769
2770     macro_rules! check_encoder_for_simple {
2771         ($value:expr, $expected:expr) => ({
2772             let s = format!("{}", super::as_json(&$value));
2773             assert_eq!(s, $expected);
2774
2775             let s = format!("{}", super::as_pretty_json(&$value));
2776             assert_eq!(s, $expected);
2777         })
2778     }
2779
2780     #[test]
2781     fn test_write_some() {
2782         check_encoder_for_simple!(Some("jodhpurs".to_string()), "\"jodhpurs\"");
2783     }
2784
2785     #[test]
2786     fn test_write_none() {
2787         check_encoder_for_simple!(None::<string::String>, "null");
2788     }
2789
2790     #[test]
2791     fn test_write_char() {
2792         check_encoder_for_simple!('a', "\"a\"");
2793         check_encoder_for_simple!('\t', "\"\\t\"");
2794         check_encoder_for_simple!('\u{0000}', "\"\\u0000\"");
2795         check_encoder_for_simple!('\u{001b}', "\"\\u001b\"");
2796         check_encoder_for_simple!('\u{007f}', "\"\\u007f\"");
2797         check_encoder_for_simple!('\u{00a0}', "\"\u{00a0}\"");
2798         check_encoder_for_simple!('\u{abcd}', "\"\u{abcd}\"");
2799         check_encoder_for_simple!('\u{10ffff}', "\"\u{10ffff}\"");
2800     }
2801
2802     #[test]
2803     fn test_trailing_characters() {
2804         assert_eq!(from_str("nulla"),  Err(SyntaxError(TrailingCharacters, 1, 5)));
2805         assert_eq!(from_str("truea"),  Err(SyntaxError(TrailingCharacters, 1, 5)));
2806         assert_eq!(from_str("falsea"), Err(SyntaxError(TrailingCharacters, 1, 6)));
2807         assert_eq!(from_str("1a"),     Err(SyntaxError(TrailingCharacters, 1, 2)));
2808         assert_eq!(from_str("[]a"),    Err(SyntaxError(TrailingCharacters, 1, 3)));
2809         assert_eq!(from_str("{}a"),    Err(SyntaxError(TrailingCharacters, 1, 3)));
2810     }
2811
2812     #[test]
2813     fn test_read_identifiers() {
2814         assert_eq!(from_str("n"),    Err(SyntaxError(InvalidSyntax, 1, 2)));
2815         assert_eq!(from_str("nul"),  Err(SyntaxError(InvalidSyntax, 1, 4)));
2816         assert_eq!(from_str("t"),    Err(SyntaxError(InvalidSyntax, 1, 2)));
2817         assert_eq!(from_str("truz"), Err(SyntaxError(InvalidSyntax, 1, 4)));
2818         assert_eq!(from_str("f"),    Err(SyntaxError(InvalidSyntax, 1, 2)));
2819         assert_eq!(from_str("faz"),  Err(SyntaxError(InvalidSyntax, 1, 3)));
2820
2821         assert_eq!(from_str("null"), Ok(Null));
2822         assert_eq!(from_str("true"), Ok(Boolean(true)));
2823         assert_eq!(from_str("false"), Ok(Boolean(false)));
2824         assert_eq!(from_str(" null "), Ok(Null));
2825         assert_eq!(from_str(" true "), Ok(Boolean(true)));
2826         assert_eq!(from_str(" false "), Ok(Boolean(false)));
2827     }
2828
2829     #[test]
2830     fn test_decode_identifiers() {
2831         let v: () = super::decode("null").unwrap();
2832         assert_eq!(v, ());
2833
2834         let v: bool = super::decode("true").unwrap();
2835         assert_eq!(v, true);
2836
2837         let v: bool = super::decode("false").unwrap();
2838         assert_eq!(v, false);
2839     }
2840
2841     #[test]
2842     fn test_read_number() {
2843         assert_eq!(from_str("+"),   Err(SyntaxError(InvalidSyntax, 1, 1)));
2844         assert_eq!(from_str("."),   Err(SyntaxError(InvalidSyntax, 1, 1)));
2845         assert_eq!(from_str("NaN"), Err(SyntaxError(InvalidSyntax, 1, 1)));
2846         assert_eq!(from_str("-"),   Err(SyntaxError(InvalidNumber, 1, 2)));
2847         assert_eq!(from_str("00"),  Err(SyntaxError(InvalidNumber, 1, 2)));
2848         assert_eq!(from_str("1."),  Err(SyntaxError(InvalidNumber, 1, 3)));
2849         assert_eq!(from_str("1e"),  Err(SyntaxError(InvalidNumber, 1, 3)));
2850         assert_eq!(from_str("1e+"), Err(SyntaxError(InvalidNumber, 1, 4)));
2851
2852         assert_eq!(from_str("18446744073709551616"), Err(SyntaxError(InvalidNumber, 1, 20)));
2853         assert_eq!(from_str("-9223372036854775809"), Err(SyntaxError(InvalidNumber, 1, 21)));
2854
2855         assert_eq!(from_str("3"), Ok(U64(3)));
2856         assert_eq!(from_str("3.1"), Ok(F64(3.1)));
2857         assert_eq!(from_str("-1.2"), Ok(F64(-1.2)));
2858         assert_eq!(from_str("0.4"), Ok(F64(0.4)));
2859         assert_eq!(from_str("0.4e5"), Ok(F64(0.4e5)));
2860         assert_eq!(from_str("0.4e+15"), Ok(F64(0.4e15)));
2861         assert_eq!(from_str("0.4e-01"), Ok(F64(0.4e-01)));
2862         assert_eq!(from_str(" 3 "), Ok(U64(3)));
2863
2864         assert_eq!(from_str("-9223372036854775808"), Ok(I64(i64::MIN)));
2865         assert_eq!(from_str("9223372036854775807"), Ok(U64(i64::MAX as u64)));
2866         assert_eq!(from_str("18446744073709551615"), Ok(U64(u64::MAX)));
2867     }
2868
2869     #[test]
2870     fn test_decode_numbers() {
2871         let v: f64 = super::decode("3").unwrap();
2872         assert_eq!(v, 3.0);
2873
2874         let v: f64 = super::decode("3.1").unwrap();
2875         assert_eq!(v, 3.1);
2876
2877         let v: f64 = super::decode("-1.2").unwrap();
2878         assert_eq!(v, -1.2);
2879
2880         let v: f64 = super::decode("0.4").unwrap();
2881         assert_eq!(v, 0.4);
2882
2883         let v: f64 = super::decode("0.4e5").unwrap();
2884         assert_eq!(v, 0.4e5);
2885
2886         let v: f64 = super::decode("0.4e15").unwrap();
2887         assert_eq!(v, 0.4e15);
2888
2889         let v: f64 = super::decode("0.4e-01").unwrap();
2890         assert_eq!(v, 0.4e-01);
2891
2892         let v: u64 = super::decode("0").unwrap();
2893         assert_eq!(v, 0);
2894
2895         let v: u64 = super::decode("18446744073709551615").unwrap();
2896         assert_eq!(v, u64::MAX);
2897
2898         let v: i64 = super::decode("-9223372036854775808").unwrap();
2899         assert_eq!(v, i64::MIN);
2900
2901         let v: i64 = super::decode("9223372036854775807").unwrap();
2902         assert_eq!(v, i64::MAX);
2903
2904         let res: DecodeResult<i64> = super::decode("765.25252");
2905         assert_eq!(res, Err(ExpectedError("Integer".to_string(),
2906                                           "765.25252".to_string())));
2907     }
2908
2909     #[test]
2910     fn test_read_str() {
2911         assert_eq!(from_str("\""),    Err(SyntaxError(EOFWhileParsingString, 1, 2)));
2912         assert_eq!(from_str("\"lol"), Err(SyntaxError(EOFWhileParsingString, 1, 5)));
2913
2914         assert_eq!(from_str("\"\""), Ok(String("".to_string())));
2915         assert_eq!(from_str("\"foo\""), Ok(String("foo".to_string())));
2916         assert_eq!(from_str("\"\\\"\""), Ok(String("\"".to_string())));
2917         assert_eq!(from_str("\"\\b\""), Ok(String("\x08".to_string())));
2918         assert_eq!(from_str("\"\\n\""), Ok(String("\n".to_string())));
2919         assert_eq!(from_str("\"\\r\""), Ok(String("\r".to_string())));
2920         assert_eq!(from_str("\"\\t\""), Ok(String("\t".to_string())));
2921         assert_eq!(from_str(" \"foo\" "), Ok(String("foo".to_string())));
2922         assert_eq!(from_str("\"\\u12ab\""), Ok(String("\u{12ab}".to_string())));
2923         assert_eq!(from_str("\"\\uAB12\""), Ok(String("\u{AB12}".to_string())));
2924     }
2925
2926     #[test]
2927     fn test_decode_str() {
2928         let s = [("\"\"", ""),
2929                  ("\"foo\"", "foo"),
2930                  ("\"\\\"\"", "\""),
2931                  ("\"\\b\"", "\x08"),
2932                  ("\"\\n\"", "\n"),
2933                  ("\"\\r\"", "\r"),
2934                  ("\"\\t\"", "\t"),
2935                  ("\"\\u12ab\"", "\u{12ab}"),
2936                  ("\"\\uAB12\"", "\u{AB12}")];
2937
2938         for &(i, o) in s.iter() {
2939             let v: string::String = super::decode(i).unwrap();
2940             assert_eq!(v, o);
2941         }
2942     }
2943
2944     #[test]
2945     fn test_read_array() {
2946         assert_eq!(from_str("["),     Err(SyntaxError(EOFWhileParsingValue, 1, 2)));
2947         assert_eq!(from_str("[1"),    Err(SyntaxError(EOFWhileParsingArray, 1, 3)));
2948         assert_eq!(from_str("[1,"),   Err(SyntaxError(EOFWhileParsingValue, 1, 4)));
2949         assert_eq!(from_str("[1,]"),  Err(SyntaxError(InvalidSyntax,        1, 4)));
2950         assert_eq!(from_str("[6 7]"), Err(SyntaxError(InvalidSyntax,        1, 4)));
2951
2952         assert_eq!(from_str("[]"), Ok(Array(vec![])));
2953         assert_eq!(from_str("[ ]"), Ok(Array(vec![])));
2954         assert_eq!(from_str("[true]"), Ok(Array(vec![Boolean(true)])));
2955         assert_eq!(from_str("[ false ]"), Ok(Array(vec![Boolean(false)])));
2956         assert_eq!(from_str("[null]"), Ok(Array(vec![Null])));
2957         assert_eq!(from_str("[3, 1]"),
2958                      Ok(Array(vec![U64(3), U64(1)])));
2959         assert_eq!(from_str("\n[3, 2]\n"),
2960                      Ok(Array(vec![U64(3), U64(2)])));
2961         assert_eq!(from_str("[2, [4, 1]]"),
2962                Ok(Array(vec![U64(2), Array(vec![U64(4), U64(1)])])));
2963     }
2964
2965     #[test]
2966     fn test_decode_array() {
2967         let v: Vec<()> = super::decode("[]").unwrap();
2968         assert_eq!(v, vec![]);
2969
2970         let v: Vec<()> = super::decode("[null]").unwrap();
2971         assert_eq!(v, vec![()]);
2972
2973         let v: Vec<bool> = super::decode("[true]").unwrap();
2974         assert_eq!(v, vec![true]);
2975
2976         let v: Vec<int> = super::decode("[3, 1]").unwrap();
2977         assert_eq!(v, vec![3, 1]);
2978
2979         let v: Vec<Vec<uint>> = super::decode("[[3], [1, 2]]").unwrap();
2980         assert_eq!(v, vec![vec![3], vec![1, 2]]);
2981     }
2982
2983     #[test]
2984     fn test_decode_tuple() {
2985         let t: (uint, uint, uint) = super::decode("[1, 2, 3]").unwrap();
2986         assert_eq!(t, (1u, 2, 3));
2987
2988         let t: (uint, string::String) = super::decode("[1, \"two\"]").unwrap();
2989         assert_eq!(t, (1u, "two".to_string()));
2990     }
2991
2992     #[test]
2993     fn test_decode_tuple_malformed_types() {
2994         assert!(super::decode::<(uint, string::String)>("[1, 2]").is_err());
2995     }
2996
2997     #[test]
2998     fn test_decode_tuple_malformed_length() {
2999         assert!(super::decode::<(uint, uint)>("[1, 2, 3]").is_err());
3000     }
3001
3002     #[test]
3003     fn test_read_object() {
3004         assert_eq!(from_str("{"),       Err(SyntaxError(EOFWhileParsingObject, 1, 2)));
3005         assert_eq!(from_str("{ "),      Err(SyntaxError(EOFWhileParsingObject, 1, 3)));
3006         assert_eq!(from_str("{1"),      Err(SyntaxError(KeyMustBeAString,      1, 2)));
3007         assert_eq!(from_str("{ \"a\""), Err(SyntaxError(EOFWhileParsingObject, 1, 6)));
3008         assert_eq!(from_str("{\"a\""),  Err(SyntaxError(EOFWhileParsingObject, 1, 5)));
3009         assert_eq!(from_str("{\"a\" "), Err(SyntaxError(EOFWhileParsingObject, 1, 6)));
3010
3011         assert_eq!(from_str("{\"a\" 1"),   Err(SyntaxError(ExpectedColon,         1, 6)));
3012         assert_eq!(from_str("{\"a\":"),    Err(SyntaxError(EOFWhileParsingValue,  1, 6)));
3013         assert_eq!(from_str("{\"a\":1"),   Err(SyntaxError(EOFWhileParsingObject, 1, 7)));
3014         assert_eq!(from_str("{\"a\":1 1"), Err(SyntaxError(InvalidSyntax,         1, 8)));
3015         assert_eq!(from_str("{\"a\":1,"),  Err(SyntaxError(EOFWhileParsingObject, 1, 8)));
3016
3017         assert_eq!(from_str("{}").unwrap(), mk_object(&[]));
3018         assert_eq!(from_str("{\"a\": 3}").unwrap(),
3019                   mk_object(&[("a".to_string(), U64(3))]));
3020
3021         assert_eq!(from_str(
3022                       "{ \"a\": null, \"b\" : true }").unwrap(),
3023                   mk_object(&[
3024                       ("a".to_string(), Null),
3025                       ("b".to_string(), Boolean(true))]));
3026         assert_eq!(from_str("\n{ \"a\": null, \"b\" : true }\n").unwrap(),
3027                   mk_object(&[
3028                       ("a".to_string(), Null),
3029                       ("b".to_string(), Boolean(true))]));
3030         assert_eq!(from_str(
3031                       "{\"a\" : 1.0 ,\"b\": [ true ]}").unwrap(),
3032                   mk_object(&[
3033                       ("a".to_string(), F64(1.0)),
3034                       ("b".to_string(), Array(vec![Boolean(true)]))
3035                   ]));
3036         assert_eq!(from_str(
3037                       "{\
3038                           \"a\": 1.0, \
3039                           \"b\": [\
3040                               true,\
3041                               \"foo\\nbar\", \
3042                               { \"c\": {\"d\": null} } \
3043                           ]\
3044                       }").unwrap(),
3045                   mk_object(&[
3046                       ("a".to_string(), F64(1.0)),
3047                       ("b".to_string(), Array(vec![
3048                           Boolean(true),
3049                           String("foo\nbar".to_string()),
3050                           mk_object(&[
3051                               ("c".to_string(), mk_object(&[("d".to_string(), Null)]))
3052                           ])
3053                       ]))
3054                   ]));
3055     }
3056
3057     #[test]
3058     fn test_decode_struct() {
3059         let s = "{
3060             \"inner\": [
3061                 { \"a\": null, \"b\": 2, \"c\": [\"abc\", \"xyz\"] }
3062             ]
3063         }";
3064
3065         let v: Outer = super::decode(s).unwrap();
3066         assert_eq!(
3067             v,
3068             Outer {
3069                 inner: vec![
3070                     Inner { a: (), b: 2, c: vec!["abc".to_string(), "xyz".to_string()] }
3071                 ]
3072             }
3073         );
3074     }
3075
3076     #[derive(RustcDecodable)]
3077     struct FloatStruct {
3078         f: f64,
3079         a: Vec<f64>
3080     }
3081     #[test]
3082     fn test_decode_struct_with_nan() {
3083         let s = "{\"f\":null,\"a\":[null,123]}";
3084         let obj: FloatStruct = super::decode(s).unwrap();
3085         assert!(obj.f.is_nan());
3086         assert!(obj.a[0].is_nan());
3087         assert_eq!(obj.a[1], 123f64);
3088     }
3089
3090     #[test]
3091     fn test_decode_option() {
3092         let value: Option<string::String> = super::decode("null").unwrap();
3093         assert_eq!(value, None);
3094
3095         let value: Option<string::String> = super::decode("\"jodhpurs\"").unwrap();
3096         assert_eq!(value, Some("jodhpurs".to_string()));
3097     }
3098
3099     #[test]
3100     fn test_decode_enum() {
3101         let value: Animal = super::decode("\"Dog\"").unwrap();
3102         assert_eq!(value, Dog);
3103
3104         let s = "{\"variant\":\"Frog\",\"fields\":[\"Henry\",349]}";
3105         let value: Animal = super::decode(s).unwrap();
3106         assert_eq!(value, Frog("Henry".to_string(), 349));
3107     }
3108
3109     #[test]
3110     fn test_decode_map() {
3111         let s = "{\"a\": \"Dog\", \"b\": {\"variant\":\"Frog\",\
3112                   \"fields\":[\"Henry\", 349]}}";
3113         let mut map: BTreeMap<string::String, Animal> = super::decode(s).unwrap();
3114
3115         assert_eq!(map.remove(&"a".to_string()), Some(Dog));
3116         assert_eq!(map.remove(&"b".to_string()), Some(Frog("Henry".to_string(), 349)));
3117     }
3118
3119     #[test]
3120     fn test_multiline_errors() {
3121         assert_eq!(from_str("{\n  \"foo\":\n \"bar\""),
3122             Err(SyntaxError(EOFWhileParsingObject, 3u, 8u)));
3123     }
3124
3125     #[derive(RustcDecodable)]
3126     #[allow(dead_code)]
3127     struct DecodeStruct {
3128         x: f64,
3129         y: bool,
3130         z: string::String,
3131         w: Vec<DecodeStruct>
3132     }
3133     #[derive(RustcDecodable)]
3134     enum DecodeEnum {
3135         A(f64),
3136         B(string::String)
3137     }
3138     fn check_err<T: Decodable>(to_parse: &'static str, expected: DecoderError) {
3139         let res: DecodeResult<T> = match from_str(to_parse) {
3140             Err(e) => Err(ParseError(e)),
3141             Ok(json) => Decodable::decode(&mut Decoder::new(json))
3142         };
3143         match res {
3144             Ok(_) => panic!("`{:?}` parsed & decoded ok, expecting error `{:?}`",
3145                               to_parse, expected),
3146             Err(ParseError(e)) => panic!("`{:?}` is not valid json: {:?}",
3147                                            to_parse, e),
3148             Err(e) => {
3149                 assert_eq!(e, expected);
3150             }
3151         }
3152     }
3153     #[test]
3154     fn test_decode_errors_struct() {
3155         check_err::<DecodeStruct>("[]", ExpectedError("Object".to_string(), "[]".to_string()));
3156         check_err::<DecodeStruct>("{\"x\": true, \"y\": true, \"z\": \"\", \"w\": []}",
3157                                   ExpectedError("Number".to_string(), "true".to_string()));
3158         check_err::<DecodeStruct>("{\"x\": 1, \"y\": [], \"z\": \"\", \"w\": []}",
3159                                   ExpectedError("Boolean".to_string(), "[]".to_string()));
3160         check_err::<DecodeStruct>("{\"x\": 1, \"y\": true, \"z\": {}, \"w\": []}",
3161                                   ExpectedError("String".to_string(), "{}".to_string()));
3162         check_err::<DecodeStruct>("{\"x\": 1, \"y\": true, \"z\": \"\", \"w\": null}",
3163                                   ExpectedError("Array".to_string(), "null".to_string()));
3164         check_err::<DecodeStruct>("{\"x\": 1, \"y\": true, \"z\": \"\"}",
3165                                   MissingFieldError("w".to_string()));
3166     }
3167     #[test]
3168     fn test_decode_errors_enum() {
3169         check_err::<DecodeEnum>("{}",
3170                                 MissingFieldError("variant".to_string()));
3171         check_err::<DecodeEnum>("{\"variant\": 1}",
3172                                 ExpectedError("String".to_string(), "1".to_string()));
3173         check_err::<DecodeEnum>("{\"variant\": \"A\"}",
3174                                 MissingFieldError("fields".to_string()));
3175         check_err::<DecodeEnum>("{\"variant\": \"A\", \"fields\": null}",
3176                                 ExpectedError("Array".to_string(), "null".to_string()));
3177         check_err::<DecodeEnum>("{\"variant\": \"C\", \"fields\": []}",
3178                                 UnknownVariantError("C".to_string()));
3179     }
3180
3181     #[test]
3182     fn test_find(){
3183         let json_value = from_str("{\"dog\" : \"cat\"}").unwrap();
3184         let found_str = json_value.find("dog");
3185         assert!(found_str.unwrap().as_string().unwrap() == "cat");
3186     }
3187
3188     #[test]
3189     fn test_find_path(){
3190         let json_value = from_str("{\"dog\":{\"cat\": {\"mouse\" : \"cheese\"}}}").unwrap();
3191         let found_str = json_value.find_path(&["dog", "cat", "mouse"]);
3192         assert!(found_str.unwrap().as_string().unwrap() == "cheese");
3193     }
3194
3195     #[test]
3196     fn test_search(){
3197         let json_value = from_str("{\"dog\":{\"cat\": {\"mouse\" : \"cheese\"}}}").unwrap();
3198         let found_str = json_value.search("mouse").and_then(|j| j.as_string());
3199         assert!(found_str.unwrap() == "cheese");
3200     }
3201
3202     #[test]
3203     fn test_index(){
3204         let json_value = from_str("{\"animals\":[\"dog\",\"cat\",\"mouse\"]}").unwrap();
3205         let ref array = json_value["animals"];
3206         assert_eq!(array[0].as_string().unwrap(), "dog");
3207         assert_eq!(array[1].as_string().unwrap(), "cat");
3208         assert_eq!(array[2].as_string().unwrap(), "mouse");
3209     }
3210
3211     #[test]
3212     fn test_is_object(){
3213         let json_value = from_str("{}").unwrap();
3214         assert!(json_value.is_object());
3215     }
3216
3217     #[test]
3218     fn test_as_object(){
3219         let json_value = from_str("{}").unwrap();
3220         let json_object = json_value.as_object();
3221         assert!(json_object.is_some());
3222     }
3223
3224     #[test]
3225     fn test_is_array(){
3226         let json_value = from_str("[1, 2, 3]").unwrap();
3227         assert!(json_value.is_array());
3228     }
3229
3230     #[test]
3231     fn test_as_array(){
3232         let json_value = from_str("[1, 2, 3]").unwrap();
3233         let json_array = json_value.as_array();
3234         let expected_length = 3;
3235         assert!(json_array.is_some() && json_array.unwrap().len() == expected_length);
3236     }
3237
3238     #[test]
3239     fn test_is_string(){
3240         let json_value = from_str("\"dog\"").unwrap();
3241         assert!(json_value.is_string());
3242     }
3243
3244     #[test]
3245     fn test_as_string(){
3246         let json_value = from_str("\"dog\"").unwrap();
3247         let json_str = json_value.as_string();
3248         let expected_str = "dog";
3249         assert_eq!(json_str, Some(expected_str));
3250     }
3251
3252     #[test]
3253     fn test_is_number(){
3254         let json_value = from_str("12").unwrap();
3255         assert!(json_value.is_number());
3256     }
3257
3258     #[test]
3259     fn test_is_i64(){
3260         let json_value = from_str("-12").unwrap();
3261         assert!(json_value.is_i64());
3262
3263         let json_value = from_str("12").unwrap();
3264         assert!(!json_value.is_i64());
3265
3266         let json_value = from_str("12.0").unwrap();
3267         assert!(!json_value.is_i64());
3268     }
3269
3270     #[test]
3271     fn test_is_u64(){
3272         let json_value = from_str("12").unwrap();
3273         assert!(json_value.is_u64());
3274
3275         let json_value = from_str("-12").unwrap();
3276         assert!(!json_value.is_u64());
3277
3278         let json_value = from_str("12.0").unwrap();
3279         assert!(!json_value.is_u64());
3280     }
3281
3282     #[test]
3283     fn test_is_f64(){
3284         let json_value = from_str("12").unwrap();
3285         assert!(!json_value.is_f64());
3286
3287         let json_value = from_str("-12").unwrap();
3288         assert!(!json_value.is_f64());
3289
3290         let json_value = from_str("12.0").unwrap();
3291         assert!(json_value.is_f64());
3292
3293         let json_value = from_str("-12.0").unwrap();
3294         assert!(json_value.is_f64());
3295     }
3296
3297     #[test]
3298     fn test_as_i64(){
3299         let json_value = from_str("-12").unwrap();
3300         let json_num = json_value.as_i64();
3301         assert_eq!(json_num, Some(-12));
3302     }
3303
3304     #[test]
3305     fn test_as_u64(){
3306         let json_value = from_str("12").unwrap();
3307         let json_num = json_value.as_u64();
3308         assert_eq!(json_num, Some(12));
3309     }
3310
3311     #[test]
3312     fn test_as_f64(){
3313         let json_value = from_str("12.0").unwrap();
3314         let json_num = json_value.as_f64();
3315         assert_eq!(json_num, Some(12f64));
3316     }
3317
3318     #[test]
3319     fn test_is_boolean(){
3320         let json_value = from_str("false").unwrap();
3321         assert!(json_value.is_boolean());
3322     }
3323
3324     #[test]
3325     fn test_as_boolean(){
3326         let json_value = from_str("false").unwrap();
3327         let json_bool = json_value.as_boolean();
3328         let expected_bool = false;
3329         assert!(json_bool.is_some() && json_bool.unwrap() == expected_bool);
3330     }
3331
3332     #[test]
3333     fn test_is_null(){
3334         let json_value = from_str("null").unwrap();
3335         assert!(json_value.is_null());
3336     }
3337
3338     #[test]
3339     fn test_as_null(){
3340         let json_value = from_str("null").unwrap();
3341         let json_null = json_value.as_null();
3342         let expected_null = ();
3343         assert!(json_null.is_some() && json_null.unwrap() == expected_null);
3344     }
3345
3346     #[test]
3347     fn test_encode_hashmap_with_numeric_key() {
3348         use std::str::from_utf8;
3349         use std::io::Writer;
3350         use std::collections::HashMap;
3351         let mut hm: HashMap<uint, bool> = HashMap::new();
3352         hm.insert(1, true);
3353         let mut mem_buf = Vec::new();
3354         write!(&mut mem_buf, "{}", super::as_pretty_json(&hm)).unwrap();
3355         let json_str = from_utf8(&mem_buf[]).unwrap();
3356         match from_str(json_str) {
3357             Err(_) => panic!("Unable to parse json_str: {:?}", json_str),
3358             _ => {} // it parsed and we are good to go
3359         }
3360     }
3361
3362     #[test]
3363     fn test_prettyencode_hashmap_with_numeric_key() {
3364         use std::str::from_utf8;
3365         use std::io::Writer;
3366         use std::collections::HashMap;
3367         let mut hm: HashMap<uint, bool> = HashMap::new();
3368         hm.insert(1, true);
3369         let mut mem_buf = Vec::new();
3370         write!(&mut mem_buf, "{}", super::as_pretty_json(&hm)).unwrap();
3371         let json_str = from_utf8(&mem_buf[]).unwrap();
3372         match from_str(json_str) {
3373             Err(_) => panic!("Unable to parse json_str: {:?}", json_str),
3374             _ => {} // it parsed and we are good to go
3375         }
3376     }
3377
3378     #[test]
3379     fn test_prettyencoder_indent_level_param() {
3380         use std::str::from_utf8;
3381         use std::collections::BTreeMap;
3382
3383         let mut tree = BTreeMap::new();
3384
3385         tree.insert("hello".to_string(), String("guten tag".to_string()));
3386         tree.insert("goodbye".to_string(), String("sayonara".to_string()));
3387
3388         let json = Array(
3389             // The following layout below should look a lot like
3390             // the pretty-printed JSON (indent * x)
3391             vec!
3392             ( // 0x
3393                 String("greetings".to_string()), // 1x
3394                 Object(tree), // 1x + 2x + 2x + 1x
3395             ) // 0x
3396             // End JSON array (7 lines)
3397         );
3398
3399         // Helper function for counting indents
3400         fn indents(source: &str) -> uint {
3401             let trimmed = source.trim_left_matches(' ');
3402             source.len() - trimmed.len()
3403         }
3404
3405         // Test up to 4 spaces of indents (more?)
3406         for i in range(0, 4u) {
3407             let mut writer = Vec::new();
3408             write!(&mut writer, "{}",
3409                    super::as_pretty_json(&json).indent(i)).unwrap();
3410
3411             let printed = from_utf8(&writer[]).unwrap();
3412
3413             // Check for indents at each line
3414             let lines: Vec<&str> = printed.lines().collect();
3415             assert_eq!(lines.len(), 7); // JSON should be 7 lines
3416
3417             assert_eq!(indents(lines[0]), 0 * i); // [
3418             assert_eq!(indents(lines[1]), 1 * i); //   "greetings",
3419             assert_eq!(indents(lines[2]), 1 * i); //   {
3420             assert_eq!(indents(lines[3]), 2 * i); //     "hello": "guten tag",
3421             assert_eq!(indents(lines[4]), 2 * i); //     "goodbye": "sayonara"
3422             assert_eq!(indents(lines[5]), 1 * i); //   },
3423             assert_eq!(indents(lines[6]), 0 * i); // ]
3424
3425             // Finally, test that the pretty-printed JSON is valid
3426             from_str(printed).ok().expect("Pretty-printed JSON is invalid!");
3427         }
3428     }
3429
3430     #[test]
3431     fn test_hashmap_with_numeric_key_can_handle_double_quote_delimited_key() {
3432         use std::collections::HashMap;
3433         use Decodable;
3434         let json_str = "{\"1\":true}";
3435         let json_obj = match from_str(json_str) {
3436             Err(_) => panic!("Unable to parse json_str: {:?}", json_str),
3437             Ok(o) => o
3438         };
3439         let mut decoder = Decoder::new(json_obj);
3440         let _hm: HashMap<uint, bool> = Decodable::decode(&mut decoder).unwrap();
3441     }
3442
3443     #[test]
3444     fn test_hashmap_with_numeric_key_will_error_with_string_keys() {
3445         use std::collections::HashMap;
3446         use Decodable;
3447         let json_str = "{\"a\":true}";
3448         let json_obj = match from_str(json_str) {
3449             Err(_) => panic!("Unable to parse json_str: {:?}", json_str),
3450             Ok(o) => o
3451         };
3452         let mut decoder = Decoder::new(json_obj);
3453         let result: Result<HashMap<uint, bool>, DecoderError> = Decodable::decode(&mut decoder);
3454         assert_eq!(result, Err(ExpectedError("Number".to_string(), "a".to_string())));
3455     }
3456
3457     fn assert_stream_equal(src: &str,
3458                            expected: Vec<(JsonEvent, Vec<StackElement>)>) {
3459         let mut parser = Parser::new(src.chars());
3460         let mut i = 0;
3461         loop {
3462             let evt = match parser.next() {
3463                 Some(e) => e,
3464                 None => { break; }
3465             };
3466             let (ref expected_evt, ref expected_stack) = expected[i];
3467             if !parser.stack().is_equal_to(expected_stack.as_slice()) {
3468                 panic!("Parser stack is not equal to {:?}", expected_stack);
3469             }
3470             assert_eq!(&evt, expected_evt);
3471             i+=1;
3472         }
3473     }
3474     #[test]
3475     #[cfg_attr(target_pointer_width = "32", ignore)] // FIXME(#14064)
3476     fn test_streaming_parser() {
3477         assert_stream_equal(
3478             r#"{ "foo":"bar", "array" : [0, 1, 2, 3, 4, 5], "idents":[null,true,false]}"#,
3479             vec![
3480                 (ObjectStart,             vec![]),
3481                   (StringValue("bar".to_string()),   vec![StackElement::Key("foo")]),
3482                   (ArrayStart,            vec![StackElement::Key("array")]),
3483                     (U64Value(0),         vec![StackElement::Key("array"), StackElement::Index(0)]),
3484                     (U64Value(1),         vec![StackElement::Key("array"), StackElement::Index(1)]),
3485                     (U64Value(2),         vec![StackElement::Key("array"), StackElement::Index(2)]),
3486                     (U64Value(3),         vec![StackElement::Key("array"), StackElement::Index(3)]),
3487                     (U64Value(4),         vec![StackElement::Key("array"), StackElement::Index(4)]),
3488                     (U64Value(5),         vec![StackElement::Key("array"), StackElement::Index(5)]),
3489                   (ArrayEnd,              vec![StackElement::Key("array")]),
3490                   (ArrayStart,            vec![StackElement::Key("idents")]),
3491                     (NullValue,           vec![StackElement::Key("idents"),
3492                                                StackElement::Index(0)]),
3493                     (BooleanValue(true),  vec![StackElement::Key("idents"),
3494                                                StackElement::Index(1)]),
3495                     (BooleanValue(false), vec![StackElement::Key("idents"),
3496                                                StackElement::Index(2)]),
3497                   (ArrayEnd,              vec![StackElement::Key("idents")]),
3498                 (ObjectEnd,               vec![]),
3499             ]
3500         );
3501     }
3502     fn last_event(src: &str) -> JsonEvent {
3503         let mut parser = Parser::new(src.chars());
3504         let mut evt = NullValue;
3505         loop {
3506             evt = match parser.next() {
3507                 Some(e) => e,
3508                 None => return evt,
3509             }
3510         }
3511     }
3512
3513     #[test]
3514     #[cfg_attr(target_pointer_width = "32", ignore)] // FIXME(#14064)
3515     fn test_read_object_streaming() {
3516         assert_eq!(last_event("{ "),      Error(SyntaxError(EOFWhileParsingObject, 1, 3)));
3517         assert_eq!(last_event("{1"),      Error(SyntaxError(KeyMustBeAString,      1, 2)));
3518         assert_eq!(last_event("{ \"a\""), Error(SyntaxError(EOFWhileParsingObject, 1, 6)));
3519         assert_eq!(last_event("{\"a\""),  Error(SyntaxError(EOFWhileParsingObject, 1, 5)));
3520         assert_eq!(last_event("{\"a\" "), Error(SyntaxError(EOFWhileParsingObject, 1, 6)));
3521
3522         assert_eq!(last_event("{\"a\" 1"),   Error(SyntaxError(ExpectedColon,         1, 6)));
3523         assert_eq!(last_event("{\"a\":"),    Error(SyntaxError(EOFWhileParsingValue,  1, 6)));
3524         assert_eq!(last_event("{\"a\":1"),   Error(SyntaxError(EOFWhileParsingObject, 1, 7)));
3525         assert_eq!(last_event("{\"a\":1 1"), Error(SyntaxError(InvalidSyntax,         1, 8)));
3526         assert_eq!(last_event("{\"a\":1,"),  Error(SyntaxError(EOFWhileParsingObject, 1, 8)));
3527         assert_eq!(last_event("{\"a\":1,}"), Error(SyntaxError(TrailingComma, 1, 8)));
3528
3529         assert_stream_equal(
3530             "{}",
3531             vec![(ObjectStart, vec![]), (ObjectEnd, vec![])]
3532         );
3533         assert_stream_equal(
3534             "{\"a\": 3}",
3535             vec![
3536                 (ObjectStart,        vec![]),
3537                   (U64Value(3),      vec![StackElement::Key("a")]),
3538                 (ObjectEnd,          vec![]),
3539             ]
3540         );
3541         assert_stream_equal(
3542             "{ \"a\": null, \"b\" : true }",
3543             vec![
3544                 (ObjectStart,           vec![]),
3545                   (NullValue,           vec![StackElement::Key("a")]),
3546                   (BooleanValue(true),  vec![StackElement::Key("b")]),
3547                 (ObjectEnd,             vec![]),
3548             ]
3549         );
3550         assert_stream_equal(
3551             "{\"a\" : 1.0 ,\"b\": [ true ]}",
3552             vec![
3553                 (ObjectStart,           vec![]),
3554                   (F64Value(1.0),       vec![StackElement::Key("a")]),
3555                   (ArrayStart,          vec![StackElement::Key("b")]),
3556                     (BooleanValue(true),vec![StackElement::Key("b"), StackElement::Index(0)]),
3557                   (ArrayEnd,            vec![StackElement::Key("b")]),
3558                 (ObjectEnd,             vec![]),
3559             ]
3560         );
3561         assert_stream_equal(
3562             r#"{
3563                 "a": 1.0,
3564                 "b": [
3565                     true,
3566                     "foo\nbar",
3567                     { "c": {"d": null} }
3568                 ]
3569             }"#,
3570             vec![
3571                 (ObjectStart,                   vec![]),
3572                   (F64Value(1.0),               vec![StackElement::Key("a")]),
3573                   (ArrayStart,                  vec![StackElement::Key("b")]),
3574                     (BooleanValue(true),        vec![StackElement::Key("b"),
3575                                                      StackElement::Index(0)]),
3576                     (StringValue("foo\nbar".to_string()),  vec![StackElement::Key("b"),
3577                                                                 StackElement::Index(1)]),
3578                     (ObjectStart,               vec![StackElement::Key("b"),
3579                                                      StackElement::Index(2)]),
3580                       (ObjectStart,             vec![StackElement::Key("b"),
3581                                                      StackElement::Index(2),
3582                                                      StackElement::Key("c")]),
3583                         (NullValue,             vec![StackElement::Key("b"),
3584                                                      StackElement::Index(2),
3585                                                      StackElement::Key("c"),
3586                                                      StackElement::Key("d")]),
3587                       (ObjectEnd,               vec![StackElement::Key("b"),
3588                                                      StackElement::Index(2),
3589                                                      StackElement::Key("c")]),
3590                     (ObjectEnd,                 vec![StackElement::Key("b"),
3591                                                      StackElement::Index(2)]),
3592                   (ArrayEnd,                    vec![StackElement::Key("b")]),
3593                 (ObjectEnd,                     vec![]),
3594             ]
3595         );
3596     }
3597     #[test]
3598     #[cfg_attr(target_pointer_width = "32", ignore)] // FIXME(#14064)
3599     fn test_read_array_streaming() {
3600         assert_stream_equal(
3601             "[]",
3602             vec![
3603                 (ArrayStart, vec![]),
3604                 (ArrayEnd,   vec![]),
3605             ]
3606         );
3607         assert_stream_equal(
3608             "[ ]",
3609             vec![
3610                 (ArrayStart, vec![]),
3611                 (ArrayEnd,   vec![]),
3612             ]
3613         );
3614         assert_stream_equal(
3615             "[true]",
3616             vec![
3617                 (ArrayStart,             vec![]),
3618                     (BooleanValue(true), vec![StackElement::Index(0)]),
3619                 (ArrayEnd,               vec![]),
3620             ]
3621         );
3622         assert_stream_equal(
3623             "[ false ]",
3624             vec![
3625                 (ArrayStart,              vec![]),
3626                     (BooleanValue(false), vec![StackElement::Index(0)]),
3627                 (ArrayEnd,                vec![]),
3628             ]
3629         );
3630         assert_stream_equal(
3631             "[null]",
3632             vec![
3633                 (ArrayStart,    vec![]),
3634                     (NullValue, vec![StackElement::Index(0)]),
3635                 (ArrayEnd,      vec![]),
3636             ]
3637         );
3638         assert_stream_equal(
3639             "[3, 1]",
3640             vec![
3641                 (ArrayStart,      vec![]),
3642                     (U64Value(3), vec![StackElement::Index(0)]),
3643                     (U64Value(1), vec![StackElement::Index(1)]),
3644                 (ArrayEnd,        vec![]),
3645             ]
3646         );
3647         assert_stream_equal(
3648             "\n[3, 2]\n",
3649             vec![
3650                 (ArrayStart,      vec![]),
3651                     (U64Value(3), vec![StackElement::Index(0)]),
3652                     (U64Value(2), vec![StackElement::Index(1)]),
3653                 (ArrayEnd,        vec![]),
3654             ]
3655         );
3656         assert_stream_equal(
3657             "[2, [4, 1]]",
3658             vec![
3659                 (ArrayStart,           vec![]),
3660                     (U64Value(2),      vec![StackElement::Index(0)]),
3661                     (ArrayStart,       vec![StackElement::Index(1)]),
3662                         (U64Value(4),  vec![StackElement::Index(1), StackElement::Index(0)]),
3663                         (U64Value(1),  vec![StackElement::Index(1), StackElement::Index(1)]),
3664                     (ArrayEnd,         vec![StackElement::Index(1)]),
3665                 (ArrayEnd,             vec![]),
3666             ]
3667         );
3668
3669         assert_eq!(last_event("["), Error(SyntaxError(EOFWhileParsingValue, 1,  2)));
3670
3671         assert_eq!(from_str("["),     Err(SyntaxError(EOFWhileParsingValue, 1, 2)));
3672         assert_eq!(from_str("[1"),    Err(SyntaxError(EOFWhileParsingArray, 1, 3)));
3673         assert_eq!(from_str("[1,"),   Err(SyntaxError(EOFWhileParsingValue, 1, 4)));
3674         assert_eq!(from_str("[1,]"),  Err(SyntaxError(InvalidSyntax,        1, 4)));
3675         assert_eq!(from_str("[6 7]"), Err(SyntaxError(InvalidSyntax,        1, 4)));
3676
3677     }
3678     #[test]
3679     fn test_trailing_characters_streaming() {
3680         assert_eq!(last_event("nulla"),  Error(SyntaxError(TrailingCharacters, 1, 5)));
3681         assert_eq!(last_event("truea"),  Error(SyntaxError(TrailingCharacters, 1, 5)));
3682         assert_eq!(last_event("falsea"), Error(SyntaxError(TrailingCharacters, 1, 6)));
3683         assert_eq!(last_event("1a"),     Error(SyntaxError(TrailingCharacters, 1, 2)));
3684         assert_eq!(last_event("[]a"),    Error(SyntaxError(TrailingCharacters, 1, 3)));
3685         assert_eq!(last_event("{}a"),    Error(SyntaxError(TrailingCharacters, 1, 3)));
3686     }
3687     #[test]
3688     fn test_read_identifiers_streaming() {
3689         assert_eq!(Parser::new("null".chars()).next(), Some(NullValue));
3690         assert_eq!(Parser::new("true".chars()).next(), Some(BooleanValue(true)));
3691         assert_eq!(Parser::new("false".chars()).next(), Some(BooleanValue(false)));
3692
3693         assert_eq!(last_event("n"),    Error(SyntaxError(InvalidSyntax, 1, 2)));
3694         assert_eq!(last_event("nul"),  Error(SyntaxError(InvalidSyntax, 1, 4)));
3695         assert_eq!(last_event("t"),    Error(SyntaxError(InvalidSyntax, 1, 2)));
3696         assert_eq!(last_event("truz"), Error(SyntaxError(InvalidSyntax, 1, 4)));
3697         assert_eq!(last_event("f"),    Error(SyntaxError(InvalidSyntax, 1, 2)));
3698         assert_eq!(last_event("faz"),  Error(SyntaxError(InvalidSyntax, 1, 3)));
3699     }
3700
3701     #[test]
3702     fn test_stack() {
3703         let mut stack = Stack::new();
3704
3705         assert!(stack.is_empty());
3706         assert!(stack.len() == 0);
3707         assert!(!stack.last_is_index());
3708
3709         stack.push_index(0);
3710         stack.bump_index();
3711
3712         assert!(stack.len() == 1);
3713         assert!(stack.is_equal_to(&[StackElement::Index(1)]));
3714         assert!(stack.starts_with(&[StackElement::Index(1)]));
3715         assert!(stack.ends_with(&[StackElement::Index(1)]));
3716         assert!(stack.last_is_index());
3717         assert!(stack.get(0) == StackElement::Index(1));
3718
3719         stack.push_key("foo".to_string());
3720
3721         assert!(stack.len() == 2);
3722         assert!(stack.is_equal_to(&[StackElement::Index(1), StackElement::Key("foo")]));
3723         assert!(stack.starts_with(&[StackElement::Index(1), StackElement::Key("foo")]));
3724         assert!(stack.starts_with(&[StackElement::Index(1)]));
3725         assert!(stack.ends_with(&[StackElement::Index(1), StackElement::Key("foo")]));
3726         assert!(stack.ends_with(&[StackElement::Key("foo")]));
3727         assert!(!stack.last_is_index());
3728         assert!(stack.get(0) == StackElement::Index(1));
3729         assert!(stack.get(1) == StackElement::Key("foo"));
3730
3731         stack.push_key("bar".to_string());
3732
3733         assert!(stack.len() == 3);
3734         assert!(stack.is_equal_to(&[StackElement::Index(1),
3735                                     StackElement::Key("foo"),
3736                                     StackElement::Key("bar")]));
3737         assert!(stack.starts_with(&[StackElement::Index(1)]));
3738         assert!(stack.starts_with(&[StackElement::Index(1), StackElement::Key("foo")]));
3739         assert!(stack.starts_with(&[StackElement::Index(1),
3740                                     StackElement::Key("foo"),
3741                                     StackElement::Key("bar")]));
3742         assert!(stack.ends_with(&[StackElement::Key("bar")]));
3743         assert!(stack.ends_with(&[StackElement::Key("foo"), StackElement::Key("bar")]));
3744         assert!(stack.ends_with(&[StackElement::Index(1),
3745                                   StackElement::Key("foo"),
3746                                   StackElement::Key("bar")]));
3747         assert!(!stack.last_is_index());
3748         assert!(stack.get(0) == StackElement::Index(1));
3749         assert!(stack.get(1) == StackElement::Key("foo"));
3750         assert!(stack.get(2) == StackElement::Key("bar"));
3751
3752         stack.pop();
3753
3754         assert!(stack.len() == 2);
3755         assert!(stack.is_equal_to(&[StackElement::Index(1), StackElement::Key("foo")]));
3756         assert!(stack.starts_with(&[StackElement::Index(1), StackElement::Key("foo")]));
3757         assert!(stack.starts_with(&[StackElement::Index(1)]));
3758         assert!(stack.ends_with(&[StackElement::Index(1), StackElement::Key("foo")]));
3759         assert!(stack.ends_with(&[StackElement::Key("foo")]));
3760         assert!(!stack.last_is_index());
3761         assert!(stack.get(0) == StackElement::Index(1));
3762         assert!(stack.get(1) == StackElement::Key("foo"));
3763     }
3764
3765     #[test]
3766     fn test_to_json() {
3767         use std::collections::{HashMap,BTreeMap};
3768         use super::ToJson;
3769
3770         let array2 = Array(vec!(U64(1), U64(2)));
3771         let array3 = Array(vec!(U64(1), U64(2), U64(3)));
3772         let object = {
3773             let mut tree_map = BTreeMap::new();
3774             tree_map.insert("a".to_string(), U64(1));
3775             tree_map.insert("b".to_string(), U64(2));
3776             Object(tree_map)
3777         };
3778
3779         assert_eq!(array2.to_json(), array2);
3780         assert_eq!(object.to_json(), object);
3781         assert_eq!(3_i.to_json(), I64(3));
3782         assert_eq!(4_i8.to_json(), I64(4));
3783         assert_eq!(5_i16.to_json(), I64(5));
3784         assert_eq!(6_i32.to_json(), I64(6));
3785         assert_eq!(7_i64.to_json(), I64(7));
3786         assert_eq!(8_u.to_json(), U64(8));
3787         assert_eq!(9_u8.to_json(), U64(9));
3788         assert_eq!(10_u16.to_json(), U64(10));
3789         assert_eq!(11_u32.to_json(), U64(11));
3790         assert_eq!(12_u64.to_json(), U64(12));
3791         assert_eq!(13.0_f32.to_json(), F64(13.0_f64));
3792         assert_eq!(14.0_f64.to_json(), F64(14.0_f64));
3793         assert_eq!(().to_json(), Null);
3794         assert_eq!(f32::INFINITY.to_json(), Null);
3795         assert_eq!(f64::NAN.to_json(), Null);
3796         assert_eq!(true.to_json(), Boolean(true));
3797         assert_eq!(false.to_json(), Boolean(false));
3798         assert_eq!("abc".to_json(), String("abc".to_string()));
3799         assert_eq!("abc".to_string().to_json(), String("abc".to_string()));
3800         assert_eq!((1u, 2u).to_json(), array2);
3801         assert_eq!((1u, 2u, 3u).to_json(), array3);
3802         assert_eq!([1u, 2].to_json(), array2);
3803         assert_eq!((&[1u, 2, 3]).to_json(), array3);
3804         assert_eq!((vec![1u, 2]).to_json(), array2);
3805         assert_eq!(vec!(1u, 2, 3).to_json(), array3);
3806         let mut tree_map = BTreeMap::new();
3807         tree_map.insert("a".to_string(), 1u);
3808         tree_map.insert("b".to_string(), 2);
3809         assert_eq!(tree_map.to_json(), object);
3810         let mut hash_map = HashMap::new();
3811         hash_map.insert("a".to_string(), 1u);
3812         hash_map.insert("b".to_string(), 2);
3813         assert_eq!(hash_map.to_json(), object);
3814         assert_eq!(Some(15i).to_json(), I64(15));
3815         assert_eq!(Some(15u).to_json(), U64(15));
3816         assert_eq!(None::<int>.to_json(), Null);
3817     }
3818
3819     #[bench]
3820     fn bench_streaming_small(b: &mut Bencher) {
3821         b.iter( || {
3822             let mut parser = Parser::new(
3823                 r#"{
3824                     "a": 1.0,
3825                     "b": [
3826                         true,
3827                         "foo\nbar",
3828                         { "c": {"d": null} }
3829                     ]
3830                 }"#.chars()
3831             );
3832             loop {
3833                 match parser.next() {
3834                     None => return,
3835                     _ => {}
3836                 }
3837             }
3838         });
3839     }
3840     #[bench]
3841     fn bench_small(b: &mut Bencher) {
3842         b.iter( || {
3843             let _ = from_str(r#"{
3844                 "a": 1.0,
3845                 "b": [
3846                     true,
3847                     "foo\nbar",
3848                     { "c": {"d": null} }
3849                 ]
3850             }"#);
3851         });
3852     }
3853
3854     fn big_json() -> string::String {
3855         let mut src = "[\n".to_string();
3856         for _ in range(0i, 500) {
3857             src.push_str(r#"{ "a": true, "b": null, "c":3.1415, "d": "Hello world", "e": \
3858                             [1,2,3]},"#);
3859         }
3860         src.push_str("{}]");
3861         return src;
3862     }
3863
3864     #[bench]
3865     fn bench_streaming_large(b: &mut Bencher) {
3866         let src = big_json();
3867         b.iter( || {
3868             let mut parser = Parser::new(src.chars());
3869             loop {
3870                 match parser.next() {
3871                     None => return,
3872                     _ => {}
3873                 }
3874             }
3875         });
3876     }
3877     #[bench]
3878     fn bench_large(b: &mut Bencher) {
3879         let src = big_json();
3880         b.iter( || { let _ = from_str(src.as_slice()); });
3881     }
3882 }