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