1 // Copyright 2012-2014 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_docs)]
17 //! JSON parsing and serialization
21 //! JSON (JavaScript Object Notation) is a way to write data in Javascript.
22 //! Like XML, it allows to encode structured data in a text format that can be easily read by humans
23 //! Its simple syntax and native compatibility with JavaScript have made it a widely used format.
25 //! Data types that can be encoded are JavaScript types (see the `Json` enum for more details):
27 //! * `Boolean`: equivalent to rust's `bool`
28 //! * `Number`: equivalent to rust's `f64`
29 //! * `String`: equivalent to rust's `String`
30 //! * `Array`: equivalent to rust's `Vec<T>`, but also allowing objects of different types in the
32 //! * `Object`: equivalent to rust's `Treemap<String, json::Json>`
35 //! An object is a series of string keys mapping to values, in `"key": value` format.
36 //! Arrays are enclosed in square brackets ([ ... ]) and objects in curly brackets ({ ... }).
37 //! A simple JSON document encoding a person, his/her age, address and phone numbers could look like
41 //! "FirstName": "John",
42 //! "LastName": "Doe",
45 //! "Street": "Downing Street 10",
47 //! "Country": "Great Britain"
56 //! # Rust Type-based Encoding and Decoding
58 //! Rust provides a mechanism for low boilerplate encoding & decoding of values to and from JSON via
59 //! the serialization API.
60 //! To be able to encode a piece of data, it must implement the `serialize::Encodable` trait.
61 //! To be able to decode a piece of data, it must implement the `serialize::Decodable` trait.
62 //! The Rust compiler provides an annotation to automatically generate the code for these traits:
63 //! `#[deriving(Decodable, Encodable)]`
65 //! The JSON API provides an enum `json::Json` and a trait `ToJson` to encode objects.
66 //! The `ToJson` trait provides a `to_json` method to convert an object into a `json::Json` value.
67 //! A `json::Json` value can be encoded as a string or buffer using the functions described above.
68 //! You can also use the `json::Encoder` object, which implements the `Encoder` trait.
70 //! When using `ToJson` the `Encodable` trait implementation is not mandatory.
74 //! ## Using Autoserialization
76 //! Create a struct called `TestStruct` and serialize and deserialize it to and from JSON using the
77 //! serialization API, using the derived serialization code.
80 //! extern crate serialize;
81 //! use serialize::json;
83 //! // Automatically generate `Decodable` and `Encodable` trait implementations
84 //! #[deriving(Decodable, Encodable)]
85 //! pub struct TestStruct {
88 //! data_vector: Vec<u8>,
92 //! let object = TestStruct {
94 //! data_str: "toto".to_string(),
95 //! data_vector: vec![2,3,4,5],
98 //! // Serialize using `json::encode`
99 //! let encoded = json::encode(&object);
101 //! // Deserialize using `json::decode`
102 //! let decoded: TestStruct = json::decode(encoded.as_slice()).unwrap();
106 //! ## Using the `ToJson` trait
108 //! The examples above use the `ToJson` trait to generate the JSON string, which is required
109 //! for custom mappings.
111 //! ### Simple example of `ToJson` usage
114 //! extern crate serialize;
115 //! use serialize::json::ToJson;
116 //! use serialize::json;
118 //! // A custom data structure
119 //! struct ComplexNum {
124 //! // JSON value representation
125 //! impl ToJson for ComplexNum {
126 //! fn to_json(&self) -> json::Json {
127 //! json::String(format!("{}+{}i", self.a, self.b))
131 //! // Only generate `Encodable` trait implementation
132 //! #[deriving(Encodable)]
133 //! pub struct ComplexNumRecord {
140 //! let num = ComplexNum { a: 0.0001, b: 12.539 };
141 //! let data: String = json::encode(&ComplexNumRecord{
143 //! dsc: "test".to_string(),
144 //! val: num.to_json(),
146 //! println!("data: {}", data);
147 //! // data: {"uid":1,"dsc":"test","val":"0.0001+12.539j"};
151 //! ### Verbose example of `ToJson` usage
154 //! extern crate serialize;
155 //! use std::collections::TreeMap;
156 //! use serialize::json::ToJson;
157 //! use serialize::json;
159 //! // Only generate `Decodable` trait implementation
160 //! #[deriving(Decodable)]
161 //! pub struct TestStruct {
163 //! data_str: String,
164 //! data_vector: Vec<u8>,
167 //! // Specify encoding method manually
168 //! impl ToJson for TestStruct {
169 //! fn to_json(&self) -> json::Json {
170 //! let mut d = TreeMap::new();
171 //! // All standard types implement `to_json()`, so use it
172 //! d.insert("data_int".to_string(), self.data_int.to_json());
173 //! d.insert("data_str".to_string(), self.data_str.to_json());
174 //! d.insert("data_vector".to_string(), self.data_vector.to_json());
180 //! // Serialize using `ToJson`
181 //! let input_data = TestStruct {
183 //! data_str: "toto".to_string(),
184 //! data_vector: vec![2,3,4,5],
186 //! let json_obj: json::Json = input_data.to_json();
187 //! let json_str: String = json_obj.to_string();
189 //! // Deserialize like before
190 //! let decoded: TestStruct = json::decode(json_str.as_slice()).unwrap();
194 pub use self::JsonEvent::*;
195 pub use self::StackElement::*;
196 pub use self::Json::*;
197 pub use self::ErrorCode::*;
198 pub use self::ParserError::*;
199 pub use self::DecoderError::*;
200 use self::ParserState::*;
201 use self::InternalStackElement::*;
204 use std::collections::{HashMap, TreeMap};
205 use std::{char, f64, fmt, io, num, str};
206 use std::mem::{swap, transmute};
207 use std::num::{Float, FPNaN, FPInfinite, Int};
208 use std::str::{FromStr, ScalarValue};
215 /// Represents a json value
216 #[deriving(Clone, PartialEq, PartialOrd)]
221 String(string::String),
228 pub type JsonArray = Vec<Json>;
229 pub type JsonObject = TreeMap<string::String, Json>;
231 /// The errors that can arise while parsing a JSON stream.
232 #[deriving(Clone, PartialEq)]
236 EOFWhileParsingObject,
237 EOFWhileParsingArray,
238 EOFWhileParsingValue,
239 EOFWhileParsingString,
245 InvalidUnicodeCodePoint,
246 LoneLeadingSurrogateInHexEscape,
247 UnexpectedEndOfHexEscape,
253 #[deriving(Clone, PartialEq, Show)]
254 pub enum ParserError {
256 SyntaxError(ErrorCode, uint, uint),
257 IoError(io::IoErrorKind, &'static str),
260 // Builder and Parser have the same errors.
261 pub type BuilderError = ParserError;
263 #[deriving(Clone, PartialEq, Show)]
264 pub enum DecoderError {
265 ParseError(ParserError),
266 ExpectedError(string::String, string::String),
267 MissingFieldError(string::String),
268 UnknownVariantError(string::String),
269 ApplicationError(string::String)
272 /// Returns a readable error string for a given error code.
273 pub fn error_str(error: ErrorCode) -> &'static str {
275 InvalidSyntax => "invalid syntax",
276 InvalidNumber => "invalid number",
277 EOFWhileParsingObject => "EOF While parsing object",
278 EOFWhileParsingArray => "EOF While parsing array",
279 EOFWhileParsingValue => "EOF While parsing value",
280 EOFWhileParsingString => "EOF While parsing string",
281 KeyMustBeAString => "key must be a string",
282 ExpectedColon => "expected `:`",
283 TrailingCharacters => "trailing characters",
284 TrailingComma => "trailing comma",
285 InvalidEscape => "invalid escape",
286 UnrecognizedHex => "invalid \\u escape (unrecognized hex)",
287 NotFourDigit => "invalid \\u escape (not four digits)",
288 NotUtf8 => "contents not utf-8",
289 InvalidUnicodeCodePoint => "invalid Unicode code point",
290 LoneLeadingSurrogateInHexEscape => "lone leading surrogate in hex escape",
291 UnexpectedEndOfHexEscape => "unexpected end of hex escape",
295 /// Shortcut function to decode a JSON `&str` into an object
296 pub fn decode<T: ::Decodable<Decoder, DecoderError>>(s: &str) -> DecodeResult<T> {
297 let json = match from_str(s) {
299 Err(e) => return Err(ParseError(e))
302 let mut decoder = Decoder::new(json);
303 ::Decodable::decode(&mut decoder)
306 /// Shortcut function to encode a `T` into a JSON `String`
307 pub fn encode<'a, T: Encodable<Encoder<'a>, io::IoError>>(object: &T) -> string::String {
308 let buff = Encoder::buffer_encode(object);
309 string::String::from_utf8(buff).unwrap()
312 impl fmt::Show for ErrorCode {
313 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
314 error_str(*self).fmt(f)
318 fn io_error_to_error(io: io::IoError) -> ParserError {
319 IoError(io.kind, io.desc)
322 impl std::error::Error for DecoderError {
323 fn description(&self) -> &str { "decoder error" }
324 fn detail(&self) -> Option<std::string::String> { Some(self.to_string()) }
327 pub type EncodeResult = io::IoResult<()>;
328 pub type DecodeResult<T> = Result<T, DecoderError>;
330 pub fn escape_bytes(wr: &mut io::Writer, bytes: &[u8]) -> Result<(), io::IoError> {
331 try!(wr.write_str("\""));
335 for (i, byte) in bytes.iter().enumerate() {
336 let escaped = match *byte {
348 try!(wr.write(bytes[start..i]));
351 try!(wr.write_str(escaped));
356 if start != bytes.len() {
357 try!(wr.write(bytes[start..]));
363 fn escape_str(writer: &mut io::Writer, v: &str) -> Result<(), io::IoError> {
364 escape_bytes(writer, v.as_bytes())
367 fn escape_char(writer: &mut io::Writer, v: char) -> Result<(), io::IoError> {
368 let mut buf = [0, .. 4];
369 v.encode_utf8(&mut buf);
370 escape_bytes(writer, &mut buf)
373 fn spaces(wr: &mut io::Writer, mut n: uint) -> Result<(), io::IoError> {
374 const LEN: uint = 16;
375 static BUF: [u8, ..LEN] = [b' ', ..LEN];
378 try!(wr.write(&BUF));
389 fn fmt_number_or_null(v: f64) -> string::String {
391 FPNaN | FPInfinite => string::String::from_str("null"),
392 _ => f64::to_str_digits(v, 6u)
396 /// A structure for implementing serialization to JSON.
397 pub struct Encoder<'a> {
398 writer: &'a mut io::Writer+'a,
401 impl<'a> Encoder<'a> {
402 /// Creates a new JSON encoder whose output will be written to the writer
404 pub fn new(writer: &'a mut io::Writer) -> Encoder<'a> {
405 Encoder { writer: writer }
408 /// Encode the specified struct into a json [u8]
409 pub fn buffer_encode<T:Encodable<Encoder<'a>, io::IoError>>(object: &T) -> Vec<u8> {
410 //Serialize the object in a string using a writer
411 let mut m = Vec::new();
412 // FIXME(14302) remove the transmute and unsafe block.
414 let mut encoder = Encoder::new(&mut m as &mut io::Writer);
415 // Vec<u8> never Errs
416 let _ = object.encode(transmute(&mut encoder));
422 impl<'a> ::Encoder<io::IoError> for Encoder<'a> {
423 fn emit_nil(&mut self) -> EncodeResult { write!(self.writer, "null") }
425 fn emit_uint(&mut self, v: uint) -> EncodeResult { self.emit_f64(v as f64) }
426 fn emit_u64(&mut self, v: u64) -> EncodeResult { self.emit_f64(v as f64) }
427 fn emit_u32(&mut self, v: u32) -> EncodeResult { self.emit_f64(v as f64) }
428 fn emit_u16(&mut self, v: u16) -> EncodeResult { self.emit_f64(v as f64) }
429 fn emit_u8(&mut self, v: u8) -> EncodeResult { self.emit_f64(v as f64) }
431 fn emit_int(&mut self, v: int) -> EncodeResult { self.emit_f64(v as f64) }
432 fn emit_i64(&mut self, v: i64) -> EncodeResult { self.emit_f64(v as f64) }
433 fn emit_i32(&mut self, v: i32) -> EncodeResult { self.emit_f64(v as f64) }
434 fn emit_i16(&mut self, v: i16) -> EncodeResult { self.emit_f64(v as f64) }
435 fn emit_i8(&mut self, v: i8) -> EncodeResult { self.emit_f64(v as f64) }
437 fn emit_bool(&mut self, v: bool) -> EncodeResult {
439 write!(self.writer, "true")
441 write!(self.writer, "false")
445 fn emit_f64(&mut self, v: f64) -> EncodeResult {
446 write!(self.writer, "{}", fmt_number_or_null(v))
448 fn emit_f32(&mut self, v: f32) -> EncodeResult { self.emit_f64(v as f64) }
450 fn emit_char(&mut self, v: char) -> EncodeResult {
451 escape_char(self.writer, v)
453 fn emit_str(&mut self, v: &str) -> EncodeResult {
454 escape_str(self.writer, v)
457 fn emit_enum(&mut self, _name: &str, f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
461 fn emit_enum_variant(&mut self,
465 f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
466 // enums are encoded as strings or objects
468 // Kangaroo(34,"William") => {"variant": "Kangaroo", "fields": [34,"William"]}
470 escape_str(self.writer, name)
472 try!(write!(self.writer, "{{\"variant\":"));
473 try!(escape_str(self.writer, name));
474 try!(write!(self.writer, ",\"fields\":["));
476 write!(self.writer, "]}}")
480 fn emit_enum_variant_arg(&mut self,
482 f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
484 try!(write!(self.writer, ","));
489 fn emit_enum_struct_variant(&mut self,
493 f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
494 self.emit_enum_variant(name, id, cnt, f)
497 fn emit_enum_struct_variant_field(&mut self,
500 f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
501 self.emit_enum_variant_arg(idx, f)
504 fn emit_struct(&mut self,
507 f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
508 try!(write!(self.writer, "{{"));
510 write!(self.writer, "}}")
513 fn emit_struct_field(&mut self,
516 f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
517 if idx != 0 { try!(write!(self.writer, ",")); }
518 try!(escape_str(self.writer, name));
519 try!(write!(self.writer, ":"));
523 fn emit_tuple(&mut self, len: uint, f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
524 self.emit_seq(len, f)
526 fn emit_tuple_arg(&mut self,
528 f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
529 self.emit_seq_elt(idx, f)
532 fn emit_tuple_struct(&mut self,
535 f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
536 self.emit_seq(len, f)
538 fn emit_tuple_struct_arg(&mut self,
540 f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
541 self.emit_seq_elt(idx, f)
544 fn emit_option(&mut self, f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
547 fn emit_option_none(&mut self) -> EncodeResult { self.emit_nil() }
548 fn emit_option_some(&mut self, f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
552 fn emit_seq(&mut self, _len: uint, f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
553 try!(write!(self.writer, "["));
555 write!(self.writer, "]")
558 fn emit_seq_elt(&mut self, idx: uint, f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
560 try!(write!(self.writer, ","));
565 fn emit_map(&mut self, _len: uint, f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
566 try!(write!(self.writer, "{{"));
568 write!(self.writer, "}}")
571 fn emit_map_elt_key(&mut self,
573 f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
574 if idx != 0 { try!(write!(self.writer, ",")) }
575 // ref #12967, make sure to wrap a key in double quotes,
576 // in the event that its of a type that omits them (eg numbers)
577 let mut buf = Vec::new();
578 // FIXME(14302) remove the transmute and unsafe block.
580 let mut check_encoder = Encoder::new(&mut buf);
581 try!(f(transmute(&mut check_encoder)));
583 let out = str::from_utf8(buf[]).unwrap();
584 let needs_wrapping = out.char_at(0) != '"' && out.char_at_reverse(out.len()) != '"';
585 if needs_wrapping { try!(write!(self.writer, "\"")); }
587 if needs_wrapping { try!(write!(self.writer, "\"")); }
591 fn emit_map_elt_val(&mut self,
593 f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
594 try!(write!(self.writer, ":"));
599 /// Another encoder for JSON, but prints out human-readable JSON instead of
601 pub struct PrettyEncoder<'a> {
602 writer: &'a mut io::Writer+'a,
607 impl<'a> PrettyEncoder<'a> {
608 /// Creates a new encoder whose output will be written to the specified writer
609 pub fn new<'a>(writer: &'a mut io::Writer) -> PrettyEncoder<'a> {
610 PrettyEncoder { writer: writer, curr_indent: 0, indent: 2, }
613 /// Set the number of spaces to indent for each level.
614 /// This is safe to set during encoding.
615 pub fn set_indent<'a>(&mut self, indent: uint) {
616 // self.indent very well could be 0 so we need to use checked division.
617 let level = self.curr_indent.checked_div(self.indent).unwrap_or(0);
618 self.indent = indent;
619 self.curr_indent = level * self.indent;
623 impl<'a> ::Encoder<io::IoError> for PrettyEncoder<'a> {
624 fn emit_nil(&mut self) -> EncodeResult { write!(self.writer, "null") }
626 fn emit_uint(&mut self, v: uint) -> EncodeResult { self.emit_f64(v as f64) }
627 fn emit_u64(&mut self, v: u64) -> EncodeResult { self.emit_f64(v as f64) }
628 fn emit_u32(&mut self, v: u32) -> EncodeResult { self.emit_f64(v as f64) }
629 fn emit_u16(&mut self, v: u16) -> EncodeResult { self.emit_f64(v as f64) }
630 fn emit_u8(&mut self, v: u8) -> EncodeResult { self.emit_f64(v as f64) }
632 fn emit_int(&mut self, v: int) -> EncodeResult { self.emit_f64(v as f64) }
633 fn emit_i64(&mut self, v: i64) -> EncodeResult { self.emit_f64(v as f64) }
634 fn emit_i32(&mut self, v: i32) -> EncodeResult { self.emit_f64(v as f64) }
635 fn emit_i16(&mut self, v: i16) -> EncodeResult { self.emit_f64(v as f64) }
636 fn emit_i8(&mut self, v: i8) -> EncodeResult { self.emit_f64(v as f64) }
638 fn emit_bool(&mut self, v: bool) -> EncodeResult {
640 write!(self.writer, "true")
642 write!(self.writer, "false")
646 fn emit_f64(&mut self, v: f64) -> EncodeResult {
647 write!(self.writer, "{}", fmt_number_or_null(v))
649 fn emit_f32(&mut self, v: f32) -> EncodeResult {
650 self.emit_f64(v as f64)
653 fn emit_char(&mut self, v: char) -> EncodeResult {
654 escape_char(self.writer, v)
656 fn emit_str(&mut self, v: &str) -> EncodeResult {
657 escape_str(self.writer, v)
660 fn emit_enum(&mut self,
662 f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
666 fn emit_enum_variant(&mut self,
670 f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
672 escape_str(self.writer, name)
674 try!(write!(self.writer, "{{\n"));
675 self.curr_indent += self.indent;
676 try!(spaces(self.writer, self.curr_indent));
677 try!(write!(self.writer, "\"variant\": "));
678 try!(escape_str(self.writer, name));
679 try!(write!(self.writer, ",\n"));
680 try!(spaces(self.writer, self.curr_indent));
681 try!(write!(self.writer, "\"fields\": [\n"));
682 self.curr_indent += self.indent;
684 self.curr_indent -= self.indent;
685 try!(write!(self.writer, "\n"));
686 try!(spaces(self.writer, self.curr_indent));
687 self.curr_indent -= self.indent;
688 try!(write!(self.writer, "]\n"));
689 try!(spaces(self.writer, self.curr_indent));
690 write!(self.writer, "}}")
694 fn emit_enum_variant_arg(&mut self,
696 f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
698 try!(write!(self.writer, ",\n"));
700 try!(spaces(self.writer, self.curr_indent));
704 fn emit_enum_struct_variant(&mut self,
708 f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
709 self.emit_enum_variant(name, id, cnt, f)
712 fn emit_enum_struct_variant_field(&mut self,
715 f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
716 self.emit_enum_variant_arg(idx, f)
720 fn emit_struct(&mut self,
723 f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
725 write!(self.writer, "{{}}")
727 try!(write!(self.writer, "{{"));
728 self.curr_indent += self.indent;
730 self.curr_indent -= self.indent;
731 try!(write!(self.writer, "\n"));
732 try!(spaces(self.writer, self.curr_indent));
733 write!(self.writer, "}}")
737 fn emit_struct_field(&mut self,
740 f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
742 try!(write!(self.writer, "\n"));
744 try!(write!(self.writer, ",\n"));
746 try!(spaces(self.writer, self.curr_indent));
747 try!(escape_str(self.writer, name));
748 try!(write!(self.writer, ": "));
752 fn emit_tuple(&mut self,
754 f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
755 self.emit_seq(len, f)
757 fn emit_tuple_arg(&mut self,
759 f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
760 self.emit_seq_elt(idx, f)
763 fn emit_tuple_struct(&mut self,
766 f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
767 self.emit_seq(len, f)
769 fn emit_tuple_struct_arg(&mut self,
771 f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
772 self.emit_seq_elt(idx, f)
775 fn emit_option(&mut self, f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
778 fn emit_option_none(&mut self) -> EncodeResult { self.emit_nil() }
779 fn emit_option_some(&mut self, f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
783 fn emit_seq(&mut self,
785 f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
787 write!(self.writer, "[]")
789 try!(write!(self.writer, "["));
790 self.curr_indent += self.indent;
792 self.curr_indent -= self.indent;
793 try!(write!(self.writer, "\n"));
794 try!(spaces(self.writer, self.curr_indent));
795 write!(self.writer, "]")
799 fn emit_seq_elt(&mut self,
801 f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
803 try!(write!(self.writer, "\n"));
805 try!(write!(self.writer, ",\n"));
807 try!(spaces(self.writer, self.curr_indent));
811 fn emit_map(&mut self,
813 f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
815 write!(self.writer, "{{}}")
817 try!(write!(self.writer, "{{"));
818 self.curr_indent += self.indent;
820 self.curr_indent -= self.indent;
821 try!(write!(self.writer, "\n"));
822 try!(spaces(self.writer, self.curr_indent));
823 write!(self.writer, "}}")
827 fn emit_map_elt_key(&mut self,
829 f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
831 try!(write!(self.writer, "\n"));
833 try!(write!(self.writer, ",\n"));
835 try!(spaces(self.writer, self.curr_indent));
836 // ref #12967, make sure to wrap a key in double quotes,
837 // in the event that its of a type that omits them (eg numbers)
838 let mut buf = Vec::new();
839 // FIXME(14302) remove the transmute and unsafe block.
841 let mut check_encoder = PrettyEncoder::new(&mut buf);
842 try!(f(transmute(&mut check_encoder)));
844 let out = str::from_utf8(buf[]).unwrap();
845 let needs_wrapping = out.char_at(0) != '"' && out.char_at_reverse(out.len()) != '"';
846 if needs_wrapping { try!(write!(self.writer, "\"")); }
848 if needs_wrapping { try!(write!(self.writer, "\"")); }
852 fn emit_map_elt_val(&mut self,
854 f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
855 try!(write!(self.writer, ": "));
860 impl<E: ::Encoder<S>, S> Encodable<E, S> for Json {
861 fn encode(&self, e: &mut E) -> Result<(), S> {
863 I64(v) => v.encode(e),
864 U64(v) => v.encode(e),
865 F64(v) => v.encode(e),
866 String(ref v) => v.encode(e),
867 Boolean(v) => v.encode(e),
868 Array(ref v) => v.encode(e),
869 Object(ref v) => v.encode(e),
870 Null => e.emit_nil(),
876 /// Encodes a json value into an io::writer. Uses a single line.
877 pub fn to_writer(&self, writer: &mut io::Writer) -> EncodeResult {
878 let mut encoder = Encoder::new(writer);
879 self.encode(&mut encoder)
882 /// Encodes a json value into an io::writer.
883 /// Pretty-prints in a more readable format.
884 pub fn to_pretty_writer(&self, writer: &mut io::Writer) -> EncodeResult {
885 let mut encoder = PrettyEncoder::new(writer);
886 self.encode(&mut encoder)
889 /// Encodes a json value into a string
890 pub fn to_pretty_str(&self) -> string::String {
891 let mut s = Vec::new();
892 self.to_pretty_writer(&mut s as &mut io::Writer).unwrap();
893 string::String::from_utf8(s).unwrap()
896 /// If the Json value is an Object, returns the value associated with the provided key.
897 /// Otherwise, returns None.
898 pub fn find<'a>(&'a self, key: &str) -> Option<&'a Json>{
900 &Object(ref map) => map.get(key),
905 /// Attempts to get a nested Json Object for each key in `keys`.
906 /// If any key is found not to exist, find_path will return None.
907 /// Otherwise, it will return the Json value associated with the final key.
908 pub fn find_path<'a>(&'a self, keys: &[&str]) -> Option<&'a Json>{
909 let mut target = self;
910 for key in keys.iter() {
911 match target.find(*key) {
912 Some(t) => { target = t; },
919 /// If the Json value is an Object, performs a depth-first search until
920 /// a value associated with the provided key is found. If no value is found
921 /// or the Json value is not an Object, returns None.
922 pub fn search<'a>(&'a self, key: &str) -> Option<&'a Json> {
924 &Object(ref map) => {
926 Some(json_value) => Some(json_value),
928 for (_, v) in map.iter() {
929 match v.search(key) {
930 x if x.is_some() => return x,
942 /// Returns true if the Json value is an Object. Returns false otherwise.
943 pub fn is_object<'a>(&'a self) -> bool {
944 self.as_object().is_some()
947 /// If the Json value is an Object, returns the associated TreeMap.
948 /// Returns None otherwise.
949 pub fn as_object<'a>(&'a self) -> Option<&'a JsonObject> {
951 &Object(ref map) => Some(map),
956 /// Returns true if the Json value is an Array. Returns false otherwise.
957 pub fn is_array<'a>(&'a self) -> bool {
958 self.as_array().is_some()
961 /// If the Json value is an Array, returns the associated vector.
962 /// Returns None otherwise.
963 pub fn as_array<'a>(&'a self) -> Option<&'a JsonArray> {
965 &Array(ref array) => Some(&*array),
970 /// Returns true if the Json value is a String. Returns false otherwise.
971 pub fn is_string<'a>(&'a self) -> bool {
972 self.as_string().is_some()
975 /// If the Json value is a String, returns the associated str.
976 /// Returns None otherwise.
977 pub fn as_string<'a>(&'a self) -> Option<&'a str> {
979 String(ref s) => Some(s.as_slice()),
984 /// Returns true if the Json value is a Number. Returns false otherwise.
985 pub fn is_number(&self) -> bool {
987 I64(_) | U64(_) | F64(_) => true,
992 /// Returns true if the Json value is a i64. Returns false otherwise.
993 pub fn is_i64(&self) -> bool {
1000 /// Returns true if the Json value is a u64. Returns false otherwise.
1001 pub fn is_u64(&self) -> bool {
1008 /// Returns true if the Json value is a f64. Returns false otherwise.
1009 pub fn is_f64(&self) -> bool {
1016 /// If the Json value is a number, return or cast it to a i64.
1017 /// Returns None otherwise.
1018 pub fn as_i64(&self) -> Option<i64> {
1021 U64(n) => num::cast(n),
1026 /// If the Json value is a number, return or cast it to a u64.
1027 /// Returns None otherwise.
1028 pub fn as_u64(&self) -> Option<u64> {
1030 I64(n) => num::cast(n),
1036 /// If the Json value is a number, return or cast it to a f64.
1037 /// Returns None otherwise.
1038 pub fn as_f64(&self) -> Option<f64> {
1040 I64(n) => num::cast(n),
1041 U64(n) => num::cast(n),
1047 /// Returns true if the Json value is a Boolean. Returns false otherwise.
1048 pub fn is_boolean(&self) -> bool {
1049 self.as_boolean().is_some()
1052 /// If the Json value is a Boolean, returns the associated bool.
1053 /// Returns None otherwise.
1054 pub fn as_boolean(&self) -> Option<bool> {
1056 &Boolean(b) => Some(b),
1061 /// Returns true if the Json value is a Null. Returns false otherwise.
1062 pub fn is_null(&self) -> bool {
1063 self.as_null().is_some()
1066 /// If the Json value is a Null, returns ().
1067 /// Returns None otherwise.
1068 pub fn as_null(&self) -> Option<()> {
1076 impl<'a> ops::Index<&'a str, Json> for Json {
1077 fn index<'a>(&'a self, idx: & &str) -> &'a Json {
1078 self.find(*idx).unwrap()
1082 impl ops::Index<uint, Json> for Json {
1083 fn index<'a>(&'a self, idx: &uint) -> &'a Json {
1085 &Array(ref v) => v.index(idx),
1086 _ => panic!("can only index Json with uint if it is an array")
1091 /// The output of the streaming parser.
1092 #[deriving(PartialEq, Clone, Show)]
1093 pub enum JsonEvent {
1102 StringValue(string::String),
1107 #[deriving(PartialEq, Show)]
1109 // Parse a value in an array, true means first element.
1111 // Parse ',' or ']' after an element in an array.
1113 // Parse a key:value in an object, true means first element.
1115 // Parse ',' or ']' after an element in an object.
1119 // Expecting the stream to end.
1121 // Parsing can't continue.
1125 /// A Stack represents the current position of the parser in the logical
1126 /// structure of the JSON stream.
1127 /// For example foo.bar[3].x
1129 stack: Vec<InternalStackElement>,
1130 str_buffer: Vec<u8>,
1133 /// StackElements compose a Stack.
1134 /// For example, Key("foo"), Key("bar"), Index(3) and Key("x") are the
1135 /// StackElements compositing the stack that represents foo.bar[3].x
1136 #[deriving(PartialEq, Clone, Show)]
1137 pub enum StackElement<'l> {
1142 // Internally, Key elements are stored as indices in a buffer to avoid
1143 // allocating a string for every member of an object.
1144 #[deriving(PartialEq, Clone, Show)]
1145 enum InternalStackElement {
1147 InternalKey(u16, u16), // start, size
1151 pub fn new() -> Stack {
1152 Stack { stack: Vec::new(), str_buffer: Vec::new() }
1155 /// Returns The number of elements in the Stack.
1156 pub fn len(&self) -> uint { self.stack.len() }
1158 /// Returns true if the stack is empty.
1159 pub fn is_empty(&self) -> bool { self.stack.is_empty() }
1161 /// Provides access to the StackElement at a given index.
1162 /// lower indices are at the bottom of the stack while higher indices are
1164 pub fn get<'l>(&'l self, idx: uint) -> StackElement<'l> {
1165 match self.stack[idx] {
1166 InternalIndex(i) => Index(i),
1167 InternalKey(start, size) => {
1169 self.str_buffer[start as uint .. start as uint + size as uint]).unwrap())
1174 /// Compares this stack with an array of StackElements.
1175 pub fn is_equal_to(&self, rhs: &[StackElement]) -> bool {
1176 if self.stack.len() != rhs.len() { return false; }
1177 for i in range(0, rhs.len()) {
1178 if self.get(i) != rhs[i] { return false; }
1183 /// Returns true if the bottom-most elements of this stack are the same as
1184 /// the ones passed as parameter.
1185 pub fn starts_with(&self, rhs: &[StackElement]) -> bool {
1186 if self.stack.len() < rhs.len() { return false; }
1187 for i in range(0, rhs.len()) {
1188 if self.get(i) != rhs[i] { return false; }
1193 /// Returns true if the top-most elements of this stack are the same as
1194 /// the ones passed as parameter.
1195 pub fn ends_with(&self, rhs: &[StackElement]) -> bool {
1196 if self.stack.len() < rhs.len() { return false; }
1197 let offset = self.stack.len() - rhs.len();
1198 for i in range(0, rhs.len()) {
1199 if self.get(i + offset) != rhs[i] { return false; }
1204 /// Returns the top-most element (if any).
1205 pub fn top<'l>(&'l self) -> Option<StackElement<'l>> {
1206 return match self.stack.last() {
1208 Some(&InternalIndex(i)) => Some(Index(i)),
1209 Some(&InternalKey(start, size)) => {
1210 Some(Key(str::from_utf8(
1211 self.str_buffer[start as uint .. (start+size) as uint]
1217 // Used by Parser to insert Key elements at the top of the stack.
1218 fn push_key(&mut self, key: string::String) {
1219 self.stack.push(InternalKey(self.str_buffer.len() as u16, key.len() as u16));
1220 for c in key.as_bytes().iter() {
1221 self.str_buffer.push(*c);
1225 // Used by Parser to insert Index elements at the top of the stack.
1226 fn push_index(&mut self, index: u32) {
1227 self.stack.push(InternalIndex(index));
1230 // Used by Parser to remove the top-most element of the stack.
1232 assert!(!self.is_empty());
1233 match *self.stack.last().unwrap() {
1234 InternalKey(_, sz) => {
1235 let new_size = self.str_buffer.len() - sz as uint;
1236 self.str_buffer.truncate(new_size);
1238 InternalIndex(_) => {}
1243 // Used by Parser to test whether the top-most element is an index.
1244 fn last_is_index(&self) -> bool {
1245 if self.is_empty() { return false; }
1246 return match *self.stack.last().unwrap() {
1247 InternalIndex(_) => true,
1252 // Used by Parser to increment the index of the top-most element.
1253 fn bump_index(&mut self) {
1254 let len = self.stack.len();
1255 let idx = match *self.stack.last().unwrap() {
1256 InternalIndex(i) => { i + 1 }
1259 self.stack[len - 1] = InternalIndex(idx);
1263 /// A streaming JSON parser implemented as an iterator of JsonEvent, consuming
1264 /// an iterator of char.
1265 pub struct Parser<T> {
1270 // We maintain a stack representing where we are in the logical structure
1271 // of the JSON stream.
1273 // A state machine is kept to make it possible to interrupt and resume parsing.
1277 impl<T: Iterator<char>> Iterator<JsonEvent> for Parser<T> {
1278 fn next(&mut self) -> Option<JsonEvent> {
1279 if self.state == ParseFinished {
1283 if self.state == ParseBeforeFinish {
1284 self.parse_whitespace();
1285 // Make sure there is no trailing characters.
1287 self.state = ParseFinished;
1290 return Some(self.error_event(TrailingCharacters));
1294 return Some(self.parse());
1298 impl<T: Iterator<char>> Parser<T> {
1299 /// Creates the JSON parser.
1300 pub fn new(rdr: T) -> Parser<T> {
1301 let mut p = Parser {
1306 stack: Stack::new(),
1313 /// Provides access to the current position in the logical structure of the
1315 pub fn stack<'l>(&'l self) -> &'l Stack {
1319 fn eof(&self) -> bool { self.ch.is_none() }
1320 fn ch_or_null(&self) -> char { self.ch.unwrap_or('\x00') }
1321 fn bump(&mut self) {
1322 self.ch = self.rdr.next();
1324 if self.ch_is('\n') {
1332 fn next_char(&mut self) -> Option<char> {
1336 fn ch_is(&self, c: char) -> bool {
1340 fn error<T>(&self, reason: ErrorCode) -> Result<T, ParserError> {
1341 Err(SyntaxError(reason, self.line, self.col))
1344 fn parse_whitespace(&mut self) {
1345 while self.ch_is(' ') ||
1348 self.ch_is('\r') { self.bump(); }
1351 fn parse_number(&mut self) -> JsonEvent {
1352 let mut neg = false;
1354 if self.ch_is('-') {
1359 let res = match self.parse_u64() {
1361 Err(e) => { return Error(e); }
1364 if self.ch_is('.') || self.ch_is('e') || self.ch_is('E') {
1365 let mut res = res as f64;
1367 if self.ch_is('.') {
1368 res = match self.parse_decimal(res) {
1370 Err(e) => { return Error(e); }
1374 if self.ch_is('e') || self.ch_is('E') {
1375 res = match self.parse_exponent(res) {
1377 Err(e) => { return Error(e); }
1388 let res = -(res as i64);
1390 // Make sure we didn't underflow.
1392 Error(SyntaxError(InvalidNumber, self.line, self.col))
1402 fn parse_u64(&mut self) -> Result<u64, ParserError> {
1404 let last_accum = 0; // necessary to detect overflow.
1406 match self.ch_or_null() {
1410 // A leading '0' must be the only digit before the decimal point.
1411 match self.ch_or_null() {
1412 '0' ... '9' => return self.error(InvalidNumber),
1418 match self.ch_or_null() {
1419 c @ '0' ... '9' => {
1421 accum += (c as u64) - ('0' as u64);
1423 // Detect overflow by comparing to the last value.
1424 if accum <= last_accum { return self.error(InvalidNumber); }
1432 _ => return self.error(InvalidNumber),
1438 fn parse_decimal(&mut self, mut res: f64) -> Result<f64, ParserError> {
1441 // Make sure a digit follows the decimal place.
1442 match self.ch_or_null() {
1444 _ => return self.error(InvalidNumber)
1449 match self.ch_or_null() {
1450 c @ '0' ... '9' => {
1452 res += (((c as int) - ('0' as int)) as f64) * dec;
1462 fn parse_exponent(&mut self, mut res: f64) -> Result<f64, ParserError> {
1466 let mut neg_exp = false;
1468 if self.ch_is('+') {
1470 } else if self.ch_is('-') {
1475 // Make sure a digit follows the exponent place.
1476 match self.ch_or_null() {
1478 _ => return self.error(InvalidNumber)
1481 match self.ch_or_null() {
1482 c @ '0' ... '9' => {
1484 exp += (c as uint) - ('0' as uint);
1492 let exp = 10_f64.powi(exp as i32);
1502 fn decode_hex_escape(&mut self) -> Result<u16, ParserError> {
1505 while i < 4 && !self.eof() {
1507 n = match self.ch_or_null() {
1508 c @ '0' ... '9' => n * 16 + ((c as u16) - ('0' as u16)),
1509 'a' | 'A' => n * 16 + 10,
1510 'b' | 'B' => n * 16 + 11,
1511 'c' | 'C' => n * 16 + 12,
1512 'd' | 'D' => n * 16 + 13,
1513 'e' | 'E' => n * 16 + 14,
1514 'f' | 'F' => n * 16 + 15,
1515 _ => return self.error(InvalidEscape)
1521 // Error out if we didn't parse 4 digits.
1523 return self.error(InvalidEscape);
1529 fn parse_str(&mut self) -> Result<string::String, ParserError> {
1530 let mut escape = false;
1531 let mut res = string::String::new();
1536 return self.error(EOFWhileParsingString);
1540 match self.ch_or_null() {
1541 '"' => res.push('"'),
1542 '\\' => res.push('\\'),
1543 '/' => res.push('/'),
1544 'b' => res.push('\x08'),
1545 'f' => res.push('\x0c'),
1546 'n' => res.push('\n'),
1547 'r' => res.push('\r'),
1548 't' => res.push('\t'),
1549 'u' => match try!(self.decode_hex_escape()) {
1550 0xDC00 ... 0xDFFF => {
1551 return self.error(LoneLeadingSurrogateInHexEscape)
1554 // Non-BMP characters are encoded as a sequence of
1555 // two hex escapes, representing UTF-16 surrogates.
1556 n1 @ 0xD800 ... 0xDBFF => {
1557 match (self.next_char(), self.next_char()) {
1558 (Some('\\'), Some('u')) => (),
1559 _ => return self.error(UnexpectedEndOfHexEscape),
1562 let buf = [n1, try!(self.decode_hex_escape())];
1563 match str::utf16_items(buf.as_slice()).next() {
1564 Some(ScalarValue(c)) => res.push(c),
1565 _ => return self.error(LoneLeadingSurrogateInHexEscape),
1569 n => match char::from_u32(n as u32) {
1570 Some(c) => res.push(c),
1571 None => return self.error(InvalidUnicodeCodePoint),
1574 _ => return self.error(InvalidEscape),
1577 } else if self.ch_is('\\') {
1585 Some(c) => res.push(c),
1586 None => unreachable!()
1592 // Invoked at each iteration, consumes the stream until it has enough
1593 // information to return a JsonEvent.
1594 // Manages an internal state so that parsing can be interrupted and resumed.
1595 // Also keeps track of the position in the logical structure of the json
1596 // stream int the form of a stack that can be queried by the user using the
1598 fn parse(&mut self) -> JsonEvent {
1600 // The only paths where the loop can spin a new iteration
1601 // are in the cases ParseArrayComma and ParseObjectComma if ','
1602 // is parsed. In these cases the state is set to (respectively)
1603 // ParseArray(false) and ParseObject(false), which always return,
1604 // so there is no risk of getting stuck in an infinite loop.
1605 // All other paths return before the end of the loop's iteration.
1606 self.parse_whitespace();
1610 return self.parse_start();
1612 ParseArray(first) => {
1613 return self.parse_array(first);
1615 ParseArrayComma => {
1616 match self.parse_array_comma_or_end() {
1617 Some(evt) => { return evt; }
1621 ParseObject(first) => {
1622 return self.parse_object(first);
1624 ParseObjectComma => {
1626 if self.ch_is(',') {
1627 self.state = ParseObject(false);
1630 return self.parse_object_end();
1634 return self.error_event(InvalidSyntax);
1640 fn parse_start(&mut self) -> JsonEvent {
1641 let val = self.parse_value();
1642 self.state = match val {
1643 Error(_) => ParseFinished,
1644 ArrayStart => ParseArray(true),
1645 ObjectStart => ParseObject(true),
1646 _ => ParseBeforeFinish,
1651 fn parse_array(&mut self, first: bool) -> JsonEvent {
1652 if self.ch_is(']') {
1654 self.error_event(InvalidSyntax)
1656 self.state = if self.stack.is_empty() {
1658 } else if self.stack.last_is_index() {
1668 self.stack.push_index(0);
1670 let val = self.parse_value();
1671 self.state = match val {
1672 Error(_) => ParseFinished,
1673 ArrayStart => ParseArray(true),
1674 ObjectStart => ParseObject(true),
1675 _ => ParseArrayComma,
1681 fn parse_array_comma_or_end(&mut self) -> Option<JsonEvent> {
1682 if self.ch_is(',') {
1683 self.stack.bump_index();
1684 self.state = ParseArray(false);
1687 } else if self.ch_is(']') {
1689 self.state = if self.stack.is_empty() {
1691 } else if self.stack.last_is_index() {
1698 } else if self.eof() {
1699 Some(self.error_event(EOFWhileParsingArray))
1701 Some(self.error_event(InvalidSyntax))
1705 fn parse_object(&mut self, first: bool) -> JsonEvent {
1706 if self.ch_is('}') {
1708 if self.stack.is_empty() {
1709 return self.error_event(TrailingComma);
1714 self.state = if self.stack.is_empty() {
1716 } else if self.stack.last_is_index() {
1725 return self.error_event(EOFWhileParsingObject);
1727 if !self.ch_is('"') {
1728 return self.error_event(KeyMustBeAString);
1730 let s = match self.parse_str() {
1733 self.state = ParseFinished;
1737 self.parse_whitespace();
1739 return self.error_event(EOFWhileParsingObject);
1740 } else if self.ch_or_null() != ':' {
1741 return self.error_event(ExpectedColon);
1743 self.stack.push_key(s);
1745 self.parse_whitespace();
1747 let val = self.parse_value();
1749 self.state = match val {
1750 Error(_) => ParseFinished,
1751 ArrayStart => ParseArray(true),
1752 ObjectStart => ParseObject(true),
1753 _ => ParseObjectComma,
1758 fn parse_object_end(&mut self) -> JsonEvent {
1759 if self.ch_is('}') {
1760 self.state = if self.stack.is_empty() {
1762 } else if self.stack.last_is_index() {
1769 } else if self.eof() {
1770 self.error_event(EOFWhileParsingObject)
1772 self.error_event(InvalidSyntax)
1776 fn parse_value(&mut self) -> JsonEvent {
1777 if self.eof() { return self.error_event(EOFWhileParsingValue); }
1778 match self.ch_or_null() {
1779 'n' => { self.parse_ident("ull", NullValue) }
1780 't' => { self.parse_ident("rue", BooleanValue(true)) }
1781 'f' => { self.parse_ident("alse", BooleanValue(false)) }
1782 '0' ... '9' | '-' => self.parse_number(),
1783 '"' => match self.parse_str() {
1784 Ok(s) => StringValue(s),
1795 _ => { self.error_event(InvalidSyntax) }
1799 fn parse_ident(&mut self, ident: &str, value: JsonEvent) -> JsonEvent {
1800 if ident.chars().all(|c| Some(c) == self.next_char()) {
1804 Error(SyntaxError(InvalidSyntax, self.line, self.col))
1808 fn error_event(&mut self, reason: ErrorCode) -> JsonEvent {
1809 self.state = ParseFinished;
1810 Error(SyntaxError(reason, self.line, self.col))
1814 /// A Builder consumes a json::Parser to create a generic Json structure.
1815 pub struct Builder<T> {
1817 token: Option<JsonEvent>,
1820 impl<T: Iterator<char>> Builder<T> {
1821 /// Create a JSON Builder.
1822 pub fn new(src: T) -> Builder<T> {
1823 Builder { parser: Parser::new(src), token: None, }
1826 // Decode a Json value from a Parser.
1827 pub fn build(&mut self) -> Result<Json, BuilderError> {
1829 let result = self.build_value();
1833 Some(Error(e)) => { return Err(e); }
1834 ref tok => { panic!("unexpected token {}", tok.clone()); }
1839 fn bump(&mut self) {
1840 self.token = self.parser.next();
1843 fn build_value(&mut self) -> Result<Json, BuilderError> {
1845 Some(NullValue) => Ok(Null),
1846 Some(I64Value(n)) => Ok(I64(n)),
1847 Some(U64Value(n)) => Ok(U64(n)),
1848 Some(F64Value(n)) => Ok(F64(n)),
1849 Some(BooleanValue(b)) => Ok(Boolean(b)),
1850 Some(StringValue(ref mut s)) => {
1851 let mut temp = string::String::new();
1855 Some(Error(e)) => Err(e),
1856 Some(ArrayStart) => self.build_array(),
1857 Some(ObjectStart) => self.build_object(),
1858 Some(ObjectEnd) => self.parser.error(InvalidSyntax),
1859 Some(ArrayEnd) => self.parser.error(InvalidSyntax),
1860 None => self.parser.error(EOFWhileParsingValue),
1864 fn build_array(&mut self) -> Result<Json, BuilderError> {
1866 let mut values = Vec::new();
1869 if self.token == Some(ArrayEnd) {
1870 return Ok(Array(values.into_iter().collect()));
1872 match self.build_value() {
1873 Ok(v) => values.push(v),
1874 Err(e) => { return Err(e) }
1880 fn build_object(&mut self) -> Result<Json, BuilderError> {
1883 let mut values = TreeMap::new();
1887 Some(ObjectEnd) => { return Ok(Object(values)); }
1888 Some(Error(e)) => { return Err(e); }
1892 let key = match self.parser.stack().top() {
1893 Some(Key(k)) => { k.to_string() }
1894 _ => { panic!("invalid state"); }
1896 match self.build_value() {
1897 Ok(value) => { values.insert(key, value); }
1898 Err(e) => { return Err(e); }
1902 return self.parser.error(EOFWhileParsingObject);
1906 /// Decodes a json value from an `&mut io::Reader`
1907 pub fn from_reader(rdr: &mut io::Reader) -> Result<Json, BuilderError> {
1908 let contents = match rdr.read_to_end() {
1910 Err(e) => return Err(io_error_to_error(e))
1912 let s = match str::from_utf8(contents.as_slice()) {
1914 _ => return Err(SyntaxError(NotUtf8, 0, 0))
1916 let mut builder = Builder::new(s.chars());
1920 /// Decodes a json value from a string
1921 pub fn from_str(s: &str) -> Result<Json, BuilderError> {
1922 let mut builder = Builder::new(s.chars());
1926 /// A structure to decode JSON to values in rust.
1927 pub struct Decoder {
1932 /// Creates a new decoder instance for decoding the specified JSON value.
1933 pub fn new(json: Json) -> Decoder {
1934 Decoder { stack: vec![json] }
1939 fn pop(&mut self) -> Json {
1940 self.stack.pop().unwrap()
1944 macro_rules! expect(
1945 ($e:expr, Null) => ({
1948 other => Err(ExpectedError("Null".to_string(),
1949 format!("{}", other)))
1952 ($e:expr, $t:ident) => ({
1956 Err(ExpectedError(stringify!($t).to_string(),
1957 format!("{}", other)))
1963 macro_rules! read_primitive {
1964 ($name:ident, $ty:ty) => {
1965 fn $name(&mut self) -> DecodeResult<$ty> {
1968 match num::cast(f) {
1970 None => Err(ExpectedError("Number".to_string(), format!("{}", f))),
1974 match num::cast(f) {
1976 None => Err(ExpectedError("Number".to_string(), format!("{}", f))),
1980 match num::cast(f) {
1982 None => Err(ExpectedError("Number".to_string(), format!("{}", f))),
1986 // re: #12967.. a type w/ numeric keys (ie HashMap<uint, V> etc)
1987 // is going to have a string here, as per JSON spec.
1988 match std::str::from_str(s.as_slice()) {
1990 None => Err(ExpectedError("Number".to_string(), s)),
1993 value => Err(ExpectedError("Number".to_string(), format!("{}", value)))
1999 impl ::Decoder<DecoderError> for Decoder {
2000 fn read_nil(&mut self) -> DecodeResult<()> {
2002 expect!(self.pop(), Null)
2005 read_primitive!(read_uint, uint)
2006 read_primitive!(read_u8, u8)
2007 read_primitive!(read_u16, u16)
2008 read_primitive!(read_u32, u32)
2009 read_primitive!(read_u64, u64)
2010 read_primitive!(read_int, int)
2011 read_primitive!(read_i8, i8)
2012 read_primitive!(read_i16, i16)
2013 read_primitive!(read_i32, i32)
2014 read_primitive!(read_i64, i64)
2016 fn read_f32(&mut self) -> DecodeResult<f32> { self.read_f64().map(|x| x as f32) }
2018 fn read_f64(&mut self) -> DecodeResult<f64> {
2021 I64(f) => Ok(f as f64),
2022 U64(f) => Ok(f as f64),
2025 // re: #12967.. a type w/ numeric keys (ie HashMap<uint, V> etc)
2026 // is going to have a string here, as per JSON spec.
2027 match std::str::from_str(s.as_slice()) {
2029 None => Err(ExpectedError("Number".to_string(), s)),
2032 Null => Ok(f64::NAN),
2033 value => Err(ExpectedError("Number".to_string(), format!("{}", value)))
2037 fn read_bool(&mut self) -> DecodeResult<bool> {
2038 debug!("read_bool");
2039 expect!(self.pop(), Boolean)
2042 fn read_char(&mut self) -> DecodeResult<char> {
2043 let s = try!(self.read_str());
2045 let mut it = s.as_slice().chars();
2046 match (it.next(), it.next()) {
2047 // exactly one character
2048 (Some(c), None) => return Ok(c),
2052 Err(ExpectedError("single character string".to_string(), format!("{}", s)))
2055 fn read_str(&mut self) -> DecodeResult<string::String> {
2057 expect!(self.pop(), String)
2060 fn read_enum<T>(&mut self,
2062 f: |&mut Decoder| -> DecodeResult<T>) -> DecodeResult<T> {
2063 debug!("read_enum({})", name);
2067 fn read_enum_variant<T>(&mut self,
2069 f: |&mut Decoder, uint| -> DecodeResult<T>)
2070 -> DecodeResult<T> {
2071 debug!("read_enum_variant(names={})", names);
2072 let name = match self.pop() {
2075 let n = match o.remove(&"variant".to_string()) {
2076 Some(String(s)) => s,
2078 return Err(ExpectedError("String".to_string(), format!("{}", val)))
2081 return Err(MissingFieldError("variant".to_string()))
2084 match o.remove(&"fields".to_string()) {
2086 for field in l.into_iter().rev() {
2087 self.stack.push(field);
2091 return Err(ExpectedError("Array".to_string(), format!("{}", val)))
2094 return Err(MissingFieldError("fields".to_string()))
2100 return Err(ExpectedError("String or Object".to_string(), format!("{}", json)))
2103 let idx = match names.iter()
2104 .position(|n| str::eq_slice(*n, name.as_slice())) {
2106 None => return Err(UnknownVariantError(name))
2111 fn read_enum_variant_arg<T>(&mut self, idx: uint, f: |&mut Decoder| -> DecodeResult<T>)
2112 -> DecodeResult<T> {
2113 debug!("read_enum_variant_arg(idx={})", idx);
2117 fn read_enum_struct_variant<T>(&mut self,
2119 f: |&mut Decoder, uint| -> DecodeResult<T>)
2120 -> DecodeResult<T> {
2121 debug!("read_enum_struct_variant(names={})", names);
2122 self.read_enum_variant(names, f)
2126 fn read_enum_struct_variant_field<T>(&mut self,
2129 f: |&mut Decoder| -> DecodeResult<T>)
2130 -> DecodeResult<T> {
2131 debug!("read_enum_struct_variant_field(name={}, idx={})", name, idx);
2132 self.read_enum_variant_arg(idx, f)
2135 fn read_struct<T>(&mut self,
2138 f: |&mut Decoder| -> DecodeResult<T>)
2139 -> DecodeResult<T> {
2140 debug!("read_struct(name={}, len={})", name, len);
2141 let value = try!(f(self));
2146 fn read_struct_field<T>(&mut self,
2149 f: |&mut Decoder| -> DecodeResult<T>)
2150 -> DecodeResult<T> {
2151 debug!("read_struct_field(name={}, idx={})", name, idx);
2152 let mut obj = try!(expect!(self.pop(), Object));
2154 let value = match obj.remove(&name.to_string()) {
2156 // Add a Null and try to parse it as an Option<_>
2157 // to get None as a default value.
2158 self.stack.push(Null);
2161 Err(_) => return Err(MissingFieldError(name.to_string())),
2165 self.stack.push(json);
2169 self.stack.push(Object(obj));
2173 fn read_tuple<T>(&mut self,
2175 f: |&mut Decoder| -> DecodeResult<T>)
2176 -> DecodeResult<T> {
2177 debug!("read_tuple()");
2178 self.read_seq(|d, len| {
2179 if len == tuple_len {
2182 Err(ExpectedError(format!("Tuple{}", tuple_len), format!("Tuple{}", len)))
2187 fn read_tuple_arg<T>(&mut self,
2189 f: |&mut Decoder| -> DecodeResult<T>) -> DecodeResult<T> {
2190 debug!("read_tuple_arg(idx={})", idx);
2191 self.read_seq_elt(idx, f)
2194 fn read_tuple_struct<T>(&mut self,
2197 f: |&mut Decoder| -> DecodeResult<T>)
2198 -> DecodeResult<T> {
2199 debug!("read_tuple_struct(name={})", name);
2200 self.read_tuple(len, f)
2203 fn read_tuple_struct_arg<T>(&mut self,
2205 f: |&mut Decoder| -> DecodeResult<T>)
2206 -> DecodeResult<T> {
2207 debug!("read_tuple_struct_arg(idx={})", idx);
2208 self.read_tuple_arg(idx, f)
2211 fn read_option<T>(&mut self, f: |&mut Decoder, bool| -> DecodeResult<T>) -> DecodeResult<T> {
2212 debug!("read_option()");
2214 Null => f(self, false),
2215 value => { self.stack.push(value); f(self, true) }
2219 fn read_seq<T>(&mut self, f: |&mut Decoder, uint| -> DecodeResult<T>) -> DecodeResult<T> {
2220 debug!("read_seq()");
2221 let array = try!(expect!(self.pop(), Array));
2222 let len = array.len();
2223 for v in array.into_iter().rev() {
2229 fn read_seq_elt<T>(&mut self,
2231 f: |&mut Decoder| -> DecodeResult<T>) -> DecodeResult<T> {
2232 debug!("read_seq_elt(idx={})", idx);
2236 fn read_map<T>(&mut self, f: |&mut Decoder, uint| -> DecodeResult<T>) -> DecodeResult<T> {
2237 debug!("read_map()");
2238 let obj = try!(expect!(self.pop(), Object));
2239 let len = obj.len();
2240 for (key, value) in obj.into_iter() {
2241 self.stack.push(value);
2242 self.stack.push(String(key));
2247 fn read_map_elt_key<T>(&mut self, idx: uint, f: |&mut Decoder| -> DecodeResult<T>)
2248 -> DecodeResult<T> {
2249 debug!("read_map_elt_key(idx={})", idx);
2253 fn read_map_elt_val<T>(&mut self, idx: uint, f: |&mut Decoder| -> DecodeResult<T>)
2254 -> DecodeResult<T> {
2255 debug!("read_map_elt_val(idx={})", idx);
2259 fn error(&mut self, err: &str) -> DecoderError {
2260 ApplicationError(err.to_string())
2264 /// A trait for converting values to JSON
2265 pub trait ToJson for Sized? {
2266 /// Converts the value of `self` to an instance of JSON
2267 fn to_json(&self) -> Json;
2270 macro_rules! to_json_impl_i64(
2272 $(impl ToJson for $t {
2273 fn to_json(&self) -> Json { I64(*self as i64) }
2278 to_json_impl_i64!(int, i8, i16, i32, i64)
2280 macro_rules! to_json_impl_u64(
2282 $(impl ToJson for $t {
2283 fn to_json(&self) -> Json { U64(*self as u64) }
2288 to_json_impl_u64!(uint, u8, u16, u32, u64)
2290 impl ToJson for Json {
2291 fn to_json(&self) -> Json { self.clone() }
2294 impl ToJson for f32 {
2295 fn to_json(&self) -> Json { (*self as f64).to_json() }
2298 impl ToJson for f64 {
2299 fn to_json(&self) -> Json {
2300 match self.classify() {
2301 FPNaN | FPInfinite => Null,
2307 impl ToJson for () {
2308 fn to_json(&self) -> Json { Null }
2311 impl ToJson for bool {
2312 fn to_json(&self) -> Json { Boolean(*self) }
2315 impl ToJson for str {
2316 fn to_json(&self) -> Json { String(self.into_string()) }
2319 impl ToJson for string::String {
2320 fn to_json(&self) -> Json { String((*self).clone()) }
2323 macro_rules! tuple_impl {
2324 // use variables to indicate the arity of the tuple
2325 ($($tyvar:ident),* ) => {
2326 // the trailing commas are for the 1 tuple
2328 $( $tyvar : ToJson ),*
2329 > ToJson for ( $( $tyvar ),* , ) {
2332 #[allow(non_snake_case)]
2333 fn to_json(&self) -> Json {
2335 ($(ref $tyvar),*,) => Array(vec![$($tyvar.to_json()),*])
2344 tuple_impl!{A, B, C}
2345 tuple_impl!{A, B, C, D}
2346 tuple_impl!{A, B, C, D, E}
2347 tuple_impl!{A, B, C, D, E, F}
2348 tuple_impl!{A, B, C, D, E, F, G}
2349 tuple_impl!{A, B, C, D, E, F, G, H}
2350 tuple_impl!{A, B, C, D, E, F, G, H, I}
2351 tuple_impl!{A, B, C, D, E, F, G, H, I, J}
2352 tuple_impl!{A, B, C, D, E, F, G, H, I, J, K}
2353 tuple_impl!{A, B, C, D, E, F, G, H, I, J, K, L}
2355 impl<A: ToJson> ToJson for [A] {
2356 fn to_json(&self) -> Json { Array(self.iter().map(|elt| elt.to_json()).collect()) }
2359 impl<A: ToJson> ToJson for Vec<A> {
2360 fn to_json(&self) -> Json { Array(self.iter().map(|elt| elt.to_json()).collect()) }
2363 impl<A: ToJson> ToJson for TreeMap<string::String, A> {
2364 fn to_json(&self) -> Json {
2365 let mut d = TreeMap::new();
2366 for (key, value) in self.iter() {
2367 d.insert((*key).clone(), value.to_json());
2373 impl<A: ToJson> ToJson for HashMap<string::String, A> {
2374 fn to_json(&self) -> Json {
2375 let mut d = TreeMap::new();
2376 for (key, value) in self.iter() {
2377 d.insert((*key).clone(), value.to_json());
2383 impl<A:ToJson> ToJson for Option<A> {
2384 fn to_json(&self) -> Json {
2387 Some(ref value) => value.to_json()
2392 impl fmt::Show for Json {
2393 /// Encodes a json value into a string
2394 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2395 self.to_writer(f).map_err(|_| fmt::Error)
2399 impl FromStr for Json {
2400 fn from_str(s: &str) -> Option<Json> {
2408 use self::Animal::*;
2409 use self::DecodeEnum::*;
2410 use self::test::Bencher;
2411 use {Encodable, Decodable};
2412 use super::{Array, Encoder, Decoder, Error, Boolean, I64, U64, F64, String, Null,
2413 PrettyEncoder, Object, Json, from_str, ParseError, ExpectedError,
2414 MissingFieldError, UnknownVariantError, DecodeResult, DecoderError,
2415 JsonEvent, Parser, StackElement,
2416 ObjectStart, ObjectEnd, ArrayStart, ArrayEnd, BooleanValue, U64Value,
2417 F64Value, StringValue, NullValue, SyntaxError, Key, Index, Stack,
2418 InvalidSyntax, InvalidNumber, EOFWhileParsingObject, EOFWhileParsingArray,
2419 EOFWhileParsingValue, EOFWhileParsingString, KeyMustBeAString, ExpectedColon,
2420 TrailingCharacters, TrailingComma};
2421 use std::{i64, u64, f32, f64, io};
2422 use std::collections::TreeMap;
2423 use std::num::Float;
2426 #[deriving(Decodable, Eq, PartialEq, Show)]
2432 fn test_decode_option_none() {
2434 let obj: OptionData = super::decode(s).unwrap();
2435 assert_eq!(obj, OptionData { opt: None });
2439 fn test_decode_option_some() {
2440 let s = "{ \"opt\": 10 }";
2441 let obj: OptionData = super::decode(s).unwrap();
2442 assert_eq!(obj, OptionData { opt: Some(10u) });
2446 fn test_decode_option_malformed() {
2447 check_err::<OptionData>("{ \"opt\": [] }",
2448 ExpectedError("Number".to_string(), "[]".to_string()));
2449 check_err::<OptionData>("{ \"opt\": false }",
2450 ExpectedError("Number".to_string(), "false".to_string()));
2453 #[deriving(PartialEq, Encodable, Decodable, Show)]
2456 Frog(string::String, int)
2459 #[deriving(PartialEq, Encodable, Decodable, Show)]
2463 c: Vec<string::String>,
2466 #[deriving(PartialEq, Encodable, Decodable, Show)]
2471 fn mk_object(items: &[(string::String, Json)]) -> Json {
2472 let mut d = TreeMap::new();
2474 for item in items.iter() {
2476 (ref key, ref value) => { d.insert((*key).clone(), (*value).clone()); },
2484 fn test_from_str_trait() {
2486 assert!(::std::str::from_str::<Json>(s).unwrap() == from_str(s).unwrap());
2490 fn test_write_null() {
2491 assert_eq!(Null.to_string().into_string(), "null".to_string());
2492 assert_eq!(Null.to_pretty_str().into_string(), "null".to_string());
2496 fn test_write_i64() {
2497 assert_eq!(U64(0).to_string().into_string(), "0".to_string());
2498 assert_eq!(U64(0).to_pretty_str().into_string(), "0".to_string());
2500 assert_eq!(U64(1234).to_string().into_string(), "1234".to_string());
2501 assert_eq!(U64(1234).to_pretty_str().into_string(), "1234".to_string());
2503 assert_eq!(I64(-5678).to_string().into_string(), "-5678".to_string());
2504 assert_eq!(I64(-5678).to_pretty_str().into_string(), "-5678".to_string());
2508 fn test_write_f64() {
2509 assert_eq!(F64(3.0).to_string().into_string(), "3".to_string());
2510 assert_eq!(F64(3.0).to_pretty_str().into_string(), "3".to_string());
2512 assert_eq!(F64(3.1).to_string().into_string(), "3.1".to_string());
2513 assert_eq!(F64(3.1).to_pretty_str().into_string(), "3.1".to_string());
2515 assert_eq!(F64(-1.5).to_string().into_string(), "-1.5".to_string());
2516 assert_eq!(F64(-1.5).to_pretty_str().into_string(), "-1.5".to_string());
2518 assert_eq!(F64(0.5).to_string().into_string(), "0.5".to_string());
2519 assert_eq!(F64(0.5).to_pretty_str().into_string(), "0.5".to_string());
2521 assert_eq!(F64(f64::NAN).to_string().into_string(), "null".to_string());
2522 assert_eq!(F64(f64::NAN).to_pretty_str().into_string(), "null".to_string());
2524 assert_eq!(F64(f64::INFINITY).to_string().into_string(), "null".to_string());
2525 assert_eq!(F64(f64::INFINITY).to_pretty_str().into_string(), "null".to_string());
2527 assert_eq!(F64(f64::NEG_INFINITY).to_string().into_string(), "null".to_string());
2528 assert_eq!(F64(f64::NEG_INFINITY).to_pretty_str().into_string(), "null".to_string());
2532 fn test_write_str() {
2533 assert_eq!(String("".to_string()).to_string().into_string(), "\"\"".to_string());
2534 assert_eq!(String("".to_string()).to_pretty_str().into_string(), "\"\"".to_string());
2536 assert_eq!(String("foo".to_string()).to_string().into_string(), "\"foo\"".to_string());
2537 assert_eq!(String("foo".to_string()).to_pretty_str().into_string(), "\"foo\"".to_string());
2541 fn test_write_bool() {
2542 assert_eq!(Boolean(true).to_string().into_string(), "true".to_string());
2543 assert_eq!(Boolean(true).to_pretty_str().into_string(), "true".to_string());
2545 assert_eq!(Boolean(false).to_string().into_string(), "false".to_string());
2546 assert_eq!(Boolean(false).to_pretty_str().into_string(), "false".to_string());
2550 fn test_write_array() {
2551 assert_eq!(Array(vec![]).to_string().into_string(), "[]".to_string());
2552 assert_eq!(Array(vec![]).to_pretty_str().into_string(), "[]".to_string());
2554 assert_eq!(Array(vec![Boolean(true)]).to_string().into_string(), "[true]".to_string());
2556 Array(vec![Boolean(true)]).to_pretty_str().into_string(),
2563 let long_test_array = Array(vec![
2566 Array(vec![String("foo\nbar".to_string()), F64(3.5)])]);
2568 assert_eq!(long_test_array.to_string().into_string(),
2569 "[false,null,[\"foo\\nbar\",3.5]]".to_string());
2571 long_test_array.to_pretty_str().into_string(),
2585 fn test_write_object() {
2586 assert_eq!(mk_object(&[]).to_string().into_string(), "{}".to_string());
2587 assert_eq!(mk_object(&[]).to_pretty_str().into_string(), "{}".to_string());
2591 ("a".to_string(), Boolean(true))
2592 ]).to_string().into_string(),
2593 "{\"a\":true}".to_string()
2596 mk_object(&[("a".to_string(), Boolean(true))]).to_pretty_str(),
2603 let complex_obj = mk_object(&[
2604 ("b".to_string(), Array(vec![
2605 mk_object(&[("c".to_string(), String("\x0c\r".to_string()))]),
2606 mk_object(&[("d".to_string(), String("".to_string()))])
2611 complex_obj.to_string().into_string(),
2614 {\"c\":\"\\f\\r\"},\
2620 complex_obj.to_pretty_str().into_string(),
2625 \"c\": \"\\f\\r\"\n \
2634 let a = mk_object(&[
2635 ("a".to_string(), Boolean(true)),
2636 ("b".to_string(), Array(vec![
2637 mk_object(&[("c".to_string(), String("\x0c\r".to_string()))]),
2638 mk_object(&[("d".to_string(), String("".to_string()))])
2642 // We can't compare the strings directly because the object fields be
2643 // printed in a different order.
2644 assert_eq!(a.clone(), from_str(a.to_string().as_slice()).unwrap());
2645 assert_eq!(a.clone(),
2646 from_str(a.to_pretty_str().as_slice()).unwrap());
2649 fn with_str_writer(f: |&mut io::Writer|) -> string::String {
2652 let mut m = Vec::new();
2653 f(&mut m as &mut io::Writer);
2654 string::String::from_utf8(m).unwrap()
2658 fn test_write_enum() {
2661 with_str_writer(|writer| {
2662 let mut encoder = Encoder::new(writer);
2663 animal.encode(&mut encoder).unwrap();
2665 "\"Dog\"".to_string()
2668 with_str_writer(|writer| {
2669 let mut encoder = PrettyEncoder::new(writer);
2670 animal.encode(&mut encoder).unwrap();
2672 "\"Dog\"".to_string()
2675 let animal = Frog("Henry".to_string(), 349);
2677 with_str_writer(|writer| {
2678 let mut encoder = Encoder::new(writer);
2679 animal.encode(&mut encoder).unwrap();
2681 "{\"variant\":\"Frog\",\"fields\":[\"Henry\",349]}".to_string()
2684 with_str_writer(|writer| {
2685 let mut encoder = PrettyEncoder::new(writer);
2686 animal.encode(&mut encoder).unwrap();
2689 \"variant\": \"Frog\",\n \
2699 fn test_write_some() {
2700 let value = Some("jodhpurs".to_string());
2701 let s = with_str_writer(|writer| {
2702 let mut encoder = Encoder::new(writer);
2703 value.encode(&mut encoder).unwrap();
2705 assert_eq!(s, "\"jodhpurs\"".to_string());
2707 let value = Some("jodhpurs".to_string());
2708 let s = with_str_writer(|writer| {
2709 let mut encoder = PrettyEncoder::new(writer);
2710 value.encode(&mut encoder).unwrap();
2712 assert_eq!(s, "\"jodhpurs\"".to_string());
2716 fn test_write_none() {
2717 let value: Option<string::String> = None;
2718 let s = with_str_writer(|writer| {
2719 let mut encoder = Encoder::new(writer);
2720 value.encode(&mut encoder).unwrap();
2722 assert_eq!(s, "null".to_string());
2724 let s = with_str_writer(|writer| {
2725 let mut encoder = Encoder::new(writer);
2726 value.encode(&mut encoder).unwrap();
2728 assert_eq!(s, "null".to_string());
2732 fn test_trailing_characters() {
2733 assert_eq!(from_str("nulla"), Err(SyntaxError(TrailingCharacters, 1, 5)));
2734 assert_eq!(from_str("truea"), Err(SyntaxError(TrailingCharacters, 1, 5)));
2735 assert_eq!(from_str("falsea"), Err(SyntaxError(TrailingCharacters, 1, 6)));
2736 assert_eq!(from_str("1a"), Err(SyntaxError(TrailingCharacters, 1, 2)));
2737 assert_eq!(from_str("[]a"), Err(SyntaxError(TrailingCharacters, 1, 3)));
2738 assert_eq!(from_str("{}a"), Err(SyntaxError(TrailingCharacters, 1, 3)));
2742 fn test_read_identifiers() {
2743 assert_eq!(from_str("n"), Err(SyntaxError(InvalidSyntax, 1, 2)));
2744 assert_eq!(from_str("nul"), Err(SyntaxError(InvalidSyntax, 1, 4)));
2745 assert_eq!(from_str("t"), Err(SyntaxError(InvalidSyntax, 1, 2)));
2746 assert_eq!(from_str("truz"), Err(SyntaxError(InvalidSyntax, 1, 4)));
2747 assert_eq!(from_str("f"), Err(SyntaxError(InvalidSyntax, 1, 2)));
2748 assert_eq!(from_str("faz"), Err(SyntaxError(InvalidSyntax, 1, 3)));
2750 assert_eq!(from_str("null"), Ok(Null));
2751 assert_eq!(from_str("true"), Ok(Boolean(true)));
2752 assert_eq!(from_str("false"), Ok(Boolean(false)));
2753 assert_eq!(from_str(" null "), Ok(Null));
2754 assert_eq!(from_str(" true "), Ok(Boolean(true)));
2755 assert_eq!(from_str(" false "), Ok(Boolean(false)));
2759 fn test_decode_identifiers() {
2760 let v: () = super::decode("null").unwrap();
2763 let v: bool = super::decode("true").unwrap();
2764 assert_eq!(v, true);
2766 let v: bool = super::decode("false").unwrap();
2767 assert_eq!(v, false);
2771 fn test_read_number() {
2772 assert_eq!(from_str("+"), Err(SyntaxError(InvalidSyntax, 1, 1)));
2773 assert_eq!(from_str("."), Err(SyntaxError(InvalidSyntax, 1, 1)));
2774 assert_eq!(from_str("NaN"), Err(SyntaxError(InvalidSyntax, 1, 1)));
2775 assert_eq!(from_str("-"), Err(SyntaxError(InvalidNumber, 1, 2)));
2776 assert_eq!(from_str("00"), Err(SyntaxError(InvalidNumber, 1, 2)));
2777 assert_eq!(from_str("1."), Err(SyntaxError(InvalidNumber, 1, 3)));
2778 assert_eq!(from_str("1e"), Err(SyntaxError(InvalidNumber, 1, 3)));
2779 assert_eq!(from_str("1e+"), Err(SyntaxError(InvalidNumber, 1, 4)));
2781 assert_eq!(from_str("18446744073709551616"), Err(SyntaxError(InvalidNumber, 1, 20)));
2782 assert_eq!(from_str("-9223372036854775809"), Err(SyntaxError(InvalidNumber, 1, 21)));
2784 assert_eq!(from_str("3"), Ok(U64(3)));
2785 assert_eq!(from_str("3.1"), Ok(F64(3.1)));
2786 assert_eq!(from_str("-1.2"), Ok(F64(-1.2)));
2787 assert_eq!(from_str("0.4"), Ok(F64(0.4)));
2788 assert_eq!(from_str("0.4e5"), Ok(F64(0.4e5)));
2789 assert_eq!(from_str("0.4e+15"), Ok(F64(0.4e15)));
2790 assert_eq!(from_str("0.4e-01"), Ok(F64(0.4e-01)));
2791 assert_eq!(from_str(" 3 "), Ok(U64(3)));
2793 assert_eq!(from_str("-9223372036854775808"), Ok(I64(i64::MIN)));
2794 assert_eq!(from_str("9223372036854775807"), Ok(U64(i64::MAX as u64)));
2795 assert_eq!(from_str("18446744073709551615"), Ok(U64(u64::MAX)));
2799 fn test_decode_numbers() {
2800 let v: f64 = super::decode("3").unwrap();
2803 let v: f64 = super::decode("3.1").unwrap();
2806 let v: f64 = super::decode("-1.2").unwrap();
2807 assert_eq!(v, -1.2);
2809 let v: f64 = super::decode("0.4").unwrap();
2812 let v: f64 = super::decode("0.4e5").unwrap();
2813 assert_eq!(v, 0.4e5);
2815 let v: f64 = super::decode("0.4e15").unwrap();
2816 assert_eq!(v, 0.4e15);
2818 let v: f64 = super::decode("0.4e-01").unwrap();
2819 assert_eq!(v, 0.4e-01);
2821 let v: u64 = super::decode("0").unwrap();
2824 let v: u64 = super::decode("18446744073709551615").unwrap();
2825 assert_eq!(v, u64::MAX);
2827 let v: i64 = super::decode("-9223372036854775808").unwrap();
2828 assert_eq!(v, i64::MIN);
2830 let v: i64 = super::decode("9223372036854775807").unwrap();
2831 assert_eq!(v, i64::MAX);
2835 fn test_read_str() {
2836 assert_eq!(from_str("\""), Err(SyntaxError(EOFWhileParsingString, 1, 2)));
2837 assert_eq!(from_str("\"lol"), Err(SyntaxError(EOFWhileParsingString, 1, 5)));
2839 assert_eq!(from_str("\"\""), Ok(String("".to_string())));
2840 assert_eq!(from_str("\"foo\""), Ok(String("foo".to_string())));
2841 assert_eq!(from_str("\"\\\"\""), Ok(String("\"".to_string())));
2842 assert_eq!(from_str("\"\\b\""), Ok(String("\x08".to_string())));
2843 assert_eq!(from_str("\"\\n\""), Ok(String("\n".to_string())));
2844 assert_eq!(from_str("\"\\r\""), Ok(String("\r".to_string())));
2845 assert_eq!(from_str("\"\\t\""), Ok(String("\t".to_string())));
2846 assert_eq!(from_str(" \"foo\" "), Ok(String("foo".to_string())));
2847 assert_eq!(from_str("\"\\u12ab\""), Ok(String("\u12ab".to_string())));
2848 assert_eq!(from_str("\"\\uAB12\""), Ok(String("\uAB12".to_string())));
2852 fn test_decode_str() {
2853 let s = [("\"\"", ""),
2856 ("\"\\b\"", "\x08"),
2860 ("\"\\u12ab\"", "\u12ab"),
2861 ("\"\\uAB12\"", "\uAB12")];
2863 for &(i, o) in s.iter() {
2864 let v: string::String = super::decode(i).unwrap();
2865 assert_eq!(v.as_slice(), o);
2870 fn test_read_array() {
2871 assert_eq!(from_str("["), Err(SyntaxError(EOFWhileParsingValue, 1, 2)));
2872 assert_eq!(from_str("[1"), Err(SyntaxError(EOFWhileParsingArray, 1, 3)));
2873 assert_eq!(from_str("[1,"), Err(SyntaxError(EOFWhileParsingValue, 1, 4)));
2874 assert_eq!(from_str("[1,]"), Err(SyntaxError(InvalidSyntax, 1, 4)));
2875 assert_eq!(from_str("[6 7]"), Err(SyntaxError(InvalidSyntax, 1, 4)));
2877 assert_eq!(from_str("[]"), Ok(Array(vec![])));
2878 assert_eq!(from_str("[ ]"), Ok(Array(vec![])));
2879 assert_eq!(from_str("[true]"), Ok(Array(vec![Boolean(true)])));
2880 assert_eq!(from_str("[ false ]"), Ok(Array(vec![Boolean(false)])));
2881 assert_eq!(from_str("[null]"), Ok(Array(vec![Null])));
2882 assert_eq!(from_str("[3, 1]"),
2883 Ok(Array(vec![U64(3), U64(1)])));
2884 assert_eq!(from_str("\n[3, 2]\n"),
2885 Ok(Array(vec![U64(3), U64(2)])));
2886 assert_eq!(from_str("[2, [4, 1]]"),
2887 Ok(Array(vec![U64(2), Array(vec![U64(4), U64(1)])])));
2891 fn test_decode_array() {
2892 let v: Vec<()> = super::decode("[]").unwrap();
2893 assert_eq!(v, vec![]);
2895 let v: Vec<()> = super::decode("[null]").unwrap();
2896 assert_eq!(v, vec![()]);
2898 let v: Vec<bool> = super::decode("[true]").unwrap();
2899 assert_eq!(v, vec![true]);
2901 let v: Vec<int> = super::decode("[3, 1]").unwrap();
2902 assert_eq!(v, vec![3, 1]);
2904 let v: Vec<Vec<uint>> = super::decode("[[3], [1, 2]]").unwrap();
2905 assert_eq!(v, vec![vec![3], vec![1, 2]]);
2909 fn test_decode_tuple() {
2910 let t: (uint, uint, uint) = super::decode("[1, 2, 3]").unwrap();
2911 assert_eq!(t, (1u, 2, 3))
2913 let t: (uint, string::String) = super::decode("[1, \"two\"]").unwrap();
2914 assert_eq!(t, (1u, "two".to_string()));
2918 fn test_decode_tuple_malformed_types() {
2919 assert!(super::decode::<(uint, string::String)>("[1, 2]").is_err());
2923 fn test_decode_tuple_malformed_length() {
2924 assert!(super::decode::<(uint, uint)>("[1, 2, 3]").is_err());
2928 fn test_read_object() {
2929 assert_eq!(from_str("{"), Err(SyntaxError(EOFWhileParsingObject, 1, 2)));
2930 assert_eq!(from_str("{ "), Err(SyntaxError(EOFWhileParsingObject, 1, 3)));
2931 assert_eq!(from_str("{1"), Err(SyntaxError(KeyMustBeAString, 1, 2)));
2932 assert_eq!(from_str("{ \"a\""), Err(SyntaxError(EOFWhileParsingObject, 1, 6)));
2933 assert_eq!(from_str("{\"a\""), Err(SyntaxError(EOFWhileParsingObject, 1, 5)));
2934 assert_eq!(from_str("{\"a\" "), Err(SyntaxError(EOFWhileParsingObject, 1, 6)));
2936 assert_eq!(from_str("{\"a\" 1"), Err(SyntaxError(ExpectedColon, 1, 6)));
2937 assert_eq!(from_str("{\"a\":"), Err(SyntaxError(EOFWhileParsingValue, 1, 6)));
2938 assert_eq!(from_str("{\"a\":1"), Err(SyntaxError(EOFWhileParsingObject, 1, 7)));
2939 assert_eq!(from_str("{\"a\":1 1"), Err(SyntaxError(InvalidSyntax, 1, 8)));
2940 assert_eq!(from_str("{\"a\":1,"), Err(SyntaxError(EOFWhileParsingObject, 1, 8)));
2942 assert_eq!(from_str("{}").unwrap(), mk_object(&[]));
2943 assert_eq!(from_str("{\"a\": 3}").unwrap(),
2944 mk_object(&[("a".to_string(), U64(3))]));
2946 assert_eq!(from_str(
2947 "{ \"a\": null, \"b\" : true }").unwrap(),
2949 ("a".to_string(), Null),
2950 ("b".to_string(), Boolean(true))]));
2951 assert_eq!(from_str("\n{ \"a\": null, \"b\" : true }\n").unwrap(),
2953 ("a".to_string(), Null),
2954 ("b".to_string(), Boolean(true))]));
2955 assert_eq!(from_str(
2956 "{\"a\" : 1.0 ,\"b\": [ true ]}").unwrap(),
2958 ("a".to_string(), F64(1.0)),
2959 ("b".to_string(), Array(vec![Boolean(true)]))
2961 assert_eq!(from_str(
2967 { \"c\": {\"d\": null} } \
2971 ("a".to_string(), F64(1.0)),
2972 ("b".to_string(), Array(vec![
2974 String("foo\nbar".to_string()),
2976 ("c".to_string(), mk_object(&[("d".to_string(), Null)]))
2983 fn test_decode_struct() {
2986 { \"a\": null, \"b\": 2, \"c\": [\"abc\", \"xyz\"] }
2990 let v: Outer = super::decode(s).unwrap();
2995 Inner { a: (), b: 2, c: vec!["abc".to_string(), "xyz".to_string()] }
3001 #[deriving(Decodable)]
3002 struct FloatStruct {
3007 fn test_decode_struct_with_nan() {
3008 let s = "{\"f\":null,\"a\":[null,123]}";
3009 let obj: FloatStruct = super::decode(s).unwrap();
3010 assert!(obj.f.is_nan());
3011 assert!(obj.a[0].is_nan());
3012 assert_eq!(obj.a[1], 123f64);
3016 fn test_decode_option() {
3017 let value: Option<string::String> = super::decode("null").unwrap();
3018 assert_eq!(value, None);
3020 let value: Option<string::String> = super::decode("\"jodhpurs\"").unwrap();
3021 assert_eq!(value, Some("jodhpurs".to_string()));
3025 fn test_decode_enum() {
3026 let value: Animal = super::decode("\"Dog\"").unwrap();
3027 assert_eq!(value, Dog);
3029 let s = "{\"variant\":\"Frog\",\"fields\":[\"Henry\",349]}";
3030 let value: Animal = super::decode(s).unwrap();
3031 assert_eq!(value, Frog("Henry".to_string(), 349));
3035 fn test_decode_map() {
3036 let s = "{\"a\": \"Dog\", \"b\": {\"variant\":\"Frog\",\
3037 \"fields\":[\"Henry\", 349]}}";
3038 let mut map: TreeMap<string::String, Animal> = super::decode(s).unwrap();
3040 assert_eq!(map.remove(&"a".to_string()), Some(Dog));
3041 assert_eq!(map.remove(&"b".to_string()), Some(Frog("Henry".to_string(), 349)));
3045 fn test_multiline_errors() {
3046 assert_eq!(from_str("{\n \"foo\":\n \"bar\""),
3047 Err(SyntaxError(EOFWhileParsingObject, 3u, 8u)));
3050 #[deriving(Decodable)]
3052 struct DecodeStruct {
3056 w: Vec<DecodeStruct>
3058 #[deriving(Decodable)]
3063 fn check_err<T: Decodable<Decoder, DecoderError>>(to_parse: &'static str,
3064 expected: DecoderError) {
3065 let res: DecodeResult<T> = match from_str(to_parse) {
3066 Err(e) => Err(ParseError(e)),
3067 Ok(json) => Decodable::decode(&mut Decoder::new(json))
3070 Ok(_) => panic!("`{}` parsed & decoded ok, expecting error `{}`",
3071 to_parse, expected),
3072 Err(ParseError(e)) => panic!("`{}` is not valid json: {}",
3075 assert_eq!(e, expected);
3080 fn test_decode_errors_struct() {
3081 check_err::<DecodeStruct>("[]", ExpectedError("Object".to_string(), "[]".to_string()));
3082 check_err::<DecodeStruct>("{\"x\": true, \"y\": true, \"z\": \"\", \"w\": []}",
3083 ExpectedError("Number".to_string(), "true".to_string()));
3084 check_err::<DecodeStruct>("{\"x\": 1, \"y\": [], \"z\": \"\", \"w\": []}",
3085 ExpectedError("Boolean".to_string(), "[]".to_string()));
3086 check_err::<DecodeStruct>("{\"x\": 1, \"y\": true, \"z\": {}, \"w\": []}",
3087 ExpectedError("String".to_string(), "{}".to_string()));
3088 check_err::<DecodeStruct>("{\"x\": 1, \"y\": true, \"z\": \"\", \"w\": null}",
3089 ExpectedError("Array".to_string(), "null".to_string()));
3090 check_err::<DecodeStruct>("{\"x\": 1, \"y\": true, \"z\": \"\"}",
3091 MissingFieldError("w".to_string()));
3094 fn test_decode_errors_enum() {
3095 check_err::<DecodeEnum>("{}",
3096 MissingFieldError("variant".to_string()));
3097 check_err::<DecodeEnum>("{\"variant\": 1}",
3098 ExpectedError("String".to_string(), "1".to_string()));
3099 check_err::<DecodeEnum>("{\"variant\": \"A\"}",
3100 MissingFieldError("fields".to_string()));
3101 check_err::<DecodeEnum>("{\"variant\": \"A\", \"fields\": null}",
3102 ExpectedError("Array".to_string(), "null".to_string()));
3103 check_err::<DecodeEnum>("{\"variant\": \"C\", \"fields\": []}",
3104 UnknownVariantError("C".to_string()));
3109 let json_value = from_str("{\"dog\" : \"cat\"}").unwrap();
3110 let found_str = json_value.find("dog");
3111 assert!(found_str.unwrap().as_string().unwrap() == "cat");
3115 fn test_find_path(){
3116 let json_value = from_str("{\"dog\":{\"cat\": {\"mouse\" : \"cheese\"}}}").unwrap();
3117 let found_str = json_value.find_path(&["dog", "cat", "mouse"]);
3118 assert!(found_str.unwrap().as_string().unwrap() == "cheese");
3123 let json_value = from_str("{\"dog\":{\"cat\": {\"mouse\" : \"cheese\"}}}").unwrap();
3124 let found_str = json_value.search("mouse").and_then(|j| j.as_string());
3125 assert!(found_str.unwrap() == "cheese");
3130 let json_value = from_str("{\"animals\":[\"dog\",\"cat\",\"mouse\"]}").unwrap();
3131 let ref array = json_value["animals"];
3132 assert_eq!(array[0].as_string().unwrap(), "dog");
3133 assert_eq!(array[1].as_string().unwrap(), "cat");
3134 assert_eq!(array[2].as_string().unwrap(), "mouse");
3138 fn test_is_object(){
3139 let json_value = from_str("{}").unwrap();
3140 assert!(json_value.is_object());
3144 fn test_as_object(){
3145 let json_value = from_str("{}").unwrap();
3146 let json_object = json_value.as_object();
3147 assert!(json_object.is_some());
3152 let json_value = from_str("[1, 2, 3]").unwrap();
3153 assert!(json_value.is_array());
3158 let json_value = from_str("[1, 2, 3]").unwrap();
3159 let json_array = json_value.as_array();
3160 let expected_length = 3;
3161 assert!(json_array.is_some() && json_array.unwrap().len() == expected_length);
3165 fn test_is_string(){
3166 let json_value = from_str("\"dog\"").unwrap();
3167 assert!(json_value.is_string());
3171 fn test_as_string(){
3172 let json_value = from_str("\"dog\"").unwrap();
3173 let json_str = json_value.as_string();
3174 let expected_str = "dog";
3175 assert_eq!(json_str, Some(expected_str));
3179 fn test_is_number(){
3180 let json_value = from_str("12").unwrap();
3181 assert!(json_value.is_number());
3186 let json_value = from_str("-12").unwrap();
3187 assert!(json_value.is_i64());
3189 let json_value = from_str("12").unwrap();
3190 assert!(!json_value.is_i64());
3192 let json_value = from_str("12.0").unwrap();
3193 assert!(!json_value.is_i64());
3198 let json_value = from_str("12").unwrap();
3199 assert!(json_value.is_u64());
3201 let json_value = from_str("-12").unwrap();
3202 assert!(!json_value.is_u64());
3204 let json_value = from_str("12.0").unwrap();
3205 assert!(!json_value.is_u64());
3210 let json_value = from_str("12").unwrap();
3211 assert!(!json_value.is_f64());
3213 let json_value = from_str("-12").unwrap();
3214 assert!(!json_value.is_f64());
3216 let json_value = from_str("12.0").unwrap();
3217 assert!(json_value.is_f64());
3219 let json_value = from_str("-12.0").unwrap();
3220 assert!(json_value.is_f64());
3225 let json_value = from_str("-12").unwrap();
3226 let json_num = json_value.as_i64();
3227 assert_eq!(json_num, Some(-12));
3232 let json_value = from_str("12").unwrap();
3233 let json_num = json_value.as_u64();
3234 assert_eq!(json_num, Some(12));
3239 let json_value = from_str("12.0").unwrap();
3240 let json_num = json_value.as_f64();
3241 assert_eq!(json_num, Some(12f64));
3245 fn test_is_boolean(){
3246 let json_value = from_str("false").unwrap();
3247 assert!(json_value.is_boolean());
3251 fn test_as_boolean(){
3252 let json_value = from_str("false").unwrap();
3253 let json_bool = json_value.as_boolean();
3254 let expected_bool = false;
3255 assert!(json_bool.is_some() && json_bool.unwrap() == expected_bool);
3260 let json_value = from_str("null").unwrap();
3261 assert!(json_value.is_null());
3266 let json_value = from_str("null").unwrap();
3267 let json_null = json_value.as_null();
3268 let expected_null = ();
3269 assert!(json_null.is_some() && json_null.unwrap() == expected_null);
3273 fn test_encode_hashmap_with_numeric_key() {
3274 use std::str::from_utf8;
3275 use std::io::Writer;
3276 use std::collections::HashMap;
3277 let mut hm: HashMap<uint, bool> = HashMap::new();
3279 let mut mem_buf = Vec::new();
3281 let mut encoder = Encoder::new(&mut mem_buf as &mut io::Writer);
3282 hm.encode(&mut encoder).unwrap();
3284 let json_str = from_utf8(mem_buf[]).unwrap();
3285 match from_str(json_str) {
3286 Err(_) => panic!("Unable to parse json_str: {}", json_str),
3287 _ => {} // it parsed and we are good to go
3292 fn test_prettyencode_hashmap_with_numeric_key() {
3293 use std::str::from_utf8;
3294 use std::io::Writer;
3295 use std::collections::HashMap;
3296 let mut hm: HashMap<uint, bool> = HashMap::new();
3298 let mut mem_buf = Vec::new();
3300 let mut encoder = PrettyEncoder::new(&mut mem_buf as &mut io::Writer);
3301 hm.encode(&mut encoder).unwrap()
3303 let json_str = from_utf8(mem_buf[]).unwrap();
3304 match from_str(json_str) {
3305 Err(_) => panic!("Unable to parse json_str: {}", json_str),
3306 _ => {} // it parsed and we are good to go
3311 fn test_prettyencoder_indent_level_param() {
3312 use std::str::from_utf8;
3313 use std::collections::TreeMap;
3315 let mut tree = TreeMap::new();
3317 tree.insert("hello".into_string(), String("guten tag".into_string()));
3318 tree.insert("goodbye".into_string(), String("sayonara".into_string()));
3321 // The following layout below should look a lot like
3322 // the pretty-printed JSON (indent * x)
3325 String("greetings".into_string()), // 1x
3326 Object(tree), // 1x + 2x + 2x + 1x
3328 // End JSON array (7 lines)
3331 // Helper function for counting indents
3332 fn indents(source: &str) -> uint {
3333 let trimmed = source.trim_left_chars(' ');
3334 source.len() - trimmed.len()
3337 // Test up to 4 spaces of indents (more?)
3338 for i in range(0, 4u) {
3339 let mut writer = Vec::new();
3341 let ref mut encoder = PrettyEncoder::new(&mut writer);
3342 encoder.set_indent(i);
3343 json.encode(encoder).unwrap();
3346 let printed = from_utf8(writer[]).unwrap();
3348 // Check for indents at each line
3349 let lines: Vec<&str> = printed.lines().collect();
3350 assert_eq!(lines.len(), 7); // JSON should be 7 lines
3352 assert_eq!(indents(lines[0]), 0 * i); // [
3353 assert_eq!(indents(lines[1]), 1 * i); // "greetings",
3354 assert_eq!(indents(lines[2]), 1 * i); // {
3355 assert_eq!(indents(lines[3]), 2 * i); // "hello": "guten tag",
3356 assert_eq!(indents(lines[4]), 2 * i); // "goodbye": "sayonara"
3357 assert_eq!(indents(lines[5]), 1 * i); // },
3358 assert_eq!(indents(lines[6]), 0 * i); // ]
3360 // Finally, test that the pretty-printed JSON is valid
3361 from_str(printed).ok().expect("Pretty-printed JSON is invalid!");
3366 fn test_hashmap_with_numeric_key_can_handle_double_quote_delimited_key() {
3367 use std::collections::HashMap;
3369 let json_str = "{\"1\":true}";
3370 let json_obj = match from_str(json_str) {
3371 Err(_) => panic!("Unable to parse json_str: {}", json_str),
3374 let mut decoder = Decoder::new(json_obj);
3375 let _hm: HashMap<uint, bool> = Decodable::decode(&mut decoder).unwrap();
3379 fn test_hashmap_with_numeric_key_will_error_with_string_keys() {
3380 use std::collections::HashMap;
3382 let json_str = "{\"a\":true}";
3383 let json_obj = match from_str(json_str) {
3384 Err(_) => panic!("Unable to parse json_str: {}", json_str),
3387 let mut decoder = Decoder::new(json_obj);
3388 let result: Result<HashMap<uint, bool>, DecoderError> = Decodable::decode(&mut decoder);
3389 assert_eq!(result, Err(ExpectedError("Number".to_string(), "a".to_string())));
3392 fn assert_stream_equal(src: &str,
3393 expected: Vec<(JsonEvent, Vec<StackElement>)>) {
3394 let mut parser = Parser::new(src.chars());
3397 let evt = match parser.next() {
3401 let (ref expected_evt, ref expected_stack) = expected[i];
3402 if !parser.stack().is_equal_to(expected_stack.as_slice()) {
3403 panic!("Parser stack is not equal to {}", expected_stack);
3405 assert_eq!(&evt, expected_evt);
3410 #[cfg_attr(target_word_size = "32", ignore)] // FIXME(#14064)
3411 fn test_streaming_parser() {
3412 assert_stream_equal(
3413 r#"{ "foo":"bar", "array" : [0, 1, 2, 3, 4, 5], "idents":[null,true,false]}"#,
3415 (ObjectStart, vec![]),
3416 (StringValue("bar".to_string()), vec![Key("foo")]),
3417 (ArrayStart, vec![Key("array")]),
3418 (U64Value(0), vec![Key("array"), Index(0)]),
3419 (U64Value(1), vec![Key("array"), Index(1)]),
3420 (U64Value(2), vec![Key("array"), Index(2)]),
3421 (U64Value(3), vec![Key("array"), Index(3)]),
3422 (U64Value(4), vec![Key("array"), Index(4)]),
3423 (U64Value(5), vec![Key("array"), Index(5)]),
3424 (ArrayEnd, vec![Key("array")]),
3425 (ArrayStart, vec![Key("idents")]),
3426 (NullValue, vec![Key("idents"), Index(0)]),
3427 (BooleanValue(true), vec![Key("idents"), Index(1)]),
3428 (BooleanValue(false), vec![Key("idents"), Index(2)]),
3429 (ArrayEnd, vec![Key("idents")]),
3430 (ObjectEnd, vec![]),
3434 fn last_event(src: &str) -> JsonEvent {
3435 let mut parser = Parser::new(src.chars());
3436 let mut evt = NullValue;
3438 evt = match parser.next() {
3446 #[cfg_attr(target_word_size = "32", ignore)] // FIXME(#14064)
3447 fn test_read_object_streaming() {
3448 assert_eq!(last_event("{ "), Error(SyntaxError(EOFWhileParsingObject, 1, 3)));
3449 assert_eq!(last_event("{1"), Error(SyntaxError(KeyMustBeAString, 1, 2)));
3450 assert_eq!(last_event("{ \"a\""), Error(SyntaxError(EOFWhileParsingObject, 1, 6)));
3451 assert_eq!(last_event("{\"a\""), Error(SyntaxError(EOFWhileParsingObject, 1, 5)));
3452 assert_eq!(last_event("{\"a\" "), Error(SyntaxError(EOFWhileParsingObject, 1, 6)));
3454 assert_eq!(last_event("{\"a\" 1"), Error(SyntaxError(ExpectedColon, 1, 6)));
3455 assert_eq!(last_event("{\"a\":"), Error(SyntaxError(EOFWhileParsingValue, 1, 6)));
3456 assert_eq!(last_event("{\"a\":1"), Error(SyntaxError(EOFWhileParsingObject, 1, 7)));
3457 assert_eq!(last_event("{\"a\":1 1"), Error(SyntaxError(InvalidSyntax, 1, 8)));
3458 assert_eq!(last_event("{\"a\":1,"), Error(SyntaxError(EOFWhileParsingObject, 1, 8)));
3459 assert_eq!(last_event("{\"a\":1,}"), Error(SyntaxError(TrailingComma, 1, 8)));
3461 assert_stream_equal(
3463 vec![(ObjectStart, vec![]), (ObjectEnd, vec![])]
3465 assert_stream_equal(
3468 (ObjectStart, vec![]),
3469 (U64Value(3), vec![Key("a")]),
3470 (ObjectEnd, vec![]),
3473 assert_stream_equal(
3474 "{ \"a\": null, \"b\" : true }",
3476 (ObjectStart, vec![]),
3477 (NullValue, vec![Key("a")]),
3478 (BooleanValue(true), vec![Key("b")]),
3479 (ObjectEnd, vec![]),
3482 assert_stream_equal(
3483 "{\"a\" : 1.0 ,\"b\": [ true ]}",
3485 (ObjectStart, vec![]),
3486 (F64Value(1.0), vec![Key("a")]),
3487 (ArrayStart, vec![Key("b")]),
3488 (BooleanValue(true),vec![Key("b"), Index(0)]),
3489 (ArrayEnd, vec![Key("b")]),
3490 (ObjectEnd, vec![]),
3493 assert_stream_equal(
3499 { "c": {"d": null} }
3503 (ObjectStart, vec![]),
3504 (F64Value(1.0), vec![Key("a")]),
3505 (ArrayStart, vec![Key("b")]),
3506 (BooleanValue(true), vec![Key("b"), Index(0)]),
3507 (StringValue("foo\nbar".to_string()), vec![Key("b"), Index(1)]),
3508 (ObjectStart, vec![Key("b"), Index(2)]),
3509 (ObjectStart, vec![Key("b"), Index(2), Key("c")]),
3510 (NullValue, vec![Key("b"), Index(2), Key("c"), Key("d")]),
3511 (ObjectEnd, vec![Key("b"), Index(2), Key("c")]),
3512 (ObjectEnd, vec![Key("b"), Index(2)]),
3513 (ArrayEnd, vec![Key("b")]),
3514 (ObjectEnd, vec![]),
3519 #[cfg_attr(target_word_size = "32", ignore)] // FIXME(#14064)
3520 fn test_read_array_streaming() {
3521 assert_stream_equal(
3524 (ArrayStart, vec![]),
3528 assert_stream_equal(
3531 (ArrayStart, vec![]),
3535 assert_stream_equal(
3538 (ArrayStart, vec![]),
3539 (BooleanValue(true), vec![Index(0)]),
3543 assert_stream_equal(
3546 (ArrayStart, vec![]),
3547 (BooleanValue(false), vec![Index(0)]),
3551 assert_stream_equal(
3554 (ArrayStart, vec![]),
3555 (NullValue, vec![Index(0)]),
3559 assert_stream_equal(
3562 (ArrayStart, vec![]),
3563 (U64Value(3), vec![Index(0)]),
3564 (U64Value(1), vec![Index(1)]),
3568 assert_stream_equal(
3571 (ArrayStart, vec![]),
3572 (U64Value(3), vec![Index(0)]),
3573 (U64Value(2), vec![Index(1)]),
3577 assert_stream_equal(
3580 (ArrayStart, vec![]),
3581 (U64Value(2), vec![Index(0)]),
3582 (ArrayStart, vec![Index(1)]),
3583 (U64Value(4), vec![Index(1), Index(0)]),
3584 (U64Value(1), vec![Index(1), Index(1)]),
3585 (ArrayEnd, vec![Index(1)]),
3590 assert_eq!(last_event("["), Error(SyntaxError(EOFWhileParsingValue, 1, 2)));
3592 assert_eq!(from_str("["), Err(SyntaxError(EOFWhileParsingValue, 1, 2)));
3593 assert_eq!(from_str("[1"), Err(SyntaxError(EOFWhileParsingArray, 1, 3)));
3594 assert_eq!(from_str("[1,"), Err(SyntaxError(EOFWhileParsingValue, 1, 4)));
3595 assert_eq!(from_str("[1,]"), Err(SyntaxError(InvalidSyntax, 1, 4)));
3596 assert_eq!(from_str("[6 7]"), Err(SyntaxError(InvalidSyntax, 1, 4)));
3600 fn test_trailing_characters_streaming() {
3601 assert_eq!(last_event("nulla"), Error(SyntaxError(TrailingCharacters, 1, 5)));
3602 assert_eq!(last_event("truea"), Error(SyntaxError(TrailingCharacters, 1, 5)));
3603 assert_eq!(last_event("falsea"), Error(SyntaxError(TrailingCharacters, 1, 6)));
3604 assert_eq!(last_event("1a"), Error(SyntaxError(TrailingCharacters, 1, 2)));
3605 assert_eq!(last_event("[]a"), Error(SyntaxError(TrailingCharacters, 1, 3)));
3606 assert_eq!(last_event("{}a"), Error(SyntaxError(TrailingCharacters, 1, 3)));
3609 fn test_read_identifiers_streaming() {
3610 assert_eq!(Parser::new("null".chars()).next(), Some(NullValue));
3611 assert_eq!(Parser::new("true".chars()).next(), Some(BooleanValue(true)));
3612 assert_eq!(Parser::new("false".chars()).next(), Some(BooleanValue(false)));
3614 assert_eq!(last_event("n"), Error(SyntaxError(InvalidSyntax, 1, 2)));
3615 assert_eq!(last_event("nul"), Error(SyntaxError(InvalidSyntax, 1, 4)));
3616 assert_eq!(last_event("t"), Error(SyntaxError(InvalidSyntax, 1, 2)));
3617 assert_eq!(last_event("truz"), Error(SyntaxError(InvalidSyntax, 1, 4)));
3618 assert_eq!(last_event("f"), Error(SyntaxError(InvalidSyntax, 1, 2)));
3619 assert_eq!(last_event("faz"), Error(SyntaxError(InvalidSyntax, 1, 3)));
3624 let mut stack = Stack::new();
3626 assert!(stack.is_empty());
3627 assert!(stack.len() == 0);
3628 assert!(!stack.last_is_index());
3630 stack.push_index(0);
3633 assert!(stack.len() == 1);
3634 assert!(stack.is_equal_to(&[Index(1)]));
3635 assert!(stack.starts_with(&[Index(1)]));
3636 assert!(stack.ends_with(&[Index(1)]));
3637 assert!(stack.last_is_index());
3638 assert!(stack.get(0) == Index(1));
3640 stack.push_key("foo".to_string());
3642 assert!(stack.len() == 2);
3643 assert!(stack.is_equal_to(&[Index(1), Key("foo")]));
3644 assert!(stack.starts_with(&[Index(1), Key("foo")]));
3645 assert!(stack.starts_with(&[Index(1)]));
3646 assert!(stack.ends_with(&[Index(1), Key("foo")]));
3647 assert!(stack.ends_with(&[Key("foo")]));
3648 assert!(!stack.last_is_index());
3649 assert!(stack.get(0) == Index(1));
3650 assert!(stack.get(1) == Key("foo"));
3652 stack.push_key("bar".to_string());
3654 assert!(stack.len() == 3);
3655 assert!(stack.is_equal_to(&[Index(1), Key("foo"), Key("bar")]));
3656 assert!(stack.starts_with(&[Index(1)]));
3657 assert!(stack.starts_with(&[Index(1), Key("foo")]));
3658 assert!(stack.starts_with(&[Index(1), Key("foo"), Key("bar")]));
3659 assert!(stack.ends_with(&[Key("bar")]));
3660 assert!(stack.ends_with(&[Key("foo"), Key("bar")]));
3661 assert!(stack.ends_with(&[Index(1), Key("foo"), Key("bar")]));
3662 assert!(!stack.last_is_index());
3663 assert!(stack.get(0) == Index(1));
3664 assert!(stack.get(1) == Key("foo"));
3665 assert!(stack.get(2) == Key("bar"));
3669 assert!(stack.len() == 2);
3670 assert!(stack.is_equal_to(&[Index(1), Key("foo")]));
3671 assert!(stack.starts_with(&[Index(1), Key("foo")]));
3672 assert!(stack.starts_with(&[Index(1)]));
3673 assert!(stack.ends_with(&[Index(1), Key("foo")]));
3674 assert!(stack.ends_with(&[Key("foo")]));
3675 assert!(!stack.last_is_index());
3676 assert!(stack.get(0) == Index(1));
3677 assert!(stack.get(1) == Key("foo"));
3682 use std::collections::{HashMap,TreeMap};
3685 let array2 = Array(vec!(U64(1), U64(2)));
3686 let array3 = Array(vec!(U64(1), U64(2), U64(3)));
3688 let mut tree_map = TreeMap::new();
3689 tree_map.insert("a".to_string(), U64(1));
3690 tree_map.insert("b".to_string(), U64(2));
3694 assert_eq!(array2.to_json(), array2);
3695 assert_eq!(object.to_json(), object);
3696 assert_eq!(3_i.to_json(), I64(3));
3697 assert_eq!(4_i8.to_json(), I64(4));
3698 assert_eq!(5_i16.to_json(), I64(5));
3699 assert_eq!(6_i32.to_json(), I64(6));
3700 assert_eq!(7_i64.to_json(), I64(7));
3701 assert_eq!(8_u.to_json(), U64(8));
3702 assert_eq!(9_u8.to_json(), U64(9));
3703 assert_eq!(10_u16.to_json(), U64(10));
3704 assert_eq!(11_u32.to_json(), U64(11));
3705 assert_eq!(12_u64.to_json(), U64(12));
3706 assert_eq!(13.0_f32.to_json(), F64(13.0_f64));
3707 assert_eq!(14.0_f64.to_json(), F64(14.0_f64));
3708 assert_eq!(().to_json(), Null);
3709 assert_eq!(f32::INFINITY.to_json(), Null);
3710 assert_eq!(f64::NAN.to_json(), Null);
3711 assert_eq!(true.to_json(), Boolean(true));
3712 assert_eq!(false.to_json(), Boolean(false));
3713 assert_eq!("abc".to_json(), String("abc".into_string()));
3714 assert_eq!("abc".into_string().to_json(), String("abc".into_string()));
3715 assert_eq!((1u, 2u).to_json(), array2);
3716 assert_eq!((1u, 2u, 3u).to_json(), array3);
3717 assert_eq!([1u, 2].to_json(), array2);
3718 assert_eq!((&[1u, 2, 3]).to_json(), array3);
3719 assert_eq!((vec![1u, 2]).to_json(), array2);
3720 assert_eq!(vec!(1u, 2, 3).to_json(), array3);
3721 let mut tree_map = TreeMap::new();
3722 tree_map.insert("a".to_string(), 1u);
3723 tree_map.insert("b".to_string(), 2);
3724 assert_eq!(tree_map.to_json(), object);
3725 let mut hash_map = HashMap::new();
3726 hash_map.insert("a".to_string(), 1u);
3727 hash_map.insert("b".to_string(), 2);
3728 assert_eq!(hash_map.to_json(), object);
3729 assert_eq!(Some(15i).to_json(), I64(15));
3730 assert_eq!(Some(15u).to_json(), U64(15));
3731 assert_eq!(None::<int>.to_json(), Null);
3735 fn bench_streaming_small(b: &mut Bencher) {
3737 let mut parser = Parser::new(
3743 { "c": {"d": null} }
3748 match parser.next() {
3756 fn bench_small(b: &mut Bencher) {
3758 let _ = from_str(r#"{
3763 { "c": {"d": null} }
3769 fn big_json() -> string::String {
3770 let mut src = "[\n".to_string();
3771 for _ in range(0i, 500) {
3772 src.push_str(r#"{ "a": true, "b": null, "c":3.1415, "d": "Hello world", "e": \
3775 src.push_str("{}]");
3780 fn bench_streaming_large(b: &mut Bencher) {
3781 let src = big_json();
3783 let mut parser = Parser::new(src.as_slice().chars());
3785 match parser.next() {
3793 fn bench_large(b: &mut Bencher) {
3794 let src = big_json();
3795 b.iter( || { let _ = from_str(src.as_slice()); });