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::{mod, ToJson, Json};
117 //! // A custom data structure
118 //! struct ComplexNum {
123 //! // JSON value representation
124 //! impl ToJson for ComplexNum {
125 //! fn to_json(&self) -> Json {
126 //! Json::String(format!("{}+{}i", self.a, self.b))
130 //! // Only generate `Encodable` trait implementation
131 //! #[deriving(Encodable)]
132 //! pub struct ComplexNumRecord {
139 //! let num = ComplexNum { a: 0.0001, b: 12.539 };
140 //! let data: String = json::encode(&ComplexNumRecord{
142 //! dsc: "test".to_string(),
143 //! val: num.to_json(),
145 //! println!("data: {}", data);
146 //! // data: {"uid":1,"dsc":"test","val":"0.0001+12.539j"};
150 //! ### Verbose example of `ToJson` usage
153 //! extern crate serialize;
154 //! use std::collections::TreeMap;
155 //! use serialize::json::{mod, Json, ToJson};
157 //! // Only generate `Decodable` trait implementation
158 //! #[deriving(Decodable)]
159 //! pub struct TestStruct {
161 //! data_str: String,
162 //! data_vector: Vec<u8>,
165 //! // Specify encoding method manually
166 //! impl ToJson for TestStruct {
167 //! fn to_json(&self) -> Json {
168 //! let mut d = TreeMap::new();
169 //! // All standard types implement `to_json()`, so use it
170 //! d.insert("data_int".to_string(), self.data_int.to_json());
171 //! d.insert("data_str".to_string(), self.data_str.to_json());
172 //! d.insert("data_vector".to_string(), self.data_vector.to_json());
178 //! // Serialize using `ToJson`
179 //! let input_data = TestStruct {
181 //! data_str: "toto".to_string(),
182 //! data_vector: vec![2,3,4,5],
184 //! let json_obj: Json = input_data.to_json();
185 //! let json_str: String = json_obj.to_string();
187 //! // Deserialize like before
188 //! let decoded: TestStruct = json::decode(json_str.as_slice()).unwrap();
192 use self::JsonEvent::*;
193 use self::StackElement::*;
194 use self::ErrorCode::*;
195 use self::ParserError::*;
196 use self::DecoderError::*;
197 use self::ParserState::*;
198 use self::InternalStackElement::*;
201 use std::collections::{HashMap, TreeMap};
202 use std::{char, f64, fmt, io, num, str};
203 use std::mem::{swap, transmute};
204 use std::num::{Float, FPNaN, FPInfinite, Int};
205 use std::str::{FromStr, ScalarValue};
212 /// Represents a json value
213 #[deriving(Clone, PartialEq, PartialOrd)]
218 String(string::String),
221 Object(self::Object),
225 pub type Array = Vec<Json>;
226 pub type Object = TreeMap<string::String, Json>;
228 /// The errors that can arise while parsing a JSON stream.
229 #[deriving(Clone, PartialEq)]
233 EOFWhileParsingObject,
234 EOFWhileParsingArray,
235 EOFWhileParsingValue,
236 EOFWhileParsingString,
242 InvalidUnicodeCodePoint,
243 LoneLeadingSurrogateInHexEscape,
244 UnexpectedEndOfHexEscape,
250 #[deriving(Clone, PartialEq, Show)]
251 pub enum ParserError {
253 SyntaxError(ErrorCode, uint, uint),
254 IoError(io::IoErrorKind, &'static str),
257 // Builder and Parser have the same errors.
258 pub type BuilderError = ParserError;
260 #[deriving(Clone, PartialEq, Show)]
261 pub enum DecoderError {
262 ParseError(ParserError),
263 ExpectedError(string::String, string::String),
264 MissingFieldError(string::String),
265 UnknownVariantError(string::String),
266 ApplicationError(string::String)
269 /// Returns a readable error string for a given error code.
270 pub fn error_str(error: ErrorCode) -> &'static str {
272 InvalidSyntax => "invalid syntax",
273 InvalidNumber => "invalid number",
274 EOFWhileParsingObject => "EOF While parsing object",
275 EOFWhileParsingArray => "EOF While parsing array",
276 EOFWhileParsingValue => "EOF While parsing value",
277 EOFWhileParsingString => "EOF While parsing string",
278 KeyMustBeAString => "key must be a string",
279 ExpectedColon => "expected `:`",
280 TrailingCharacters => "trailing characters",
281 TrailingComma => "trailing comma",
282 InvalidEscape => "invalid escape",
283 UnrecognizedHex => "invalid \\u escape (unrecognized hex)",
284 NotFourDigit => "invalid \\u escape (not four digits)",
285 NotUtf8 => "contents not utf-8",
286 InvalidUnicodeCodePoint => "invalid Unicode code point",
287 LoneLeadingSurrogateInHexEscape => "lone leading surrogate in hex escape",
288 UnexpectedEndOfHexEscape => "unexpected end of hex escape",
292 /// Shortcut function to decode a JSON `&str` into an object
293 pub fn decode<T: ::Decodable<Decoder, DecoderError>>(s: &str) -> DecodeResult<T> {
294 let json = match from_str(s) {
296 Err(e) => return Err(ParseError(e))
299 let mut decoder = Decoder::new(json);
300 ::Decodable::decode(&mut decoder)
303 /// Shortcut function to encode a `T` into a JSON `String`
304 pub fn encode<'a, T: Encodable<Encoder<'a>, io::IoError>>(object: &T) -> string::String {
305 let buff = Encoder::buffer_encode(object);
306 string::String::from_utf8(buff).unwrap()
309 impl fmt::Show for ErrorCode {
310 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
311 error_str(*self).fmt(f)
315 fn io_error_to_error(io: io::IoError) -> ParserError {
316 IoError(io.kind, io.desc)
319 impl std::error::Error for DecoderError {
320 fn description(&self) -> &str { "decoder error" }
321 fn detail(&self) -> Option<std::string::String> { Some(self.to_string()) }
324 pub type EncodeResult = io::IoResult<()>;
325 pub type DecodeResult<T> = Result<T, DecoderError>;
327 pub fn escape_bytes(wr: &mut io::Writer, bytes: &[u8]) -> Result<(), io::IoError> {
328 try!(wr.write_str("\""));
332 for (i, byte) in bytes.iter().enumerate() {
333 let escaped = match *byte {
345 try!(wr.write(bytes[start..i]));
348 try!(wr.write_str(escaped));
353 if start != bytes.len() {
354 try!(wr.write(bytes[start..]));
360 fn escape_str(writer: &mut io::Writer, v: &str) -> Result<(), io::IoError> {
361 escape_bytes(writer, v.as_bytes())
364 fn escape_char(writer: &mut io::Writer, v: char) -> Result<(), io::IoError> {
365 let mut buf = [0, .. 4];
366 v.encode_utf8(&mut buf);
367 escape_bytes(writer, &mut buf)
370 fn spaces(wr: &mut io::Writer, mut n: uint) -> Result<(), io::IoError> {
371 const LEN: uint = 16;
372 static BUF: [u8, ..LEN] = [b' ', ..LEN];
375 try!(wr.write(&BUF));
386 fn fmt_number_or_null(v: f64) -> string::String {
388 FPNaN | FPInfinite => string::String::from_str("null"),
389 _ => f64::to_str_digits(v, 6u)
393 /// A structure for implementing serialization to JSON.
394 pub struct Encoder<'a> {
395 writer: &'a mut (io::Writer+'a),
398 impl<'a> Encoder<'a> {
399 /// Creates a new JSON encoder whose output will be written to the writer
401 pub fn new(writer: &'a mut io::Writer) -> Encoder<'a> {
402 Encoder { writer: writer }
405 /// Encode the specified struct into a json [u8]
406 pub fn buffer_encode<T:Encodable<Encoder<'a>, io::IoError>>(object: &T) -> Vec<u8> {
407 //Serialize the object in a string using a writer
408 let mut m = Vec::new();
409 // FIXME(14302) remove the transmute and unsafe block.
411 let mut encoder = Encoder::new(&mut m as &mut io::Writer);
412 // Vec<u8> never Errs
413 let _ = object.encode(transmute(&mut encoder));
419 impl<'a> ::Encoder<io::IoError> for Encoder<'a> {
420 fn emit_nil(&mut self) -> EncodeResult { write!(self.writer, "null") }
422 fn emit_uint(&mut self, v: uint) -> EncodeResult { write!(self.writer, "{}", v) }
423 fn emit_u64(&mut self, v: u64) -> EncodeResult { write!(self.writer, "{}", v) }
424 fn emit_u32(&mut self, v: u32) -> EncodeResult { write!(self.writer, "{}", v) }
425 fn emit_u16(&mut self, v: u16) -> EncodeResult { write!(self.writer, "{}", v) }
426 fn emit_u8(&mut self, v: u8) -> EncodeResult { write!(self.writer, "{}", v) }
428 fn emit_int(&mut self, v: int) -> EncodeResult { write!(self.writer, "{}", v) }
429 fn emit_i64(&mut self, v: i64) -> EncodeResult { write!(self.writer, "{}", v) }
430 fn emit_i32(&mut self, v: i32) -> EncodeResult { write!(self.writer, "{}", v) }
431 fn emit_i16(&mut self, v: i16) -> EncodeResult { write!(self.writer, "{}", v) }
432 fn emit_i8(&mut self, v: i8) -> EncodeResult { write!(self.writer, "{}", v) }
434 fn emit_bool(&mut self, v: bool) -> EncodeResult {
436 write!(self.writer, "true")
438 write!(self.writer, "false")
442 fn emit_f64(&mut self, v: f64) -> EncodeResult {
443 write!(self.writer, "{}", fmt_number_or_null(v))
445 fn emit_f32(&mut self, v: f32) -> EncodeResult { self.emit_f64(v as f64) }
447 fn emit_char(&mut self, v: char) -> EncodeResult {
448 escape_char(self.writer, v)
450 fn emit_str(&mut self, v: &str) -> EncodeResult {
451 escape_str(self.writer, v)
454 fn emit_enum(&mut self, _name: &str, f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
458 fn emit_enum_variant(&mut self,
462 f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
463 // enums are encoded as strings or objects
465 // Kangaroo(34,"William") => {"variant": "Kangaroo", "fields": [34,"William"]}
467 escape_str(self.writer, name)
469 try!(write!(self.writer, "{{\"variant\":"));
470 try!(escape_str(self.writer, name));
471 try!(write!(self.writer, ",\"fields\":["));
473 write!(self.writer, "]}}")
477 fn emit_enum_variant_arg(&mut self,
479 f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
481 try!(write!(self.writer, ","));
486 fn emit_enum_struct_variant(&mut self,
490 f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
491 self.emit_enum_variant(name, id, cnt, f)
494 fn emit_enum_struct_variant_field(&mut self,
497 f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
498 self.emit_enum_variant_arg(idx, f)
501 fn emit_struct(&mut self,
504 f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
505 try!(write!(self.writer, "{{"));
507 write!(self.writer, "}}")
510 fn emit_struct_field(&mut self,
513 f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
514 if idx != 0 { try!(write!(self.writer, ",")); }
515 try!(escape_str(self.writer, name));
516 try!(write!(self.writer, ":"));
520 fn emit_tuple(&mut self, len: uint, f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
521 self.emit_seq(len, f)
523 fn emit_tuple_arg(&mut self,
525 f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
526 self.emit_seq_elt(idx, f)
529 fn emit_tuple_struct(&mut self,
532 f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
533 self.emit_seq(len, f)
535 fn emit_tuple_struct_arg(&mut self,
537 f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
538 self.emit_seq_elt(idx, f)
541 fn emit_option(&mut self, f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
544 fn emit_option_none(&mut self) -> EncodeResult { self.emit_nil() }
545 fn emit_option_some(&mut self, f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
549 fn emit_seq(&mut self, _len: uint, f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
550 try!(write!(self.writer, "["));
552 write!(self.writer, "]")
555 fn emit_seq_elt(&mut self, idx: uint, f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
557 try!(write!(self.writer, ","));
562 fn emit_map(&mut self, _len: uint, f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
563 try!(write!(self.writer, "{{"));
565 write!(self.writer, "}}")
568 fn emit_map_elt_key(&mut self,
570 f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
571 if idx != 0 { try!(write!(self.writer, ",")) }
572 // ref #12967, make sure to wrap a key in double quotes,
573 // in the event that its of a type that omits them (eg numbers)
574 let mut buf = Vec::new();
575 // FIXME(14302) remove the transmute and unsafe block.
577 let mut check_encoder = Encoder::new(&mut buf);
578 try!(f(transmute(&mut check_encoder)));
580 let out = str::from_utf8(buf[]).unwrap();
581 let needs_wrapping = out.char_at(0) != '"' && out.char_at_reverse(out.len()) != '"';
582 if needs_wrapping { try!(write!(self.writer, "\"")); }
584 if needs_wrapping { try!(write!(self.writer, "\"")); }
588 fn emit_map_elt_val(&mut self,
590 f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
591 try!(write!(self.writer, ":"));
596 /// Another encoder for JSON, but prints out human-readable JSON instead of
598 pub struct PrettyEncoder<'a> {
599 writer: &'a mut (io::Writer+'a),
604 impl<'a> PrettyEncoder<'a> {
605 /// Creates a new encoder whose output will be written to the specified writer
606 pub fn new<'a>(writer: &'a mut io::Writer) -> PrettyEncoder<'a> {
607 PrettyEncoder { writer: writer, curr_indent: 0, indent: 2, }
610 /// Set the number of spaces to indent for each level.
611 /// This is safe to set during encoding.
612 pub fn set_indent<'a>(&mut self, indent: uint) {
613 // self.indent very well could be 0 so we need to use checked division.
614 let level = self.curr_indent.checked_div(self.indent).unwrap_or(0);
615 self.indent = indent;
616 self.curr_indent = level * self.indent;
620 impl<'a> ::Encoder<io::IoError> for PrettyEncoder<'a> {
621 fn emit_nil(&mut self) -> EncodeResult { write!(self.writer, "null") }
623 fn emit_uint(&mut self, v: uint) -> EncodeResult { write!(self.writer, "{}", v) }
624 fn emit_u64(&mut self, v: u64) -> EncodeResult { write!(self.writer, "{}", v) }
625 fn emit_u32(&mut self, v: u32) -> EncodeResult { write!(self.writer, "{}", v) }
626 fn emit_u16(&mut self, v: u16) -> EncodeResult { write!(self.writer, "{}", v) }
627 fn emit_u8(&mut self, v: u8) -> EncodeResult { write!(self.writer, "{}", v) }
629 fn emit_int(&mut self, v: int) -> EncodeResult { write!(self.writer, "{}", v) }
630 fn emit_i64(&mut self, v: i64) -> EncodeResult { write!(self.writer, "{}", v) }
631 fn emit_i32(&mut self, v: i32) -> EncodeResult { write!(self.writer, "{}", v) }
632 fn emit_i16(&mut self, v: i16) -> EncodeResult { write!(self.writer, "{}", v) }
633 fn emit_i8(&mut self, v: i8) -> EncodeResult { write!(self.writer, "{}", v) }
635 fn emit_bool(&mut self, v: bool) -> EncodeResult {
637 write!(self.writer, "true")
639 write!(self.writer, "false")
643 fn emit_f64(&mut self, v: f64) -> EncodeResult {
644 write!(self.writer, "{}", fmt_number_or_null(v))
646 fn emit_f32(&mut self, v: f32) -> EncodeResult {
647 self.emit_f64(v as f64)
650 fn emit_char(&mut self, v: char) -> EncodeResult {
651 escape_char(self.writer, v)
653 fn emit_str(&mut self, v: &str) -> EncodeResult {
654 escape_str(self.writer, v)
657 fn emit_enum(&mut self,
659 f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
663 fn emit_enum_variant(&mut self,
667 f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
669 escape_str(self.writer, name)
671 try!(write!(self.writer, "{{\n"));
672 self.curr_indent += self.indent;
673 try!(spaces(self.writer, self.curr_indent));
674 try!(write!(self.writer, "\"variant\": "));
675 try!(escape_str(self.writer, name));
676 try!(write!(self.writer, ",\n"));
677 try!(spaces(self.writer, self.curr_indent));
678 try!(write!(self.writer, "\"fields\": [\n"));
679 self.curr_indent += self.indent;
681 self.curr_indent -= self.indent;
682 try!(write!(self.writer, "\n"));
683 try!(spaces(self.writer, self.curr_indent));
684 self.curr_indent -= self.indent;
685 try!(write!(self.writer, "]\n"));
686 try!(spaces(self.writer, self.curr_indent));
687 write!(self.writer, "}}")
691 fn emit_enum_variant_arg(&mut self,
693 f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
695 try!(write!(self.writer, ",\n"));
697 try!(spaces(self.writer, self.curr_indent));
701 fn emit_enum_struct_variant(&mut self,
705 f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
706 self.emit_enum_variant(name, id, cnt, f)
709 fn emit_enum_struct_variant_field(&mut self,
712 f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
713 self.emit_enum_variant_arg(idx, f)
717 fn emit_struct(&mut self,
720 f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
722 write!(self.writer, "{{}}")
724 try!(write!(self.writer, "{{"));
725 self.curr_indent += self.indent;
727 self.curr_indent -= self.indent;
728 try!(write!(self.writer, "\n"));
729 try!(spaces(self.writer, self.curr_indent));
730 write!(self.writer, "}}")
734 fn emit_struct_field(&mut self,
737 f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
739 try!(write!(self.writer, "\n"));
741 try!(write!(self.writer, ",\n"));
743 try!(spaces(self.writer, self.curr_indent));
744 try!(escape_str(self.writer, name));
745 try!(write!(self.writer, ": "));
749 fn emit_tuple(&mut self,
751 f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
752 self.emit_seq(len, f)
754 fn emit_tuple_arg(&mut self,
756 f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
757 self.emit_seq_elt(idx, f)
760 fn emit_tuple_struct(&mut self,
763 f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
764 self.emit_seq(len, f)
766 fn emit_tuple_struct_arg(&mut self,
768 f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
769 self.emit_seq_elt(idx, f)
772 fn emit_option(&mut self, f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
775 fn emit_option_none(&mut self) -> EncodeResult { self.emit_nil() }
776 fn emit_option_some(&mut self, f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
780 fn emit_seq(&mut self,
782 f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
784 write!(self.writer, "[]")
786 try!(write!(self.writer, "["));
787 self.curr_indent += self.indent;
789 self.curr_indent -= self.indent;
790 try!(write!(self.writer, "\n"));
791 try!(spaces(self.writer, self.curr_indent));
792 write!(self.writer, "]")
796 fn emit_seq_elt(&mut self,
798 f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
800 try!(write!(self.writer, "\n"));
802 try!(write!(self.writer, ",\n"));
804 try!(spaces(self.writer, self.curr_indent));
808 fn emit_map(&mut self,
810 f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
812 write!(self.writer, "{{}}")
814 try!(write!(self.writer, "{{"));
815 self.curr_indent += self.indent;
817 self.curr_indent -= self.indent;
818 try!(write!(self.writer, "\n"));
819 try!(spaces(self.writer, self.curr_indent));
820 write!(self.writer, "}}")
824 fn emit_map_elt_key(&mut self,
826 f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
828 try!(write!(self.writer, "\n"));
830 try!(write!(self.writer, ",\n"));
832 try!(spaces(self.writer, self.curr_indent));
833 // ref #12967, make sure to wrap a key in double quotes,
834 // in the event that its of a type that omits them (eg numbers)
835 let mut buf = Vec::new();
836 // FIXME(14302) remove the transmute and unsafe block.
838 let mut check_encoder = PrettyEncoder::new(&mut buf);
839 try!(f(transmute(&mut check_encoder)));
841 let out = str::from_utf8(buf[]).unwrap();
842 let needs_wrapping = out.char_at(0) != '"' && out.char_at_reverse(out.len()) != '"';
843 if needs_wrapping { try!(write!(self.writer, "\"")); }
845 if needs_wrapping { try!(write!(self.writer, "\"")); }
849 fn emit_map_elt_val(&mut self,
851 f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
852 try!(write!(self.writer, ": "));
857 impl<E: ::Encoder<S>, S> Encodable<E, S> for Json {
858 fn encode(&self, e: &mut E) -> Result<(), S> {
860 Json::I64(v) => v.encode(e),
861 Json::U64(v) => v.encode(e),
862 Json::F64(v) => v.encode(e),
863 Json::String(ref v) => v.encode(e),
864 Json::Boolean(v) => v.encode(e),
865 Json::Array(ref v) => v.encode(e),
866 Json::Object(ref v) => v.encode(e),
867 Json::Null => e.emit_nil(),
873 /// Encodes a json value into an io::writer. Uses a single line.
874 pub fn to_writer(&self, writer: &mut io::Writer) -> EncodeResult {
875 let mut encoder = Encoder::new(writer);
876 self.encode(&mut encoder)
879 /// Encodes a json value into an io::writer.
880 /// Pretty-prints in a more readable format.
881 pub fn to_pretty_writer(&self, writer: &mut io::Writer) -> EncodeResult {
882 let mut encoder = PrettyEncoder::new(writer);
883 self.encode(&mut encoder)
886 /// Encodes a json value into a string
887 pub fn to_pretty_str(&self) -> string::String {
888 let mut s = Vec::new();
889 self.to_pretty_writer(&mut s as &mut io::Writer).unwrap();
890 string::String::from_utf8(s).unwrap()
893 /// If the Json value is an Object, returns the value associated with the provided key.
894 /// Otherwise, returns None.
895 pub fn find<'a>(&'a self, key: &str) -> Option<&'a Json>{
897 &Json::Object(ref map) => map.get(key),
902 /// Attempts to get a nested Json Object for each key in `keys`.
903 /// If any key is found not to exist, find_path will return None.
904 /// Otherwise, it will return the Json value associated with the final key.
905 pub fn find_path<'a>(&'a self, keys: &[&str]) -> Option<&'a Json>{
906 let mut target = self;
907 for key in keys.iter() {
908 match target.find(*key) {
909 Some(t) => { target = t; },
916 /// If the Json value is an Object, performs a depth-first search until
917 /// a value associated with the provided key is found. If no value is found
918 /// or the Json value is not an Object, returns None.
919 pub fn search<'a>(&'a self, key: &str) -> Option<&'a Json> {
921 &Json::Object(ref map) => {
923 Some(json_value) => Some(json_value),
925 for (_, v) in map.iter() {
926 match v.search(key) {
927 x if x.is_some() => return x,
939 /// Returns true if the Json value is an Object. Returns false otherwise.
940 pub fn is_object<'a>(&'a self) -> bool {
941 self.as_object().is_some()
944 /// If the Json value is an Object, returns the associated TreeMap.
945 /// Returns None otherwise.
946 pub fn as_object<'a>(&'a self) -> Option<&'a Object> {
948 &Json::Object(ref map) => Some(map),
953 /// Returns true if the Json value is an Array. Returns false otherwise.
954 pub fn is_array<'a>(&'a self) -> bool {
955 self.as_array().is_some()
958 /// If the Json value is an Array, returns the associated vector.
959 /// Returns None otherwise.
960 pub fn as_array<'a>(&'a self) -> Option<&'a Array> {
962 &Json::Array(ref array) => Some(&*array),
967 /// Returns true if the Json value is a String. Returns false otherwise.
968 pub fn is_string<'a>(&'a self) -> bool {
969 self.as_string().is_some()
972 /// If the Json value is a String, returns the associated str.
973 /// Returns None otherwise.
974 pub fn as_string<'a>(&'a self) -> Option<&'a str> {
976 Json::String(ref s) => Some(s.as_slice()),
981 /// Returns true if the Json value is a Number. Returns false otherwise.
982 pub fn is_number(&self) -> bool {
984 Json::I64(_) | Json::U64(_) | Json::F64(_) => true,
989 /// Returns true if the Json value is a i64. Returns false otherwise.
990 pub fn is_i64(&self) -> bool {
992 Json::I64(_) => true,
997 /// Returns true if the Json value is a u64. Returns false otherwise.
998 pub fn is_u64(&self) -> bool {
1000 Json::U64(_) => true,
1005 /// Returns true if the Json value is a f64. Returns false otherwise.
1006 pub fn is_f64(&self) -> bool {
1008 Json::F64(_) => true,
1013 /// If the Json value is a number, return or cast it to a i64.
1014 /// Returns None otherwise.
1015 pub fn as_i64(&self) -> Option<i64> {
1017 Json::I64(n) => Some(n),
1018 Json::U64(n) => num::cast(n),
1023 /// If the Json value is a number, return or cast it to a u64.
1024 /// Returns None otherwise.
1025 pub fn as_u64(&self) -> Option<u64> {
1027 Json::I64(n) => num::cast(n),
1028 Json::U64(n) => Some(n),
1033 /// If the Json value is a number, return or cast it to a f64.
1034 /// Returns None otherwise.
1035 pub fn as_f64(&self) -> Option<f64> {
1037 Json::I64(n) => num::cast(n),
1038 Json::U64(n) => num::cast(n),
1039 Json::F64(n) => Some(n),
1044 /// Returns true if the Json value is a Boolean. Returns false otherwise.
1045 pub fn is_boolean(&self) -> bool {
1046 self.as_boolean().is_some()
1049 /// If the Json value is a Boolean, returns the associated bool.
1050 /// Returns None otherwise.
1051 pub fn as_boolean(&self) -> Option<bool> {
1053 &Json::Boolean(b) => Some(b),
1058 /// Returns true if the Json value is a Null. Returns false otherwise.
1059 pub fn is_null(&self) -> bool {
1060 self.as_null().is_some()
1063 /// If the Json value is a Null, returns ().
1064 /// Returns None otherwise.
1065 pub fn as_null(&self) -> Option<()> {
1067 &Json::Null => Some(()),
1073 impl<'a> ops::Index<&'a str, Json> for Json {
1074 fn index<'a>(&'a self, idx: & &str) -> &'a Json {
1075 self.find(*idx).unwrap()
1079 impl ops::Index<uint, Json> for Json {
1080 fn index<'a>(&'a self, idx: &uint) -> &'a Json {
1082 &Json::Array(ref v) => v.index(idx),
1083 _ => panic!("can only index Json with uint if it is an array")
1088 /// The output of the streaming parser.
1089 #[deriving(PartialEq, Clone, Show)]
1090 pub enum JsonEvent {
1099 StringValue(string::String),
1104 #[deriving(PartialEq, Show)]
1106 // Parse a value in an array, true means first element.
1108 // Parse ',' or ']' after an element in an array.
1110 // Parse a key:value in an object, true means first element.
1112 // Parse ',' or ']' after an element in an object.
1116 // Expecting the stream to end.
1118 // Parsing can't continue.
1122 /// A Stack represents the current position of the parser in the logical
1123 /// structure of the JSON stream.
1124 /// For example foo.bar[3].x
1126 stack: Vec<InternalStackElement>,
1127 str_buffer: Vec<u8>,
1130 /// StackElements compose a Stack.
1131 /// For example, Key("foo"), Key("bar"), Index(3) and Key("x") are the
1132 /// StackElements compositing the stack that represents foo.bar[3].x
1133 #[deriving(PartialEq, Clone, Show)]
1134 pub enum StackElement<'l> {
1139 // Internally, Key elements are stored as indices in a buffer to avoid
1140 // allocating a string for every member of an object.
1141 #[deriving(PartialEq, Clone, Show)]
1142 enum InternalStackElement {
1144 InternalKey(u16, u16), // start, size
1148 pub fn new() -> Stack {
1149 Stack { stack: Vec::new(), str_buffer: Vec::new() }
1152 /// Returns The number of elements in the Stack.
1153 pub fn len(&self) -> uint { self.stack.len() }
1155 /// Returns true if the stack is empty.
1156 pub fn is_empty(&self) -> bool { self.stack.is_empty() }
1158 /// Provides access to the StackElement at a given index.
1159 /// lower indices are at the bottom of the stack while higher indices are
1161 pub fn get<'l>(&'l self, idx: uint) -> StackElement<'l> {
1162 match self.stack[idx] {
1163 InternalIndex(i) => Index(i),
1164 InternalKey(start, size) => {
1166 self.str_buffer[start as uint .. start as uint + size as uint]).unwrap())
1171 /// Compares this stack with an array of StackElements.
1172 pub fn is_equal_to(&self, rhs: &[StackElement]) -> bool {
1173 if self.stack.len() != rhs.len() { return false; }
1174 for i in range(0, rhs.len()) {
1175 if self.get(i) != rhs[i] { return false; }
1180 /// Returns true if the bottom-most elements of this stack are the same as
1181 /// the ones passed as parameter.
1182 pub fn starts_with(&self, rhs: &[StackElement]) -> bool {
1183 if self.stack.len() < rhs.len() { return false; }
1184 for i in range(0, rhs.len()) {
1185 if self.get(i) != rhs[i] { return false; }
1190 /// Returns true if the top-most elements of this stack are the same as
1191 /// the ones passed as parameter.
1192 pub fn ends_with(&self, rhs: &[StackElement]) -> bool {
1193 if self.stack.len() < rhs.len() { return false; }
1194 let offset = self.stack.len() - rhs.len();
1195 for i in range(0, rhs.len()) {
1196 if self.get(i + offset) != rhs[i] { return false; }
1201 /// Returns the top-most element (if any).
1202 pub fn top<'l>(&'l self) -> Option<StackElement<'l>> {
1203 return match self.stack.last() {
1205 Some(&InternalIndex(i)) => Some(Index(i)),
1206 Some(&InternalKey(start, size)) => {
1207 Some(Key(str::from_utf8(
1208 self.str_buffer[start as uint .. (start+size) as uint]
1214 // Used by Parser to insert Key elements at the top of the stack.
1215 fn push_key(&mut self, key: string::String) {
1216 self.stack.push(InternalKey(self.str_buffer.len() as u16, key.len() as u16));
1217 for c in key.as_bytes().iter() {
1218 self.str_buffer.push(*c);
1222 // Used by Parser to insert Index elements at the top of the stack.
1223 fn push_index(&mut self, index: u32) {
1224 self.stack.push(InternalIndex(index));
1227 // Used by Parser to remove the top-most element of the stack.
1229 assert!(!self.is_empty());
1230 match *self.stack.last().unwrap() {
1231 InternalKey(_, sz) => {
1232 let new_size = self.str_buffer.len() - sz as uint;
1233 self.str_buffer.truncate(new_size);
1235 InternalIndex(_) => {}
1240 // Used by Parser to test whether the top-most element is an index.
1241 fn last_is_index(&self) -> bool {
1242 if self.is_empty() { return false; }
1243 return match *self.stack.last().unwrap() {
1244 InternalIndex(_) => true,
1249 // Used by Parser to increment the index of the top-most element.
1250 fn bump_index(&mut self) {
1251 let len = self.stack.len();
1252 let idx = match *self.stack.last().unwrap() {
1253 InternalIndex(i) => { i + 1 }
1256 self.stack[len - 1] = InternalIndex(idx);
1260 /// A streaming JSON parser implemented as an iterator of JsonEvent, consuming
1261 /// an iterator of char.
1262 pub struct Parser<T> {
1267 // We maintain a stack representing where we are in the logical structure
1268 // of the JSON stream.
1270 // A state machine is kept to make it possible to interrupt and resume parsing.
1274 impl<T: Iterator<char>> Iterator<JsonEvent> for Parser<T> {
1275 fn next(&mut self) -> Option<JsonEvent> {
1276 if self.state == ParseFinished {
1280 if self.state == ParseBeforeFinish {
1281 self.parse_whitespace();
1282 // Make sure there is no trailing characters.
1284 self.state = ParseFinished;
1287 return Some(self.error_event(TrailingCharacters));
1291 return Some(self.parse());
1295 impl<T: Iterator<char>> Parser<T> {
1296 /// Creates the JSON parser.
1297 pub fn new(rdr: T) -> Parser<T> {
1298 let mut p = Parser {
1303 stack: Stack::new(),
1310 /// Provides access to the current position in the logical structure of the
1312 pub fn stack<'l>(&'l self) -> &'l Stack {
1316 fn eof(&self) -> bool { self.ch.is_none() }
1317 fn ch_or_null(&self) -> char { self.ch.unwrap_or('\x00') }
1318 fn bump(&mut self) {
1319 self.ch = self.rdr.next();
1321 if self.ch_is('\n') {
1329 fn next_char(&mut self) -> Option<char> {
1333 fn ch_is(&self, c: char) -> bool {
1337 fn error<T>(&self, reason: ErrorCode) -> Result<T, ParserError> {
1338 Err(SyntaxError(reason, self.line, self.col))
1341 fn parse_whitespace(&mut self) {
1342 while self.ch_is(' ') ||
1345 self.ch_is('\r') { self.bump(); }
1348 fn parse_number(&mut self) -> JsonEvent {
1349 let mut neg = false;
1351 if self.ch_is('-') {
1356 let res = match self.parse_u64() {
1358 Err(e) => { return Error(e); }
1361 if self.ch_is('.') || self.ch_is('e') || self.ch_is('E') {
1362 let mut res = res as f64;
1364 if self.ch_is('.') {
1365 res = match self.parse_decimal(res) {
1367 Err(e) => { return Error(e); }
1371 if self.ch_is('e') || self.ch_is('E') {
1372 res = match self.parse_exponent(res) {
1374 Err(e) => { return Error(e); }
1385 let res = -(res as i64);
1387 // Make sure we didn't underflow.
1389 Error(SyntaxError(InvalidNumber, self.line, self.col))
1399 fn parse_u64(&mut self) -> Result<u64, ParserError> {
1401 let last_accum = 0; // necessary to detect overflow.
1403 match self.ch_or_null() {
1407 // A leading '0' must be the only digit before the decimal point.
1408 match self.ch_or_null() {
1409 '0' ... '9' => return self.error(InvalidNumber),
1415 match self.ch_or_null() {
1416 c @ '0' ... '9' => {
1418 accum += (c as u64) - ('0' as u64);
1420 // Detect overflow by comparing to the last value.
1421 if accum <= last_accum { return self.error(InvalidNumber); }
1429 _ => return self.error(InvalidNumber),
1435 fn parse_decimal(&mut self, mut res: f64) -> Result<f64, ParserError> {
1438 // Make sure a digit follows the decimal place.
1439 match self.ch_or_null() {
1441 _ => return self.error(InvalidNumber)
1446 match self.ch_or_null() {
1447 c @ '0' ... '9' => {
1449 res += (((c as int) - ('0' as int)) as f64) * dec;
1459 fn parse_exponent(&mut self, mut res: f64) -> Result<f64, ParserError> {
1463 let mut neg_exp = false;
1465 if self.ch_is('+') {
1467 } else if self.ch_is('-') {
1472 // Make sure a digit follows the exponent place.
1473 match self.ch_or_null() {
1475 _ => return self.error(InvalidNumber)
1478 match self.ch_or_null() {
1479 c @ '0' ... '9' => {
1481 exp += (c as uint) - ('0' as uint);
1489 let exp = 10_f64.powi(exp as i32);
1499 fn decode_hex_escape(&mut self) -> Result<u16, ParserError> {
1502 while i < 4 && !self.eof() {
1504 n = match self.ch_or_null() {
1505 c @ '0' ... '9' => n * 16 + ((c as u16) - ('0' as u16)),
1506 'a' | 'A' => n * 16 + 10,
1507 'b' | 'B' => n * 16 + 11,
1508 'c' | 'C' => n * 16 + 12,
1509 'd' | 'D' => n * 16 + 13,
1510 'e' | 'E' => n * 16 + 14,
1511 'f' | 'F' => n * 16 + 15,
1512 _ => return self.error(InvalidEscape)
1518 // Error out if we didn't parse 4 digits.
1520 return self.error(InvalidEscape);
1526 fn parse_str(&mut self) -> Result<string::String, ParserError> {
1527 let mut escape = false;
1528 let mut res = string::String::new();
1533 return self.error(EOFWhileParsingString);
1537 match self.ch_or_null() {
1538 '"' => res.push('"'),
1539 '\\' => res.push('\\'),
1540 '/' => res.push('/'),
1541 'b' => res.push('\x08'),
1542 'f' => res.push('\x0c'),
1543 'n' => res.push('\n'),
1544 'r' => res.push('\r'),
1545 't' => res.push('\t'),
1546 'u' => match try!(self.decode_hex_escape()) {
1547 0xDC00 ... 0xDFFF => {
1548 return self.error(LoneLeadingSurrogateInHexEscape)
1551 // Non-BMP characters are encoded as a sequence of
1552 // two hex escapes, representing UTF-16 surrogates.
1553 n1 @ 0xD800 ... 0xDBFF => {
1554 match (self.next_char(), self.next_char()) {
1555 (Some('\\'), Some('u')) => (),
1556 _ => return self.error(UnexpectedEndOfHexEscape),
1559 let buf = [n1, try!(self.decode_hex_escape())];
1560 match str::utf16_items(buf.as_slice()).next() {
1561 Some(ScalarValue(c)) => res.push(c),
1562 _ => return self.error(LoneLeadingSurrogateInHexEscape),
1566 n => match char::from_u32(n as u32) {
1567 Some(c) => res.push(c),
1568 None => return self.error(InvalidUnicodeCodePoint),
1571 _ => return self.error(InvalidEscape),
1574 } else if self.ch_is('\\') {
1582 Some(c) => res.push(c),
1583 None => unreachable!()
1589 // Invoked at each iteration, consumes the stream until it has enough
1590 // information to return a JsonEvent.
1591 // Manages an internal state so that parsing can be interrupted and resumed.
1592 // Also keeps track of the position in the logical structure of the json
1593 // stream int the form of a stack that can be queried by the user using the
1595 fn parse(&mut self) -> JsonEvent {
1597 // The only paths where the loop can spin a new iteration
1598 // are in the cases ParseArrayComma and ParseObjectComma if ','
1599 // is parsed. In these cases the state is set to (respectively)
1600 // ParseArray(false) and ParseObject(false), which always return,
1601 // so there is no risk of getting stuck in an infinite loop.
1602 // All other paths return before the end of the loop's iteration.
1603 self.parse_whitespace();
1607 return self.parse_start();
1609 ParseArray(first) => {
1610 return self.parse_array(first);
1612 ParseArrayComma => {
1613 match self.parse_array_comma_or_end() {
1614 Some(evt) => { return evt; }
1618 ParseObject(first) => {
1619 return self.parse_object(first);
1621 ParseObjectComma => {
1623 if self.ch_is(',') {
1624 self.state = ParseObject(false);
1627 return self.parse_object_end();
1631 return self.error_event(InvalidSyntax);
1637 fn parse_start(&mut self) -> JsonEvent {
1638 let val = self.parse_value();
1639 self.state = match val {
1640 Error(_) => ParseFinished,
1641 ArrayStart => ParseArray(true),
1642 ObjectStart => ParseObject(true),
1643 _ => ParseBeforeFinish,
1648 fn parse_array(&mut self, first: bool) -> JsonEvent {
1649 if self.ch_is(']') {
1651 self.error_event(InvalidSyntax)
1653 self.state = if self.stack.is_empty() {
1655 } else if self.stack.last_is_index() {
1665 self.stack.push_index(0);
1667 let val = self.parse_value();
1668 self.state = match val {
1669 Error(_) => ParseFinished,
1670 ArrayStart => ParseArray(true),
1671 ObjectStart => ParseObject(true),
1672 _ => ParseArrayComma,
1678 fn parse_array_comma_or_end(&mut self) -> Option<JsonEvent> {
1679 if self.ch_is(',') {
1680 self.stack.bump_index();
1681 self.state = ParseArray(false);
1684 } else if self.ch_is(']') {
1686 self.state = if self.stack.is_empty() {
1688 } else if self.stack.last_is_index() {
1695 } else if self.eof() {
1696 Some(self.error_event(EOFWhileParsingArray))
1698 Some(self.error_event(InvalidSyntax))
1702 fn parse_object(&mut self, first: bool) -> JsonEvent {
1703 if self.ch_is('}') {
1705 if self.stack.is_empty() {
1706 return self.error_event(TrailingComma);
1711 self.state = if self.stack.is_empty() {
1713 } else if self.stack.last_is_index() {
1722 return self.error_event(EOFWhileParsingObject);
1724 if !self.ch_is('"') {
1725 return self.error_event(KeyMustBeAString);
1727 let s = match self.parse_str() {
1730 self.state = ParseFinished;
1734 self.parse_whitespace();
1736 return self.error_event(EOFWhileParsingObject);
1737 } else if self.ch_or_null() != ':' {
1738 return self.error_event(ExpectedColon);
1740 self.stack.push_key(s);
1742 self.parse_whitespace();
1744 let val = self.parse_value();
1746 self.state = match val {
1747 Error(_) => ParseFinished,
1748 ArrayStart => ParseArray(true),
1749 ObjectStart => ParseObject(true),
1750 _ => ParseObjectComma,
1755 fn parse_object_end(&mut self) -> JsonEvent {
1756 if self.ch_is('}') {
1757 self.state = if self.stack.is_empty() {
1759 } else if self.stack.last_is_index() {
1766 } else if self.eof() {
1767 self.error_event(EOFWhileParsingObject)
1769 self.error_event(InvalidSyntax)
1773 fn parse_value(&mut self) -> JsonEvent {
1774 if self.eof() { return self.error_event(EOFWhileParsingValue); }
1775 match self.ch_or_null() {
1776 'n' => { self.parse_ident("ull", NullValue) }
1777 't' => { self.parse_ident("rue", BooleanValue(true)) }
1778 'f' => { self.parse_ident("alse", BooleanValue(false)) }
1779 '0' ... '9' | '-' => self.parse_number(),
1780 '"' => match self.parse_str() {
1781 Ok(s) => StringValue(s),
1792 _ => { self.error_event(InvalidSyntax) }
1796 fn parse_ident(&mut self, ident: &str, value: JsonEvent) -> JsonEvent {
1797 if ident.chars().all(|c| Some(c) == self.next_char()) {
1801 Error(SyntaxError(InvalidSyntax, self.line, self.col))
1805 fn error_event(&mut self, reason: ErrorCode) -> JsonEvent {
1806 self.state = ParseFinished;
1807 Error(SyntaxError(reason, self.line, self.col))
1811 /// A Builder consumes a json::Parser to create a generic Json structure.
1812 pub struct Builder<T> {
1814 token: Option<JsonEvent>,
1817 impl<T: Iterator<char>> Builder<T> {
1818 /// Create a JSON Builder.
1819 pub fn new(src: T) -> Builder<T> {
1820 Builder { parser: Parser::new(src), token: None, }
1823 // Decode a Json value from a Parser.
1824 pub fn build(&mut self) -> Result<Json, BuilderError> {
1826 let result = self.build_value();
1830 Some(Error(e)) => { return Err(e); }
1831 ref tok => { panic!("unexpected token {}", tok.clone()); }
1836 fn bump(&mut self) {
1837 self.token = self.parser.next();
1840 fn build_value(&mut self) -> Result<Json, BuilderError> {
1841 return match self.token {
1842 Some(NullValue) => Ok(Json::Null),
1843 Some(I64Value(n)) => Ok(Json::I64(n)),
1844 Some(U64Value(n)) => Ok(Json::U64(n)),
1845 Some(F64Value(n)) => Ok(Json::F64(n)),
1846 Some(BooleanValue(b)) => Ok(Json::Boolean(b)),
1847 Some(StringValue(ref mut s)) => {
1848 let mut temp = string::String::new();
1850 Ok(Json::String(temp))
1852 Some(Error(e)) => Err(e),
1853 Some(ArrayStart) => self.build_array(),
1854 Some(ObjectStart) => self.build_object(),
1855 Some(ObjectEnd) => self.parser.error(InvalidSyntax),
1856 Some(ArrayEnd) => self.parser.error(InvalidSyntax),
1857 None => self.parser.error(EOFWhileParsingValue),
1861 fn build_array(&mut self) -> Result<Json, BuilderError> {
1863 let mut values = Vec::new();
1866 if self.token == Some(ArrayEnd) {
1867 return Ok(Json::Array(values.into_iter().collect()));
1869 match self.build_value() {
1870 Ok(v) => values.push(v),
1871 Err(e) => { return Err(e) }
1877 fn build_object(&mut self) -> Result<Json, BuilderError> {
1880 let mut values = TreeMap::new();
1884 Some(ObjectEnd) => { return Ok(Json::Object(values)); }
1885 Some(Error(e)) => { return Err(e); }
1889 let key = match self.parser.stack().top() {
1890 Some(Key(k)) => { k.to_string() }
1891 _ => { panic!("invalid state"); }
1893 match self.build_value() {
1894 Ok(value) => { values.insert(key, value); }
1895 Err(e) => { return Err(e); }
1899 return self.parser.error(EOFWhileParsingObject);
1903 /// Decodes a json value from an `&mut io::Reader`
1904 pub fn from_reader(rdr: &mut io::Reader) -> Result<Json, BuilderError> {
1905 let contents = match rdr.read_to_end() {
1907 Err(e) => return Err(io_error_to_error(e))
1909 let s = match str::from_utf8(contents.as_slice()) {
1911 _ => return Err(SyntaxError(NotUtf8, 0, 0))
1913 let mut builder = Builder::new(s.chars());
1917 /// Decodes a json value from a string
1918 pub fn from_str(s: &str) -> Result<Json, BuilderError> {
1919 let mut builder = Builder::new(s.chars());
1923 /// A structure to decode JSON to values in rust.
1924 pub struct Decoder {
1929 /// Creates a new decoder instance for decoding the specified JSON value.
1930 pub fn new(json: Json) -> Decoder {
1931 Decoder { stack: vec![json] }
1936 fn pop(&mut self) -> Json {
1937 self.stack.pop().unwrap()
1941 macro_rules! expect(
1942 ($e:expr, Null) => ({
1944 Json::Null => Ok(()),
1945 other => Err(ExpectedError("Null".to_string(),
1946 format!("{}", other)))
1949 ($e:expr, $t:ident) => ({
1951 Json::$t(v) => Ok(v),
1953 Err(ExpectedError(stringify!($t).to_string(),
1954 format!("{}", other)))
1960 macro_rules! read_primitive {
1961 ($name:ident, $ty:ty) => {
1962 fn $name(&mut self) -> DecodeResult<$ty> {
1965 match num::cast(f) {
1967 None => Err(ExpectedError("Number".to_string(), format!("{}", f))),
1971 match num::cast(f) {
1973 None => Err(ExpectedError("Number".to_string(), format!("{}", f))),
1977 match num::cast(f) {
1979 None => Err(ExpectedError("Number".to_string(), format!("{}", f))),
1982 Json::String(s) => {
1983 // re: #12967.. a type w/ numeric keys (ie HashMap<uint, V> etc)
1984 // is going to have a string here, as per JSON spec.
1985 match std::str::from_str(s.as_slice()) {
1987 None => Err(ExpectedError("Number".to_string(), s)),
1990 value => Err(ExpectedError("Number".to_string(), format!("{}", value)))
1996 impl ::Decoder<DecoderError> for Decoder {
1997 fn read_nil(&mut self) -> DecodeResult<()> {
1999 expect!(self.pop(), Null)
2002 read_primitive!(read_uint, uint)
2003 read_primitive!(read_u8, u8)
2004 read_primitive!(read_u16, u16)
2005 read_primitive!(read_u32, u32)
2006 read_primitive!(read_u64, u64)
2007 read_primitive!(read_int, int)
2008 read_primitive!(read_i8, i8)
2009 read_primitive!(read_i16, i16)
2010 read_primitive!(read_i32, i32)
2011 read_primitive!(read_i64, i64)
2013 fn read_f32(&mut self) -> DecodeResult<f32> { self.read_f64().map(|x| x as f32) }
2015 fn read_f64(&mut self) -> DecodeResult<f64> {
2018 Json::I64(f) => Ok(f as f64),
2019 Json::U64(f) => Ok(f as f64),
2020 Json::F64(f) => Ok(f),
2021 Json::String(s) => {
2022 // re: #12967.. a type w/ numeric keys (ie HashMap<uint, V> etc)
2023 // is going to have a string here, as per JSON spec.
2024 match std::str::from_str(s.as_slice()) {
2026 None => Err(ExpectedError("Number".to_string(), s)),
2029 Json::Null => Ok(f64::NAN),
2030 value => Err(ExpectedError("Number".to_string(), format!("{}", value)))
2034 fn read_bool(&mut self) -> DecodeResult<bool> {
2035 debug!("read_bool");
2036 expect!(self.pop(), Boolean)
2039 fn read_char(&mut self) -> DecodeResult<char> {
2040 let s = try!(self.read_str());
2042 let mut it = s.chars();
2043 match (it.next(), it.next()) {
2044 // exactly one character
2045 (Some(c), None) => return Ok(c),
2049 Err(ExpectedError("single character string".to_string(), format!("{}", s)))
2052 fn read_str(&mut self) -> DecodeResult<string::String> {
2054 expect!(self.pop(), String)
2057 fn read_enum<T>(&mut self,
2059 f: |&mut Decoder| -> DecodeResult<T>) -> DecodeResult<T> {
2060 debug!("read_enum({})", name);
2064 fn read_enum_variant<T>(&mut self,
2066 f: |&mut Decoder, uint| -> DecodeResult<T>)
2067 -> DecodeResult<T> {
2068 debug!("read_enum_variant(names={})", names);
2069 let name = match self.pop() {
2070 Json::String(s) => s,
2071 Json::Object(mut o) => {
2072 let n = match o.remove(&"variant".to_string()) {
2073 Some(Json::String(s)) => s,
2075 return Err(ExpectedError("String".to_string(), format!("{}", val)))
2078 return Err(MissingFieldError("variant".to_string()))
2081 match o.remove(&"fields".to_string()) {
2082 Some(Json::Array(l)) => {
2083 for field in l.into_iter().rev() {
2084 self.stack.push(field);
2088 return Err(ExpectedError("Array".to_string(), format!("{}", val)))
2091 return Err(MissingFieldError("fields".to_string()))
2097 return Err(ExpectedError("String or Object".to_string(), format!("{}", json)))
2100 let idx = match names.iter()
2101 .position(|n| str::eq_slice(*n, name.as_slice())) {
2103 None => return Err(UnknownVariantError(name))
2108 fn read_enum_variant_arg<T>(&mut self, idx: uint, f: |&mut Decoder| -> DecodeResult<T>)
2109 -> DecodeResult<T> {
2110 debug!("read_enum_variant_arg(idx={})", idx);
2114 fn read_enum_struct_variant<T>(&mut self,
2116 f: |&mut Decoder, uint| -> DecodeResult<T>)
2117 -> DecodeResult<T> {
2118 debug!("read_enum_struct_variant(names={})", names);
2119 self.read_enum_variant(names, f)
2123 fn read_enum_struct_variant_field<T>(&mut self,
2126 f: |&mut Decoder| -> DecodeResult<T>)
2127 -> DecodeResult<T> {
2128 debug!("read_enum_struct_variant_field(name={}, idx={})", name, idx);
2129 self.read_enum_variant_arg(idx, f)
2132 fn read_struct<T>(&mut self,
2135 f: |&mut Decoder| -> DecodeResult<T>)
2136 -> DecodeResult<T> {
2137 debug!("read_struct(name={}, len={})", name, len);
2138 let value = try!(f(self));
2143 fn read_struct_field<T>(&mut self,
2146 f: |&mut Decoder| -> DecodeResult<T>)
2147 -> DecodeResult<T> {
2148 debug!("read_struct_field(name={}, idx={})", name, idx);
2149 let mut obj = try!(expect!(self.pop(), Object));
2151 let value = match obj.remove(&name.to_string()) {
2153 // Add a Null and try to parse it as an Option<_>
2154 // to get None as a default value.
2155 self.stack.push(Json::Null);
2158 Err(_) => return Err(MissingFieldError(name.to_string())),
2162 self.stack.push(json);
2166 self.stack.push(Json::Object(obj));
2170 fn read_tuple<T>(&mut self,
2172 f: |&mut Decoder| -> DecodeResult<T>)
2173 -> DecodeResult<T> {
2174 debug!("read_tuple()");
2175 self.read_seq(|d, len| {
2176 if len == tuple_len {
2179 Err(ExpectedError(format!("Tuple{}", tuple_len), format!("Tuple{}", len)))
2184 fn read_tuple_arg<T>(&mut self,
2186 f: |&mut Decoder| -> DecodeResult<T>) -> DecodeResult<T> {
2187 debug!("read_tuple_arg(idx={})", idx);
2188 self.read_seq_elt(idx, f)
2191 fn read_tuple_struct<T>(&mut self,
2194 f: |&mut Decoder| -> DecodeResult<T>)
2195 -> DecodeResult<T> {
2196 debug!("read_tuple_struct(name={})", name);
2197 self.read_tuple(len, f)
2200 fn read_tuple_struct_arg<T>(&mut self,
2202 f: |&mut Decoder| -> DecodeResult<T>)
2203 -> DecodeResult<T> {
2204 debug!("read_tuple_struct_arg(idx={})", idx);
2205 self.read_tuple_arg(idx, f)
2208 fn read_option<T>(&mut self, f: |&mut Decoder, bool| -> DecodeResult<T>) -> DecodeResult<T> {
2209 debug!("read_option()");
2211 Json::Null => f(self, false),
2212 value => { self.stack.push(value); f(self, true) }
2216 fn read_seq<T>(&mut self, f: |&mut Decoder, uint| -> DecodeResult<T>) -> DecodeResult<T> {
2217 debug!("read_seq()");
2218 let array = try!(expect!(self.pop(), Array));
2219 let len = array.len();
2220 for v in array.into_iter().rev() {
2226 fn read_seq_elt<T>(&mut self,
2228 f: |&mut Decoder| -> DecodeResult<T>) -> DecodeResult<T> {
2229 debug!("read_seq_elt(idx={})", idx);
2233 fn read_map<T>(&mut self, f: |&mut Decoder, uint| -> DecodeResult<T>) -> DecodeResult<T> {
2234 debug!("read_map()");
2235 let obj = try!(expect!(self.pop(), Object));
2236 let len = obj.len();
2237 for (key, value) in obj.into_iter() {
2238 self.stack.push(value);
2239 self.stack.push(Json::String(key));
2244 fn read_map_elt_key<T>(&mut self, idx: uint, f: |&mut Decoder| -> DecodeResult<T>)
2245 -> DecodeResult<T> {
2246 debug!("read_map_elt_key(idx={})", idx);
2250 fn read_map_elt_val<T>(&mut self, idx: uint, f: |&mut Decoder| -> DecodeResult<T>)
2251 -> DecodeResult<T> {
2252 debug!("read_map_elt_val(idx={})", idx);
2256 fn error(&mut self, err: &str) -> DecoderError {
2257 ApplicationError(err.to_string())
2261 /// A trait for converting values to JSON
2262 pub trait ToJson for Sized? {
2263 /// Converts the value of `self` to an instance of JSON
2264 fn to_json(&self) -> Json;
2267 macro_rules! to_json_impl_i64(
2269 $(impl ToJson for $t {
2270 fn to_json(&self) -> Json { Json::I64(*self as i64) }
2275 to_json_impl_i64!(int, i8, i16, i32, i64)
2277 macro_rules! to_json_impl_u64(
2279 $(impl ToJson for $t {
2280 fn to_json(&self) -> Json { Json::U64(*self as u64) }
2285 to_json_impl_u64!(uint, u8, u16, u32, u64)
2287 impl ToJson for Json {
2288 fn to_json(&self) -> Json { self.clone() }
2291 impl ToJson for f32 {
2292 fn to_json(&self) -> Json { (*self as f64).to_json() }
2295 impl ToJson for f64 {
2296 fn to_json(&self) -> Json {
2297 match self.classify() {
2298 FPNaN | FPInfinite => Json::Null,
2299 _ => Json::F64(*self)
2304 impl ToJson for () {
2305 fn to_json(&self) -> Json { Json::Null }
2308 impl ToJson for bool {
2309 fn to_json(&self) -> Json { Json::Boolean(*self) }
2312 impl ToJson for str {
2313 fn to_json(&self) -> Json { Json::String(self.into_string()) }
2316 impl ToJson for string::String {
2317 fn to_json(&self) -> Json { Json::String((*self).clone()) }
2320 macro_rules! tuple_impl {
2321 // use variables to indicate the arity of the tuple
2322 ($($tyvar:ident),* ) => {
2323 // the trailing commas are for the 1 tuple
2325 $( $tyvar : ToJson ),*
2326 > ToJson for ( $( $tyvar ),* , ) {
2329 #[allow(non_snake_case)]
2330 fn to_json(&self) -> Json {
2332 ($(ref $tyvar),*,) => Json::Array(vec![$($tyvar.to_json()),*])
2341 tuple_impl!{A, B, C}
2342 tuple_impl!{A, B, C, D}
2343 tuple_impl!{A, B, C, D, E}
2344 tuple_impl!{A, B, C, D, E, F}
2345 tuple_impl!{A, B, C, D, E, F, G}
2346 tuple_impl!{A, B, C, D, E, F, G, H}
2347 tuple_impl!{A, B, C, D, E, F, G, H, I}
2348 tuple_impl!{A, B, C, D, E, F, G, H, I, J}
2349 tuple_impl!{A, B, C, D, E, F, G, H, I, J, K}
2350 tuple_impl!{A, B, C, D, E, F, G, H, I, J, K, L}
2352 impl<A: ToJson> ToJson for [A] {
2353 fn to_json(&self) -> Json { Json::Array(self.iter().map(|elt| elt.to_json()).collect()) }
2356 impl<A: ToJson> ToJson for Vec<A> {
2357 fn to_json(&self) -> Json { Json::Array(self.iter().map(|elt| elt.to_json()).collect()) }
2360 impl<A: ToJson> ToJson for TreeMap<string::String, A> {
2361 fn to_json(&self) -> Json {
2362 let mut d = TreeMap::new();
2363 for (key, value) in self.iter() {
2364 d.insert((*key).clone(), value.to_json());
2370 impl<A: ToJson> ToJson for HashMap<string::String, A> {
2371 fn to_json(&self) -> Json {
2372 let mut d = TreeMap::new();
2373 for (key, value) in self.iter() {
2374 d.insert((*key).clone(), value.to_json());
2380 impl<A:ToJson> ToJson for Option<A> {
2381 fn to_json(&self) -> Json {
2384 Some(ref value) => value.to_json()
2389 impl fmt::Show for Json {
2390 /// Encodes a json value into a string
2391 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2392 self.to_writer(f).map_err(|_| fmt::Error)
2396 impl FromStr for Json {
2397 fn from_str(s: &str) -> Option<Json> {
2405 use self::Animal::*;
2406 use self::DecodeEnum::*;
2407 use self::test::Bencher;
2408 use {Encodable, Decodable};
2410 use super::ErrorCode::*;
2411 use super::ParserError::*;
2412 use super::DecoderError::*;
2413 use super::JsonEvent::*;
2414 use super::ParserState::*;
2415 use super::StackElement::*;
2416 use super::InternalStackElement::*;
2417 use super::{PrettyEncoder, Json, from_str, DecodeResult, DecoderError, JsonEvent, Parser,
2418 StackElement, Stack, Encoder, Decoder};
2419 use std::{i64, u64, f32, f64, io};
2420 use std::collections::TreeMap;
2421 use std::num::Float;
2424 #[deriving(Decodable, Eq, PartialEq, Show)]
2430 fn test_decode_option_none() {
2432 let obj: OptionData = super::decode(s).unwrap();
2433 assert_eq!(obj, OptionData { opt: None });
2437 fn test_decode_option_some() {
2438 let s = "{ \"opt\": 10 }";
2439 let obj: OptionData = super::decode(s).unwrap();
2440 assert_eq!(obj, OptionData { opt: Some(10u) });
2444 fn test_decode_option_malformed() {
2445 check_err::<OptionData>("{ \"opt\": [] }",
2446 ExpectedError("Number".to_string(), "[]".to_string()));
2447 check_err::<OptionData>("{ \"opt\": false }",
2448 ExpectedError("Number".to_string(), "false".to_string()));
2451 #[deriving(PartialEq, Encodable, Decodable, Show)]
2454 Frog(string::String, int)
2457 #[deriving(PartialEq, Encodable, Decodable, Show)]
2461 c: Vec<string::String>,
2464 #[deriving(PartialEq, Encodable, Decodable, Show)]
2469 fn mk_object(items: &[(string::String, Json)]) -> Json {
2470 let mut d = TreeMap::new();
2472 for item in items.iter() {
2474 (ref key, ref value) => { d.insert((*key).clone(), (*value).clone()); },
2482 fn test_from_str_trait() {
2484 assert!(::std::str::from_str::<Json>(s).unwrap() == from_str(s).unwrap());
2488 fn test_write_null() {
2489 assert_eq!(Null.to_string().into_string(), "null");
2490 assert_eq!(Null.to_pretty_str().into_string(), "null");
2494 fn test_write_i64() {
2495 assert_eq!(U64(0).to_string().into_string(), "0");
2496 assert_eq!(U64(0).to_pretty_str().into_string(), "0");
2498 assert_eq!(U64(1234).to_string().into_string(), "1234");
2499 assert_eq!(U64(1234).to_pretty_str().into_string(), "1234");
2501 assert_eq!(I64(-5678).to_string().into_string(), "-5678");
2502 assert_eq!(I64(-5678).to_pretty_str().into_string(), "-5678");
2504 assert_eq!(U64(7650007200025252000).to_string(), "7650007200025252000");
2505 assert_eq!(U64(7650007200025252000).to_pretty_str(), "7650007200025252000");
2509 fn test_write_f64() {
2510 assert_eq!(F64(3.0).to_string().into_string(), "3");
2511 assert_eq!(F64(3.0).to_pretty_str().into_string(), "3");
2513 assert_eq!(F64(3.1).to_string().into_string(), "3.1");
2514 assert_eq!(F64(3.1).to_pretty_str().into_string(), "3.1");
2516 assert_eq!(F64(-1.5).to_string().into_string(), "-1.5");
2517 assert_eq!(F64(-1.5).to_pretty_str().into_string(), "-1.5");
2519 assert_eq!(F64(0.5).to_string().into_string(), "0.5");
2520 assert_eq!(F64(0.5).to_pretty_str().into_string(), "0.5");
2522 assert_eq!(F64(f64::NAN).to_string().into_string(), "null");
2523 assert_eq!(F64(f64::NAN).to_pretty_str().into_string(), "null");
2525 assert_eq!(F64(f64::INFINITY).to_string().into_string(), "null");
2526 assert_eq!(F64(f64::INFINITY).to_pretty_str().into_string(), "null");
2528 assert_eq!(F64(f64::NEG_INFINITY).to_string().into_string(), "null");
2529 assert_eq!(F64(f64::NEG_INFINITY).to_pretty_str().into_string(), "null");
2533 fn test_write_str() {
2534 assert_eq!(String("".to_string()).to_string().into_string(), "\"\"");
2535 assert_eq!(String("".to_string()).to_pretty_str().into_string(), "\"\"");
2537 assert_eq!(String("foo".to_string()).to_string().into_string(), "\"foo\"");
2538 assert_eq!(String("foo".to_string()).to_pretty_str().into_string(), "\"foo\"");
2542 fn test_write_bool() {
2543 assert_eq!(Boolean(true).to_string().into_string(), "true");
2544 assert_eq!(Boolean(true).to_pretty_str().into_string(), "true");
2546 assert_eq!(Boolean(false).to_string().into_string(), "false");
2547 assert_eq!(Boolean(false).to_pretty_str().into_string(), "false");
2551 fn test_write_array() {
2552 assert_eq!(Array(vec![]).to_string().into_string(), "[]");
2553 assert_eq!(Array(vec![]).to_pretty_str().into_string(), "[]");
2555 assert_eq!(Array(vec![Boolean(true)]).to_string().into_string(), "[true]");
2557 Array(vec![Boolean(true)]).to_pretty_str().into_string(),
2564 let long_test_array = Array(vec![
2567 Array(vec![String("foo\nbar".to_string()), F64(3.5)])]);
2569 assert_eq!(long_test_array.to_string().into_string(),
2570 "[false,null,[\"foo\\nbar\",3.5]]");
2572 long_test_array.to_pretty_str().into_string(),
2586 fn test_write_object() {
2587 assert_eq!(mk_object(&[]).to_string().into_string(), "{}");
2588 assert_eq!(mk_object(&[]).to_pretty_str().into_string(), "{}");
2592 ("a".to_string(), Boolean(true))
2593 ]).to_string().into_string(),
2597 mk_object(&[("a".to_string(), Boolean(true))]).to_pretty_str(),
2604 let complex_obj = mk_object(&[
2605 ("b".to_string(), Array(vec![
2606 mk_object(&[("c".to_string(), String("\x0c\r".to_string()))]),
2607 mk_object(&[("d".to_string(), String("".to_string()))])
2612 complex_obj.to_string().into_string(),
2615 {\"c\":\"\\f\\r\"},\
2621 complex_obj.to_pretty_str().into_string(),
2626 \"c\": \"\\f\\r\"\n \
2635 let a = mk_object(&[
2636 ("a".to_string(), Boolean(true)),
2637 ("b".to_string(), Array(vec![
2638 mk_object(&[("c".to_string(), String("\x0c\r".to_string()))]),
2639 mk_object(&[("d".to_string(), String("".to_string()))])
2643 // We can't compare the strings directly because the object fields be
2644 // printed in a different order.
2645 assert_eq!(a.clone(), from_str(a.to_string().as_slice()).unwrap());
2646 assert_eq!(a.clone(),
2647 from_str(a.to_pretty_str().as_slice()).unwrap());
2650 fn with_str_writer(f: |&mut io::Writer|) -> string::String {
2653 let mut m = Vec::new();
2654 f(&mut m as &mut io::Writer);
2655 string::String::from_utf8(m).unwrap()
2659 fn test_write_enum() {
2662 with_str_writer(|writer| {
2663 let mut encoder = Encoder::new(writer);
2664 animal.encode(&mut encoder).unwrap();
2669 with_str_writer(|writer| {
2670 let mut encoder = PrettyEncoder::new(writer);
2671 animal.encode(&mut encoder).unwrap();
2676 let animal = Frog("Henry".to_string(), 349);
2678 with_str_writer(|writer| {
2679 let mut encoder = Encoder::new(writer);
2680 animal.encode(&mut encoder).unwrap();
2682 "{\"variant\":\"Frog\",\"fields\":[\"Henry\",349]}"
2685 with_str_writer(|writer| {
2686 let mut encoder = PrettyEncoder::new(writer);
2687 animal.encode(&mut encoder).unwrap();
2690 \"variant\": \"Frog\",\n \
2700 fn test_write_some() {
2701 let value = Some("jodhpurs".to_string());
2702 let s = with_str_writer(|writer| {
2703 let mut encoder = Encoder::new(writer);
2704 value.encode(&mut encoder).unwrap();
2706 assert_eq!(s, "\"jodhpurs\"");
2708 let value = Some("jodhpurs".to_string());
2709 let s = with_str_writer(|writer| {
2710 let mut encoder = PrettyEncoder::new(writer);
2711 value.encode(&mut encoder).unwrap();
2713 assert_eq!(s, "\"jodhpurs\"");
2717 fn test_write_none() {
2718 let value: Option<string::String> = None;
2719 let s = with_str_writer(|writer| {
2720 let mut encoder = Encoder::new(writer);
2721 value.encode(&mut encoder).unwrap();
2723 assert_eq!(s, "null");
2725 let s = with_str_writer(|writer| {
2726 let mut encoder = Encoder::new(writer);
2727 value.encode(&mut encoder).unwrap();
2729 assert_eq!(s, "null");
2733 fn test_trailing_characters() {
2734 assert_eq!(from_str("nulla"), Err(SyntaxError(TrailingCharacters, 1, 5)));
2735 assert_eq!(from_str("truea"), Err(SyntaxError(TrailingCharacters, 1, 5)));
2736 assert_eq!(from_str("falsea"), Err(SyntaxError(TrailingCharacters, 1, 6)));
2737 assert_eq!(from_str("1a"), Err(SyntaxError(TrailingCharacters, 1, 2)));
2738 assert_eq!(from_str("[]a"), Err(SyntaxError(TrailingCharacters, 1, 3)));
2739 assert_eq!(from_str("{}a"), Err(SyntaxError(TrailingCharacters, 1, 3)));
2743 fn test_read_identifiers() {
2744 assert_eq!(from_str("n"), Err(SyntaxError(InvalidSyntax, 1, 2)));
2745 assert_eq!(from_str("nul"), Err(SyntaxError(InvalidSyntax, 1, 4)));
2746 assert_eq!(from_str("t"), Err(SyntaxError(InvalidSyntax, 1, 2)));
2747 assert_eq!(from_str("truz"), Err(SyntaxError(InvalidSyntax, 1, 4)));
2748 assert_eq!(from_str("f"), Err(SyntaxError(InvalidSyntax, 1, 2)));
2749 assert_eq!(from_str("faz"), Err(SyntaxError(InvalidSyntax, 1, 3)));
2751 assert_eq!(from_str("null"), Ok(Null));
2752 assert_eq!(from_str("true"), Ok(Boolean(true)));
2753 assert_eq!(from_str("false"), Ok(Boolean(false)));
2754 assert_eq!(from_str(" null "), Ok(Null));
2755 assert_eq!(from_str(" true "), Ok(Boolean(true)));
2756 assert_eq!(from_str(" false "), Ok(Boolean(false)));
2760 fn test_decode_identifiers() {
2761 let v: () = super::decode("null").unwrap();
2764 let v: bool = super::decode("true").unwrap();
2765 assert_eq!(v, true);
2767 let v: bool = super::decode("false").unwrap();
2768 assert_eq!(v, false);
2772 fn test_read_number() {
2773 assert_eq!(from_str("+"), Err(SyntaxError(InvalidSyntax, 1, 1)));
2774 assert_eq!(from_str("."), Err(SyntaxError(InvalidSyntax, 1, 1)));
2775 assert_eq!(from_str("NaN"), Err(SyntaxError(InvalidSyntax, 1, 1)));
2776 assert_eq!(from_str("-"), Err(SyntaxError(InvalidNumber, 1, 2)));
2777 assert_eq!(from_str("00"), Err(SyntaxError(InvalidNumber, 1, 2)));
2778 assert_eq!(from_str("1."), Err(SyntaxError(InvalidNumber, 1, 3)));
2779 assert_eq!(from_str("1e"), Err(SyntaxError(InvalidNumber, 1, 3)));
2780 assert_eq!(from_str("1e+"), Err(SyntaxError(InvalidNumber, 1, 4)));
2782 assert_eq!(from_str("18446744073709551616"), Err(SyntaxError(InvalidNumber, 1, 20)));
2783 assert_eq!(from_str("-9223372036854775809"), Err(SyntaxError(InvalidNumber, 1, 21)));
2785 assert_eq!(from_str("3"), Ok(U64(3)));
2786 assert_eq!(from_str("3.1"), Ok(F64(3.1)));
2787 assert_eq!(from_str("-1.2"), Ok(F64(-1.2)));
2788 assert_eq!(from_str("0.4"), Ok(F64(0.4)));
2789 assert_eq!(from_str("0.4e5"), Ok(F64(0.4e5)));
2790 assert_eq!(from_str("0.4e+15"), Ok(F64(0.4e15)));
2791 assert_eq!(from_str("0.4e-01"), Ok(F64(0.4e-01)));
2792 assert_eq!(from_str(" 3 "), Ok(U64(3)));
2794 assert_eq!(from_str("-9223372036854775808"), Ok(I64(i64::MIN)));
2795 assert_eq!(from_str("9223372036854775807"), Ok(U64(i64::MAX as u64)));
2796 assert_eq!(from_str("18446744073709551615"), Ok(U64(u64::MAX)));
2800 fn test_decode_numbers() {
2801 let v: f64 = super::decode("3").unwrap();
2804 let v: f64 = super::decode("3.1").unwrap();
2807 let v: f64 = super::decode("-1.2").unwrap();
2808 assert_eq!(v, -1.2);
2810 let v: f64 = super::decode("0.4").unwrap();
2813 let v: f64 = super::decode("0.4e5").unwrap();
2814 assert_eq!(v, 0.4e5);
2816 let v: f64 = super::decode("0.4e15").unwrap();
2817 assert_eq!(v, 0.4e15);
2819 let v: f64 = super::decode("0.4e-01").unwrap();
2820 assert_eq!(v, 0.4e-01);
2822 let v: u64 = super::decode("0").unwrap();
2825 let v: u64 = super::decode("18446744073709551615").unwrap();
2826 assert_eq!(v, u64::MAX);
2828 let v: i64 = super::decode("-9223372036854775808").unwrap();
2829 assert_eq!(v, i64::MIN);
2831 let v: i64 = super::decode("9223372036854775807").unwrap();
2832 assert_eq!(v, i64::MAX);
2836 fn test_read_str() {
2837 assert_eq!(from_str("\""), Err(SyntaxError(EOFWhileParsingString, 1, 2)));
2838 assert_eq!(from_str("\"lol"), Err(SyntaxError(EOFWhileParsingString, 1, 5)));
2840 assert_eq!(from_str("\"\""), Ok(String("".to_string())));
2841 assert_eq!(from_str("\"foo\""), Ok(String("foo".to_string())));
2842 assert_eq!(from_str("\"\\\"\""), Ok(String("\"".to_string())));
2843 assert_eq!(from_str("\"\\b\""), Ok(String("\x08".to_string())));
2844 assert_eq!(from_str("\"\\n\""), Ok(String("\n".to_string())));
2845 assert_eq!(from_str("\"\\r\""), Ok(String("\r".to_string())));
2846 assert_eq!(from_str("\"\\t\""), Ok(String("\t".to_string())));
2847 assert_eq!(from_str(" \"foo\" "), Ok(String("foo".to_string())));
2848 assert_eq!(from_str("\"\\u12ab\""), Ok(String("\u12ab".to_string())));
2849 assert_eq!(from_str("\"\\uAB12\""), Ok(String("\uAB12".to_string())));
2853 fn test_decode_str() {
2854 let s = [("\"\"", ""),
2857 ("\"\\b\"", "\x08"),
2861 ("\"\\u12ab\"", "\u12ab"),
2862 ("\"\\uAB12\"", "\uAB12")];
2864 for &(i, o) in s.iter() {
2865 let v: string::String = super::decode(i).unwrap();
2871 fn test_read_array() {
2872 assert_eq!(from_str("["), Err(SyntaxError(EOFWhileParsingValue, 1, 2)));
2873 assert_eq!(from_str("[1"), Err(SyntaxError(EOFWhileParsingArray, 1, 3)));
2874 assert_eq!(from_str("[1,"), Err(SyntaxError(EOFWhileParsingValue, 1, 4)));
2875 assert_eq!(from_str("[1,]"), Err(SyntaxError(InvalidSyntax, 1, 4)));
2876 assert_eq!(from_str("[6 7]"), Err(SyntaxError(InvalidSyntax, 1, 4)));
2878 assert_eq!(from_str("[]"), Ok(Array(vec![])));
2879 assert_eq!(from_str("[ ]"), Ok(Array(vec![])));
2880 assert_eq!(from_str("[true]"), Ok(Array(vec![Boolean(true)])));
2881 assert_eq!(from_str("[ false ]"), Ok(Array(vec![Boolean(false)])));
2882 assert_eq!(from_str("[null]"), Ok(Array(vec![Null])));
2883 assert_eq!(from_str("[3, 1]"),
2884 Ok(Array(vec![U64(3), U64(1)])));
2885 assert_eq!(from_str("\n[3, 2]\n"),
2886 Ok(Array(vec![U64(3), U64(2)])));
2887 assert_eq!(from_str("[2, [4, 1]]"),
2888 Ok(Array(vec![U64(2), Array(vec![U64(4), U64(1)])])));
2892 fn test_decode_array() {
2893 let v: Vec<()> = super::decode("[]").unwrap();
2894 assert_eq!(v, vec![]);
2896 let v: Vec<()> = super::decode("[null]").unwrap();
2897 assert_eq!(v, vec![()]);
2899 let v: Vec<bool> = super::decode("[true]").unwrap();
2900 assert_eq!(v, vec![true]);
2902 let v: Vec<int> = super::decode("[3, 1]").unwrap();
2903 assert_eq!(v, vec![3, 1]);
2905 let v: Vec<Vec<uint>> = super::decode("[[3], [1, 2]]").unwrap();
2906 assert_eq!(v, vec![vec![3], vec![1, 2]]);
2910 fn test_decode_tuple() {
2911 let t: (uint, uint, uint) = super::decode("[1, 2, 3]").unwrap();
2912 assert_eq!(t, (1u, 2, 3))
2914 let t: (uint, string::String) = super::decode("[1, \"two\"]").unwrap();
2915 assert_eq!(t, (1u, "two".to_string()));
2919 fn test_decode_tuple_malformed_types() {
2920 assert!(super::decode::<(uint, string::String)>("[1, 2]").is_err());
2924 fn test_decode_tuple_malformed_length() {
2925 assert!(super::decode::<(uint, uint)>("[1, 2, 3]").is_err());
2929 fn test_read_object() {
2930 assert_eq!(from_str("{"), Err(SyntaxError(EOFWhileParsingObject, 1, 2)));
2931 assert_eq!(from_str("{ "), Err(SyntaxError(EOFWhileParsingObject, 1, 3)));
2932 assert_eq!(from_str("{1"), Err(SyntaxError(KeyMustBeAString, 1, 2)));
2933 assert_eq!(from_str("{ \"a\""), Err(SyntaxError(EOFWhileParsingObject, 1, 6)));
2934 assert_eq!(from_str("{\"a\""), Err(SyntaxError(EOFWhileParsingObject, 1, 5)));
2935 assert_eq!(from_str("{\"a\" "), Err(SyntaxError(EOFWhileParsingObject, 1, 6)));
2937 assert_eq!(from_str("{\"a\" 1"), Err(SyntaxError(ExpectedColon, 1, 6)));
2938 assert_eq!(from_str("{\"a\":"), Err(SyntaxError(EOFWhileParsingValue, 1, 6)));
2939 assert_eq!(from_str("{\"a\":1"), Err(SyntaxError(EOFWhileParsingObject, 1, 7)));
2940 assert_eq!(from_str("{\"a\":1 1"), Err(SyntaxError(InvalidSyntax, 1, 8)));
2941 assert_eq!(from_str("{\"a\":1,"), Err(SyntaxError(EOFWhileParsingObject, 1, 8)));
2943 assert_eq!(from_str("{}").unwrap(), mk_object(&[]));
2944 assert_eq!(from_str("{\"a\": 3}").unwrap(),
2945 mk_object(&[("a".to_string(), U64(3))]));
2947 assert_eq!(from_str(
2948 "{ \"a\": null, \"b\" : true }").unwrap(),
2950 ("a".to_string(), Null),
2951 ("b".to_string(), Boolean(true))]));
2952 assert_eq!(from_str("\n{ \"a\": null, \"b\" : true }\n").unwrap(),
2954 ("a".to_string(), Null),
2955 ("b".to_string(), Boolean(true))]));
2956 assert_eq!(from_str(
2957 "{\"a\" : 1.0 ,\"b\": [ true ]}").unwrap(),
2959 ("a".to_string(), F64(1.0)),
2960 ("b".to_string(), Array(vec![Boolean(true)]))
2962 assert_eq!(from_str(
2968 { \"c\": {\"d\": null} } \
2972 ("a".to_string(), F64(1.0)),
2973 ("b".to_string(), Array(vec![
2975 String("foo\nbar".to_string()),
2977 ("c".to_string(), mk_object(&[("d".to_string(), Null)]))
2984 fn test_decode_struct() {
2987 { \"a\": null, \"b\": 2, \"c\": [\"abc\", \"xyz\"] }
2991 let v: Outer = super::decode(s).unwrap();
2996 Inner { a: (), b: 2, c: vec!["abc".to_string(), "xyz".to_string()] }
3002 #[deriving(Decodable)]
3003 struct FloatStruct {
3008 fn test_decode_struct_with_nan() {
3009 let s = "{\"f\":null,\"a\":[null,123]}";
3010 let obj: FloatStruct = super::decode(s).unwrap();
3011 assert!(obj.f.is_nan());
3012 assert!(obj.a[0].is_nan());
3013 assert_eq!(obj.a[1], 123f64);
3017 fn test_decode_option() {
3018 let value: Option<string::String> = super::decode("null").unwrap();
3019 assert_eq!(value, None);
3021 let value: Option<string::String> = super::decode("\"jodhpurs\"").unwrap();
3022 assert_eq!(value, Some("jodhpurs".to_string()));
3026 fn test_decode_enum() {
3027 let value: Animal = super::decode("\"Dog\"").unwrap();
3028 assert_eq!(value, Dog);
3030 let s = "{\"variant\":\"Frog\",\"fields\":[\"Henry\",349]}";
3031 let value: Animal = super::decode(s).unwrap();
3032 assert_eq!(value, Frog("Henry".to_string(), 349));
3036 fn test_decode_map() {
3037 let s = "{\"a\": \"Dog\", \"b\": {\"variant\":\"Frog\",\
3038 \"fields\":[\"Henry\", 349]}}";
3039 let mut map: TreeMap<string::String, Animal> = super::decode(s).unwrap();
3041 assert_eq!(map.remove(&"a".to_string()), Some(Dog));
3042 assert_eq!(map.remove(&"b".to_string()), Some(Frog("Henry".to_string(), 349)));
3046 fn test_multiline_errors() {
3047 assert_eq!(from_str("{\n \"foo\":\n \"bar\""),
3048 Err(SyntaxError(EOFWhileParsingObject, 3u, 8u)));
3051 #[deriving(Decodable)]
3053 struct DecodeStruct {
3057 w: Vec<DecodeStruct>
3059 #[deriving(Decodable)]
3064 fn check_err<T: Decodable<Decoder, DecoderError>>(to_parse: &'static str,
3065 expected: DecoderError) {
3066 let res: DecodeResult<T> = match from_str(to_parse) {
3067 Err(e) => Err(ParseError(e)),
3068 Ok(json) => Decodable::decode(&mut Decoder::new(json))
3071 Ok(_) => panic!("`{}` parsed & decoded ok, expecting error `{}`",
3072 to_parse, expected),
3073 Err(ParseError(e)) => panic!("`{}` is not valid json: {}",
3076 assert_eq!(e, expected);
3081 fn test_decode_errors_struct() {
3082 check_err::<DecodeStruct>("[]", ExpectedError("Object".to_string(), "[]".to_string()));
3083 check_err::<DecodeStruct>("{\"x\": true, \"y\": true, \"z\": \"\", \"w\": []}",
3084 ExpectedError("Number".to_string(), "true".to_string()));
3085 check_err::<DecodeStruct>("{\"x\": 1, \"y\": [], \"z\": \"\", \"w\": []}",
3086 ExpectedError("Boolean".to_string(), "[]".to_string()));
3087 check_err::<DecodeStruct>("{\"x\": 1, \"y\": true, \"z\": {}, \"w\": []}",
3088 ExpectedError("String".to_string(), "{}".to_string()));
3089 check_err::<DecodeStruct>("{\"x\": 1, \"y\": true, \"z\": \"\", \"w\": null}",
3090 ExpectedError("Array".to_string(), "null".to_string()));
3091 check_err::<DecodeStruct>("{\"x\": 1, \"y\": true, \"z\": \"\"}",
3092 MissingFieldError("w".to_string()));
3095 fn test_decode_errors_enum() {
3096 check_err::<DecodeEnum>("{}",
3097 MissingFieldError("variant".to_string()));
3098 check_err::<DecodeEnum>("{\"variant\": 1}",
3099 ExpectedError("String".to_string(), "1".to_string()));
3100 check_err::<DecodeEnum>("{\"variant\": \"A\"}",
3101 MissingFieldError("fields".to_string()));
3102 check_err::<DecodeEnum>("{\"variant\": \"A\", \"fields\": null}",
3103 ExpectedError("Array".to_string(), "null".to_string()));
3104 check_err::<DecodeEnum>("{\"variant\": \"C\", \"fields\": []}",
3105 UnknownVariantError("C".to_string()));
3110 let json_value = from_str("{\"dog\" : \"cat\"}").unwrap();
3111 let found_str = json_value.find("dog");
3112 assert!(found_str.unwrap().as_string().unwrap() == "cat");
3116 fn test_find_path(){
3117 let json_value = from_str("{\"dog\":{\"cat\": {\"mouse\" : \"cheese\"}}}").unwrap();
3118 let found_str = json_value.find_path(&["dog", "cat", "mouse"]);
3119 assert!(found_str.unwrap().as_string().unwrap() == "cheese");
3124 let json_value = from_str("{\"dog\":{\"cat\": {\"mouse\" : \"cheese\"}}}").unwrap();
3125 let found_str = json_value.search("mouse").and_then(|j| j.as_string());
3126 assert!(found_str.unwrap() == "cheese");
3131 let json_value = from_str("{\"animals\":[\"dog\",\"cat\",\"mouse\"]}").unwrap();
3132 let ref array = json_value["animals"];
3133 assert_eq!(array[0].as_string().unwrap(), "dog");
3134 assert_eq!(array[1].as_string().unwrap(), "cat");
3135 assert_eq!(array[2].as_string().unwrap(), "mouse");
3139 fn test_is_object(){
3140 let json_value = from_str("{}").unwrap();
3141 assert!(json_value.is_object());
3145 fn test_as_object(){
3146 let json_value = from_str("{}").unwrap();
3147 let json_object = json_value.as_object();
3148 assert!(json_object.is_some());
3153 let json_value = from_str("[1, 2, 3]").unwrap();
3154 assert!(json_value.is_array());
3159 let json_value = from_str("[1, 2, 3]").unwrap();
3160 let json_array = json_value.as_array();
3161 let expected_length = 3;
3162 assert!(json_array.is_some() && json_array.unwrap().len() == expected_length);
3166 fn test_is_string(){
3167 let json_value = from_str("\"dog\"").unwrap();
3168 assert!(json_value.is_string());
3172 fn test_as_string(){
3173 let json_value = from_str("\"dog\"").unwrap();
3174 let json_str = json_value.as_string();
3175 let expected_str = "dog";
3176 assert_eq!(json_str, Some(expected_str));
3180 fn test_is_number(){
3181 let json_value = from_str("12").unwrap();
3182 assert!(json_value.is_number());
3187 let json_value = from_str("-12").unwrap();
3188 assert!(json_value.is_i64());
3190 let json_value = from_str("12").unwrap();
3191 assert!(!json_value.is_i64());
3193 let json_value = from_str("12.0").unwrap();
3194 assert!(!json_value.is_i64());
3199 let json_value = from_str("12").unwrap();
3200 assert!(json_value.is_u64());
3202 let json_value = from_str("-12").unwrap();
3203 assert!(!json_value.is_u64());
3205 let json_value = from_str("12.0").unwrap();
3206 assert!(!json_value.is_u64());
3211 let json_value = from_str("12").unwrap();
3212 assert!(!json_value.is_f64());
3214 let json_value = from_str("-12").unwrap();
3215 assert!(!json_value.is_f64());
3217 let json_value = from_str("12.0").unwrap();
3218 assert!(json_value.is_f64());
3220 let json_value = from_str("-12.0").unwrap();
3221 assert!(json_value.is_f64());
3226 let json_value = from_str("-12").unwrap();
3227 let json_num = json_value.as_i64();
3228 assert_eq!(json_num, Some(-12));
3233 let json_value = from_str("12").unwrap();
3234 let json_num = json_value.as_u64();
3235 assert_eq!(json_num, Some(12));
3240 let json_value = from_str("12.0").unwrap();
3241 let json_num = json_value.as_f64();
3242 assert_eq!(json_num, Some(12f64));
3246 fn test_is_boolean(){
3247 let json_value = from_str("false").unwrap();
3248 assert!(json_value.is_boolean());
3252 fn test_as_boolean(){
3253 let json_value = from_str("false").unwrap();
3254 let json_bool = json_value.as_boolean();
3255 let expected_bool = false;
3256 assert!(json_bool.is_some() && json_bool.unwrap() == expected_bool);
3261 let json_value = from_str("null").unwrap();
3262 assert!(json_value.is_null());
3267 let json_value = from_str("null").unwrap();
3268 let json_null = json_value.as_null();
3269 let expected_null = ();
3270 assert!(json_null.is_some() && json_null.unwrap() == expected_null);
3274 fn test_encode_hashmap_with_numeric_key() {
3275 use std::str::from_utf8;
3276 use std::io::Writer;
3277 use std::collections::HashMap;
3278 let mut hm: HashMap<uint, bool> = HashMap::new();
3280 let mut mem_buf = Vec::new();
3282 let mut encoder = Encoder::new(&mut mem_buf as &mut io::Writer);
3283 hm.encode(&mut encoder).unwrap();
3285 let json_str = from_utf8(mem_buf[]).unwrap();
3286 match from_str(json_str) {
3287 Err(_) => panic!("Unable to parse json_str: {}", json_str),
3288 _ => {} // it parsed and we are good to go
3293 fn test_prettyencode_hashmap_with_numeric_key() {
3294 use std::str::from_utf8;
3295 use std::io::Writer;
3296 use std::collections::HashMap;
3297 let mut hm: HashMap<uint, bool> = HashMap::new();
3299 let mut mem_buf = Vec::new();
3301 let mut encoder = PrettyEncoder::new(&mut mem_buf as &mut io::Writer);
3302 hm.encode(&mut encoder).unwrap()
3304 let json_str = from_utf8(mem_buf[]).unwrap();
3305 match from_str(json_str) {
3306 Err(_) => panic!("Unable to parse json_str: {}", json_str),
3307 _ => {} // it parsed and we are good to go
3312 fn test_prettyencoder_indent_level_param() {
3313 use std::str::from_utf8;
3314 use std::collections::TreeMap;
3316 let mut tree = TreeMap::new();
3318 tree.insert("hello".into_string(), String("guten tag".into_string()));
3319 tree.insert("goodbye".into_string(), String("sayonara".into_string()));
3322 // The following layout below should look a lot like
3323 // the pretty-printed JSON (indent * x)
3326 String("greetings".into_string()), // 1x
3327 Object(tree), // 1x + 2x + 2x + 1x
3329 // End JSON array (7 lines)
3332 // Helper function for counting indents
3333 fn indents(source: &str) -> uint {
3334 let trimmed = source.trim_left_chars(' ');
3335 source.len() - trimmed.len()
3338 // Test up to 4 spaces of indents (more?)
3339 for i in range(0, 4u) {
3340 let mut writer = Vec::new();
3342 let ref mut encoder = PrettyEncoder::new(&mut writer);
3343 encoder.set_indent(i);
3344 json.encode(encoder).unwrap();
3347 let printed = from_utf8(writer[]).unwrap();
3349 // Check for indents at each line
3350 let lines: Vec<&str> = printed.lines().collect();
3351 assert_eq!(lines.len(), 7); // JSON should be 7 lines
3353 assert_eq!(indents(lines[0]), 0 * i); // [
3354 assert_eq!(indents(lines[1]), 1 * i); // "greetings",
3355 assert_eq!(indents(lines[2]), 1 * i); // {
3356 assert_eq!(indents(lines[3]), 2 * i); // "hello": "guten tag",
3357 assert_eq!(indents(lines[4]), 2 * i); // "goodbye": "sayonara"
3358 assert_eq!(indents(lines[5]), 1 * i); // },
3359 assert_eq!(indents(lines[6]), 0 * i); // ]
3361 // Finally, test that the pretty-printed JSON is valid
3362 from_str(printed).ok().expect("Pretty-printed JSON is invalid!");
3367 fn test_hashmap_with_numeric_key_can_handle_double_quote_delimited_key() {
3368 use std::collections::HashMap;
3370 let json_str = "{\"1\":true}";
3371 let json_obj = match from_str(json_str) {
3372 Err(_) => panic!("Unable to parse json_str: {}", json_str),
3375 let mut decoder = Decoder::new(json_obj);
3376 let _hm: HashMap<uint, bool> = Decodable::decode(&mut decoder).unwrap();
3380 fn test_hashmap_with_numeric_key_will_error_with_string_keys() {
3381 use std::collections::HashMap;
3383 let json_str = "{\"a\":true}";
3384 let json_obj = match from_str(json_str) {
3385 Err(_) => panic!("Unable to parse json_str: {}", json_str),
3388 let mut decoder = Decoder::new(json_obj);
3389 let result: Result<HashMap<uint, bool>, DecoderError> = Decodable::decode(&mut decoder);
3390 assert_eq!(result, Err(ExpectedError("Number".to_string(), "a".to_string())));
3393 fn assert_stream_equal(src: &str,
3394 expected: Vec<(JsonEvent, Vec<StackElement>)>) {
3395 let mut parser = Parser::new(src.chars());
3398 let evt = match parser.next() {
3402 let (ref expected_evt, ref expected_stack) = expected[i];
3403 if !parser.stack().is_equal_to(expected_stack.as_slice()) {
3404 panic!("Parser stack is not equal to {}", expected_stack);
3406 assert_eq!(&evt, expected_evt);
3411 #[cfg_attr(target_word_size = "32", ignore)] // FIXME(#14064)
3412 fn test_streaming_parser() {
3413 assert_stream_equal(
3414 r#"{ "foo":"bar", "array" : [0, 1, 2, 3, 4, 5], "idents":[null,true,false]}"#,
3416 (ObjectStart, vec![]),
3417 (StringValue("bar".to_string()), vec![Key("foo")]),
3418 (ArrayStart, vec![Key("array")]),
3419 (U64Value(0), vec![Key("array"), Index(0)]),
3420 (U64Value(1), vec![Key("array"), Index(1)]),
3421 (U64Value(2), vec![Key("array"), Index(2)]),
3422 (U64Value(3), vec![Key("array"), Index(3)]),
3423 (U64Value(4), vec![Key("array"), Index(4)]),
3424 (U64Value(5), vec![Key("array"), Index(5)]),
3425 (ArrayEnd, vec![Key("array")]),
3426 (ArrayStart, vec![Key("idents")]),
3427 (NullValue, vec![Key("idents"), Index(0)]),
3428 (BooleanValue(true), vec![Key("idents"), Index(1)]),
3429 (BooleanValue(false), vec![Key("idents"), Index(2)]),
3430 (ArrayEnd, vec![Key("idents")]),
3431 (ObjectEnd, vec![]),
3435 fn last_event(src: &str) -> JsonEvent {
3436 let mut parser = Parser::new(src.chars());
3437 let mut evt = NullValue;
3439 evt = match parser.next() {
3447 #[cfg_attr(target_word_size = "32", ignore)] // FIXME(#14064)
3448 fn test_read_object_streaming() {
3449 assert_eq!(last_event("{ "), Error(SyntaxError(EOFWhileParsingObject, 1, 3)));
3450 assert_eq!(last_event("{1"), Error(SyntaxError(KeyMustBeAString, 1, 2)));
3451 assert_eq!(last_event("{ \"a\""), Error(SyntaxError(EOFWhileParsingObject, 1, 6)));
3452 assert_eq!(last_event("{\"a\""), Error(SyntaxError(EOFWhileParsingObject, 1, 5)));
3453 assert_eq!(last_event("{\"a\" "), Error(SyntaxError(EOFWhileParsingObject, 1, 6)));
3455 assert_eq!(last_event("{\"a\" 1"), Error(SyntaxError(ExpectedColon, 1, 6)));
3456 assert_eq!(last_event("{\"a\":"), Error(SyntaxError(EOFWhileParsingValue, 1, 6)));
3457 assert_eq!(last_event("{\"a\":1"), Error(SyntaxError(EOFWhileParsingObject, 1, 7)));
3458 assert_eq!(last_event("{\"a\":1 1"), Error(SyntaxError(InvalidSyntax, 1, 8)));
3459 assert_eq!(last_event("{\"a\":1,"), Error(SyntaxError(EOFWhileParsingObject, 1, 8)));
3460 assert_eq!(last_event("{\"a\":1,}"), Error(SyntaxError(TrailingComma, 1, 8)));
3462 assert_stream_equal(
3464 vec![(ObjectStart, vec![]), (ObjectEnd, vec![])]
3466 assert_stream_equal(
3469 (ObjectStart, vec![]),
3470 (U64Value(3), vec![Key("a")]),
3471 (ObjectEnd, vec![]),
3474 assert_stream_equal(
3475 "{ \"a\": null, \"b\" : true }",
3477 (ObjectStart, vec![]),
3478 (NullValue, vec![Key("a")]),
3479 (BooleanValue(true), vec![Key("b")]),
3480 (ObjectEnd, vec![]),
3483 assert_stream_equal(
3484 "{\"a\" : 1.0 ,\"b\": [ true ]}",
3486 (ObjectStart, vec![]),
3487 (F64Value(1.0), vec![Key("a")]),
3488 (ArrayStart, vec![Key("b")]),
3489 (BooleanValue(true),vec![Key("b"), Index(0)]),
3490 (ArrayEnd, vec![Key("b")]),
3491 (ObjectEnd, vec![]),
3494 assert_stream_equal(
3500 { "c": {"d": null} }
3504 (ObjectStart, vec![]),
3505 (F64Value(1.0), vec![Key("a")]),
3506 (ArrayStart, vec![Key("b")]),
3507 (BooleanValue(true), vec![Key("b"), Index(0)]),
3508 (StringValue("foo\nbar".to_string()), vec![Key("b"), Index(1)]),
3509 (ObjectStart, vec![Key("b"), Index(2)]),
3510 (ObjectStart, vec![Key("b"), Index(2), Key("c")]),
3511 (NullValue, vec![Key("b"), Index(2), Key("c"), Key("d")]),
3512 (ObjectEnd, vec![Key("b"), Index(2), Key("c")]),
3513 (ObjectEnd, vec![Key("b"), Index(2)]),
3514 (ArrayEnd, vec![Key("b")]),
3515 (ObjectEnd, vec![]),
3520 #[cfg_attr(target_word_size = "32", ignore)] // FIXME(#14064)
3521 fn test_read_array_streaming() {
3522 assert_stream_equal(
3525 (ArrayStart, vec![]),
3529 assert_stream_equal(
3532 (ArrayStart, vec![]),
3536 assert_stream_equal(
3539 (ArrayStart, vec![]),
3540 (BooleanValue(true), vec![Index(0)]),
3544 assert_stream_equal(
3547 (ArrayStart, vec![]),
3548 (BooleanValue(false), vec![Index(0)]),
3552 assert_stream_equal(
3555 (ArrayStart, vec![]),
3556 (NullValue, vec![Index(0)]),
3560 assert_stream_equal(
3563 (ArrayStart, vec![]),
3564 (U64Value(3), vec![Index(0)]),
3565 (U64Value(1), vec![Index(1)]),
3569 assert_stream_equal(
3572 (ArrayStart, vec![]),
3573 (U64Value(3), vec![Index(0)]),
3574 (U64Value(2), vec![Index(1)]),
3578 assert_stream_equal(
3581 (ArrayStart, vec![]),
3582 (U64Value(2), vec![Index(0)]),
3583 (ArrayStart, vec![Index(1)]),
3584 (U64Value(4), vec![Index(1), Index(0)]),
3585 (U64Value(1), vec![Index(1), Index(1)]),
3586 (ArrayEnd, vec![Index(1)]),
3591 assert_eq!(last_event("["), Error(SyntaxError(EOFWhileParsingValue, 1, 2)));
3593 assert_eq!(from_str("["), Err(SyntaxError(EOFWhileParsingValue, 1, 2)));
3594 assert_eq!(from_str("[1"), Err(SyntaxError(EOFWhileParsingArray, 1, 3)));
3595 assert_eq!(from_str("[1,"), Err(SyntaxError(EOFWhileParsingValue, 1, 4)));
3596 assert_eq!(from_str("[1,]"), Err(SyntaxError(InvalidSyntax, 1, 4)));
3597 assert_eq!(from_str("[6 7]"), Err(SyntaxError(InvalidSyntax, 1, 4)));
3601 fn test_trailing_characters_streaming() {
3602 assert_eq!(last_event("nulla"), Error(SyntaxError(TrailingCharacters, 1, 5)));
3603 assert_eq!(last_event("truea"), Error(SyntaxError(TrailingCharacters, 1, 5)));
3604 assert_eq!(last_event("falsea"), Error(SyntaxError(TrailingCharacters, 1, 6)));
3605 assert_eq!(last_event("1a"), Error(SyntaxError(TrailingCharacters, 1, 2)));
3606 assert_eq!(last_event("[]a"), Error(SyntaxError(TrailingCharacters, 1, 3)));
3607 assert_eq!(last_event("{}a"), Error(SyntaxError(TrailingCharacters, 1, 3)));
3610 fn test_read_identifiers_streaming() {
3611 assert_eq!(Parser::new("null".chars()).next(), Some(NullValue));
3612 assert_eq!(Parser::new("true".chars()).next(), Some(BooleanValue(true)));
3613 assert_eq!(Parser::new("false".chars()).next(), Some(BooleanValue(false)));
3615 assert_eq!(last_event("n"), Error(SyntaxError(InvalidSyntax, 1, 2)));
3616 assert_eq!(last_event("nul"), Error(SyntaxError(InvalidSyntax, 1, 4)));
3617 assert_eq!(last_event("t"), Error(SyntaxError(InvalidSyntax, 1, 2)));
3618 assert_eq!(last_event("truz"), Error(SyntaxError(InvalidSyntax, 1, 4)));
3619 assert_eq!(last_event("f"), Error(SyntaxError(InvalidSyntax, 1, 2)));
3620 assert_eq!(last_event("faz"), Error(SyntaxError(InvalidSyntax, 1, 3)));
3625 let mut stack = Stack::new();
3627 assert!(stack.is_empty());
3628 assert!(stack.len() == 0);
3629 assert!(!stack.last_is_index());
3631 stack.push_index(0);
3634 assert!(stack.len() == 1);
3635 assert!(stack.is_equal_to(&[Index(1)]));
3636 assert!(stack.starts_with(&[Index(1)]));
3637 assert!(stack.ends_with(&[Index(1)]));
3638 assert!(stack.last_is_index());
3639 assert!(stack.get(0) == Index(1));
3641 stack.push_key("foo".to_string());
3643 assert!(stack.len() == 2);
3644 assert!(stack.is_equal_to(&[Index(1), Key("foo")]));
3645 assert!(stack.starts_with(&[Index(1), Key("foo")]));
3646 assert!(stack.starts_with(&[Index(1)]));
3647 assert!(stack.ends_with(&[Index(1), Key("foo")]));
3648 assert!(stack.ends_with(&[Key("foo")]));
3649 assert!(!stack.last_is_index());
3650 assert!(stack.get(0) == Index(1));
3651 assert!(stack.get(1) == Key("foo"));
3653 stack.push_key("bar".to_string());
3655 assert!(stack.len() == 3);
3656 assert!(stack.is_equal_to(&[Index(1), Key("foo"), Key("bar")]));
3657 assert!(stack.starts_with(&[Index(1)]));
3658 assert!(stack.starts_with(&[Index(1), Key("foo")]));
3659 assert!(stack.starts_with(&[Index(1), Key("foo"), Key("bar")]));
3660 assert!(stack.ends_with(&[Key("bar")]));
3661 assert!(stack.ends_with(&[Key("foo"), Key("bar")]));
3662 assert!(stack.ends_with(&[Index(1), Key("foo"), Key("bar")]));
3663 assert!(!stack.last_is_index());
3664 assert!(stack.get(0) == Index(1));
3665 assert!(stack.get(1) == Key("foo"));
3666 assert!(stack.get(2) == Key("bar"));
3670 assert!(stack.len() == 2);
3671 assert!(stack.is_equal_to(&[Index(1), Key("foo")]));
3672 assert!(stack.starts_with(&[Index(1), Key("foo")]));
3673 assert!(stack.starts_with(&[Index(1)]));
3674 assert!(stack.ends_with(&[Index(1), Key("foo")]));
3675 assert!(stack.ends_with(&[Key("foo")]));
3676 assert!(!stack.last_is_index());
3677 assert!(stack.get(0) == Index(1));
3678 assert!(stack.get(1) == Key("foo"));
3683 use std::collections::{HashMap,TreeMap};
3686 let array2 = Array(vec!(U64(1), U64(2)));
3687 let array3 = Array(vec!(U64(1), U64(2), U64(3)));
3689 let mut tree_map = TreeMap::new();
3690 tree_map.insert("a".to_string(), U64(1));
3691 tree_map.insert("b".to_string(), U64(2));
3695 assert_eq!(array2.to_json(), array2);
3696 assert_eq!(object.to_json(), object);
3697 assert_eq!(3_i.to_json(), I64(3));
3698 assert_eq!(4_i8.to_json(), I64(4));
3699 assert_eq!(5_i16.to_json(), I64(5));
3700 assert_eq!(6_i32.to_json(), I64(6));
3701 assert_eq!(7_i64.to_json(), I64(7));
3702 assert_eq!(8_u.to_json(), U64(8));
3703 assert_eq!(9_u8.to_json(), U64(9));
3704 assert_eq!(10_u16.to_json(), U64(10));
3705 assert_eq!(11_u32.to_json(), U64(11));
3706 assert_eq!(12_u64.to_json(), U64(12));
3707 assert_eq!(13.0_f32.to_json(), F64(13.0_f64));
3708 assert_eq!(14.0_f64.to_json(), F64(14.0_f64));
3709 assert_eq!(().to_json(), Null);
3710 assert_eq!(f32::INFINITY.to_json(), Null);
3711 assert_eq!(f64::NAN.to_json(), Null);
3712 assert_eq!(true.to_json(), Boolean(true));
3713 assert_eq!(false.to_json(), Boolean(false));
3714 assert_eq!("abc".to_json(), String("abc".into_string()));
3715 assert_eq!("abc".into_string().to_json(), String("abc".into_string()));
3716 assert_eq!((1u, 2u).to_json(), array2);
3717 assert_eq!((1u, 2u, 3u).to_json(), array3);
3718 assert_eq!([1u, 2].to_json(), array2);
3719 assert_eq!((&[1u, 2, 3]).to_json(), array3);
3720 assert_eq!((vec![1u, 2]).to_json(), array2);
3721 assert_eq!(vec!(1u, 2, 3).to_json(), array3);
3722 let mut tree_map = TreeMap::new();
3723 tree_map.insert("a".to_string(), 1u);
3724 tree_map.insert("b".to_string(), 2);
3725 assert_eq!(tree_map.to_json(), object);
3726 let mut hash_map = HashMap::new();
3727 hash_map.insert("a".to_string(), 1u);
3728 hash_map.insert("b".to_string(), 2);
3729 assert_eq!(hash_map.to_json(), object);
3730 assert_eq!(Some(15i).to_json(), I64(15));
3731 assert_eq!(Some(15u).to_json(), U64(15));
3732 assert_eq!(None::<int>.to_json(), Null);
3736 fn bench_streaming_small(b: &mut Bencher) {
3738 let mut parser = Parser::new(
3744 { "c": {"d": null} }
3749 match parser.next() {
3757 fn bench_small(b: &mut Bencher) {
3759 let _ = from_str(r#"{
3764 { "c": {"d": null} }
3770 fn big_json() -> string::String {
3771 let mut src = "[\n".to_string();
3772 for _ in range(0i, 500) {
3773 src.push_str(r#"{ "a": true, "b": null, "c":3.1415, "d": "Hello world", "e": \
3776 src.push_str("{}]");
3781 fn bench_streaming_large(b: &mut Bencher) {
3782 let src = big_json();
3784 let mut parser = Parser::new(src.chars());
3786 match parser.next() {
3794 fn bench_large(b: &mut Bencher) {
3795 let src = big_json();
3796 b.iter( || { let _ = from_str(src.as_slice()); });