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