]> git.lizzy.rs Git - rust.git/blob - src/libserialize/json.rs
rollup merge of #20709: thiagopnts/ownership-guide-typo
[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.index(&(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.index(&(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.index(&(0..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.index(&(0..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.index(&FullRange)).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.index(&FullRange)).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.index(&FullRange)),
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.index(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.index(&((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.index(&((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<T>(&self, reason: ErrorCode) -> Result<T, 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.index(&FullRange)) {
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::ops::Index;
2515     use std::string;
2516
2517     #[derive(RustcDecodable, Eq, PartialEq, Show)]
2518     struct OptionData {
2519         opt: Option<uint>,
2520     }
2521
2522     #[test]
2523     fn test_decode_option_none() {
2524         let s ="{}";
2525         let obj: OptionData = super::decode(s).unwrap();
2526         assert_eq!(obj, OptionData { opt: None });
2527     }
2528
2529     #[test]
2530     fn test_decode_option_some() {
2531         let s = "{ \"opt\": 10 }";
2532         let obj: OptionData = super::decode(s).unwrap();
2533         assert_eq!(obj, OptionData { opt: Some(10u) });
2534     }
2535
2536     #[test]
2537     fn test_decode_option_malformed() {
2538         check_err::<OptionData>("{ \"opt\": [] }",
2539                                 ExpectedError("Number".to_string(), "[]".to_string()));
2540         check_err::<OptionData>("{ \"opt\": false }",
2541                                 ExpectedError("Number".to_string(), "false".to_string()));
2542     }
2543
2544     #[derive(PartialEq, RustcEncodable, RustcDecodable, Show)]
2545     enum Animal {
2546         Dog,
2547         Frog(string::String, int)
2548     }
2549
2550     #[derive(PartialEq, RustcEncodable, RustcDecodable, Show)]
2551     struct Inner {
2552         a: (),
2553         b: uint,
2554         c: Vec<string::String>,
2555     }
2556
2557     #[derive(PartialEq, RustcEncodable, RustcDecodable, Show)]
2558     struct Outer {
2559         inner: Vec<Inner>,
2560     }
2561
2562     fn mk_object(items: &[(string::String, Json)]) -> Json {
2563         let mut d = BTreeMap::new();
2564
2565         for item in items.iter() {
2566             match *item {
2567                 (ref key, ref value) => { d.insert((*key).clone(), (*value).clone()); },
2568             }
2569         };
2570
2571         Object(d)
2572     }
2573
2574     #[test]
2575     fn test_from_str_trait() {
2576         let s = "null";
2577         assert!(s.parse::<Json>().unwrap() == s.parse().unwrap());
2578     }
2579
2580     #[test]
2581     fn test_write_null() {
2582         assert_eq!(Null.to_string(), "null");
2583         assert_eq!(Null.pretty().to_string(), "null");
2584     }
2585
2586     #[test]
2587     fn test_write_i64() {
2588         assert_eq!(U64(0).to_string(), "0");
2589         assert_eq!(U64(0).pretty().to_string(), "0");
2590
2591         assert_eq!(U64(1234).to_string(), "1234");
2592         assert_eq!(U64(1234).pretty().to_string(), "1234");
2593
2594         assert_eq!(I64(-5678).to_string(), "-5678");
2595         assert_eq!(I64(-5678).pretty().to_string(), "-5678");
2596
2597         assert_eq!(U64(7650007200025252000).to_string(), "7650007200025252000");
2598         assert_eq!(U64(7650007200025252000).pretty().to_string(), "7650007200025252000");
2599     }
2600
2601     #[test]
2602     fn test_write_f64() {
2603         assert_eq!(F64(3.0).to_string(), "3.0");
2604         assert_eq!(F64(3.0).pretty().to_string(), "3.0");
2605
2606         assert_eq!(F64(3.1).to_string(), "3.1");
2607         assert_eq!(F64(3.1).pretty().to_string(), "3.1");
2608
2609         assert_eq!(F64(-1.5).to_string(), "-1.5");
2610         assert_eq!(F64(-1.5).pretty().to_string(), "-1.5");
2611
2612         assert_eq!(F64(0.5).to_string(), "0.5");
2613         assert_eq!(F64(0.5).pretty().to_string(), "0.5");
2614
2615         assert_eq!(F64(f64::NAN).to_string(), "null");
2616         assert_eq!(F64(f64::NAN).pretty().to_string(), "null");
2617
2618         assert_eq!(F64(f64::INFINITY).to_string(), "null");
2619         assert_eq!(F64(f64::INFINITY).pretty().to_string(), "null");
2620
2621         assert_eq!(F64(f64::NEG_INFINITY).to_string(), "null");
2622         assert_eq!(F64(f64::NEG_INFINITY).pretty().to_string(), "null");
2623     }
2624
2625     #[test]
2626     fn test_write_str() {
2627         assert_eq!(String("".to_string()).to_string(), "\"\"");
2628         assert_eq!(String("".to_string()).pretty().to_string(), "\"\"");
2629
2630         assert_eq!(String("homura".to_string()).to_string(), "\"homura\"");
2631         assert_eq!(String("madoka".to_string()).pretty().to_string(), "\"madoka\"");
2632     }
2633
2634     #[test]
2635     fn test_write_bool() {
2636         assert_eq!(Boolean(true).to_string(), "true");
2637         assert_eq!(Boolean(true).pretty().to_string(), "true");
2638
2639         assert_eq!(Boolean(false).to_string(), "false");
2640         assert_eq!(Boolean(false).pretty().to_string(), "false");
2641     }
2642
2643     #[test]
2644     fn test_write_array() {
2645         assert_eq!(Array(vec![]).to_string(), "[]");
2646         assert_eq!(Array(vec![]).pretty().to_string(), "[]");
2647
2648         assert_eq!(Array(vec![Boolean(true)]).to_string(), "[true]");
2649         assert_eq!(
2650             Array(vec![Boolean(true)]).pretty().to_string(),
2651             "\
2652             [\n  \
2653                 true\n\
2654             ]"
2655         );
2656
2657         let long_test_array = Array(vec![
2658             Boolean(false),
2659             Null,
2660             Array(vec![String("foo\nbar".to_string()), F64(3.5)])]);
2661
2662         assert_eq!(long_test_array.to_string(),
2663             "[false,null,[\"foo\\nbar\",3.5]]");
2664         assert_eq!(
2665             long_test_array.pretty().to_string(),
2666             "\
2667             [\n  \
2668                 false,\n  \
2669                 null,\n  \
2670                 [\n    \
2671                     \"foo\\nbar\",\n    \
2672                     3.5\n  \
2673                 ]\n\
2674             ]"
2675         );
2676     }
2677
2678     #[test]
2679     fn test_write_object() {
2680         assert_eq!(mk_object(&[]).to_string(), "{}");
2681         assert_eq!(mk_object(&[]).pretty().to_string(), "{}");
2682
2683         assert_eq!(
2684             mk_object(&[
2685                 ("a".to_string(), Boolean(true))
2686             ]).to_string(),
2687             "{\"a\":true}"
2688         );
2689         assert_eq!(
2690             mk_object(&[("a".to_string(), Boolean(true))]).pretty().to_string(),
2691             "\
2692             {\n  \
2693                 \"a\": true\n\
2694             }"
2695         );
2696
2697         let complex_obj = mk_object(&[
2698                 ("b".to_string(), Array(vec![
2699                     mk_object(&[("c".to_string(), String("\x0c\r".to_string()))]),
2700                     mk_object(&[("d".to_string(), String("".to_string()))])
2701                 ]))
2702             ]);
2703
2704         assert_eq!(
2705             complex_obj.to_string(),
2706             "{\
2707                 \"b\":[\
2708                     {\"c\":\"\\f\\r\"},\
2709                     {\"d\":\"\"}\
2710                 ]\
2711             }"
2712         );
2713         assert_eq!(
2714             complex_obj.pretty().to_string(),
2715             "\
2716             {\n  \
2717                 \"b\": [\n    \
2718                     {\n      \
2719                         \"c\": \"\\f\\r\"\n    \
2720                     },\n    \
2721                     {\n      \
2722                         \"d\": \"\"\n    \
2723                     }\n  \
2724                 ]\n\
2725             }"
2726         );
2727
2728         let a = mk_object(&[
2729             ("a".to_string(), Boolean(true)),
2730             ("b".to_string(), Array(vec![
2731                 mk_object(&[("c".to_string(), String("\x0c\r".to_string()))]),
2732                 mk_object(&[("d".to_string(), String("".to_string()))])
2733             ]))
2734         ]);
2735
2736         // We can't compare the strings directly because the object fields be
2737         // printed in a different order.
2738         assert_eq!(a.clone(), a.to_string().parse().unwrap());
2739         assert_eq!(a.clone(), a.pretty().to_string().parse().unwrap());
2740     }
2741
2742     #[test]
2743     fn test_write_enum() {
2744         let animal = Dog;
2745         assert_eq!(
2746             format!("{}", super::as_json(&animal)),
2747             "\"Dog\""
2748         );
2749         assert_eq!(
2750             format!("{}", super::as_pretty_json(&animal)),
2751             "\"Dog\""
2752         );
2753
2754         let animal = Frog("Henry".to_string(), 349);
2755         assert_eq!(
2756             format!("{}", super::as_json(&animal)),
2757             "{\"variant\":\"Frog\",\"fields\":[\"Henry\",349]}"
2758         );
2759         assert_eq!(
2760             format!("{}", super::as_pretty_json(&animal)),
2761             "{\n  \
2762                \"variant\": \"Frog\",\n  \
2763                \"fields\": [\n    \
2764                  \"Henry\",\n    \
2765                  349\n  \
2766                ]\n\
2767              }"
2768         );
2769     }
2770
2771     macro_rules! check_encoder_for_simple {
2772         ($value:expr, $expected:expr) => ({
2773             let s = format!("{}", super::as_json(&$value));
2774             assert_eq!(s, $expected);
2775
2776             let s = format!("{}", super::as_pretty_json(&$value));
2777             assert_eq!(s, $expected);
2778         })
2779     }
2780
2781     #[test]
2782     fn test_write_some() {
2783         check_encoder_for_simple!(Some("jodhpurs".to_string()), "\"jodhpurs\"");
2784     }
2785
2786     #[test]
2787     fn test_write_none() {
2788         check_encoder_for_simple!(None::<string::String>, "null");
2789     }
2790
2791     #[test]
2792     fn test_write_char() {
2793         check_encoder_for_simple!('a', "\"a\"");
2794         check_encoder_for_simple!('\t', "\"\\t\"");
2795         check_encoder_for_simple!('\u{0000}', "\"\\u0000\"");
2796         check_encoder_for_simple!('\u{001b}', "\"\\u001b\"");
2797         check_encoder_for_simple!('\u{007f}', "\"\\u007f\"");
2798         check_encoder_for_simple!('\u{00a0}', "\"\u{00a0}\"");
2799         check_encoder_for_simple!('\u{abcd}', "\"\u{abcd}\"");
2800         check_encoder_for_simple!('\u{10ffff}', "\"\u{10ffff}\"");
2801     }
2802
2803     #[test]
2804     fn test_trailing_characters() {
2805         assert_eq!(from_str("nulla"),  Err(SyntaxError(TrailingCharacters, 1, 5)));
2806         assert_eq!(from_str("truea"),  Err(SyntaxError(TrailingCharacters, 1, 5)));
2807         assert_eq!(from_str("falsea"), Err(SyntaxError(TrailingCharacters, 1, 6)));
2808         assert_eq!(from_str("1a"),     Err(SyntaxError(TrailingCharacters, 1, 2)));
2809         assert_eq!(from_str("[]a"),    Err(SyntaxError(TrailingCharacters, 1, 3)));
2810         assert_eq!(from_str("{}a"),    Err(SyntaxError(TrailingCharacters, 1, 3)));
2811     }
2812
2813     #[test]
2814     fn test_read_identifiers() {
2815         assert_eq!(from_str("n"),    Err(SyntaxError(InvalidSyntax, 1, 2)));
2816         assert_eq!(from_str("nul"),  Err(SyntaxError(InvalidSyntax, 1, 4)));
2817         assert_eq!(from_str("t"),    Err(SyntaxError(InvalidSyntax, 1, 2)));
2818         assert_eq!(from_str("truz"), Err(SyntaxError(InvalidSyntax, 1, 4)));
2819         assert_eq!(from_str("f"),    Err(SyntaxError(InvalidSyntax, 1, 2)));
2820         assert_eq!(from_str("faz"),  Err(SyntaxError(InvalidSyntax, 1, 3)));
2821
2822         assert_eq!(from_str("null"), Ok(Null));
2823         assert_eq!(from_str("true"), Ok(Boolean(true)));
2824         assert_eq!(from_str("false"), Ok(Boolean(false)));
2825         assert_eq!(from_str(" null "), Ok(Null));
2826         assert_eq!(from_str(" true "), Ok(Boolean(true)));
2827         assert_eq!(from_str(" false "), Ok(Boolean(false)));
2828     }
2829
2830     #[test]
2831     fn test_decode_identifiers() {
2832         let v: () = super::decode("null").unwrap();
2833         assert_eq!(v, ());
2834
2835         let v: bool = super::decode("true").unwrap();
2836         assert_eq!(v, true);
2837
2838         let v: bool = super::decode("false").unwrap();
2839         assert_eq!(v, false);
2840     }
2841
2842     #[test]
2843     fn test_read_number() {
2844         assert_eq!(from_str("+"),   Err(SyntaxError(InvalidSyntax, 1, 1)));
2845         assert_eq!(from_str("."),   Err(SyntaxError(InvalidSyntax, 1, 1)));
2846         assert_eq!(from_str("NaN"), Err(SyntaxError(InvalidSyntax, 1, 1)));
2847         assert_eq!(from_str("-"),   Err(SyntaxError(InvalidNumber, 1, 2)));
2848         assert_eq!(from_str("00"),  Err(SyntaxError(InvalidNumber, 1, 2)));
2849         assert_eq!(from_str("1."),  Err(SyntaxError(InvalidNumber, 1, 3)));
2850         assert_eq!(from_str("1e"),  Err(SyntaxError(InvalidNumber, 1, 3)));
2851         assert_eq!(from_str("1e+"), Err(SyntaxError(InvalidNumber, 1, 4)));
2852
2853         assert_eq!(from_str("18446744073709551616"), Err(SyntaxError(InvalidNumber, 1, 20)));
2854         assert_eq!(from_str("-9223372036854775809"), Err(SyntaxError(InvalidNumber, 1, 21)));
2855
2856         assert_eq!(from_str("3"), Ok(U64(3)));
2857         assert_eq!(from_str("3.1"), Ok(F64(3.1)));
2858         assert_eq!(from_str("-1.2"), Ok(F64(-1.2)));
2859         assert_eq!(from_str("0.4"), Ok(F64(0.4)));
2860         assert_eq!(from_str("0.4e5"), Ok(F64(0.4e5)));
2861         assert_eq!(from_str("0.4e+15"), Ok(F64(0.4e15)));
2862         assert_eq!(from_str("0.4e-01"), Ok(F64(0.4e-01)));
2863         assert_eq!(from_str(" 3 "), Ok(U64(3)));
2864
2865         assert_eq!(from_str("-9223372036854775808"), Ok(I64(i64::MIN)));
2866         assert_eq!(from_str("9223372036854775807"), Ok(U64(i64::MAX as u64)));
2867         assert_eq!(from_str("18446744073709551615"), Ok(U64(u64::MAX)));
2868     }
2869
2870     #[test]
2871     fn test_decode_numbers() {
2872         let v: f64 = super::decode("3").unwrap();
2873         assert_eq!(v, 3.0);
2874
2875         let v: f64 = super::decode("3.1").unwrap();
2876         assert_eq!(v, 3.1);
2877
2878         let v: f64 = super::decode("-1.2").unwrap();
2879         assert_eq!(v, -1.2);
2880
2881         let v: f64 = super::decode("0.4").unwrap();
2882         assert_eq!(v, 0.4);
2883
2884         let v: f64 = super::decode("0.4e5").unwrap();
2885         assert_eq!(v, 0.4e5);
2886
2887         let v: f64 = super::decode("0.4e15").unwrap();
2888         assert_eq!(v, 0.4e15);
2889
2890         let v: f64 = super::decode("0.4e-01").unwrap();
2891         assert_eq!(v, 0.4e-01);
2892
2893         let v: u64 = super::decode("0").unwrap();
2894         assert_eq!(v, 0);
2895
2896         let v: u64 = super::decode("18446744073709551615").unwrap();
2897         assert_eq!(v, u64::MAX);
2898
2899         let v: i64 = super::decode("-9223372036854775808").unwrap();
2900         assert_eq!(v, i64::MIN);
2901
2902         let v: i64 = super::decode("9223372036854775807").unwrap();
2903         assert_eq!(v, i64::MAX);
2904
2905         let res: DecodeResult<i64> = super::decode("765.25252");
2906         assert_eq!(res, Err(ExpectedError("Integer".to_string(),
2907                                           "765.25252".to_string())));
2908     }
2909
2910     #[test]
2911     fn test_read_str() {
2912         assert_eq!(from_str("\""),    Err(SyntaxError(EOFWhileParsingString, 1, 2)));
2913         assert_eq!(from_str("\"lol"), Err(SyntaxError(EOFWhileParsingString, 1, 5)));
2914
2915         assert_eq!(from_str("\"\""), Ok(String("".to_string())));
2916         assert_eq!(from_str("\"foo\""), Ok(String("foo".to_string())));
2917         assert_eq!(from_str("\"\\\"\""), Ok(String("\"".to_string())));
2918         assert_eq!(from_str("\"\\b\""), Ok(String("\x08".to_string())));
2919         assert_eq!(from_str("\"\\n\""), Ok(String("\n".to_string())));
2920         assert_eq!(from_str("\"\\r\""), Ok(String("\r".to_string())));
2921         assert_eq!(from_str("\"\\t\""), Ok(String("\t".to_string())));
2922         assert_eq!(from_str(" \"foo\" "), Ok(String("foo".to_string())));
2923         assert_eq!(from_str("\"\\u12ab\""), Ok(String("\u{12ab}".to_string())));
2924         assert_eq!(from_str("\"\\uAB12\""), Ok(String("\u{AB12}".to_string())));
2925     }
2926
2927     #[test]
2928     fn test_decode_str() {
2929         let s = [("\"\"", ""),
2930                  ("\"foo\"", "foo"),
2931                  ("\"\\\"\"", "\""),
2932                  ("\"\\b\"", "\x08"),
2933                  ("\"\\n\"", "\n"),
2934                  ("\"\\r\"", "\r"),
2935                  ("\"\\t\"", "\t"),
2936                  ("\"\\u12ab\"", "\u{12ab}"),
2937                  ("\"\\uAB12\"", "\u{AB12}")];
2938
2939         for &(i, o) in s.iter() {
2940             let v: string::String = super::decode(i).unwrap();
2941             assert_eq!(v, o);
2942         }
2943     }
2944
2945     #[test]
2946     fn test_read_array() {
2947         assert_eq!(from_str("["),     Err(SyntaxError(EOFWhileParsingValue, 1, 2)));
2948         assert_eq!(from_str("[1"),    Err(SyntaxError(EOFWhileParsingArray, 1, 3)));
2949         assert_eq!(from_str("[1,"),   Err(SyntaxError(EOFWhileParsingValue, 1, 4)));
2950         assert_eq!(from_str("[1,]"),  Err(SyntaxError(InvalidSyntax,        1, 4)));
2951         assert_eq!(from_str("[6 7]"), Err(SyntaxError(InvalidSyntax,        1, 4)));
2952
2953         assert_eq!(from_str("[]"), Ok(Array(vec![])));
2954         assert_eq!(from_str("[ ]"), Ok(Array(vec![])));
2955         assert_eq!(from_str("[true]"), Ok(Array(vec![Boolean(true)])));
2956         assert_eq!(from_str("[ false ]"), Ok(Array(vec![Boolean(false)])));
2957         assert_eq!(from_str("[null]"), Ok(Array(vec![Null])));
2958         assert_eq!(from_str("[3, 1]"),
2959                      Ok(Array(vec![U64(3), U64(1)])));
2960         assert_eq!(from_str("\n[3, 2]\n"),
2961                      Ok(Array(vec![U64(3), U64(2)])));
2962         assert_eq!(from_str("[2, [4, 1]]"),
2963                Ok(Array(vec![U64(2), Array(vec![U64(4), U64(1)])])));
2964     }
2965
2966     #[test]
2967     fn test_decode_array() {
2968         let v: Vec<()> = super::decode("[]").unwrap();
2969         assert_eq!(v, vec![]);
2970
2971         let v: Vec<()> = super::decode("[null]").unwrap();
2972         assert_eq!(v, vec![()]);
2973
2974         let v: Vec<bool> = super::decode("[true]").unwrap();
2975         assert_eq!(v, vec![true]);
2976
2977         let v: Vec<int> = super::decode("[3, 1]").unwrap();
2978         assert_eq!(v, vec![3, 1]);
2979
2980         let v: Vec<Vec<uint>> = super::decode("[[3], [1, 2]]").unwrap();
2981         assert_eq!(v, vec![vec![3], vec![1, 2]]);
2982     }
2983
2984     #[test]
2985     fn test_decode_tuple() {
2986         let t: (uint, uint, uint) = super::decode("[1, 2, 3]").unwrap();
2987         assert_eq!(t, (1u, 2, 3));
2988
2989         let t: (uint, string::String) = super::decode("[1, \"two\"]").unwrap();
2990         assert_eq!(t, (1u, "two".to_string()));
2991     }
2992
2993     #[test]
2994     fn test_decode_tuple_malformed_types() {
2995         assert!(super::decode::<(uint, string::String)>("[1, 2]").is_err());
2996     }
2997
2998     #[test]
2999     fn test_decode_tuple_malformed_length() {
3000         assert!(super::decode::<(uint, uint)>("[1, 2, 3]").is_err());
3001     }
3002
3003     #[test]
3004     fn test_read_object() {
3005         assert_eq!(from_str("{"),       Err(SyntaxError(EOFWhileParsingObject, 1, 2)));
3006         assert_eq!(from_str("{ "),      Err(SyntaxError(EOFWhileParsingObject, 1, 3)));
3007         assert_eq!(from_str("{1"),      Err(SyntaxError(KeyMustBeAString,      1, 2)));
3008         assert_eq!(from_str("{ \"a\""), Err(SyntaxError(EOFWhileParsingObject, 1, 6)));
3009         assert_eq!(from_str("{\"a\""),  Err(SyntaxError(EOFWhileParsingObject, 1, 5)));
3010         assert_eq!(from_str("{\"a\" "), Err(SyntaxError(EOFWhileParsingObject, 1, 6)));
3011
3012         assert_eq!(from_str("{\"a\" 1"),   Err(SyntaxError(ExpectedColon,         1, 6)));
3013         assert_eq!(from_str("{\"a\":"),    Err(SyntaxError(EOFWhileParsingValue,  1, 6)));
3014         assert_eq!(from_str("{\"a\":1"),   Err(SyntaxError(EOFWhileParsingObject, 1, 7)));
3015         assert_eq!(from_str("{\"a\":1 1"), Err(SyntaxError(InvalidSyntax,         1, 8)));
3016         assert_eq!(from_str("{\"a\":1,"),  Err(SyntaxError(EOFWhileParsingObject, 1, 8)));
3017
3018         assert_eq!(from_str("{}").unwrap(), mk_object(&[]));
3019         assert_eq!(from_str("{\"a\": 3}").unwrap(),
3020                   mk_object(&[("a".to_string(), U64(3))]));
3021
3022         assert_eq!(from_str(
3023                       "{ \"a\": null, \"b\" : true }").unwrap(),
3024                   mk_object(&[
3025                       ("a".to_string(), Null),
3026                       ("b".to_string(), Boolean(true))]));
3027         assert_eq!(from_str("\n{ \"a\": null, \"b\" : true }\n").unwrap(),
3028                   mk_object(&[
3029                       ("a".to_string(), Null),
3030                       ("b".to_string(), Boolean(true))]));
3031         assert_eq!(from_str(
3032                       "{\"a\" : 1.0 ,\"b\": [ true ]}").unwrap(),
3033                   mk_object(&[
3034                       ("a".to_string(), F64(1.0)),
3035                       ("b".to_string(), Array(vec![Boolean(true)]))
3036                   ]));
3037         assert_eq!(from_str(
3038                       "{\
3039                           \"a\": 1.0, \
3040                           \"b\": [\
3041                               true,\
3042                               \"foo\\nbar\", \
3043                               { \"c\": {\"d\": null} } \
3044                           ]\
3045                       }").unwrap(),
3046                   mk_object(&[
3047                       ("a".to_string(), F64(1.0)),
3048                       ("b".to_string(), Array(vec![
3049                           Boolean(true),
3050                           String("foo\nbar".to_string()),
3051                           mk_object(&[
3052                               ("c".to_string(), mk_object(&[("d".to_string(), Null)]))
3053                           ])
3054                       ]))
3055                   ]));
3056     }
3057
3058     #[test]
3059     fn test_decode_struct() {
3060         let s = "{
3061             \"inner\": [
3062                 { \"a\": null, \"b\": 2, \"c\": [\"abc\", \"xyz\"] }
3063             ]
3064         }";
3065
3066         let v: Outer = super::decode(s).unwrap();
3067         assert_eq!(
3068             v,
3069             Outer {
3070                 inner: vec![
3071                     Inner { a: (), b: 2, c: vec!["abc".to_string(), "xyz".to_string()] }
3072                 ]
3073             }
3074         );
3075     }
3076
3077     #[derive(RustcDecodable)]
3078     struct FloatStruct {
3079         f: f64,
3080         a: Vec<f64>
3081     }
3082     #[test]
3083     fn test_decode_struct_with_nan() {
3084         let s = "{\"f\":null,\"a\":[null,123]}";
3085         let obj: FloatStruct = super::decode(s).unwrap();
3086         assert!(obj.f.is_nan());
3087         assert!(obj.a[0].is_nan());
3088         assert_eq!(obj.a[1], 123f64);
3089     }
3090
3091     #[test]
3092     fn test_decode_option() {
3093         let value: Option<string::String> = super::decode("null").unwrap();
3094         assert_eq!(value, None);
3095
3096         let value: Option<string::String> = super::decode("\"jodhpurs\"").unwrap();
3097         assert_eq!(value, Some("jodhpurs".to_string()));
3098     }
3099
3100     #[test]
3101     fn test_decode_enum() {
3102         let value: Animal = super::decode("\"Dog\"").unwrap();
3103         assert_eq!(value, Dog);
3104
3105         let s = "{\"variant\":\"Frog\",\"fields\":[\"Henry\",349]}";
3106         let value: Animal = super::decode(s).unwrap();
3107         assert_eq!(value, Frog("Henry".to_string(), 349));
3108     }
3109
3110     #[test]
3111     fn test_decode_map() {
3112         let s = "{\"a\": \"Dog\", \"b\": {\"variant\":\"Frog\",\
3113                   \"fields\":[\"Henry\", 349]}}";
3114         let mut map: BTreeMap<string::String, Animal> = super::decode(s).unwrap();
3115
3116         assert_eq!(map.remove(&"a".to_string()), Some(Dog));
3117         assert_eq!(map.remove(&"b".to_string()), Some(Frog("Henry".to_string(), 349)));
3118     }
3119
3120     #[test]
3121     fn test_multiline_errors() {
3122         assert_eq!(from_str("{\n  \"foo\":\n \"bar\""),
3123             Err(SyntaxError(EOFWhileParsingObject, 3u, 8u)));
3124     }
3125
3126     #[derive(RustcDecodable)]
3127     #[allow(dead_code)]
3128     struct DecodeStruct {
3129         x: f64,
3130         y: bool,
3131         z: string::String,
3132         w: Vec<DecodeStruct>
3133     }
3134     #[derive(RustcDecodable)]
3135     enum DecodeEnum {
3136         A(f64),
3137         B(string::String)
3138     }
3139     fn check_err<T: Decodable>(to_parse: &'static str, expected: DecoderError) {
3140         let res: DecodeResult<T> = match from_str(to_parse) {
3141             Err(e) => Err(ParseError(e)),
3142             Ok(json) => Decodable::decode(&mut Decoder::new(json))
3143         };
3144         match res {
3145             Ok(_) => panic!("`{:?}` parsed & decoded ok, expecting error `{:?}`",
3146                               to_parse, expected),
3147             Err(ParseError(e)) => panic!("`{:?}` is not valid json: {:?}",
3148                                            to_parse, e),
3149             Err(e) => {
3150                 assert_eq!(e, expected);
3151             }
3152         }
3153     }
3154     #[test]
3155     fn test_decode_errors_struct() {
3156         check_err::<DecodeStruct>("[]", ExpectedError("Object".to_string(), "[]".to_string()));
3157         check_err::<DecodeStruct>("{\"x\": true, \"y\": true, \"z\": \"\", \"w\": []}",
3158                                   ExpectedError("Number".to_string(), "true".to_string()));
3159         check_err::<DecodeStruct>("{\"x\": 1, \"y\": [], \"z\": \"\", \"w\": []}",
3160                                   ExpectedError("Boolean".to_string(), "[]".to_string()));
3161         check_err::<DecodeStruct>("{\"x\": 1, \"y\": true, \"z\": {}, \"w\": []}",
3162                                   ExpectedError("String".to_string(), "{}".to_string()));
3163         check_err::<DecodeStruct>("{\"x\": 1, \"y\": true, \"z\": \"\", \"w\": null}",
3164                                   ExpectedError("Array".to_string(), "null".to_string()));
3165         check_err::<DecodeStruct>("{\"x\": 1, \"y\": true, \"z\": \"\"}",
3166                                   MissingFieldError("w".to_string()));
3167     }
3168     #[test]
3169     fn test_decode_errors_enum() {
3170         check_err::<DecodeEnum>("{}",
3171                                 MissingFieldError("variant".to_string()));
3172         check_err::<DecodeEnum>("{\"variant\": 1}",
3173                                 ExpectedError("String".to_string(), "1".to_string()));
3174         check_err::<DecodeEnum>("{\"variant\": \"A\"}",
3175                                 MissingFieldError("fields".to_string()));
3176         check_err::<DecodeEnum>("{\"variant\": \"A\", \"fields\": null}",
3177                                 ExpectedError("Array".to_string(), "null".to_string()));
3178         check_err::<DecodeEnum>("{\"variant\": \"C\", \"fields\": []}",
3179                                 UnknownVariantError("C".to_string()));
3180     }
3181
3182     #[test]
3183     fn test_find(){
3184         let json_value = from_str("{\"dog\" : \"cat\"}").unwrap();
3185         let found_str = json_value.find("dog");
3186         assert!(found_str.unwrap().as_string().unwrap() == "cat");
3187     }
3188
3189     #[test]
3190     fn test_find_path(){
3191         let json_value = from_str("{\"dog\":{\"cat\": {\"mouse\" : \"cheese\"}}}").unwrap();
3192         let found_str = json_value.find_path(&["dog", "cat", "mouse"]);
3193         assert!(found_str.unwrap().as_string().unwrap() == "cheese");
3194     }
3195
3196     #[test]
3197     fn test_search(){
3198         let json_value = from_str("{\"dog\":{\"cat\": {\"mouse\" : \"cheese\"}}}").unwrap();
3199         let found_str = json_value.search("mouse").and_then(|j| j.as_string());
3200         assert!(found_str.unwrap() == "cheese");
3201     }
3202
3203     #[test]
3204     fn test_index(){
3205         let json_value = from_str("{\"animals\":[\"dog\",\"cat\",\"mouse\"]}").unwrap();
3206         let ref array = json_value["animals"];
3207         assert_eq!(array[0].as_string().unwrap(), "dog");
3208         assert_eq!(array[1].as_string().unwrap(), "cat");
3209         assert_eq!(array[2].as_string().unwrap(), "mouse");
3210     }
3211
3212     #[test]
3213     fn test_is_object(){
3214         let json_value = from_str("{}").unwrap();
3215         assert!(json_value.is_object());
3216     }
3217
3218     #[test]
3219     fn test_as_object(){
3220         let json_value = from_str("{}").unwrap();
3221         let json_object = json_value.as_object();
3222         assert!(json_object.is_some());
3223     }
3224
3225     #[test]
3226     fn test_is_array(){
3227         let json_value = from_str("[1, 2, 3]").unwrap();
3228         assert!(json_value.is_array());
3229     }
3230
3231     #[test]
3232     fn test_as_array(){
3233         let json_value = from_str("[1, 2, 3]").unwrap();
3234         let json_array = json_value.as_array();
3235         let expected_length = 3;
3236         assert!(json_array.is_some() && json_array.unwrap().len() == expected_length);
3237     }
3238
3239     #[test]
3240     fn test_is_string(){
3241         let json_value = from_str("\"dog\"").unwrap();
3242         assert!(json_value.is_string());
3243     }
3244
3245     #[test]
3246     fn test_as_string(){
3247         let json_value = from_str("\"dog\"").unwrap();
3248         let json_str = json_value.as_string();
3249         let expected_str = "dog";
3250         assert_eq!(json_str, Some(expected_str));
3251     }
3252
3253     #[test]
3254     fn test_is_number(){
3255         let json_value = from_str("12").unwrap();
3256         assert!(json_value.is_number());
3257     }
3258
3259     #[test]
3260     fn test_is_i64(){
3261         let json_value = from_str("-12").unwrap();
3262         assert!(json_value.is_i64());
3263
3264         let json_value = from_str("12").unwrap();
3265         assert!(!json_value.is_i64());
3266
3267         let json_value = from_str("12.0").unwrap();
3268         assert!(!json_value.is_i64());
3269     }
3270
3271     #[test]
3272     fn test_is_u64(){
3273         let json_value = from_str("12").unwrap();
3274         assert!(json_value.is_u64());
3275
3276         let json_value = from_str("-12").unwrap();
3277         assert!(!json_value.is_u64());
3278
3279         let json_value = from_str("12.0").unwrap();
3280         assert!(!json_value.is_u64());
3281     }
3282
3283     #[test]
3284     fn test_is_f64(){
3285         let json_value = from_str("12").unwrap();
3286         assert!(!json_value.is_f64());
3287
3288         let json_value = from_str("-12").unwrap();
3289         assert!(!json_value.is_f64());
3290
3291         let json_value = from_str("12.0").unwrap();
3292         assert!(json_value.is_f64());
3293
3294         let json_value = from_str("-12.0").unwrap();
3295         assert!(json_value.is_f64());
3296     }
3297
3298     #[test]
3299     fn test_as_i64(){
3300         let json_value = from_str("-12").unwrap();
3301         let json_num = json_value.as_i64();
3302         assert_eq!(json_num, Some(-12));
3303     }
3304
3305     #[test]
3306     fn test_as_u64(){
3307         let json_value = from_str("12").unwrap();
3308         let json_num = json_value.as_u64();
3309         assert_eq!(json_num, Some(12));
3310     }
3311
3312     #[test]
3313     fn test_as_f64(){
3314         let json_value = from_str("12.0").unwrap();
3315         let json_num = json_value.as_f64();
3316         assert_eq!(json_num, Some(12f64));
3317     }
3318
3319     #[test]
3320     fn test_is_boolean(){
3321         let json_value = from_str("false").unwrap();
3322         assert!(json_value.is_boolean());
3323     }
3324
3325     #[test]
3326     fn test_as_boolean(){
3327         let json_value = from_str("false").unwrap();
3328         let json_bool = json_value.as_boolean();
3329         let expected_bool = false;
3330         assert!(json_bool.is_some() && json_bool.unwrap() == expected_bool);
3331     }
3332
3333     #[test]
3334     fn test_is_null(){
3335         let json_value = from_str("null").unwrap();
3336         assert!(json_value.is_null());
3337     }
3338
3339     #[test]
3340     fn test_as_null(){
3341         let json_value = from_str("null").unwrap();
3342         let json_null = json_value.as_null();
3343         let expected_null = ();
3344         assert!(json_null.is_some() && json_null.unwrap() == expected_null);
3345     }
3346
3347     #[test]
3348     fn test_encode_hashmap_with_numeric_key() {
3349         use std::str::from_utf8;
3350         use std::io::Writer;
3351         use std::collections::HashMap;
3352         let mut hm: HashMap<uint, bool> = HashMap::new();
3353         hm.insert(1, true);
3354         let mut mem_buf = Vec::new();
3355         write!(&mut mem_buf, "{}", super::as_pretty_json(&hm)).unwrap();
3356         let json_str = from_utf8(mem_buf.index(&FullRange)).unwrap();
3357         match from_str(json_str) {
3358             Err(_) => panic!("Unable to parse json_str: {:?}", json_str),
3359             _ => {} // it parsed and we are good to go
3360         }
3361     }
3362
3363     #[test]
3364     fn test_prettyencode_hashmap_with_numeric_key() {
3365         use std::str::from_utf8;
3366         use std::io::Writer;
3367         use std::collections::HashMap;
3368         let mut hm: HashMap<uint, bool> = HashMap::new();
3369         hm.insert(1, true);
3370         let mut mem_buf = Vec::new();
3371         write!(&mut mem_buf, "{}", super::as_pretty_json(&hm)).unwrap();
3372         let json_str = from_utf8(mem_buf.index(&FullRange)).unwrap();
3373         match from_str(json_str) {
3374             Err(_) => panic!("Unable to parse json_str: {:?}", json_str),
3375             _ => {} // it parsed and we are good to go
3376         }
3377     }
3378
3379     #[test]
3380     fn test_prettyencoder_indent_level_param() {
3381         use std::str::from_utf8;
3382         use std::collections::BTreeMap;
3383
3384         let mut tree = BTreeMap::new();
3385
3386         tree.insert("hello".to_string(), String("guten tag".to_string()));
3387         tree.insert("goodbye".to_string(), String("sayonara".to_string()));
3388
3389         let json = Array(
3390             // The following layout below should look a lot like
3391             // the pretty-printed JSON (indent * x)
3392             vec!
3393             ( // 0x
3394                 String("greetings".to_string()), // 1x
3395                 Object(tree), // 1x + 2x + 2x + 1x
3396             ) // 0x
3397             // End JSON array (7 lines)
3398         );
3399
3400         // Helper function for counting indents
3401         fn indents(source: &str) -> uint {
3402             let trimmed = source.trim_left_matches(' ');
3403             source.len() - trimmed.len()
3404         }
3405
3406         // Test up to 4 spaces of indents (more?)
3407         for i in range(0, 4u) {
3408             let mut writer = Vec::new();
3409             write!(&mut writer, "{}",
3410                    super::as_pretty_json(&json).indent(i)).unwrap();
3411
3412             let printed = from_utf8(writer.index(&FullRange)).unwrap();
3413
3414             // Check for indents at each line
3415             let lines: Vec<&str> = printed.lines().collect();
3416             assert_eq!(lines.len(), 7); // JSON should be 7 lines
3417
3418             assert_eq!(indents(lines[0]), 0 * i); // [
3419             assert_eq!(indents(lines[1]), 1 * i); //   "greetings",
3420             assert_eq!(indents(lines[2]), 1 * i); //   {
3421             assert_eq!(indents(lines[3]), 2 * i); //     "hello": "guten tag",
3422             assert_eq!(indents(lines[4]), 2 * i); //     "goodbye": "sayonara"
3423             assert_eq!(indents(lines[5]), 1 * i); //   },
3424             assert_eq!(indents(lines[6]), 0 * i); // ]
3425
3426             // Finally, test that the pretty-printed JSON is valid
3427             from_str(printed).ok().expect("Pretty-printed JSON is invalid!");
3428         }
3429     }
3430
3431     #[test]
3432     fn test_hashmap_with_numeric_key_can_handle_double_quote_delimited_key() {
3433         use std::collections::HashMap;
3434         use Decodable;
3435         let json_str = "{\"1\":true}";
3436         let json_obj = match from_str(json_str) {
3437             Err(_) => panic!("Unable to parse json_str: {:?}", json_str),
3438             Ok(o) => o
3439         };
3440         let mut decoder = Decoder::new(json_obj);
3441         let _hm: HashMap<uint, bool> = Decodable::decode(&mut decoder).unwrap();
3442     }
3443
3444     #[test]
3445     fn test_hashmap_with_numeric_key_will_error_with_string_keys() {
3446         use std::collections::HashMap;
3447         use Decodable;
3448         let json_str = "{\"a\":true}";
3449         let json_obj = match from_str(json_str) {
3450             Err(_) => panic!("Unable to parse json_str: {:?}", json_str),
3451             Ok(o) => o
3452         };
3453         let mut decoder = Decoder::new(json_obj);
3454         let result: Result<HashMap<uint, bool>, DecoderError> = Decodable::decode(&mut decoder);
3455         assert_eq!(result, Err(ExpectedError("Number".to_string(), "a".to_string())));
3456     }
3457
3458     fn assert_stream_equal(src: &str,
3459                            expected: Vec<(JsonEvent, Vec<StackElement>)>) {
3460         let mut parser = Parser::new(src.chars());
3461         let mut i = 0;
3462         loop {
3463             let evt = match parser.next() {
3464                 Some(e) => e,
3465                 None => { break; }
3466             };
3467             let (ref expected_evt, ref expected_stack) = expected[i];
3468             if !parser.stack().is_equal_to(expected_stack.as_slice()) {
3469                 panic!("Parser stack is not equal to {:?}", expected_stack);
3470             }
3471             assert_eq!(&evt, expected_evt);
3472             i+=1;
3473         }
3474     }
3475     #[test]
3476     #[cfg_attr(target_pointer_width = "32", ignore)] // FIXME(#14064)
3477     fn test_streaming_parser() {
3478         assert_stream_equal(
3479             r#"{ "foo":"bar", "array" : [0, 1, 2, 3, 4, 5], "idents":[null,true,false]}"#,
3480             vec![
3481                 (ObjectStart,             vec![]),
3482                   (StringValue("bar".to_string()),   vec![StackElement::Key("foo")]),
3483                   (ArrayStart,            vec![StackElement::Key("array")]),
3484                     (U64Value(0),         vec![StackElement::Key("array"), StackElement::Index(0)]),
3485                     (U64Value(1),         vec![StackElement::Key("array"), StackElement::Index(1)]),
3486                     (U64Value(2),         vec![StackElement::Key("array"), StackElement::Index(2)]),
3487                     (U64Value(3),         vec![StackElement::Key("array"), StackElement::Index(3)]),
3488                     (U64Value(4),         vec![StackElement::Key("array"), StackElement::Index(4)]),
3489                     (U64Value(5),         vec![StackElement::Key("array"), StackElement::Index(5)]),
3490                   (ArrayEnd,              vec![StackElement::Key("array")]),
3491                   (ArrayStart,            vec![StackElement::Key("idents")]),
3492                     (NullValue,           vec![StackElement::Key("idents"),
3493                                                StackElement::Index(0)]),
3494                     (BooleanValue(true),  vec![StackElement::Key("idents"),
3495                                                StackElement::Index(1)]),
3496                     (BooleanValue(false), vec![StackElement::Key("idents"),
3497                                                StackElement::Index(2)]),
3498                   (ArrayEnd,              vec![StackElement::Key("idents")]),
3499                 (ObjectEnd,               vec![]),
3500             ]
3501         );
3502     }
3503     fn last_event(src: &str) -> JsonEvent {
3504         let mut parser = Parser::new(src.chars());
3505         let mut evt = NullValue;
3506         loop {
3507             evt = match parser.next() {
3508                 Some(e) => e,
3509                 None => return evt,
3510             }
3511         }
3512     }
3513
3514     #[test]
3515     #[cfg_attr(target_pointer_width = "32", ignore)] // FIXME(#14064)
3516     fn test_read_object_streaming() {
3517         assert_eq!(last_event("{ "),      Error(SyntaxError(EOFWhileParsingObject, 1, 3)));
3518         assert_eq!(last_event("{1"),      Error(SyntaxError(KeyMustBeAString,      1, 2)));
3519         assert_eq!(last_event("{ \"a\""), Error(SyntaxError(EOFWhileParsingObject, 1, 6)));
3520         assert_eq!(last_event("{\"a\""),  Error(SyntaxError(EOFWhileParsingObject, 1, 5)));
3521         assert_eq!(last_event("{\"a\" "), Error(SyntaxError(EOFWhileParsingObject, 1, 6)));
3522
3523         assert_eq!(last_event("{\"a\" 1"),   Error(SyntaxError(ExpectedColon,         1, 6)));
3524         assert_eq!(last_event("{\"a\":"),    Error(SyntaxError(EOFWhileParsingValue,  1, 6)));
3525         assert_eq!(last_event("{\"a\":1"),   Error(SyntaxError(EOFWhileParsingObject, 1, 7)));
3526         assert_eq!(last_event("{\"a\":1 1"), Error(SyntaxError(InvalidSyntax,         1, 8)));
3527         assert_eq!(last_event("{\"a\":1,"),  Error(SyntaxError(EOFWhileParsingObject, 1, 8)));
3528         assert_eq!(last_event("{\"a\":1,}"), Error(SyntaxError(TrailingComma, 1, 8)));
3529
3530         assert_stream_equal(
3531             "{}",
3532             vec![(ObjectStart, vec![]), (ObjectEnd, vec![])]
3533         );
3534         assert_stream_equal(
3535             "{\"a\": 3}",
3536             vec![
3537                 (ObjectStart,        vec![]),
3538                   (U64Value(3),      vec![StackElement::Key("a")]),
3539                 (ObjectEnd,          vec![]),
3540             ]
3541         );
3542         assert_stream_equal(
3543             "{ \"a\": null, \"b\" : true }",
3544             vec![
3545                 (ObjectStart,           vec![]),
3546                   (NullValue,           vec![StackElement::Key("a")]),
3547                   (BooleanValue(true),  vec![StackElement::Key("b")]),
3548                 (ObjectEnd,             vec![]),
3549             ]
3550         );
3551         assert_stream_equal(
3552             "{\"a\" : 1.0 ,\"b\": [ true ]}",
3553             vec![
3554                 (ObjectStart,           vec![]),
3555                   (F64Value(1.0),       vec![StackElement::Key("a")]),
3556                   (ArrayStart,          vec![StackElement::Key("b")]),
3557                     (BooleanValue(true),vec![StackElement::Key("b"), StackElement::Index(0)]),
3558                   (ArrayEnd,            vec![StackElement::Key("b")]),
3559                 (ObjectEnd,             vec![]),
3560             ]
3561         );
3562         assert_stream_equal(
3563             r#"{
3564                 "a": 1.0,
3565                 "b": [
3566                     true,
3567                     "foo\nbar",
3568                     { "c": {"d": null} }
3569                 ]
3570             }"#,
3571             vec![
3572                 (ObjectStart,                   vec![]),
3573                   (F64Value(1.0),               vec![StackElement::Key("a")]),
3574                   (ArrayStart,                  vec![StackElement::Key("b")]),
3575                     (BooleanValue(true),        vec![StackElement::Key("b"),
3576                                                      StackElement::Index(0)]),
3577                     (StringValue("foo\nbar".to_string()),  vec![StackElement::Key("b"),
3578                                                                 StackElement::Index(1)]),
3579                     (ObjectStart,               vec![StackElement::Key("b"),
3580                                                      StackElement::Index(2)]),
3581                       (ObjectStart,             vec![StackElement::Key("b"),
3582                                                      StackElement::Index(2),
3583                                                      StackElement::Key("c")]),
3584                         (NullValue,             vec![StackElement::Key("b"),
3585                                                      StackElement::Index(2),
3586                                                      StackElement::Key("c"),
3587                                                      StackElement::Key("d")]),
3588                       (ObjectEnd,               vec![StackElement::Key("b"),
3589                                                      StackElement::Index(2),
3590                                                      StackElement::Key("c")]),
3591                     (ObjectEnd,                 vec![StackElement::Key("b"),
3592                                                      StackElement::Index(2)]),
3593                   (ArrayEnd,                    vec![StackElement::Key("b")]),
3594                 (ObjectEnd,                     vec![]),
3595             ]
3596         );
3597     }
3598     #[test]
3599     #[cfg_attr(target_pointer_width = "32", ignore)] // FIXME(#14064)
3600     fn test_read_array_streaming() {
3601         assert_stream_equal(
3602             "[]",
3603             vec![
3604                 (ArrayStart, vec![]),
3605                 (ArrayEnd,   vec![]),
3606             ]
3607         );
3608         assert_stream_equal(
3609             "[ ]",
3610             vec![
3611                 (ArrayStart, vec![]),
3612                 (ArrayEnd,   vec![]),
3613             ]
3614         );
3615         assert_stream_equal(
3616             "[true]",
3617             vec![
3618                 (ArrayStart,             vec![]),
3619                     (BooleanValue(true), vec![StackElement::Index(0)]),
3620                 (ArrayEnd,               vec![]),
3621             ]
3622         );
3623         assert_stream_equal(
3624             "[ false ]",
3625             vec![
3626                 (ArrayStart,              vec![]),
3627                     (BooleanValue(false), vec![StackElement::Index(0)]),
3628                 (ArrayEnd,                vec![]),
3629             ]
3630         );
3631         assert_stream_equal(
3632             "[null]",
3633             vec![
3634                 (ArrayStart,    vec![]),
3635                     (NullValue, vec![StackElement::Index(0)]),
3636                 (ArrayEnd,      vec![]),
3637             ]
3638         );
3639         assert_stream_equal(
3640             "[3, 1]",
3641             vec![
3642                 (ArrayStart,      vec![]),
3643                     (U64Value(3), vec![StackElement::Index(0)]),
3644                     (U64Value(1), vec![StackElement::Index(1)]),
3645                 (ArrayEnd,        vec![]),
3646             ]
3647         );
3648         assert_stream_equal(
3649             "\n[3, 2]\n",
3650             vec![
3651                 (ArrayStart,      vec![]),
3652                     (U64Value(3), vec![StackElement::Index(0)]),
3653                     (U64Value(2), vec![StackElement::Index(1)]),
3654                 (ArrayEnd,        vec![]),
3655             ]
3656         );
3657         assert_stream_equal(
3658             "[2, [4, 1]]",
3659             vec![
3660                 (ArrayStart,           vec![]),
3661                     (U64Value(2),      vec![StackElement::Index(0)]),
3662                     (ArrayStart,       vec![StackElement::Index(1)]),
3663                         (U64Value(4),  vec![StackElement::Index(1), StackElement::Index(0)]),
3664                         (U64Value(1),  vec![StackElement::Index(1), StackElement::Index(1)]),
3665                     (ArrayEnd,         vec![StackElement::Index(1)]),
3666                 (ArrayEnd,             vec![]),
3667             ]
3668         );
3669
3670         assert_eq!(last_event("["), Error(SyntaxError(EOFWhileParsingValue, 1,  2)));
3671
3672         assert_eq!(from_str("["),     Err(SyntaxError(EOFWhileParsingValue, 1, 2)));
3673         assert_eq!(from_str("[1"),    Err(SyntaxError(EOFWhileParsingArray, 1, 3)));
3674         assert_eq!(from_str("[1,"),   Err(SyntaxError(EOFWhileParsingValue, 1, 4)));
3675         assert_eq!(from_str("[1,]"),  Err(SyntaxError(InvalidSyntax,        1, 4)));
3676         assert_eq!(from_str("[6 7]"), Err(SyntaxError(InvalidSyntax,        1, 4)));
3677
3678     }
3679     #[test]
3680     fn test_trailing_characters_streaming() {
3681         assert_eq!(last_event("nulla"),  Error(SyntaxError(TrailingCharacters, 1, 5)));
3682         assert_eq!(last_event("truea"),  Error(SyntaxError(TrailingCharacters, 1, 5)));
3683         assert_eq!(last_event("falsea"), Error(SyntaxError(TrailingCharacters, 1, 6)));
3684         assert_eq!(last_event("1a"),     Error(SyntaxError(TrailingCharacters, 1, 2)));
3685         assert_eq!(last_event("[]a"),    Error(SyntaxError(TrailingCharacters, 1, 3)));
3686         assert_eq!(last_event("{}a"),    Error(SyntaxError(TrailingCharacters, 1, 3)));
3687     }
3688     #[test]
3689     fn test_read_identifiers_streaming() {
3690         assert_eq!(Parser::new("null".chars()).next(), Some(NullValue));
3691         assert_eq!(Parser::new("true".chars()).next(), Some(BooleanValue(true)));
3692         assert_eq!(Parser::new("false".chars()).next(), Some(BooleanValue(false)));
3693
3694         assert_eq!(last_event("n"),    Error(SyntaxError(InvalidSyntax, 1, 2)));
3695         assert_eq!(last_event("nul"),  Error(SyntaxError(InvalidSyntax, 1, 4)));
3696         assert_eq!(last_event("t"),    Error(SyntaxError(InvalidSyntax, 1, 2)));
3697         assert_eq!(last_event("truz"), Error(SyntaxError(InvalidSyntax, 1, 4)));
3698         assert_eq!(last_event("f"),    Error(SyntaxError(InvalidSyntax, 1, 2)));
3699         assert_eq!(last_event("faz"),  Error(SyntaxError(InvalidSyntax, 1, 3)));
3700     }
3701
3702     #[test]
3703     fn test_stack() {
3704         let mut stack = Stack::new();
3705
3706         assert!(stack.is_empty());
3707         assert!(stack.len() == 0);
3708         assert!(!stack.last_is_index());
3709
3710         stack.push_index(0);
3711         stack.bump_index();
3712
3713         assert!(stack.len() == 1);
3714         assert!(stack.is_equal_to(&[StackElement::Index(1)]));
3715         assert!(stack.starts_with(&[StackElement::Index(1)]));
3716         assert!(stack.ends_with(&[StackElement::Index(1)]));
3717         assert!(stack.last_is_index());
3718         assert!(stack.get(0) == StackElement::Index(1));
3719
3720         stack.push_key("foo".to_string());
3721
3722         assert!(stack.len() == 2);
3723         assert!(stack.is_equal_to(&[StackElement::Index(1), StackElement::Key("foo")]));
3724         assert!(stack.starts_with(&[StackElement::Index(1), StackElement::Key("foo")]));
3725         assert!(stack.starts_with(&[StackElement::Index(1)]));
3726         assert!(stack.ends_with(&[StackElement::Index(1), StackElement::Key("foo")]));
3727         assert!(stack.ends_with(&[StackElement::Key("foo")]));
3728         assert!(!stack.last_is_index());
3729         assert!(stack.get(0) == StackElement::Index(1));
3730         assert!(stack.get(1) == StackElement::Key("foo"));
3731
3732         stack.push_key("bar".to_string());
3733
3734         assert!(stack.len() == 3);
3735         assert!(stack.is_equal_to(&[StackElement::Index(1),
3736                                     StackElement::Key("foo"),
3737                                     StackElement::Key("bar")]));
3738         assert!(stack.starts_with(&[StackElement::Index(1)]));
3739         assert!(stack.starts_with(&[StackElement::Index(1), StackElement::Key("foo")]));
3740         assert!(stack.starts_with(&[StackElement::Index(1),
3741                                     StackElement::Key("foo"),
3742                                     StackElement::Key("bar")]));
3743         assert!(stack.ends_with(&[StackElement::Key("bar")]));
3744         assert!(stack.ends_with(&[StackElement::Key("foo"), StackElement::Key("bar")]));
3745         assert!(stack.ends_with(&[StackElement::Index(1),
3746                                   StackElement::Key("foo"),
3747                                   StackElement::Key("bar")]));
3748         assert!(!stack.last_is_index());
3749         assert!(stack.get(0) == StackElement::Index(1));
3750         assert!(stack.get(1) == StackElement::Key("foo"));
3751         assert!(stack.get(2) == StackElement::Key("bar"));
3752
3753         stack.pop();
3754
3755         assert!(stack.len() == 2);
3756         assert!(stack.is_equal_to(&[StackElement::Index(1), StackElement::Key("foo")]));
3757         assert!(stack.starts_with(&[StackElement::Index(1), StackElement::Key("foo")]));
3758         assert!(stack.starts_with(&[StackElement::Index(1)]));
3759         assert!(stack.ends_with(&[StackElement::Index(1), StackElement::Key("foo")]));
3760         assert!(stack.ends_with(&[StackElement::Key("foo")]));
3761         assert!(!stack.last_is_index());
3762         assert!(stack.get(0) == StackElement::Index(1));
3763         assert!(stack.get(1) == StackElement::Key("foo"));
3764     }
3765
3766     #[test]
3767     fn test_to_json() {
3768         use std::collections::{HashMap,BTreeMap};
3769         use super::ToJson;
3770
3771         let array2 = Array(vec!(U64(1), U64(2)));
3772         let array3 = Array(vec!(U64(1), U64(2), U64(3)));
3773         let object = {
3774             let mut tree_map = BTreeMap::new();
3775             tree_map.insert("a".to_string(), U64(1));
3776             tree_map.insert("b".to_string(), U64(2));
3777             Object(tree_map)
3778         };
3779
3780         assert_eq!(array2.to_json(), array2);
3781         assert_eq!(object.to_json(), object);
3782         assert_eq!(3_i.to_json(), I64(3));
3783         assert_eq!(4_i8.to_json(), I64(4));
3784         assert_eq!(5_i16.to_json(), I64(5));
3785         assert_eq!(6_i32.to_json(), I64(6));
3786         assert_eq!(7_i64.to_json(), I64(7));
3787         assert_eq!(8_u.to_json(), U64(8));
3788         assert_eq!(9_u8.to_json(), U64(9));
3789         assert_eq!(10_u16.to_json(), U64(10));
3790         assert_eq!(11_u32.to_json(), U64(11));
3791         assert_eq!(12_u64.to_json(), U64(12));
3792         assert_eq!(13.0_f32.to_json(), F64(13.0_f64));
3793         assert_eq!(14.0_f64.to_json(), F64(14.0_f64));
3794         assert_eq!(().to_json(), Null);
3795         assert_eq!(f32::INFINITY.to_json(), Null);
3796         assert_eq!(f64::NAN.to_json(), Null);
3797         assert_eq!(true.to_json(), Boolean(true));
3798         assert_eq!(false.to_json(), Boolean(false));
3799         assert_eq!("abc".to_json(), String("abc".to_string()));
3800         assert_eq!("abc".to_string().to_json(), String("abc".to_string()));
3801         assert_eq!((1u, 2u).to_json(), array2);
3802         assert_eq!((1u, 2u, 3u).to_json(), array3);
3803         assert_eq!([1u, 2].to_json(), array2);
3804         assert_eq!((&[1u, 2, 3]).to_json(), array3);
3805         assert_eq!((vec![1u, 2]).to_json(), array2);
3806         assert_eq!(vec!(1u, 2, 3).to_json(), array3);
3807         let mut tree_map = BTreeMap::new();
3808         tree_map.insert("a".to_string(), 1u);
3809         tree_map.insert("b".to_string(), 2);
3810         assert_eq!(tree_map.to_json(), object);
3811         let mut hash_map = HashMap::new();
3812         hash_map.insert("a".to_string(), 1u);
3813         hash_map.insert("b".to_string(), 2);
3814         assert_eq!(hash_map.to_json(), object);
3815         assert_eq!(Some(15i).to_json(), I64(15));
3816         assert_eq!(Some(15u).to_json(), U64(15));
3817         assert_eq!(None::<int>.to_json(), Null);
3818     }
3819
3820     #[bench]
3821     fn bench_streaming_small(b: &mut Bencher) {
3822         b.iter( || {
3823             let mut parser = Parser::new(
3824                 r#"{
3825                     "a": 1.0,
3826                     "b": [
3827                         true,
3828                         "foo\nbar",
3829                         { "c": {"d": null} }
3830                     ]
3831                 }"#.chars()
3832             );
3833             loop {
3834                 match parser.next() {
3835                     None => return,
3836                     _ => {}
3837                 }
3838             }
3839         });
3840     }
3841     #[bench]
3842     fn bench_small(b: &mut Bencher) {
3843         b.iter( || {
3844             let _ = from_str(r#"{
3845                 "a": 1.0,
3846                 "b": [
3847                     true,
3848                     "foo\nbar",
3849                     { "c": {"d": null} }
3850                 ]
3851             }"#);
3852         });
3853     }
3854
3855     fn big_json() -> string::String {
3856         let mut src = "[\n".to_string();
3857         for _ in range(0i, 500) {
3858             src.push_str(r#"{ "a": true, "b": null, "c":3.1415, "d": "Hello world", "e": \
3859                             [1,2,3]},"#);
3860         }
3861         src.push_str("{}]");
3862         return src;
3863     }
3864
3865     #[bench]
3866     fn bench_streaming_large(b: &mut Bencher) {
3867         let src = big_json();
3868         b.iter( || {
3869             let mut parser = Parser::new(src.chars());
3870             loop {
3871                 match parser.next() {
3872                     None => return,
3873                     _ => {}
3874                 }
3875             }
3876         });
3877     }
3878     #[bench]
3879     fn bench_large(b: &mut Bencher) {
3880         let src = big_json();
3881         b.iter( || { let _ = from_str(src.as_slice()); });
3882     }
3883 }