]> git.lizzy.rs Git - rust.git/blob - src/libserialize/json.rs
93a5e2ec4c8b15a1a9be4050a924906c48c51c1b
[rust.git] / src / libserialize / json.rs
1 // Copyright 2012-2013 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 one to encode structured data in a text format that can be read by humans easily.
24 Its native compatibility with JavaScript and its simple syntax make it used widely.
25
26 Json data are encoded in a form of "key":"value".
27 Data types that can be encoded are JavaScript types :
28 boolean (`true` or `false`), number (`f64`), string, array, object, null.
29 An object is a series of string keys mapping to values, in `"key": value` format.
30 Arrays are enclosed in square brackets ([ ... ]) and objects in curly brackets ({ ... }).
31 A simple JSON document encoding a person, his/her age, address and phone numbers could look like:
32
33 ```ignore
34 {
35     "FirstName": "John",
36     "LastName": "Doe",
37     "Age": 43,
38     "Address": {
39         "Street": "Downing Street 10",
40         "City": "London",
41         "Country": "Great Britain"
42     },
43     "PhoneNumbers": [
44         "+44 1234567",
45         "+44 2345678"
46     ]
47 }
48 ```
49
50 # Rust Type-based Encoding and Decoding
51
52 Rust provides a mechanism for low boilerplate encoding & decoding
53 of values to and from JSON via the serialization API.
54 To be able to encode a piece of data, it must implement the `serialize::Encodable` trait.
55 To be able to decode a piece of data, it must implement the `serialize::Decodable` trait.
56 The Rust compiler provides an annotation to automatically generate
57 the code for these traits: `#[deriving(Decodable, Encodable)]`
58
59 To encode using Encodable :
60
61 ```rust
62 use std::io;
63 use serialize::{json, Encodable};
64
65  #[deriving(Encodable)]
66  pub struct TestStruct   {
67     data_str: ~str,
68  }
69
70 fn main() {
71     let to_encode_object = TestStruct{data_str:"example of string to encode".to_owned()};
72     let mut m = io::MemWriter::new();
73     {
74         let mut encoder = json::Encoder::new(&mut m as &mut std::io::Writer);
75         match to_encode_object.encode(&mut encoder) {
76             Ok(()) => (),
77             Err(e) => fail!("json encoding error: {}", e)
78         };
79     }
80 }
81 ```
82
83 Two wrapper functions are provided to encode a Encodable object
84 into a string (~str) or buffer (~[u8]): `str_encode(&m)` and `buffer_encode(&m)`.
85
86 ```rust
87 use serialize::json;
88 let to_encode_object = "example of string to encode".to_owned();
89 let encoded_str: ~str = json::Encoder::str_encode(&to_encode_object);
90 ```
91
92 JSON API provide an enum `json::Json` and a trait `ToJson` to encode object.
93 The trait `ToJson` encode object into a container `json::Json` and the API provide writer
94 to encode them into a stream or a string ...
95
96 When using `ToJson` the `Encodable` trait implementation is not mandatory.
97
98 A basic `ToJson` example using a TreeMap of attribute name / attribute value:
99
100
101 ```rust
102 extern crate collections;
103 extern crate serialize;
104
105 use serialize::json;
106 use serialize::json::ToJson;
107 use collections::TreeMap;
108
109 pub struct MyStruct  {
110     attr1: u8,
111     attr2: ~str,
112 }
113
114 impl ToJson for MyStruct {
115     fn to_json( &self ) -> json::Json {
116         let mut d = ~TreeMap::new();
117         d.insert("attr1".to_owned(), self.attr1.to_json());
118         d.insert("attr2".to_owned(), self.attr2.to_json());
119         json::Object(d)
120     }
121 }
122
123 fn main() {
124     let test2: MyStruct = MyStruct {attr1: 1, attr2:"test".to_owned()};
125     let tjson: json::Json = test2.to_json();
126     let json_str: ~str = tjson.to_str();
127 }
128 ```
129
130 To decode a JSON string using `Decodable` trait :
131
132 ```rust
133 extern crate serialize;
134 use serialize::{json, Decodable};
135
136 #[deriving(Decodable)]
137 pub struct MyStruct  {
138      attr1: u8,
139      attr2: ~str,
140 }
141
142 fn main() {
143     let json_str_to_decode: ~str =
144             "{\"attr1\":1,\"attr2\":\"toto\"}".to_owned();
145     let json_object = json::from_str(json_str_to_decode);
146     let mut decoder = json::Decoder::new(json_object.unwrap());
147     let decoded_object: MyStruct = match Decodable::decode(&mut decoder) {
148         Ok(v) => v,
149         Err(e) => fail!("Decoding error: {}", e)
150     }; // create the final object
151 }
152 ```
153
154 # Examples of use
155
156 ## Using Autoserialization
157
158 Create a struct called TestStruct1 and serialize and deserialize it to and from JSON
159 using the serialization API, using the derived serialization code.
160
161 ```rust
162 extern crate serialize;
163 use serialize::{json, Encodable, Decodable};
164
165  #[deriving(Decodable, Encodable)] //generate Decodable, Encodable impl.
166  pub struct TestStruct1  {
167     data_int: u8,
168     data_str: ~str,
169     data_vector: ~[u8],
170  }
171
172 // To serialize use the `json::str_encode` to encode an object in a string.
173 // It calls the generated `Encodable` impl.
174 fn main() {
175     let to_encode_object = TestStruct1
176          {data_int: 1, data_str:"toto".to_owned(), data_vector:~[2,3,4,5]};
177     let encoded_str: ~str = json::Encoder::str_encode(&to_encode_object);
178
179     // To deserialize use the `json::from_str` and `json::Decoder`
180
181     let json_object = json::from_str(encoded_str);
182     let mut decoder = json::Decoder::new(json_object.unwrap());
183     let decoded1: TestStruct1 = Decodable::decode(&mut decoder).unwrap(); // create the final object
184 }
185 ```
186
187 ## Using `ToJson`
188
189 This example use the ToJson impl to deserialize the JSON string.
190 Example of `ToJson` trait implementation for TestStruct1.
191
192 ```rust
193 extern crate serialize;
194 extern crate collections;
195
196 use serialize::json::ToJson;
197 use serialize::{json, Encodable, Decodable};
198 use collections::TreeMap;
199
200 #[deriving(Decodable, Encodable)] // generate Decodable, Encodable impl.
201 pub struct TestStruct1  {
202     data_int: u8,
203     data_str: ~str,
204     data_vector: ~[u8],
205 }
206
207 impl ToJson for TestStruct1 {
208     fn to_json( &self ) -> json::Json {
209         let mut d = ~TreeMap::new();
210         d.insert("data_int".to_owned(), self.data_int.to_json());
211         d.insert("data_str".to_owned(), self.data_str.to_json());
212         d.insert("data_vector".to_owned(), self.data_vector.to_json());
213         json::Object(d)
214     }
215 }
216
217 fn main() {
218     // Serialization using our impl of to_json
219
220     let test2: TestStruct1 = TestStruct1 {data_int: 1, data_str:"toto".to_owned(),
221                                           data_vector:~[2,3,4,5]};
222     let tjson: json::Json = test2.to_json();
223     let json_str: ~str = tjson.to_str();
224
225     // Deserialize like before.
226
227     let mut decoder = json::Decoder::new(json::from_str(json_str).unwrap());
228     // create the final object
229     let decoded2: TestStruct1 = Decodable::decode(&mut decoder).unwrap();
230 }
231 ```
232
233 */
234
235 use collections::HashMap;
236 use std::char;
237 use std::f64;
238 use std::fmt;
239 use std::io::MemWriter;
240 use std::io;
241 use std::num;
242 use std::str;
243 use std::str::ScalarValue;
244 use std::strbuf::StrBuf;
245
246 use Encodable;
247 use collections::TreeMap;
248
249 /// Represents a json value
250 #[deriving(Clone, Eq)]
251 pub enum Json {
252     Number(f64),
253     String(~str),
254     Boolean(bool),
255     List(List),
256     Object(~Object),
257     Null,
258 }
259
260 pub type List = ~[Json];
261 pub type Object = TreeMap<~str, Json>;
262
263 #[deriving(Eq, Show)]
264 pub enum Error {
265     /// msg, line, col
266     ParseError(~str, uint, uint),
267     ExpectedError(~str, ~str),
268     MissingFieldError(~str),
269     UnknownVariantError(~str),
270     IoError(io::IoError)
271 }
272
273 pub type EncodeResult = io::IoResult<()>;
274 pub type DecodeResult<T> = Result<T, Error>;
275
276 fn escape_str(s: &str) -> ~str {
277     let mut escaped = StrBuf::from_str("\"");
278     for c in s.chars() {
279         match c {
280           '"' => escaped.push_str("\\\""),
281           '\\' => escaped.push_str("\\\\"),
282           '\x08' => escaped.push_str("\\b"),
283           '\x0c' => escaped.push_str("\\f"),
284           '\n' => escaped.push_str("\\n"),
285           '\r' => escaped.push_str("\\r"),
286           '\t' => escaped.push_str("\\t"),
287           _ => escaped.push_char(c),
288         }
289     };
290     escaped.push_char('"');
291     escaped.into_owned()
292 }
293
294 fn spaces(n: uint) -> ~str {
295     let mut ss = StrBuf::new();
296     for _ in range(0, n) {
297         ss.push_str(" ");
298     }
299     return ss.into_owned();
300 }
301
302 /// A structure for implementing serialization to JSON.
303 pub struct Encoder<'a> {
304     wr: &'a mut io::Writer,
305 }
306
307 impl<'a> Encoder<'a> {
308     /// Creates a new JSON encoder whose output will be written to the writer
309     /// specified.
310     pub fn new<'a>(wr: &'a mut io::Writer) -> Encoder<'a> {
311         Encoder { wr: wr }
312     }
313
314     /// Encode the specified struct into a json [u8]
315     pub fn buffer_encode<T:Encodable<Encoder<'a>, io::IoError>>(to_encode_object: &T) -> Vec<u8>  {
316        //Serialize the object in a string using a writer
317         let mut m = MemWriter::new();
318         {
319             let mut encoder = Encoder::new(&mut m as &mut io::Writer);
320             // MemWriter never Errs
321             let _ = to_encode_object.encode(&mut encoder);
322         }
323         m.unwrap()
324     }
325
326     /// Encode the specified struct into a json str
327     pub fn str_encode<T:Encodable<Encoder<'a>, io::IoError>>(to_encode_object: &T) -> ~str  {
328         let buff = Encoder::buffer_encode(to_encode_object);
329         str::from_utf8(buff.as_slice()).unwrap().to_owned()
330     }
331 }
332
333 impl<'a> ::Encoder<io::IoError> for Encoder<'a> {
334     fn emit_nil(&mut self) -> EncodeResult { write!(self.wr, "null") }
335
336     fn emit_uint(&mut self, v: uint) -> EncodeResult { self.emit_f64(v as f64) }
337     fn emit_u64(&mut self, v: u64) -> EncodeResult { self.emit_f64(v as f64) }
338     fn emit_u32(&mut self, v: u32) -> EncodeResult { self.emit_f64(v as f64) }
339     fn emit_u16(&mut self, v: u16) -> EncodeResult { self.emit_f64(v as f64) }
340     fn emit_u8(&mut self, v: u8) -> EncodeResult  { self.emit_f64(v as f64) }
341
342     fn emit_int(&mut self, v: int) -> EncodeResult { self.emit_f64(v as f64) }
343     fn emit_i64(&mut self, v: i64) -> EncodeResult { self.emit_f64(v as f64) }
344     fn emit_i32(&mut self, v: i32) -> EncodeResult { self.emit_f64(v as f64) }
345     fn emit_i16(&mut self, v: i16) -> EncodeResult { self.emit_f64(v as f64) }
346     fn emit_i8(&mut self, v: i8) -> EncodeResult  { self.emit_f64(v as f64) }
347
348     fn emit_bool(&mut self, v: bool) -> EncodeResult {
349         if v {
350             write!(self.wr, "true")
351         } else {
352             write!(self.wr, "false")
353         }
354     }
355
356     fn emit_f64(&mut self, v: f64) -> EncodeResult {
357         write!(self.wr, "{}", f64::to_str_digits(v, 6u))
358     }
359     fn emit_f32(&mut self, v: f32) -> EncodeResult { self.emit_f64(v as f64) }
360
361     fn emit_char(&mut self, v: char) -> EncodeResult { self.emit_str(str::from_char(v)) }
362     fn emit_str(&mut self, v: &str) -> EncodeResult {
363         write!(self.wr, "{}", escape_str(v))
364     }
365
366     fn emit_enum(&mut self,
367                  _name: &str,
368                  f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult { f(self) }
369
370     fn emit_enum_variant(&mut self,
371                          name: &str,
372                          _id: uint,
373                          cnt: uint,
374                          f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
375         // enums are encoded as strings or objects
376         // Bunny => "Bunny"
377         // Kangaroo(34,"William") => {"variant": "Kangaroo", "fields": [34,"William"]}
378         if cnt == 0 {
379             write!(self.wr, "{}", escape_str(name))
380         } else {
381             try!(write!(self.wr, "\\{\"variant\":"));
382             try!(write!(self.wr, "{}", escape_str(name)));
383             try!(write!(self.wr, ",\"fields\":["));
384             try!(f(self));
385             write!(self.wr, "]\\}")
386         }
387     }
388
389     fn emit_enum_variant_arg(&mut self,
390                              idx: uint,
391                              f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
392         if idx != 0 {
393             try!(write!(self.wr, ","));
394         }
395         f(self)
396     }
397
398     fn emit_enum_struct_variant(&mut self,
399                                 name: &str,
400                                 id: uint,
401                                 cnt: uint,
402                                 f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
403         self.emit_enum_variant(name, id, cnt, f)
404     }
405
406     fn emit_enum_struct_variant_field(&mut self,
407                                       _: &str,
408                                       idx: uint,
409                                       f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
410         self.emit_enum_variant_arg(idx, f)
411     }
412
413     fn emit_struct(&mut self,
414                    _: &str,
415                    _: uint,
416                    f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
417         try!(write!(self.wr, r"\{"));
418         try!(f(self));
419         write!(self.wr, r"\}")
420     }
421
422     fn emit_struct_field(&mut self,
423                          name: &str,
424                          idx: uint,
425                          f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
426         if idx != 0 { try!(write!(self.wr, ",")); }
427         try!(write!(self.wr, "{}:", escape_str(name)));
428         f(self)
429     }
430
431     fn emit_tuple(&mut self, len: uint, f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
432         self.emit_seq(len, f)
433     }
434     fn emit_tuple_arg(&mut self,
435                       idx: uint,
436                       f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
437         self.emit_seq_elt(idx, f)
438     }
439
440     fn emit_tuple_struct(&mut self,
441                          _name: &str,
442                          len: uint,
443                          f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
444         self.emit_seq(len, f)
445     }
446     fn emit_tuple_struct_arg(&mut self,
447                              idx: uint,
448                              f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
449         self.emit_seq_elt(idx, f)
450     }
451
452     fn emit_option(&mut self, f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
453         f(self)
454     }
455     fn emit_option_none(&mut self) -> EncodeResult { self.emit_nil() }
456     fn emit_option_some(&mut self, f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
457         f(self)
458     }
459
460     fn emit_seq(&mut self, _len: uint, f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
461         try!(write!(self.wr, "["));
462         try!(f(self));
463         write!(self.wr, "]")
464     }
465
466     fn emit_seq_elt(&mut self, idx: uint, f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
467         if idx != 0 {
468             try!(write!(self.wr, ","));
469         }
470         f(self)
471     }
472
473     fn emit_map(&mut self, _len: uint, f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
474         try!(write!(self.wr, r"\{"));
475         try!(f(self));
476         write!(self.wr, r"\}")
477     }
478
479     fn emit_map_elt_key(&mut self,
480                         idx: uint,
481                         f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
482         use std::str::from_utf8;
483         if idx != 0 { try!(write!(self.wr, ",")) }
484         // ref #12967, make sure to wrap a key in double quotes,
485         // in the event that its of a type that omits them (eg numbers)
486         let mut buf = MemWriter::new();
487         let mut check_encoder = Encoder::new(&mut buf);
488         try!(f(&mut check_encoder));
489         let buf = buf.unwrap();
490         let out = from_utf8(buf.as_slice()).unwrap();
491         let needs_wrapping = out.char_at(0) != '"' &&
492             out.char_at_reverse(out.len()) != '"';
493         if needs_wrapping { try!(write!(self.wr, "\"")); }
494         try!(f(self));
495         if needs_wrapping { try!(write!(self.wr, "\"")); }
496         Ok(())
497     }
498
499     fn emit_map_elt_val(&mut self,
500                         _idx: uint,
501                         f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
502         try!(write!(self.wr, ":"));
503         f(self)
504     }
505 }
506
507 /// Another encoder for JSON, but prints out human-readable JSON instead of
508 /// compact data
509 pub struct PrettyEncoder<'a> {
510     wr: &'a mut io::Writer,
511     indent: uint,
512 }
513
514 impl<'a> PrettyEncoder<'a> {
515     /// Creates a new encoder whose output will be written to the specified writer
516     pub fn new<'a>(wr: &'a mut io::Writer) -> PrettyEncoder<'a> {
517         PrettyEncoder {
518             wr: wr,
519             indent: 0,
520         }
521     }
522 }
523
524 impl<'a> ::Encoder<io::IoError> for PrettyEncoder<'a> {
525     fn emit_nil(&mut self) -> EncodeResult { write!(self.wr, "null") }
526
527     fn emit_uint(&mut self, v: uint) -> EncodeResult { self.emit_f64(v as f64) }
528     fn emit_u64(&mut self, v: u64) -> EncodeResult { self.emit_f64(v as f64) }
529     fn emit_u32(&mut self, v: u32) -> EncodeResult { self.emit_f64(v as f64) }
530     fn emit_u16(&mut self, v: u16) -> EncodeResult { self.emit_f64(v as f64) }
531     fn emit_u8(&mut self, v: u8) -> EncodeResult { self.emit_f64(v as f64) }
532
533     fn emit_int(&mut self, v: int) -> EncodeResult { self.emit_f64(v as f64) }
534     fn emit_i64(&mut self, v: i64) -> EncodeResult { self.emit_f64(v as f64) }
535     fn emit_i32(&mut self, v: i32) -> EncodeResult { self.emit_f64(v as f64) }
536     fn emit_i16(&mut self, v: i16) -> EncodeResult { self.emit_f64(v as f64) }
537     fn emit_i8(&mut self, v: i8) -> EncodeResult { self.emit_f64(v as f64) }
538
539     fn emit_bool(&mut self, v: bool) -> EncodeResult {
540         if v {
541             write!(self.wr, "true")
542         } else {
543             write!(self.wr, "false")
544         }
545     }
546
547     fn emit_f64(&mut self, v: f64) -> EncodeResult {
548         write!(self.wr, "{}", f64::to_str_digits(v, 6u))
549     }
550     fn emit_f32(&mut self, v: f32) -> EncodeResult { self.emit_f64(v as f64) }
551
552     fn emit_char(&mut self, v: char) -> EncodeResult { self.emit_str(str::from_char(v)) }
553     fn emit_str(&mut self, v: &str) -> EncodeResult {
554         write!(self.wr, "{}", escape_str(v))
555     }
556
557     fn emit_enum(&mut self,
558                  _name: &str,
559                  f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
560         f(self)
561     }
562
563     fn emit_enum_variant(&mut self,
564                          name: &str,
565                          _: uint,
566                          cnt: uint,
567                          f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
568         if cnt == 0 {
569             write!(self.wr, "{}", escape_str(name))
570         } else {
571             self.indent += 2;
572             try!(write!(self.wr, "[\n{}{},\n", spaces(self.indent),
573                           escape_str(name)));
574             try!(f(self));
575             self.indent -= 2;
576             write!(self.wr, "\n{}]", spaces(self.indent))
577         }
578     }
579
580     fn emit_enum_variant_arg(&mut self,
581                              idx: uint,
582                              f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
583         if idx != 0 {
584             try!(write!(self.wr, ",\n"));
585         }
586         try!(write!(self.wr, "{}", spaces(self.indent)));
587         f(self)
588     }
589
590     fn emit_enum_struct_variant(&mut self,
591                                 name: &str,
592                                 id: uint,
593                                 cnt: uint,
594                                 f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
595         self.emit_enum_variant(name, id, cnt, f)
596     }
597
598     fn emit_enum_struct_variant_field(&mut self,
599                                       _: &str,
600                                       idx: uint,
601                                       f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
602         self.emit_enum_variant_arg(idx, f)
603     }
604
605
606     fn emit_struct(&mut self,
607                    _: &str,
608                    len: uint,
609                    f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
610         if len == 0 {
611             write!(self.wr, "\\{\\}")
612         } else {
613             try!(write!(self.wr, "\\{"));
614             self.indent += 2;
615             try!(f(self));
616             self.indent -= 2;
617             write!(self.wr, "\n{}\\}", spaces(self.indent))
618         }
619     }
620
621     fn emit_struct_field(&mut self,
622                          name: &str,
623                          idx: uint,
624                          f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
625         if idx == 0 {
626             try!(write!(self.wr, "\n"));
627         } else {
628             try!(write!(self.wr, ",\n"));
629         }
630         try!(write!(self.wr, "{}{}: ", spaces(self.indent), escape_str(name)));
631         f(self)
632     }
633
634     fn emit_tuple(&mut self,
635                   len: uint,
636                   f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
637         self.emit_seq(len, f)
638     }
639     fn emit_tuple_arg(&mut self,
640                       idx: uint,
641                       f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
642         self.emit_seq_elt(idx, f)
643     }
644
645     fn emit_tuple_struct(&mut self,
646                          _: &str,
647                          len: uint,
648                          f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
649         self.emit_seq(len, f)
650     }
651     fn emit_tuple_struct_arg(&mut self,
652                              idx: uint,
653                              f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
654         self.emit_seq_elt(idx, f)
655     }
656
657     fn emit_option(&mut self, f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
658         f(self)
659     }
660     fn emit_option_none(&mut self) -> EncodeResult { self.emit_nil() }
661     fn emit_option_some(&mut self, f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
662         f(self)
663     }
664
665     fn emit_seq(&mut self,
666                 len: uint,
667                 f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
668         if len == 0 {
669             write!(self.wr, "[]")
670         } else {
671             try!(write!(self.wr, "["));
672             self.indent += 2;
673             try!(f(self));
674             self.indent -= 2;
675             write!(self.wr, "\n{}]", spaces(self.indent))
676         }
677     }
678
679     fn emit_seq_elt(&mut self,
680                     idx: uint,
681                     f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
682         if idx == 0 {
683             try!(write!(self.wr, "\n"));
684         } else {
685             try!(write!(self.wr, ",\n"));
686         }
687         try!(write!(self.wr, "{}", spaces(self.indent)));
688         f(self)
689     }
690
691     fn emit_map(&mut self,
692                 len: uint,
693                 f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
694         if len == 0 {
695             write!(self.wr, "\\{\\}")
696         } else {
697             try!(write!(self.wr, "\\{"));
698             self.indent += 2;
699             try!(f(self));
700             self.indent -= 2;
701             write!(self.wr, "\n{}\\}", spaces(self.indent))
702         }
703     }
704
705     fn emit_map_elt_key(&mut self,
706                         idx: uint,
707                         f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
708         use std::str::from_utf8;
709         if idx == 0 {
710             try!(write!(self.wr, "\n"));
711         } else {
712             try!(write!(self.wr, ",\n"));
713         }
714         try!(write!(self.wr, "{}", spaces(self.indent)));
715         // ref #12967, make sure to wrap a key in double quotes,
716         // in the event that its of a type that omits them (eg numbers)
717         let mut buf = MemWriter::new();
718         let mut check_encoder = PrettyEncoder::new(&mut buf);
719         try!(f(&mut check_encoder));
720         let buf = buf.unwrap();
721         let out = from_utf8(buf.as_slice()).unwrap();
722         let needs_wrapping = out.char_at(0) != '"' &&
723             out.char_at_reverse(out.len()) != '"';
724         if needs_wrapping { try!(write!(self.wr, "\"")); }
725         try!(f(self));
726         if needs_wrapping { try!(write!(self.wr, "\"")); }
727         Ok(())
728     }
729
730     fn emit_map_elt_val(&mut self,
731                         _idx: uint,
732                         f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
733         try!(write!(self.wr, ": "));
734         f(self)
735     }
736 }
737
738 impl<E: ::Encoder<S>, S> Encodable<E, S> for Json {
739     fn encode(&self, e: &mut E) -> Result<(), S> {
740         match *self {
741             Number(v) => v.encode(e),
742             String(ref v) => v.encode(e),
743             Boolean(v) => v.encode(e),
744             List(ref v) => v.encode(e),
745             Object(ref v) => v.encode(e),
746             Null => e.emit_nil(),
747         }
748     }
749 }
750
751 impl Json {
752     /// Encodes a json value into a io::writer.  Uses a single line.
753     pub fn to_writer(&self, wr: &mut io::Writer) -> EncodeResult {
754         let mut encoder = Encoder::new(wr);
755         self.encode(&mut encoder)
756     }
757
758     /// Encodes a json value into a io::writer.
759     /// Pretty-prints in a more readable format.
760     pub fn to_pretty_writer(&self, wr: &mut io::Writer) -> EncodeResult {
761         let mut encoder = PrettyEncoder::new(wr);
762         self.encode(&mut encoder)
763     }
764
765     /// Encodes a json value into a string
766     pub fn to_pretty_str(&self) -> ~str {
767         let mut s = MemWriter::new();
768         self.to_pretty_writer(&mut s as &mut io::Writer).unwrap();
769         str::from_utf8(s.unwrap().as_slice()).unwrap().to_owned()
770     }
771
772      /// If the Json value is an Object, returns the value associated with the provided key.
773     /// Otherwise, returns None.
774     pub fn find<'a>(&'a self, key: &~str) -> Option<&'a Json>{
775         match self {
776             &Object(ref map) => map.find(key),
777             _ => None
778         }
779     }
780
781     /// Attempts to get a nested Json Object for each key in `keys`.
782     /// If any key is found not to exist, find_path will return None.
783     /// Otherwise, it will return the Json value associated with the final key.
784     pub fn find_path<'a>(&'a self, keys: &[&~str]) -> Option<&'a Json>{
785         let mut target = self;
786         for key in keys.iter() {
787             match target.find(*key) {
788                 Some(t) => { target = t; },
789                 None => return None
790             }
791         }
792         Some(target)
793     }
794
795     /// If the Json value is an Object, performs a depth-first search until
796     /// a value associated with the provided key is found. If no value is found
797     /// or the Json value is not an Object, returns None.
798     pub fn search<'a>(&'a self, key: &~str) -> Option<&'a Json> {
799         match self {
800             &Object(ref map) => {
801                 match map.find(key) {
802                     Some(json_value) => Some(json_value),
803                     None => {
804                         let mut value : Option<&'a Json> = None;
805                         for (_, v) in map.iter() {
806                             value = v.search(key);
807                             if value.is_some() {
808                                 break;
809                             }
810                         }
811                         value
812                     }
813                 }
814             },
815             _ => None
816         }
817     }
818
819     /// Returns true if the Json value is an Object. Returns false otherwise.
820     pub fn is_object<'a>(&'a self) -> bool {
821         self.as_object().is_some()
822     }
823
824     /// If the Json value is an Object, returns the associated TreeMap.
825     /// Returns None otherwise.
826     pub fn as_object<'a>(&'a self) -> Option<&'a Object> {
827         match self {
828             &Object(ref map) => Some(&**map),
829             _ => None
830         }
831     }
832
833     /// Returns true if the Json value is a List. Returns false otherwise.
834     pub fn is_list<'a>(&'a self) -> bool {
835         self.as_list().is_some()
836     }
837
838     /// If the Json value is a List, returns the associated vector.
839     /// Returns None otherwise.
840     pub fn as_list<'a>(&'a self) -> Option<&'a List> {
841         match self {
842             &List(ref list) => Some(&*list),
843             _ => None
844         }
845     }
846
847     /// Returns true if the Json value is a String. Returns false otherwise.
848     pub fn is_string<'a>(&'a self) -> bool {
849         self.as_string().is_some()
850     }
851
852     /// If the Json value is a String, returns the associated str.
853     /// Returns None otherwise.
854     pub fn as_string<'a>(&'a self) -> Option<&'a str> {
855         match *self {
856             String(ref s) => Some(s.as_slice()),
857             _ => None
858         }
859     }
860
861     /// Returns true if the Json value is a Number. Returns false otherwise.
862     pub fn is_number(&self) -> bool {
863         self.as_number().is_some()
864     }
865
866     /// If the Json value is a Number, returns the associated f64.
867     /// Returns None otherwise.
868     pub fn as_number(&self) -> Option<f64> {
869         match self {
870             &Number(n) => Some(n),
871             _ => None
872         }
873     }
874
875     /// Returns true if the Json value is a Boolean. Returns false otherwise.
876     pub fn is_boolean(&self) -> bool {
877         self.as_boolean().is_some()
878     }
879
880     /// If the Json value is a Boolean, returns the associated bool.
881     /// Returns None otherwise.
882     pub fn as_boolean(&self) -> Option<bool> {
883         match self {
884             &Boolean(b) => Some(b),
885             _ => None
886         }
887     }
888
889     /// Returns true if the Json value is a Null. Returns false otherwise.
890     pub fn is_null(&self) -> bool {
891         self.as_null().is_some()
892     }
893
894     /// If the Json value is a Null, returns ().
895     /// Returns None otherwise.
896     pub fn as_null(&self) -> Option<()> {
897         match self {
898             &Null => Some(()),
899             _ => None
900         }
901     }
902 }
903
904 pub struct Parser<T> {
905     rdr: T,
906     ch: Option<char>,
907     line: uint,
908     col: uint,
909 }
910
911 impl<T: Iterator<char>> Parser<T> {
912     /// Decode a json value from an Iterator<char>
913     pub fn new(rdr: T) -> Parser<T> {
914         let mut p = Parser {
915             rdr: rdr,
916             ch: Some('\x00'),
917             line: 1,
918             col: 0,
919         };
920         p.bump();
921         p
922     }
923 }
924
925 impl<T: Iterator<char>> Parser<T> {
926     pub fn parse(&mut self) -> DecodeResult<Json> {
927         match self.parse_value() {
928           Ok(value) => {
929             // Skip trailing whitespaces.
930             self.parse_whitespace();
931             // Make sure there is no trailing characters.
932             if self.eof() {
933                 Ok(value)
934             } else {
935                 self.error("trailing characters".to_owned())
936             }
937           }
938           Err(e) => Err(e)
939         }
940     }
941 }
942
943 impl<T : Iterator<char>> Parser<T> {
944     fn eof(&self) -> bool { self.ch.is_none() }
945     fn ch_or_null(&self) -> char { self.ch.unwrap_or('\x00') }
946     fn bump(&mut self) {
947         self.ch = self.rdr.next();
948
949         if self.ch_is('\n') {
950             self.line += 1u;
951             self.col = 1u;
952         } else {
953             self.col += 1u;
954         }
955     }
956
957     fn next_char(&mut self) -> Option<char> {
958         self.bump();
959         self.ch
960     }
961     fn ch_is(&self, c: char) -> bool {
962         self.ch == Some(c)
963     }
964
965     fn error<T>(&self, msg: ~str) -> DecodeResult<T> {
966         Err(ParseError(msg, self.line, self.col))
967     }
968
969     fn parse_value(&mut self) -> DecodeResult<Json> {
970         self.parse_whitespace();
971
972         if self.eof() { return self.error("EOF while parsing value".to_owned()); }
973
974         match self.ch_or_null() {
975             'n' => self.parse_ident("ull", Null),
976             't' => self.parse_ident("rue", Boolean(true)),
977             'f' => self.parse_ident("alse", Boolean(false)),
978             '0' .. '9' | '-' => self.parse_number(),
979             '"' => {
980                 match self.parse_str() {
981                     Ok(s) => Ok(String(s)),
982                     Err(e) => Err(e),
983                 }
984             },
985             '[' => self.parse_list(),
986             '{' => self.parse_object(),
987             _ => self.error("invalid syntax".to_owned()),
988         }
989     }
990
991     fn parse_whitespace(&mut self) {
992         while self.ch_is(' ') ||
993               self.ch_is('\n') ||
994               self.ch_is('\t') ||
995               self.ch_is('\r') { self.bump(); }
996     }
997
998     fn parse_ident(&mut self, ident: &str, value: Json) -> DecodeResult<Json> {
999         if ident.chars().all(|c| Some(c) == self.next_char()) {
1000             self.bump();
1001             Ok(value)
1002         } else {
1003             self.error("invalid syntax".to_owned())
1004         }
1005     }
1006
1007     fn parse_number(&mut self) -> DecodeResult<Json> {
1008         let mut neg = 1.0;
1009
1010         if self.ch_is('-') {
1011             self.bump();
1012             neg = -1.0;
1013         }
1014
1015         let mut res = match self.parse_integer() {
1016           Ok(res) => res,
1017           Err(e) => return Err(e)
1018         };
1019
1020         if self.ch_is('.') {
1021             match self.parse_decimal(res) {
1022               Ok(r) => res = r,
1023               Err(e) => return Err(e)
1024             }
1025         }
1026
1027         if self.ch_is('e') || self.ch_is('E') {
1028             match self.parse_exponent(res) {
1029               Ok(r) => res = r,
1030               Err(e) => return Err(e)
1031             }
1032         }
1033
1034         Ok(Number(neg * res))
1035     }
1036
1037     fn parse_integer(&mut self) -> DecodeResult<f64> {
1038         let mut res = 0.0;
1039
1040         match self.ch_or_null() {
1041             '0' => {
1042                 self.bump();
1043
1044                 // There can be only one leading '0'.
1045                 match self.ch_or_null() {
1046                     '0' .. '9' => return self.error("invalid number".to_owned()),
1047                     _ => ()
1048                 }
1049             },
1050             '1' .. '9' => {
1051                 while !self.eof() {
1052                     match self.ch_or_null() {
1053                         c @ '0' .. '9' => {
1054                             res *= 10.0;
1055                             res += ((c as int) - ('0' as int)) as f64;
1056
1057                             self.bump();
1058                         }
1059                         _ => break,
1060                     }
1061                 }
1062             }
1063             _ => return self.error("invalid number".to_owned()),
1064         }
1065         Ok(res)
1066     }
1067
1068     fn parse_decimal(&mut self, res: f64) -> DecodeResult<f64> {
1069         self.bump();
1070
1071         // Make sure a digit follows the decimal place.
1072         match self.ch_or_null() {
1073             '0' .. '9' => (),
1074              _ => return self.error("invalid number".to_owned())
1075         }
1076
1077         let mut res = res;
1078         let mut dec = 1.0;
1079         while !self.eof() {
1080             match self.ch_or_null() {
1081                 c @ '0' .. '9' => {
1082                     dec /= 10.0;
1083                     res += (((c as int) - ('0' as int)) as f64) * dec;
1084
1085                     self.bump();
1086                 }
1087                 _ => break,
1088             }
1089         }
1090
1091         Ok(res)
1092     }
1093
1094     fn parse_exponent(&mut self, mut res: f64) -> DecodeResult<f64> {
1095         self.bump();
1096
1097         let mut exp = 0u;
1098         let mut neg_exp = false;
1099
1100         if self.ch_is('+') {
1101             self.bump();
1102         } else if self.ch_is('-') {
1103             self.bump();
1104             neg_exp = true;
1105         }
1106
1107         // Make sure a digit follows the exponent place.
1108         match self.ch_or_null() {
1109             '0' .. '9' => (),
1110             _ => return self.error("invalid number".to_owned())
1111         }
1112         while !self.eof() {
1113             match self.ch_or_null() {
1114                 c @ '0' .. '9' => {
1115                     exp *= 10;
1116                     exp += (c as uint) - ('0' as uint);
1117
1118                     self.bump();
1119                 }
1120                 _ => break
1121             }
1122         }
1123
1124         let exp: f64 = num::pow(10u as f64, exp);
1125         if neg_exp {
1126             res /= exp;
1127         } else {
1128             res *= exp;
1129         }
1130
1131         Ok(res)
1132     }
1133
1134     fn decode_hex_escape(&mut self) -> DecodeResult<u16> {
1135         let mut i = 0u;
1136         let mut n = 0u16;
1137         while i < 4u && !self.eof() {
1138             self.bump();
1139             n = match self.ch_or_null() {
1140                 c @ '0' .. '9' => n * 16_u16 + ((c as u16) - ('0' as u16)),
1141                 'a' | 'A' => n * 16_u16 + 10_u16,
1142                 'b' | 'B' => n * 16_u16 + 11_u16,
1143                 'c' | 'C' => n * 16_u16 + 12_u16,
1144                 'd' | 'D' => n * 16_u16 + 13_u16,
1145                 'e' | 'E' => n * 16_u16 + 14_u16,
1146                 'f' | 'F' => n * 16_u16 + 15_u16,
1147                 _ => return self.error(
1148                     "invalid \\u escape (unrecognized hex)".to_owned())
1149             };
1150
1151             i += 1u;
1152         }
1153
1154         // Error out if we didn't parse 4 digits.
1155         if i != 4u {
1156             return self.error(
1157                 "invalid \\u escape (not four digits)".to_owned());
1158         }
1159
1160         Ok(n)
1161     }
1162
1163     fn parse_str(&mut self) -> DecodeResult<~str> {
1164         let mut escape = false;
1165         let mut res = StrBuf::new();
1166
1167         loop {
1168             self.bump();
1169             if self.eof() {
1170                 return self.error("EOF while parsing string".to_owned());
1171             }
1172
1173             if escape {
1174                 match self.ch_or_null() {
1175                     '"' => res.push_char('"'),
1176                     '\\' => res.push_char('\\'),
1177                     '/' => res.push_char('/'),
1178                     'b' => res.push_char('\x08'),
1179                     'f' => res.push_char('\x0c'),
1180                     'n' => res.push_char('\n'),
1181                     'r' => res.push_char('\r'),
1182                     't' => res.push_char('\t'),
1183                     'u' => match try!(self.decode_hex_escape()) {
1184                         0xDC00 .. 0xDFFF => return self.error(
1185                                 "lone trailing surrogate in hex escape".to_owned()),
1186
1187                         // Non-BMP characters are encoded as a sequence of
1188                         // two hex escapes, representing UTF-16 surrogates.
1189                         n1 @ 0xD800 .. 0xDBFF => {
1190                             let c1 = self.next_char();
1191                             let c2 = self.next_char();
1192                             match (c1, c2) {
1193                                 (Some('\\'), Some('u')) => (),
1194                                 _ => return self.error(
1195                                     "unexpected end of non-BMP hex escape".to_owned()),
1196                             }
1197
1198                             let buf = [n1, try!(self.decode_hex_escape())];
1199                             match str::utf16_items(buf.as_slice()).next() {
1200                                 Some(ScalarValue(c)) => res.push_char(c),
1201                                 _ => return self.error(
1202                                     "lone leading surrogate in hex escape".to_owned()),
1203                             }
1204                         }
1205
1206                         n => match char::from_u32(n as u32) {
1207                             Some(c) => res.push_char(c),
1208                             None => return self.error(
1209                                 format!("invalid Unicode codepoint {:u}", n)),
1210                         },
1211                     },
1212                     _ => return self.error("invalid escape".to_owned()),
1213                 }
1214                 escape = false;
1215             } else if self.ch_is('\\') {
1216                 escape = true;
1217             } else {
1218                 match self.ch {
1219                     Some('"') => {
1220                         self.bump();
1221                         return Ok(res.into_owned());
1222                     },
1223                     Some(c) => res.push_char(c),
1224                     None => unreachable!()
1225                 }
1226             }
1227         }
1228     }
1229
1230     fn parse_list(&mut self) -> DecodeResult<Json> {
1231         self.bump();
1232         self.parse_whitespace();
1233
1234         let mut values = Vec::new();
1235
1236         if self.ch_is(']') {
1237             self.bump();
1238             return Ok(List(values.move_iter().collect()));
1239         }
1240
1241         loop {
1242             match self.parse_value() {
1243               Ok(v) => values.push(v),
1244               Err(e) => return Err(e)
1245             }
1246
1247             self.parse_whitespace();
1248             if self.eof() {
1249                 return self.error("EOF while parsing list".to_owned());
1250             }
1251
1252             if self.ch_is(',') {
1253                 self.bump();
1254             } else if self.ch_is(']') {
1255                 self.bump();
1256                 return Ok(List(values.move_iter().collect()));
1257             } else {
1258                 return self.error("expected `,` or `]`".to_owned())
1259             }
1260         };
1261     }
1262
1263     fn parse_object(&mut self) -> DecodeResult<Json> {
1264         self.bump();
1265         self.parse_whitespace();
1266
1267         let mut values = ~TreeMap::new();
1268
1269         if self.ch_is('}') {
1270           self.bump();
1271           return Ok(Object(values));
1272         }
1273
1274         while !self.eof() {
1275             self.parse_whitespace();
1276
1277             if !self.ch_is('"') {
1278                 return self.error("key must be a string".to_owned());
1279             }
1280
1281             let key = match self.parse_str() {
1282               Ok(key) => key,
1283               Err(e) => return Err(e)
1284             };
1285
1286             self.parse_whitespace();
1287
1288             if !self.ch_is(':') {
1289                 if self.eof() { break; }
1290                 return self.error("expected `:`".to_owned());
1291             }
1292             self.bump();
1293
1294             match self.parse_value() {
1295               Ok(value) => { values.insert(key, value); }
1296               Err(e) => return Err(e)
1297             }
1298             self.parse_whitespace();
1299
1300             match self.ch_or_null() {
1301                 ',' => self.bump(),
1302                 '}' => { self.bump(); return Ok(Object(values)); },
1303                 _ => {
1304                     if self.eof() { break; }
1305                     return self.error("expected `,` or `}`".to_owned());
1306                 }
1307             }
1308         }
1309
1310         return self.error("EOF while parsing object".to_owned());
1311     }
1312 }
1313
1314 /// Decodes a json value from an `&mut io::Reader`
1315 pub fn from_reader(rdr: &mut io::Reader) -> DecodeResult<Json> {
1316     let contents = match rdr.read_to_end() {
1317         Ok(c) => c,
1318         Err(e) => return Err(IoError(e))
1319     };
1320     let s = match str::from_utf8(contents.as_slice()) {
1321         Some(s) => s.to_owned(),
1322         None => return Err(ParseError("contents not utf-8".to_owned(), 0, 0))
1323     };
1324     let mut parser = Parser::new(s.chars());
1325     parser.parse()
1326 }
1327
1328 /// Decodes a json value from a string
1329 pub fn from_str(s: &str) -> DecodeResult<Json> {
1330     let mut parser = Parser::new(s.chars());
1331     parser.parse()
1332 }
1333
1334 /// A structure to decode JSON to values in rust.
1335 pub struct Decoder {
1336     stack: Vec<Json>,
1337 }
1338
1339 impl Decoder {
1340     /// Creates a new decoder instance for decoding the specified JSON value.
1341     pub fn new(json: Json) -> Decoder {
1342         Decoder {
1343             stack: vec!(json),
1344         }
1345     }
1346 }
1347
1348 impl Decoder {
1349     fn pop(&mut self) -> Json {
1350         self.stack.pop().unwrap()
1351     }
1352 }
1353
1354 macro_rules! expect(
1355     ($e:expr, Null) => ({
1356         match $e {
1357             Null => Ok(()),
1358             other => Err(ExpectedError("Null".to_owned(), format!("{}", other)))
1359         }
1360     });
1361     ($e:expr, $t:ident) => ({
1362         match $e {
1363             $t(v) => Ok(v),
1364             other => Err(ExpectedError(stringify!($t).to_owned(), format!("{}", other)))
1365         }
1366     })
1367 )
1368
1369 impl ::Decoder<Error> for Decoder {
1370     fn read_nil(&mut self) -> DecodeResult<()> {
1371         debug!("read_nil");
1372         try!(expect!(self.pop(), Null));
1373         Ok(())
1374     }
1375
1376     fn read_u64(&mut self)  -> DecodeResult<u64 > { Ok(try!(self.read_f64()) as u64) }
1377     fn read_u32(&mut self)  -> DecodeResult<u32 > { Ok(try!(self.read_f64()) as u32) }
1378     fn read_u16(&mut self)  -> DecodeResult<u16 > { Ok(try!(self.read_f64()) as u16) }
1379     fn read_u8 (&mut self)  -> DecodeResult<u8  > { Ok(try!(self.read_f64()) as u8) }
1380     fn read_uint(&mut self) -> DecodeResult<uint> { Ok(try!(self.read_f64()) as uint) }
1381
1382     fn read_i64(&mut self) -> DecodeResult<i64> { Ok(try!(self.read_f64()) as i64) }
1383     fn read_i32(&mut self) -> DecodeResult<i32> { Ok(try!(self.read_f64()) as i32) }
1384     fn read_i16(&mut self) -> DecodeResult<i16> { Ok(try!(self.read_f64()) as i16) }
1385     fn read_i8 (&mut self) -> DecodeResult<i8 > { Ok(try!(self.read_f64()) as i8) }
1386     fn read_int(&mut self) -> DecodeResult<int> { Ok(try!(self.read_f64()) as int) }
1387
1388     fn read_bool(&mut self) -> DecodeResult<bool> {
1389         debug!("read_bool");
1390         Ok(try!(expect!(self.pop(), Boolean)))
1391     }
1392
1393     fn read_f64(&mut self) -> DecodeResult<f64> {
1394         use std::from_str::FromStr;
1395         debug!("read_f64");
1396         match self.pop() {
1397             Number(f) => Ok(f),
1398             String(s) => {
1399                 // re: #12967.. a type w/ numeric keys (ie HashMap<uint, V> etc)
1400                 // is going to have a string here, as per JSON spec..
1401                 Ok(FromStr::from_str(s).unwrap())
1402             },
1403             value => Err(ExpectedError("Number".to_owned(), format!("{}", value)))
1404         }
1405     }
1406
1407     fn read_f32(&mut self) -> DecodeResult<f32> { Ok(try!(self.read_f64()) as f32) }
1408
1409     fn read_char(&mut self) -> DecodeResult<char> {
1410         let s = try!(self.read_str());
1411         {
1412             let mut it = s.chars();
1413             match (it.next(), it.next()) {
1414                 // exactly one character
1415                 (Some(c), None) => return Ok(c),
1416                 _ => ()
1417             }
1418         }
1419         Err(ExpectedError("single character string".to_owned(), format!("{}", s)))
1420     }
1421
1422     fn read_str(&mut self) -> DecodeResult<~str> {
1423         debug!("read_str");
1424         Ok(try!(expect!(self.pop(), String)))
1425     }
1426
1427     fn read_enum<T>(&mut self,
1428                     name: &str,
1429                     f: |&mut Decoder| -> DecodeResult<T>) -> DecodeResult<T> {
1430         debug!("read_enum({})", name);
1431         f(self)
1432     }
1433
1434     fn read_enum_variant<T>(&mut self,
1435                             names: &[&str],
1436                             f: |&mut Decoder, uint| -> DecodeResult<T>)
1437                             -> DecodeResult<T> {
1438         debug!("read_enum_variant(names={:?})", names);
1439         let name = match self.pop() {
1440             String(s) => s,
1441             Object(mut o) => {
1442                 let n = match o.pop(&"variant".to_owned()) {
1443                     Some(String(s)) => s,
1444                     Some(val) => return Err(ExpectedError("String".to_owned(), format!("{}", val))),
1445                     None => return Err(MissingFieldError("variant".to_owned()))
1446                 };
1447                 match o.pop(&"fields".to_owned()) {
1448                     Some(List(l)) => {
1449                         for field in l.move_rev_iter() {
1450                             self.stack.push(field.clone());
1451                         }
1452                     },
1453                     Some(val) => return Err(ExpectedError("List".to_owned(), format!("{}", val))),
1454                     None => return Err(MissingFieldError("fields".to_owned()))
1455                 }
1456                 n
1457             }
1458             json => return Err(ExpectedError("String or Object".to_owned(), format!("{}", json)))
1459         };
1460         let idx = match names.iter().position(|n| str::eq_slice(*n, name)) {
1461             Some(idx) => idx,
1462             None => return Err(UnknownVariantError(name))
1463         };
1464         f(self, idx)
1465     }
1466
1467     fn read_enum_variant_arg<T>(&mut self, idx: uint, f: |&mut Decoder| -> DecodeResult<T>)
1468                                 -> DecodeResult<T> {
1469         debug!("read_enum_variant_arg(idx={})", idx);
1470         f(self)
1471     }
1472
1473     fn read_enum_struct_variant<T>(&mut self,
1474                                    names: &[&str],
1475                                    f: |&mut Decoder, uint| -> DecodeResult<T>)
1476                                    -> DecodeResult<T> {
1477         debug!("read_enum_struct_variant(names={:?})", names);
1478         self.read_enum_variant(names, f)
1479     }
1480
1481
1482     fn read_enum_struct_variant_field<T>(&mut self,
1483                                          name: &str,
1484                                          idx: uint,
1485                                          f: |&mut Decoder| -> DecodeResult<T>)
1486                                          -> DecodeResult<T> {
1487         debug!("read_enum_struct_variant_field(name={}, idx={})", name, idx);
1488         self.read_enum_variant_arg(idx, f)
1489     }
1490
1491     fn read_struct<T>(&mut self,
1492                       name: &str,
1493                       len: uint,
1494                       f: |&mut Decoder| -> DecodeResult<T>)
1495                       -> DecodeResult<T> {
1496         debug!("read_struct(name={}, len={})", name, len);
1497         let value = try!(f(self));
1498         self.pop();
1499         Ok(value)
1500     }
1501
1502     fn read_struct_field<T>(&mut self,
1503                             name: &str,
1504                             idx: uint,
1505                             f: |&mut Decoder| -> DecodeResult<T>)
1506                             -> DecodeResult<T> {
1507         debug!("read_struct_field(name={}, idx={})", name, idx);
1508         let mut obj = try!(expect!(self.pop(), Object));
1509
1510         let value = match obj.pop(&name.to_owned()) {
1511             None => return Err(MissingFieldError(name.to_owned())),
1512             Some(json) => {
1513                 self.stack.push(json);
1514                 try!(f(self))
1515             }
1516         };
1517         self.stack.push(Object(obj));
1518         Ok(value)
1519     }
1520
1521     fn read_tuple<T>(&mut self, f: |&mut Decoder, uint| -> DecodeResult<T>) -> DecodeResult<T> {
1522         debug!("read_tuple()");
1523         self.read_seq(f)
1524     }
1525
1526     fn read_tuple_arg<T>(&mut self,
1527                          idx: uint,
1528                          f: |&mut Decoder| -> DecodeResult<T>) -> DecodeResult<T> {
1529         debug!("read_tuple_arg(idx={})", idx);
1530         self.read_seq_elt(idx, f)
1531     }
1532
1533     fn read_tuple_struct<T>(&mut self,
1534                             name: &str,
1535                             f: |&mut Decoder, uint| -> DecodeResult<T>)
1536                             -> DecodeResult<T> {
1537         debug!("read_tuple_struct(name={})", name);
1538         self.read_tuple(f)
1539     }
1540
1541     fn read_tuple_struct_arg<T>(&mut self,
1542                                 idx: uint,
1543                                 f: |&mut Decoder| -> DecodeResult<T>)
1544                                 -> DecodeResult<T> {
1545         debug!("read_tuple_struct_arg(idx={})", idx);
1546         self.read_tuple_arg(idx, f)
1547     }
1548
1549     fn read_option<T>(&mut self, f: |&mut Decoder, bool| -> DecodeResult<T>) -> DecodeResult<T> {
1550         match self.pop() {
1551             Null => f(self, false),
1552             value => { self.stack.push(value); f(self, true) }
1553         }
1554     }
1555
1556     fn read_seq<T>(&mut self, f: |&mut Decoder, uint| -> DecodeResult<T>) -> DecodeResult<T> {
1557         debug!("read_seq()");
1558         let list = try!(expect!(self.pop(), List));
1559         let len = list.len();
1560         for v in list.move_rev_iter() {
1561             self.stack.push(v);
1562         }
1563         f(self, len)
1564     }
1565
1566     fn read_seq_elt<T>(&mut self,
1567                        idx: uint,
1568                        f: |&mut Decoder| -> DecodeResult<T>) -> DecodeResult<T> {
1569         debug!("read_seq_elt(idx={})", idx);
1570         f(self)
1571     }
1572
1573     fn read_map<T>(&mut self, f: |&mut Decoder, uint| -> DecodeResult<T>) -> DecodeResult<T> {
1574         debug!("read_map()");
1575         let obj = try!(expect!(self.pop(), Object));
1576         let len = obj.len();
1577         for (key, value) in obj.move_iter() {
1578             self.stack.push(value);
1579             self.stack.push(String(key));
1580         }
1581         f(self, len)
1582     }
1583
1584     fn read_map_elt_key<T>(&mut self, idx: uint, f: |&mut Decoder| -> DecodeResult<T>)
1585                            -> DecodeResult<T> {
1586         debug!("read_map_elt_key(idx={})", idx);
1587         f(self)
1588     }
1589
1590     fn read_map_elt_val<T>(&mut self, idx: uint, f: |&mut Decoder| -> DecodeResult<T>)
1591                            -> DecodeResult<T> {
1592         debug!("read_map_elt_val(idx={})", idx);
1593         f(self)
1594     }
1595 }
1596
1597 /// Test if two json values are less than one another
1598 impl Ord for Json {
1599     fn lt(&self, other: &Json) -> bool {
1600         match *self {
1601             Number(f0) => {
1602                 match *other {
1603                     Number(f1) => f0 < f1,
1604                     String(_) | Boolean(_) | List(_) | Object(_) |
1605                     Null => true
1606                 }
1607             }
1608
1609             String(ref s0) => {
1610                 match *other {
1611                     Number(_) => false,
1612                     String(ref s1) => s0 < s1,
1613                     Boolean(_) | List(_) | Object(_) | Null => true
1614                 }
1615             }
1616
1617             Boolean(b0) => {
1618                 match *other {
1619                     Number(_) | String(_) => false,
1620                     Boolean(b1) => b0 < b1,
1621                     List(_) | Object(_) | Null => true
1622                 }
1623             }
1624
1625             List(ref l0) => {
1626                 match *other {
1627                     Number(_) | String(_) | Boolean(_) => false,
1628                     List(ref l1) => (*l0) < (*l1),
1629                     Object(_) | Null => true
1630                 }
1631             }
1632
1633             Object(ref d0) => {
1634                 match *other {
1635                     Number(_) | String(_) | Boolean(_) | List(_) => false,
1636                     Object(ref d1) => d0 < d1,
1637                     Null => true
1638                 }
1639             }
1640
1641             Null => {
1642                 match *other {
1643                     Number(_) | String(_) | Boolean(_) | List(_) |
1644                     Object(_) =>
1645                         false,
1646                     Null => true
1647                 }
1648             }
1649         }
1650     }
1651 }
1652
1653 /// A trait for converting values to JSON
1654 pub trait ToJson {
1655     /// Converts the value of `self` to an instance of JSON
1656     fn to_json(&self) -> Json;
1657 }
1658
1659 impl ToJson for Json {
1660     fn to_json(&self) -> Json { (*self).clone() }
1661 }
1662
1663 impl ToJson for int {
1664     fn to_json(&self) -> Json { Number(*self as f64) }
1665 }
1666
1667 impl ToJson for i8 {
1668     fn to_json(&self) -> Json { Number(*self as f64) }
1669 }
1670
1671 impl ToJson for i16 {
1672     fn to_json(&self) -> Json { Number(*self as f64) }
1673 }
1674
1675 impl ToJson for i32 {
1676     fn to_json(&self) -> Json { Number(*self as f64) }
1677 }
1678
1679 impl ToJson for i64 {
1680     fn to_json(&self) -> Json { Number(*self as f64) }
1681 }
1682
1683 impl ToJson for uint {
1684     fn to_json(&self) -> Json { Number(*self as f64) }
1685 }
1686
1687 impl ToJson for u8 {
1688     fn to_json(&self) -> Json { Number(*self as f64) }
1689 }
1690
1691 impl ToJson for u16 {
1692     fn to_json(&self) -> Json { Number(*self as f64) }
1693 }
1694
1695 impl ToJson for u32 {
1696     fn to_json(&self) -> Json { Number(*self as f64) }
1697 }
1698
1699 impl ToJson for u64 {
1700     fn to_json(&self) -> Json { Number(*self as f64) }
1701 }
1702
1703 impl ToJson for f32 {
1704     fn to_json(&self) -> Json { Number(*self as f64) }
1705 }
1706
1707 impl ToJson for f64 {
1708     fn to_json(&self) -> Json { Number(*self) }
1709 }
1710
1711 impl ToJson for () {
1712     fn to_json(&self) -> Json { Null }
1713 }
1714
1715 impl ToJson for bool {
1716     fn to_json(&self) -> Json { Boolean(*self) }
1717 }
1718
1719 impl ToJson for ~str {
1720     fn to_json(&self) -> Json { String((*self).clone()) }
1721 }
1722
1723 impl<A:ToJson,B:ToJson> ToJson for (A, B) {
1724     fn to_json(&self) -> Json {
1725         match *self {
1726           (ref a, ref b) => {
1727             List(~[a.to_json(), b.to_json()])
1728           }
1729         }
1730     }
1731 }
1732
1733 impl<A:ToJson,B:ToJson,C:ToJson> ToJson for (A, B, C) {
1734     fn to_json(&self) -> Json {
1735         match *self {
1736           (ref a, ref b, ref c) => {
1737             List(~[a.to_json(), b.to_json(), c.to_json()])
1738           }
1739         }
1740     }
1741 }
1742
1743 impl<A:ToJson> ToJson for ~[A] {
1744     fn to_json(&self) -> Json { List(self.iter().map(|elt| elt.to_json()).collect()) }
1745 }
1746
1747 impl<A:ToJson> ToJson for TreeMap<~str, A> {
1748     fn to_json(&self) -> Json {
1749         let mut d = TreeMap::new();
1750         for (key, value) in self.iter() {
1751             d.insert((*key).clone(), value.to_json());
1752         }
1753         Object(~d)
1754     }
1755 }
1756
1757 impl<A:ToJson> ToJson for HashMap<~str, A> {
1758     fn to_json(&self) -> Json {
1759         let mut d = TreeMap::new();
1760         for (key, value) in self.iter() {
1761             d.insert((*key).clone(), value.to_json());
1762         }
1763         Object(~d)
1764     }
1765 }
1766
1767 impl<A:ToJson> ToJson for Option<A> {
1768     fn to_json(&self) -> Json {
1769         match *self {
1770           None => Null,
1771           Some(ref value) => value.to_json()
1772         }
1773     }
1774 }
1775
1776 impl fmt::Show for Json {
1777     /// Encodes a json value into a string
1778     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1779         self.to_writer(f.buf)
1780     }
1781 }
1782
1783 #[cfg(test)]
1784 mod tests {
1785     use {Encodable, Decodable};
1786     use super::{Encoder, Decoder, Error, Boolean, Number, List, String, Null,
1787                 PrettyEncoder, Object, Json, from_str, ParseError, ExpectedError,
1788                 MissingFieldError, UnknownVariantError, DecodeResult };
1789     use std::io;
1790     use collections::TreeMap;
1791
1792     #[deriving(Eq, Encodable, Decodable, Show)]
1793     enum Animal {
1794         Dog,
1795         Frog(~str, int)
1796     }
1797
1798     #[deriving(Eq, Encodable, Decodable, Show)]
1799     struct Inner {
1800         a: (),
1801         b: uint,
1802         c: ~[~str],
1803     }
1804
1805     #[deriving(Eq, Encodable, Decodable, Show)]
1806     struct Outer {
1807         inner: ~[Inner],
1808     }
1809
1810     fn mk_object(items: &[(~str, Json)]) -> Json {
1811         let mut d = ~TreeMap::new();
1812
1813         for item in items.iter() {
1814             match *item {
1815                 (ref key, ref value) => { d.insert((*key).clone(), (*value).clone()); },
1816             }
1817         };
1818
1819         Object(d)
1820     }
1821
1822     #[test]
1823     fn test_write_null() {
1824         assert_eq!(Null.to_str(), "null".to_owned());
1825         assert_eq!(Null.to_pretty_str(), "null".to_owned());
1826     }
1827
1828
1829     #[test]
1830     fn test_write_number() {
1831         assert_eq!(Number(3.0).to_str(), "3".to_owned());
1832         assert_eq!(Number(3.0).to_pretty_str(), "3".to_owned());
1833
1834         assert_eq!(Number(3.1).to_str(), "3.1".to_owned());
1835         assert_eq!(Number(3.1).to_pretty_str(), "3.1".to_owned());
1836
1837         assert_eq!(Number(-1.5).to_str(), "-1.5".to_owned());
1838         assert_eq!(Number(-1.5).to_pretty_str(), "-1.5".to_owned());
1839
1840         assert_eq!(Number(0.5).to_str(), "0.5".to_owned());
1841         assert_eq!(Number(0.5).to_pretty_str(), "0.5".to_owned());
1842     }
1843
1844     #[test]
1845     fn test_write_str() {
1846         assert_eq!(String("".to_owned()).to_str(), "\"\"".to_owned());
1847         assert_eq!(String("".to_owned()).to_pretty_str(), "\"\"".to_owned());
1848
1849         assert_eq!(String("foo".to_owned()).to_str(), "\"foo\"".to_owned());
1850         assert_eq!(String("foo".to_owned()).to_pretty_str(), "\"foo\"".to_owned());
1851     }
1852
1853     #[test]
1854     fn test_write_bool() {
1855         assert_eq!(Boolean(true).to_str(), "true".to_owned());
1856         assert_eq!(Boolean(true).to_pretty_str(), "true".to_owned());
1857
1858         assert_eq!(Boolean(false).to_str(), "false".to_owned());
1859         assert_eq!(Boolean(false).to_pretty_str(), "false".to_owned());
1860     }
1861
1862     #[test]
1863     fn test_write_list() {
1864         assert_eq!(List(~[]).to_str(), "[]".to_owned());
1865         assert_eq!(List(~[]).to_pretty_str(), "[]".to_owned());
1866
1867         assert_eq!(List(~[Boolean(true)]).to_str(), "[true]".to_owned());
1868         assert_eq!(
1869             List(~[Boolean(true)]).to_pretty_str(),
1870             "\
1871             [\n  \
1872                 true\n\
1873             ]".to_owned()
1874         );
1875
1876         let long_test_list = List(~[
1877             Boolean(false),
1878             Null,
1879             List(~[String("foo\nbar".to_owned()), Number(3.5)])]);
1880
1881         assert_eq!(long_test_list.to_str(),
1882             "[false,null,[\"foo\\nbar\",3.5]]".to_owned());
1883         assert_eq!(
1884             long_test_list.to_pretty_str(),
1885             "\
1886             [\n  \
1887                 false,\n  \
1888                 null,\n  \
1889                 [\n    \
1890                     \"foo\\nbar\",\n    \
1891                     3.5\n  \
1892                 ]\n\
1893             ]".to_owned()
1894         );
1895     }
1896
1897     #[test]
1898     fn test_write_object() {
1899         assert_eq!(mk_object([]).to_str(), "{}".to_owned());
1900         assert_eq!(mk_object([]).to_pretty_str(), "{}".to_owned());
1901
1902         assert_eq!(
1903             mk_object([("a".to_owned(), Boolean(true))]).to_str(),
1904             "{\"a\":true}".to_owned()
1905         );
1906         assert_eq!(
1907             mk_object([("a".to_owned(), Boolean(true))]).to_pretty_str(),
1908             "\
1909             {\n  \
1910                 \"a\": true\n\
1911             }".to_owned()
1912         );
1913
1914         let complex_obj = mk_object([
1915                 ("b".to_owned(), List(~[
1916                     mk_object([("c".to_owned(), String("\x0c\r".to_owned()))]),
1917                     mk_object([("d".to_owned(), String("".to_owned()))])
1918                 ]))
1919             ]);
1920
1921         assert_eq!(
1922             complex_obj.to_str(),
1923             "{\
1924                 \"b\":[\
1925                     {\"c\":\"\\f\\r\"},\
1926                     {\"d\":\"\"}\
1927                 ]\
1928             }".to_owned()
1929         );
1930         assert_eq!(
1931             complex_obj.to_pretty_str(),
1932             "\
1933             {\n  \
1934                 \"b\": [\n    \
1935                     {\n      \
1936                         \"c\": \"\\f\\r\"\n    \
1937                     },\n    \
1938                     {\n      \
1939                         \"d\": \"\"\n    \
1940                     }\n  \
1941                 ]\n\
1942             }".to_owned()
1943         );
1944
1945         let a = mk_object([
1946             ("a".to_owned(), Boolean(true)),
1947             ("b".to_owned(), List(~[
1948                 mk_object([("c".to_owned(), String("\x0c\r".to_owned()))]),
1949                 mk_object([("d".to_owned(), String("".to_owned()))])
1950             ]))
1951         ]);
1952
1953         // We can't compare the strings directly because the object fields be
1954         // printed in a different order.
1955         assert_eq!(a.clone(), from_str(a.to_str()).unwrap());
1956         assert_eq!(a.clone(), from_str(a.to_pretty_str()).unwrap());
1957     }
1958
1959     fn with_str_writer(f: |&mut io::Writer|) -> ~str {
1960         use std::io::MemWriter;
1961         use std::str;
1962
1963         let mut m = MemWriter::new();
1964         f(&mut m as &mut io::Writer);
1965         str::from_utf8(m.unwrap().as_slice()).unwrap().to_owned()
1966     }
1967
1968     #[test]
1969     fn test_write_enum() {
1970         let animal = Dog;
1971         assert_eq!(
1972             with_str_writer(|wr| {
1973                 let mut encoder = Encoder::new(wr);
1974                 animal.encode(&mut encoder).unwrap();
1975             }),
1976             "\"Dog\"".to_owned()
1977         );
1978         assert_eq!(
1979             with_str_writer(|wr| {
1980                 let mut encoder = PrettyEncoder::new(wr);
1981                 animal.encode(&mut encoder).unwrap();
1982             }),
1983             "\"Dog\"".to_owned()
1984         );
1985
1986         let animal = Frog("Henry".to_owned(), 349);
1987         assert_eq!(
1988             with_str_writer(|wr| {
1989                 let mut encoder = Encoder::new(wr);
1990                 animal.encode(&mut encoder).unwrap();
1991             }),
1992             "{\"variant\":\"Frog\",\"fields\":[\"Henry\",349]}".to_owned()
1993         );
1994         assert_eq!(
1995             with_str_writer(|wr| {
1996                 let mut encoder = PrettyEncoder::new(wr);
1997                 animal.encode(&mut encoder).unwrap();
1998             }),
1999             "\
2000             [\n  \
2001                 \"Frog\",\n  \
2002                 \"Henry\",\n  \
2003                 349\n\
2004             ]".to_owned()
2005         );
2006     }
2007
2008     #[test]
2009     fn test_write_some() {
2010         let value = Some("jodhpurs".to_owned());
2011         let s = with_str_writer(|wr| {
2012             let mut encoder = Encoder::new(wr);
2013             value.encode(&mut encoder).unwrap();
2014         });
2015         assert_eq!(s, "\"jodhpurs\"".to_owned());
2016
2017         let value = Some("jodhpurs".to_owned());
2018         let s = with_str_writer(|wr| {
2019             let mut encoder = PrettyEncoder::new(wr);
2020             value.encode(&mut encoder).unwrap();
2021         });
2022         assert_eq!(s, "\"jodhpurs\"".to_owned());
2023     }
2024
2025     #[test]
2026     fn test_write_none() {
2027         let value: Option<~str> = None;
2028         let s = with_str_writer(|wr| {
2029             let mut encoder = Encoder::new(wr);
2030             value.encode(&mut encoder).unwrap();
2031         });
2032         assert_eq!(s, "null".to_owned());
2033
2034         let s = with_str_writer(|wr| {
2035             let mut encoder = Encoder::new(wr);
2036             value.encode(&mut encoder).unwrap();
2037         });
2038         assert_eq!(s, "null".to_owned());
2039     }
2040
2041     #[test]
2042     fn test_trailing_characters() {
2043         assert_eq!(from_str("nulla"),
2044             Err(ParseError("trailing characters".to_owned(), 1u, 5u)));
2045         assert_eq!(from_str("truea"),
2046             Err(ParseError("trailing characters".to_owned(), 1u, 5u)));
2047         assert_eq!(from_str("falsea"),
2048             Err(ParseError("trailing characters".to_owned(), 1u, 6u)));
2049         assert_eq!(from_str("1a"),
2050             Err(ParseError("trailing characters".to_owned(), 1u, 2u)));
2051         assert_eq!(from_str("[]a"),
2052             Err(ParseError("trailing characters".to_owned(), 1u, 3u)));
2053         assert_eq!(from_str("{}a"),
2054             Err(ParseError("trailing characters".to_owned(), 1u, 3u)));
2055     }
2056
2057     #[test]
2058     fn test_read_identifiers() {
2059         assert_eq!(from_str("n"),
2060             Err(ParseError("invalid syntax".to_owned(), 1u, 2u)));
2061         assert_eq!(from_str("nul"),
2062             Err(ParseError("invalid syntax".to_owned(), 1u, 4u)));
2063
2064         assert_eq!(from_str("t"),
2065             Err(ParseError("invalid syntax".to_owned(), 1u, 2u)));
2066         assert_eq!(from_str("truz"),
2067             Err(ParseError("invalid syntax".to_owned(), 1u, 4u)));
2068
2069         assert_eq!(from_str("f"),
2070             Err(ParseError("invalid syntax".to_owned(), 1u, 2u)));
2071         assert_eq!(from_str("faz"),
2072             Err(ParseError("invalid syntax".to_owned(), 1u, 3u)));
2073
2074         assert_eq!(from_str("null"), Ok(Null));
2075         assert_eq!(from_str("true"), Ok(Boolean(true)));
2076         assert_eq!(from_str("false"), Ok(Boolean(false)));
2077         assert_eq!(from_str(" null "), Ok(Null));
2078         assert_eq!(from_str(" true "), Ok(Boolean(true)));
2079         assert_eq!(from_str(" false "), Ok(Boolean(false)));
2080     }
2081
2082     #[test]
2083     fn test_decode_identifiers() {
2084         let mut decoder = Decoder::new(from_str("null").unwrap());
2085         let v: () = Decodable::decode(&mut decoder).unwrap();
2086         assert_eq!(v, ());
2087
2088         let mut decoder = Decoder::new(from_str("true").unwrap());
2089         let v: bool = Decodable::decode(&mut decoder).unwrap();
2090         assert_eq!(v, true);
2091
2092         let mut decoder = Decoder::new(from_str("false").unwrap());
2093         let v: bool = Decodable::decode(&mut decoder).unwrap();
2094         assert_eq!(v, false);
2095     }
2096
2097     #[test]
2098     fn test_read_number() {
2099         assert_eq!(from_str("+"),
2100             Err(ParseError("invalid syntax".to_owned(), 1u, 1u)));
2101         assert_eq!(from_str("."),
2102             Err(ParseError("invalid syntax".to_owned(), 1u, 1u)));
2103
2104         assert_eq!(from_str("-"),
2105             Err(ParseError("invalid number".to_owned(), 1u, 2u)));
2106         assert_eq!(from_str("00"),
2107             Err(ParseError("invalid number".to_owned(), 1u, 2u)));
2108         assert_eq!(from_str("1."),
2109             Err(ParseError("invalid number".to_owned(), 1u, 3u)));
2110         assert_eq!(from_str("1e"),
2111             Err(ParseError("invalid number".to_owned(), 1u, 3u)));
2112         assert_eq!(from_str("1e+"),
2113             Err(ParseError("invalid number".to_owned(), 1u, 4u)));
2114
2115         assert_eq!(from_str("3"), Ok(Number(3.0)));
2116         assert_eq!(from_str("3.1"), Ok(Number(3.1)));
2117         assert_eq!(from_str("-1.2"), Ok(Number(-1.2)));
2118         assert_eq!(from_str("0.4"), Ok(Number(0.4)));
2119         assert_eq!(from_str("0.4e5"), Ok(Number(0.4e5)));
2120         assert_eq!(from_str("0.4e+15"), Ok(Number(0.4e15)));
2121         assert_eq!(from_str("0.4e-01"), Ok(Number(0.4e-01)));
2122         assert_eq!(from_str(" 3 "), Ok(Number(3.0)));
2123     }
2124
2125     #[test]
2126     fn test_decode_numbers() {
2127         let mut decoder = Decoder::new(from_str("3").unwrap());
2128         let v: f64 = Decodable::decode(&mut decoder).unwrap();
2129         assert_eq!(v, 3.0);
2130
2131         let mut decoder = Decoder::new(from_str("3.1").unwrap());
2132         let v: f64 = Decodable::decode(&mut decoder).unwrap();
2133         assert_eq!(v, 3.1);
2134
2135         let mut decoder = Decoder::new(from_str("-1.2").unwrap());
2136         let v: f64 = Decodable::decode(&mut decoder).unwrap();
2137         assert_eq!(v, -1.2);
2138
2139         let mut decoder = Decoder::new(from_str("0.4").unwrap());
2140         let v: f64 = Decodable::decode(&mut decoder).unwrap();
2141         assert_eq!(v, 0.4);
2142
2143         let mut decoder = Decoder::new(from_str("0.4e5").unwrap());
2144         let v: f64 = Decodable::decode(&mut decoder).unwrap();
2145         assert_eq!(v, 0.4e5);
2146
2147         let mut decoder = Decoder::new(from_str("0.4e15").unwrap());
2148         let v: f64 = Decodable::decode(&mut decoder).unwrap();
2149         assert_eq!(v, 0.4e15);
2150
2151         let mut decoder = Decoder::new(from_str("0.4e-01").unwrap());
2152         let v: f64 = Decodable::decode(&mut decoder).unwrap();
2153         assert_eq!(v, 0.4e-01);
2154     }
2155
2156     #[test]
2157     fn test_read_str() {
2158         assert_eq!(from_str("\""),
2159             Err(ParseError("EOF while parsing string".to_owned(), 1u, 2u)));
2160         assert_eq!(from_str("\"lol"),
2161             Err(ParseError("EOF while parsing string".to_owned(), 1u, 5u)));
2162
2163         assert_eq!(from_str("\"\""), Ok(String("".to_owned())));
2164         assert_eq!(from_str("\"foo\""), Ok(String("foo".to_owned())));
2165         assert_eq!(from_str("\"\\\"\""), Ok(String("\"".to_owned())));
2166         assert_eq!(from_str("\"\\b\""), Ok(String("\x08".to_owned())));
2167         assert_eq!(from_str("\"\\n\""), Ok(String("\n".to_owned())));
2168         assert_eq!(from_str("\"\\r\""), Ok(String("\r".to_owned())));
2169         assert_eq!(from_str("\"\\t\""), Ok(String("\t".to_owned())));
2170         assert_eq!(from_str(" \"foo\" "), Ok(String("foo".to_owned())));
2171         assert_eq!(from_str("\"\\u12ab\""), Ok(String("\u12ab".to_owned())));
2172         assert_eq!(from_str("\"\\uAB12\""), Ok(String("\uAB12".to_owned())));
2173
2174         // Non-BMP escapes.  The exact error messages and positions are kind of
2175         // arbitrary.
2176         assert_eq!(from_str("\"\\ud83d\\udca9\""), Ok(String("\U0001F4A9".to_owned())));
2177         assert!(from_str("\"\\ud83d\"").is_err());
2178         assert!(from_str("\"\\udca9\"").is_err());
2179         assert!(from_str("\"\\ud83d\\ud83d\"").is_err());
2180         assert!(from_str("\"\\ud83dx\"").is_err());
2181         assert!(from_str("\"\\udca9\\udca9\"").is_err());
2182         assert!(from_str("\"\\udca9x\"").is_err());
2183     }
2184
2185     #[test]
2186     fn test_decode_str() {
2187         let mut decoder = Decoder::new(from_str("\"\"").unwrap());
2188         let v: ~str = Decodable::decode(&mut decoder).unwrap();
2189         assert_eq!(v, "".to_owned());
2190
2191         let mut decoder = Decoder::new(from_str("\"foo\"").unwrap());
2192         let v: ~str = Decodable::decode(&mut decoder).unwrap();
2193         assert_eq!(v, "foo".to_owned());
2194
2195         let mut decoder = Decoder::new(from_str("\"\\\"\"").unwrap());
2196         let v: ~str = Decodable::decode(&mut decoder).unwrap();
2197         assert_eq!(v, "\"".to_owned());
2198
2199         let mut decoder = Decoder::new(from_str("\"\\b\"").unwrap());
2200         let v: ~str = Decodable::decode(&mut decoder).unwrap();
2201         assert_eq!(v, "\x08".to_owned());
2202
2203         let mut decoder = Decoder::new(from_str("\"\\n\"").unwrap());
2204         let v: ~str = Decodable::decode(&mut decoder).unwrap();
2205         assert_eq!(v, "\n".to_owned());
2206
2207         let mut decoder = Decoder::new(from_str("\"\\r\"").unwrap());
2208         let v: ~str = Decodable::decode(&mut decoder).unwrap();
2209         assert_eq!(v, "\r".to_owned());
2210
2211         let mut decoder = Decoder::new(from_str("\"\\t\"").unwrap());
2212         let v: ~str = Decodable::decode(&mut decoder).unwrap();
2213         assert_eq!(v, "\t".to_owned());
2214
2215         let mut decoder = Decoder::new(from_str("\"\\u12ab\"").unwrap());
2216         let v: ~str = Decodable::decode(&mut decoder).unwrap();
2217         assert_eq!(v, "\u12ab".to_owned());
2218
2219         let mut decoder = Decoder::new(from_str("\"\\uAB12\"").unwrap());
2220         let v: ~str = Decodable::decode(&mut decoder).unwrap();
2221         assert_eq!(v, "\uAB12".to_owned());
2222     }
2223
2224     #[test]
2225     fn test_read_list() {
2226         assert_eq!(from_str("["),
2227             Err(ParseError("EOF while parsing value".to_owned(), 1u, 2u)));
2228         assert_eq!(from_str("[1"),
2229             Err(ParseError("EOF while parsing list".to_owned(), 1u, 3u)));
2230         assert_eq!(from_str("[1,"),
2231             Err(ParseError("EOF while parsing value".to_owned(), 1u, 4u)));
2232         assert_eq!(from_str("[1,]"),
2233             Err(ParseError("invalid syntax".to_owned(), 1u, 4u)));
2234         assert_eq!(from_str("[6 7]"),
2235             Err(ParseError("expected `,` or `]`".to_owned(), 1u, 4u)));
2236
2237         assert_eq!(from_str("[]"), Ok(List(~[])));
2238         assert_eq!(from_str("[ ]"), Ok(List(~[])));
2239         assert_eq!(from_str("[true]"), Ok(List(~[Boolean(true)])));
2240         assert_eq!(from_str("[ false ]"), Ok(List(~[Boolean(false)])));
2241         assert_eq!(from_str("[null]"), Ok(List(~[Null])));
2242         assert_eq!(from_str("[3, 1]"),
2243                      Ok(List(~[Number(3.0), Number(1.0)])));
2244         assert_eq!(from_str("\n[3, 2]\n"),
2245                      Ok(List(~[Number(3.0), Number(2.0)])));
2246         assert_eq!(from_str("[2, [4, 1]]"),
2247                Ok(List(~[Number(2.0), List(~[Number(4.0), Number(1.0)])])));
2248     }
2249
2250     #[test]
2251     fn test_decode_list() {
2252         let mut decoder = Decoder::new(from_str("[]").unwrap());
2253         let v: ~[()] = Decodable::decode(&mut decoder).unwrap();
2254         assert_eq!(v, ~[]);
2255
2256         let mut decoder = Decoder::new(from_str("[null]").unwrap());
2257         let v: ~[()] = Decodable::decode(&mut decoder).unwrap();
2258         assert_eq!(v, ~[()]);
2259
2260         let mut decoder = Decoder::new(from_str("[true]").unwrap());
2261         let v: ~[bool] = Decodable::decode(&mut decoder).unwrap();
2262         assert_eq!(v, ~[true]);
2263
2264         let mut decoder = Decoder::new(from_str("[true]").unwrap());
2265         let v: ~[bool] = Decodable::decode(&mut decoder).unwrap();
2266         assert_eq!(v, ~[true]);
2267
2268         let mut decoder = Decoder::new(from_str("[3, 1]").unwrap());
2269         let v: ~[int] = Decodable::decode(&mut decoder).unwrap();
2270         assert_eq!(v, ~[3, 1]);
2271
2272         let mut decoder = Decoder::new(from_str("[[3], [1, 2]]").unwrap());
2273         let v: ~[~[uint]] = Decodable::decode(&mut decoder).unwrap();
2274         assert_eq!(v, ~[~[3], ~[1, 2]]);
2275     }
2276
2277     #[test]
2278     fn test_read_object() {
2279         assert_eq!(from_str("{"),
2280             Err(ParseError("EOF while parsing object".to_owned(), 1u, 2u)));
2281         assert_eq!(from_str("{ "),
2282             Err(ParseError("EOF while parsing object".to_owned(), 1u, 3u)));
2283         assert_eq!(from_str("{1"),
2284             Err(ParseError("key must be a string".to_owned(), 1u, 2u)));
2285         assert_eq!(from_str("{ \"a\""),
2286             Err(ParseError("EOF while parsing object".to_owned(), 1u, 6u)));
2287         assert_eq!(from_str("{\"a\""),
2288             Err(ParseError("EOF while parsing object".to_owned(), 1u, 5u)));
2289         assert_eq!(from_str("{\"a\" "),
2290             Err(ParseError("EOF while parsing object".to_owned(), 1u, 6u)));
2291
2292         assert_eq!(from_str("{\"a\" 1"),
2293             Err(ParseError("expected `:`".to_owned(), 1u, 6u)));
2294         assert_eq!(from_str("{\"a\":"),
2295             Err(ParseError("EOF while parsing value".to_owned(), 1u, 6u)));
2296         assert_eq!(from_str("{\"a\":1"),
2297             Err(ParseError("EOF while parsing object".to_owned(), 1u, 7u)));
2298         assert_eq!(from_str("{\"a\":1 1"),
2299             Err(ParseError("expected `,` or `}`".to_owned(), 1u, 8u)));
2300         assert_eq!(from_str("{\"a\":1,"),
2301             Err(ParseError("EOF while parsing object".to_owned(), 1u, 8u)));
2302
2303         assert_eq!(from_str("{}").unwrap(), mk_object([]));
2304         assert_eq!(from_str("{\"a\": 3}").unwrap(),
2305                   mk_object([("a".to_owned(), Number(3.0))]));
2306
2307         assert_eq!(from_str(
2308                       "{ \"a\": null, \"b\" : true }").unwrap(),
2309                   mk_object([
2310                       ("a".to_owned(), Null),
2311                       ("b".to_owned(), Boolean(true))]));
2312         assert_eq!(from_str("\n{ \"a\": null, \"b\" : true }\n").unwrap(),
2313                   mk_object([
2314                       ("a".to_owned(), Null),
2315                       ("b".to_owned(), Boolean(true))]));
2316         assert_eq!(from_str(
2317                       "{\"a\" : 1.0 ,\"b\": [ true ]}").unwrap(),
2318                   mk_object([
2319                       ("a".to_owned(), Number(1.0)),
2320                       ("b".to_owned(), List(~[Boolean(true)]))
2321                   ]));
2322         assert_eq!(from_str(
2323                       "{".to_owned() +
2324                           "\"a\": 1.0, " +
2325                           "\"b\": [" +
2326                               "true," +
2327                               "\"foo\\nbar\", " +
2328                               "{ \"c\": {\"d\": null} } " +
2329                           "]" +
2330                       "}").unwrap(),
2331                   mk_object([
2332                       ("a".to_owned(), Number(1.0)),
2333                       ("b".to_owned(), List(~[
2334                           Boolean(true),
2335                           String("foo\nbar".to_owned()),
2336                           mk_object([
2337                               ("c".to_owned(), mk_object([("d".to_owned(), Null)]))
2338                           ])
2339                       ]))
2340                   ]));
2341     }
2342
2343     #[test]
2344     fn test_decode_struct() {
2345         let s = "{
2346             \"inner\": [
2347                 { \"a\": null, \"b\": 2, \"c\": [\"abc\", \"xyz\"] }
2348             ]
2349         }".to_owned();
2350         let mut decoder = Decoder::new(from_str(s).unwrap());
2351         let v: Outer = Decodable::decode(&mut decoder).unwrap();
2352         assert_eq!(
2353             v,
2354             Outer {
2355                 inner: ~[
2356                     Inner { a: (), b: 2, c: ~["abc".to_owned(), "xyz".to_owned()] }
2357                 ]
2358             }
2359         );
2360     }
2361
2362     #[test]
2363     fn test_decode_option() {
2364         let mut decoder = Decoder::new(from_str("null").unwrap());
2365         let value: Option<~str> = Decodable::decode(&mut decoder).unwrap();
2366         assert_eq!(value, None);
2367
2368         let mut decoder = Decoder::new(from_str("\"jodhpurs\"").unwrap());
2369         let value: Option<~str> = Decodable::decode(&mut decoder).unwrap();
2370         assert_eq!(value, Some("jodhpurs".to_owned()));
2371     }
2372
2373     #[test]
2374     fn test_decode_enum() {
2375         let mut decoder = Decoder::new(from_str("\"Dog\"").unwrap());
2376         let value: Animal = Decodable::decode(&mut decoder).unwrap();
2377         assert_eq!(value, Dog);
2378
2379         let s = "{\"variant\":\"Frog\",\"fields\":[\"Henry\",349]}";
2380         let mut decoder = Decoder::new(from_str(s).unwrap());
2381         let value: Animal = Decodable::decode(&mut decoder).unwrap();
2382         assert_eq!(value, Frog("Henry".to_owned(), 349));
2383     }
2384
2385     #[test]
2386     fn test_decode_map() {
2387         let s = "{\"a\": \"Dog\", \"b\": {\"variant\":\"Frog\",\
2388                   \"fields\":[\"Henry\", 349]}}".to_owned();
2389         let mut decoder = Decoder::new(from_str(s).unwrap());
2390         let mut map: TreeMap<~str, Animal> = Decodable::decode(&mut decoder).unwrap();
2391
2392         assert_eq!(map.pop(&"a".to_owned()), Some(Dog));
2393         assert_eq!(map.pop(&"b".to_owned()), Some(Frog("Henry".to_owned(), 349)));
2394     }
2395
2396     #[test]
2397     fn test_multiline_errors() {
2398         assert_eq!(from_str("{\n  \"foo\":\n \"bar\""),
2399             Err(ParseError("EOF while parsing object".to_owned(), 3u, 8u)));
2400     }
2401
2402     #[deriving(Decodable)]
2403     struct DecodeStruct {
2404         x: f64,
2405         y: bool,
2406         z: ~str,
2407         w: ~[DecodeStruct]
2408     }
2409     #[deriving(Decodable)]
2410     enum DecodeEnum {
2411         A(f64),
2412         B(~str)
2413     }
2414     fn check_err<T: Decodable<Decoder, Error>>(to_parse: &'static str, expected: Error) {
2415         let res: DecodeResult<T> = match from_str(to_parse) {
2416             Err(e) => Err(e),
2417             Ok(json) => Decodable::decode(&mut Decoder::new(json))
2418         };
2419         match res {
2420             Ok(_) => fail!("`{}` parsed & decoded ok, expecting error `{}`",
2421                               to_parse, expected),
2422             Err(ParseError(e, _, _)) => fail!("`{}` is not valid json: {}",
2423                                            to_parse, e),
2424             Err(e) => {
2425                 assert_eq!(e, expected);
2426             }
2427
2428         }
2429     }
2430     #[test]
2431     fn test_decode_errors_struct() {
2432         check_err::<DecodeStruct>("[]", ExpectedError("Object".to_owned(), "[]".to_owned()));
2433         check_err::<DecodeStruct>("{\"x\": true, \"y\": true, \"z\": \"\", \"w\": []}",
2434                                   ExpectedError("Number".to_owned(), "true".to_owned()));
2435         check_err::<DecodeStruct>("{\"x\": 1, \"y\": [], \"z\": \"\", \"w\": []}",
2436                                   ExpectedError("Boolean".to_owned(), "[]".to_owned()));
2437         check_err::<DecodeStruct>("{\"x\": 1, \"y\": true, \"z\": {}, \"w\": []}",
2438                                   ExpectedError("String".to_owned(), "{}".to_owned()));
2439         check_err::<DecodeStruct>("{\"x\": 1, \"y\": true, \"z\": \"\", \"w\": null}",
2440                                   ExpectedError("List".to_owned(), "null".to_owned()));
2441         check_err::<DecodeStruct>("{\"x\": 1, \"y\": true, \"z\": \"\"}",
2442                                   MissingFieldError("w".to_owned()));
2443     }
2444     #[test]
2445     fn test_decode_errors_enum() {
2446         check_err::<DecodeEnum>("{}",
2447                                 MissingFieldError("variant".to_owned()));
2448         check_err::<DecodeEnum>("{\"variant\": 1}",
2449                                 ExpectedError("String".to_owned(), "1".to_owned()));
2450         check_err::<DecodeEnum>("{\"variant\": \"A\"}",
2451                                 MissingFieldError("fields".to_owned()));
2452         check_err::<DecodeEnum>("{\"variant\": \"A\", \"fields\": null}",
2453                                 ExpectedError("List".to_owned(), "null".to_owned()));
2454         check_err::<DecodeEnum>("{\"variant\": \"C\", \"fields\": []}",
2455                                 UnknownVariantError("C".to_owned()));
2456     }
2457
2458     #[test]
2459     fn test_find(){
2460         let json_value = from_str("{\"dog\" : \"cat\"}").unwrap();
2461         let found_str = json_value.find(&"dog".to_owned());
2462         assert!(found_str.is_some() && found_str.unwrap().as_string().unwrap() == &"cat");
2463     }
2464
2465     #[test]
2466     fn test_find_path(){
2467         let json_value = from_str("{\"dog\":{\"cat\": {\"mouse\" : \"cheese\"}}}").unwrap();
2468         let found_str = json_value.find_path(&[&"dog".to_owned(),
2469                                              &"cat".to_owned(), &"mouse".to_owned()]);
2470         assert!(found_str.is_some() && found_str.unwrap().as_string().unwrap() == &"cheese");
2471     }
2472
2473     #[test]
2474     fn test_search(){
2475         let json_value = from_str("{\"dog\":{\"cat\": {\"mouse\" : \"cheese\"}}}").unwrap();
2476         let found_str = json_value.search(&"mouse".to_owned()).and_then(|j| j.as_string());
2477         assert!(found_str.is_some());
2478         assert!(found_str.unwrap() == &"cheese");
2479     }
2480
2481     #[test]
2482     fn test_is_object(){
2483         let json_value = from_str("{}").unwrap();
2484         assert!(json_value.is_object());
2485     }
2486
2487     #[test]
2488     fn test_as_object(){
2489         let json_value = from_str("{}").unwrap();
2490         let json_object = json_value.as_object();
2491         assert!(json_object.is_some());
2492     }
2493
2494     #[test]
2495     fn test_is_list(){
2496         let json_value = from_str("[1, 2, 3]").unwrap();
2497         assert!(json_value.is_list());
2498     }
2499
2500     #[test]
2501     fn test_as_list(){
2502         let json_value = from_str("[1, 2, 3]").unwrap();
2503         let json_list = json_value.as_list();
2504         let expected_length = 3;
2505         assert!(json_list.is_some() && json_list.unwrap().len() == expected_length);
2506     }
2507
2508     #[test]
2509     fn test_is_string(){
2510         let json_value = from_str("\"dog\"").unwrap();
2511         assert!(json_value.is_string());
2512     }
2513
2514     #[test]
2515     fn test_as_string(){
2516         let json_value = from_str("\"dog\"").unwrap();
2517         let json_str = json_value.as_string();
2518         let expected_str = &"dog";
2519         assert_eq!(json_str, Some(expected_str));
2520     }
2521
2522     #[test]
2523     fn test_is_number(){
2524         let json_value = from_str("12").unwrap();
2525         assert!(json_value.is_number());
2526     }
2527
2528     #[test]
2529     fn test_as_number(){
2530         let json_value = from_str("12").unwrap();
2531         let json_num = json_value.as_number();
2532         let expected_num = 12f64;
2533         assert!(json_num.is_some() && json_num.unwrap() == expected_num);
2534     }
2535
2536     #[test]
2537     fn test_is_boolean(){
2538         let json_value = from_str("false").unwrap();
2539         assert!(json_value.is_boolean());
2540     }
2541
2542     #[test]
2543     fn test_as_boolean(){
2544         let json_value = from_str("false").unwrap();
2545         let json_bool = json_value.as_boolean();
2546         let expected_bool = false;
2547         assert!(json_bool.is_some() && json_bool.unwrap() == expected_bool);
2548     }
2549
2550     #[test]
2551     fn test_is_null(){
2552         let json_value = from_str("null").unwrap();
2553         assert!(json_value.is_null());
2554     }
2555
2556     #[test]
2557     fn test_as_null(){
2558         let json_value = from_str("null").unwrap();
2559         let json_null = json_value.as_null();
2560         let expected_null = ();
2561         assert!(json_null.is_some() && json_null.unwrap() == expected_null);
2562     }
2563
2564     #[test]
2565     fn test_encode_hashmap_with_numeric_key() {
2566         use std::str::from_utf8;
2567         use std::io::Writer;
2568         use std::io::MemWriter;
2569         use collections::HashMap;
2570         let mut hm: HashMap<uint, bool> = HashMap::new();
2571         hm.insert(1, true);
2572         let mut mem_buf = MemWriter::new();
2573         {
2574             let mut encoder = Encoder::new(&mut mem_buf as &mut io::Writer);
2575             hm.encode(&mut encoder).unwrap();
2576         }
2577         let bytes = mem_buf.unwrap();
2578         let json_str = from_utf8(bytes.as_slice()).unwrap();
2579         match from_str(json_str) {
2580             Err(_) => fail!("Unable to parse json_str: {:?}", json_str),
2581             _ => {} // it parsed and we are good to go
2582         }
2583     }
2584     #[test]
2585     fn test_prettyencode_hashmap_with_numeric_key() {
2586         use std::str::from_utf8;
2587         use std::io::Writer;
2588         use std::io::MemWriter;
2589         use collections::HashMap;
2590         let mut hm: HashMap<uint, bool> = HashMap::new();
2591         hm.insert(1, true);
2592         let mut mem_buf = MemWriter::new();
2593         {
2594             let mut encoder = PrettyEncoder::new(&mut mem_buf as &mut io::Writer);
2595             hm.encode(&mut encoder).unwrap();
2596         }
2597         let bytes = mem_buf.unwrap();
2598         let json_str = from_utf8(bytes.as_slice()).unwrap();
2599         match from_str(json_str) {
2600             Err(_) => fail!("Unable to parse json_str: {:?}", json_str),
2601             _ => {} // it parsed and we are good to go
2602         }
2603     }
2604     #[test]
2605     fn test_hashmap_with_numeric_key_can_handle_double_quote_delimited_key() {
2606         use collections::HashMap;
2607         use Decodable;
2608         let json_str = "{\"1\":true}";
2609         let json_obj = match from_str(json_str) {
2610             Err(_) => fail!("Unable to parse json_str: {:?}", json_str),
2611             Ok(o) => o
2612         };
2613         let mut decoder = Decoder::new(json_obj);
2614         let _hm: HashMap<uint, bool> = Decodable::decode(&mut decoder).unwrap();
2615     }
2616 }