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.
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.
11 // Rust JSON serialization library
12 // Copyright (c) 2011 Google Inc.
14 #![forbid(non_camel_case_types)]
15 #![allow(missing_doc)]
18 JSON parsing and serialization
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.
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:
39 "Street": "Downing Street 10",
41 "Country": "Great Britain"
50 # Rust Type-based Encoding and Decoding
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)]`
59 To encode using Encodable :
63 use serialize::{json, Encodable};
65 #[deriving(Encodable)]
66 pub struct TestStruct {
71 let to_encode_object = TestStruct{data_str:~"example of string to encode"};
72 let mut m = io::MemWriter::new();
74 let mut encoder = json::Encoder::new(&mut m as &mut std::io::Writer);
75 match to_encode_object.encode(&mut encoder) {
77 Err(e) => fail!("json encoding error: {}", e)
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)`.
88 let to_encode_object = ~"example of string to encode";
89 let encoded_str: ~str = json::Encoder::str_encode(&to_encode_object);
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 ...
96 When using `ToJson` the `Encodable` trait implementation is not mandatory.
98 A basic `ToJson` example using a TreeMap of attribute name / attribute value:
102 extern crate collections;
103 extern crate serialize;
106 use serialize::json::ToJson;
107 use collections::TreeMap;
109 pub struct MyStruct {
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());
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();
130 To decode a JSON string using `Decodable` trait :
133 extern crate serialize;
134 use serialize::{json, Decodable};
136 #[deriving(Decodable)]
137 pub struct MyStruct {
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) {
149 Err(e) => fail!("Decoding error: {}", e)
150 }; // create the final object
156 ## Using Autoserialization
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.
162 extern crate serialize;
163 use serialize::{json, Encodable, Decodable};
165 #[deriving(Decodable, Encodable)] //generate Decodable, Encodable impl.
166 pub struct TestStruct1 {
172 // To serialize use the `json::str_encode` to encode an object in a string.
173 // It calls the generated `Encodable` impl.
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);
179 // To deserialize use the `json::from_str` and `json::Decoder`
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
189 This example use the ToJson impl to deserialize the JSON string.
190 Example of `ToJson` trait implementation for TestStruct1.
193 extern crate serialize;
194 extern crate collections;
196 use serialize::json::ToJson;
197 use serialize::{json, Encodable, Decodable};
198 use collections::TreeMap;
200 #[deriving(Decodable, Encodable)] // generate Decodable, Encodable impl.
201 pub struct TestStruct1 {
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());
218 // Serialization using our impl of to_json
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();
224 // Deserialize like before.
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();
236 use collections::HashMap;
238 use std::io::MemWriter;
244 use collections::TreeMap;
246 /// Represents a json value
247 #[deriving(Clone, Eq)]
257 pub type List = ~[Json];
258 pub type Object = TreeMap<~str, Json>;
260 #[deriving(Eq, Show)]
263 ParseError(~str, uint, uint),
264 ExpectedError(~str, ~str),
265 MissingFieldError(~str),
266 UnknownVariantError(~str),
270 pub type EncodeResult = io::IoResult<()>;
271 pub type DecodeResult<T> = Result<T, Error>;
273 fn escape_str(s: &str) -> ~str {
274 let mut escaped = ~"\"";
277 '"' => escaped.push_str("\\\""),
278 '\\' => escaped.push_str("\\\\"),
279 '\x08' => escaped.push_str("\\b"),
280 '\x0c' => escaped.push_str("\\f"),
281 '\n' => escaped.push_str("\\n"),
282 '\r' => escaped.push_str("\\r"),
283 '\t' => escaped.push_str("\\t"),
284 _ => escaped.push_char(c),
288 escaped.push_char('"');
293 fn spaces(n: uint) -> ~str {
295 for _ in range(0, n) { ss.push_str(" "); }
299 /// A structure for implementing serialization to JSON.
300 pub struct Encoder<'a> {
301 priv wr: &'a mut io::Writer,
304 impl<'a> Encoder<'a> {
305 /// Creates a new JSON encoder whose output will be written to the writer
307 pub fn new<'a>(wr: &'a mut io::Writer) -> Encoder<'a> {
311 /// Encode the specified struct into a json [u8]
312 pub fn buffer_encode<T:Encodable<Encoder<'a>, io::IoError>>(to_encode_object: &T) -> ~[u8] {
313 //Serialize the object in a string using a writer
314 let mut m = MemWriter::new();
316 let mut encoder = Encoder::new(&mut m as &mut io::Writer);
317 // MemWriter never Errs
318 let _ = to_encode_object.encode(&mut encoder);
323 /// Encode the specified struct into a json str
324 pub fn str_encode<T:Encodable<Encoder<'a>, io::IoError>>(to_encode_object: &T) -> ~str {
325 let buff:~[u8] = Encoder::buffer_encode(to_encode_object);
326 str::from_utf8_owned(buff).unwrap()
330 impl<'a> ::Encoder<io::IoError> for Encoder<'a> {
331 fn emit_nil(&mut self) -> EncodeResult { write!(self.wr, "null") }
333 fn emit_uint(&mut self, v: uint) -> EncodeResult { self.emit_f64(v as f64) }
334 fn emit_u64(&mut self, v: u64) -> EncodeResult { self.emit_f64(v as f64) }
335 fn emit_u32(&mut self, v: u32) -> EncodeResult { self.emit_f64(v as f64) }
336 fn emit_u16(&mut self, v: u16) -> EncodeResult { self.emit_f64(v as f64) }
337 fn emit_u8(&mut self, v: u8) -> EncodeResult { self.emit_f64(v as f64) }
339 fn emit_int(&mut self, v: int) -> EncodeResult { self.emit_f64(v as f64) }
340 fn emit_i64(&mut self, v: i64) -> EncodeResult { self.emit_f64(v as f64) }
341 fn emit_i32(&mut self, v: i32) -> EncodeResult { self.emit_f64(v as f64) }
342 fn emit_i16(&mut self, v: i16) -> EncodeResult { self.emit_f64(v as f64) }
343 fn emit_i8(&mut self, v: i8) -> EncodeResult { self.emit_f64(v as f64) }
345 fn emit_bool(&mut self, v: bool) -> EncodeResult {
347 write!(self.wr, "true")
349 write!(self.wr, "false")
353 fn emit_f64(&mut self, v: f64) -> EncodeResult {
354 write!(self.wr, "{}", f64::to_str_digits(v, 6u))
356 fn emit_f32(&mut self, v: f32) -> EncodeResult { self.emit_f64(v as f64) }
358 fn emit_char(&mut self, v: char) -> EncodeResult { self.emit_str(str::from_char(v)) }
359 fn emit_str(&mut self, v: &str) -> EncodeResult {
360 write!(self.wr, "{}", escape_str(v))
363 fn emit_enum(&mut self,
365 f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult { f(self) }
367 fn emit_enum_variant(&mut self,
371 f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
372 // enums are encoded as strings or objects
374 // Kangaroo(34,"William") => {"variant": "Kangaroo", "fields": [34,"William"]}
376 write!(self.wr, "{}", escape_str(name))
378 try!(write!(self.wr, "\\{\"variant\":"));
379 try!(write!(self.wr, "{}", escape_str(name)));
380 try!(write!(self.wr, ",\"fields\":["));
382 write!(self.wr, "]\\}")
386 fn emit_enum_variant_arg(&mut self,
388 f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
390 try!(write!(self.wr, ","));
395 fn emit_enum_struct_variant(&mut self,
399 f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
400 self.emit_enum_variant(name, id, cnt, f)
403 fn emit_enum_struct_variant_field(&mut self,
406 f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
407 self.emit_enum_variant_arg(idx, f)
410 fn emit_struct(&mut self,
413 f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
414 try!(write!(self.wr, r"\{"));
416 write!(self.wr, r"\}")
419 fn emit_struct_field(&mut self,
422 f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
423 if idx != 0 { try!(write!(self.wr, ",")); }
424 try!(write!(self.wr, "{}:", escape_str(name)));
428 fn emit_tuple(&mut self, len: uint, f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
429 self.emit_seq(len, f)
431 fn emit_tuple_arg(&mut self,
433 f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
434 self.emit_seq_elt(idx, f)
437 fn emit_tuple_struct(&mut self,
440 f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
441 self.emit_seq(len, f)
443 fn emit_tuple_struct_arg(&mut self,
445 f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
446 self.emit_seq_elt(idx, f)
449 fn emit_option(&mut self, f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
452 fn emit_option_none(&mut self) -> EncodeResult { self.emit_nil() }
453 fn emit_option_some(&mut self, f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
457 fn emit_seq(&mut self, _len: uint, f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
458 try!(write!(self.wr, "["));
463 fn emit_seq_elt(&mut self, idx: uint, f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
465 try!(write!(self.wr, ","));
470 fn emit_map(&mut self, _len: uint, f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
471 try!(write!(self.wr, r"\{"));
473 write!(self.wr, r"\}")
476 fn emit_map_elt_key(&mut self,
478 f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
479 use std::str::from_utf8;
480 if idx != 0 { try!(write!(self.wr, ",")) }
481 // ref #12967, make sure to wrap a key in double quotes,
482 // in the event that its of a type that omits them (eg numbers)
483 let mut buf = MemWriter::new();
484 let mut check_encoder = Encoder::new(&mut buf);
485 try!(f(&mut check_encoder));
486 let buf = buf.unwrap();
487 let out = from_utf8(buf).unwrap();
488 let needs_wrapping = out.char_at(0) != '"' &&
489 out.char_at_reverse(out.len()) != '"';
490 if needs_wrapping { try!(write!(self.wr, "\"")); }
492 if needs_wrapping { try!(write!(self.wr, "\"")); }
496 fn emit_map_elt_val(&mut self,
498 f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
499 try!(write!(self.wr, ":"));
504 /// Another encoder for JSON, but prints out human-readable JSON instead of
506 pub struct PrettyEncoder<'a> {
507 priv wr: &'a mut io::Writer,
511 impl<'a> PrettyEncoder<'a> {
512 /// Creates a new encoder whose output will be written to the specified writer
513 pub fn new<'a>(wr: &'a mut io::Writer) -> PrettyEncoder<'a> {
521 impl<'a> ::Encoder<io::IoError> for PrettyEncoder<'a> {
522 fn emit_nil(&mut self) -> EncodeResult { write!(self.wr, "null") }
524 fn emit_uint(&mut self, v: uint) -> EncodeResult { self.emit_f64(v as f64) }
525 fn emit_u64(&mut self, v: u64) -> EncodeResult { self.emit_f64(v as f64) }
526 fn emit_u32(&mut self, v: u32) -> EncodeResult { self.emit_f64(v as f64) }
527 fn emit_u16(&mut self, v: u16) -> EncodeResult { self.emit_f64(v as f64) }
528 fn emit_u8(&mut self, v: u8) -> EncodeResult { self.emit_f64(v as f64) }
530 fn emit_int(&mut self, v: int) -> EncodeResult { self.emit_f64(v as f64) }
531 fn emit_i64(&mut self, v: i64) -> EncodeResult { self.emit_f64(v as f64) }
532 fn emit_i32(&mut self, v: i32) -> EncodeResult { self.emit_f64(v as f64) }
533 fn emit_i16(&mut self, v: i16) -> EncodeResult { self.emit_f64(v as f64) }
534 fn emit_i8(&mut self, v: i8) -> EncodeResult { self.emit_f64(v as f64) }
536 fn emit_bool(&mut self, v: bool) -> EncodeResult {
538 write!(self.wr, "true")
540 write!(self.wr, "false")
544 fn emit_f64(&mut self, v: f64) -> EncodeResult {
545 write!(self.wr, "{}", f64::to_str_digits(v, 6u))
547 fn emit_f32(&mut self, v: f32) -> EncodeResult { self.emit_f64(v as f64) }
549 fn emit_char(&mut self, v: char) -> EncodeResult { self.emit_str(str::from_char(v)) }
550 fn emit_str(&mut self, v: &str) -> EncodeResult {
551 write!(self.wr, "{}", escape_str(v))
554 fn emit_enum(&mut self,
556 f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
560 fn emit_enum_variant(&mut self,
564 f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
566 write!(self.wr, "{}", escape_str(name))
569 try!(write!(self.wr, "[\n{}{},\n", spaces(self.indent),
573 write!(self.wr, "\n{}]", spaces(self.indent))
577 fn emit_enum_variant_arg(&mut self,
579 f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
581 try!(write!(self.wr, ",\n"));
583 try!(write!(self.wr, "{}", spaces(self.indent)));
587 fn emit_enum_struct_variant(&mut self,
591 f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
592 self.emit_enum_variant(name, id, cnt, f)
595 fn emit_enum_struct_variant_field(&mut self,
598 f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
599 self.emit_enum_variant_arg(idx, f)
603 fn emit_struct(&mut self,
606 f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
608 write!(self.wr, "\\{\\}")
610 try!(write!(self.wr, "\\{"));
614 write!(self.wr, "\n{}\\}", spaces(self.indent))
618 fn emit_struct_field(&mut self,
621 f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
623 try!(write!(self.wr, "\n"));
625 try!(write!(self.wr, ",\n"));
627 try!(write!(self.wr, "{}{}: ", spaces(self.indent), escape_str(name)));
631 fn emit_tuple(&mut self,
633 f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
634 self.emit_seq(len, f)
636 fn emit_tuple_arg(&mut self,
638 f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
639 self.emit_seq_elt(idx, f)
642 fn emit_tuple_struct(&mut self,
645 f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
646 self.emit_seq(len, f)
648 fn emit_tuple_struct_arg(&mut self,
650 f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
651 self.emit_seq_elt(idx, f)
654 fn emit_option(&mut self, f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
657 fn emit_option_none(&mut self) -> EncodeResult { self.emit_nil() }
658 fn emit_option_some(&mut self, f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
662 fn emit_seq(&mut self,
664 f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
666 write!(self.wr, "[]")
668 try!(write!(self.wr, "["));
672 write!(self.wr, "\n{}]", spaces(self.indent))
676 fn emit_seq_elt(&mut self,
678 f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
680 try!(write!(self.wr, "\n"));
682 try!(write!(self.wr, ",\n"));
684 try!(write!(self.wr, "{}", spaces(self.indent)));
688 fn emit_map(&mut self,
690 f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
692 write!(self.wr, "\\{\\}")
694 try!(write!(self.wr, "\\{"));
698 write!(self.wr, "\n{}\\}", spaces(self.indent))
702 fn emit_map_elt_key(&mut self,
704 f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
705 use std::str::from_utf8;
707 try!(write!(self.wr, "\n"));
709 try!(write!(self.wr, ",\n"));
711 try!(write!(self.wr, "{}", spaces(self.indent)));
712 // ref #12967, make sure to wrap a key in double quotes,
713 // in the event that its of a type that omits them (eg numbers)
714 let mut buf = MemWriter::new();
715 let mut check_encoder = PrettyEncoder::new(&mut buf);
716 try!(f(&mut check_encoder));
717 let buf = buf.unwrap();
718 let out = from_utf8(buf).unwrap();
719 let needs_wrapping = out.char_at(0) != '"' &&
720 out.char_at_reverse(out.len()) != '"';
721 if needs_wrapping { try!(write!(self.wr, "\"")); }
723 if needs_wrapping { try!(write!(self.wr, "\"")); }
727 fn emit_map_elt_val(&mut self,
729 f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
730 try!(write!(self.wr, ": "));
735 impl<E: ::Encoder<io::IoError>> Encodable<E, io::IoError> for Json {
736 fn encode(&self, e: &mut E) -> EncodeResult {
738 Number(v) => v.encode(e),
739 String(ref v) => v.encode(e),
740 Boolean(v) => v.encode(e),
741 List(ref v) => v.encode(e),
742 Object(ref v) => v.encode(e),
743 Null => e.emit_nil(),
749 /// Encodes a json value into a io::writer. Uses a single line.
750 pub fn to_writer(&self, wr: &mut io::Writer) -> EncodeResult {
751 let mut encoder = Encoder::new(wr);
752 self.encode(&mut encoder)
755 /// Encodes a json value into a io::writer.
756 /// Pretty-prints in a more readable format.
757 pub fn to_pretty_writer(&self, wr: &mut io::Writer) -> EncodeResult {
758 let mut encoder = PrettyEncoder::new(wr);
759 self.encode(&mut encoder)
762 /// Encodes a json value into a string
763 pub fn to_pretty_str(&self) -> ~str {
764 let mut s = MemWriter::new();
765 self.to_pretty_writer(&mut s as &mut io::Writer).unwrap();
766 str::from_utf8_owned(s.unwrap()).unwrap()
769 /// If the Json value is an Object, returns the value associated with the provided key.
770 /// Otherwise, returns None.
771 pub fn find<'a>(&'a self, key: &~str) -> Option<&'a Json>{
773 &Object(ref map) => map.find(key),
778 /// Attempts to get a nested Json Object for each key in `keys`.
779 /// If any key is found not to exist, find_path will return None.
780 /// Otherwise, it will return the Json value associated with the final key.
781 pub fn find_path<'a>(&'a self, keys: &[&~str]) -> Option<&'a Json>{
782 let mut target = self;
783 for key in keys.iter() {
784 match target.find(*key) {
785 Some(t) => { target = t; },
792 /// If the Json value is an Object, performs a depth-first search until
793 /// a value associated with the provided key is found. If no value is found
794 /// or the Json value is not an Object, returns None.
795 pub fn search<'a>(&'a self, key: &~str) -> Option<&'a Json> {
797 &Object(ref map) => {
798 match map.find(key) {
799 Some(json_value) => Some(json_value),
801 let mut value : Option<&'a Json> = None;
802 for (_, v) in map.iter() {
803 value = v.search(key);
816 /// Returns true if the Json value is an Object. Returns false otherwise.
817 pub fn is_object<'a>(&'a self) -> bool {
818 self.as_object().is_some()
821 /// If the Json value is an Object, returns the associated TreeMap.
822 /// Returns None otherwise.
823 pub fn as_object<'a>(&'a self) -> Option<&'a Object> {
825 &Object(ref map) => Some(&**map),
830 /// Returns true if the Json value is a List. Returns false otherwise.
831 pub fn is_list<'a>(&'a self) -> bool {
832 self.as_list().is_some()
835 /// If the Json value is a List, returns the associated vector.
836 /// Returns None otherwise.
837 pub fn as_list<'a>(&'a self) -> Option<&'a List> {
839 &List(ref list) => Some(&*list),
844 /// Returns true if the Json value is a String. Returns false otherwise.
845 pub fn is_string<'a>(&'a self) -> bool {
846 self.as_string().is_some()
849 /// If the Json value is a String, returns the associated str.
850 /// Returns None otherwise.
851 pub fn as_string<'a>(&'a self) -> Option<&'a str> {
853 String(ref s) => Some(s.as_slice()),
858 /// Returns true if the Json value is a Number. Returns false otherwise.
859 pub fn is_number(&self) -> bool {
860 self.as_number().is_some()
863 /// If the Json value is a Number, returns the associated f64.
864 /// Returns None otherwise.
865 pub fn as_number(&self) -> Option<f64> {
867 &Number(n) => Some(n),
872 /// Returns true if the Json value is a Boolean. Returns false otherwise.
873 pub fn is_boolean(&self) -> bool {
874 self.as_boolean().is_some()
877 /// If the Json value is a Boolean, returns the associated bool.
878 /// Returns None otherwise.
879 pub fn as_boolean(&self) -> Option<bool> {
881 &Boolean(b) => Some(b),
886 /// Returns true if the Json value is a Null. Returns false otherwise.
887 pub fn is_null(&self) -> bool {
888 self.as_null().is_some()
891 /// If the Json value is a Null, returns ().
892 /// Returns None otherwise.
893 pub fn as_null(&self) -> Option<()> {
901 pub struct Parser<T> {
903 priv ch: Option<char>,
908 impl<T: Iterator<char>> Parser<T> {
909 /// Decode a json value from an Iterator<char>
910 pub fn new(rdr: T) -> Parser<T> {
922 impl<T: Iterator<char>> Parser<T> {
923 pub fn parse(&mut self) -> DecodeResult<Json> {
924 match self.parse_value() {
926 // Skip trailing whitespaces.
927 self.parse_whitespace();
928 // Make sure there is no trailing characters.
932 self.error(~"trailing characters")
940 impl<T : Iterator<char>> Parser<T> {
941 fn eof(&self) -> bool { self.ch.is_none() }
942 fn ch_or_null(&self) -> char { self.ch.unwrap_or('\x00') }
944 self.ch = self.rdr.next();
946 if self.ch_is('\n') {
954 fn next_char(&mut self) -> Option<char> {
958 fn ch_is(&self, c: char) -> bool {
962 fn error<T>(&self, msg: ~str) -> DecodeResult<T> {
963 Err(ParseError(msg, self.line, self.col))
966 fn parse_value(&mut self) -> DecodeResult<Json> {
967 self.parse_whitespace();
969 if self.eof() { return self.error(~"EOF while parsing value"); }
971 match self.ch_or_null() {
972 'n' => self.parse_ident("ull", Null),
973 't' => self.parse_ident("rue", Boolean(true)),
974 'f' => self.parse_ident("alse", Boolean(false)),
975 '0' .. '9' | '-' => self.parse_number(),
977 match self.parse_str() {
978 Ok(s) => Ok(String(s)),
982 '[' => self.parse_list(),
983 '{' => self.parse_object(),
984 _ => self.error(~"invalid syntax"),
988 fn parse_whitespace(&mut self) {
989 while self.ch_is(' ') ||
992 self.ch_is('\r') { self.bump(); }
995 fn parse_ident(&mut self, ident: &str, value: Json) -> DecodeResult<Json> {
996 if ident.chars().all(|c| Some(c) == self.next_char()) {
1000 self.error(~"invalid syntax")
1004 fn parse_number(&mut self) -> DecodeResult<Json> {
1007 if self.ch_is('-') {
1012 let mut res = match self.parse_integer() {
1014 Err(e) => return Err(e)
1017 if self.ch_is('.') {
1018 match self.parse_decimal(res) {
1020 Err(e) => return Err(e)
1024 if self.ch_is('e') || self.ch_is('E') {
1025 match self.parse_exponent(res) {
1027 Err(e) => return Err(e)
1031 Ok(Number(neg * res))
1034 fn parse_integer(&mut self) -> DecodeResult<f64> {
1037 match self.ch_or_null() {
1041 // There can be only one leading '0'.
1042 match self.ch_or_null() {
1043 '0' .. '9' => return self.error(~"invalid number"),
1049 match self.ch_or_null() {
1052 res += ((c as int) - ('0' as int)) as f64;
1060 _ => return self.error(~"invalid number"),
1065 fn parse_decimal(&mut self, res: f64) -> DecodeResult<f64> {
1068 // Make sure a digit follows the decimal place.
1069 match self.ch_or_null() {
1071 _ => return self.error(~"invalid number")
1077 match self.ch_or_null() {
1080 res += (((c as int) - ('0' as int)) as f64) * dec;
1091 fn parse_exponent(&mut self, mut res: f64) -> DecodeResult<f64> {
1095 let mut neg_exp = false;
1097 if self.ch_is('+') {
1099 } else if self.ch_is('-') {
1104 // Make sure a digit follows the exponent place.
1105 match self.ch_or_null() {
1107 _ => return self.error(~"invalid number")
1110 match self.ch_or_null() {
1113 exp += (c as uint) - ('0' as uint);
1121 let exp: f64 = num::pow(10u as f64, exp);
1131 fn parse_str(&mut self) -> DecodeResult<~str> {
1132 let mut escape = false;
1138 return self.error(~"EOF while parsing string");
1142 match self.ch_or_null() {
1143 '"' => res.push_char('"'),
1144 '\\' => res.push_char('\\'),
1145 '/' => res.push_char('/'),
1146 'b' => res.push_char('\x08'),
1147 'f' => res.push_char('\x0c'),
1148 'n' => res.push_char('\n'),
1149 'r' => res.push_char('\r'),
1150 't' => res.push_char('\t'),
1155 while i < 4u && !self.eof() {
1157 n = match self.ch_or_null() {
1158 c @ '0' .. '9' => n * 16u + (c as uint) - ('0' as uint),
1159 'a' | 'A' => n * 16u + 10u,
1160 'b' | 'B' => n * 16u + 11u,
1161 'c' | 'C' => n * 16u + 12u,
1162 'd' | 'D' => n * 16u + 13u,
1163 'e' | 'E' => n * 16u + 14u,
1164 'f' | 'F' => n * 16u + 15u,
1165 _ => return self.error(
1166 ~"invalid \\u escape (unrecognized hex)")
1172 // Error out if we didn't parse 4 digits.
1175 ~"invalid \\u escape (not four digits)");
1178 res.push_char(char::from_u32(n as u32).unwrap());
1180 _ => return self.error(~"invalid escape"),
1183 } else if self.ch_is('\\') {
1187 Some('"') => { self.bump(); return Ok(res); },
1188 Some(c) => res.push_char(c),
1189 None => unreachable!()
1195 fn parse_list(&mut self) -> DecodeResult<Json> {
1197 self.parse_whitespace();
1199 let mut values = ~[];
1201 if self.ch_is(']') {
1203 return Ok(List(values));
1207 match self.parse_value() {
1208 Ok(v) => values.push(v),
1209 Err(e) => return Err(e)
1212 self.parse_whitespace();
1214 return self.error(~"EOF while parsing list");
1217 if self.ch_is(',') {
1219 } else if self.ch_is(']') {
1221 return Ok(List(values));
1223 return self.error(~"expected `,` or `]`")
1228 fn parse_object(&mut self) -> DecodeResult<Json> {
1230 self.parse_whitespace();
1232 let mut values = ~TreeMap::new();
1234 if self.ch_is('}') {
1236 return Ok(Object(values));
1240 self.parse_whitespace();
1242 if !self.ch_is('"') {
1243 return self.error(~"key must be a string");
1246 let key = match self.parse_str() {
1248 Err(e) => return Err(e)
1251 self.parse_whitespace();
1253 if !self.ch_is(':') {
1254 if self.eof() { break; }
1255 return self.error(~"expected `:`");
1259 match self.parse_value() {
1260 Ok(value) => { values.insert(key, value); }
1261 Err(e) => return Err(e)
1263 self.parse_whitespace();
1265 match self.ch_or_null() {
1267 '}' => { self.bump(); return Ok(Object(values)); },
1269 if self.eof() { break; }
1270 return self.error(~"expected `,` or `}`");
1275 return self.error(~"EOF while parsing object");
1279 /// Decodes a json value from an `&mut io::Reader`
1280 pub fn from_reader(rdr: &mut io::Reader) -> DecodeResult<Json> {
1281 let contents = match rdr.read_to_end() {
1283 Err(e) => return Err(IoError(e))
1285 let s = match str::from_utf8_owned(contents) {
1287 None => return Err(ParseError(~"contents not utf-8", 0, 0))
1289 let mut parser = Parser::new(s.chars());
1293 /// Decodes a json value from a string
1294 pub fn from_str(s: &str) -> DecodeResult<Json> {
1295 let mut parser = Parser::new(s.chars());
1299 /// A structure to decode JSON to values in rust.
1300 pub struct Decoder {
1301 priv stack: ~[Json],
1305 /// Creates a new decoder instance for decoding the specified JSON value.
1306 pub fn new(json: Json) -> Decoder {
1314 fn pop(&mut self) -> Json {
1315 self.stack.pop().unwrap()
1319 macro_rules! expect(
1320 ($e:expr, Null) => ({
1323 other => Err(ExpectedError(~"Null", format!("{}", other)))
1326 ($e:expr, $t:ident) => ({
1329 other => Err(ExpectedError(stringify!($t).to_owned(), format!("{}", other)))
1334 impl ::Decoder<Error> for Decoder {
1335 fn read_nil(&mut self) -> DecodeResult<()> {
1337 try!(expect!(self.pop(), Null));
1341 fn read_u64(&mut self) -> DecodeResult<u64 > { Ok(try!(self.read_f64()) as u64) }
1342 fn read_u32(&mut self) -> DecodeResult<u32 > { Ok(try!(self.read_f64()) as u32) }
1343 fn read_u16(&mut self) -> DecodeResult<u16 > { Ok(try!(self.read_f64()) as u16) }
1344 fn read_u8 (&mut self) -> DecodeResult<u8 > { Ok(try!(self.read_f64()) as u8) }
1345 fn read_uint(&mut self) -> DecodeResult<uint> { Ok(try!(self.read_f64()) as uint) }
1347 fn read_i64(&mut self) -> DecodeResult<i64> { Ok(try!(self.read_f64()) as i64) }
1348 fn read_i32(&mut self) -> DecodeResult<i32> { Ok(try!(self.read_f64()) as i32) }
1349 fn read_i16(&mut self) -> DecodeResult<i16> { Ok(try!(self.read_f64()) as i16) }
1350 fn read_i8 (&mut self) -> DecodeResult<i8 > { Ok(try!(self.read_f64()) as i8) }
1351 fn read_int(&mut self) -> DecodeResult<int> { Ok(try!(self.read_f64()) as int) }
1353 fn read_bool(&mut self) -> DecodeResult<bool> {
1354 debug!("read_bool");
1355 Ok(try!(expect!(self.pop(), Boolean)))
1358 fn read_f64(&mut self) -> DecodeResult<f64> {
1359 use std::from_str::FromStr;
1364 // re: #12967.. a type w/ numeric keys (ie HashMap<uint, V> etc)
1365 // is going to have a string here, as per JSON spec..
1366 Ok(FromStr::from_str(s).unwrap())
1368 value => Err(ExpectedError(~"Number", format!("{}", value)))
1372 fn read_f32(&mut self) -> DecodeResult<f32> { Ok(try!(self.read_f64()) as f32) }
1374 fn read_char(&mut self) -> DecodeResult<char> {
1375 let s = try!(self.read_str());
1377 let mut it = s.chars();
1378 match (it.next(), it.next()) {
1379 // exactly one character
1380 (Some(c), None) => return Ok(c),
1384 Err(ExpectedError(~"single character string", format!("{}", s)))
1387 fn read_str(&mut self) -> DecodeResult<~str> {
1389 Ok(try!(expect!(self.pop(), String)))
1392 fn read_enum<T>(&mut self,
1394 f: |&mut Decoder| -> DecodeResult<T>) -> DecodeResult<T> {
1395 debug!("read_enum({})", name);
1399 fn read_enum_variant<T>(&mut self,
1401 f: |&mut Decoder, uint| -> DecodeResult<T>)
1402 -> DecodeResult<T> {
1403 debug!("read_enum_variant(names={:?})", names);
1404 let name = match self.pop() {
1407 let n = match o.pop(&~"variant") {
1408 Some(String(s)) => s,
1409 Some(val) => return Err(ExpectedError(~"String", format!("{}", val))),
1410 None => return Err(MissingFieldError(~"variant"))
1412 match o.pop(&~"fields") {
1414 for field in l.move_rev_iter() {
1415 self.stack.push(field.clone());
1418 Some(val) => return Err(ExpectedError(~"List", format!("{}", val))),
1419 None => return Err(MissingFieldError(~"fields"))
1423 json => return Err(ExpectedError(~"String or Object", format!("{}", json)))
1425 let idx = match names.iter().position(|n| str::eq_slice(*n, name)) {
1427 None => return Err(UnknownVariantError(name))
1432 fn read_enum_variant_arg<T>(&mut self, idx: uint, f: |&mut Decoder| -> DecodeResult<T>)
1433 -> DecodeResult<T> {
1434 debug!("read_enum_variant_arg(idx={})", idx);
1438 fn read_enum_struct_variant<T>(&mut self,
1440 f: |&mut Decoder, uint| -> DecodeResult<T>)
1441 -> DecodeResult<T> {
1442 debug!("read_enum_struct_variant(names={:?})", names);
1443 self.read_enum_variant(names, f)
1447 fn read_enum_struct_variant_field<T>(&mut self,
1450 f: |&mut Decoder| -> DecodeResult<T>)
1451 -> DecodeResult<T> {
1452 debug!("read_enum_struct_variant_field(name={}, idx={})", name, idx);
1453 self.read_enum_variant_arg(idx, f)
1456 fn read_struct<T>(&mut self,
1459 f: |&mut Decoder| -> DecodeResult<T>)
1460 -> DecodeResult<T> {
1461 debug!("read_struct(name={}, len={})", name, len);
1462 let value = try!(f(self));
1467 fn read_struct_field<T>(&mut self,
1470 f: |&mut Decoder| -> DecodeResult<T>)
1471 -> DecodeResult<T> {
1472 debug!("read_struct_field(name={}, idx={})", name, idx);
1473 let mut obj = try!(expect!(self.pop(), Object));
1475 let value = match obj.pop(&name.to_owned()) {
1476 None => return Err(MissingFieldError(name.to_owned())),
1478 self.stack.push(json);
1482 self.stack.push(Object(obj));
1486 fn read_tuple<T>(&mut self, f: |&mut Decoder, uint| -> DecodeResult<T>) -> DecodeResult<T> {
1487 debug!("read_tuple()");
1491 fn read_tuple_arg<T>(&mut self,
1493 f: |&mut Decoder| -> DecodeResult<T>) -> DecodeResult<T> {
1494 debug!("read_tuple_arg(idx={})", idx);
1495 self.read_seq_elt(idx, f)
1498 fn read_tuple_struct<T>(&mut self,
1500 f: |&mut Decoder, uint| -> DecodeResult<T>)
1501 -> DecodeResult<T> {
1502 debug!("read_tuple_struct(name={})", name);
1506 fn read_tuple_struct_arg<T>(&mut self,
1508 f: |&mut Decoder| -> DecodeResult<T>)
1509 -> DecodeResult<T> {
1510 debug!("read_tuple_struct_arg(idx={})", idx);
1511 self.read_tuple_arg(idx, f)
1514 fn read_option<T>(&mut self, f: |&mut Decoder, bool| -> DecodeResult<T>) -> DecodeResult<T> {
1516 Null => f(self, false),
1517 value => { self.stack.push(value); f(self, true) }
1521 fn read_seq<T>(&mut self, f: |&mut Decoder, uint| -> DecodeResult<T>) -> DecodeResult<T> {
1522 debug!("read_seq()");
1523 let list = try!(expect!(self.pop(), List));
1524 let len = list.len();
1525 for v in list.move_rev_iter() {
1531 fn read_seq_elt<T>(&mut self,
1533 f: |&mut Decoder| -> DecodeResult<T>) -> DecodeResult<T> {
1534 debug!("read_seq_elt(idx={})", idx);
1538 fn read_map<T>(&mut self, f: |&mut Decoder, uint| -> DecodeResult<T>) -> DecodeResult<T> {
1539 debug!("read_map()");
1540 let obj = try!(expect!(self.pop(), Object));
1541 let len = obj.len();
1542 for (key, value) in obj.move_iter() {
1543 self.stack.push(value);
1544 self.stack.push(String(key));
1549 fn read_map_elt_key<T>(&mut self, idx: uint, f: |&mut Decoder| -> DecodeResult<T>)
1550 -> DecodeResult<T> {
1551 debug!("read_map_elt_key(idx={})", idx);
1555 fn read_map_elt_val<T>(&mut self, idx: uint, f: |&mut Decoder| -> DecodeResult<T>)
1556 -> DecodeResult<T> {
1557 debug!("read_map_elt_val(idx={})", idx);
1562 /// Test if two json values are less than one another
1564 fn lt(&self, other: &Json) -> bool {
1568 Number(f1) => f0 < f1,
1569 String(_) | Boolean(_) | List(_) | Object(_) |
1577 String(ref s1) => s0 < s1,
1578 Boolean(_) | List(_) | Object(_) | Null => true
1584 Number(_) | String(_) => false,
1585 Boolean(b1) => b0 < b1,
1586 List(_) | Object(_) | Null => true
1592 Number(_) | String(_) | Boolean(_) => false,
1593 List(ref l1) => (*l0) < (*l1),
1594 Object(_) | Null => true
1600 Number(_) | String(_) | Boolean(_) | List(_) => false,
1601 Object(ref d1) => d0 < d1,
1608 Number(_) | String(_) | Boolean(_) | List(_) |
1618 /// A trait for converting values to JSON
1620 /// Converts the value of `self` to an instance of JSON
1621 fn to_json(&self) -> Json;
1624 impl ToJson for Json {
1625 fn to_json(&self) -> Json { (*self).clone() }
1628 impl ToJson for int {
1629 fn to_json(&self) -> Json { Number(*self as f64) }
1632 impl ToJson for i8 {
1633 fn to_json(&self) -> Json { Number(*self as f64) }
1636 impl ToJson for i16 {
1637 fn to_json(&self) -> Json { Number(*self as f64) }
1640 impl ToJson for i32 {
1641 fn to_json(&self) -> Json { Number(*self as f64) }
1644 impl ToJson for i64 {
1645 fn to_json(&self) -> Json { Number(*self as f64) }
1648 impl ToJson for uint {
1649 fn to_json(&self) -> Json { Number(*self as f64) }
1652 impl ToJson for u8 {
1653 fn to_json(&self) -> Json { Number(*self as f64) }
1656 impl ToJson for u16 {
1657 fn to_json(&self) -> Json { Number(*self as f64) }
1660 impl ToJson for u32 {
1661 fn to_json(&self) -> Json { Number(*self as f64) }
1664 impl ToJson for u64 {
1665 fn to_json(&self) -> Json { Number(*self as f64) }
1668 impl ToJson for f32 {
1669 fn to_json(&self) -> Json { Number(*self as f64) }
1672 impl ToJson for f64 {
1673 fn to_json(&self) -> Json { Number(*self) }
1676 impl ToJson for () {
1677 fn to_json(&self) -> Json { Null }
1680 impl ToJson for bool {
1681 fn to_json(&self) -> Json { Boolean(*self) }
1684 impl ToJson for ~str {
1685 fn to_json(&self) -> Json { String((*self).clone()) }
1688 impl<A:ToJson,B:ToJson> ToJson for (A, B) {
1689 fn to_json(&self) -> Json {
1692 List(~[a.to_json(), b.to_json()])
1698 impl<A:ToJson,B:ToJson,C:ToJson> ToJson for (A, B, C) {
1699 fn to_json(&self) -> Json {
1701 (ref a, ref b, ref c) => {
1702 List(~[a.to_json(), b.to_json(), c.to_json()])
1708 impl<A:ToJson> ToJson for ~[A] {
1709 fn to_json(&self) -> Json { List(self.map(|elt| elt.to_json())) }
1712 impl<A:ToJson> ToJson for TreeMap<~str, A> {
1713 fn to_json(&self) -> Json {
1714 let mut d = TreeMap::new();
1715 for (key, value) in self.iter() {
1716 d.insert((*key).clone(), value.to_json());
1722 impl<A:ToJson> ToJson for HashMap<~str, A> {
1723 fn to_json(&self) -> Json {
1724 let mut d = TreeMap::new();
1725 for (key, value) in self.iter() {
1726 d.insert((*key).clone(), value.to_json());
1732 impl<A:ToJson> ToJson for Option<A> {
1733 fn to_json(&self) -> Json {
1736 Some(ref value) => value.to_json()
1741 impl fmt::Show for Json {
1742 /// Encodes a json value into a string
1743 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1744 self.to_writer(f.buf)
1750 use {Encodable, Decodable};
1751 use super::{Encoder, Decoder, Error, Boolean, Number, List, String, Null,
1752 PrettyEncoder, Object, Json, from_str, ParseError, ExpectedError,
1753 MissingFieldError, UnknownVariantError, DecodeResult };
1755 use collections::TreeMap;
1757 #[deriving(Eq, Encodable, Decodable, Show)]
1763 #[deriving(Eq, Encodable, Decodable, Show)]
1770 #[deriving(Eq, Encodable, Decodable, Show)]
1775 fn mk_object(items: &[(~str, Json)]) -> Json {
1776 let mut d = ~TreeMap::new();
1778 for item in items.iter() {
1780 (ref key, ref value) => { d.insert((*key).clone(), (*value).clone()); },
1788 fn test_write_null() {
1789 assert_eq!(Null.to_str(), ~"null");
1790 assert_eq!(Null.to_pretty_str(), ~"null");
1795 fn test_write_number() {
1796 assert_eq!(Number(3.0).to_str(), ~"3");
1797 assert_eq!(Number(3.0).to_pretty_str(), ~"3");
1799 assert_eq!(Number(3.1).to_str(), ~"3.1");
1800 assert_eq!(Number(3.1).to_pretty_str(), ~"3.1");
1802 assert_eq!(Number(-1.5).to_str(), ~"-1.5");
1803 assert_eq!(Number(-1.5).to_pretty_str(), ~"-1.5");
1805 assert_eq!(Number(0.5).to_str(), ~"0.5");
1806 assert_eq!(Number(0.5).to_pretty_str(), ~"0.5");
1810 fn test_write_str() {
1811 assert_eq!(String(~"").to_str(), ~"\"\"");
1812 assert_eq!(String(~"").to_pretty_str(), ~"\"\"");
1814 assert_eq!(String(~"foo").to_str(), ~"\"foo\"");
1815 assert_eq!(String(~"foo").to_pretty_str(), ~"\"foo\"");
1819 fn test_write_bool() {
1820 assert_eq!(Boolean(true).to_str(), ~"true");
1821 assert_eq!(Boolean(true).to_pretty_str(), ~"true");
1823 assert_eq!(Boolean(false).to_str(), ~"false");
1824 assert_eq!(Boolean(false).to_pretty_str(), ~"false");
1828 fn test_write_list() {
1829 assert_eq!(List(~[]).to_str(), ~"[]");
1830 assert_eq!(List(~[]).to_pretty_str(), ~"[]");
1832 assert_eq!(List(~[Boolean(true)]).to_str(), ~"[true]");
1834 List(~[Boolean(true)]).to_pretty_str(),
1841 let long_test_list = List(~[
1844 List(~[String(~"foo\nbar"), Number(3.5)])]);
1846 assert_eq!(long_test_list.to_str(),
1847 ~"[false,null,[\"foo\\nbar\",3.5]]");
1849 long_test_list.to_pretty_str(),
1863 fn test_write_object() {
1864 assert_eq!(mk_object([]).to_str(), ~"{}");
1865 assert_eq!(mk_object([]).to_pretty_str(), ~"{}");
1868 mk_object([(~"a", Boolean(true))]).to_str(),
1872 mk_object([(~"a", Boolean(true))]).to_pretty_str(),
1879 let complex_obj = mk_object([
1881 mk_object([(~"c", String(~"\x0c\r"))]),
1882 mk_object([(~"d", String(~""))])
1887 complex_obj.to_str(),
1890 {\"c\":\"\\f\\r\"},\
1896 complex_obj.to_pretty_str(),
1901 \"c\": \"\\f\\r\"\n \
1911 (~"a", Boolean(true)),
1913 mk_object([(~"c", String(~"\x0c\r"))]),
1914 mk_object([(~"d", String(~""))])
1918 // We can't compare the strings directly because the object fields be
1919 // printed in a different order.
1920 assert_eq!(a.clone(), from_str(a.to_str()).unwrap());
1921 assert_eq!(a.clone(), from_str(a.to_pretty_str()).unwrap());
1924 fn with_str_writer(f: |&mut io::Writer|) -> ~str {
1925 use std::io::MemWriter;
1928 let mut m = MemWriter::new();
1929 f(&mut m as &mut io::Writer);
1930 str::from_utf8_owned(m.unwrap()).unwrap()
1934 fn test_write_enum() {
1937 with_str_writer(|wr| {
1938 let mut encoder = Encoder::new(wr);
1939 animal.encode(&mut encoder).unwrap();
1944 with_str_writer(|wr| {
1945 let mut encoder = PrettyEncoder::new(wr);
1946 animal.encode(&mut encoder).unwrap();
1951 let animal = Frog(~"Henry", 349);
1953 with_str_writer(|wr| {
1954 let mut encoder = Encoder::new(wr);
1955 animal.encode(&mut encoder).unwrap();
1957 ~"{\"variant\":\"Frog\",\"fields\":[\"Henry\",349]}"
1960 with_str_writer(|wr| {
1961 let mut encoder = PrettyEncoder::new(wr);
1962 animal.encode(&mut encoder).unwrap();
1974 fn test_write_some() {
1975 let value = Some(~"jodhpurs");
1976 let s = with_str_writer(|wr| {
1977 let mut encoder = Encoder::new(wr);
1978 value.encode(&mut encoder).unwrap();
1980 assert_eq!(s, ~"\"jodhpurs\"");
1982 let value = Some(~"jodhpurs");
1983 let s = with_str_writer(|wr| {
1984 let mut encoder = PrettyEncoder::new(wr);
1985 value.encode(&mut encoder).unwrap();
1987 assert_eq!(s, ~"\"jodhpurs\"");
1991 fn test_write_none() {
1992 let value: Option<~str> = None;
1993 let s = with_str_writer(|wr| {
1994 let mut encoder = Encoder::new(wr);
1995 value.encode(&mut encoder).unwrap();
1997 assert_eq!(s, ~"null");
1999 let s = with_str_writer(|wr| {
2000 let mut encoder = Encoder::new(wr);
2001 value.encode(&mut encoder).unwrap();
2003 assert_eq!(s, ~"null");
2007 fn test_trailing_characters() {
2008 assert_eq!(from_str("nulla"),
2009 Err(ParseError(~"trailing characters", 1u, 5u)));
2010 assert_eq!(from_str("truea"),
2011 Err(ParseError(~"trailing characters", 1u, 5u)));
2012 assert_eq!(from_str("falsea"),
2013 Err(ParseError(~"trailing characters", 1u, 6u)));
2014 assert_eq!(from_str("1a"),
2015 Err(ParseError(~"trailing characters", 1u, 2u)));
2016 assert_eq!(from_str("[]a"),
2017 Err(ParseError(~"trailing characters", 1u, 3u)));
2018 assert_eq!(from_str("{}a"),
2019 Err(ParseError(~"trailing characters", 1u, 3u)));
2023 fn test_read_identifiers() {
2024 assert_eq!(from_str("n"),
2025 Err(ParseError(~"invalid syntax", 1u, 2u)));
2026 assert_eq!(from_str("nul"),
2027 Err(ParseError(~"invalid syntax", 1u, 4u)));
2029 assert_eq!(from_str("t"),
2030 Err(ParseError(~"invalid syntax", 1u, 2u)));
2031 assert_eq!(from_str("truz"),
2032 Err(ParseError(~"invalid syntax", 1u, 4u)));
2034 assert_eq!(from_str("f"),
2035 Err(ParseError(~"invalid syntax", 1u, 2u)));
2036 assert_eq!(from_str("faz"),
2037 Err(ParseError(~"invalid syntax", 1u, 3u)));
2039 assert_eq!(from_str("null"), Ok(Null));
2040 assert_eq!(from_str("true"), Ok(Boolean(true)));
2041 assert_eq!(from_str("false"), Ok(Boolean(false)));
2042 assert_eq!(from_str(" null "), Ok(Null));
2043 assert_eq!(from_str(" true "), Ok(Boolean(true)));
2044 assert_eq!(from_str(" false "), Ok(Boolean(false)));
2048 fn test_decode_identifiers() {
2049 let mut decoder = Decoder::new(from_str("null").unwrap());
2050 let v: () = Decodable::decode(&mut decoder).unwrap();
2053 let mut decoder = Decoder::new(from_str("true").unwrap());
2054 let v: bool = Decodable::decode(&mut decoder).unwrap();
2055 assert_eq!(v, true);
2057 let mut decoder = Decoder::new(from_str("false").unwrap());
2058 let v: bool = Decodable::decode(&mut decoder).unwrap();
2059 assert_eq!(v, false);
2063 fn test_read_number() {
2064 assert_eq!(from_str("+"),
2065 Err(ParseError(~"invalid syntax", 1u, 1u)));
2066 assert_eq!(from_str("."),
2067 Err(ParseError(~"invalid syntax", 1u, 1u)));
2069 assert_eq!(from_str("-"),
2070 Err(ParseError(~"invalid number", 1u, 2u)));
2071 assert_eq!(from_str("00"),
2072 Err(ParseError(~"invalid number", 1u, 2u)));
2073 assert_eq!(from_str("1."),
2074 Err(ParseError(~"invalid number", 1u, 3u)));
2075 assert_eq!(from_str("1e"),
2076 Err(ParseError(~"invalid number", 1u, 3u)));
2077 assert_eq!(from_str("1e+"),
2078 Err(ParseError(~"invalid number", 1u, 4u)));
2080 assert_eq!(from_str("3"), Ok(Number(3.0)));
2081 assert_eq!(from_str("3.1"), Ok(Number(3.1)));
2082 assert_eq!(from_str("-1.2"), Ok(Number(-1.2)));
2083 assert_eq!(from_str("0.4"), Ok(Number(0.4)));
2084 assert_eq!(from_str("0.4e5"), Ok(Number(0.4e5)));
2085 assert_eq!(from_str("0.4e+15"), Ok(Number(0.4e15)));
2086 assert_eq!(from_str("0.4e-01"), Ok(Number(0.4e-01)));
2087 assert_eq!(from_str(" 3 "), Ok(Number(3.0)));
2091 fn test_decode_numbers() {
2092 let mut decoder = Decoder::new(from_str("3").unwrap());
2093 let v: f64 = Decodable::decode(&mut decoder).unwrap();
2096 let mut decoder = Decoder::new(from_str("3.1").unwrap());
2097 let v: f64 = Decodable::decode(&mut decoder).unwrap();
2100 let mut decoder = Decoder::new(from_str("-1.2").unwrap());
2101 let v: f64 = Decodable::decode(&mut decoder).unwrap();
2102 assert_eq!(v, -1.2);
2104 let mut decoder = Decoder::new(from_str("0.4").unwrap());
2105 let v: f64 = Decodable::decode(&mut decoder).unwrap();
2108 let mut decoder = Decoder::new(from_str("0.4e5").unwrap());
2109 let v: f64 = Decodable::decode(&mut decoder).unwrap();
2110 assert_eq!(v, 0.4e5);
2112 let mut decoder = Decoder::new(from_str("0.4e15").unwrap());
2113 let v: f64 = Decodable::decode(&mut decoder).unwrap();
2114 assert_eq!(v, 0.4e15);
2116 let mut decoder = Decoder::new(from_str("0.4e-01").unwrap());
2117 let v: f64 = Decodable::decode(&mut decoder).unwrap();
2118 assert_eq!(v, 0.4e-01);
2122 fn test_read_str() {
2123 assert_eq!(from_str("\""),
2124 Err(ParseError(~"EOF while parsing string", 1u, 2u)));
2125 assert_eq!(from_str("\"lol"),
2126 Err(ParseError(~"EOF while parsing string", 1u, 5u)));
2128 assert_eq!(from_str("\"\""), Ok(String(~"")));
2129 assert_eq!(from_str("\"foo\""), Ok(String(~"foo")));
2130 assert_eq!(from_str("\"\\\"\""), Ok(String(~"\"")));
2131 assert_eq!(from_str("\"\\b\""), Ok(String(~"\x08")));
2132 assert_eq!(from_str("\"\\n\""), Ok(String(~"\n")));
2133 assert_eq!(from_str("\"\\r\""), Ok(String(~"\r")));
2134 assert_eq!(from_str("\"\\t\""), Ok(String(~"\t")));
2135 assert_eq!(from_str(" \"foo\" "), Ok(String(~"foo")));
2136 assert_eq!(from_str("\"\\u12ab\""), Ok(String(~"\u12ab")));
2137 assert_eq!(from_str("\"\\uAB12\""), Ok(String(~"\uAB12")));
2141 fn test_decode_str() {
2142 let mut decoder = Decoder::new(from_str("\"\"").unwrap());
2143 let v: ~str = Decodable::decode(&mut decoder).unwrap();
2146 let mut decoder = Decoder::new(from_str("\"foo\"").unwrap());
2147 let v: ~str = Decodable::decode(&mut decoder).unwrap();
2148 assert_eq!(v, ~"foo");
2150 let mut decoder = Decoder::new(from_str("\"\\\"\"").unwrap());
2151 let v: ~str = Decodable::decode(&mut decoder).unwrap();
2152 assert_eq!(v, ~"\"");
2154 let mut decoder = Decoder::new(from_str("\"\\b\"").unwrap());
2155 let v: ~str = Decodable::decode(&mut decoder).unwrap();
2156 assert_eq!(v, ~"\x08");
2158 let mut decoder = Decoder::new(from_str("\"\\n\"").unwrap());
2159 let v: ~str = Decodable::decode(&mut decoder).unwrap();
2160 assert_eq!(v, ~"\n");
2162 let mut decoder = Decoder::new(from_str("\"\\r\"").unwrap());
2163 let v: ~str = Decodable::decode(&mut decoder).unwrap();
2164 assert_eq!(v, ~"\r");
2166 let mut decoder = Decoder::new(from_str("\"\\t\"").unwrap());
2167 let v: ~str = Decodable::decode(&mut decoder).unwrap();
2168 assert_eq!(v, ~"\t");
2170 let mut decoder = Decoder::new(from_str("\"\\u12ab\"").unwrap());
2171 let v: ~str = Decodable::decode(&mut decoder).unwrap();
2172 assert_eq!(v, ~"\u12ab");
2174 let mut decoder = Decoder::new(from_str("\"\\uAB12\"").unwrap());
2175 let v: ~str = Decodable::decode(&mut decoder).unwrap();
2176 assert_eq!(v, ~"\uAB12");
2180 fn test_read_list() {
2181 assert_eq!(from_str("["),
2182 Err(ParseError(~"EOF while parsing value", 1u, 2u)));
2183 assert_eq!(from_str("[1"),
2184 Err(ParseError(~"EOF while parsing list", 1u, 3u)));
2185 assert_eq!(from_str("[1,"),
2186 Err(ParseError(~"EOF while parsing value", 1u, 4u)));
2187 assert_eq!(from_str("[1,]"),
2188 Err(ParseError(~"invalid syntax", 1u, 4u)));
2189 assert_eq!(from_str("[6 7]"),
2190 Err(ParseError(~"expected `,` or `]`", 1u, 4u)));
2192 assert_eq!(from_str("[]"), Ok(List(~[])));
2193 assert_eq!(from_str("[ ]"), Ok(List(~[])));
2194 assert_eq!(from_str("[true]"), Ok(List(~[Boolean(true)])));
2195 assert_eq!(from_str("[ false ]"), Ok(List(~[Boolean(false)])));
2196 assert_eq!(from_str("[null]"), Ok(List(~[Null])));
2197 assert_eq!(from_str("[3, 1]"),
2198 Ok(List(~[Number(3.0), Number(1.0)])));
2199 assert_eq!(from_str("\n[3, 2]\n"),
2200 Ok(List(~[Number(3.0), Number(2.0)])));
2201 assert_eq!(from_str("[2, [4, 1]]"),
2202 Ok(List(~[Number(2.0), List(~[Number(4.0), Number(1.0)])])));
2206 fn test_decode_list() {
2207 let mut decoder = Decoder::new(from_str("[]").unwrap());
2208 let v: ~[()] = Decodable::decode(&mut decoder).unwrap();
2211 let mut decoder = Decoder::new(from_str("[null]").unwrap());
2212 let v: ~[()] = Decodable::decode(&mut decoder).unwrap();
2213 assert_eq!(v, ~[()]);
2215 let mut decoder = Decoder::new(from_str("[true]").unwrap());
2216 let v: ~[bool] = Decodable::decode(&mut decoder).unwrap();
2217 assert_eq!(v, ~[true]);
2219 let mut decoder = Decoder::new(from_str("[true]").unwrap());
2220 let v: ~[bool] = Decodable::decode(&mut decoder).unwrap();
2221 assert_eq!(v, ~[true]);
2223 let mut decoder = Decoder::new(from_str("[3, 1]").unwrap());
2224 let v: ~[int] = Decodable::decode(&mut decoder).unwrap();
2225 assert_eq!(v, ~[3, 1]);
2227 let mut decoder = Decoder::new(from_str("[[3], [1, 2]]").unwrap());
2228 let v: ~[~[uint]] = Decodable::decode(&mut decoder).unwrap();
2229 assert_eq!(v, ~[~[3], ~[1, 2]]);
2233 fn test_read_object() {
2234 assert_eq!(from_str("{"),
2235 Err(ParseError(~"EOF while parsing object", 1u, 2u)));
2236 assert_eq!(from_str("{ "),
2237 Err(ParseError(~"EOF while parsing object", 1u, 3u)));
2238 assert_eq!(from_str("{1"),
2239 Err(ParseError(~"key must be a string", 1u, 2u)));
2240 assert_eq!(from_str("{ \"a\""),
2241 Err(ParseError(~"EOF while parsing object", 1u, 6u)));
2242 assert_eq!(from_str("{\"a\""),
2243 Err(ParseError(~"EOF while parsing object", 1u, 5u)));
2244 assert_eq!(from_str("{\"a\" "),
2245 Err(ParseError(~"EOF while parsing object", 1u, 6u)));
2247 assert_eq!(from_str("{\"a\" 1"),
2248 Err(ParseError(~"expected `:`", 1u, 6u)));
2249 assert_eq!(from_str("{\"a\":"),
2250 Err(ParseError(~"EOF while parsing value", 1u, 6u)));
2251 assert_eq!(from_str("{\"a\":1"),
2252 Err(ParseError(~"EOF while parsing object", 1u, 7u)));
2253 assert_eq!(from_str("{\"a\":1 1"),
2254 Err(ParseError(~"expected `,` or `}`", 1u, 8u)));
2255 assert_eq!(from_str("{\"a\":1,"),
2256 Err(ParseError(~"EOF while parsing object", 1u, 8u)));
2258 assert_eq!(from_str("{}").unwrap(), mk_object([]));
2259 assert_eq!(from_str("{\"a\": 3}").unwrap(),
2260 mk_object([(~"a", Number(3.0))]));
2262 assert_eq!(from_str(
2263 "{ \"a\": null, \"b\" : true }").unwrap(),
2266 (~"b", Boolean(true))]));
2267 assert_eq!(from_str("\n{ \"a\": null, \"b\" : true }\n").unwrap(),
2270 (~"b", Boolean(true))]));
2271 assert_eq!(from_str(
2272 "{\"a\" : 1.0 ,\"b\": [ true ]}").unwrap(),
2274 (~"a", Number(1.0)),
2275 (~"b", List(~[Boolean(true)]))
2277 assert_eq!(from_str(
2283 "{ \"c\": {\"d\": null} } " +
2287 (~"a", Number(1.0)),
2290 String(~"foo\nbar"),
2292 (~"c", mk_object([(~"d", Null)]))
2299 fn test_decode_struct() {
2302 { \"a\": null, \"b\": 2, \"c\": [\"abc\", \"xyz\"] }
2305 let mut decoder = Decoder::new(from_str(s).unwrap());
2306 let v: Outer = Decodable::decode(&mut decoder).unwrap();
2311 Inner { a: (), b: 2, c: ~[~"abc", ~"xyz"] }
2318 fn test_decode_option() {
2319 let mut decoder = Decoder::new(from_str("null").unwrap());
2320 let value: Option<~str> = Decodable::decode(&mut decoder).unwrap();
2321 assert_eq!(value, None);
2323 let mut decoder = Decoder::new(from_str("\"jodhpurs\"").unwrap());
2324 let value: Option<~str> = Decodable::decode(&mut decoder).unwrap();
2325 assert_eq!(value, Some(~"jodhpurs"));
2329 fn test_decode_enum() {
2330 let mut decoder = Decoder::new(from_str("\"Dog\"").unwrap());
2331 let value: Animal = Decodable::decode(&mut decoder).unwrap();
2332 assert_eq!(value, Dog);
2334 let s = "{\"variant\":\"Frog\",\"fields\":[\"Henry\",349]}";
2335 let mut decoder = Decoder::new(from_str(s).unwrap());
2336 let value: Animal = Decodable::decode(&mut decoder).unwrap();
2337 assert_eq!(value, Frog(~"Henry", 349));
2341 fn test_decode_map() {
2342 let s = ~"{\"a\": \"Dog\", \"b\": {\"variant\":\"Frog\",\"fields\":[\"Henry\", 349]}}";
2343 let mut decoder = Decoder::new(from_str(s).unwrap());
2344 let mut map: TreeMap<~str, Animal> = Decodable::decode(&mut decoder).unwrap();
2346 assert_eq!(map.pop(&~"a"), Some(Dog));
2347 assert_eq!(map.pop(&~"b"), Some(Frog(~"Henry", 349)));
2351 fn test_multiline_errors() {
2352 assert_eq!(from_str("{\n \"foo\":\n \"bar\""),
2353 Err(ParseError(~"EOF while parsing object", 3u, 8u)));
2356 #[deriving(Decodable)]
2357 struct DecodeStruct {
2363 #[deriving(Decodable)]
2368 fn check_err<T: Decodable<Decoder, Error>>(to_parse: &'static str, expected: Error) {
2369 let res: DecodeResult<T> = match from_str(to_parse) {
2371 Ok(json) => Decodable::decode(&mut Decoder::new(json))
2374 Ok(_) => fail!("`{}` parsed & decoded ok, expecting error `{}`",
2375 to_parse, expected),
2376 Err(ParseError(e, _, _)) => fail!("`{}` is not valid json: {}",
2379 assert_eq!(e, expected);
2385 fn test_decode_errors_struct() {
2386 check_err::<DecodeStruct>("[]", ExpectedError(~"Object", ~"[]"));
2387 check_err::<DecodeStruct>("{\"x\": true, \"y\": true, \"z\": \"\", \"w\": []}",
2388 ExpectedError(~"Number", ~"true"));
2389 check_err::<DecodeStruct>("{\"x\": 1, \"y\": [], \"z\": \"\", \"w\": []}",
2390 ExpectedError(~"Boolean", ~"[]"));
2391 check_err::<DecodeStruct>("{\"x\": 1, \"y\": true, \"z\": {}, \"w\": []}",
2392 ExpectedError(~"String", ~"{}"));
2393 check_err::<DecodeStruct>("{\"x\": 1, \"y\": true, \"z\": \"\", \"w\": null}",
2394 ExpectedError(~"List", ~"null"));
2395 check_err::<DecodeStruct>("{\"x\": 1, \"y\": true, \"z\": \"\"}",
2396 MissingFieldError(~"w"));
2399 fn test_decode_errors_enum() {
2400 check_err::<DecodeEnum>("{}",
2401 MissingFieldError(~"variant"));
2402 check_err::<DecodeEnum>("{\"variant\": 1}",
2403 ExpectedError(~"String", ~"1"));
2404 check_err::<DecodeEnum>("{\"variant\": \"A\"}",
2405 MissingFieldError(~"fields"));
2406 check_err::<DecodeEnum>("{\"variant\": \"A\", \"fields\": null}",
2407 ExpectedError(~"List", ~"null"));
2408 check_err::<DecodeEnum>("{\"variant\": \"C\", \"fields\": []}",
2409 UnknownVariantError(~"C"));
2414 let json_value = from_str("{\"dog\" : \"cat\"}").unwrap();
2415 let found_str = json_value.find(&~"dog");
2416 assert!(found_str.is_some() && found_str.unwrap().as_string().unwrap() == &"cat");
2420 fn test_find_path(){
2421 let json_value = from_str("{\"dog\":{\"cat\": {\"mouse\" : \"cheese\"}}}").unwrap();
2422 let found_str = json_value.find_path(&[&~"dog", &~"cat", &~"mouse"]);
2423 assert!(found_str.is_some() && found_str.unwrap().as_string().unwrap() == &"cheese");
2428 let json_value = from_str("{\"dog\":{\"cat\": {\"mouse\" : \"cheese\"}}}").unwrap();
2429 let found_str = json_value.search(&~"mouse").and_then(|j| j.as_string());
2430 assert!(found_str.is_some());
2431 assert!(found_str.unwrap() == &"cheese");
2435 fn test_is_object(){
2436 let json_value = from_str("{}").unwrap();
2437 assert!(json_value.is_object());
2441 fn test_as_object(){
2442 let json_value = from_str("{}").unwrap();
2443 let json_object = json_value.as_object();
2444 assert!(json_object.is_some());
2449 let json_value = from_str("[1, 2, 3]").unwrap();
2450 assert!(json_value.is_list());
2455 let json_value = from_str("[1, 2, 3]").unwrap();
2456 let json_list = json_value.as_list();
2457 let expected_length = 3;
2458 assert!(json_list.is_some() && json_list.unwrap().len() == expected_length);
2462 fn test_is_string(){
2463 let json_value = from_str("\"dog\"").unwrap();
2464 assert!(json_value.is_string());
2468 fn test_as_string(){
2469 let json_value = from_str("\"dog\"").unwrap();
2470 let json_str = json_value.as_string();
2471 let expected_str = &"dog";
2472 assert_eq!(json_str, Some(expected_str));
2476 fn test_is_number(){
2477 let json_value = from_str("12").unwrap();
2478 assert!(json_value.is_number());
2482 fn test_as_number(){
2483 let json_value = from_str("12").unwrap();
2484 let json_num = json_value.as_number();
2485 let expected_num = 12f64;
2486 assert!(json_num.is_some() && json_num.unwrap() == expected_num);
2490 fn test_is_boolean(){
2491 let json_value = from_str("false").unwrap();
2492 assert!(json_value.is_boolean());
2496 fn test_as_boolean(){
2497 let json_value = from_str("false").unwrap();
2498 let json_bool = json_value.as_boolean();
2499 let expected_bool = false;
2500 assert!(json_bool.is_some() && json_bool.unwrap() == expected_bool);
2505 let json_value = from_str("null").unwrap();
2506 assert!(json_value.is_null());
2511 let json_value = from_str("null").unwrap();
2512 let json_null = json_value.as_null();
2513 let expected_null = ();
2514 assert!(json_null.is_some() && json_null.unwrap() == expected_null);
2518 fn test_encode_hashmap_with_numeric_key() {
2519 use std::str::from_utf8;
2520 use std::io::Writer;
2521 use std::io::MemWriter;
2522 use collections::HashMap;
2523 let mut hm: HashMap<uint, bool> = HashMap::new();
2525 let mut mem_buf = MemWriter::new();
2527 let mut encoder = Encoder::new(&mut mem_buf as &mut io::Writer);
2528 hm.encode(&mut encoder).unwrap();
2530 let bytes = mem_buf.unwrap();
2531 let json_str = from_utf8(bytes).unwrap();
2532 match from_str(json_str) {
2533 Err(_) => fail!("Unable to parse json_str: {:?}", json_str),
2534 _ => {} // it parsed and we are good to go
2538 fn test_prettyencode_hashmap_with_numeric_key() {
2539 use std::str::from_utf8;
2540 use std::io::Writer;
2541 use std::io::MemWriter;
2542 use collections::HashMap;
2543 let mut hm: HashMap<uint, bool> = HashMap::new();
2545 let mut mem_buf = MemWriter::new();
2547 let mut encoder = PrettyEncoder::new(&mut mem_buf as &mut io::Writer);
2548 hm.encode(&mut encoder).unwrap();
2550 let bytes = mem_buf.unwrap();
2551 let json_str = from_utf8(bytes).unwrap();
2552 match from_str(json_str) {
2553 Err(_) => fail!("Unable to parse json_str: {:?}", json_str),
2554 _ => {} // it parsed and we are good to go
2558 fn test_hashmap_with_numeric_key_can_handle_double_quote_delimited_key() {
2559 use collections::HashMap;
2561 let json_str = "{\"1\":true}";
2562 let json_obj = match from_str(json_str) {
2563 Err(_) => fail!("Unable to parse json_str: {:?}", json_str),
2566 let mut decoder = Decoder::new(json_obj);
2567 let _hm: HashMap<uint, bool> = Decodable::decode(&mut decoder).unwrap();