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