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