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 `BTreeMap<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::RustcEncodable` trait.
61 //! To be able to decode a piece of data, it must implement the `serialize::RustcDecodable` trait.
62 //! The Rust compiler provides an annotation to automatically generate the code for these traits:
63 //! `#[derive(RustcDecodable, RustcEncodable)]`
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 `RustcEncodable` 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 //! // FIXME(#19470): this cannot be ```rust``` because it fails orphan checking at the moment
81 //! extern crate serialize;
82 //! use serialize::json;
84 //! // Automatically generate `Decodable` and `Encodable` trait implementations
85 //! #[derive(RustcDecodable, RustcEncodable)]
86 //! pub struct TestStruct {
89 //! data_vector: Vec<u8>,
93 //! let object = TestStruct {
95 //! data_str: "homura".to_string(),
96 //! data_vector: vec![2,3,4,5],
99 //! // Serialize using `json::encode`
100 //! let encoded = json::encode(&object);
102 //! // Deserialize using `json::decode`
103 //! let decoded: TestStruct = json::decode(encoded.as_slice()).unwrap();
107 //! ## Using the `ToJson` trait
109 //! The examples above use the `ToJson` trait to generate the JSON string, which is required
110 //! for custom mappings.
112 //! ### Simple example of `ToJson` usage
115 //! // FIXME(#19470): this cannot be ```rust``` because it fails orphan checking at the moment
116 //! extern crate serialize;
117 //! use serialize::json::{self, ToJson, Json};
119 //! // A custom data structure
120 //! struct ComplexNum {
125 //! // JSON value representation
126 //! impl ToJson for ComplexNum {
127 //! fn to_json(&self) -> Json {
128 //! Json::String(format!("{}+{}i", self.a, self.b))
132 //! // Only generate `RustcEncodable` trait implementation
133 //! #[derive(Encodable)]
134 //! pub struct ComplexNumRecord {
141 //! let num = ComplexNum { a: 0.0001, b: 12.539 };
142 //! let data: String = json::encode(&ComplexNumRecord{
144 //! dsc: "test".to_string(),
145 //! val: num.to_json(),
147 //! println!("data: {}", data);
148 //! // data: {"uid":1,"dsc":"test","val":"0.0001+12.539j"};
152 //! ### Verbose example of `ToJson` usage
155 //! // FIXME(#19470): this cannot be ```rust``` because it fails orphan checking at the moment
156 //! extern crate serialize;
157 //! use std::collections::BTreeMap;
158 //! use serialize::json::{self, Json, ToJson};
160 //! // Only generate `Decodable` trait implementation
161 //! #[derive(Decodable)]
162 //! pub struct TestStruct {
164 //! data_str: String,
165 //! data_vector: Vec<u8>,
168 //! // Specify encoding method manually
169 //! impl ToJson for TestStruct {
170 //! fn to_json(&self) -> Json {
171 //! let mut d = BTreeMap::new();
172 //! // All standard types implement `to_json()`, so use it
173 //! d.insert("data_int".to_string(), self.data_int.to_json());
174 //! d.insert("data_str".to_string(), self.data_str.to_json());
175 //! d.insert("data_vector".to_string(), self.data_vector.to_json());
181 //! // Serialize using `ToJson`
182 //! let input_data = TestStruct {
184 //! data_str: "madoka".to_string(),
185 //! data_vector: vec![2,3,4,5],
187 //! let json_obj: Json = input_data.to_json();
188 //! let json_str: String = json_obj.to_string();
190 //! // Deserialize like before
191 //! let decoded: TestStruct = json::decode(json_str.as_slice()).unwrap();
195 use self::JsonEvent::*;
196 use self::StackElement::*;
197 use self::ErrorCode::*;
198 use self::ParserError::*;
199 use self::DecoderError::*;
200 use self::ParserState::*;
201 use self::InternalStackElement::*;
204 use std::collections::{HashMap, BTreeMap};
205 use std::{char, f64, fmt, io, num, str};
206 use std::mem::{swap, transmute};
207 use std::num::{Float, Int};
208 use std::num::FpCategory as Fp;
209 use std::str::FromStr;
212 use unicode::str as unicode_str;
213 use unicode::str::Utf16Item;
217 /// Represents a json value
218 #[derive(Clone, PartialEq, PartialOrd)]
223 String(string::String),
226 Object(self::Object),
230 pub type Array = Vec<Json>;
231 pub type Object = BTreeMap<string::String, Json>;
233 pub struct PrettyJson<'a> { inner: &'a Json }
235 pub struct AsJson<'a, T: 'a> { inner: &'a T }
236 pub struct AsPrettyJson<'a, T: 'a> { inner: &'a T, indent: Option<uint> }
238 /// The errors that can arise while parsing a JSON stream.
239 #[derive(Clone, Copy, PartialEq)]
243 EOFWhileParsingObject,
244 EOFWhileParsingArray,
245 EOFWhileParsingValue,
246 EOFWhileParsingString,
252 InvalidUnicodeCodePoint,
253 LoneLeadingSurrogateInHexEscape,
254 UnexpectedEndOfHexEscape,
260 #[derive(Clone, Copy, PartialEq, Show)]
261 pub enum ParserError {
263 SyntaxError(ErrorCode, uint, uint),
264 IoError(io::IoErrorKind, &'static str),
267 // Builder and Parser have the same errors.
268 pub type BuilderError = ParserError;
270 #[derive(Clone, PartialEq, Show)]
271 pub enum DecoderError {
272 ParseError(ParserError),
273 ExpectedError(string::String, string::String),
274 MissingFieldError(string::String),
275 UnknownVariantError(string::String),
276 ApplicationError(string::String)
279 /// Returns a readable error string for a given error code.
280 pub fn error_str(error: ErrorCode) -> &'static str {
282 InvalidSyntax => "invalid syntax",
283 InvalidNumber => "invalid number",
284 EOFWhileParsingObject => "EOF While parsing object",
285 EOFWhileParsingArray => "EOF While parsing array",
286 EOFWhileParsingValue => "EOF While parsing value",
287 EOFWhileParsingString => "EOF While parsing string",
288 KeyMustBeAString => "key must be a string",
289 ExpectedColon => "expected `:`",
290 TrailingCharacters => "trailing characters",
291 TrailingComma => "trailing comma",
292 InvalidEscape => "invalid escape",
293 UnrecognizedHex => "invalid \\u{ esc}ape (unrecognized hex)",
294 NotFourDigit => "invalid \\u{ esc}ape (not four digits)",
295 NotUtf8 => "contents not utf-8",
296 InvalidUnicodeCodePoint => "invalid Unicode code point",
297 LoneLeadingSurrogateInHexEscape => "lone leading surrogate in hex escape",
298 UnexpectedEndOfHexEscape => "unexpected end of hex escape",
302 /// Shortcut function to decode a JSON `&str` into an object
303 pub fn decode<T: ::Decodable<Decoder, DecoderError>>(s: &str) -> DecodeResult<T> {
304 let json = match from_str(s) {
306 Err(e) => return Err(ParseError(e))
309 let mut decoder = Decoder::new(json);
310 ::Decodable::decode(&mut decoder)
313 /// Shortcut function to encode a `T` into a JSON `String`
314 pub fn encode<T>(object: &T) -> string::String
315 where T: for<'a> Encodable<Encoder<'a>, fmt::Error>
317 let mut s = String::new();
319 let mut encoder = Encoder::new(&mut s);
320 let _ = object.encode(&mut encoder);
325 impl fmt::Show for ErrorCode {
326 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
327 error_str(*self).fmt(f)
331 fn io_error_to_error(io: io::IoError) -> ParserError {
332 IoError(io.kind, io.desc)
335 impl std::error::Error for DecoderError {
336 fn description(&self) -> &str { "decoder error" }
337 fn detail(&self) -> Option<std::string::String> { Some(self.to_string()) }
340 pub type EncodeResult = fmt::Result;
341 pub type DecodeResult<T> = Result<T, DecoderError>;
343 fn escape_str(wr: &mut fmt::Writer, v: &str) -> fmt::Result {
344 try!(wr.write_str("\""));
348 for (i, byte) in v.bytes().enumerate() {
349 let escaped = match byte {
352 b'\x00' => "\\u0000",
353 b'\x01' => "\\u0001",
354 b'\x02' => "\\u0002",
355 b'\x03' => "\\u0003",
356 b'\x04' => "\\u0004",
357 b'\x05' => "\\u0005",
358 b'\x06' => "\\u0006",
359 b'\x07' => "\\u0007",
363 b'\x0b' => "\\u000b",
366 b'\x0e' => "\\u000e",
367 b'\x0f' => "\\u000f",
368 b'\x10' => "\\u0010",
369 b'\x11' => "\\u0011",
370 b'\x12' => "\\u0012",
371 b'\x13' => "\\u0013",
372 b'\x14' => "\\u0014",
373 b'\x15' => "\\u0015",
374 b'\x16' => "\\u0016",
375 b'\x17' => "\\u0017",
376 b'\x18' => "\\u0018",
377 b'\x19' => "\\u0019",
378 b'\x1a' => "\\u001a",
379 b'\x1b' => "\\u001b",
380 b'\x1c' => "\\u001c",
381 b'\x1d' => "\\u001d",
382 b'\x1e' => "\\u001e",
383 b'\x1f' => "\\u001f",
384 b'\x7f' => "\\u007f",
389 try!(wr.write_str(v[start..i]));
392 try!(wr.write_str(escaped));
397 if start != v.len() {
398 try!(wr.write_str(v[start..]));
404 fn escape_char(writer: &mut fmt::Writer, v: char) -> fmt::Result {
405 let mut buf = [0; 4];
406 let n = v.encode_utf8(&mut buf).unwrap();
407 let buf = unsafe { str::from_utf8_unchecked(buf[0..n]) };
408 escape_str(writer, buf)
411 fn spaces(wr: &mut fmt::Writer, mut n: uint) -> fmt::Result {
412 const BUF: &'static str = " ";
414 while n >= BUF.len() {
415 try!(wr.write_str(BUF));
420 wr.write_str(BUF[..n])
426 fn fmt_number_or_null(v: f64) -> string::String {
428 Fp::Nan | Fp::Infinite => string::String::from_str("null"),
429 _ if v.fract() != 0f64 => f64::to_str_digits(v, 6u),
430 _ => f64::to_str_digits(v, 6u) + ".0",
434 /// A structure for implementing serialization to JSON.
435 pub struct Encoder<'a> {
436 writer: &'a mut (fmt::Writer+'a),
439 impl<'a> Encoder<'a> {
440 /// Creates a new JSON encoder whose output will be written to the writer
442 pub fn new(writer: &'a mut fmt::Writer) -> Encoder<'a> {
443 Encoder { writer: writer }
447 impl<'a> ::Encoder<fmt::Error> for Encoder<'a> {
448 fn emit_nil(&mut self) -> EncodeResult { write!(self.writer, "null") }
450 fn emit_uint(&mut self, v: uint) -> EncodeResult { write!(self.writer, "{}", v) }
451 fn emit_u64(&mut self, v: u64) -> EncodeResult { write!(self.writer, "{}", v) }
452 fn emit_u32(&mut self, v: u32) -> EncodeResult { write!(self.writer, "{}", v) }
453 fn emit_u16(&mut self, v: u16) -> EncodeResult { write!(self.writer, "{}", v) }
454 fn emit_u8(&mut self, v: u8) -> EncodeResult { write!(self.writer, "{}", v) }
456 fn emit_int(&mut self, v: int) -> EncodeResult { write!(self.writer, "{}", v) }
457 fn emit_i64(&mut self, v: i64) -> EncodeResult { write!(self.writer, "{}", v) }
458 fn emit_i32(&mut self, v: i32) -> EncodeResult { write!(self.writer, "{}", v) }
459 fn emit_i16(&mut self, v: i16) -> EncodeResult { write!(self.writer, "{}", v) }
460 fn emit_i8(&mut self, v: i8) -> EncodeResult { write!(self.writer, "{}", v) }
462 fn emit_bool(&mut self, v: bool) -> EncodeResult {
464 write!(self.writer, "true")
466 write!(self.writer, "false")
470 fn emit_f64(&mut self, v: f64) -> EncodeResult {
471 write!(self.writer, "{}", fmt_number_or_null(v))
473 fn emit_f32(&mut self, v: f32) -> EncodeResult {
474 self.emit_f64(v as f64)
477 fn emit_char(&mut self, v: char) -> EncodeResult {
478 escape_char(self.writer, v)
480 fn emit_str(&mut self, v: &str) -> EncodeResult {
481 escape_str(self.writer, v)
484 fn emit_enum<F>(&mut self, _name: &str, f: F) -> EncodeResult where
485 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
490 fn emit_enum_variant<F>(&mut self,
494 f: F) -> EncodeResult where
495 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
497 // enums are encoded as strings or objects
499 // Kangaroo(34,"William") => {"variant": "Kangaroo", "fields": [34,"William"]}
501 escape_str(self.writer, name)
503 try!(write!(self.writer, "{{\"variant\":"));
504 try!(escape_str(self.writer, name));
505 try!(write!(self.writer, ",\"fields\":["));
507 write!(self.writer, "]}}")
511 fn emit_enum_variant_arg<F>(&mut self, idx: uint, f: F) -> EncodeResult where
512 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
515 try!(write!(self.writer, ","));
520 fn emit_enum_struct_variant<F>(&mut self,
524 f: F) -> EncodeResult where
525 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
527 self.emit_enum_variant(name, id, cnt, f)
530 fn emit_enum_struct_variant_field<F>(&mut self,
533 f: F) -> EncodeResult where
534 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
536 self.emit_enum_variant_arg(idx, f)
539 fn emit_struct<F>(&mut self, _: &str, _: uint, f: F) -> EncodeResult where
540 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
542 try!(write!(self.writer, "{{"));
544 write!(self.writer, "}}")
547 fn emit_struct_field<F>(&mut self, name: &str, idx: uint, f: F) -> EncodeResult where
548 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
550 if idx != 0 { try!(write!(self.writer, ",")); }
551 try!(escape_str(self.writer, name));
552 try!(write!(self.writer, ":"));
556 fn emit_tuple<F>(&mut self, len: uint, f: F) -> EncodeResult where
557 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
559 self.emit_seq(len, f)
561 fn emit_tuple_arg<F>(&mut self, idx: uint, f: F) -> EncodeResult where
562 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
564 self.emit_seq_elt(idx, f)
567 fn emit_tuple_struct<F>(&mut self, _name: &str, len: uint, f: F) -> EncodeResult where
568 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
570 self.emit_seq(len, f)
572 fn emit_tuple_struct_arg<F>(&mut self, idx: uint, f: F) -> EncodeResult where
573 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
575 self.emit_seq_elt(idx, f)
578 fn emit_option<F>(&mut self, f: F) -> EncodeResult where
579 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
583 fn emit_option_none(&mut self) -> EncodeResult { self.emit_nil() }
584 fn emit_option_some<F>(&mut self, f: F) -> EncodeResult where
585 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
590 fn emit_seq<F>(&mut self, _len: uint, f: F) -> EncodeResult where
591 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
593 try!(write!(self.writer, "["));
595 write!(self.writer, "]")
598 fn emit_seq_elt<F>(&mut self, idx: uint, f: F) -> EncodeResult where
599 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
602 try!(write!(self.writer, ","));
607 fn emit_map<F>(&mut self, _len: uint, f: F) -> EncodeResult where
608 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
610 try!(write!(self.writer, "{{"));
612 write!(self.writer, "}}")
615 fn emit_map_elt_key<F>(&mut self, idx: uint, mut f: F) -> EncodeResult where
616 F: FnMut(&mut Encoder<'a>) -> EncodeResult,
618 if idx != 0 { try!(write!(self.writer, ",")) }
619 // ref #12967, make sure to wrap a key in double quotes,
620 // in the event that its of a type that omits them (eg numbers)
621 let mut buf = Vec::new();
622 // FIXME(14302) remove the transmute and unsafe block.
624 let mut check_encoder = Encoder::new(&mut buf);
625 try!(f(transmute(&mut check_encoder)));
627 let out = str::from_utf8(buf[]).unwrap();
628 let needs_wrapping = out.char_at(0) != '"' && out.char_at_reverse(out.len()) != '"';
629 if needs_wrapping { try!(write!(self.writer, "\"")); }
631 if needs_wrapping { try!(write!(self.writer, "\"")); }
635 fn emit_map_elt_val<F>(&mut self, _idx: uint, f: F) -> EncodeResult where
636 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
638 try!(write!(self.writer, ":"));
643 /// Another encoder for JSON, but prints out human-readable JSON instead of
645 pub struct PrettyEncoder<'a> {
646 writer: &'a mut (fmt::Writer+'a),
651 impl<'a> PrettyEncoder<'a> {
652 /// Creates a new encoder whose output will be written to the specified writer
653 pub fn new(writer: &'a mut fmt::Writer) -> PrettyEncoder<'a> {
654 PrettyEncoder { writer: writer, curr_indent: 0, indent: 2, }
657 /// Set the number of spaces to indent for each level.
658 /// This is safe to set during encoding.
659 pub fn set_indent(&mut self, indent: uint) {
660 // self.indent very well could be 0 so we need to use checked division.
661 let level = self.curr_indent.checked_div(self.indent).unwrap_or(0);
662 self.indent = indent;
663 self.curr_indent = level * self.indent;
667 impl<'a> ::Encoder<fmt::Error> for PrettyEncoder<'a> {
668 fn emit_nil(&mut self) -> EncodeResult { write!(self.writer, "null") }
670 fn emit_uint(&mut self, v: uint) -> EncodeResult { write!(self.writer, "{}", v) }
671 fn emit_u64(&mut self, v: u64) -> EncodeResult { write!(self.writer, "{}", v) }
672 fn emit_u32(&mut self, v: u32) -> EncodeResult { write!(self.writer, "{}", v) }
673 fn emit_u16(&mut self, v: u16) -> EncodeResult { write!(self.writer, "{}", v) }
674 fn emit_u8(&mut self, v: u8) -> EncodeResult { write!(self.writer, "{}", v) }
676 fn emit_int(&mut self, v: int) -> EncodeResult { write!(self.writer, "{}", v) }
677 fn emit_i64(&mut self, v: i64) -> EncodeResult { write!(self.writer, "{}", v) }
678 fn emit_i32(&mut self, v: i32) -> EncodeResult { write!(self.writer, "{}", v) }
679 fn emit_i16(&mut self, v: i16) -> EncodeResult { write!(self.writer, "{}", v) }
680 fn emit_i8(&mut self, v: i8) -> EncodeResult { write!(self.writer, "{}", v) }
682 fn emit_bool(&mut self, v: bool) -> EncodeResult {
684 write!(self.writer, "true")
686 write!(self.writer, "false")
690 fn emit_f64(&mut self, v: f64) -> EncodeResult {
691 write!(self.writer, "{}", fmt_number_or_null(v))
693 fn emit_f32(&mut self, v: f32) -> EncodeResult {
694 self.emit_f64(v as f64)
697 fn emit_char(&mut self, v: char) -> EncodeResult {
698 escape_char(self.writer, v)
700 fn emit_str(&mut self, v: &str) -> EncodeResult {
701 escape_str(self.writer, v)
704 fn emit_enum<F>(&mut self, _name: &str, f: F) -> EncodeResult where
705 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
710 fn emit_enum_variant<F>(&mut self,
715 -> EncodeResult where
716 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
719 escape_str(self.writer, name)
721 try!(write!(self.writer, "{{\n"));
722 self.curr_indent += self.indent;
723 try!(spaces(self.writer, self.curr_indent));
724 try!(write!(self.writer, "\"variant\": "));
725 try!(escape_str(self.writer, name));
726 try!(write!(self.writer, ",\n"));
727 try!(spaces(self.writer, self.curr_indent));
728 try!(write!(self.writer, "\"fields\": [\n"));
729 self.curr_indent += self.indent;
731 self.curr_indent -= self.indent;
732 try!(write!(self.writer, "\n"));
733 try!(spaces(self.writer, self.curr_indent));
734 self.curr_indent -= self.indent;
735 try!(write!(self.writer, "]\n"));
736 try!(spaces(self.writer, self.curr_indent));
737 write!(self.writer, "}}")
741 fn emit_enum_variant_arg<F>(&mut self, idx: uint, f: F) -> EncodeResult where
742 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
745 try!(write!(self.writer, ",\n"));
747 try!(spaces(self.writer, self.curr_indent));
751 fn emit_enum_struct_variant<F>(&mut self,
755 f: F) -> EncodeResult where
756 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
758 self.emit_enum_variant(name, id, cnt, f)
761 fn emit_enum_struct_variant_field<F>(&mut self,
764 f: F) -> EncodeResult where
765 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
767 self.emit_enum_variant_arg(idx, f)
771 fn emit_struct<F>(&mut self, _: &str, len: uint, f: F) -> EncodeResult where
772 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
775 write!(self.writer, "{{}}")
777 try!(write!(self.writer, "{{"));
778 self.curr_indent += self.indent;
780 self.curr_indent -= self.indent;
781 try!(write!(self.writer, "\n"));
782 try!(spaces(self.writer, self.curr_indent));
783 write!(self.writer, "}}")
787 fn emit_struct_field<F>(&mut self, name: &str, idx: uint, f: F) -> EncodeResult where
788 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
791 try!(write!(self.writer, "\n"));
793 try!(write!(self.writer, ",\n"));
795 try!(spaces(self.writer, self.curr_indent));
796 try!(escape_str(self.writer, name));
797 try!(write!(self.writer, ": "));
801 fn emit_tuple<F>(&mut self, len: uint, f: F) -> EncodeResult where
802 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
804 self.emit_seq(len, f)
806 fn emit_tuple_arg<F>(&mut self, idx: uint, f: F) -> EncodeResult where
807 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
809 self.emit_seq_elt(idx, f)
812 fn emit_tuple_struct<F>(&mut self, _: &str, len: uint, f: F) -> EncodeResult where
813 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
815 self.emit_seq(len, f)
817 fn emit_tuple_struct_arg<F>(&mut self, idx: uint, f: F) -> EncodeResult where
818 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
820 self.emit_seq_elt(idx, f)
823 fn emit_option<F>(&mut self, f: F) -> EncodeResult where
824 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
828 fn emit_option_none(&mut self) -> EncodeResult { self.emit_nil() }
829 fn emit_option_some<F>(&mut self, f: F) -> EncodeResult where
830 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
835 fn emit_seq<F>(&mut self, len: uint, f: F) -> EncodeResult where
836 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
839 write!(self.writer, "[]")
841 try!(write!(self.writer, "["));
842 self.curr_indent += self.indent;
844 self.curr_indent -= self.indent;
845 try!(write!(self.writer, "\n"));
846 try!(spaces(self.writer, self.curr_indent));
847 write!(self.writer, "]")
851 fn emit_seq_elt<F>(&mut self, idx: uint, f: F) -> EncodeResult where
852 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
855 try!(write!(self.writer, "\n"));
857 try!(write!(self.writer, ",\n"));
859 try!(spaces(self.writer, self.curr_indent));
863 fn emit_map<F>(&mut self, len: uint, f: F) -> EncodeResult where
864 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
867 write!(self.writer, "{{}}")
869 try!(write!(self.writer, "{{"));
870 self.curr_indent += self.indent;
872 self.curr_indent -= self.indent;
873 try!(write!(self.writer, "\n"));
874 try!(spaces(self.writer, self.curr_indent));
875 write!(self.writer, "}}")
879 fn emit_map_elt_key<F>(&mut self, idx: uint, mut f: F) -> EncodeResult where
880 F: FnMut(&mut PrettyEncoder<'a>) -> EncodeResult,
883 try!(write!(self.writer, "\n"));
885 try!(write!(self.writer, ",\n"));
887 try!(spaces(self.writer, self.curr_indent));
888 // ref #12967, make sure to wrap a key in double quotes,
889 // in the event that its of a type that omits them (eg numbers)
890 let mut buf = Vec::new();
891 // FIXME(14302) remove the transmute and unsafe block.
893 let mut check_encoder = PrettyEncoder::new(&mut buf);
894 try!(f(transmute(&mut check_encoder)));
896 let out = str::from_utf8(buf[]).unwrap();
897 let needs_wrapping = out.char_at(0) != '"' && out.char_at_reverse(out.len()) != '"';
898 if needs_wrapping { try!(write!(self.writer, "\"")); }
900 if needs_wrapping { try!(write!(self.writer, "\"")); }
904 fn emit_map_elt_val<F>(&mut self, _idx: uint, f: F) -> EncodeResult where
905 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
907 try!(write!(self.writer, ": "));
912 impl<E: ::Encoder<S>, S> Encodable<E, S> for Json {
913 fn encode(&self, e: &mut E) -> Result<(), S> {
915 Json::I64(v) => v.encode(e),
916 Json::U64(v) => v.encode(e),
917 Json::F64(v) => v.encode(e),
918 Json::String(ref v) => v.encode(e),
919 Json::Boolean(v) => v.encode(e),
920 Json::Array(ref v) => v.encode(e),
921 Json::Object(ref v) => v.encode(e),
922 Json::Null => e.emit_nil(),
927 /// Create an `AsJson` wrapper which can be used to print a value as JSON
928 /// on-the-fly via `write!`
929 pub fn as_json<T>(t: &T) -> AsJson<T> {
933 /// Create an `AsPrettyJson` wrapper which can be used to print a value as JSON
934 /// on-the-fly via `write!`
935 pub fn as_pretty_json<T>(t: &T) -> AsPrettyJson<T> {
936 AsPrettyJson { inner: t, indent: None }
940 /// Borrow this json object as a pretty object to generate a pretty
941 /// representation for it via `Show`.
942 pub fn pretty(&self) -> PrettyJson {
943 PrettyJson { inner: self }
946 /// If the Json value is an Object, returns the value associated with the provided key.
947 /// Otherwise, returns None.
948 pub fn find<'a>(&'a self, key: &str) -> Option<&'a Json>{
950 &Json::Object(ref map) => map.get(key),
955 /// Attempts to get a nested Json Object for each key in `keys`.
956 /// If any key is found not to exist, find_path will return None.
957 /// Otherwise, it will return the Json value associated with the final key.
958 pub fn find_path<'a>(&'a self, keys: &[&str]) -> Option<&'a Json>{
959 let mut target = self;
960 for key in keys.iter() {
961 match target.find(*key) {
962 Some(t) => { target = t; },
969 /// If the Json value is an Object, performs a depth-first search until
970 /// a value associated with the provided key is found. If no value is found
971 /// or the Json value is not an Object, returns None.
972 pub fn search<'a>(&'a self, key: &str) -> Option<&'a Json> {
974 &Json::Object(ref map) => {
976 Some(json_value) => Some(json_value),
978 for (_, v) in map.iter() {
979 match v.search(key) {
980 x if x.is_some() => return x,
992 /// Returns true if the Json value is an Object. Returns false otherwise.
993 pub fn is_object<'a>(&'a self) -> bool {
994 self.as_object().is_some()
997 /// If the Json value is an Object, returns the associated BTreeMap.
998 /// Returns None otherwise.
999 pub fn as_object<'a>(&'a self) -> Option<&'a Object> {
1001 &Json::Object(ref map) => Some(map),
1006 /// Returns true if the Json value is an Array. Returns false otherwise.
1007 pub fn is_array<'a>(&'a self) -> bool {
1008 self.as_array().is_some()
1011 /// If the Json value is an Array, returns the associated vector.
1012 /// Returns None otherwise.
1013 pub fn as_array<'a>(&'a self) -> Option<&'a Array> {
1015 &Json::Array(ref array) => Some(&*array),
1020 /// Returns true if the Json value is a String. Returns false otherwise.
1021 pub fn is_string<'a>(&'a self) -> bool {
1022 self.as_string().is_some()
1025 /// If the Json value is a String, returns the associated str.
1026 /// Returns None otherwise.
1027 pub fn as_string<'a>(&'a self) -> Option<&'a str> {
1029 Json::String(ref s) => Some(s[]),
1034 /// Returns true if the Json value is a Number. Returns false otherwise.
1035 pub fn is_number(&self) -> bool {
1037 Json::I64(_) | Json::U64(_) | Json::F64(_) => true,
1042 /// Returns true if the Json value is a i64. Returns false otherwise.
1043 pub fn is_i64(&self) -> bool {
1045 Json::I64(_) => true,
1050 /// Returns true if the Json value is a u64. Returns false otherwise.
1051 pub fn is_u64(&self) -> bool {
1053 Json::U64(_) => true,
1058 /// Returns true if the Json value is a f64. Returns false otherwise.
1059 pub fn is_f64(&self) -> bool {
1061 Json::F64(_) => true,
1066 /// If the Json value is a number, return or cast it to a i64.
1067 /// Returns None otherwise.
1068 pub fn as_i64(&self) -> Option<i64> {
1070 Json::I64(n) => Some(n),
1071 Json::U64(n) => num::cast(n),
1076 /// If the Json value is a number, return or cast it to a u64.
1077 /// Returns None otherwise.
1078 pub fn as_u64(&self) -> Option<u64> {
1080 Json::I64(n) => num::cast(n),
1081 Json::U64(n) => Some(n),
1086 /// If the Json value is a number, return or cast it to a f64.
1087 /// Returns None otherwise.
1088 pub fn as_f64(&self) -> Option<f64> {
1090 Json::I64(n) => num::cast(n),
1091 Json::U64(n) => num::cast(n),
1092 Json::F64(n) => Some(n),
1097 /// Returns true if the Json value is a Boolean. Returns false otherwise.
1098 pub fn is_boolean(&self) -> bool {
1099 self.as_boolean().is_some()
1102 /// If the Json value is a Boolean, returns the associated bool.
1103 /// Returns None otherwise.
1104 pub fn as_boolean(&self) -> Option<bool> {
1106 &Json::Boolean(b) => Some(b),
1111 /// Returns true if the Json value is a Null. Returns false otherwise.
1112 pub fn is_null(&self) -> bool {
1113 self.as_null().is_some()
1116 /// If the Json value is a Null, returns ().
1117 /// Returns None otherwise.
1118 pub fn as_null(&self) -> Option<()> {
1120 &Json::Null => Some(()),
1126 // NOTE(stage0): remove impl after a snapshot
1128 impl<'a> ops::Index<&'a str, Json> for Json {
1129 fn index(&self, idx: & &str) -> &Json {
1130 self.find(*idx).unwrap()
1134 #[cfg(not(stage0))] // NOTE(stage0): remove cfg after a snapshot
1135 impl<'a> ops::Index<&'a str> for Json {
1138 fn index(&self, idx: & &str) -> &Json {
1139 self.find(*idx).unwrap()
1143 // NOTE(stage0): remove impl after a snapshot
1145 impl ops::Index<uint, Json> for Json {
1146 fn index<'a>(&'a self, idx: &uint) -> &'a Json {
1148 &Json::Array(ref v) => v.index(idx),
1149 _ => panic!("can only index Json with uint if it is an array")
1154 #[cfg(not(stage0))] // NOTE(stage0): remove cfg after a snapshot
1155 impl ops::Index<uint> for Json {
1158 fn index<'a>(&'a self, idx: &uint) -> &'a Json {
1160 &Json::Array(ref v) => v.index(idx),
1161 _ => panic!("can only index Json with uint if it is an array")
1166 /// The output of the streaming parser.
1167 #[derive(PartialEq, Clone, Show)]
1168 pub enum JsonEvent {
1177 StringValue(string::String),
1182 #[derive(PartialEq, Show)]
1184 // Parse a value in an array, true means first element.
1186 // Parse ',' or ']' after an element in an array.
1188 // Parse a key:value in an object, true means first element.
1190 // Parse ',' or ']' after an element in an object.
1194 // Expecting the stream to end.
1196 // Parsing can't continue.
1200 /// A Stack represents the current position of the parser in the logical
1201 /// structure of the JSON stream.
1202 /// For example foo.bar[3].x
1204 stack: Vec<InternalStackElement>,
1205 str_buffer: Vec<u8>,
1208 /// StackElements compose a Stack.
1209 /// For example, Key("foo"), Key("bar"), Index(3) and Key("x") are the
1210 /// StackElements compositing the stack that represents foo.bar[3].x
1211 #[derive(PartialEq, Clone, Show)]
1212 pub enum StackElement<'l> {
1217 // Internally, Key elements are stored as indices in a buffer to avoid
1218 // allocating a string for every member of an object.
1219 #[derive(PartialEq, Clone, Show)]
1220 enum InternalStackElement {
1222 InternalKey(u16, u16), // start, size
1226 pub fn new() -> Stack {
1227 Stack { stack: Vec::new(), str_buffer: Vec::new() }
1230 /// Returns The number of elements in the Stack.
1231 pub fn len(&self) -> uint { self.stack.len() }
1233 /// Returns true if the stack is empty.
1234 pub fn is_empty(&self) -> bool { self.stack.is_empty() }
1236 /// Provides access to the StackElement at a given index.
1237 /// lower indices are at the bottom of the stack while higher indices are
1239 pub fn get<'l>(&'l self, idx: uint) -> StackElement<'l> {
1240 match self.stack[idx] {
1241 InternalIndex(i) => Index(i),
1242 InternalKey(start, size) => {
1244 self.str_buffer[start as uint .. start as uint + size as uint]).unwrap())
1249 /// Compares this stack with an array of StackElements.
1250 pub fn is_equal_to(&self, rhs: &[StackElement]) -> bool {
1251 if self.stack.len() != rhs.len() { return false; }
1252 for i in range(0, rhs.len()) {
1253 if self.get(i) != rhs[i] { return false; }
1258 /// Returns true if the bottom-most elements of this stack are the same as
1259 /// the ones passed as parameter.
1260 pub fn starts_with(&self, rhs: &[StackElement]) -> bool {
1261 if self.stack.len() < rhs.len() { return false; }
1262 for i in range(0, rhs.len()) {
1263 if self.get(i) != rhs[i] { return false; }
1268 /// Returns true if the top-most elements of this stack are the same as
1269 /// the ones passed as parameter.
1270 pub fn ends_with(&self, rhs: &[StackElement]) -> bool {
1271 if self.stack.len() < rhs.len() { return false; }
1272 let offset = self.stack.len() - rhs.len();
1273 for i in range(0, rhs.len()) {
1274 if self.get(i + offset) != rhs[i] { return false; }
1279 /// Returns the top-most element (if any).
1280 pub fn top<'l>(&'l self) -> Option<StackElement<'l>> {
1281 return match self.stack.last() {
1283 Some(&InternalIndex(i)) => Some(Index(i)),
1284 Some(&InternalKey(start, size)) => {
1285 Some(Key(str::from_utf8(
1286 self.str_buffer[start as uint .. (start+size) as uint]
1292 // Used by Parser to insert Key elements at the top of the stack.
1293 fn push_key(&mut self, key: string::String) {
1294 self.stack.push(InternalKey(self.str_buffer.len() as u16, key.len() as u16));
1295 for c in key.as_bytes().iter() {
1296 self.str_buffer.push(*c);
1300 // Used by Parser to insert Index elements at the top of the stack.
1301 fn push_index(&mut self, index: u32) {
1302 self.stack.push(InternalIndex(index));
1305 // Used by Parser to remove the top-most element of the stack.
1307 assert!(!self.is_empty());
1308 match *self.stack.last().unwrap() {
1309 InternalKey(_, sz) => {
1310 let new_size = self.str_buffer.len() - sz as uint;
1311 self.str_buffer.truncate(new_size);
1313 InternalIndex(_) => {}
1318 // Used by Parser to test whether the top-most element is an index.
1319 fn last_is_index(&self) -> bool {
1320 if self.is_empty() { return false; }
1321 return match *self.stack.last().unwrap() {
1322 InternalIndex(_) => true,
1327 // Used by Parser to increment the index of the top-most element.
1328 fn bump_index(&mut self) {
1329 let len = self.stack.len();
1330 let idx = match *self.stack.last().unwrap() {
1331 InternalIndex(i) => { i + 1 }
1334 self.stack[len - 1] = InternalIndex(idx);
1338 /// A streaming JSON parser implemented as an iterator of JsonEvent, consuming
1339 /// an iterator of char.
1340 pub struct Parser<T> {
1345 // We maintain a stack representing where we are in the logical structure
1346 // of the JSON stream.
1348 // A state machine is kept to make it possible to interrupt and resume parsing.
1352 impl<T: Iterator<Item=char>> Iterator for Parser<T> {
1353 type Item = JsonEvent;
1355 fn next(&mut self) -> Option<JsonEvent> {
1356 if self.state == ParseFinished {
1360 if self.state == ParseBeforeFinish {
1361 self.parse_whitespace();
1362 // Make sure there is no trailing characters.
1364 self.state = ParseFinished;
1367 return Some(self.error_event(TrailingCharacters));
1371 return Some(self.parse());
1375 impl<T: Iterator<Item=char>> Parser<T> {
1376 /// Creates the JSON parser.
1377 pub fn new(rdr: T) -> Parser<T> {
1378 let mut p = Parser {
1383 stack: Stack::new(),
1390 /// Provides access to the current position in the logical structure of the
1392 pub fn stack<'l>(&'l self) -> &'l Stack {
1396 fn eof(&self) -> bool { self.ch.is_none() }
1397 fn ch_or_null(&self) -> char { self.ch.unwrap_or('\x00') }
1398 fn bump(&mut self) {
1399 self.ch = self.rdr.next();
1401 if self.ch_is('\n') {
1409 fn next_char(&mut self) -> Option<char> {
1413 fn ch_is(&self, c: char) -> bool {
1417 fn error<T>(&self, reason: ErrorCode) -> Result<T, ParserError> {
1418 Err(SyntaxError(reason, self.line, self.col))
1421 fn parse_whitespace(&mut self) {
1422 while self.ch_is(' ') ||
1425 self.ch_is('\r') { self.bump(); }
1428 fn parse_number(&mut self) -> JsonEvent {
1429 let mut neg = false;
1431 if self.ch_is('-') {
1436 let res = match self.parse_u64() {
1438 Err(e) => { return Error(e); }
1441 if self.ch_is('.') || self.ch_is('e') || self.ch_is('E') {
1442 let mut res = res as f64;
1444 if self.ch_is('.') {
1445 res = match self.parse_decimal(res) {
1447 Err(e) => { return Error(e); }
1451 if self.ch_is('e') || self.ch_is('E') {
1452 res = match self.parse_exponent(res) {
1454 Err(e) => { return Error(e); }
1465 let res = -(res as i64);
1467 // Make sure we didn't underflow.
1469 Error(SyntaxError(InvalidNumber, self.line, self.col))
1479 fn parse_u64(&mut self) -> Result<u64, ParserError> {
1481 let last_accum = 0; // necessary to detect overflow.
1483 match self.ch_or_null() {
1487 // A leading '0' must be the only digit before the decimal point.
1488 match self.ch_or_null() {
1489 '0' ... '9' => return self.error(InvalidNumber),
1495 match self.ch_or_null() {
1496 c @ '0' ... '9' => {
1498 accum += (c as u64) - ('0' as u64);
1500 // Detect overflow by comparing to the last value.
1501 if accum <= last_accum { return self.error(InvalidNumber); }
1509 _ => return self.error(InvalidNumber),
1515 fn parse_decimal(&mut self, mut res: f64) -> Result<f64, ParserError> {
1518 // Make sure a digit follows the decimal place.
1519 match self.ch_or_null() {
1521 _ => return self.error(InvalidNumber)
1526 match self.ch_or_null() {
1527 c @ '0' ... '9' => {
1529 res += (((c as int) - ('0' as int)) as f64) * dec;
1539 fn parse_exponent(&mut self, mut res: f64) -> Result<f64, ParserError> {
1543 let mut neg_exp = false;
1545 if self.ch_is('+') {
1547 } else if self.ch_is('-') {
1552 // Make sure a digit follows the exponent place.
1553 match self.ch_or_null() {
1555 _ => return self.error(InvalidNumber)
1558 match self.ch_or_null() {
1559 c @ '0' ... '9' => {
1561 exp += (c as uint) - ('0' as uint);
1569 let exp = 10_f64.powi(exp as i32);
1579 fn decode_hex_escape(&mut self) -> Result<u16, ParserError> {
1582 while i < 4 && !self.eof() {
1584 n = match self.ch_or_null() {
1585 c @ '0' ... '9' => n * 16 + ((c as u16) - ('0' as u16)),
1586 'a' | 'A' => n * 16 + 10,
1587 'b' | 'B' => n * 16 + 11,
1588 'c' | 'C' => n * 16 + 12,
1589 'd' | 'D' => n * 16 + 13,
1590 'e' | 'E' => n * 16 + 14,
1591 'f' | 'F' => n * 16 + 15,
1592 _ => return self.error(InvalidEscape)
1598 // Error out if we didn't parse 4 digits.
1600 return self.error(InvalidEscape);
1606 fn parse_str(&mut self) -> Result<string::String, ParserError> {
1607 let mut escape = false;
1608 let mut res = string::String::new();
1613 return self.error(EOFWhileParsingString);
1617 match self.ch_or_null() {
1618 '"' => res.push('"'),
1619 '\\' => res.push('\\'),
1620 '/' => res.push('/'),
1621 'b' => res.push('\x08'),
1622 'f' => res.push('\x0c'),
1623 'n' => res.push('\n'),
1624 'r' => res.push('\r'),
1625 't' => res.push('\t'),
1626 'u' => match try!(self.decode_hex_escape()) {
1627 0xDC00 ... 0xDFFF => {
1628 return self.error(LoneLeadingSurrogateInHexEscape)
1631 // Non-BMP characters are encoded as a sequence of
1632 // two hex escapes, representing UTF-16 surrogates.
1633 n1 @ 0xD800 ... 0xDBFF => {
1634 match (self.next_char(), self.next_char()) {
1635 (Some('\\'), Some('u')) => (),
1636 _ => return self.error(UnexpectedEndOfHexEscape),
1639 let buf = [n1, try!(self.decode_hex_escape())];
1640 match unicode_str::utf16_items(&buf).next() {
1641 Some(Utf16Item::ScalarValue(c)) => res.push(c),
1642 _ => return self.error(LoneLeadingSurrogateInHexEscape),
1646 n => match char::from_u32(n as u32) {
1647 Some(c) => res.push(c),
1648 None => return self.error(InvalidUnicodeCodePoint),
1651 _ => return self.error(InvalidEscape),
1654 } else if self.ch_is('\\') {
1662 Some(c) => res.push(c),
1663 None => unreachable!()
1669 // Invoked at each iteration, consumes the stream until it has enough
1670 // information to return a JsonEvent.
1671 // Manages an internal state so that parsing can be interrupted and resumed.
1672 // Also keeps track of the position in the logical structure of the json
1673 // stream int the form of a stack that can be queried by the user using the
1675 fn parse(&mut self) -> JsonEvent {
1677 // The only paths where the loop can spin a new iteration
1678 // are in the cases ParseArrayComma and ParseObjectComma if ','
1679 // is parsed. In these cases the state is set to (respectively)
1680 // ParseArray(false) and ParseObject(false), which always return,
1681 // so there is no risk of getting stuck in an infinite loop.
1682 // All other paths return before the end of the loop's iteration.
1683 self.parse_whitespace();
1687 return self.parse_start();
1689 ParseArray(first) => {
1690 return self.parse_array(first);
1692 ParseArrayComma => {
1693 match self.parse_array_comma_or_end() {
1694 Some(evt) => { return evt; }
1698 ParseObject(first) => {
1699 return self.parse_object(first);
1701 ParseObjectComma => {
1703 if self.ch_is(',') {
1704 self.state = ParseObject(false);
1707 return self.parse_object_end();
1711 return self.error_event(InvalidSyntax);
1717 fn parse_start(&mut self) -> JsonEvent {
1718 let val = self.parse_value();
1719 self.state = match val {
1720 Error(_) => ParseFinished,
1721 ArrayStart => ParseArray(true),
1722 ObjectStart => ParseObject(true),
1723 _ => ParseBeforeFinish,
1728 fn parse_array(&mut self, first: bool) -> JsonEvent {
1729 if self.ch_is(']') {
1731 self.error_event(InvalidSyntax)
1733 self.state = if self.stack.is_empty() {
1735 } else if self.stack.last_is_index() {
1745 self.stack.push_index(0);
1747 let val = self.parse_value();
1748 self.state = match val {
1749 Error(_) => ParseFinished,
1750 ArrayStart => ParseArray(true),
1751 ObjectStart => ParseObject(true),
1752 _ => ParseArrayComma,
1758 fn parse_array_comma_or_end(&mut self) -> Option<JsonEvent> {
1759 if self.ch_is(',') {
1760 self.stack.bump_index();
1761 self.state = ParseArray(false);
1764 } else if self.ch_is(']') {
1766 self.state = if self.stack.is_empty() {
1768 } else if self.stack.last_is_index() {
1775 } else if self.eof() {
1776 Some(self.error_event(EOFWhileParsingArray))
1778 Some(self.error_event(InvalidSyntax))
1782 fn parse_object(&mut self, first: bool) -> JsonEvent {
1783 if self.ch_is('}') {
1785 if self.stack.is_empty() {
1786 return self.error_event(TrailingComma);
1791 self.state = if self.stack.is_empty() {
1793 } else if self.stack.last_is_index() {
1802 return self.error_event(EOFWhileParsingObject);
1804 if !self.ch_is('"') {
1805 return self.error_event(KeyMustBeAString);
1807 let s = match self.parse_str() {
1810 self.state = ParseFinished;
1814 self.parse_whitespace();
1816 return self.error_event(EOFWhileParsingObject);
1817 } else if self.ch_or_null() != ':' {
1818 return self.error_event(ExpectedColon);
1820 self.stack.push_key(s);
1822 self.parse_whitespace();
1824 let val = self.parse_value();
1826 self.state = match val {
1827 Error(_) => ParseFinished,
1828 ArrayStart => ParseArray(true),
1829 ObjectStart => ParseObject(true),
1830 _ => ParseObjectComma,
1835 fn parse_object_end(&mut self) -> JsonEvent {
1836 if self.ch_is('}') {
1837 self.state = if self.stack.is_empty() {
1839 } else if self.stack.last_is_index() {
1846 } else if self.eof() {
1847 self.error_event(EOFWhileParsingObject)
1849 self.error_event(InvalidSyntax)
1853 fn parse_value(&mut self) -> JsonEvent {
1854 if self.eof() { return self.error_event(EOFWhileParsingValue); }
1855 match self.ch_or_null() {
1856 'n' => { self.parse_ident("ull", NullValue) }
1857 't' => { self.parse_ident("rue", BooleanValue(true)) }
1858 'f' => { self.parse_ident("alse", BooleanValue(false)) }
1859 '0' ... '9' | '-' => self.parse_number(),
1860 '"' => match self.parse_str() {
1861 Ok(s) => StringValue(s),
1872 _ => { self.error_event(InvalidSyntax) }
1876 fn parse_ident(&mut self, ident: &str, value: JsonEvent) -> JsonEvent {
1877 if ident.chars().all(|c| Some(c) == self.next_char()) {
1881 Error(SyntaxError(InvalidSyntax, self.line, self.col))
1885 fn error_event(&mut self, reason: ErrorCode) -> JsonEvent {
1886 self.state = ParseFinished;
1887 Error(SyntaxError(reason, self.line, self.col))
1891 /// A Builder consumes a json::Parser to create a generic Json structure.
1892 pub struct Builder<T> {
1894 token: Option<JsonEvent>,
1897 impl<T: Iterator<Item=char>> Builder<T> {
1898 /// Create a JSON Builder.
1899 pub fn new(src: T) -> Builder<T> {
1900 Builder { parser: Parser::new(src), token: None, }
1903 // Decode a Json value from a Parser.
1904 pub fn build(&mut self) -> Result<Json, BuilderError> {
1906 let result = self.build_value();
1910 Some(Error(e)) => { return Err(e); }
1911 ref tok => { panic!("unexpected token {}", tok.clone()); }
1916 fn bump(&mut self) {
1917 self.token = self.parser.next();
1920 fn build_value(&mut self) -> Result<Json, BuilderError> {
1921 return match self.token {
1922 Some(NullValue) => Ok(Json::Null),
1923 Some(I64Value(n)) => Ok(Json::I64(n)),
1924 Some(U64Value(n)) => Ok(Json::U64(n)),
1925 Some(F64Value(n)) => Ok(Json::F64(n)),
1926 Some(BooleanValue(b)) => Ok(Json::Boolean(b)),
1927 Some(StringValue(ref mut s)) => {
1928 let mut temp = string::String::new();
1930 Ok(Json::String(temp))
1932 Some(Error(e)) => Err(e),
1933 Some(ArrayStart) => self.build_array(),
1934 Some(ObjectStart) => self.build_object(),
1935 Some(ObjectEnd) => self.parser.error(InvalidSyntax),
1936 Some(ArrayEnd) => self.parser.error(InvalidSyntax),
1937 None => self.parser.error(EOFWhileParsingValue),
1941 fn build_array(&mut self) -> Result<Json, BuilderError> {
1943 let mut values = Vec::new();
1946 if self.token == Some(ArrayEnd) {
1947 return Ok(Json::Array(values.into_iter().collect()));
1949 match self.build_value() {
1950 Ok(v) => values.push(v),
1951 Err(e) => { return Err(e) }
1957 fn build_object(&mut self) -> Result<Json, BuilderError> {
1960 let mut values = BTreeMap::new();
1964 Some(ObjectEnd) => { return Ok(Json::Object(values)); }
1965 Some(Error(e)) => { return Err(e); }
1969 let key = match self.parser.stack().top() {
1970 Some(Key(k)) => { k.to_string() }
1971 _ => { panic!("invalid state"); }
1973 match self.build_value() {
1974 Ok(value) => { values.insert(key, value); }
1975 Err(e) => { return Err(e); }
1979 return self.parser.error(EOFWhileParsingObject);
1983 /// Decodes a json value from an `&mut io::Reader`
1984 pub fn from_reader(rdr: &mut io::Reader) -> Result<Json, BuilderError> {
1985 let contents = match rdr.read_to_end() {
1987 Err(e) => return Err(io_error_to_error(e))
1989 let s = match str::from_utf8(contents.as_slice()).ok() {
1991 _ => return Err(SyntaxError(NotUtf8, 0, 0))
1993 let mut builder = Builder::new(s.chars());
1997 /// Decodes a json value from a string
1998 pub fn from_str(s: &str) -> Result<Json, BuilderError> {
1999 let mut builder = Builder::new(s.chars());
2003 /// A structure to decode JSON to values in rust.
2004 pub struct Decoder {
2009 /// Creates a new decoder instance for decoding the specified JSON value.
2010 pub fn new(json: Json) -> Decoder {
2011 Decoder { stack: vec![json] }
2016 fn pop(&mut self) -> Json {
2017 self.stack.pop().unwrap()
2021 macro_rules! expect {
2022 ($e:expr, Null) => ({
2024 Json::Null => Ok(()),
2025 other => Err(ExpectedError("Null".to_string(),
2026 format!("{}", other)))
2029 ($e:expr, $t:ident) => ({
2031 Json::$t(v) => Ok(v),
2033 Err(ExpectedError(stringify!($t).to_string(),
2034 format!("{}", other)))
2040 macro_rules! read_primitive {
2041 ($name:ident, $ty:ty) => {
2042 fn $name(&mut self) -> DecodeResult<$ty> {
2044 Json::I64(f) => match num::cast(f) {
2046 None => Err(ExpectedError("Number".to_string(), format!("{}", f))),
2048 Json::U64(f) => match num::cast(f) {
2050 None => Err(ExpectedError("Number".to_string(), format!("{}", f))),
2052 Json::F64(f) => Err(ExpectedError("Integer".to_string(), format!("{}", f))),
2053 // re: #12967.. a type w/ numeric keys (ie HashMap<uint, V> etc)
2054 // is going to have a string here, as per JSON spec.
2055 Json::String(s) => match s.parse() {
2057 None => Err(ExpectedError("Number".to_string(), s)),
2059 value => Err(ExpectedError("Number".to_string(), format!("{}", value))),
2065 impl ::Decoder<DecoderError> for Decoder {
2066 fn read_nil(&mut self) -> DecodeResult<()> {
2067 expect!(self.pop(), Null)
2070 read_primitive! { read_uint, uint }
2071 read_primitive! { read_u8, u8 }
2072 read_primitive! { read_u16, u16 }
2073 read_primitive! { read_u32, u32 }
2074 read_primitive! { read_u64, u64 }
2075 read_primitive! { read_int, int }
2076 read_primitive! { read_i8, i8 }
2077 read_primitive! { read_i16, i16 }
2078 read_primitive! { read_i32, i32 }
2079 read_primitive! { read_i64, i64 }
2081 fn read_f32(&mut self) -> DecodeResult<f32> { self.read_f64().map(|x| x as f32) }
2083 fn read_f64(&mut self) -> DecodeResult<f64> {
2085 Json::I64(f) => Ok(f as f64),
2086 Json::U64(f) => Ok(f as f64),
2087 Json::F64(f) => Ok(f),
2088 Json::String(s) => {
2089 // re: #12967.. a type w/ numeric keys (ie HashMap<uint, V> etc)
2090 // is going to have a string here, as per JSON spec.
2093 None => Err(ExpectedError("Number".to_string(), s)),
2096 Json::Null => Ok(f64::NAN),
2097 value => Err(ExpectedError("Number".to_string(), format!("{}", value)))
2101 fn read_bool(&mut self) -> DecodeResult<bool> {
2102 expect!(self.pop(), Boolean)
2105 fn read_char(&mut self) -> DecodeResult<char> {
2106 let s = try!(self.read_str());
2108 let mut it = s.chars();
2109 match (it.next(), it.next()) {
2110 // exactly one character
2111 (Some(c), None) => return Ok(c),
2115 Err(ExpectedError("single character string".to_string(), format!("{}", s)))
2118 fn read_str(&mut self) -> DecodeResult<string::String> {
2119 expect!(self.pop(), String)
2122 fn read_enum<T, F>(&mut self, _name: &str, f: F) -> DecodeResult<T> where
2123 F: FnOnce(&mut Decoder) -> DecodeResult<T>,
2128 fn read_enum_variant<T, F>(&mut self, names: &[&str],
2129 mut f: F) -> DecodeResult<T>
2130 where F: FnMut(&mut Decoder, uint) -> DecodeResult<T>,
2132 let name = match self.pop() {
2133 Json::String(s) => s,
2134 Json::Object(mut o) => {
2135 let n = match o.remove(&"variant".to_string()) {
2136 Some(Json::String(s)) => s,
2138 return Err(ExpectedError("String".to_string(), format!("{}", val)))
2141 return Err(MissingFieldError("variant".to_string()))
2144 match o.remove(&"fields".to_string()) {
2145 Some(Json::Array(l)) => {
2146 for field in l.into_iter().rev() {
2147 self.stack.push(field);
2151 return Err(ExpectedError("Array".to_string(), format!("{}", val)))
2154 return Err(MissingFieldError("fields".to_string()))
2160 return Err(ExpectedError("String or Object".to_string(), format!("{}", json)))
2163 let idx = match names.iter().position(|n| *n == name[]) {
2165 None => return Err(UnknownVariantError(name))
2170 fn read_enum_variant_arg<T, F>(&mut self, _idx: uint, f: F) -> DecodeResult<T> where
2171 F: FnOnce(&mut Decoder) -> DecodeResult<T>,
2176 fn read_enum_struct_variant<T, F>(&mut self, names: &[&str], f: F) -> DecodeResult<T> where
2177 F: FnMut(&mut Decoder, uint) -> DecodeResult<T>,
2179 self.read_enum_variant(names, f)
2183 fn read_enum_struct_variant_field<T, F>(&mut self,
2187 -> DecodeResult<T> where
2188 F: FnOnce(&mut Decoder) -> DecodeResult<T>,
2190 self.read_enum_variant_arg(idx, f)
2193 fn read_struct<T, F>(&mut self, _name: &str, _len: uint, f: F) -> DecodeResult<T> where
2194 F: FnOnce(&mut Decoder) -> DecodeResult<T>,
2196 let value = try!(f(self));
2201 fn read_struct_field<T, F>(&mut self,
2205 -> DecodeResult<T> where
2206 F: FnOnce(&mut Decoder) -> DecodeResult<T>,
2208 let mut obj = try!(expect!(self.pop(), Object));
2210 let value = match obj.remove(&name.to_string()) {
2212 // Add a Null and try to parse it as an Option<_>
2213 // to get None as a default value.
2214 self.stack.push(Json::Null);
2217 Err(_) => return Err(MissingFieldError(name.to_string())),
2221 self.stack.push(json);
2225 self.stack.push(Json::Object(obj));
2229 fn read_tuple<T, F>(&mut self, tuple_len: uint, f: F) -> DecodeResult<T> where
2230 F: FnOnce(&mut Decoder) -> DecodeResult<T>,
2232 self.read_seq(move |d, len| {
2233 if len == tuple_len {
2236 Err(ExpectedError(format!("Tuple{}", tuple_len), format!("Tuple{}", len)))
2241 fn read_tuple_arg<T, F>(&mut self, idx: uint, f: F) -> DecodeResult<T> where
2242 F: FnOnce(&mut Decoder) -> DecodeResult<T>,
2244 self.read_seq_elt(idx, f)
2247 fn read_tuple_struct<T, F>(&mut self,
2251 -> DecodeResult<T> where
2252 F: FnOnce(&mut Decoder) -> DecodeResult<T>,
2254 self.read_tuple(len, f)
2257 fn read_tuple_struct_arg<T, F>(&mut self,
2260 -> DecodeResult<T> where
2261 F: FnOnce(&mut Decoder) -> DecodeResult<T>,
2263 self.read_tuple_arg(idx, f)
2266 fn read_option<T, F>(&mut self, mut f: F) -> DecodeResult<T> where
2267 F: FnMut(&mut Decoder, bool) -> DecodeResult<T>,
2270 Json::Null => f(self, false),
2271 value => { self.stack.push(value); f(self, true) }
2275 fn read_seq<T, F>(&mut self, f: F) -> DecodeResult<T> where
2276 F: FnOnce(&mut Decoder, uint) -> DecodeResult<T>,
2278 let array = try!(expect!(self.pop(), Array));
2279 let len = array.len();
2280 for v in array.into_iter().rev() {
2286 fn read_seq_elt<T, F>(&mut self, _idx: uint, f: F) -> DecodeResult<T> where
2287 F: FnOnce(&mut Decoder) -> DecodeResult<T>,
2292 fn read_map<T, F>(&mut self, f: F) -> DecodeResult<T> where
2293 F: FnOnce(&mut Decoder, uint) -> DecodeResult<T>,
2295 let obj = try!(expect!(self.pop(), Object));
2296 let len = obj.len();
2297 for (key, value) in obj.into_iter() {
2298 self.stack.push(value);
2299 self.stack.push(Json::String(key));
2304 fn read_map_elt_key<T, F>(&mut self, _idx: uint, f: F) -> DecodeResult<T> where
2305 F: FnOnce(&mut Decoder) -> DecodeResult<T>,
2310 fn read_map_elt_val<T, F>(&mut self, _idx: uint, f: F) -> DecodeResult<T> where
2311 F: FnOnce(&mut Decoder) -> DecodeResult<T>,
2316 fn error(&mut self, err: &str) -> DecoderError {
2317 ApplicationError(err.to_string())
2321 /// A trait for converting values to JSON
2322 pub trait ToJson for Sized? {
2323 /// Converts the value of `self` to an instance of JSON
2324 fn to_json(&self) -> Json;
2327 macro_rules! to_json_impl_i64 {
2329 $(impl ToJson for $t {
2330 fn to_json(&self) -> Json { Json::I64(*self as i64) }
2335 to_json_impl_i64! { int, i8, i16, i32, i64 }
2337 macro_rules! to_json_impl_u64 {
2339 $(impl ToJson for $t {
2340 fn to_json(&self) -> Json { Json::U64(*self as u64) }
2345 to_json_impl_u64! { uint, u8, u16, u32, u64 }
2347 impl ToJson for Json {
2348 fn to_json(&self) -> Json { self.clone() }
2351 impl ToJson for f32 {
2352 fn to_json(&self) -> Json { (*self as f64).to_json() }
2355 impl ToJson for f64 {
2356 fn to_json(&self) -> Json {
2357 match self.classify() {
2358 Fp::Nan | Fp::Infinite => Json::Null,
2359 _ => Json::F64(*self)
2364 impl ToJson for () {
2365 fn to_json(&self) -> Json { Json::Null }
2368 impl ToJson for bool {
2369 fn to_json(&self) -> Json { Json::Boolean(*self) }
2372 impl ToJson for str {
2373 fn to_json(&self) -> Json { Json::String(self.to_string()) }
2376 impl ToJson for string::String {
2377 fn to_json(&self) -> Json { Json::String((*self).clone()) }
2380 macro_rules! tuple_impl {
2381 // use variables to indicate the arity of the tuple
2382 ($($tyvar:ident),* ) => {
2383 // the trailing commas are for the 1 tuple
2385 $( $tyvar : ToJson ),*
2386 > ToJson for ( $( $tyvar ),* , ) {
2389 #[allow(non_snake_case)]
2390 fn to_json(&self) -> Json {
2392 ($(ref $tyvar),*,) => Json::Array(vec![$($tyvar.to_json()),*])
2401 tuple_impl!{A, B, C}
2402 tuple_impl!{A, B, C, D}
2403 tuple_impl!{A, B, C, D, E}
2404 tuple_impl!{A, B, C, D, E, F}
2405 tuple_impl!{A, B, C, D, E, F, G}
2406 tuple_impl!{A, B, C, D, E, F, G, H}
2407 tuple_impl!{A, B, C, D, E, F, G, H, I}
2408 tuple_impl!{A, B, C, D, E, F, G, H, I, J}
2409 tuple_impl!{A, B, C, D, E, F, G, H, I, J, K}
2410 tuple_impl!{A, B, C, D, E, F, G, H, I, J, K, L}
2412 impl<A: ToJson> ToJson for [A] {
2413 fn to_json(&self) -> Json { Json::Array(self.iter().map(|elt| elt.to_json()).collect()) }
2416 impl<A: ToJson> ToJson for Vec<A> {
2417 fn to_json(&self) -> Json { Json::Array(self.iter().map(|elt| elt.to_json()).collect()) }
2420 impl<A: ToJson> ToJson for BTreeMap<string::String, A> {
2421 fn to_json(&self) -> Json {
2422 let mut d = BTreeMap::new();
2423 for (key, value) in self.iter() {
2424 d.insert((*key).clone(), value.to_json());
2430 impl<A: ToJson> ToJson for HashMap<string::String, A> {
2431 fn to_json(&self) -> Json {
2432 let mut d = BTreeMap::new();
2433 for (key, value) in self.iter() {
2434 d.insert((*key).clone(), value.to_json());
2440 impl<A:ToJson> ToJson for Option<A> {
2441 fn to_json(&self) -> Json {
2444 Some(ref value) => value.to_json()
2449 struct FormatShim<'a, 'b: 'a> {
2450 inner: &'a mut fmt::Formatter<'b>,
2453 impl<'a, 'b> fmt::Writer for FormatShim<'a, 'b> {
2454 fn write_str(&mut self, s: &str) -> fmt::Result {
2455 self.inner.write_str(s)
2459 impl fmt::Show for Json {
2460 /// Encodes a json value into a string
2461 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2462 let mut shim = FormatShim { inner: f };
2463 let mut encoder = Encoder::new(&mut shim);
2464 self.encode(&mut encoder)
2468 impl<'a> fmt::Show for PrettyJson<'a> {
2469 /// Encodes a json value into a string
2470 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2471 let mut shim = FormatShim { inner: f };
2472 let mut encoder = PrettyEncoder::new(&mut shim);
2473 self.inner.encode(&mut encoder)
2477 impl<'a, T> fmt::Show for AsJson<'a, T>
2478 where T: for<'b> Encodable<Encoder<'b>, fmt::Error>
2480 /// Encodes a json value into a string
2481 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2482 let mut shim = FormatShim { inner: f };
2483 let mut encoder = Encoder::new(&mut shim);
2484 self.inner.encode(&mut encoder)
2488 impl<'a, T> AsPrettyJson<'a, T> {
2489 /// Set the indentation level for the emitted JSON
2490 pub fn indent(mut self, indent: uint) -> AsPrettyJson<'a, T> {
2491 self.indent = Some(indent);
2496 impl<'a, T> fmt::Show for AsPrettyJson<'a, T>
2497 where T: for<'b> Encodable<PrettyEncoder<'b>, fmt::Error>
2499 /// Encodes a json value into a string
2500 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2501 let mut shim = FormatShim { inner: f };
2502 let mut encoder = PrettyEncoder::new(&mut shim);
2504 Some(n) => encoder.set_indent(n),
2507 self.inner.encode(&mut encoder)
2511 impl FromStr for Json {
2512 fn from_str(s: &str) -> Option<Json> {
2520 use self::Animal::*;
2521 use self::DecodeEnum::*;
2522 use self::test::Bencher;
2523 use {Encodable, Decodable};
2525 use super::ErrorCode::*;
2526 use super::ParserError::*;
2527 use super::DecoderError::*;
2528 use super::JsonEvent::*;
2529 use super::StackElement::*;
2530 use super::{Json, from_str, DecodeResult, DecoderError, JsonEvent, Parser,
2531 StackElement, Stack, Decoder};
2532 use std::{i64, u64, f32, f64};
2533 use std::collections::BTreeMap;
2534 use std::num::Float;
2537 #[derive(RustcDecodable, Eq, PartialEq, Show)]
2543 fn test_decode_option_none() {
2545 let obj: OptionData = super::decode(s).unwrap();
2546 assert_eq!(obj, OptionData { opt: None });
2550 fn test_decode_option_some() {
2551 let s = "{ \"opt\": 10 }";
2552 let obj: OptionData = super::decode(s).unwrap();
2553 assert_eq!(obj, OptionData { opt: Some(10u) });
2557 fn test_decode_option_malformed() {
2558 check_err::<OptionData>("{ \"opt\": [] }",
2559 ExpectedError("Number".to_string(), "[]".to_string()));
2560 check_err::<OptionData>("{ \"opt\": false }",
2561 ExpectedError("Number".to_string(), "false".to_string()));
2564 #[derive(PartialEq, RustcEncodable, RustcDecodable, Show)]
2567 Frog(string::String, int)
2570 #[derive(PartialEq, RustcEncodable, RustcDecodable, Show)]
2574 c: Vec<string::String>,
2577 #[derive(PartialEq, RustcEncodable, RustcDecodable, Show)]
2582 fn mk_object(items: &[(string::String, Json)]) -> Json {
2583 let mut d = BTreeMap::new();
2585 for item in items.iter() {
2587 (ref key, ref value) => { d.insert((*key).clone(), (*value).clone()); },
2595 fn test_from_str_trait() {
2597 assert!(s.parse::<Json>().unwrap() == s.parse().unwrap());
2601 fn test_write_null() {
2602 assert_eq!(Null.to_string(), "null");
2603 assert_eq!(Null.pretty().to_string(), "null");
2607 fn test_write_i64() {
2608 assert_eq!(U64(0).to_string(), "0");
2609 assert_eq!(U64(0).pretty().to_string(), "0");
2611 assert_eq!(U64(1234).to_string(), "1234");
2612 assert_eq!(U64(1234).pretty().to_string(), "1234");
2614 assert_eq!(I64(-5678).to_string(), "-5678");
2615 assert_eq!(I64(-5678).pretty().to_string(), "-5678");
2617 assert_eq!(U64(7650007200025252000).to_string(), "7650007200025252000");
2618 assert_eq!(U64(7650007200025252000).pretty().to_string(), "7650007200025252000");
2622 fn test_write_f64() {
2623 assert_eq!(F64(3.0).to_string(), "3.0");
2624 assert_eq!(F64(3.0).pretty().to_string(), "3.0");
2626 assert_eq!(F64(3.1).to_string(), "3.1");
2627 assert_eq!(F64(3.1).pretty().to_string(), "3.1");
2629 assert_eq!(F64(-1.5).to_string(), "-1.5");
2630 assert_eq!(F64(-1.5).pretty().to_string(), "-1.5");
2632 assert_eq!(F64(0.5).to_string(), "0.5");
2633 assert_eq!(F64(0.5).pretty().to_string(), "0.5");
2635 assert_eq!(F64(f64::NAN).to_string(), "null");
2636 assert_eq!(F64(f64::NAN).pretty().to_string(), "null");
2638 assert_eq!(F64(f64::INFINITY).to_string(), "null");
2639 assert_eq!(F64(f64::INFINITY).pretty().to_string(), "null");
2641 assert_eq!(F64(f64::NEG_INFINITY).to_string(), "null");
2642 assert_eq!(F64(f64::NEG_INFINITY).pretty().to_string(), "null");
2646 fn test_write_str() {
2647 assert_eq!(String("".to_string()).to_string(), "\"\"");
2648 assert_eq!(String("".to_string()).pretty().to_string(), "\"\"");
2650 assert_eq!(String("homura".to_string()).to_string(), "\"homura\"");
2651 assert_eq!(String("madoka".to_string()).pretty().to_string(), "\"madoka\"");
2655 fn test_write_bool() {
2656 assert_eq!(Boolean(true).to_string(), "true");
2657 assert_eq!(Boolean(true).pretty().to_string(), "true");
2659 assert_eq!(Boolean(false).to_string(), "false");
2660 assert_eq!(Boolean(false).pretty().to_string(), "false");
2664 fn test_write_array() {
2665 assert_eq!(Array(vec![]).to_string(), "[]");
2666 assert_eq!(Array(vec![]).pretty().to_string(), "[]");
2668 assert_eq!(Array(vec![Boolean(true)]).to_string(), "[true]");
2670 Array(vec![Boolean(true)]).pretty().to_string(),
2677 let long_test_array = Array(vec![
2680 Array(vec![String("foo\nbar".to_string()), F64(3.5)])]);
2682 assert_eq!(long_test_array.to_string(),
2683 "[false,null,[\"foo\\nbar\",3.5]]");
2685 long_test_array.pretty().to_string(),
2699 fn test_write_object() {
2700 assert_eq!(mk_object(&[]).to_string(), "{}");
2701 assert_eq!(mk_object(&[]).pretty().to_string(), "{}");
2705 ("a".to_string(), Boolean(true))
2710 mk_object(&[("a".to_string(), Boolean(true))]).pretty().to_string(),
2717 let complex_obj = mk_object(&[
2718 ("b".to_string(), Array(vec![
2719 mk_object(&[("c".to_string(), String("\x0c\r".to_string()))]),
2720 mk_object(&[("d".to_string(), String("".to_string()))])
2725 complex_obj.to_string(),
2728 {\"c\":\"\\f\\r\"},\
2734 complex_obj.pretty().to_string(),
2739 \"c\": \"\\f\\r\"\n \
2748 let a = mk_object(&[
2749 ("a".to_string(), Boolean(true)),
2750 ("b".to_string(), Array(vec![
2751 mk_object(&[("c".to_string(), String("\x0c\r".to_string()))]),
2752 mk_object(&[("d".to_string(), String("".to_string()))])
2756 // We can't compare the strings directly because the object fields be
2757 // printed in a different order.
2758 assert_eq!(a.clone(), a.to_string().parse().unwrap());
2759 assert_eq!(a.clone(), a.pretty().to_string().parse().unwrap());
2763 fn test_write_enum() {
2766 format!("{}", super::as_json(&animal)),
2770 format!("{}", super::as_pretty_json(&animal)),
2774 let animal = Frog("Henry".to_string(), 349);
2776 format!("{}", super::as_json(&animal)),
2777 "{\"variant\":\"Frog\",\"fields\":[\"Henry\",349]}"
2780 format!("{}", super::as_pretty_json(&animal)),
2782 \"variant\": \"Frog\",\n \
2791 macro_rules! check_encoder_for_simple {
2792 ($value:expr, $expected:expr) => ({
2793 let s = format!("{}", super::as_json(&$value));
2794 assert_eq!(s, $expected);
2796 let s = format!("{}", super::as_pretty_json(&$value));
2797 assert_eq!(s, $expected);
2802 fn test_write_some() {
2803 check_encoder_for_simple!(Some("jodhpurs".to_string()), "\"jodhpurs\"");
2807 fn test_write_none() {
2808 check_encoder_for_simple!(None::<string::String>, "null");
2812 fn test_write_char() {
2813 check_encoder_for_simple!('a', "\"a\"");
2814 check_encoder_for_simple!('\t', "\"\\t\"");
2815 check_encoder_for_simple!('\u{0000}', "\"\\u0000\"");
2816 check_encoder_for_simple!('\u{001b}', "\"\\u001b\"");
2817 check_encoder_for_simple!('\u{007f}', "\"\\u007f\"");
2818 check_encoder_for_simple!('\u{00a0}', "\"\u{00a0}\"");
2819 check_encoder_for_simple!('\u{abcd}', "\"\u{abcd}\"");
2820 check_encoder_for_simple!('\u{10ffff}', "\"\u{10ffff}\"");
2824 fn test_trailing_characters() {
2825 assert_eq!(from_str("nulla"), Err(SyntaxError(TrailingCharacters, 1, 5)));
2826 assert_eq!(from_str("truea"), Err(SyntaxError(TrailingCharacters, 1, 5)));
2827 assert_eq!(from_str("falsea"), Err(SyntaxError(TrailingCharacters, 1, 6)));
2828 assert_eq!(from_str("1a"), Err(SyntaxError(TrailingCharacters, 1, 2)));
2829 assert_eq!(from_str("[]a"), Err(SyntaxError(TrailingCharacters, 1, 3)));
2830 assert_eq!(from_str("{}a"), Err(SyntaxError(TrailingCharacters, 1, 3)));
2834 fn test_read_identifiers() {
2835 assert_eq!(from_str("n"), Err(SyntaxError(InvalidSyntax, 1, 2)));
2836 assert_eq!(from_str("nul"), Err(SyntaxError(InvalidSyntax, 1, 4)));
2837 assert_eq!(from_str("t"), Err(SyntaxError(InvalidSyntax, 1, 2)));
2838 assert_eq!(from_str("truz"), Err(SyntaxError(InvalidSyntax, 1, 4)));
2839 assert_eq!(from_str("f"), Err(SyntaxError(InvalidSyntax, 1, 2)));
2840 assert_eq!(from_str("faz"), Err(SyntaxError(InvalidSyntax, 1, 3)));
2842 assert_eq!(from_str("null"), Ok(Null));
2843 assert_eq!(from_str("true"), Ok(Boolean(true)));
2844 assert_eq!(from_str("false"), Ok(Boolean(false)));
2845 assert_eq!(from_str(" null "), Ok(Null));
2846 assert_eq!(from_str(" true "), Ok(Boolean(true)));
2847 assert_eq!(from_str(" false "), Ok(Boolean(false)));
2851 fn test_decode_identifiers() {
2852 let v: () = super::decode("null").unwrap();
2855 let v: bool = super::decode("true").unwrap();
2856 assert_eq!(v, true);
2858 let v: bool = super::decode("false").unwrap();
2859 assert_eq!(v, false);
2863 fn test_read_number() {
2864 assert_eq!(from_str("+"), Err(SyntaxError(InvalidSyntax, 1, 1)));
2865 assert_eq!(from_str("."), Err(SyntaxError(InvalidSyntax, 1, 1)));
2866 assert_eq!(from_str("NaN"), Err(SyntaxError(InvalidSyntax, 1, 1)));
2867 assert_eq!(from_str("-"), Err(SyntaxError(InvalidNumber, 1, 2)));
2868 assert_eq!(from_str("00"), Err(SyntaxError(InvalidNumber, 1, 2)));
2869 assert_eq!(from_str("1."), Err(SyntaxError(InvalidNumber, 1, 3)));
2870 assert_eq!(from_str("1e"), Err(SyntaxError(InvalidNumber, 1, 3)));
2871 assert_eq!(from_str("1e+"), Err(SyntaxError(InvalidNumber, 1, 4)));
2873 assert_eq!(from_str("18446744073709551616"), Err(SyntaxError(InvalidNumber, 1, 20)));
2874 assert_eq!(from_str("-9223372036854775809"), Err(SyntaxError(InvalidNumber, 1, 21)));
2876 assert_eq!(from_str("3"), Ok(U64(3)));
2877 assert_eq!(from_str("3.1"), Ok(F64(3.1)));
2878 assert_eq!(from_str("-1.2"), Ok(F64(-1.2)));
2879 assert_eq!(from_str("0.4"), Ok(F64(0.4)));
2880 assert_eq!(from_str("0.4e5"), Ok(F64(0.4e5)));
2881 assert_eq!(from_str("0.4e+15"), Ok(F64(0.4e15)));
2882 assert_eq!(from_str("0.4e-01"), Ok(F64(0.4e-01)));
2883 assert_eq!(from_str(" 3 "), Ok(U64(3)));
2885 assert_eq!(from_str("-9223372036854775808"), Ok(I64(i64::MIN)));
2886 assert_eq!(from_str("9223372036854775807"), Ok(U64(i64::MAX as u64)));
2887 assert_eq!(from_str("18446744073709551615"), Ok(U64(u64::MAX)));
2891 fn test_decode_numbers() {
2892 let v: f64 = super::decode("3").unwrap();
2895 let v: f64 = super::decode("3.1").unwrap();
2898 let v: f64 = super::decode("-1.2").unwrap();
2899 assert_eq!(v, -1.2);
2901 let v: f64 = super::decode("0.4").unwrap();
2904 let v: f64 = super::decode("0.4e5").unwrap();
2905 assert_eq!(v, 0.4e5);
2907 let v: f64 = super::decode("0.4e15").unwrap();
2908 assert_eq!(v, 0.4e15);
2910 let v: f64 = super::decode("0.4e-01").unwrap();
2911 assert_eq!(v, 0.4e-01);
2913 let v: u64 = super::decode("0").unwrap();
2916 let v: u64 = super::decode("18446744073709551615").unwrap();
2917 assert_eq!(v, u64::MAX);
2919 let v: i64 = super::decode("-9223372036854775808").unwrap();
2920 assert_eq!(v, i64::MIN);
2922 let v: i64 = super::decode("9223372036854775807").unwrap();
2923 assert_eq!(v, i64::MAX);
2925 let res: DecodeResult<i64> = super::decode("765.25252");
2926 assert_eq!(res, Err(ExpectedError("Integer".to_string(), "765.25252".to_string())));
2930 fn test_read_str() {
2931 assert_eq!(from_str("\""), Err(SyntaxError(EOFWhileParsingString, 1, 2)));
2932 assert_eq!(from_str("\"lol"), Err(SyntaxError(EOFWhileParsingString, 1, 5)));
2934 assert_eq!(from_str("\"\""), Ok(String("".to_string())));
2935 assert_eq!(from_str("\"foo\""), Ok(String("foo".to_string())));
2936 assert_eq!(from_str("\"\\\"\""), Ok(String("\"".to_string())));
2937 assert_eq!(from_str("\"\\b\""), Ok(String("\x08".to_string())));
2938 assert_eq!(from_str("\"\\n\""), Ok(String("\n".to_string())));
2939 assert_eq!(from_str("\"\\r\""), Ok(String("\r".to_string())));
2940 assert_eq!(from_str("\"\\t\""), Ok(String("\t".to_string())));
2941 assert_eq!(from_str(" \"foo\" "), Ok(String("foo".to_string())));
2942 assert_eq!(from_str("\"\\u12ab\""), Ok(String("\u{12ab}".to_string())));
2943 assert_eq!(from_str("\"\\uAB12\""), Ok(String("\u{AB12}".to_string())));
2947 fn test_decode_str() {
2948 let s = [("\"\"", ""),
2951 ("\"\\b\"", "\x08"),
2955 ("\"\\u12ab\"", "\u{12ab}"),
2956 ("\"\\uAB12\"", "\u{AB12}")];
2958 for &(i, o) in s.iter() {
2959 let v: string::String = super::decode(i).unwrap();
2965 fn test_read_array() {
2966 assert_eq!(from_str("["), Err(SyntaxError(EOFWhileParsingValue, 1, 2)));
2967 assert_eq!(from_str("[1"), Err(SyntaxError(EOFWhileParsingArray, 1, 3)));
2968 assert_eq!(from_str("[1,"), Err(SyntaxError(EOFWhileParsingValue, 1, 4)));
2969 assert_eq!(from_str("[1,]"), Err(SyntaxError(InvalidSyntax, 1, 4)));
2970 assert_eq!(from_str("[6 7]"), Err(SyntaxError(InvalidSyntax, 1, 4)));
2972 assert_eq!(from_str("[]"), Ok(Array(vec![])));
2973 assert_eq!(from_str("[ ]"), Ok(Array(vec![])));
2974 assert_eq!(from_str("[true]"), Ok(Array(vec![Boolean(true)])));
2975 assert_eq!(from_str("[ false ]"), Ok(Array(vec![Boolean(false)])));
2976 assert_eq!(from_str("[null]"), Ok(Array(vec![Null])));
2977 assert_eq!(from_str("[3, 1]"),
2978 Ok(Array(vec![U64(3), U64(1)])));
2979 assert_eq!(from_str("\n[3, 2]\n"),
2980 Ok(Array(vec![U64(3), U64(2)])));
2981 assert_eq!(from_str("[2, [4, 1]]"),
2982 Ok(Array(vec![U64(2), Array(vec![U64(4), U64(1)])])));
2986 fn test_decode_array() {
2987 let v: Vec<()> = super::decode("[]").unwrap();
2988 assert_eq!(v, vec![]);
2990 let v: Vec<()> = super::decode("[null]").unwrap();
2991 assert_eq!(v, vec![()]);
2993 let v: Vec<bool> = super::decode("[true]").unwrap();
2994 assert_eq!(v, vec![true]);
2996 let v: Vec<int> = super::decode("[3, 1]").unwrap();
2997 assert_eq!(v, vec![3, 1]);
2999 let v: Vec<Vec<uint>> = super::decode("[[3], [1, 2]]").unwrap();
3000 assert_eq!(v, vec![vec![3], vec![1, 2]]);
3004 fn test_decode_tuple() {
3005 let t: (uint, uint, uint) = super::decode("[1, 2, 3]").unwrap();
3006 assert_eq!(t, (1u, 2, 3));
3008 let t: (uint, string::String) = super::decode("[1, \"two\"]").unwrap();
3009 assert_eq!(t, (1u, "two".to_string()));
3013 fn test_decode_tuple_malformed_types() {
3014 assert!(super::decode::<(uint, string::String)>("[1, 2]").is_err());
3018 fn test_decode_tuple_malformed_length() {
3019 assert!(super::decode::<(uint, uint)>("[1, 2, 3]").is_err());
3023 fn test_read_object() {
3024 assert_eq!(from_str("{"), Err(SyntaxError(EOFWhileParsingObject, 1, 2)));
3025 assert_eq!(from_str("{ "), Err(SyntaxError(EOFWhileParsingObject, 1, 3)));
3026 assert_eq!(from_str("{1"), Err(SyntaxError(KeyMustBeAString, 1, 2)));
3027 assert_eq!(from_str("{ \"a\""), Err(SyntaxError(EOFWhileParsingObject, 1, 6)));
3028 assert_eq!(from_str("{\"a\""), Err(SyntaxError(EOFWhileParsingObject, 1, 5)));
3029 assert_eq!(from_str("{\"a\" "), Err(SyntaxError(EOFWhileParsingObject, 1, 6)));
3031 assert_eq!(from_str("{\"a\" 1"), Err(SyntaxError(ExpectedColon, 1, 6)));
3032 assert_eq!(from_str("{\"a\":"), Err(SyntaxError(EOFWhileParsingValue, 1, 6)));
3033 assert_eq!(from_str("{\"a\":1"), Err(SyntaxError(EOFWhileParsingObject, 1, 7)));
3034 assert_eq!(from_str("{\"a\":1 1"), Err(SyntaxError(InvalidSyntax, 1, 8)));
3035 assert_eq!(from_str("{\"a\":1,"), Err(SyntaxError(EOFWhileParsingObject, 1, 8)));
3037 assert_eq!(from_str("{}").unwrap(), mk_object(&[]));
3038 assert_eq!(from_str("{\"a\": 3}").unwrap(),
3039 mk_object(&[("a".to_string(), U64(3))]));
3041 assert_eq!(from_str(
3042 "{ \"a\": null, \"b\" : true }").unwrap(),
3044 ("a".to_string(), Null),
3045 ("b".to_string(), Boolean(true))]));
3046 assert_eq!(from_str("\n{ \"a\": null, \"b\" : true }\n").unwrap(),
3048 ("a".to_string(), Null),
3049 ("b".to_string(), Boolean(true))]));
3050 assert_eq!(from_str(
3051 "{\"a\" : 1.0 ,\"b\": [ true ]}").unwrap(),
3053 ("a".to_string(), F64(1.0)),
3054 ("b".to_string(), Array(vec![Boolean(true)]))
3056 assert_eq!(from_str(
3062 { \"c\": {\"d\": null} } \
3066 ("a".to_string(), F64(1.0)),
3067 ("b".to_string(), Array(vec![
3069 String("foo\nbar".to_string()),
3071 ("c".to_string(), mk_object(&[("d".to_string(), Null)]))
3078 fn test_decode_struct() {
3081 { \"a\": null, \"b\": 2, \"c\": [\"abc\", \"xyz\"] }
3085 let v: Outer = super::decode(s).unwrap();
3090 Inner { a: (), b: 2, c: vec!["abc".to_string(), "xyz".to_string()] }
3096 #[derive(RustcDecodable)]
3097 struct FloatStruct {
3102 fn test_decode_struct_with_nan() {
3103 let s = "{\"f\":null,\"a\":[null,123]}";
3104 let obj: FloatStruct = super::decode(s).unwrap();
3105 assert!(obj.f.is_nan());
3106 assert!(obj.a[0].is_nan());
3107 assert_eq!(obj.a[1], 123f64);
3111 fn test_decode_option() {
3112 let value: Option<string::String> = super::decode("null").unwrap();
3113 assert_eq!(value, None);
3115 let value: Option<string::String> = super::decode("\"jodhpurs\"").unwrap();
3116 assert_eq!(value, Some("jodhpurs".to_string()));
3120 fn test_decode_enum() {
3121 let value: Animal = super::decode("\"Dog\"").unwrap();
3122 assert_eq!(value, Dog);
3124 let s = "{\"variant\":\"Frog\",\"fields\":[\"Henry\",349]}";
3125 let value: Animal = super::decode(s).unwrap();
3126 assert_eq!(value, Frog("Henry".to_string(), 349));
3130 fn test_decode_map() {
3131 let s = "{\"a\": \"Dog\", \"b\": {\"variant\":\"Frog\",\
3132 \"fields\":[\"Henry\", 349]}}";
3133 let mut map: BTreeMap<string::String, Animal> = super::decode(s).unwrap();
3135 assert_eq!(map.remove(&"a".to_string()), Some(Dog));
3136 assert_eq!(map.remove(&"b".to_string()), Some(Frog("Henry".to_string(), 349)));
3140 fn test_multiline_errors() {
3141 assert_eq!(from_str("{\n \"foo\":\n \"bar\""),
3142 Err(SyntaxError(EOFWhileParsingObject, 3u, 8u)));
3145 #[derive(RustcDecodable)]
3147 struct DecodeStruct {
3151 w: Vec<DecodeStruct>
3153 #[derive(RustcDecodable)]
3158 fn check_err<T: Decodable<Decoder, DecoderError>>(to_parse: &'static str,
3159 expected: DecoderError) {
3160 let res: DecodeResult<T> = match from_str(to_parse) {
3161 Err(e) => Err(ParseError(e)),
3162 Ok(json) => Decodable::decode(&mut Decoder::new(json))
3165 Ok(_) => panic!("`{}` parsed & decoded ok, expecting error `{}`",
3166 to_parse, expected),
3167 Err(ParseError(e)) => panic!("`{}` is not valid json: {}",
3170 assert_eq!(e, expected);
3175 fn test_decode_errors_struct() {
3176 check_err::<DecodeStruct>("[]", ExpectedError("Object".to_string(), "[]".to_string()));
3177 check_err::<DecodeStruct>("{\"x\": true, \"y\": true, \"z\": \"\", \"w\": []}",
3178 ExpectedError("Number".to_string(), "true".to_string()));
3179 check_err::<DecodeStruct>("{\"x\": 1, \"y\": [], \"z\": \"\", \"w\": []}",
3180 ExpectedError("Boolean".to_string(), "[]".to_string()));
3181 check_err::<DecodeStruct>("{\"x\": 1, \"y\": true, \"z\": {}, \"w\": []}",
3182 ExpectedError("String".to_string(), "{}".to_string()));
3183 check_err::<DecodeStruct>("{\"x\": 1, \"y\": true, \"z\": \"\", \"w\": null}",
3184 ExpectedError("Array".to_string(), "null".to_string()));
3185 check_err::<DecodeStruct>("{\"x\": 1, \"y\": true, \"z\": \"\"}",
3186 MissingFieldError("w".to_string()));
3189 fn test_decode_errors_enum() {
3190 check_err::<DecodeEnum>("{}",
3191 MissingFieldError("variant".to_string()));
3192 check_err::<DecodeEnum>("{\"variant\": 1}",
3193 ExpectedError("String".to_string(), "1".to_string()));
3194 check_err::<DecodeEnum>("{\"variant\": \"A\"}",
3195 MissingFieldError("fields".to_string()));
3196 check_err::<DecodeEnum>("{\"variant\": \"A\", \"fields\": null}",
3197 ExpectedError("Array".to_string(), "null".to_string()));
3198 check_err::<DecodeEnum>("{\"variant\": \"C\", \"fields\": []}",
3199 UnknownVariantError("C".to_string()));
3204 let json_value = from_str("{\"dog\" : \"cat\"}").unwrap();
3205 let found_str = json_value.find("dog");
3206 assert!(found_str.unwrap().as_string().unwrap() == "cat");
3210 fn test_find_path(){
3211 let json_value = from_str("{\"dog\":{\"cat\": {\"mouse\" : \"cheese\"}}}").unwrap();
3212 let found_str = json_value.find_path(&["dog", "cat", "mouse"]);
3213 assert!(found_str.unwrap().as_string().unwrap() == "cheese");
3218 let json_value = from_str("{\"dog\":{\"cat\": {\"mouse\" : \"cheese\"}}}").unwrap();
3219 let found_str = json_value.search("mouse").and_then(|j| j.as_string());
3220 assert!(found_str.unwrap() == "cheese");
3225 let json_value = from_str("{\"animals\":[\"dog\",\"cat\",\"mouse\"]}").unwrap();
3226 let ref array = json_value["animals"];
3227 assert_eq!(array[0].as_string().unwrap(), "dog");
3228 assert_eq!(array[1].as_string().unwrap(), "cat");
3229 assert_eq!(array[2].as_string().unwrap(), "mouse");
3233 fn test_is_object(){
3234 let json_value = from_str("{}").unwrap();
3235 assert!(json_value.is_object());
3239 fn test_as_object(){
3240 let json_value = from_str("{}").unwrap();
3241 let json_object = json_value.as_object();
3242 assert!(json_object.is_some());
3247 let json_value = from_str("[1, 2, 3]").unwrap();
3248 assert!(json_value.is_array());
3253 let json_value = from_str("[1, 2, 3]").unwrap();
3254 let json_array = json_value.as_array();
3255 let expected_length = 3;
3256 assert!(json_array.is_some() && json_array.unwrap().len() == expected_length);
3260 fn test_is_string(){
3261 let json_value = from_str("\"dog\"").unwrap();
3262 assert!(json_value.is_string());
3266 fn test_as_string(){
3267 let json_value = from_str("\"dog\"").unwrap();
3268 let json_str = json_value.as_string();
3269 let expected_str = "dog";
3270 assert_eq!(json_str, Some(expected_str));
3274 fn test_is_number(){
3275 let json_value = from_str("12").unwrap();
3276 assert!(json_value.is_number());
3281 let json_value = from_str("-12").unwrap();
3282 assert!(json_value.is_i64());
3284 let json_value = from_str("12").unwrap();
3285 assert!(!json_value.is_i64());
3287 let json_value = from_str("12.0").unwrap();
3288 assert!(!json_value.is_i64());
3293 let json_value = from_str("12").unwrap();
3294 assert!(json_value.is_u64());
3296 let json_value = from_str("-12").unwrap();
3297 assert!(!json_value.is_u64());
3299 let json_value = from_str("12.0").unwrap();
3300 assert!(!json_value.is_u64());
3305 let json_value = from_str("12").unwrap();
3306 assert!(!json_value.is_f64());
3308 let json_value = from_str("-12").unwrap();
3309 assert!(!json_value.is_f64());
3311 let json_value = from_str("12.0").unwrap();
3312 assert!(json_value.is_f64());
3314 let json_value = from_str("-12.0").unwrap();
3315 assert!(json_value.is_f64());
3320 let json_value = from_str("-12").unwrap();
3321 let json_num = json_value.as_i64();
3322 assert_eq!(json_num, Some(-12));
3327 let json_value = from_str("12").unwrap();
3328 let json_num = json_value.as_u64();
3329 assert_eq!(json_num, Some(12));
3334 let json_value = from_str("12.0").unwrap();
3335 let json_num = json_value.as_f64();
3336 assert_eq!(json_num, Some(12f64));
3340 fn test_is_boolean(){
3341 let json_value = from_str("false").unwrap();
3342 assert!(json_value.is_boolean());
3346 fn test_as_boolean(){
3347 let json_value = from_str("false").unwrap();
3348 let json_bool = json_value.as_boolean();
3349 let expected_bool = false;
3350 assert!(json_bool.is_some() && json_bool.unwrap() == expected_bool);
3355 let json_value = from_str("null").unwrap();
3356 assert!(json_value.is_null());
3361 let json_value = from_str("null").unwrap();
3362 let json_null = json_value.as_null();
3363 let expected_null = ();
3364 assert!(json_null.is_some() && json_null.unwrap() == expected_null);
3368 fn test_encode_hashmap_with_numeric_key() {
3369 use std::str::from_utf8;
3370 use std::io::Writer;
3371 use std::collections::HashMap;
3372 let mut hm: HashMap<uint, bool> = HashMap::new();
3374 let mut mem_buf = Vec::new();
3375 write!(&mut mem_buf, "{}", super::as_pretty_json(&hm)).unwrap();
3376 let json_str = from_utf8(mem_buf[]).unwrap();
3377 match from_str(json_str) {
3378 Err(_) => panic!("Unable to parse json_str: {}", json_str),
3379 _ => {} // it parsed and we are good to go
3384 fn test_prettyencode_hashmap_with_numeric_key() {
3385 use std::str::from_utf8;
3386 use std::io::Writer;
3387 use std::collections::HashMap;
3388 let mut hm: HashMap<uint, bool> = HashMap::new();
3390 let mut mem_buf = Vec::new();
3391 write!(&mut mem_buf, "{}", super::as_pretty_json(&hm)).unwrap();
3392 let json_str = from_utf8(mem_buf[]).unwrap();
3393 match from_str(json_str) {
3394 Err(_) => panic!("Unable to parse json_str: {}", json_str),
3395 _ => {} // it parsed and we are good to go
3400 fn test_prettyencoder_indent_level_param() {
3401 use std::str::from_utf8;
3402 use std::collections::BTreeMap;
3404 let mut tree = BTreeMap::new();
3406 tree.insert("hello".to_string(), String("guten tag".to_string()));
3407 tree.insert("goodbye".to_string(), String("sayonara".to_string()));
3410 // The following layout below should look a lot like
3411 // the pretty-printed JSON (indent * x)
3414 String("greetings".to_string()), // 1x
3415 Object(tree), // 1x + 2x + 2x + 1x
3417 // End JSON array (7 lines)
3420 // Helper function for counting indents
3421 fn indents(source: &str) -> uint {
3422 let trimmed = source.trim_left_matches(' ');
3423 source.len() - trimmed.len()
3426 // Test up to 4 spaces of indents (more?)
3427 for i in range(0, 4u) {
3428 let mut writer = Vec::new();
3429 write!(&mut writer, "{}",
3430 super::as_pretty_json(&json).indent(i)).unwrap();
3432 let printed = from_utf8(writer[]).unwrap();
3434 // Check for indents at each line
3435 let lines: Vec<&str> = printed.lines().collect();
3436 assert_eq!(lines.len(), 7); // JSON should be 7 lines
3438 assert_eq!(indents(lines[0]), 0 * i); // [
3439 assert_eq!(indents(lines[1]), 1 * i); // "greetings",
3440 assert_eq!(indents(lines[2]), 1 * i); // {
3441 assert_eq!(indents(lines[3]), 2 * i); // "hello": "guten tag",
3442 assert_eq!(indents(lines[4]), 2 * i); // "goodbye": "sayonara"
3443 assert_eq!(indents(lines[5]), 1 * i); // },
3444 assert_eq!(indents(lines[6]), 0 * i); // ]
3446 // Finally, test that the pretty-printed JSON is valid
3447 from_str(printed).ok().expect("Pretty-printed JSON is invalid!");
3452 fn test_hashmap_with_numeric_key_can_handle_double_quote_delimited_key() {
3453 use std::collections::HashMap;
3455 let json_str = "{\"1\":true}";
3456 let json_obj = match from_str(json_str) {
3457 Err(_) => panic!("Unable to parse json_str: {}", json_str),
3460 let mut decoder = Decoder::new(json_obj);
3461 let _hm: HashMap<uint, bool> = Decodable::decode(&mut decoder).unwrap();
3465 fn test_hashmap_with_numeric_key_will_error_with_string_keys() {
3466 use std::collections::HashMap;
3468 let json_str = "{\"a\":true}";
3469 let json_obj = match from_str(json_str) {
3470 Err(_) => panic!("Unable to parse json_str: {}", json_str),
3473 let mut decoder = Decoder::new(json_obj);
3474 let result: Result<HashMap<uint, bool>, DecoderError> = Decodable::decode(&mut decoder);
3475 assert_eq!(result, Err(ExpectedError("Number".to_string(), "a".to_string())));
3478 fn assert_stream_equal(src: &str,
3479 expected: Vec<(JsonEvent, Vec<StackElement>)>) {
3480 let mut parser = Parser::new(src.chars());
3483 let evt = match parser.next() {
3487 let (ref expected_evt, ref expected_stack) = expected[i];
3488 if !parser.stack().is_equal_to(expected_stack.as_slice()) {
3489 panic!("Parser stack is not equal to {}", expected_stack);
3491 assert_eq!(&evt, expected_evt);
3496 #[cfg_attr(target_word_size = "32", ignore)] // FIXME(#14064)
3497 fn test_streaming_parser() {
3498 assert_stream_equal(
3499 r#"{ "foo":"bar", "array" : [0, 1, 2, 3, 4, 5], "idents":[null,true,false]}"#,
3501 (ObjectStart, vec![]),
3502 (StringValue("bar".to_string()), vec![Key("foo")]),
3503 (ArrayStart, vec![Key("array")]),
3504 (U64Value(0), vec![Key("array"), Index(0)]),
3505 (U64Value(1), vec![Key("array"), Index(1)]),
3506 (U64Value(2), vec![Key("array"), Index(2)]),
3507 (U64Value(3), vec![Key("array"), Index(3)]),
3508 (U64Value(4), vec![Key("array"), Index(4)]),
3509 (U64Value(5), vec![Key("array"), Index(5)]),
3510 (ArrayEnd, vec![Key("array")]),
3511 (ArrayStart, vec![Key("idents")]),
3512 (NullValue, vec![Key("idents"), Index(0)]),
3513 (BooleanValue(true), vec![Key("idents"), Index(1)]),
3514 (BooleanValue(false), vec![Key("idents"), Index(2)]),
3515 (ArrayEnd, vec![Key("idents")]),
3516 (ObjectEnd, vec![]),
3520 fn last_event(src: &str) -> JsonEvent {
3521 let mut parser = Parser::new(src.chars());
3522 let mut evt = NullValue;
3524 evt = match parser.next() {
3532 #[cfg_attr(target_word_size = "32", ignore)] // FIXME(#14064)
3533 fn test_read_object_streaming() {
3534 assert_eq!(last_event("{ "), Error(SyntaxError(EOFWhileParsingObject, 1, 3)));
3535 assert_eq!(last_event("{1"), Error(SyntaxError(KeyMustBeAString, 1, 2)));
3536 assert_eq!(last_event("{ \"a\""), Error(SyntaxError(EOFWhileParsingObject, 1, 6)));
3537 assert_eq!(last_event("{\"a\""), Error(SyntaxError(EOFWhileParsingObject, 1, 5)));
3538 assert_eq!(last_event("{\"a\" "), Error(SyntaxError(EOFWhileParsingObject, 1, 6)));
3540 assert_eq!(last_event("{\"a\" 1"), Error(SyntaxError(ExpectedColon, 1, 6)));
3541 assert_eq!(last_event("{\"a\":"), Error(SyntaxError(EOFWhileParsingValue, 1, 6)));
3542 assert_eq!(last_event("{\"a\":1"), Error(SyntaxError(EOFWhileParsingObject, 1, 7)));
3543 assert_eq!(last_event("{\"a\":1 1"), Error(SyntaxError(InvalidSyntax, 1, 8)));
3544 assert_eq!(last_event("{\"a\":1,"), Error(SyntaxError(EOFWhileParsingObject, 1, 8)));
3545 assert_eq!(last_event("{\"a\":1,}"), Error(SyntaxError(TrailingComma, 1, 8)));
3547 assert_stream_equal(
3549 vec![(ObjectStart, vec![]), (ObjectEnd, vec![])]
3551 assert_stream_equal(
3554 (ObjectStart, vec![]),
3555 (U64Value(3), vec![Key("a")]),
3556 (ObjectEnd, vec![]),
3559 assert_stream_equal(
3560 "{ \"a\": null, \"b\" : true }",
3562 (ObjectStart, vec![]),
3563 (NullValue, vec![Key("a")]),
3564 (BooleanValue(true), vec![Key("b")]),
3565 (ObjectEnd, vec![]),
3568 assert_stream_equal(
3569 "{\"a\" : 1.0 ,\"b\": [ true ]}",
3571 (ObjectStart, vec![]),
3572 (F64Value(1.0), vec![Key("a")]),
3573 (ArrayStart, vec![Key("b")]),
3574 (BooleanValue(true),vec![Key("b"), Index(0)]),
3575 (ArrayEnd, vec![Key("b")]),
3576 (ObjectEnd, vec![]),
3579 assert_stream_equal(
3585 { "c": {"d": null} }
3589 (ObjectStart, vec![]),
3590 (F64Value(1.0), vec![Key("a")]),
3591 (ArrayStart, vec![Key("b")]),
3592 (BooleanValue(true), vec![Key("b"), Index(0)]),
3593 (StringValue("foo\nbar".to_string()), vec![Key("b"), Index(1)]),
3594 (ObjectStart, vec![Key("b"), Index(2)]),
3595 (ObjectStart, vec![Key("b"), Index(2), Key("c")]),
3596 (NullValue, vec![Key("b"), Index(2), Key("c"), Key("d")]),
3597 (ObjectEnd, vec![Key("b"), Index(2), Key("c")]),
3598 (ObjectEnd, vec![Key("b"), Index(2)]),
3599 (ArrayEnd, vec![Key("b")]),
3600 (ObjectEnd, vec![]),
3605 #[cfg_attr(target_word_size = "32", ignore)] // FIXME(#14064)
3606 fn test_read_array_streaming() {
3607 assert_stream_equal(
3610 (ArrayStart, vec![]),
3614 assert_stream_equal(
3617 (ArrayStart, vec![]),
3621 assert_stream_equal(
3624 (ArrayStart, vec![]),
3625 (BooleanValue(true), vec![Index(0)]),
3629 assert_stream_equal(
3632 (ArrayStart, vec![]),
3633 (BooleanValue(false), vec![Index(0)]),
3637 assert_stream_equal(
3640 (ArrayStart, vec![]),
3641 (NullValue, vec![Index(0)]),
3645 assert_stream_equal(
3648 (ArrayStart, vec![]),
3649 (U64Value(3), vec![Index(0)]),
3650 (U64Value(1), vec![Index(1)]),
3654 assert_stream_equal(
3657 (ArrayStart, vec![]),
3658 (U64Value(3), vec![Index(0)]),
3659 (U64Value(2), vec![Index(1)]),
3663 assert_stream_equal(
3666 (ArrayStart, vec![]),
3667 (U64Value(2), vec![Index(0)]),
3668 (ArrayStart, vec![Index(1)]),
3669 (U64Value(4), vec![Index(1), Index(0)]),
3670 (U64Value(1), vec![Index(1), Index(1)]),
3671 (ArrayEnd, vec![Index(1)]),
3676 assert_eq!(last_event("["), Error(SyntaxError(EOFWhileParsingValue, 1, 2)));
3678 assert_eq!(from_str("["), Err(SyntaxError(EOFWhileParsingValue, 1, 2)));
3679 assert_eq!(from_str("[1"), Err(SyntaxError(EOFWhileParsingArray, 1, 3)));
3680 assert_eq!(from_str("[1,"), Err(SyntaxError(EOFWhileParsingValue, 1, 4)));
3681 assert_eq!(from_str("[1,]"), Err(SyntaxError(InvalidSyntax, 1, 4)));
3682 assert_eq!(from_str("[6 7]"), Err(SyntaxError(InvalidSyntax, 1, 4)));
3686 fn test_trailing_characters_streaming() {
3687 assert_eq!(last_event("nulla"), Error(SyntaxError(TrailingCharacters, 1, 5)));
3688 assert_eq!(last_event("truea"), Error(SyntaxError(TrailingCharacters, 1, 5)));
3689 assert_eq!(last_event("falsea"), Error(SyntaxError(TrailingCharacters, 1, 6)));
3690 assert_eq!(last_event("1a"), Error(SyntaxError(TrailingCharacters, 1, 2)));
3691 assert_eq!(last_event("[]a"), Error(SyntaxError(TrailingCharacters, 1, 3)));
3692 assert_eq!(last_event("{}a"), Error(SyntaxError(TrailingCharacters, 1, 3)));
3695 fn test_read_identifiers_streaming() {
3696 assert_eq!(Parser::new("null".chars()).next(), Some(NullValue));
3697 assert_eq!(Parser::new("true".chars()).next(), Some(BooleanValue(true)));
3698 assert_eq!(Parser::new("false".chars()).next(), Some(BooleanValue(false)));
3700 assert_eq!(last_event("n"), Error(SyntaxError(InvalidSyntax, 1, 2)));
3701 assert_eq!(last_event("nul"), Error(SyntaxError(InvalidSyntax, 1, 4)));
3702 assert_eq!(last_event("t"), Error(SyntaxError(InvalidSyntax, 1, 2)));
3703 assert_eq!(last_event("truz"), Error(SyntaxError(InvalidSyntax, 1, 4)));
3704 assert_eq!(last_event("f"), Error(SyntaxError(InvalidSyntax, 1, 2)));
3705 assert_eq!(last_event("faz"), Error(SyntaxError(InvalidSyntax, 1, 3)));
3710 let mut stack = Stack::new();
3712 assert!(stack.is_empty());
3713 assert!(stack.len() == 0);
3714 assert!(!stack.last_is_index());
3716 stack.push_index(0);
3719 assert!(stack.len() == 1);
3720 assert!(stack.is_equal_to(&[Index(1)]));
3721 assert!(stack.starts_with(&[Index(1)]));
3722 assert!(stack.ends_with(&[Index(1)]));
3723 assert!(stack.last_is_index());
3724 assert!(stack.get(0) == Index(1));
3726 stack.push_key("foo".to_string());
3728 assert!(stack.len() == 2);
3729 assert!(stack.is_equal_to(&[Index(1), Key("foo")]));
3730 assert!(stack.starts_with(&[Index(1), Key("foo")]));
3731 assert!(stack.starts_with(&[Index(1)]));
3732 assert!(stack.ends_with(&[Index(1), Key("foo")]));
3733 assert!(stack.ends_with(&[Key("foo")]));
3734 assert!(!stack.last_is_index());
3735 assert!(stack.get(0) == Index(1));
3736 assert!(stack.get(1) == Key("foo"));
3738 stack.push_key("bar".to_string());
3740 assert!(stack.len() == 3);
3741 assert!(stack.is_equal_to(&[Index(1), Key("foo"), Key("bar")]));
3742 assert!(stack.starts_with(&[Index(1)]));
3743 assert!(stack.starts_with(&[Index(1), Key("foo")]));
3744 assert!(stack.starts_with(&[Index(1), Key("foo"), Key("bar")]));
3745 assert!(stack.ends_with(&[Key("bar")]));
3746 assert!(stack.ends_with(&[Key("foo"), Key("bar")]));
3747 assert!(stack.ends_with(&[Index(1), Key("foo"), Key("bar")]));
3748 assert!(!stack.last_is_index());
3749 assert!(stack.get(0) == Index(1));
3750 assert!(stack.get(1) == Key("foo"));
3751 assert!(stack.get(2) == Key("bar"));
3755 assert!(stack.len() == 2);
3756 assert!(stack.is_equal_to(&[Index(1), Key("foo")]));
3757 assert!(stack.starts_with(&[Index(1), Key("foo")]));
3758 assert!(stack.starts_with(&[Index(1)]));
3759 assert!(stack.ends_with(&[Index(1), Key("foo")]));
3760 assert!(stack.ends_with(&[Key("foo")]));
3761 assert!(!stack.last_is_index());
3762 assert!(stack.get(0) == Index(1));
3763 assert!(stack.get(1) == Key("foo"));
3768 use std::collections::{HashMap,BTreeMap};
3771 let array2 = Array(vec!(U64(1), U64(2)));
3772 let array3 = Array(vec!(U64(1), U64(2), U64(3)));
3774 let mut tree_map = BTreeMap::new();
3775 tree_map.insert("a".to_string(), U64(1));
3776 tree_map.insert("b".to_string(), U64(2));
3780 assert_eq!(array2.to_json(), array2);
3781 assert_eq!(object.to_json(), object);
3782 assert_eq!(3_i.to_json(), I64(3));
3783 assert_eq!(4_i8.to_json(), I64(4));
3784 assert_eq!(5_i16.to_json(), I64(5));
3785 assert_eq!(6_i32.to_json(), I64(6));
3786 assert_eq!(7_i64.to_json(), I64(7));
3787 assert_eq!(8_u.to_json(), U64(8));
3788 assert_eq!(9_u8.to_json(), U64(9));
3789 assert_eq!(10_u16.to_json(), U64(10));
3790 assert_eq!(11_u32.to_json(), U64(11));
3791 assert_eq!(12_u64.to_json(), U64(12));
3792 assert_eq!(13.0_f32.to_json(), F64(13.0_f64));
3793 assert_eq!(14.0_f64.to_json(), F64(14.0_f64));
3794 assert_eq!(().to_json(), Null);
3795 assert_eq!(f32::INFINITY.to_json(), Null);
3796 assert_eq!(f64::NAN.to_json(), Null);
3797 assert_eq!(true.to_json(), Boolean(true));
3798 assert_eq!(false.to_json(), Boolean(false));
3799 assert_eq!("abc".to_json(), String("abc".to_string()));
3800 assert_eq!("abc".to_string().to_json(), String("abc".to_string()));
3801 assert_eq!((1u, 2u).to_json(), array2);
3802 assert_eq!((1u, 2u, 3u).to_json(), array3);
3803 assert_eq!([1u, 2].to_json(), array2);
3804 assert_eq!((&[1u, 2, 3]).to_json(), array3);
3805 assert_eq!((vec![1u, 2]).to_json(), array2);
3806 assert_eq!(vec!(1u, 2, 3).to_json(), array3);
3807 let mut tree_map = BTreeMap::new();
3808 tree_map.insert("a".to_string(), 1u);
3809 tree_map.insert("b".to_string(), 2);
3810 assert_eq!(tree_map.to_json(), object);
3811 let mut hash_map = HashMap::new();
3812 hash_map.insert("a".to_string(), 1u);
3813 hash_map.insert("b".to_string(), 2);
3814 assert_eq!(hash_map.to_json(), object);
3815 assert_eq!(Some(15i).to_json(), I64(15));
3816 assert_eq!(Some(15u).to_json(), U64(15));
3817 assert_eq!(None::<int>.to_json(), Null);
3821 fn bench_streaming_small(b: &mut Bencher) {
3823 let mut parser = Parser::new(
3829 { "c": {"d": null} }
3834 match parser.next() {
3842 fn bench_small(b: &mut Bencher) {
3844 let _ = from_str(r#"{
3849 { "c": {"d": null} }
3855 fn big_json() -> string::String {
3856 let mut src = "[\n".to_string();
3857 for _ in range(0i, 500) {
3858 src.push_str(r#"{ "a": true, "b": null, "c":3.1415, "d": "Hello world", "e": \
3861 src.push_str("{}]");
3866 fn bench_streaming_large(b: &mut Bencher) {
3867 let src = big_json();
3869 let mut parser = Parser::new(src.chars());
3871 match parser.next() {
3879 fn bench_large(b: &mut Bencher) {
3880 let src = big_json();
3881 b.iter( || { let _ = from_str(src.as_slice()); });