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".to_string()};
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 (String) or buffer (~[u8]): `str_encode(&m)` and `buffer_encode(&m)`.
88 let to_encode_object = "example of string to encode".to_string();
89 let encoded_str: String = 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 = box TreeMap::new();
117 d.insert("attr1".to_string(), self.attr1.to_json());
118 d.insert("attr2".to_string(), self.attr2.to_json());
124 let test2: MyStruct = MyStruct {attr1: 1, attr2:"test".to_string()};
125 let tjson: json::Json = test2.to_json();
126 let json_str: String = tjson.to_str().into_string();
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: String =
144 "{\"attr1\":1,\"attr2\":\"toto\"}".to_string();
145 let json_object = json::from_str(json_str_to_decode.as_slice());
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 {
169 data_vector: Vec<u8>,
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".to_string(), data_vector:vec![2,3,4,5]};
177 let encoded_str: String = 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.as_slice());
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 {
204 data_vector: Vec<u8>,
207 impl ToJson for TestStruct1 {
208 fn to_json( &self ) -> json::Json {
209 let mut d = box TreeMap::new();
210 d.insert("data_int".to_string(), self.data_int.to_json());
211 d.insert("data_str".to_string(), self.data_str.to_json());
212 d.insert("data_vector".to_string(), self.data_vector.to_json());
218 // Serialization using our impl of to_json
220 let test2: TestStruct1 = TestStruct1 {data_int: 1, data_str:"toto".to_string(),
221 data_vector:vec![2,3,4,5]};
222 let tjson: json::Json = test2.to_json();
223 let json_str: String = tjson.to_str().into_string();
225 // Deserialize like before.
228 json::Decoder::new(json::from_str(json_str.as_slice()).unwrap());
229 // create the final object
230 let decoded2: TestStruct1 = Decodable::decode(&mut decoder).unwrap();
239 use std::io::MemWriter;
243 use std::str::ScalarValue;
245 use std::string::String;
249 use collections::{HashMap, TreeMap};
251 /// Represents a json value
252 #[deriving(Clone, Eq)]
262 pub type List = Vec<Json>;
263 pub type Object = TreeMap<String, Json>;
265 /// The errors that can arise while parsing a JSON stream.
266 #[deriving(Clone, Eq)]
270 EOFWhileParsingObject,
272 EOFWhileParsingValue,
273 EOFWhileParsingString,
278 InvalidUnicodeCodePoint,
279 LoneLeadingSurrogateInHexEscape,
280 UnexpectedEndOfHexEscape,
286 #[deriving(Clone, Eq, Show)]
287 pub enum ParserError {
289 SyntaxError(ErrorCode, uint, uint),
290 IoError(io::IoErrorKind, &'static str),
293 // Builder and Parser have the same errors.
294 pub type BuilderError = ParserError;
296 #[deriving(Clone, Eq, Show)]
297 pub enum DecoderError {
298 ParseError(ParserError),
299 ExpectedError(String, String),
300 MissingFieldError(String),
301 UnknownVariantError(String),
304 /// Returns a readable error string for a given error code.
305 pub fn error_str(error: ErrorCode) -> &'static str {
307 InvalidSyntax => "invalid syntax",
308 InvalidNumber => "invalid number",
309 EOFWhileParsingObject => "EOF While parsing object",
310 EOFWhileParsingList => "EOF While parsing list",
311 EOFWhileParsingValue => "EOF While parsing value",
312 EOFWhileParsingString => "EOF While parsing string",
313 KeyMustBeAString => "key must be a string",
314 ExpectedColon => "expected `:`",
315 TrailingCharacters => "trailing characters",
316 InvalidEscape => "invalid escape",
317 UnrecognizedHex => "invalid \\u escape (unrecognized hex)",
318 NotFourDigit => "invalid \\u escape (not four digits)",
319 NotUtf8 => "contents not utf-8",
320 InvalidUnicodeCodePoint => "invalid unicode code point",
321 LoneLeadingSurrogateInHexEscape => "lone leading surrogate in hex escape",
322 UnexpectedEndOfHexEscape => "unexpected end of hex escape",
326 impl fmt::Show for ErrorCode {
327 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
328 error_str(*self).fmt(f)
333 fn io_error_to_error(io: io::IoError) -> ParserError {
334 IoError(io.kind, io.desc)
337 pub type EncodeResult = io::IoResult<()>;
338 pub type DecodeResult<T> = Result<T, DecoderError>;
340 fn escape_str(s: &str) -> String {
341 let mut escaped = String::from_str("\"");
344 '"' => escaped.push_str("\\\""),
345 '\\' => escaped.push_str("\\\\"),
346 '\x08' => escaped.push_str("\\b"),
347 '\x0c' => escaped.push_str("\\f"),
348 '\n' => escaped.push_str("\\n"),
349 '\r' => escaped.push_str("\\r"),
350 '\t' => escaped.push_str("\\t"),
351 _ => escaped.push_char(c),
354 escaped.push_char('"');
358 fn spaces(n: uint) -> String {
359 let mut ss = String::new();
360 for _ in range(0, n) {
366 /// A structure for implementing serialization to JSON.
367 pub struct Encoder<'a> {
368 wr: &'a mut io::Writer,
371 impl<'a> Encoder<'a> {
372 /// Creates a new JSON encoder whose output will be written to the writer
374 pub fn new<'a>(wr: &'a mut io::Writer) -> Encoder<'a> {
378 /// Encode the specified struct into a json [u8]
379 pub fn buffer_encode<T:Encodable<Encoder<'a>, io::IoError>>(to_encode_object: &T) -> Vec<u8> {
380 //Serialize the object in a string using a writer
381 let mut m = MemWriter::new();
383 let mut encoder = Encoder::new(&mut m as &mut io::Writer);
384 // MemWriter never Errs
385 let _ = to_encode_object.encode(&mut encoder);
390 /// Encode the specified struct into a json str
391 pub fn str_encode<T:Encodable<Encoder<'a>,
393 to_encode_object: &T)
395 let buff = Encoder::buffer_encode(to_encode_object);
396 str::from_utf8(buff.as_slice()).unwrap().to_string()
400 impl<'a> ::Encoder<io::IoError> for Encoder<'a> {
401 fn emit_nil(&mut self) -> EncodeResult { write!(self.wr, "null") }
403 fn emit_uint(&mut self, v: uint) -> EncodeResult { self.emit_f64(v as f64) }
404 fn emit_u64(&mut self, v: u64) -> EncodeResult { self.emit_f64(v as f64) }
405 fn emit_u32(&mut self, v: u32) -> EncodeResult { self.emit_f64(v as f64) }
406 fn emit_u16(&mut self, v: u16) -> EncodeResult { self.emit_f64(v as f64) }
407 fn emit_u8(&mut self, v: u8) -> EncodeResult { self.emit_f64(v as f64) }
409 fn emit_int(&mut self, v: int) -> EncodeResult { self.emit_f64(v as f64) }
410 fn emit_i64(&mut self, v: i64) -> EncodeResult { self.emit_f64(v as f64) }
411 fn emit_i32(&mut self, v: i32) -> EncodeResult { self.emit_f64(v as f64) }
412 fn emit_i16(&mut self, v: i16) -> EncodeResult { self.emit_f64(v as f64) }
413 fn emit_i8(&mut self, v: i8) -> EncodeResult { self.emit_f64(v as f64) }
415 fn emit_bool(&mut self, v: bool) -> EncodeResult {
417 write!(self.wr, "true")
419 write!(self.wr, "false")
423 fn emit_f64(&mut self, v: f64) -> EncodeResult {
424 write!(self.wr, "{}", f64::to_str_digits(v, 6u))
426 fn emit_f32(&mut self, v: f32) -> EncodeResult { self.emit_f64(v as f64) }
428 fn emit_char(&mut self, v: char) -> EncodeResult {
429 self.emit_str(str::from_char(v).as_slice())
431 fn emit_str(&mut self, v: &str) -> EncodeResult {
432 write!(self.wr, "{}", escape_str(v))
435 fn emit_enum(&mut self,
437 f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult { f(self) }
439 fn emit_enum_variant(&mut self,
443 f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
444 // enums are encoded as strings or objects
446 // Kangaroo(34,"William") => {"variant": "Kangaroo", "fields": [34,"William"]}
448 write!(self.wr, "{}", escape_str(name))
450 try!(write!(self.wr, "\\{\"variant\":"));
451 try!(write!(self.wr, "{}", escape_str(name)));
452 try!(write!(self.wr, ",\"fields\":["));
454 write!(self.wr, "]\\}")
458 fn emit_enum_variant_arg(&mut self,
460 f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
462 try!(write!(self.wr, ","));
467 fn emit_enum_struct_variant(&mut self,
471 f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
472 self.emit_enum_variant(name, id, cnt, f)
475 fn emit_enum_struct_variant_field(&mut self,
478 f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
479 self.emit_enum_variant_arg(idx, f)
482 fn emit_struct(&mut self,
485 f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
486 try!(write!(self.wr, r"\{"));
488 write!(self.wr, r"\}")
491 fn emit_struct_field(&mut self,
494 f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
495 if idx != 0 { try!(write!(self.wr, ",")); }
496 try!(write!(self.wr, "{}:", escape_str(name)));
500 fn emit_tuple(&mut self, len: uint, f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
501 self.emit_seq(len, f)
503 fn emit_tuple_arg(&mut self,
505 f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
506 self.emit_seq_elt(idx, f)
509 fn emit_tuple_struct(&mut self,
512 f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
513 self.emit_seq(len, f)
515 fn emit_tuple_struct_arg(&mut self,
517 f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
518 self.emit_seq_elt(idx, f)
521 fn emit_option(&mut self, f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
524 fn emit_option_none(&mut self) -> EncodeResult { self.emit_nil() }
525 fn emit_option_some(&mut self, f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
529 fn emit_seq(&mut self, _len: uint, f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
530 try!(write!(self.wr, "["));
535 fn emit_seq_elt(&mut self, idx: uint, f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
537 try!(write!(self.wr, ","));
542 fn emit_map(&mut self, _len: uint, f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
543 try!(write!(self.wr, r"\{"));
545 write!(self.wr, r"\}")
548 fn emit_map_elt_key(&mut self,
550 f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
551 use std::str::from_utf8;
552 if idx != 0 { try!(write!(self.wr, ",")) }
553 // ref #12967, make sure to wrap a key in double quotes,
554 // in the event that its of a type that omits them (eg numbers)
555 let mut buf = MemWriter::new();
556 let mut check_encoder = Encoder::new(&mut buf);
557 try!(f(&mut check_encoder));
558 let buf = buf.unwrap();
559 let out = from_utf8(buf.as_slice()).unwrap();
560 let needs_wrapping = out.char_at(0) != '"' &&
561 out.char_at_reverse(out.len()) != '"';
562 if needs_wrapping { try!(write!(self.wr, "\"")); }
564 if needs_wrapping { try!(write!(self.wr, "\"")); }
568 fn emit_map_elt_val(&mut self,
570 f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
571 try!(write!(self.wr, ":"));
576 /// Another encoder for JSON, but prints out human-readable JSON instead of
578 pub struct PrettyEncoder<'a> {
579 wr: &'a mut io::Writer,
583 impl<'a> PrettyEncoder<'a> {
584 /// Creates a new encoder whose output will be written to the specified writer
585 pub fn new<'a>(wr: &'a mut io::Writer) -> PrettyEncoder<'a> {
593 impl<'a> ::Encoder<io::IoError> for PrettyEncoder<'a> {
594 fn emit_nil(&mut self) -> EncodeResult { write!(self.wr, "null") }
596 fn emit_uint(&mut self, v: uint) -> EncodeResult { self.emit_f64(v as f64) }
597 fn emit_u64(&mut self, v: u64) -> EncodeResult { self.emit_f64(v as f64) }
598 fn emit_u32(&mut self, v: u32) -> EncodeResult { self.emit_f64(v as f64) }
599 fn emit_u16(&mut self, v: u16) -> EncodeResult { self.emit_f64(v as f64) }
600 fn emit_u8(&mut self, v: u8) -> EncodeResult { self.emit_f64(v as f64) }
602 fn emit_int(&mut self, v: int) -> EncodeResult { self.emit_f64(v as f64) }
603 fn emit_i64(&mut self, v: i64) -> EncodeResult { self.emit_f64(v as f64) }
604 fn emit_i32(&mut self, v: i32) -> EncodeResult { self.emit_f64(v as f64) }
605 fn emit_i16(&mut self, v: i16) -> EncodeResult { self.emit_f64(v as f64) }
606 fn emit_i8(&mut self, v: i8) -> EncodeResult { self.emit_f64(v as f64) }
608 fn emit_bool(&mut self, v: bool) -> EncodeResult {
610 write!(self.wr, "true")
612 write!(self.wr, "false")
616 fn emit_f64(&mut self, v: f64) -> EncodeResult {
617 write!(self.wr, "{}", f64::to_str_digits(v, 6u))
619 fn emit_f32(&mut self, v: f32) -> EncodeResult {
620 self.emit_f64(v as f64)
623 fn emit_char(&mut self, v: char) -> EncodeResult {
624 self.emit_str(str::from_char(v).as_slice())
626 fn emit_str(&mut self, v: &str) -> EncodeResult {
627 write!(self.wr, "{}", escape_str(v))
630 fn emit_enum(&mut self,
632 f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
636 fn emit_enum_variant(&mut self,
640 f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
642 write!(self.wr, "{}", escape_str(name))
645 try!(write!(self.wr, "[\n{}{},\n", spaces(self.indent),
649 write!(self.wr, "\n{}]", spaces(self.indent))
653 fn emit_enum_variant_arg(&mut self,
655 f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
657 try!(write!(self.wr, ",\n"));
659 try!(write!(self.wr, "{}", spaces(self.indent)));
663 fn emit_enum_struct_variant(&mut self,
667 f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
668 self.emit_enum_variant(name, id, cnt, f)
671 fn emit_enum_struct_variant_field(&mut self,
674 f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
675 self.emit_enum_variant_arg(idx, f)
679 fn emit_struct(&mut self,
682 f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
684 write!(self.wr, "\\{\\}")
686 try!(write!(self.wr, "\\{"));
690 write!(self.wr, "\n{}\\}", spaces(self.indent))
694 fn emit_struct_field(&mut self,
697 f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
699 try!(write!(self.wr, "\n"));
701 try!(write!(self.wr, ",\n"));
703 try!(write!(self.wr, "{}{}: ", spaces(self.indent), escape_str(name)));
707 fn emit_tuple(&mut self,
709 f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
710 self.emit_seq(len, f)
712 fn emit_tuple_arg(&mut self,
714 f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
715 self.emit_seq_elt(idx, f)
718 fn emit_tuple_struct(&mut self,
721 f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
722 self.emit_seq(len, f)
724 fn emit_tuple_struct_arg(&mut self,
726 f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
727 self.emit_seq_elt(idx, f)
730 fn emit_option(&mut self, f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
733 fn emit_option_none(&mut self) -> EncodeResult { self.emit_nil() }
734 fn emit_option_some(&mut self, f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
738 fn emit_seq(&mut self,
740 f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
742 write!(self.wr, "[]")
744 try!(write!(self.wr, "["));
748 write!(self.wr, "\n{}]", spaces(self.indent))
752 fn emit_seq_elt(&mut self,
754 f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
756 try!(write!(self.wr, "\n"));
758 try!(write!(self.wr, ",\n"));
760 try!(write!(self.wr, "{}", spaces(self.indent)));
764 fn emit_map(&mut self,
766 f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
768 write!(self.wr, "\\{\\}")
770 try!(write!(self.wr, "\\{"));
774 write!(self.wr, "\n{}\\}", spaces(self.indent))
778 fn emit_map_elt_key(&mut self,
780 f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
781 use std::str::from_utf8;
783 try!(write!(self.wr, "\n"));
785 try!(write!(self.wr, ",\n"));
787 try!(write!(self.wr, "{}", spaces(self.indent)));
788 // ref #12967, make sure to wrap a key in double quotes,
789 // in the event that its of a type that omits them (eg numbers)
790 let mut buf = MemWriter::new();
791 let mut check_encoder = PrettyEncoder::new(&mut buf);
792 try!(f(&mut check_encoder));
793 let buf = buf.unwrap();
794 let out = from_utf8(buf.as_slice()).unwrap();
795 let needs_wrapping = out.char_at(0) != '"' &&
796 out.char_at_reverse(out.len()) != '"';
797 if needs_wrapping { try!(write!(self.wr, "\"")); }
799 if needs_wrapping { try!(write!(self.wr, "\"")); }
803 fn emit_map_elt_val(&mut self,
805 f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
806 try!(write!(self.wr, ": "));
811 impl<E: ::Encoder<S>, S> Encodable<E, S> for Json {
812 fn encode(&self, e: &mut E) -> Result<(), S> {
814 Number(v) => v.encode(e),
815 String(ref v) => v.encode(e),
816 Boolean(v) => v.encode(e),
817 List(ref v) => v.encode(e),
818 Object(ref v) => v.encode(e),
819 Null => e.emit_nil(),
825 /// Encodes a json value into an io::writer. Uses a single line.
826 pub fn to_writer(&self, wr: &mut io::Writer) -> EncodeResult {
827 let mut encoder = Encoder::new(wr);
828 self.encode(&mut encoder)
831 /// Encodes a json value into an io::writer.
832 /// Pretty-prints in a more readable format.
833 pub fn to_pretty_writer(&self, wr: &mut io::Writer) -> EncodeResult {
834 let mut encoder = PrettyEncoder::new(wr);
835 self.encode(&mut encoder)
838 /// Encodes a json value into a string
839 pub fn to_pretty_str(&self) -> String {
840 let mut s = MemWriter::new();
841 self.to_pretty_writer(&mut s as &mut io::Writer).unwrap();
842 str::from_utf8(s.unwrap().as_slice()).unwrap().to_string()
845 /// If the Json value is an Object, returns the value associated with the provided key.
846 /// Otherwise, returns None.
847 pub fn find<'a>(&'a self, key: &String) -> Option<&'a Json>{
849 &Object(ref map) => map.find(key),
854 /// Attempts to get a nested Json Object for each key in `keys`.
855 /// If any key is found not to exist, find_path will return None.
856 /// Otherwise, it will return the Json value associated with the final key.
857 pub fn find_path<'a>(&'a self, keys: &[&String]) -> Option<&'a Json>{
858 let mut target = self;
859 for key in keys.iter() {
860 match target.find(*key) {
861 Some(t) => { target = t; },
868 /// If the Json value is an Object, performs a depth-first search until
869 /// a value associated with the provided key is found. If no value is found
870 /// or the Json value is not an Object, returns None.
871 pub fn search<'a>(&'a self, key: &String) -> Option<&'a Json> {
873 &Object(ref map) => {
874 match map.find(key) {
875 Some(json_value) => Some(json_value),
877 let mut value : Option<&'a Json> = None;
878 for (_, v) in map.iter() {
879 value = v.search(key);
892 /// Returns true if the Json value is an Object. Returns false otherwise.
893 pub fn is_object<'a>(&'a self) -> bool {
894 self.as_object().is_some()
897 /// If the Json value is an Object, returns the associated TreeMap.
898 /// Returns None otherwise.
899 pub fn as_object<'a>(&'a self) -> Option<&'a Object> {
901 &Object(ref map) => Some(&**map),
906 /// Returns true if the Json value is a List. Returns false otherwise.
907 pub fn is_list<'a>(&'a self) -> bool {
908 self.as_list().is_some()
911 /// If the Json value is a List, returns the associated vector.
912 /// Returns None otherwise.
913 pub fn as_list<'a>(&'a self) -> Option<&'a List> {
915 &List(ref list) => Some(&*list),
920 /// Returns true if the Json value is a String. Returns false otherwise.
921 pub fn is_string<'a>(&'a self) -> bool {
922 self.as_string().is_some()
925 /// If the Json value is a String, returns the associated str.
926 /// Returns None otherwise.
927 pub fn as_string<'a>(&'a self) -> Option<&'a str> {
929 String(ref s) => Some(s.as_slice()),
934 /// Returns true if the Json value is a Number. Returns false otherwise.
935 pub fn is_number(&self) -> bool {
936 self.as_number().is_some()
939 /// If the Json value is a Number, returns the associated f64.
940 /// Returns None otherwise.
941 pub fn as_number(&self) -> Option<f64> {
943 &Number(n) => Some(n),
948 /// Returns true if the Json value is a Boolean. Returns false otherwise.
949 pub fn is_boolean(&self) -> bool {
950 self.as_boolean().is_some()
953 /// If the Json value is a Boolean, returns the associated bool.
954 /// Returns None otherwise.
955 pub fn as_boolean(&self) -> Option<bool> {
957 &Boolean(b) => Some(b),
962 /// Returns true if the Json value is a Null. Returns false otherwise.
963 pub fn is_null(&self) -> bool {
964 self.as_null().is_some()
967 /// If the Json value is a Null, returns ().
968 /// Returns None otherwise.
969 pub fn as_null(&self) -> Option<()> {
977 /// The output of the streaming parser.
978 #[deriving(Eq, Clone, Show)]
991 #[deriving(Eq, Show)]
993 // Parse a value in a list, true means first element.
995 // Parse ',' or ']' after an element in a list.
997 // Parse a key:value in an object, true means first element.
999 // Parse ',' or ']' after an element in an object.
1001 // Initialial state.
1003 // Expecting the stream to end.
1005 // Parsing can't continue.
1009 /// A Stack represents the current position of the parser in the logical
1010 /// structure of the JSON stream.
1011 /// For example foo.bar[3].x
1013 stack: Vec<InternalStackElement>,
1014 str_buffer: Vec<u8>,
1017 /// StackElements compose a Stack.
1018 /// For example, Key("foo"), Key("bar"), Index(3) and Key("x") are the
1019 /// StackElements compositing the stack that represents foo.bar[3].x
1020 #[deriving(Eq, Clone, Show)]
1021 pub enum StackElement<'l> {
1026 // Internally, Key elements are stored as indices in a buffer to avoid
1027 // allocating a string for every member of an object.
1028 #[deriving(Eq, Clone, Show)]
1029 enum InternalStackElement {
1031 InternalKey(u16, u16), // start, size
1035 pub fn new() -> Stack {
1038 str_buffer: Vec::new(),
1042 /// Returns The number of elements in the Stack.
1043 pub fn len(&self) -> uint { self.stack.len() }
1045 /// Returns true if the stack is empty, equivalent to self.len() == 0.
1046 pub fn is_empty(&self) -> bool { self.stack.len() == 0 }
1048 /// Provides access to the StackElement at a given index.
1049 /// lower indices are at the bottom of the stack while higher indices are
1051 pub fn get<'l>(&'l self, idx: uint) -> StackElement<'l> {
1052 return match *self.stack.get(idx) {
1053 InternalIndex(i) => { Index(i) }
1054 InternalKey(start, size) => {
1055 Key(str::from_utf8(self.str_buffer.slice(start as uint, (start+size) as uint)).unwrap())
1060 /// Compares this stack with an array of StackElements.
1061 pub fn is_equal_to(&self, rhs: &[StackElement]) -> bool {
1062 if self.stack.len() != rhs.len() { return false; }
1063 for i in range(0, rhs.len()) {
1064 if self.get(i) != rhs[i] { return false; }
1069 /// Returns true if the bottom-most elements of this stack are the same as
1070 /// the ones passed as parameter.
1071 pub fn starts_with(&self, rhs: &[StackElement]) -> bool {
1072 if self.stack.len() < rhs.len() { return false; }
1073 for i in range(0, rhs.len()) {
1074 if self.get(i) != rhs[i] { return false; }
1079 /// Returns true if the top-most elements of this stack are the same as
1080 /// the ones passed as parameter.
1081 pub fn ends_with(&self, rhs: &[StackElement]) -> bool {
1082 if self.stack.len() < rhs.len() { return false; }
1083 let offset = self.stack.len() - rhs.len();
1084 for i in range(0, rhs.len()) {
1085 if self.get(i + offset) != rhs[i] { return false; }
1090 /// Returns the top-most element (if any).
1091 pub fn top<'l>(&'l self) -> Option<StackElement<'l>> {
1092 return match self.stack.last() {
1094 Some(&InternalIndex(i)) => Some(Index(i)),
1095 Some(&InternalKey(start, size)) => {
1096 Some(Key(str::from_utf8(
1097 self.str_buffer.slice(start as uint, (start+size) as uint)
1103 // Used by Parser to insert Key elements at the top of the stack.
1104 fn push_key(&mut self, key: String) {
1105 self.stack.push(InternalKey(self.str_buffer.len() as u16, key.len() as u16));
1106 for c in key.as_bytes().iter() {
1107 self.str_buffer.push(*c);
1111 // Used by Parser to insert Index elements at the top of the stack.
1112 fn push_index(&mut self, index: u32) {
1113 self.stack.push(InternalIndex(index));
1116 // Used by Parser to remove the top-most element of the stack.
1118 assert!(!self.is_empty());
1119 match *self.stack.last().unwrap() {
1120 InternalKey(_, sz) => {
1121 let new_size = self.str_buffer.len() - sz as uint;
1123 self.str_buffer.set_len(new_size);
1126 InternalIndex(_) => {}
1131 // Used by Parser to test whether the top-most element is an index.
1132 fn last_is_index(&self) -> bool {
1133 if self.is_empty() { return false; }
1134 return match *self.stack.last().unwrap() {
1135 InternalIndex(_) => true,
1140 // Used by Parser to increment the index of the top-most element.
1141 fn bump_index(&mut self) {
1142 let len = self.stack.len();
1143 let idx = match *self.stack.last().unwrap() {
1144 InternalIndex(i) => { i + 1 }
1147 *self.stack.get_mut(len - 1) = InternalIndex(idx);
1151 /// A streaming JSON parser implemented as an iterator of JsonEvent, consuming
1152 /// an iterator of char.
1153 pub struct Parser<T> {
1158 // We maintain a stack representing where we are in the logical structure
1159 // of the JSON stream.
1161 // A state machine is kept to make it possible to interupt and resume parsing.
1165 impl<T: Iterator<char>> Iterator<JsonEvent> for Parser<T> {
1166 fn next(&mut self) -> Option<JsonEvent> {
1167 if self.state == ParseFinished {
1171 if self.state == ParseBeforeFinish {
1172 self.parse_whitespace();
1173 // Make sure there is no trailing characters.
1175 self.state = ParseFinished;
1178 return Some(self.error_event(TrailingCharacters));
1182 return Some(self.parse());
1186 impl<T: Iterator<char>> Parser<T> {
1187 /// Creates the JSON parser.
1188 pub fn new(rdr: T) -> Parser<T> {
1189 let mut p = Parser {
1194 stack: Stack::new(),
1201 /// Provides access to the current position in the logical structure of the
1203 pub fn stack<'l>(&'l self) -> &'l Stack {
1204 return &'l self.stack;
1207 fn eof(&self) -> bool { self.ch.is_none() }
1208 fn ch_or_null(&self) -> char { self.ch.unwrap_or('\x00') }
1209 fn bump(&mut self) {
1210 self.ch = self.rdr.next();
1212 if self.ch_is('\n') {
1220 fn next_char(&mut self) -> Option<char> {
1224 fn ch_is(&self, c: char) -> bool {
1228 fn error<T>(&self, reason: ErrorCode) -> Result<T, ParserError> {
1229 Err(SyntaxError(reason, self.line, self.col))
1232 fn parse_whitespace(&mut self) {
1233 while self.ch_is(' ') ||
1236 self.ch_is('\r') { self.bump(); }
1239 fn parse_number(&mut self) -> Result<f64, ParserError> {
1242 if self.ch_is('-') {
1247 let mut res = match self.parse_integer() {
1249 Err(e) => return Err(e)
1252 if self.ch_is('.') {
1253 match self.parse_decimal(res) {
1255 Err(e) => return Err(e)
1259 if self.ch_is('e') || self.ch_is('E') {
1260 match self.parse_exponent(res) {
1262 Err(e) => return Err(e)
1269 fn parse_integer(&mut self) -> Result<f64, ParserError> {
1272 match self.ch_or_null() {
1276 // There can be only one leading '0'.
1277 match self.ch_or_null() {
1278 '0' .. '9' => return self.error(InvalidNumber),
1284 match self.ch_or_null() {
1287 res += ((c as int) - ('0' as int)) as f64;
1294 _ => return self.error(InvalidNumber),
1299 fn parse_decimal(&mut self, res: f64) -> Result<f64, ParserError> {
1302 // Make sure a digit follows the decimal place.
1303 match self.ch_or_null() {
1305 _ => return self.error(InvalidNumber)
1311 match self.ch_or_null() {
1314 res += (((c as int) - ('0' as int)) as f64) * dec;
1324 fn parse_exponent(&mut self, mut res: f64) -> Result<f64, ParserError> {
1328 let mut neg_exp = false;
1330 if self.ch_is('+') {
1332 } else if self.ch_is('-') {
1337 // Make sure a digit follows the exponent place.
1338 match self.ch_or_null() {
1340 _ => return self.error(InvalidNumber)
1343 match self.ch_or_null() {
1346 exp += (c as uint) - ('0' as uint);
1354 let exp: f64 = num::pow(10u as f64, exp);
1364 fn decode_hex_escape(&mut self) -> Result<u16, ParserError> {
1367 while i < 4u && !self.eof() {
1369 n = match self.ch_or_null() {
1370 c @ '0' .. '9' => n * 16_u16 + ((c as u16) - ('0' as u16)),
1371 'a' | 'A' => n * 16_u16 + 10_u16,
1372 'b' | 'B' => n * 16_u16 + 11_u16,
1373 'c' | 'C' => n * 16_u16 + 12_u16,
1374 'd' | 'D' => n * 16_u16 + 13_u16,
1375 'e' | 'E' => n * 16_u16 + 14_u16,
1376 'f' | 'F' => n * 16_u16 + 15_u16,
1377 _ => return self.error(InvalidEscape)
1383 // Error out if we didn't parse 4 digits.
1385 return self.error(InvalidEscape);
1391 fn parse_str(&mut self) -> Result<String, ParserError> {
1392 let mut escape = false;
1393 let mut res = String::new();
1398 return self.error(EOFWhileParsingString);
1402 match self.ch_or_null() {
1403 '"' => res.push_char('"'),
1404 '\\' => res.push_char('\\'),
1405 '/' => res.push_char('/'),
1406 'b' => res.push_char('\x08'),
1407 'f' => res.push_char('\x0c'),
1408 'n' => res.push_char('\n'),
1409 'r' => res.push_char('\r'),
1410 't' => res.push_char('\t'),
1411 'u' => match try!(self.decode_hex_escape()) {
1412 0xDC00 .. 0xDFFF => return self.error(LoneLeadingSurrogateInHexEscape),
1414 // Non-BMP characters are encoded as a sequence of
1415 // two hex escapes, representing UTF-16 surrogates.
1416 n1 @ 0xD800 .. 0xDBFF => {
1417 let c1 = self.next_char();
1418 let c2 = self.next_char();
1420 (Some('\\'), Some('u')) => (),
1421 _ => return self.error(UnexpectedEndOfHexEscape),
1424 let buf = [n1, try!(self.decode_hex_escape())];
1425 match str::utf16_items(buf.as_slice()).next() {
1426 Some(ScalarValue(c)) => res.push_char(c),
1427 _ => return self.error(LoneLeadingSurrogateInHexEscape),
1431 n => match char::from_u32(n as u32) {
1432 Some(c) => res.push_char(c),
1433 None => return self.error(InvalidUnicodeCodePoint),
1436 _ => return self.error(InvalidEscape),
1439 } else if self.ch_is('\\') {
1447 Some(c) => res.push_char(c),
1448 None => unreachable!()
1454 // Invoked at each iteration, consumes the stream until it has enough
1455 // information to return a JsonEvent.
1456 // Manages an internal state so that parsing can be interrupted and resumed.
1457 // Also keeps track of the position in the logical structure of the json
1458 // stream int the form of a stack that can be queried by the user usng the
1460 fn parse(&mut self) -> JsonEvent {
1462 // The only paths where the loop can spin a new iteration
1463 // are in the cases ParseListComma and ParseObjectComma if ','
1464 // is parsed. In these cases the state is set to (respectively)
1465 // ParseList(false) and ParseObject(false), which always return,
1466 // so there is no risk of getting stuck in an infinite loop.
1467 // All other paths return before the end of the loop's iteration.
1468 self.parse_whitespace();
1472 return self.parse_start();
1474 ParseList(first) => {
1475 return self.parse_list(first);
1478 match self.parse_list_comma_or_end() {
1479 Some(evt) => { return evt; }
1483 ParseObject(first) => {
1484 return self.parse_object(first);
1486 ParseObjectComma => {
1488 if self.ch_is(',') {
1489 self.state = ParseObject(false);
1492 return self.parse_object_end();
1496 return self.error_event(InvalidSyntax);
1502 fn parse_start(&mut self) -> JsonEvent {
1503 let val = self.parse_value();
1504 self.state = match val {
1505 Error(_) => { ParseFinished }
1506 ListStart => { ParseList(true) }
1507 ObjectStart => { ParseObject(true) }
1508 _ => { ParseBeforeFinish }
1513 fn parse_list(&mut self, first: bool) -> JsonEvent {
1514 if self.ch_is(']') {
1516 return self.error_event(InvalidSyntax);
1518 if self.stack.is_empty() {
1519 self.state = ParseBeforeFinish;
1521 self.state = if self.stack.last_is_index() {
1531 self.stack.push_index(0);
1534 let val = self.parse_value();
1536 self.state = match val {
1537 Error(_) => { ParseFinished }
1538 ListStart => { ParseList(true) }
1539 ObjectStart => { ParseObject(true) }
1540 _ => { ParseListComma }
1545 fn parse_list_comma_or_end(&mut self) -> Option<JsonEvent> {
1546 if self.ch_is(',') {
1547 self.stack.bump_index();
1548 self.state = ParseList(false);
1551 } else if self.ch_is(']') {
1553 if self.stack.is_empty() {
1554 self.state = ParseBeforeFinish;
1556 self.state = if self.stack.last_is_index() {
1563 return Some(ListEnd);
1564 } else if self.eof() {
1565 return Some(self.error_event(EOFWhileParsingList));
1567 return Some(self.error_event(InvalidSyntax));
1571 fn parse_object(&mut self, first: bool) -> JsonEvent {
1572 if self.ch_is('}') {
1576 if self.stack.is_empty() {
1577 self.state = ParseBeforeFinish;
1579 self.state = if self.stack.last_is_index() {
1589 return self.error_event(EOFWhileParsingObject);
1591 if !self.ch_is('"') {
1592 return self.error_event(KeyMustBeAString);
1594 let s = match self.parse_str() {
1597 self.state = ParseFinished;
1601 self.parse_whitespace();
1603 return self.error_event(EOFWhileParsingObject);
1604 } else if self.ch_or_null() != ':' {
1605 return self.error_event(ExpectedColon);
1607 self.stack.push_key(s);
1609 self.parse_whitespace();
1611 let val = self.parse_value();
1613 self.state = match val {
1614 Error(_) => { ParseFinished }
1615 ListStart => { ParseList(true) }
1616 ObjectStart => { ParseObject(true) }
1617 _ => { ParseObjectComma }
1622 fn parse_object_end(&mut self) -> JsonEvent {
1623 if self.ch_is('}') {
1624 if self.stack.is_empty() {
1625 self.state = ParseBeforeFinish;
1627 self.state = if self.stack.last_is_index() {
1635 } else if self.eof() {
1636 return self.error_event(EOFWhileParsingObject);
1638 return self.error_event(InvalidSyntax);
1642 fn parse_value(&mut self) -> JsonEvent {
1643 if self.eof() { return self.error_event(EOFWhileParsingValue); }
1644 match self.ch_or_null() {
1645 'n' => { return self.parse_ident("ull", NullValue); }
1646 't' => { return self.parse_ident("rue", BooleanValue(true)); }
1647 'f' => { return self.parse_ident("alse", BooleanValue(false)); }
1648 '0' .. '9' | '-' => return match self.parse_number() {
1649 Ok(f) => NumberValue(f),
1652 '"' => return match self.parse_str() {
1653 Ok(s) => StringValue(s),
1664 _ => { return self.error_event(InvalidSyntax); }
1668 fn parse_ident(&mut self, ident: &str, value: JsonEvent) -> JsonEvent {
1669 if ident.chars().all(|c| Some(c) == self.next_char()) {
1673 Error(SyntaxError(InvalidSyntax, self.line, self.col))
1677 fn error_event(&mut self, reason: ErrorCode) -> JsonEvent {
1678 self.state = ParseFinished;
1679 Error(SyntaxError(reason, self.line, self.col))
1683 /// A Builder consumes a json::Parser to create a generic Json structure.
1684 pub struct Builder<T> {
1686 token: Option<JsonEvent>,
1689 impl<T: Iterator<char>> Builder<T> {
1690 /// Create a JSON Builder.
1691 pub fn new(src: T) -> Builder<T> {
1693 parser: Parser::new(src),
1698 // Decode a Json value from a Parser.
1699 pub fn build(&mut self) -> Result<Json, BuilderError> {
1701 let result = self.build_value();
1705 Some(Error(e)) => { return Err(e); }
1706 ref tok => { fail!("unexpected token {}", tok.clone()); }
1711 fn bump(&mut self) {
1712 self.token = self.parser.next();
1715 fn build_value(&mut self) -> Result<Json, BuilderError> {
1716 return match self.token {
1717 Some(NullValue) => { Ok(Null) }
1718 Some(NumberValue(n)) => { Ok(Number(n)) }
1719 Some(BooleanValue(b)) => { Ok(Boolean(b)) }
1720 Some(StringValue(ref mut s)) => {
1721 let mut temp = String::new();
1725 Some(Error(e)) => { Err(e) }
1726 Some(ListStart) => { self.build_list() }
1727 Some(ObjectStart) => { self.build_object() }
1728 Some(ObjectEnd) => { self.parser.error(InvalidSyntax) }
1729 Some(ListEnd) => { self.parser.error(InvalidSyntax) }
1730 None => { self.parser.error(EOFWhileParsingValue) }
1734 fn build_list(&mut self) -> Result<Json, BuilderError> {
1736 let mut values = Vec::new();
1739 if self.token == Some(ListEnd) {
1740 return Ok(List(values.move_iter().collect()));
1742 match self.build_value() {
1743 Ok(v) => values.push(v),
1744 Err(e) => { return Err(e) }
1750 fn build_object(&mut self) -> Result<Json, BuilderError> {
1753 let mut values = box TreeMap::new();
1755 while self.token != None {
1757 Some(ObjectEnd) => { return Ok(Object(values)); }
1758 Some(Error(e)) => { return Err(e); }
1762 let key = match self.parser.stack().top() {
1763 Some(Key(k)) => { k.to_string() }
1764 _ => { fail!("invalid state"); }
1766 match self.build_value() {
1767 Ok(value) => { values.insert(key, value); }
1768 Err(e) => { return Err(e); }
1772 return self.parser.error(EOFWhileParsingObject);
1777 /// Decodes a json value from an `&mut io::Reader`
1778 pub fn from_reader(rdr: &mut io::Reader) -> Result<Json, BuilderError> {
1779 let contents = match rdr.read_to_end() {
1781 Err(e) => return Err(io_error_to_error(e))
1783 let s = match str::from_utf8(contents.as_slice()) {
1784 Some(s) => s.to_string(),
1785 None => return Err(SyntaxError(NotUtf8, 0, 0))
1787 let mut builder = Builder::new(s.as_slice().chars());
1791 /// Decodes a json value from a string
1792 pub fn from_str(s: &str) -> Result<Json, BuilderError> {
1793 let mut builder = Builder::new(s.chars());
1794 return builder.build();
1797 /// A structure to decode JSON to values in rust.
1798 pub struct Decoder {
1803 /// Creates a new decoder instance for decoding the specified JSON value.
1804 pub fn new(json: Json) -> Decoder {
1812 fn pop(&mut self) -> Json {
1813 self.stack.pop().unwrap()
1817 macro_rules! expect(
1818 ($e:expr, Null) => ({
1821 other => Err(ExpectedError("Null".to_string(),
1822 format_strbuf!("{}", other)))
1825 ($e:expr, $t:ident) => ({
1829 Err(ExpectedError(stringify!($t).to_string(),
1830 format_strbuf!("{}", other)))
1836 impl ::Decoder<DecoderError> for Decoder {
1837 fn read_nil(&mut self) -> DecodeResult<()> {
1839 try!(expect!(self.pop(), Null));
1843 fn read_u64(&mut self) -> DecodeResult<u64 > { Ok(try!(self.read_f64()) as u64) }
1844 fn read_u32(&mut self) -> DecodeResult<u32 > { Ok(try!(self.read_f64()) as u32) }
1845 fn read_u16(&mut self) -> DecodeResult<u16 > { Ok(try!(self.read_f64()) as u16) }
1846 fn read_u8 (&mut self) -> DecodeResult<u8 > { Ok(try!(self.read_f64()) as u8) }
1847 fn read_uint(&mut self) -> DecodeResult<uint> { Ok(try!(self.read_f64()) as uint) }
1849 fn read_i64(&mut self) -> DecodeResult<i64> { Ok(try!(self.read_f64()) as i64) }
1850 fn read_i32(&mut self) -> DecodeResult<i32> { Ok(try!(self.read_f64()) as i32) }
1851 fn read_i16(&mut self) -> DecodeResult<i16> { Ok(try!(self.read_f64()) as i16) }
1852 fn read_i8 (&mut self) -> DecodeResult<i8 > { Ok(try!(self.read_f64()) as i8) }
1853 fn read_int(&mut self) -> DecodeResult<int> { Ok(try!(self.read_f64()) as int) }
1855 fn read_bool(&mut self) -> DecodeResult<bool> {
1856 debug!("read_bool");
1857 Ok(try!(expect!(self.pop(), Boolean)))
1860 fn read_f64(&mut self) -> DecodeResult<f64> {
1861 use std::from_str::FromStr;
1866 // re: #12967.. a type w/ numeric keys (ie HashMap<uint, V> etc)
1867 // is going to have a string here, as per JSON spec..
1868 Ok(FromStr::from_str(s.as_slice()).unwrap())
1871 Err(ExpectedError("Number".to_string(),
1872 format_strbuf!("{}", value)))
1877 fn read_f32(&mut self) -> DecodeResult<f32> { Ok(try!(self.read_f64()) as f32) }
1879 fn read_char(&mut self) -> DecodeResult<char> {
1880 let s = try!(self.read_str());
1882 let mut it = s.as_slice().chars();
1883 match (it.next(), it.next()) {
1884 // exactly one character
1885 (Some(c), None) => return Ok(c),
1889 Err(ExpectedError("single character string".to_string(),
1890 format_strbuf!("{}", s)))
1893 fn read_str(&mut self) -> DecodeResult<String> {
1895 Ok(try!(expect!(self.pop(), String)))
1898 fn read_enum<T>(&mut self,
1900 f: |&mut Decoder| -> DecodeResult<T>) -> DecodeResult<T> {
1901 debug!("read_enum({})", name);
1905 fn read_enum_variant<T>(&mut self,
1907 f: |&mut Decoder, uint| -> DecodeResult<T>)
1908 -> DecodeResult<T> {
1909 debug!("read_enum_variant(names={})", names);
1910 let name = match self.pop() {
1913 let n = match o.pop(&"variant".to_string()) {
1914 Some(String(s)) => s,
1916 return Err(ExpectedError("String".to_string(),
1917 format_strbuf!("{}", val)))
1920 return Err(MissingFieldError("variant".to_string()))
1923 match o.pop(&"fields".to_string()) {
1925 for field in l.move_iter().rev() {
1926 self.stack.push(field.clone());
1930 return Err(ExpectedError("List".to_string(),
1931 format_strbuf!("{}", val)))
1934 return Err(MissingFieldError("fields".to_string()))
1940 return Err(ExpectedError("String or Object".to_string(),
1941 format_strbuf!("{}", json)))
1944 let idx = match names.iter()
1946 str::eq_slice(*n, name.as_slice())
1949 None => return Err(UnknownVariantError(name))
1954 fn read_enum_variant_arg<T>(&mut self, idx: uint, f: |&mut Decoder| -> DecodeResult<T>)
1955 -> DecodeResult<T> {
1956 debug!("read_enum_variant_arg(idx={})", idx);
1960 fn read_enum_struct_variant<T>(&mut self,
1962 f: |&mut Decoder, uint| -> DecodeResult<T>)
1963 -> DecodeResult<T> {
1964 debug!("read_enum_struct_variant(names={})", names);
1965 self.read_enum_variant(names, f)
1969 fn read_enum_struct_variant_field<T>(&mut self,
1972 f: |&mut Decoder| -> DecodeResult<T>)
1973 -> DecodeResult<T> {
1974 debug!("read_enum_struct_variant_field(name={}, idx={})", name, idx);
1975 self.read_enum_variant_arg(idx, f)
1978 fn read_struct<T>(&mut self,
1981 f: |&mut Decoder| -> DecodeResult<T>)
1982 -> DecodeResult<T> {
1983 debug!("read_struct(name={}, len={})", name, len);
1984 let value = try!(f(self));
1989 fn read_struct_field<T>(&mut self,
1992 f: |&mut Decoder| -> DecodeResult<T>)
1993 -> DecodeResult<T> {
1994 debug!("read_struct_field(name={}, idx={})", name, idx);
1995 let mut obj = try!(expect!(self.pop(), Object));
1997 let value = match obj.pop(&name.to_string()) {
1998 None => return Err(MissingFieldError(name.to_string())),
2000 self.stack.push(json);
2004 self.stack.push(Object(obj));
2008 fn read_tuple<T>(&mut self, f: |&mut Decoder, uint| -> DecodeResult<T>) -> DecodeResult<T> {
2009 debug!("read_tuple()");
2013 fn read_tuple_arg<T>(&mut self,
2015 f: |&mut Decoder| -> DecodeResult<T>) -> DecodeResult<T> {
2016 debug!("read_tuple_arg(idx={})", idx);
2017 self.read_seq_elt(idx, f)
2020 fn read_tuple_struct<T>(&mut self,
2022 f: |&mut Decoder, uint| -> DecodeResult<T>)
2023 -> DecodeResult<T> {
2024 debug!("read_tuple_struct(name={})", name);
2028 fn read_tuple_struct_arg<T>(&mut self,
2030 f: |&mut Decoder| -> DecodeResult<T>)
2031 -> DecodeResult<T> {
2032 debug!("read_tuple_struct_arg(idx={})", idx);
2033 self.read_tuple_arg(idx, f)
2036 fn read_option<T>(&mut self, f: |&mut Decoder, bool| -> DecodeResult<T>) -> DecodeResult<T> {
2038 Null => f(self, false),
2039 value => { self.stack.push(value); f(self, true) }
2043 fn read_seq<T>(&mut self, f: |&mut Decoder, uint| -> DecodeResult<T>) -> DecodeResult<T> {
2044 debug!("read_seq()");
2045 let list = try!(expect!(self.pop(), List));
2046 let len = list.len();
2047 for v in list.move_iter().rev() {
2053 fn read_seq_elt<T>(&mut self,
2055 f: |&mut Decoder| -> DecodeResult<T>) -> DecodeResult<T> {
2056 debug!("read_seq_elt(idx={})", idx);
2060 fn read_map<T>(&mut self, f: |&mut Decoder, uint| -> DecodeResult<T>) -> DecodeResult<T> {
2061 debug!("read_map()");
2062 let obj = try!(expect!(self.pop(), Object));
2063 let len = obj.len();
2064 for (key, value) in obj.move_iter() {
2065 self.stack.push(value);
2066 self.stack.push(String(key));
2071 fn read_map_elt_key<T>(&mut self, idx: uint, f: |&mut Decoder| -> DecodeResult<T>)
2072 -> DecodeResult<T> {
2073 debug!("read_map_elt_key(idx={})", idx);
2077 fn read_map_elt_val<T>(&mut self, idx: uint, f: |&mut Decoder| -> DecodeResult<T>)
2078 -> DecodeResult<T> {
2079 debug!("read_map_elt_val(idx={})", idx);
2084 /// Test if two json values are less than one another
2086 fn lt(&self, other: &Json) -> bool {
2090 Number(f1) => f0 < f1,
2091 String(_) | Boolean(_) | List(_) | Object(_) |
2099 String(ref s1) => s0 < s1,
2100 Boolean(_) | List(_) | Object(_) | Null => true
2106 Number(_) | String(_) => false,
2107 Boolean(b1) => b0 < b1,
2108 List(_) | Object(_) | Null => true
2114 Number(_) | String(_) | Boolean(_) => false,
2115 List(ref l1) => (*l0) < (*l1),
2116 Object(_) | Null => true
2122 Number(_) | String(_) | Boolean(_) | List(_) => false,
2123 Object(ref d1) => d0 < d1,
2130 Number(_) | String(_) | Boolean(_) | List(_) |
2140 /// A trait for converting values to JSON
2142 /// Converts the value of `self` to an instance of JSON
2143 fn to_json(&self) -> Json;
2146 impl ToJson for Json {
2147 fn to_json(&self) -> Json { (*self).clone() }
2150 impl ToJson for int {
2151 fn to_json(&self) -> Json { Number(*self as f64) }
2154 impl ToJson for i8 {
2155 fn to_json(&self) -> Json { Number(*self as f64) }
2158 impl ToJson for i16 {
2159 fn to_json(&self) -> Json { Number(*self as f64) }
2162 impl ToJson for i32 {
2163 fn to_json(&self) -> Json { Number(*self as f64) }
2166 impl ToJson for i64 {
2167 fn to_json(&self) -> Json { Number(*self as f64) }
2170 impl ToJson for uint {
2171 fn to_json(&self) -> Json { Number(*self as f64) }
2174 impl ToJson for u8 {
2175 fn to_json(&self) -> Json { Number(*self as f64) }
2178 impl ToJson for u16 {
2179 fn to_json(&self) -> Json { Number(*self as f64) }
2182 impl ToJson for u32 {
2183 fn to_json(&self) -> Json { Number(*self as f64) }
2186 impl ToJson for u64 {
2187 fn to_json(&self) -> Json { Number(*self as f64) }
2190 impl ToJson for f32 {
2191 fn to_json(&self) -> Json { Number(*self as f64) }
2194 impl ToJson for f64 {
2195 fn to_json(&self) -> Json { Number(*self) }
2198 impl ToJson for () {
2199 fn to_json(&self) -> Json { Null }
2202 impl ToJson for bool {
2203 fn to_json(&self) -> Json { Boolean(*self) }
2206 impl ToJson for String {
2207 fn to_json(&self) -> Json { String((*self).clone()) }
2210 impl<A:ToJson,B:ToJson> ToJson for (A, B) {
2211 fn to_json(&self) -> Json {
2214 List(vec![a.to_json(), b.to_json()])
2220 impl<A:ToJson,B:ToJson,C:ToJson> ToJson for (A, B, C) {
2221 fn to_json(&self) -> Json {
2223 (ref a, ref b, ref c) => {
2224 List(vec![a.to_json(), b.to_json(), c.to_json()])
2230 impl<A:ToJson> ToJson for ~[A] {
2231 fn to_json(&self) -> Json { List(self.iter().map(|elt| elt.to_json()).collect()) }
2234 impl<A:ToJson> ToJson for Vec<A> {
2235 fn to_json(&self) -> Json { List(self.iter().map(|elt| elt.to_json()).collect()) }
2238 impl<A:ToJson> ToJson for TreeMap<String, A> {
2239 fn to_json(&self) -> Json {
2240 let mut d = TreeMap::new();
2241 for (key, value) in self.iter() {
2242 d.insert((*key).clone(), value.to_json());
2248 impl<A:ToJson> ToJson for HashMap<String, A> {
2249 fn to_json(&self) -> Json {
2250 let mut d = TreeMap::new();
2251 for (key, value) in self.iter() {
2252 d.insert((*key).clone(), value.to_json());
2258 impl<A:ToJson> ToJson for Option<A> {
2259 fn to_json(&self) -> Json {
2262 Some(ref value) => value.to_json()
2267 impl fmt::Show for Json {
2268 /// Encodes a json value into a string
2269 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2270 self.to_writer(f).map_err(|_| fmt::WriteError)
2277 use self::test::Bencher;
2278 use {Encodable, Decodable};
2279 use super::{Encoder, Decoder, Error, Boolean, Number, List, String, Null,
2280 PrettyEncoder, Object, Json, from_str, ParseError, ExpectedError,
2281 MissingFieldError, UnknownVariantError, DecodeResult, DecoderError,
2282 JsonEvent, Parser, StackElement,
2283 ObjectStart, ObjectEnd, ListStart, ListEnd, BooleanValue, NumberValue, StringValue,
2284 NullValue, SyntaxError, Key, Index, Stack,
2285 InvalidSyntax, InvalidNumber, EOFWhileParsingObject, EOFWhileParsingList,
2286 EOFWhileParsingValue, EOFWhileParsingString, KeyMustBeAString, ExpectedColon,
2287 TrailingCharacters};
2289 use collections::TreeMap;
2291 #[deriving(Eq, Encodable, Decodable, Show)]
2297 #[deriving(Eq, Encodable, Decodable, Show)]
2304 #[deriving(Eq, Encodable, Decodable, Show)]
2309 fn mk_object(items: &[(String, Json)]) -> Json {
2310 let mut d = box TreeMap::new();
2312 for item in items.iter() {
2314 (ref key, ref value) => { d.insert((*key).clone(), (*value).clone()); },
2322 fn test_write_null() {
2323 assert_eq!(Null.to_str().into_string(), "null".to_string());
2324 assert_eq!(Null.to_pretty_str().into_string(), "null".to_string());
2329 fn test_write_number() {
2330 assert_eq!(Number(3.0).to_str().into_string(), "3".to_string());
2331 assert_eq!(Number(3.0).to_pretty_str().into_string(), "3".to_string());
2333 assert_eq!(Number(3.1).to_str().into_string(), "3.1".to_string());
2334 assert_eq!(Number(3.1).to_pretty_str().into_string(), "3.1".to_string());
2336 assert_eq!(Number(-1.5).to_str().into_string(), "-1.5".to_string());
2337 assert_eq!(Number(-1.5).to_pretty_str().into_string(), "-1.5".to_string());
2339 assert_eq!(Number(0.5).to_str().into_string(), "0.5".to_string());
2340 assert_eq!(Number(0.5).to_pretty_str().into_string(), "0.5".to_string());
2344 fn test_write_str() {
2345 assert_eq!(String("".to_string()).to_str().into_string(), "\"\"".to_string());
2346 assert_eq!(String("".to_string()).to_pretty_str().into_string(), "\"\"".to_string());
2348 assert_eq!(String("foo".to_string()).to_str().into_string(), "\"foo\"".to_string());
2349 assert_eq!(String("foo".to_string()).to_pretty_str().into_string(), "\"foo\"".to_string());
2353 fn test_write_bool() {
2354 assert_eq!(Boolean(true).to_str().into_string(), "true".to_string());
2355 assert_eq!(Boolean(true).to_pretty_str().into_string(), "true".to_string());
2357 assert_eq!(Boolean(false).to_str().into_string(), "false".to_string());
2358 assert_eq!(Boolean(false).to_pretty_str().into_string(), "false".to_string());
2362 fn test_write_list() {
2363 assert_eq!(List(vec![]).to_str().into_string(), "[]".to_string());
2364 assert_eq!(List(vec![]).to_pretty_str().into_string(), "[]".to_string());
2366 assert_eq!(List(vec![Boolean(true)]).to_str().into_string(), "[true]".to_string());
2368 List(vec![Boolean(true)]).to_pretty_str().into_string(),
2375 let long_test_list = List(vec![
2378 List(vec![String("foo\nbar".to_string()), Number(3.5)])]);
2380 assert_eq!(long_test_list.to_str().into_string(),
2381 "[false,null,[\"foo\\nbar\",3.5]]".to_string());
2383 long_test_list.to_pretty_str().into_string(),
2397 fn test_write_object() {
2398 assert_eq!(mk_object([]).to_str().into_string(), "{}".to_string());
2399 assert_eq!(mk_object([]).to_pretty_str().into_string(), "{}".to_string());
2403 ("a".to_string(), Boolean(true))
2404 ]).to_str().into_string(),
2405 "{\"a\":true}".to_string()
2408 mk_object([("a".to_string(), Boolean(true))]).to_pretty_str(),
2415 let complex_obj = mk_object([
2416 ("b".to_string(), List(vec![
2417 mk_object([("c".to_string(), String("\x0c\r".to_string()))]),
2418 mk_object([("d".to_string(), String("".to_string()))])
2423 complex_obj.to_str().into_string(),
2426 {\"c\":\"\\f\\r\"},\
2432 complex_obj.to_pretty_str().into_string(),
2437 \"c\": \"\\f\\r\"\n \
2447 ("a".to_string(), Boolean(true)),
2448 ("b".to_string(), List(vec![
2449 mk_object([("c".to_string(), String("\x0c\r".to_string()))]),
2450 mk_object([("d".to_string(), String("".to_string()))])
2454 // We can't compare the strings directly because the object fields be
2455 // printed in a different order.
2456 assert_eq!(a.clone(), from_str(a.to_str().as_slice()).unwrap());
2457 assert_eq!(a.clone(),
2458 from_str(a.to_pretty_str().as_slice()).unwrap());
2461 fn with_str_writer(f: |&mut io::Writer|) -> String {
2462 use std::io::MemWriter;
2465 let mut m = MemWriter::new();
2466 f(&mut m as &mut io::Writer);
2467 str::from_utf8(m.unwrap().as_slice()).unwrap().to_string()
2471 fn test_write_enum() {
2474 with_str_writer(|wr| {
2475 let mut encoder = Encoder::new(wr);
2476 animal.encode(&mut encoder).unwrap();
2478 "\"Dog\"".to_string()
2481 with_str_writer(|wr| {
2482 let mut encoder = PrettyEncoder::new(wr);
2483 animal.encode(&mut encoder).unwrap();
2485 "\"Dog\"".to_string()
2488 let animal = Frog("Henry".to_string(), 349);
2490 with_str_writer(|wr| {
2491 let mut encoder = Encoder::new(wr);
2492 animal.encode(&mut encoder).unwrap();
2494 "{\"variant\":\"Frog\",\"fields\":[\"Henry\",349]}".to_string()
2497 with_str_writer(|wr| {
2498 let mut encoder = PrettyEncoder::new(wr);
2499 animal.encode(&mut encoder).unwrap();
2511 fn test_write_some() {
2512 let value = Some("jodhpurs".to_string());
2513 let s = with_str_writer(|wr| {
2514 let mut encoder = Encoder::new(wr);
2515 value.encode(&mut encoder).unwrap();
2517 assert_eq!(s, "\"jodhpurs\"".to_string());
2519 let value = Some("jodhpurs".to_string());
2520 let s = with_str_writer(|wr| {
2521 let mut encoder = PrettyEncoder::new(wr);
2522 value.encode(&mut encoder).unwrap();
2524 assert_eq!(s, "\"jodhpurs\"".to_string());
2528 fn test_write_none() {
2529 let value: Option<String> = None;
2530 let s = with_str_writer(|wr| {
2531 let mut encoder = Encoder::new(wr);
2532 value.encode(&mut encoder).unwrap();
2534 assert_eq!(s, "null".to_string());
2536 let s = with_str_writer(|wr| {
2537 let mut encoder = Encoder::new(wr);
2538 value.encode(&mut encoder).unwrap();
2540 assert_eq!(s, "null".to_string());
2544 fn test_trailing_characters() {
2545 assert_eq!(from_str("nulla"), Err(SyntaxError(TrailingCharacters, 1, 5)));
2546 assert_eq!(from_str("truea"), Err(SyntaxError(TrailingCharacters, 1, 5)));
2547 assert_eq!(from_str("falsea"), Err(SyntaxError(TrailingCharacters, 1, 6)));
2548 assert_eq!(from_str("1a"), Err(SyntaxError(TrailingCharacters, 1, 2)));
2549 assert_eq!(from_str("[]a"), Err(SyntaxError(TrailingCharacters, 1, 3)));
2550 assert_eq!(from_str("{}a"), Err(SyntaxError(TrailingCharacters, 1, 3)));
2554 fn test_read_identifiers() {
2555 assert_eq!(from_str("n"), Err(SyntaxError(InvalidSyntax, 1, 2)));
2556 assert_eq!(from_str("nul"), Err(SyntaxError(InvalidSyntax, 1, 4)));
2557 assert_eq!(from_str("t"), Err(SyntaxError(InvalidSyntax, 1, 2)));
2558 assert_eq!(from_str("truz"), Err(SyntaxError(InvalidSyntax, 1, 4)));
2559 assert_eq!(from_str("f"), Err(SyntaxError(InvalidSyntax, 1, 2)));
2560 assert_eq!(from_str("faz"), Err(SyntaxError(InvalidSyntax, 1, 3)));
2562 assert_eq!(from_str("null"), Ok(Null));
2563 assert_eq!(from_str("true"), Ok(Boolean(true)));
2564 assert_eq!(from_str("false"), Ok(Boolean(false)));
2565 assert_eq!(from_str(" null "), Ok(Null));
2566 assert_eq!(from_str(" true "), Ok(Boolean(true)));
2567 assert_eq!(from_str(" false "), Ok(Boolean(false)));
2571 fn test_decode_identifiers() {
2572 let mut decoder = Decoder::new(from_str("null").unwrap());
2573 let v: () = Decodable::decode(&mut decoder).unwrap();
2576 let mut decoder = Decoder::new(from_str("true").unwrap());
2577 let v: bool = Decodable::decode(&mut decoder).unwrap();
2578 assert_eq!(v, true);
2580 let mut decoder = Decoder::new(from_str("false").unwrap());
2581 let v: bool = Decodable::decode(&mut decoder).unwrap();
2582 assert_eq!(v, false);
2586 fn test_read_number() {
2587 assert_eq!(from_str("+"), Err(SyntaxError(InvalidSyntax, 1, 1)));
2588 assert_eq!(from_str("."), Err(SyntaxError(InvalidSyntax, 1, 1)));
2589 assert_eq!(from_str("-"), Err(SyntaxError(InvalidNumber, 1, 2)));
2590 assert_eq!(from_str("00"), Err(SyntaxError(InvalidNumber, 1, 2)));
2591 assert_eq!(from_str("1."), Err(SyntaxError(InvalidNumber, 1, 3)));
2592 assert_eq!(from_str("1e"), Err(SyntaxError(InvalidNumber, 1, 3)));
2593 assert_eq!(from_str("1e+"), Err(SyntaxError(InvalidNumber, 1, 4)));
2595 assert_eq!(from_str("3"), Ok(Number(3.0)));
2596 assert_eq!(from_str("3.1"), Ok(Number(3.1)));
2597 assert_eq!(from_str("-1.2"), Ok(Number(-1.2)));
2598 assert_eq!(from_str("0.4"), Ok(Number(0.4)));
2599 assert_eq!(from_str("0.4e5"), Ok(Number(0.4e5)));
2600 assert_eq!(from_str("0.4e+15"), Ok(Number(0.4e15)));
2601 assert_eq!(from_str("0.4e-01"), Ok(Number(0.4e-01)));
2602 assert_eq!(from_str(" 3 "), Ok(Number(3.0)));
2606 fn test_decode_numbers() {
2607 let mut decoder = Decoder::new(from_str("3").unwrap());
2608 let v: f64 = Decodable::decode(&mut decoder).unwrap();
2611 let mut decoder = Decoder::new(from_str("3.1").unwrap());
2612 let v: f64 = Decodable::decode(&mut decoder).unwrap();
2615 let mut decoder = Decoder::new(from_str("-1.2").unwrap());
2616 let v: f64 = Decodable::decode(&mut decoder).unwrap();
2617 assert_eq!(v, -1.2);
2619 let mut decoder = Decoder::new(from_str("0.4").unwrap());
2620 let v: f64 = Decodable::decode(&mut decoder).unwrap();
2623 let mut decoder = Decoder::new(from_str("0.4e5").unwrap());
2624 let v: f64 = Decodable::decode(&mut decoder).unwrap();
2625 assert_eq!(v, 0.4e5);
2627 let mut decoder = Decoder::new(from_str("0.4e15").unwrap());
2628 let v: f64 = Decodable::decode(&mut decoder).unwrap();
2629 assert_eq!(v, 0.4e15);
2631 let mut decoder = Decoder::new(from_str("0.4e-01").unwrap());
2632 let v: f64 = Decodable::decode(&mut decoder).unwrap();
2633 assert_eq!(v, 0.4e-01);
2637 fn test_read_str() {
2638 assert_eq!(from_str("\""), Err(SyntaxError(EOFWhileParsingString, 1, 2)));
2639 assert_eq!(from_str("\"lol"), Err(SyntaxError(EOFWhileParsingString, 1, 5)));
2641 assert_eq!(from_str("\"\""), Ok(String("".to_string())));
2642 assert_eq!(from_str("\"foo\""), Ok(String("foo".to_string())));
2643 assert_eq!(from_str("\"\\\"\""), Ok(String("\"".to_string())));
2644 assert_eq!(from_str("\"\\b\""), Ok(String("\x08".to_string())));
2645 assert_eq!(from_str("\"\\n\""), Ok(String("\n".to_string())));
2646 assert_eq!(from_str("\"\\r\""), Ok(String("\r".to_string())));
2647 assert_eq!(from_str("\"\\t\""), Ok(String("\t".to_string())));
2648 assert_eq!(from_str(" \"foo\" "), Ok(String("foo".to_string())));
2649 assert_eq!(from_str("\"\\u12ab\""), Ok(String("\u12ab".to_string())));
2650 assert_eq!(from_str("\"\\uAB12\""), Ok(String("\uAB12".to_string())));
2654 fn test_decode_str() {
2655 let s = [("\"\"", ""),
2658 ("\"\\b\"", "\x08"),
2662 ("\"\\u12ab\"", "\u12ab"),
2663 ("\"\\uAB12\"", "\uAB12")];
2665 for &(i, o) in s.iter() {
2666 let mut decoder = Decoder::new(from_str(i).unwrap());
2667 let v: String = Decodable::decode(&mut decoder).unwrap();
2668 assert_eq!(v.as_slice(), o);
2670 let mut decoder = Decoder::new(from_str(i).unwrap());
2671 let v: String = Decodable::decode(&mut decoder).unwrap();
2672 assert_eq!(v, o.to_string());
2677 fn test_read_list() {
2678 assert_eq!(from_str("["), Err(SyntaxError(EOFWhileParsingValue, 1, 2)));
2679 assert_eq!(from_str("[1"), Err(SyntaxError(EOFWhileParsingList, 1, 3)));
2680 assert_eq!(from_str("[1,"), Err(SyntaxError(EOFWhileParsingValue, 1, 4)));
2681 assert_eq!(from_str("[1,]"), Err(SyntaxError(InvalidSyntax, 1, 4)));
2682 assert_eq!(from_str("[6 7]"), Err(SyntaxError(InvalidSyntax, 1, 4)));
2684 assert_eq!(from_str("[]"), Ok(List(vec![])));
2685 assert_eq!(from_str("[ ]"), Ok(List(vec![])));
2686 assert_eq!(from_str("[true]"), Ok(List(vec![Boolean(true)])));
2687 assert_eq!(from_str("[ false ]"), Ok(List(vec![Boolean(false)])));
2688 assert_eq!(from_str("[null]"), Ok(List(vec![Null])));
2689 assert_eq!(from_str("[3, 1]"),
2690 Ok(List(vec![Number(3.0), Number(1.0)])));
2691 assert_eq!(from_str("\n[3, 2]\n"),
2692 Ok(List(vec![Number(3.0), Number(2.0)])));
2693 assert_eq!(from_str("[2, [4, 1]]"),
2694 Ok(List(vec![Number(2.0), List(vec![Number(4.0), Number(1.0)])])));
2698 fn test_decode_list() {
2699 let mut decoder = Decoder::new(from_str("[]").unwrap());
2700 let v: Vec<()> = Decodable::decode(&mut decoder).unwrap();
2701 assert_eq!(v, vec![]);
2703 let mut decoder = Decoder::new(from_str("[null]").unwrap());
2704 let v: Vec<()> = Decodable::decode(&mut decoder).unwrap();
2705 assert_eq!(v, vec![()]);
2707 let mut decoder = Decoder::new(from_str("[true]").unwrap());
2708 let v: Vec<bool> = Decodable::decode(&mut decoder).unwrap();
2709 assert_eq!(v, vec![true]);
2711 let mut decoder = Decoder::new(from_str("[true]").unwrap());
2712 let v: Vec<bool> = Decodable::decode(&mut decoder).unwrap();
2713 assert_eq!(v, vec![true]);
2715 let mut decoder = Decoder::new(from_str("[3, 1]").unwrap());
2716 let v: Vec<int> = Decodable::decode(&mut decoder).unwrap();
2717 assert_eq!(v, vec![3, 1]);
2719 let mut decoder = Decoder::new(from_str("[[3], [1, 2]]").unwrap());
2720 let v: Vec<Vec<uint>> = Decodable::decode(&mut decoder).unwrap();
2721 assert_eq!(v, vec![vec![3], vec![1, 2]]);
2725 fn test_read_object() {
2726 assert_eq!(from_str("{"), Err(SyntaxError(EOFWhileParsingObject, 1, 2)));
2727 assert_eq!(from_str("{ "), Err(SyntaxError(EOFWhileParsingObject, 1, 3)));
2728 assert_eq!(from_str("{1"), Err(SyntaxError(KeyMustBeAString, 1, 2)));
2729 assert_eq!(from_str("{ \"a\""), Err(SyntaxError(EOFWhileParsingObject, 1, 6)));
2730 assert_eq!(from_str("{\"a\""), Err(SyntaxError(EOFWhileParsingObject, 1, 5)));
2731 assert_eq!(from_str("{\"a\" "), Err(SyntaxError(EOFWhileParsingObject, 1, 6)));
2733 assert_eq!(from_str("{\"a\" 1"), Err(SyntaxError(ExpectedColon, 1, 6)));
2734 assert_eq!(from_str("{\"a\":"), Err(SyntaxError(EOFWhileParsingValue, 1, 6)));
2735 assert_eq!(from_str("{\"a\":1"), Err(SyntaxError(EOFWhileParsingObject, 1, 7)));
2736 assert_eq!(from_str("{\"a\":1 1"), Err(SyntaxError(InvalidSyntax, 1, 8)));
2737 assert_eq!(from_str("{\"a\":1,"), Err(SyntaxError(EOFWhileParsingObject, 1, 8)));
2739 assert_eq!(from_str("{}").unwrap(), mk_object([]));
2740 assert_eq!(from_str("{\"a\": 3}").unwrap(),
2741 mk_object([("a".to_string(), Number(3.0))]));
2743 assert_eq!(from_str(
2744 "{ \"a\": null, \"b\" : true }").unwrap(),
2746 ("a".to_string(), Null),
2747 ("b".to_string(), Boolean(true))]));
2748 assert_eq!(from_str("\n{ \"a\": null, \"b\" : true }\n").unwrap(),
2750 ("a".to_string(), Null),
2751 ("b".to_string(), Boolean(true))]));
2752 assert_eq!(from_str(
2753 "{\"a\" : 1.0 ,\"b\": [ true ]}").unwrap(),
2755 ("a".to_string(), Number(1.0)),
2756 ("b".to_string(), List(vec![Boolean(true)]))
2758 assert_eq!(from_str(
2764 { \"c\": {\"d\": null} } \
2768 ("a".to_string(), Number(1.0)),
2769 ("b".to_string(), List(vec![
2771 String("foo\nbar".to_string()),
2773 ("c".to_string(), mk_object([("d".to_string(), Null)]))
2780 fn test_decode_struct() {
2783 { \"a\": null, \"b\": 2, \"c\": [\"abc\", \"xyz\"] }
2786 let mut decoder = Decoder::new(from_str(s).unwrap());
2787 let v: Outer = Decodable::decode(&mut decoder).unwrap();
2792 Inner { a: (), b: 2, c: vec!["abc".to_string(), "xyz".to_string()] }
2799 fn test_decode_option() {
2800 let mut decoder = Decoder::new(from_str("null").unwrap());
2801 let value: Option<String> = Decodable::decode(&mut decoder).unwrap();
2802 assert_eq!(value, None);
2804 let mut decoder = Decoder::new(from_str("\"jodhpurs\"").unwrap());
2805 let value: Option<String> = Decodable::decode(&mut decoder).unwrap();
2806 assert_eq!(value, Some("jodhpurs".to_string()));
2810 fn test_decode_enum() {
2811 let mut decoder = Decoder::new(from_str("\"Dog\"").unwrap());
2812 let value: Animal = Decodable::decode(&mut decoder).unwrap();
2813 assert_eq!(value, Dog);
2815 let s = "{\"variant\":\"Frog\",\"fields\":[\"Henry\",349]}";
2816 let mut decoder = Decoder::new(from_str(s).unwrap());
2817 let value: Animal = Decodable::decode(&mut decoder).unwrap();
2818 assert_eq!(value, Frog("Henry".to_string(), 349));
2822 fn test_decode_map() {
2823 let s = "{\"a\": \"Dog\", \"b\": {\"variant\":\"Frog\",\
2824 \"fields\":[\"Henry\", 349]}}";
2825 let mut decoder = Decoder::new(from_str(s).unwrap());
2826 let mut map: TreeMap<String, Animal> = Decodable::decode(&mut decoder).unwrap();
2828 assert_eq!(map.pop(&"a".to_string()), Some(Dog));
2829 assert_eq!(map.pop(&"b".to_string()), Some(Frog("Henry".to_string(), 349)));
2833 fn test_multiline_errors() {
2834 assert_eq!(from_str("{\n \"foo\":\n \"bar\""),
2835 Err(SyntaxError(EOFWhileParsingObject, 3u, 8u)));
2838 #[deriving(Decodable)]
2839 struct DecodeStruct {
2843 w: Vec<DecodeStruct>
2845 #[deriving(Decodable)]
2850 fn check_err<T: Decodable<Decoder, DecoderError>>(to_parse: &'static str,
2851 expected: DecoderError) {
2852 let res: DecodeResult<T> = match from_str(to_parse) {
2853 Err(e) => Err(ParseError(e)),
2854 Ok(json) => Decodable::decode(&mut Decoder::new(json))
2857 Ok(_) => fail!("`{}` parsed & decoded ok, expecting error `{}`",
2858 to_parse, expected),
2859 Err(ParseError(e)) => fail!("`{}` is not valid json: {}",
2862 assert_eq!(e, expected);
2867 fn test_decode_errors_struct() {
2868 check_err::<DecodeStruct>("[]", ExpectedError("Object".to_string(), "[]".to_string()));
2869 check_err::<DecodeStruct>("{\"x\": true, \"y\": true, \"z\": \"\", \"w\": []}",
2870 ExpectedError("Number".to_string(), "true".to_string()));
2871 check_err::<DecodeStruct>("{\"x\": 1, \"y\": [], \"z\": \"\", \"w\": []}",
2872 ExpectedError("Boolean".to_string(), "[]".to_string()));
2873 check_err::<DecodeStruct>("{\"x\": 1, \"y\": true, \"z\": {}, \"w\": []}",
2874 ExpectedError("String".to_string(), "{}".to_string()));
2875 check_err::<DecodeStruct>("{\"x\": 1, \"y\": true, \"z\": \"\", \"w\": null}",
2876 ExpectedError("List".to_string(), "null".to_string()));
2877 check_err::<DecodeStruct>("{\"x\": 1, \"y\": true, \"z\": \"\"}",
2878 MissingFieldError("w".to_string()));
2881 fn test_decode_errors_enum() {
2882 check_err::<DecodeEnum>("{}",
2883 MissingFieldError("variant".to_string()));
2884 check_err::<DecodeEnum>("{\"variant\": 1}",
2885 ExpectedError("String".to_string(), "1".to_string()));
2886 check_err::<DecodeEnum>("{\"variant\": \"A\"}",
2887 MissingFieldError("fields".to_string()));
2888 check_err::<DecodeEnum>("{\"variant\": \"A\", \"fields\": null}",
2889 ExpectedError("List".to_string(), "null".to_string()));
2890 check_err::<DecodeEnum>("{\"variant\": \"C\", \"fields\": []}",
2891 UnknownVariantError("C".to_string()));
2896 let json_value = from_str("{\"dog\" : \"cat\"}").unwrap();
2897 let found_str = json_value.find(&"dog".to_string());
2898 assert!(found_str.is_some() && found_str.unwrap().as_string().unwrap() == "cat");
2902 fn test_find_path(){
2903 let json_value = from_str("{\"dog\":{\"cat\": {\"mouse\" : \"cheese\"}}}").unwrap();
2904 let found_str = json_value.find_path(&[&"dog".to_string(),
2905 &"cat".to_string(), &"mouse".to_string()]);
2906 assert!(found_str.is_some() && found_str.unwrap().as_string().unwrap() == "cheese");
2911 let json_value = from_str("{\"dog\":{\"cat\": {\"mouse\" : \"cheese\"}}}").unwrap();
2912 let found_str = json_value.search(&"mouse".to_string()).and_then(|j| j.as_string());
2913 assert!(found_str.is_some());
2914 assert!(found_str.unwrap() == "cheese");
2918 fn test_is_object(){
2919 let json_value = from_str("{}").unwrap();
2920 assert!(json_value.is_object());
2924 fn test_as_object(){
2925 let json_value = from_str("{}").unwrap();
2926 let json_object = json_value.as_object();
2927 assert!(json_object.is_some());
2932 let json_value = from_str("[1, 2, 3]").unwrap();
2933 assert!(json_value.is_list());
2938 let json_value = from_str("[1, 2, 3]").unwrap();
2939 let json_list = json_value.as_list();
2940 let expected_length = 3;
2941 assert!(json_list.is_some() && json_list.unwrap().len() == expected_length);
2945 fn test_is_string(){
2946 let json_value = from_str("\"dog\"").unwrap();
2947 assert!(json_value.is_string());
2951 fn test_as_string(){
2952 let json_value = from_str("\"dog\"").unwrap();
2953 let json_str = json_value.as_string();
2954 let expected_str = "dog";
2955 assert_eq!(json_str, Some(expected_str));
2959 fn test_is_number(){
2960 let json_value = from_str("12").unwrap();
2961 assert!(json_value.is_number());
2965 fn test_as_number(){
2966 let json_value = from_str("12").unwrap();
2967 let json_num = json_value.as_number();
2968 let expected_num = 12f64;
2969 assert!(json_num.is_some() && json_num.unwrap() == expected_num);
2973 fn test_is_boolean(){
2974 let json_value = from_str("false").unwrap();
2975 assert!(json_value.is_boolean());
2979 fn test_as_boolean(){
2980 let json_value = from_str("false").unwrap();
2981 let json_bool = json_value.as_boolean();
2982 let expected_bool = false;
2983 assert!(json_bool.is_some() && json_bool.unwrap() == expected_bool);
2988 let json_value = from_str("null").unwrap();
2989 assert!(json_value.is_null());
2994 let json_value = from_str("null").unwrap();
2995 let json_null = json_value.as_null();
2996 let expected_null = ();
2997 assert!(json_null.is_some() && json_null.unwrap() == expected_null);
3001 fn test_encode_hashmap_with_numeric_key() {
3002 use std::str::from_utf8;
3003 use std::io::Writer;
3004 use std::io::MemWriter;
3005 use collections::HashMap;
3006 let mut hm: HashMap<uint, bool> = HashMap::new();
3008 let mut mem_buf = MemWriter::new();
3010 let mut encoder = Encoder::new(&mut mem_buf as &mut io::Writer);
3011 hm.encode(&mut encoder).unwrap();
3013 let bytes = mem_buf.unwrap();
3014 let json_str = from_utf8(bytes.as_slice()).unwrap();
3015 match from_str(json_str) {
3016 Err(_) => fail!("Unable to parse json_str: {}", json_str),
3017 _ => {} // it parsed and we are good to go
3021 fn test_prettyencode_hashmap_with_numeric_key() {
3022 use std::str::from_utf8;
3023 use std::io::Writer;
3024 use std::io::MemWriter;
3025 use collections::HashMap;
3026 let mut hm: HashMap<uint, bool> = HashMap::new();
3028 let mut mem_buf = MemWriter::new();
3030 let mut encoder = PrettyEncoder::new(&mut mem_buf as &mut io::Writer);
3031 hm.encode(&mut encoder).unwrap()
3033 let bytes = mem_buf.unwrap();
3034 let json_str = from_utf8(bytes.as_slice()).unwrap();
3035 match from_str(json_str) {
3036 Err(_) => fail!("Unable to parse json_str: {}", json_str),
3037 _ => {} // it parsed and we are good to go
3041 fn test_hashmap_with_numeric_key_can_handle_double_quote_delimited_key() {
3042 use collections::HashMap;
3044 let json_str = "{\"1\":true}";
3045 let json_obj = match from_str(json_str) {
3046 Err(_) => fail!("Unable to parse json_str: {}", json_str),
3049 let mut decoder = Decoder::new(json_obj);
3050 let _hm: HashMap<uint, bool> = Decodable::decode(&mut decoder).unwrap();
3053 fn assert_stream_equal(src: &str, expected: ~[(JsonEvent, ~[StackElement])]) {
3054 let mut parser = Parser::new(src.chars());
3057 let evt = match parser.next() {
3061 let (ref expected_evt, ref expected_stack) = expected[i];
3062 if !parser.stack().is_equal_to(expected_stack.as_slice()) {
3063 fail!("Parser stack is not equal to {}", expected_stack);
3065 assert_eq!(&evt, expected_evt);
3070 fn test_streaming_parser() {
3071 assert_stream_equal(
3072 r#"{ "foo":"bar", "array" : [0, 1, 2,3 ,4,5], "idents":[null,true,false]}"#,
3075 (StringValue("bar".to_string()), ~[Key("foo")]),
3076 (ListStart, ~[Key("array")]),
3077 (NumberValue(0.0), ~[Key("array"), Index(0)]),
3078 (NumberValue(1.0), ~[Key("array"), Index(1)]),
3079 (NumberValue(2.0), ~[Key("array"), Index(2)]),
3080 (NumberValue(3.0), ~[Key("array"), Index(3)]),
3081 (NumberValue(4.0), ~[Key("array"), Index(4)]),
3082 (NumberValue(5.0), ~[Key("array"), Index(5)]),
3083 (ListEnd, ~[Key("array")]),
3084 (ListStart, ~[Key("idents")]),
3085 (NullValue, ~[Key("idents"), Index(0)]),
3086 (BooleanValue(true), ~[Key("idents"), Index(1)]),
3087 (BooleanValue(false), ~[Key("idents"), Index(2)]),
3088 (ListEnd, ~[Key("idents")]),
3093 fn last_event(src: &str) -> JsonEvent {
3094 let mut parser = Parser::new(src.chars());
3095 let mut evt = NullValue;
3097 evt = match parser.next() {
3104 #[ignore(cfg(target_word_size = "32"))] // FIXME(#14064)
3105 fn test_read_object_streaming() {
3106 assert_eq!(last_event("{ "), Error(SyntaxError(EOFWhileParsingObject, 1, 3)));
3107 assert_eq!(last_event("{1"), Error(SyntaxError(KeyMustBeAString, 1, 2)));
3108 assert_eq!(last_event("{ \"a\""), Error(SyntaxError(EOFWhileParsingObject, 1, 6)));
3109 assert_eq!(last_event("{\"a\""), Error(SyntaxError(EOFWhileParsingObject, 1, 5)));
3110 assert_eq!(last_event("{\"a\" "), Error(SyntaxError(EOFWhileParsingObject, 1, 6)));
3112 assert_eq!(last_event("{\"a\" 1"), Error(SyntaxError(ExpectedColon, 1, 6)));
3113 assert_eq!(last_event("{\"a\":"), Error(SyntaxError(EOFWhileParsingValue, 1, 6)));
3114 assert_eq!(last_event("{\"a\":1"), Error(SyntaxError(EOFWhileParsingObject, 1, 7)));
3115 assert_eq!(last_event("{\"a\":1 1"), Error(SyntaxError(InvalidSyntax, 1, 8)));
3116 assert_eq!(last_event("{\"a\":1,"), Error(SyntaxError(EOFWhileParsingObject, 1, 8)));
3118 assert_stream_equal(
3120 box [(ObjectStart, box []), (ObjectEnd, box [])]
3122 assert_stream_equal(
3125 (ObjectStart, box []),
3126 (NumberValue(3.0), box [Key("a")]),
3127 (ObjectEnd, box []),
3130 assert_stream_equal(
3131 "{ \"a\": null, \"b\" : true }",
3133 (ObjectStart, box []),
3134 (NullValue, box [Key("a")]),
3135 (BooleanValue(true), box [Key("b")]),
3136 (ObjectEnd, box []),
3139 assert_stream_equal(
3140 "{\"a\" : 1.0 ,\"b\": [ true ]}",
3142 (ObjectStart, box []),
3143 (NumberValue(1.0), box [Key("a")]),
3144 (ListStart, box [Key("b")]),
3145 (BooleanValue(true),box [Key("b"), Index(0)]),
3146 (ListEnd, box [Key("b")]),
3147 (ObjectEnd, box []),
3150 assert_stream_equal(
3156 { "c": {"d": null} }
3161 (NumberValue(1.0), ~[Key("a")]),
3162 (ListStart, ~[Key("b")]),
3163 (BooleanValue(true), ~[Key("b"), Index(0)]),
3164 (StringValue("foo\nbar".to_string()), ~[Key("b"), Index(1)]),
3165 (ObjectStart, ~[Key("b"), Index(2)]),
3166 (ObjectStart, ~[Key("b"), Index(2), Key("c")]),
3167 (NullValue, ~[Key("b"), Index(2), Key("c"), Key("d")]),
3168 (ObjectEnd, ~[Key("b"), Index(2), Key("c")]),
3169 (ObjectEnd, ~[Key("b"), Index(2)]),
3170 (ListEnd, ~[Key("b")]),
3176 #[ignore(cfg(target_word_size = "32"))] // FIXME(#14064)
3177 fn test_read_list_streaming() {
3178 assert_stream_equal(
3181 (ListStart, box []),
3185 assert_stream_equal(
3188 (ListStart, box []),
3192 assert_stream_equal(
3195 (ListStart, box []),
3196 (BooleanValue(true), box [Index(0)]),
3200 assert_stream_equal(
3203 (ListStart, box []),
3204 (BooleanValue(false), box [Index(0)]),
3208 assert_stream_equal(
3211 (ListStart, box []),
3212 (NullValue, box [Index(0)]),
3216 assert_stream_equal(
3219 (ListStart, box []),
3220 (NumberValue(3.0), box [Index(0)]),
3221 (NumberValue(1.0), box [Index(1)]),
3225 assert_stream_equal(
3228 (ListStart, box []),
3229 (NumberValue(3.0), box [Index(0)]),
3230 (NumberValue(2.0), box [Index(1)]),
3234 assert_stream_equal(
3237 (ListStart, box []),
3238 (NumberValue(2.0), box [Index(0)]),
3239 (ListStart, box [Index(1)]),
3240 (NumberValue(4.0), box [Index(1), Index(0)]),
3241 (NumberValue(1.0), box [Index(1), Index(1)]),
3242 (ListEnd, box [Index(1)]),
3247 assert_eq!(last_event("["), Error(SyntaxError(EOFWhileParsingValue, 1, 2)));
3249 assert_eq!(from_str("["), Err(SyntaxError(EOFWhileParsingValue, 1, 2)));
3250 assert_eq!(from_str("[1"), Err(SyntaxError(EOFWhileParsingList, 1, 3)));
3251 assert_eq!(from_str("[1,"), Err(SyntaxError(EOFWhileParsingValue, 1, 4)));
3252 assert_eq!(from_str("[1,]"), Err(SyntaxError(InvalidSyntax, 1, 4)));
3253 assert_eq!(from_str("[6 7]"), Err(SyntaxError(InvalidSyntax, 1, 4)));
3257 fn test_trailing_characters_streaming() {
3258 assert_eq!(last_event("nulla"), Error(SyntaxError(TrailingCharacters, 1, 5)));
3259 assert_eq!(last_event("truea"), Error(SyntaxError(TrailingCharacters, 1, 5)));
3260 assert_eq!(last_event("falsea"), Error(SyntaxError(TrailingCharacters, 1, 6)));
3261 assert_eq!(last_event("1a"), Error(SyntaxError(TrailingCharacters, 1, 2)));
3262 assert_eq!(last_event("[]a"), Error(SyntaxError(TrailingCharacters, 1, 3)));
3263 assert_eq!(last_event("{}a"), Error(SyntaxError(TrailingCharacters, 1, 3)));
3266 fn test_read_identifiers_streaming() {
3267 assert_eq!(Parser::new("null".chars()).next(), Some(NullValue));
3268 assert_eq!(Parser::new("true".chars()).next(), Some(BooleanValue(true)));
3269 assert_eq!(Parser::new("false".chars()).next(), Some(BooleanValue(false)));
3271 assert_eq!(last_event("n"), Error(SyntaxError(InvalidSyntax, 1, 2)));
3272 assert_eq!(last_event("nul"), Error(SyntaxError(InvalidSyntax, 1, 4)));
3273 assert_eq!(last_event("t"), Error(SyntaxError(InvalidSyntax, 1, 2)));
3274 assert_eq!(last_event("truz"), Error(SyntaxError(InvalidSyntax, 1, 4)));
3275 assert_eq!(last_event("f"), Error(SyntaxError(InvalidSyntax, 1, 2)));
3276 assert_eq!(last_event("faz"), Error(SyntaxError(InvalidSyntax, 1, 3)));
3281 let mut stack = Stack::new();
3283 assert!(stack.is_empty());
3284 assert!(stack.len() == 0);
3285 assert!(!stack.last_is_index());
3287 stack.push_index(0);
3290 assert!(stack.len() == 1);
3291 assert!(stack.is_equal_to([Index(1)]));
3292 assert!(stack.starts_with([Index(1)]));
3293 assert!(stack.ends_with([Index(1)]));
3294 assert!(stack.last_is_index());
3295 assert!(stack.get(0) == Index(1));
3297 stack.push_key("foo".to_string());
3299 assert!(stack.len() == 2);
3300 assert!(stack.is_equal_to([Index(1), Key("foo")]));
3301 assert!(stack.starts_with([Index(1), Key("foo")]));
3302 assert!(stack.starts_with([Index(1)]));
3303 assert!(stack.ends_with([Index(1), Key("foo")]));
3304 assert!(stack.ends_with([Key("foo")]));
3305 assert!(!stack.last_is_index());
3306 assert!(stack.get(0) == Index(1));
3307 assert!(stack.get(1) == Key("foo"));
3309 stack.push_key("bar".to_string());
3311 assert!(stack.len() == 3);
3312 assert!(stack.is_equal_to([Index(1), Key("foo"), Key("bar")]));
3313 assert!(stack.starts_with([Index(1)]));
3314 assert!(stack.starts_with([Index(1), Key("foo")]));
3315 assert!(stack.starts_with([Index(1), Key("foo"), Key("bar")]));
3316 assert!(stack.ends_with([Key("bar")]));
3317 assert!(stack.ends_with([Key("foo"), Key("bar")]));
3318 assert!(stack.ends_with([Index(1), Key("foo"), Key("bar")]));
3319 assert!(!stack.last_is_index());
3320 assert!(stack.get(0) == Index(1));
3321 assert!(stack.get(1) == Key("foo"));
3322 assert!(stack.get(2) == Key("bar"));
3326 assert!(stack.len() == 2);
3327 assert!(stack.is_equal_to([Index(1), Key("foo")]));
3328 assert!(stack.starts_with([Index(1), Key("foo")]));
3329 assert!(stack.starts_with([Index(1)]));
3330 assert!(stack.ends_with([Index(1), Key("foo")]));
3331 assert!(stack.ends_with([Key("foo")]));
3332 assert!(!stack.last_is_index());
3333 assert!(stack.get(0) == Index(1));
3334 assert!(stack.get(1) == Key("foo"));
3338 fn bench_streaming_small(b: &mut Bencher) {
3340 let mut parser = Parser::new(
3346 { "c": {"d": null} }
3351 match parser.next() {
3359 fn bench_small(b: &mut Bencher) {
3361 let _ = from_str(r#"{
3366 { "c": {"d": null} }
3372 fn big_json() -> String {
3373 let mut src = "[\n".to_string();
3374 for _ in range(0, 500) {
3375 src.push_str(r#"{ "a": true, "b": null, "c":3.1415, "d": "Hello world", "e": \
3378 src.push_str("{}]");
3383 fn bench_streaming_large(b: &mut Bencher) {
3384 let src = big_json();
3386 let mut parser = Parser::new(src.as_slice().chars());
3388 match parser.next() {
3396 fn bench_large(b: &mut Bencher) {
3397 let src = big_json();
3398 b.iter( || { let _ = from_str(src.as_slice()); });