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