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::ErrorCode::*;
197 use self::ParserError::*;
198 use self::DecoderError::*;
199 use self::ParserState::*;
200 use self::InternalStackElement::*;
203 use std::collections::{HashMap, BTreeMap};
204 use std::{char, f64, fmt, io, num, str};
205 use std::mem::{swap, transmute};
206 use std::num::{Float, Int};
207 use std::num::FpCategory as Fp;
208 use std::str::FromStr;
211 use unicode::str as unicode_str;
212 use unicode::str::Utf16Item;
216 /// Represents a json value
217 #[derive(Clone, PartialEq, PartialOrd, Show)]
222 String(string::String),
225 Object(self::Object),
229 pub type Array = Vec<Json>;
230 pub type Object = BTreeMap<string::String, Json>;
232 pub struct PrettyJson<'a> { inner: &'a Json }
234 pub struct AsJson<'a, T: 'a> { inner: &'a T }
235 pub struct AsPrettyJson<'a, T: 'a> { inner: &'a T, indent: Option<uint> }
237 /// The errors that can arise while parsing a JSON stream.
238 #[derive(Clone, Copy, PartialEq)]
242 EOFWhileParsingObject,
243 EOFWhileParsingArray,
244 EOFWhileParsingValue,
245 EOFWhileParsingString,
251 InvalidUnicodeCodePoint,
252 LoneLeadingSurrogateInHexEscape,
253 UnexpectedEndOfHexEscape,
259 #[derive(Clone, Copy, PartialEq, Show)]
260 pub enum ParserError {
262 SyntaxError(ErrorCode, uint, uint),
263 IoError(io::IoErrorKind, &'static str),
266 // Builder and Parser have the same errors.
267 pub type BuilderError = ParserError;
269 #[derive(Clone, PartialEq, Show)]
270 pub enum DecoderError {
271 ParseError(ParserError),
272 ExpectedError(string::String, string::String),
273 MissingFieldError(string::String),
274 UnknownVariantError(string::String),
275 ApplicationError(string::String)
278 /// Returns a readable error string for a given error code.
279 pub fn error_str(error: ErrorCode) -> &'static str {
281 InvalidSyntax => "invalid syntax",
282 InvalidNumber => "invalid number",
283 EOFWhileParsingObject => "EOF While parsing object",
284 EOFWhileParsingArray => "EOF While parsing array",
285 EOFWhileParsingValue => "EOF While parsing value",
286 EOFWhileParsingString => "EOF While parsing string",
287 KeyMustBeAString => "key must be a string",
288 ExpectedColon => "expected `:`",
289 TrailingCharacters => "trailing characters",
290 TrailingComma => "trailing comma",
291 InvalidEscape => "invalid escape",
292 UnrecognizedHex => "invalid \\u{ esc}ape (unrecognized hex)",
293 NotFourDigit => "invalid \\u{ esc}ape (not four digits)",
294 NotUtf8 => "contents not utf-8",
295 InvalidUnicodeCodePoint => "invalid Unicode code point",
296 LoneLeadingSurrogateInHexEscape => "lone leading surrogate in hex escape",
297 UnexpectedEndOfHexEscape => "unexpected end of hex escape",
301 /// Shortcut function to decode a JSON `&str` into an object
302 pub fn decode<T: ::Decodable>(s: &str) -> DecodeResult<T> {
303 let json = match from_str(s) {
305 Err(e) => return Err(ParseError(e))
308 let mut decoder = Decoder::new(json);
309 ::Decodable::decode(&mut decoder)
312 /// Shortcut function to encode a `T` into a JSON `String`
313 pub fn encode<T: ::Encodable>(object: &T) -> string::String {
314 let mut s = String::new();
316 let mut encoder = Encoder::new(&mut s);
317 let _ = object.encode(&mut encoder);
322 impl fmt::Show for ErrorCode {
323 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
324 error_str(*self).fmt(f)
328 fn io_error_to_error(io: io::IoError) -> ParserError {
329 IoError(io.kind, io.desc)
332 impl std::error::Error for DecoderError {
333 fn description(&self) -> &str { "decoder error" }
334 fn detail(&self) -> Option<std::string::String> { Some(format!("{:?}", self)) }
337 pub type EncodeResult = fmt::Result;
338 pub type DecodeResult<T> = Result<T, DecoderError>;
340 fn escape_str(wr: &mut fmt::Writer, v: &str) -> fmt::Result {
341 try!(wr.write_str("\""));
345 for (i, byte) in v.bytes().enumerate() {
346 let escaped = match byte {
349 b'\x00' => "\\u0000",
350 b'\x01' => "\\u0001",
351 b'\x02' => "\\u0002",
352 b'\x03' => "\\u0003",
353 b'\x04' => "\\u0004",
354 b'\x05' => "\\u0005",
355 b'\x06' => "\\u0006",
356 b'\x07' => "\\u0007",
360 b'\x0b' => "\\u000b",
363 b'\x0e' => "\\u000e",
364 b'\x0f' => "\\u000f",
365 b'\x10' => "\\u0010",
366 b'\x11' => "\\u0011",
367 b'\x12' => "\\u0012",
368 b'\x13' => "\\u0013",
369 b'\x14' => "\\u0014",
370 b'\x15' => "\\u0015",
371 b'\x16' => "\\u0016",
372 b'\x17' => "\\u0017",
373 b'\x18' => "\\u0018",
374 b'\x19' => "\\u0019",
375 b'\x1a' => "\\u001a",
376 b'\x1b' => "\\u001b",
377 b'\x1c' => "\\u001c",
378 b'\x1d' => "\\u001d",
379 b'\x1e' => "\\u001e",
380 b'\x1f' => "\\u001f",
381 b'\x7f' => "\\u007f",
386 try!(wr.write_str(v.index(&(start..i))));
389 try!(wr.write_str(escaped));
394 if start != v.len() {
395 try!(wr.write_str(v.index(&(start..))));
401 fn escape_char(writer: &mut fmt::Writer, v: char) -> fmt::Result {
402 let mut buf = [0; 4];
403 let n = v.encode_utf8(&mut buf).unwrap();
404 let buf = unsafe { str::from_utf8_unchecked(buf.index(&(0..n))) };
405 escape_str(writer, buf)
408 fn spaces(wr: &mut fmt::Writer, mut n: uint) -> fmt::Result {
409 const BUF: &'static str = " ";
411 while n >= BUF.len() {
412 try!(wr.write_str(BUF));
417 wr.write_str(BUF.index(&(0..n)))
423 fn fmt_number_or_null(v: f64) -> string::String {
425 Fp::Nan | Fp::Infinite => string::String::from_str("null"),
426 _ if v.fract() != 0f64 => f64::to_str_digits(v, 6u),
427 _ => f64::to_str_digits(v, 6u) + ".0",
431 /// A structure for implementing serialization to JSON.
432 pub struct Encoder<'a> {
433 writer: &'a mut (fmt::Writer+'a),
436 impl<'a> Encoder<'a> {
437 /// Creates a new JSON encoder whose output will be written to the writer
439 pub fn new(writer: &'a mut fmt::Writer) -> Encoder<'a> {
440 Encoder { writer: writer }
444 impl<'a> ::Encoder for Encoder<'a> {
445 type Error = fmt::Error;
447 fn emit_nil(&mut self) -> EncodeResult { write!(self.writer, "null") }
449 fn emit_uint(&mut self, v: uint) -> EncodeResult { write!(self.writer, "{}", v) }
450 fn emit_u64(&mut self, v: u64) -> EncodeResult { write!(self.writer, "{}", v) }
451 fn emit_u32(&mut self, v: u32) -> EncodeResult { write!(self.writer, "{}", v) }
452 fn emit_u16(&mut self, v: u16) -> EncodeResult { write!(self.writer, "{}", v) }
453 fn emit_u8(&mut self, v: u8) -> EncodeResult { write!(self.writer, "{}", v) }
455 fn emit_int(&mut self, v: int) -> EncodeResult { write!(self.writer, "{}", v) }
456 fn emit_i64(&mut self, v: i64) -> EncodeResult { write!(self.writer, "{}", v) }
457 fn emit_i32(&mut self, v: i32) -> EncodeResult { write!(self.writer, "{}", v) }
458 fn emit_i16(&mut self, v: i16) -> EncodeResult { write!(self.writer, "{}", v) }
459 fn emit_i8(&mut self, v: i8) -> EncodeResult { write!(self.writer, "{}", v) }
461 fn emit_bool(&mut self, v: bool) -> EncodeResult {
463 write!(self.writer, "true")
465 write!(self.writer, "false")
469 fn emit_f64(&mut self, v: f64) -> EncodeResult {
470 write!(self.writer, "{}", fmt_number_or_null(v))
472 fn emit_f32(&mut self, v: f32) -> EncodeResult {
473 self.emit_f64(v as f64)
476 fn emit_char(&mut self, v: char) -> EncodeResult {
477 escape_char(self.writer, v)
479 fn emit_str(&mut self, v: &str) -> EncodeResult {
480 escape_str(self.writer, v)
483 fn emit_enum<F>(&mut self, _name: &str, f: F) -> EncodeResult where
484 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
489 fn emit_enum_variant<F>(&mut self,
493 f: F) -> EncodeResult where
494 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
496 // enums are encoded as strings or objects
498 // Kangaroo(34,"William") => {"variant": "Kangaroo", "fields": [34,"William"]}
500 escape_str(self.writer, name)
502 try!(write!(self.writer, "{{\"variant\":"));
503 try!(escape_str(self.writer, name));
504 try!(write!(self.writer, ",\"fields\":["));
506 write!(self.writer, "]}}")
510 fn emit_enum_variant_arg<F>(&mut self, idx: uint, f: F) -> EncodeResult where
511 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
514 try!(write!(self.writer, ","));
519 fn emit_enum_struct_variant<F>(&mut self,
523 f: F) -> EncodeResult where
524 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
526 self.emit_enum_variant(name, id, cnt, f)
529 fn emit_enum_struct_variant_field<F>(&mut self,
532 f: F) -> EncodeResult where
533 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
535 self.emit_enum_variant_arg(idx, f)
538 fn emit_struct<F>(&mut self, _: &str, _: uint, f: F) -> EncodeResult where
539 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
541 try!(write!(self.writer, "{{"));
543 write!(self.writer, "}}")
546 fn emit_struct_field<F>(&mut self, name: &str, idx: uint, f: F) -> EncodeResult where
547 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
549 if idx != 0 { try!(write!(self.writer, ",")); }
550 try!(escape_str(self.writer, name));
551 try!(write!(self.writer, ":"));
555 fn emit_tuple<F>(&mut self, len: uint, f: F) -> EncodeResult where
556 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
558 self.emit_seq(len, f)
560 fn emit_tuple_arg<F>(&mut self, idx: uint, f: F) -> EncodeResult where
561 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
563 self.emit_seq_elt(idx, f)
566 fn emit_tuple_struct<F>(&mut self, _name: &str, len: uint, f: F) -> EncodeResult where
567 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
569 self.emit_seq(len, f)
571 fn emit_tuple_struct_arg<F>(&mut self, idx: uint, f: F) -> EncodeResult where
572 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
574 self.emit_seq_elt(idx, f)
577 fn emit_option<F>(&mut self, f: F) -> EncodeResult where
578 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
582 fn emit_option_none(&mut self) -> EncodeResult { self.emit_nil() }
583 fn emit_option_some<F>(&mut self, f: F) -> EncodeResult where
584 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
589 fn emit_seq<F>(&mut self, _len: uint, f: F) -> EncodeResult where
590 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
592 try!(write!(self.writer, "["));
594 write!(self.writer, "]")
597 fn emit_seq_elt<F>(&mut self, idx: uint, f: F) -> EncodeResult where
598 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
601 try!(write!(self.writer, ","));
606 fn emit_map<F>(&mut self, _len: uint, f: F) -> EncodeResult where
607 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
609 try!(write!(self.writer, "{{"));
611 write!(self.writer, "}}")
614 fn emit_map_elt_key<F>(&mut self, idx: uint, mut f: F) -> EncodeResult where
615 F: FnMut(&mut Encoder<'a>) -> EncodeResult,
617 if idx != 0 { try!(write!(self.writer, ",")) }
618 // ref #12967, make sure to wrap a key in double quotes,
619 // in the event that its of a type that omits them (eg numbers)
620 let mut buf = Vec::new();
621 // FIXME(14302) remove the transmute and unsafe block.
623 let mut check_encoder = Encoder::new(&mut buf);
624 try!(f(transmute(&mut check_encoder)));
626 let out = str::from_utf8(buf.index(&FullRange)).unwrap();
627 let needs_wrapping = out.char_at(0) != '"' && out.char_at_reverse(out.len()) != '"';
628 if needs_wrapping { try!(write!(self.writer, "\"")); }
630 if needs_wrapping { try!(write!(self.writer, "\"")); }
634 fn emit_map_elt_val<F>(&mut self, _idx: uint, f: F) -> EncodeResult where
635 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
637 try!(write!(self.writer, ":"));
642 /// Another encoder for JSON, but prints out human-readable JSON instead of
644 pub struct PrettyEncoder<'a> {
645 writer: &'a mut (fmt::Writer+'a),
650 impl<'a> PrettyEncoder<'a> {
651 /// Creates a new encoder whose output will be written to the specified writer
652 pub fn new(writer: &'a mut fmt::Writer) -> PrettyEncoder<'a> {
653 PrettyEncoder { writer: writer, curr_indent: 0, indent: 2, }
656 /// Set the number of spaces to indent for each level.
657 /// This is safe to set during encoding.
658 pub fn set_indent(&mut self, indent: uint) {
659 // self.indent very well could be 0 so we need to use checked division.
660 let level = self.curr_indent.checked_div(self.indent).unwrap_or(0);
661 self.indent = indent;
662 self.curr_indent = level * self.indent;
666 impl<'a> ::Encoder for PrettyEncoder<'a> {
667 type Error = fmt::Error;
669 fn emit_nil(&mut self) -> EncodeResult { write!(self.writer, "null") }
671 fn emit_uint(&mut self, v: uint) -> EncodeResult { write!(self.writer, "{}", v) }
672 fn emit_u64(&mut self, v: u64) -> EncodeResult { write!(self.writer, "{}", v) }
673 fn emit_u32(&mut self, v: u32) -> EncodeResult { write!(self.writer, "{}", v) }
674 fn emit_u16(&mut self, v: u16) -> EncodeResult { write!(self.writer, "{}", v) }
675 fn emit_u8(&mut self, v: u8) -> EncodeResult { write!(self.writer, "{}", v) }
677 fn emit_int(&mut self, v: int) -> EncodeResult { write!(self.writer, "{}", v) }
678 fn emit_i64(&mut self, v: i64) -> EncodeResult { write!(self.writer, "{}", v) }
679 fn emit_i32(&mut self, v: i32) -> EncodeResult { write!(self.writer, "{}", v) }
680 fn emit_i16(&mut self, v: i16) -> EncodeResult { write!(self.writer, "{}", v) }
681 fn emit_i8(&mut self, v: i8) -> EncodeResult { write!(self.writer, "{}", v) }
683 fn emit_bool(&mut self, v: bool) -> EncodeResult {
685 write!(self.writer, "true")
687 write!(self.writer, "false")
691 fn emit_f64(&mut self, v: f64) -> EncodeResult {
692 write!(self.writer, "{}", fmt_number_or_null(v))
694 fn emit_f32(&mut self, v: f32) -> EncodeResult {
695 self.emit_f64(v as f64)
698 fn emit_char(&mut self, v: char) -> EncodeResult {
699 escape_char(self.writer, v)
701 fn emit_str(&mut self, v: &str) -> EncodeResult {
702 escape_str(self.writer, v)
705 fn emit_enum<F>(&mut self, _name: &str, f: F) -> EncodeResult where
706 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
711 fn emit_enum_variant<F>(&mut self,
716 -> EncodeResult where
717 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
720 escape_str(self.writer, name)
722 try!(write!(self.writer, "{{\n"));
723 self.curr_indent += self.indent;
724 try!(spaces(self.writer, self.curr_indent));
725 try!(write!(self.writer, "\"variant\": "));
726 try!(escape_str(self.writer, name));
727 try!(write!(self.writer, ",\n"));
728 try!(spaces(self.writer, self.curr_indent));
729 try!(write!(self.writer, "\"fields\": [\n"));
730 self.curr_indent += self.indent;
732 self.curr_indent -= self.indent;
733 try!(write!(self.writer, "\n"));
734 try!(spaces(self.writer, self.curr_indent));
735 self.curr_indent -= self.indent;
736 try!(write!(self.writer, "]\n"));
737 try!(spaces(self.writer, self.curr_indent));
738 write!(self.writer, "}}")
742 fn emit_enum_variant_arg<F>(&mut self, idx: uint, f: F) -> EncodeResult where
743 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
746 try!(write!(self.writer, ",\n"));
748 try!(spaces(self.writer, self.curr_indent));
752 fn emit_enum_struct_variant<F>(&mut self,
756 f: F) -> EncodeResult where
757 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
759 self.emit_enum_variant(name, id, cnt, f)
762 fn emit_enum_struct_variant_field<F>(&mut self,
765 f: F) -> EncodeResult where
766 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
768 self.emit_enum_variant_arg(idx, f)
772 fn emit_struct<F>(&mut self, _: &str, len: uint, f: F) -> EncodeResult where
773 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
776 write!(self.writer, "{{}}")
778 try!(write!(self.writer, "{{"));
779 self.curr_indent += self.indent;
781 self.curr_indent -= self.indent;
782 try!(write!(self.writer, "\n"));
783 try!(spaces(self.writer, self.curr_indent));
784 write!(self.writer, "}}")
788 fn emit_struct_field<F>(&mut self, name: &str, idx: uint, f: F) -> EncodeResult where
789 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
792 try!(write!(self.writer, "\n"));
794 try!(write!(self.writer, ",\n"));
796 try!(spaces(self.writer, self.curr_indent));
797 try!(escape_str(self.writer, name));
798 try!(write!(self.writer, ": "));
802 fn emit_tuple<F>(&mut self, len: uint, f: F) -> EncodeResult where
803 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
805 self.emit_seq(len, f)
807 fn emit_tuple_arg<F>(&mut self, idx: uint, f: F) -> EncodeResult where
808 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
810 self.emit_seq_elt(idx, f)
813 fn emit_tuple_struct<F>(&mut self, _: &str, len: uint, f: F) -> EncodeResult where
814 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
816 self.emit_seq(len, f)
818 fn emit_tuple_struct_arg<F>(&mut self, idx: uint, f: F) -> EncodeResult where
819 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
821 self.emit_seq_elt(idx, f)
824 fn emit_option<F>(&mut self, f: F) -> EncodeResult where
825 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
829 fn emit_option_none(&mut self) -> EncodeResult { self.emit_nil() }
830 fn emit_option_some<F>(&mut self, f: F) -> EncodeResult where
831 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
836 fn emit_seq<F>(&mut self, len: uint, f: F) -> EncodeResult where
837 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
840 write!(self.writer, "[]")
842 try!(write!(self.writer, "["));
843 self.curr_indent += self.indent;
845 self.curr_indent -= self.indent;
846 try!(write!(self.writer, "\n"));
847 try!(spaces(self.writer, self.curr_indent));
848 write!(self.writer, "]")
852 fn emit_seq_elt<F>(&mut self, idx: uint, f: F) -> EncodeResult where
853 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
856 try!(write!(self.writer, "\n"));
858 try!(write!(self.writer, ",\n"));
860 try!(spaces(self.writer, self.curr_indent));
864 fn emit_map<F>(&mut self, len: uint, f: F) -> EncodeResult where
865 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
868 write!(self.writer, "{{}}")
870 try!(write!(self.writer, "{{"));
871 self.curr_indent += self.indent;
873 self.curr_indent -= self.indent;
874 try!(write!(self.writer, "\n"));
875 try!(spaces(self.writer, self.curr_indent));
876 write!(self.writer, "}}")
880 fn emit_map_elt_key<F>(&mut self, idx: uint, mut f: F) -> EncodeResult where
881 F: FnMut(&mut PrettyEncoder<'a>) -> EncodeResult,
884 try!(write!(self.writer, "\n"));
886 try!(write!(self.writer, ",\n"));
888 try!(spaces(self.writer, self.curr_indent));
889 // ref #12967, make sure to wrap a key in double quotes,
890 // in the event that its of a type that omits them (eg numbers)
891 let mut buf = Vec::new();
892 // FIXME(14302) remove the transmute and unsafe block.
894 let mut check_encoder = PrettyEncoder::new(&mut buf);
895 try!(f(transmute(&mut check_encoder)));
897 let out = str::from_utf8(buf.index(&FullRange)).unwrap();
898 let needs_wrapping = out.char_at(0) != '"' && out.char_at_reverse(out.len()) != '"';
899 if needs_wrapping { try!(write!(self.writer, "\"")); }
901 if needs_wrapping { try!(write!(self.writer, "\"")); }
905 fn emit_map_elt_val<F>(&mut self, _idx: uint, f: F) -> EncodeResult where
906 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
908 try!(write!(self.writer, ": "));
913 impl Encodable for Json {
914 fn encode<E: ::Encoder>(&self, e: &mut E) -> Result<(), E::Error> {
916 Json::I64(v) => v.encode(e),
917 Json::U64(v) => v.encode(e),
918 Json::F64(v) => v.encode(e),
919 Json::String(ref v) => v.encode(e),
920 Json::Boolean(v) => v.encode(e),
921 Json::Array(ref v) => v.encode(e),
922 Json::Object(ref v) => v.encode(e),
923 Json::Null => e.emit_nil(),
928 /// Create an `AsJson` wrapper which can be used to print a value as JSON
929 /// on-the-fly via `write!`
930 pub fn as_json<T>(t: &T) -> AsJson<T> {
934 /// Create an `AsPrettyJson` wrapper which can be used to print a value as JSON
935 /// on-the-fly via `write!`
936 pub fn as_pretty_json<T>(t: &T) -> AsPrettyJson<T> {
937 AsPrettyJson { inner: t, indent: None }
941 /// Borrow this json object as a pretty object to generate a pretty
942 /// representation for it via `Show`.
943 pub fn pretty(&self) -> PrettyJson {
944 PrettyJson { inner: self }
947 /// If the Json value is an Object, returns the value associated with the provided key.
948 /// Otherwise, returns None.
949 pub fn find<'a>(&'a self, key: &str) -> Option<&'a Json>{
951 &Json::Object(ref map) => map.get(key),
956 /// Attempts to get a nested Json Object for each key in `keys`.
957 /// If any key is found not to exist, find_path will return None.
958 /// Otherwise, it will return the Json value associated with the final key.
959 pub fn find_path<'a>(&'a self, keys: &[&str]) -> Option<&'a Json>{
960 let mut target = self;
961 for key in keys.iter() {
962 match target.find(*key) {
963 Some(t) => { target = t; },
970 /// If the Json value is an Object, performs a depth-first search until
971 /// a value associated with the provided key is found. If no value is found
972 /// or the Json value is not an Object, returns None.
973 pub fn search<'a>(&'a self, key: &str) -> Option<&'a Json> {
975 &Json::Object(ref map) => {
977 Some(json_value) => Some(json_value),
979 for (_, v) in map.iter() {
980 match v.search(key) {
981 x if x.is_some() => return x,
993 /// Returns true if the Json value is an Object. Returns false otherwise.
994 pub fn is_object<'a>(&'a self) -> bool {
995 self.as_object().is_some()
998 /// If the Json value is an Object, returns the associated BTreeMap.
999 /// Returns None otherwise.
1000 pub fn as_object<'a>(&'a self) -> Option<&'a Object> {
1002 &Json::Object(ref map) => Some(map),
1007 /// Returns true if the Json value is an Array. Returns false otherwise.
1008 pub fn is_array<'a>(&'a self) -> bool {
1009 self.as_array().is_some()
1012 /// If the Json value is an Array, returns the associated vector.
1013 /// Returns None otherwise.
1014 pub fn as_array<'a>(&'a self) -> Option<&'a Array> {
1016 &Json::Array(ref array) => Some(&*array),
1021 /// Returns true if the Json value is a String. Returns false otherwise.
1022 pub fn is_string<'a>(&'a self) -> bool {
1023 self.as_string().is_some()
1026 /// If the Json value is a String, returns the associated str.
1027 /// Returns None otherwise.
1028 pub fn as_string<'a>(&'a self) -> Option<&'a str> {
1030 Json::String(ref s) => Some(s.index(&FullRange)),
1035 /// Returns true if the Json value is a Number. Returns false otherwise.
1036 pub fn is_number(&self) -> bool {
1038 Json::I64(_) | Json::U64(_) | Json::F64(_) => true,
1043 /// Returns true if the Json value is a i64. Returns false otherwise.
1044 pub fn is_i64(&self) -> bool {
1046 Json::I64(_) => true,
1051 /// Returns true if the Json value is a u64. Returns false otherwise.
1052 pub fn is_u64(&self) -> bool {
1054 Json::U64(_) => true,
1059 /// Returns true if the Json value is a f64. Returns false otherwise.
1060 pub fn is_f64(&self) -> bool {
1062 Json::F64(_) => true,
1067 /// If the Json value is a number, return or cast it to a i64.
1068 /// Returns None otherwise.
1069 pub fn as_i64(&self) -> Option<i64> {
1071 Json::I64(n) => Some(n),
1072 Json::U64(n) => num::cast(n),
1077 /// If the Json value is a number, return or cast it to a u64.
1078 /// Returns None otherwise.
1079 pub fn as_u64(&self) -> Option<u64> {
1081 Json::I64(n) => num::cast(n),
1082 Json::U64(n) => Some(n),
1087 /// If the Json value is a number, return or cast it to a f64.
1088 /// Returns None otherwise.
1089 pub fn as_f64(&self) -> Option<f64> {
1091 Json::I64(n) => num::cast(n),
1092 Json::U64(n) => num::cast(n),
1093 Json::F64(n) => Some(n),
1098 /// Returns true if the Json value is a Boolean. Returns false otherwise.
1099 pub fn is_boolean(&self) -> bool {
1100 self.as_boolean().is_some()
1103 /// If the Json value is a Boolean, returns the associated bool.
1104 /// Returns None otherwise.
1105 pub fn as_boolean(&self) -> Option<bool> {
1107 &Json::Boolean(b) => Some(b),
1112 /// Returns true if the Json value is a Null. Returns false otherwise.
1113 pub fn is_null(&self) -> bool {
1114 self.as_null().is_some()
1117 /// If the Json value is a Null, returns ().
1118 /// Returns None otherwise.
1119 pub fn as_null(&self) -> Option<()> {
1121 &Json::Null => Some(()),
1127 impl<'a> Index<&'a str> for Json {
1130 fn index(&self, idx: & &str) -> &Json {
1131 self.find(*idx).unwrap()
1135 impl Index<uint> for Json {
1138 fn index<'a>(&'a self, idx: &uint) -> &'a Json {
1140 &Json::Array(ref v) => v.index(idx),
1141 _ => panic!("can only index Json with uint if it is an array")
1146 /// The output of the streaming parser.
1147 #[derive(PartialEq, Clone, Show)]
1148 pub enum JsonEvent {
1157 StringValue(string::String),
1162 #[derive(PartialEq, Show)]
1164 // Parse a value in an array, true means first element.
1166 // Parse ',' or ']' after an element in an array.
1168 // Parse a key:value in an object, true means first element.
1170 // Parse ',' or ']' after an element in an object.
1174 // Expecting the stream to end.
1176 // Parsing can't continue.
1180 /// A Stack represents the current position of the parser in the logical
1181 /// structure of the JSON stream.
1182 /// For example foo.bar[3].x
1184 stack: Vec<InternalStackElement>,
1185 str_buffer: Vec<u8>,
1188 /// StackElements compose a Stack.
1189 /// For example, StackElement::Key("foo"), StackElement::Key("bar"),
1190 /// StackElement::Index(3) and StackElement::Key("x") are the
1191 /// StackElements compositing the stack that represents foo.bar[3].x
1192 #[derive(PartialEq, Clone, Show)]
1193 pub enum StackElement<'l> {
1198 // Internally, Key elements are stored as indices in a buffer to avoid
1199 // allocating a string for every member of an object.
1200 #[derive(PartialEq, Clone, Show)]
1201 enum InternalStackElement {
1203 InternalKey(u16, u16), // start, size
1207 pub fn new() -> Stack {
1208 Stack { stack: Vec::new(), str_buffer: Vec::new() }
1211 /// Returns The number of elements in the Stack.
1212 pub fn len(&self) -> uint { self.stack.len() }
1214 /// Returns true if the stack is empty.
1215 pub fn is_empty(&self) -> bool { self.stack.is_empty() }
1217 /// Provides access to the StackElement at a given index.
1218 /// lower indices are at the bottom of the stack while higher indices are
1220 pub fn get<'l>(&'l self, idx: uint) -> StackElement<'l> {
1221 match self.stack[idx] {
1222 InternalIndex(i) => StackElement::Index(i),
1223 InternalKey(start, size) => {
1224 StackElement::Key(str::from_utf8(
1225 self.str_buffer.index(&((start as uint) .. (start as uint + size as uint))))
1231 /// Compares this stack with an array of StackElements.
1232 pub fn is_equal_to(&self, rhs: &[StackElement]) -> bool {
1233 if self.stack.len() != rhs.len() { return false; }
1234 for i in range(0, rhs.len()) {
1235 if self.get(i) != rhs[i] { return false; }
1240 /// Returns true if the bottom-most elements of this stack are the same as
1241 /// the ones passed as parameter.
1242 pub fn starts_with(&self, rhs: &[StackElement]) -> bool {
1243 if self.stack.len() < rhs.len() { return false; }
1244 for i in range(0, rhs.len()) {
1245 if self.get(i) != rhs[i] { return false; }
1250 /// Returns true if the top-most elements of this stack are the same as
1251 /// the ones passed as parameter.
1252 pub fn ends_with(&self, rhs: &[StackElement]) -> bool {
1253 if self.stack.len() < rhs.len() { return false; }
1254 let offset = self.stack.len() - rhs.len();
1255 for i in range(0, rhs.len()) {
1256 if self.get(i + offset) != rhs[i] { return false; }
1261 /// Returns the top-most element (if any).
1262 pub fn top<'l>(&'l self) -> Option<StackElement<'l>> {
1263 return match self.stack.last() {
1265 Some(&InternalIndex(i)) => Some(StackElement::Index(i)),
1266 Some(&InternalKey(start, size)) => {
1267 Some(StackElement::Key(str::from_utf8(
1268 self.str_buffer.index(&((start as uint) .. (start+size) as uint))
1274 // Used by Parser to insert StackElement::Key elements at the top of the stack.
1275 fn push_key(&mut self, key: string::String) {
1276 self.stack.push(InternalKey(self.str_buffer.len() as u16, key.len() as u16));
1277 for c in key.as_bytes().iter() {
1278 self.str_buffer.push(*c);
1282 // Used by Parser to insert StackElement::Index elements at the top of the stack.
1283 fn push_index(&mut self, index: u32) {
1284 self.stack.push(InternalIndex(index));
1287 // Used by Parser to remove the top-most element of the stack.
1289 assert!(!self.is_empty());
1290 match *self.stack.last().unwrap() {
1291 InternalKey(_, sz) => {
1292 let new_size = self.str_buffer.len() - sz as uint;
1293 self.str_buffer.truncate(new_size);
1295 InternalIndex(_) => {}
1300 // Used by Parser to test whether the top-most element is an index.
1301 fn last_is_index(&self) -> bool {
1302 if self.is_empty() { return false; }
1303 return match *self.stack.last().unwrap() {
1304 InternalIndex(_) => true,
1309 // Used by Parser to increment the index of the top-most element.
1310 fn bump_index(&mut self) {
1311 let len = self.stack.len();
1312 let idx = match *self.stack.last().unwrap() {
1313 InternalIndex(i) => { i + 1 }
1316 self.stack[len - 1] = InternalIndex(idx);
1320 /// A streaming JSON parser implemented as an iterator of JsonEvent, consuming
1321 /// an iterator of char.
1322 pub struct Parser<T> {
1327 // We maintain a stack representing where we are in the logical structure
1328 // of the JSON stream.
1330 // A state machine is kept to make it possible to interrupt and resume parsing.
1334 impl<T: Iterator<Item=char>> Iterator for Parser<T> {
1335 type Item = JsonEvent;
1337 fn next(&mut self) -> Option<JsonEvent> {
1338 if self.state == ParseFinished {
1342 if self.state == ParseBeforeFinish {
1343 self.parse_whitespace();
1344 // Make sure there is no trailing characters.
1346 self.state = ParseFinished;
1349 return Some(self.error_event(TrailingCharacters));
1353 return Some(self.parse());
1357 impl<T: Iterator<Item=char>> Parser<T> {
1358 /// Creates the JSON parser.
1359 pub fn new(rdr: T) -> Parser<T> {
1360 let mut p = Parser {
1365 stack: Stack::new(),
1372 /// Provides access to the current position in the logical structure of the
1374 pub fn stack<'l>(&'l self) -> &'l Stack {
1378 fn eof(&self) -> bool { self.ch.is_none() }
1379 fn ch_or_null(&self) -> char { self.ch.unwrap_or('\x00') }
1380 fn bump(&mut self) {
1381 self.ch = self.rdr.next();
1383 if self.ch_is('\n') {
1391 fn next_char(&mut self) -> Option<char> {
1395 fn ch_is(&self, c: char) -> bool {
1399 fn error<T>(&self, reason: ErrorCode) -> Result<T, ParserError> {
1400 Err(SyntaxError(reason, self.line, self.col))
1403 fn parse_whitespace(&mut self) {
1404 while self.ch_is(' ') ||
1407 self.ch_is('\r') { self.bump(); }
1410 fn parse_number(&mut self) -> JsonEvent {
1411 let mut neg = false;
1413 if self.ch_is('-') {
1418 let res = match self.parse_u64() {
1420 Err(e) => { return Error(e); }
1423 if self.ch_is('.') || self.ch_is('e') || self.ch_is('E') {
1424 let mut res = res as f64;
1426 if self.ch_is('.') {
1427 res = match self.parse_decimal(res) {
1429 Err(e) => { return Error(e); }
1433 if self.ch_is('e') || self.ch_is('E') {
1434 res = match self.parse_exponent(res) {
1436 Err(e) => { return Error(e); }
1447 let res = -(res as i64);
1449 // Make sure we didn't underflow.
1451 Error(SyntaxError(InvalidNumber, self.line, self.col))
1461 fn parse_u64(&mut self) -> Result<u64, ParserError> {
1463 let last_accum = 0; // necessary to detect overflow.
1465 match self.ch_or_null() {
1469 // A leading '0' must be the only digit before the decimal point.
1470 match self.ch_or_null() {
1471 '0' ... '9' => return self.error(InvalidNumber),
1477 match self.ch_or_null() {
1478 c @ '0' ... '9' => {
1480 accum += (c as u64) - ('0' as u64);
1482 // Detect overflow by comparing to the last value.
1483 if accum <= last_accum { return self.error(InvalidNumber); }
1491 _ => return self.error(InvalidNumber),
1497 fn parse_decimal(&mut self, mut res: f64) -> Result<f64, ParserError> {
1500 // Make sure a digit follows the decimal place.
1501 match self.ch_or_null() {
1503 _ => return self.error(InvalidNumber)
1508 match self.ch_or_null() {
1509 c @ '0' ... '9' => {
1511 res += (((c as int) - ('0' as int)) as f64) * dec;
1521 fn parse_exponent(&mut self, mut res: f64) -> Result<f64, ParserError> {
1525 let mut neg_exp = false;
1527 if self.ch_is('+') {
1529 } else if self.ch_is('-') {
1534 // Make sure a digit follows the exponent place.
1535 match self.ch_or_null() {
1537 _ => return self.error(InvalidNumber)
1540 match self.ch_or_null() {
1541 c @ '0' ... '9' => {
1543 exp += (c as uint) - ('0' as uint);
1551 let exp = 10_f64.powi(exp as i32);
1561 fn decode_hex_escape(&mut self) -> Result<u16, ParserError> {
1564 while i < 4 && !self.eof() {
1566 n = match self.ch_or_null() {
1567 c @ '0' ... '9' => n * 16 + ((c as u16) - ('0' as u16)),
1568 'a' | 'A' => n * 16 + 10,
1569 'b' | 'B' => n * 16 + 11,
1570 'c' | 'C' => n * 16 + 12,
1571 'd' | 'D' => n * 16 + 13,
1572 'e' | 'E' => n * 16 + 14,
1573 'f' | 'F' => n * 16 + 15,
1574 _ => return self.error(InvalidEscape)
1580 // Error out if we didn't parse 4 digits.
1582 return self.error(InvalidEscape);
1588 fn parse_str(&mut self) -> Result<string::String, ParserError> {
1589 let mut escape = false;
1590 let mut res = string::String::new();
1595 return self.error(EOFWhileParsingString);
1599 match self.ch_or_null() {
1600 '"' => res.push('"'),
1601 '\\' => res.push('\\'),
1602 '/' => res.push('/'),
1603 'b' => res.push('\x08'),
1604 'f' => res.push('\x0c'),
1605 'n' => res.push('\n'),
1606 'r' => res.push('\r'),
1607 't' => res.push('\t'),
1608 'u' => match try!(self.decode_hex_escape()) {
1609 0xDC00 ... 0xDFFF => {
1610 return self.error(LoneLeadingSurrogateInHexEscape)
1613 // Non-BMP characters are encoded as a sequence of
1614 // two hex escapes, representing UTF-16 surrogates.
1615 n1 @ 0xD800 ... 0xDBFF => {
1616 match (self.next_char(), self.next_char()) {
1617 (Some('\\'), Some('u')) => (),
1618 _ => return self.error(UnexpectedEndOfHexEscape),
1621 let buf = [n1, try!(self.decode_hex_escape())];
1622 match unicode_str::utf16_items(&buf).next() {
1623 Some(Utf16Item::ScalarValue(c)) => res.push(c),
1624 _ => return self.error(LoneLeadingSurrogateInHexEscape),
1628 n => match char::from_u32(n as u32) {
1629 Some(c) => res.push(c),
1630 None => return self.error(InvalidUnicodeCodePoint),
1633 _ => return self.error(InvalidEscape),
1636 } else if self.ch_is('\\') {
1644 Some(c) => res.push(c),
1645 None => unreachable!()
1651 // Invoked at each iteration, consumes the stream until it has enough
1652 // information to return a JsonEvent.
1653 // Manages an internal state so that parsing can be interrupted and resumed.
1654 // Also keeps track of the position in the logical structure of the json
1655 // stream int the form of a stack that can be queried by the user using the
1657 fn parse(&mut self) -> JsonEvent {
1659 // The only paths where the loop can spin a new iteration
1660 // are in the cases ParseArrayComma and ParseObjectComma if ','
1661 // is parsed. In these cases the state is set to (respectively)
1662 // ParseArray(false) and ParseObject(false), which always return,
1663 // so there is no risk of getting stuck in an infinite loop.
1664 // All other paths return before the end of the loop's iteration.
1665 self.parse_whitespace();
1669 return self.parse_start();
1671 ParseArray(first) => {
1672 return self.parse_array(first);
1674 ParseArrayComma => {
1675 match self.parse_array_comma_or_end() {
1676 Some(evt) => { return evt; }
1680 ParseObject(first) => {
1681 return self.parse_object(first);
1683 ParseObjectComma => {
1685 if self.ch_is(',') {
1686 self.state = ParseObject(false);
1689 return self.parse_object_end();
1693 return self.error_event(InvalidSyntax);
1699 fn parse_start(&mut self) -> JsonEvent {
1700 let val = self.parse_value();
1701 self.state = match val {
1702 Error(_) => ParseFinished,
1703 ArrayStart => ParseArray(true),
1704 ObjectStart => ParseObject(true),
1705 _ => ParseBeforeFinish,
1710 fn parse_array(&mut self, first: bool) -> JsonEvent {
1711 if self.ch_is(']') {
1713 self.error_event(InvalidSyntax)
1715 self.state = if self.stack.is_empty() {
1717 } else if self.stack.last_is_index() {
1727 self.stack.push_index(0);
1729 let val = self.parse_value();
1730 self.state = match val {
1731 Error(_) => ParseFinished,
1732 ArrayStart => ParseArray(true),
1733 ObjectStart => ParseObject(true),
1734 _ => ParseArrayComma,
1740 fn parse_array_comma_or_end(&mut self) -> Option<JsonEvent> {
1741 if self.ch_is(',') {
1742 self.stack.bump_index();
1743 self.state = ParseArray(false);
1746 } else if self.ch_is(']') {
1748 self.state = if self.stack.is_empty() {
1750 } else if self.stack.last_is_index() {
1757 } else if self.eof() {
1758 Some(self.error_event(EOFWhileParsingArray))
1760 Some(self.error_event(InvalidSyntax))
1764 fn parse_object(&mut self, first: bool) -> JsonEvent {
1765 if self.ch_is('}') {
1767 if self.stack.is_empty() {
1768 return self.error_event(TrailingComma);
1773 self.state = if self.stack.is_empty() {
1775 } else if self.stack.last_is_index() {
1784 return self.error_event(EOFWhileParsingObject);
1786 if !self.ch_is('"') {
1787 return self.error_event(KeyMustBeAString);
1789 let s = match self.parse_str() {
1792 self.state = ParseFinished;
1796 self.parse_whitespace();
1798 return self.error_event(EOFWhileParsingObject);
1799 } else if self.ch_or_null() != ':' {
1800 return self.error_event(ExpectedColon);
1802 self.stack.push_key(s);
1804 self.parse_whitespace();
1806 let val = self.parse_value();
1808 self.state = match val {
1809 Error(_) => ParseFinished,
1810 ArrayStart => ParseArray(true),
1811 ObjectStart => ParseObject(true),
1812 _ => ParseObjectComma,
1817 fn parse_object_end(&mut self) -> JsonEvent {
1818 if self.ch_is('}') {
1819 self.state = if self.stack.is_empty() {
1821 } else if self.stack.last_is_index() {
1828 } else if self.eof() {
1829 self.error_event(EOFWhileParsingObject)
1831 self.error_event(InvalidSyntax)
1835 fn parse_value(&mut self) -> JsonEvent {
1836 if self.eof() { return self.error_event(EOFWhileParsingValue); }
1837 match self.ch_or_null() {
1838 'n' => { self.parse_ident("ull", NullValue) }
1839 't' => { self.parse_ident("rue", BooleanValue(true)) }
1840 'f' => { self.parse_ident("alse", BooleanValue(false)) }
1841 '0' ... '9' | '-' => self.parse_number(),
1842 '"' => match self.parse_str() {
1843 Ok(s) => StringValue(s),
1854 _ => { self.error_event(InvalidSyntax) }
1858 fn parse_ident(&mut self, ident: &str, value: JsonEvent) -> JsonEvent {
1859 if ident.chars().all(|c| Some(c) == self.next_char()) {
1863 Error(SyntaxError(InvalidSyntax, self.line, self.col))
1867 fn error_event(&mut self, reason: ErrorCode) -> JsonEvent {
1868 self.state = ParseFinished;
1869 Error(SyntaxError(reason, self.line, self.col))
1873 /// A Builder consumes a json::Parser to create a generic Json structure.
1874 pub struct Builder<T> {
1876 token: Option<JsonEvent>,
1879 impl<T: Iterator<Item=char>> Builder<T> {
1880 /// Create a JSON Builder.
1881 pub fn new(src: T) -> Builder<T> {
1882 Builder { parser: Parser::new(src), token: None, }
1885 // Decode a Json value from a Parser.
1886 pub fn build(&mut self) -> Result<Json, BuilderError> {
1888 let result = self.build_value();
1892 Some(Error(e)) => { return Err(e); }
1893 ref tok => { panic!("unexpected token {:?}", tok.clone()); }
1898 fn bump(&mut self) {
1899 self.token = self.parser.next();
1902 fn build_value(&mut self) -> Result<Json, BuilderError> {
1903 return match self.token {
1904 Some(NullValue) => Ok(Json::Null),
1905 Some(I64Value(n)) => Ok(Json::I64(n)),
1906 Some(U64Value(n)) => Ok(Json::U64(n)),
1907 Some(F64Value(n)) => Ok(Json::F64(n)),
1908 Some(BooleanValue(b)) => Ok(Json::Boolean(b)),
1909 Some(StringValue(ref mut s)) => {
1910 let mut temp = string::String::new();
1912 Ok(Json::String(temp))
1914 Some(Error(e)) => Err(e),
1915 Some(ArrayStart) => self.build_array(),
1916 Some(ObjectStart) => self.build_object(),
1917 Some(ObjectEnd) => self.parser.error(InvalidSyntax),
1918 Some(ArrayEnd) => self.parser.error(InvalidSyntax),
1919 None => self.parser.error(EOFWhileParsingValue),
1923 fn build_array(&mut self) -> Result<Json, BuilderError> {
1925 let mut values = Vec::new();
1928 if self.token == Some(ArrayEnd) {
1929 return Ok(Json::Array(values.into_iter().collect()));
1931 match self.build_value() {
1932 Ok(v) => values.push(v),
1933 Err(e) => { return Err(e) }
1939 fn build_object(&mut self) -> Result<Json, BuilderError> {
1942 let mut values = BTreeMap::new();
1946 Some(ObjectEnd) => { return Ok(Json::Object(values)); }
1947 Some(Error(e)) => { return Err(e); }
1951 let key = match self.parser.stack().top() {
1952 Some(StackElement::Key(k)) => { k.to_string() }
1953 _ => { panic!("invalid state"); }
1955 match self.build_value() {
1956 Ok(value) => { values.insert(key, value); }
1957 Err(e) => { return Err(e); }
1961 return self.parser.error(EOFWhileParsingObject);
1965 /// Decodes a json value from an `&mut io::Reader`
1966 pub fn from_reader(rdr: &mut io::Reader) -> Result<Json, BuilderError> {
1967 let contents = match rdr.read_to_end() {
1969 Err(e) => return Err(io_error_to_error(e))
1971 let s = match str::from_utf8(contents.as_slice()).ok() {
1973 _ => return Err(SyntaxError(NotUtf8, 0, 0))
1975 let mut builder = Builder::new(s.chars());
1979 /// Decodes a json value from a string
1980 pub fn from_str(s: &str) -> Result<Json, BuilderError> {
1981 let mut builder = Builder::new(s.chars());
1985 /// A structure to decode JSON to values in rust.
1986 pub struct Decoder {
1991 /// Creates a new decoder instance for decoding the specified JSON value.
1992 pub fn new(json: Json) -> Decoder {
1993 Decoder { stack: vec![json] }
1998 fn pop(&mut self) -> Json {
1999 self.stack.pop().unwrap()
2003 macro_rules! expect {
2004 ($e:expr, Null) => ({
2006 Json::Null => Ok(()),
2007 other => Err(ExpectedError("Null".to_string(),
2008 format!("{}", other)))
2011 ($e:expr, $t:ident) => ({
2013 Json::$t(v) => Ok(v),
2015 Err(ExpectedError(stringify!($t).to_string(),
2016 format!("{}", other)))
2022 macro_rules! read_primitive {
2023 ($name:ident, $ty:ty) => {
2024 fn $name(&mut self) -> DecodeResult<$ty> {
2026 Json::I64(f) => match num::cast(f) {
2028 None => Err(ExpectedError("Number".to_string(), format!("{}", f))),
2030 Json::U64(f) => match num::cast(f) {
2032 None => Err(ExpectedError("Number".to_string(), format!("{}", f))),
2034 Json::F64(f) => Err(ExpectedError("Integer".to_string(), format!("{}", f))),
2035 // re: #12967.. a type w/ numeric keys (ie HashMap<uint, V> etc)
2036 // is going to have a string here, as per JSON spec.
2037 Json::String(s) => match s.parse() {
2039 None => Err(ExpectedError("Number".to_string(), s)),
2041 value => Err(ExpectedError("Number".to_string(), format!("{}", value))),
2047 impl ::Decoder for Decoder {
2048 type Error = DecoderError;
2050 fn read_nil(&mut self) -> DecodeResult<()> {
2051 expect!(self.pop(), Null)
2054 read_primitive! { read_uint, uint }
2055 read_primitive! { read_u8, u8 }
2056 read_primitive! { read_u16, u16 }
2057 read_primitive! { read_u32, u32 }
2058 read_primitive! { read_u64, u64 }
2059 read_primitive! { read_int, int }
2060 read_primitive! { read_i8, i8 }
2061 read_primitive! { read_i16, i16 }
2062 read_primitive! { read_i32, i32 }
2063 read_primitive! { read_i64, i64 }
2065 fn read_f32(&mut self) -> DecodeResult<f32> { self.read_f64().map(|x| x as f32) }
2067 fn read_f64(&mut self) -> DecodeResult<f64> {
2069 Json::I64(f) => Ok(f as f64),
2070 Json::U64(f) => Ok(f as f64),
2071 Json::F64(f) => Ok(f),
2072 Json::String(s) => {
2073 // re: #12967.. a type w/ numeric keys (ie HashMap<uint, V> etc)
2074 // is going to have a string here, as per JSON spec.
2077 None => Err(ExpectedError("Number".to_string(), s)),
2080 Json::Null => Ok(f64::NAN),
2081 value => Err(ExpectedError("Number".to_string(), format!("{}", value)))
2085 fn read_bool(&mut self) -> DecodeResult<bool> {
2086 expect!(self.pop(), Boolean)
2089 fn read_char(&mut self) -> DecodeResult<char> {
2090 let s = try!(self.read_str());
2092 let mut it = s.chars();
2093 match (it.next(), it.next()) {
2094 // exactly one character
2095 (Some(c), None) => return Ok(c),
2099 Err(ExpectedError("single character string".to_string(), format!("{}", s)))
2102 fn read_str(&mut self) -> DecodeResult<string::String> {
2103 expect!(self.pop(), String)
2106 fn read_enum<T, F>(&mut self, _name: &str, f: F) -> DecodeResult<T> where
2107 F: FnOnce(&mut Decoder) -> DecodeResult<T>,
2112 fn read_enum_variant<T, F>(&mut self, names: &[&str],
2113 mut f: F) -> DecodeResult<T>
2114 where F: FnMut(&mut Decoder, uint) -> DecodeResult<T>,
2116 let name = match self.pop() {
2117 Json::String(s) => s,
2118 Json::Object(mut o) => {
2119 let n = match o.remove(&"variant".to_string()) {
2120 Some(Json::String(s)) => s,
2122 return Err(ExpectedError("String".to_string(), format!("{}", val)))
2125 return Err(MissingFieldError("variant".to_string()))
2128 match o.remove(&"fields".to_string()) {
2129 Some(Json::Array(l)) => {
2130 for field in l.into_iter().rev() {
2131 self.stack.push(field);
2135 return Err(ExpectedError("Array".to_string(), format!("{}", val)))
2138 return Err(MissingFieldError("fields".to_string()))
2144 return Err(ExpectedError("String or Object".to_string(), format!("{}", json)))
2147 let idx = match names.iter().position(|n| *n == name.index(&FullRange)) {
2149 None => return Err(UnknownVariantError(name))
2154 fn read_enum_variant_arg<T, F>(&mut self, _idx: uint, f: F) -> DecodeResult<T> where
2155 F: FnOnce(&mut Decoder) -> DecodeResult<T>,
2160 fn read_enum_struct_variant<T, F>(&mut self, names: &[&str], f: F) -> DecodeResult<T> where
2161 F: FnMut(&mut Decoder, uint) -> DecodeResult<T>,
2163 self.read_enum_variant(names, f)
2167 fn read_enum_struct_variant_field<T, F>(&mut self,
2171 -> DecodeResult<T> where
2172 F: FnOnce(&mut Decoder) -> DecodeResult<T>,
2174 self.read_enum_variant_arg(idx, f)
2177 fn read_struct<T, F>(&mut self, _name: &str, _len: uint, f: F) -> DecodeResult<T> where
2178 F: FnOnce(&mut Decoder) -> DecodeResult<T>,
2180 let value = try!(f(self));
2185 fn read_struct_field<T, F>(&mut self,
2189 -> DecodeResult<T> where
2190 F: FnOnce(&mut Decoder) -> DecodeResult<T>,
2192 let mut obj = try!(expect!(self.pop(), Object));
2194 let value = match obj.remove(&name.to_string()) {
2196 // Add a Null and try to parse it as an Option<_>
2197 // to get None as a default value.
2198 self.stack.push(Json::Null);
2201 Err(_) => return Err(MissingFieldError(name.to_string())),
2205 self.stack.push(json);
2209 self.stack.push(Json::Object(obj));
2213 fn read_tuple<T, F>(&mut self, tuple_len: uint, f: F) -> DecodeResult<T> where
2214 F: FnOnce(&mut Decoder) -> DecodeResult<T>,
2216 self.read_seq(move |d, len| {
2217 if len == tuple_len {
2220 Err(ExpectedError(format!("Tuple{}", tuple_len), format!("Tuple{}", len)))
2225 fn read_tuple_arg<T, F>(&mut self, idx: uint, f: F) -> DecodeResult<T> where
2226 F: FnOnce(&mut Decoder) -> DecodeResult<T>,
2228 self.read_seq_elt(idx, f)
2231 fn read_tuple_struct<T, F>(&mut self,
2235 -> DecodeResult<T> where
2236 F: FnOnce(&mut Decoder) -> DecodeResult<T>,
2238 self.read_tuple(len, f)
2241 fn read_tuple_struct_arg<T, F>(&mut self,
2244 -> DecodeResult<T> where
2245 F: FnOnce(&mut Decoder) -> DecodeResult<T>,
2247 self.read_tuple_arg(idx, f)
2250 fn read_option<T, F>(&mut self, mut f: F) -> DecodeResult<T> where
2251 F: FnMut(&mut Decoder, bool) -> DecodeResult<T>,
2254 Json::Null => f(self, false),
2255 value => { self.stack.push(value); f(self, true) }
2259 fn read_seq<T, F>(&mut self, f: F) -> DecodeResult<T> where
2260 F: FnOnce(&mut Decoder, uint) -> DecodeResult<T>,
2262 let array = try!(expect!(self.pop(), Array));
2263 let len = array.len();
2264 for v in array.into_iter().rev() {
2270 fn read_seq_elt<T, F>(&mut self, _idx: uint, f: F) -> DecodeResult<T> where
2271 F: FnOnce(&mut Decoder) -> DecodeResult<T>,
2276 fn read_map<T, F>(&mut self, f: F) -> DecodeResult<T> where
2277 F: FnOnce(&mut Decoder, uint) -> DecodeResult<T>,
2279 let obj = try!(expect!(self.pop(), Object));
2280 let len = obj.len();
2281 for (key, value) in obj.into_iter() {
2282 self.stack.push(value);
2283 self.stack.push(Json::String(key));
2288 fn read_map_elt_key<T, F>(&mut self, _idx: uint, f: F) -> DecodeResult<T> where
2289 F: FnOnce(&mut Decoder) -> DecodeResult<T>,
2294 fn read_map_elt_val<T, F>(&mut self, _idx: uint, f: F) -> DecodeResult<T> where
2295 F: FnOnce(&mut Decoder) -> DecodeResult<T>,
2300 fn error(&mut self, err: &str) -> DecoderError {
2301 ApplicationError(err.to_string())
2305 /// A trait for converting values to JSON
2307 /// Converts the value of `self` to an instance of JSON
2308 fn to_json(&self) -> Json;
2311 macro_rules! to_json_impl_i64 {
2313 $(impl ToJson for $t {
2314 fn to_json(&self) -> Json { Json::I64(*self as i64) }
2319 to_json_impl_i64! { int, i8, i16, i32, i64 }
2321 macro_rules! to_json_impl_u64 {
2323 $(impl ToJson for $t {
2324 fn to_json(&self) -> Json { Json::U64(*self as u64) }
2329 to_json_impl_u64! { uint, u8, u16, u32, u64 }
2331 impl ToJson for Json {
2332 fn to_json(&self) -> Json { self.clone() }
2335 impl ToJson for f32 {
2336 fn to_json(&self) -> Json { (*self as f64).to_json() }
2339 impl ToJson for f64 {
2340 fn to_json(&self) -> Json {
2341 match self.classify() {
2342 Fp::Nan | Fp::Infinite => Json::Null,
2343 _ => Json::F64(*self)
2348 impl ToJson for () {
2349 fn to_json(&self) -> Json { Json::Null }
2352 impl ToJson for bool {
2353 fn to_json(&self) -> Json { Json::Boolean(*self) }
2356 impl ToJson for str {
2357 fn to_json(&self) -> Json { Json::String(self.to_string()) }
2360 impl ToJson for string::String {
2361 fn to_json(&self) -> Json { Json::String((*self).clone()) }
2364 macro_rules! tuple_impl {
2365 // use variables to indicate the arity of the tuple
2366 ($($tyvar:ident),* ) => {
2367 // the trailing commas are for the 1 tuple
2369 $( $tyvar : ToJson ),*
2370 > ToJson for ( $( $tyvar ),* , ) {
2373 #[allow(non_snake_case)]
2374 fn to_json(&self) -> Json {
2376 ($(ref $tyvar),*,) => Json::Array(vec![$($tyvar.to_json()),*])
2385 tuple_impl!{A, B, C}
2386 tuple_impl!{A, B, C, D}
2387 tuple_impl!{A, B, C, D, E}
2388 tuple_impl!{A, B, C, D, E, F}
2389 tuple_impl!{A, B, C, D, E, F, G}
2390 tuple_impl!{A, B, C, D, E, F, G, H}
2391 tuple_impl!{A, B, C, D, E, F, G, H, I}
2392 tuple_impl!{A, B, C, D, E, F, G, H, I, J}
2393 tuple_impl!{A, B, C, D, E, F, G, H, I, J, K}
2394 tuple_impl!{A, B, C, D, E, F, G, H, I, J, K, L}
2396 impl<A: ToJson> ToJson for [A] {
2397 fn to_json(&self) -> Json { Json::Array(self.iter().map(|elt| elt.to_json()).collect()) }
2400 impl<A: ToJson> ToJson for Vec<A> {
2401 fn to_json(&self) -> Json { Json::Array(self.iter().map(|elt| elt.to_json()).collect()) }
2404 impl<A: ToJson> ToJson for BTreeMap<string::String, A> {
2405 fn to_json(&self) -> Json {
2406 let mut d = BTreeMap::new();
2407 for (key, value) in self.iter() {
2408 d.insert((*key).clone(), value.to_json());
2414 impl<A: ToJson> ToJson for HashMap<string::String, A> {
2415 fn to_json(&self) -> Json {
2416 let mut d = BTreeMap::new();
2417 for (key, value) in self.iter() {
2418 d.insert((*key).clone(), value.to_json());
2424 impl<A:ToJson> ToJson for Option<A> {
2425 fn to_json(&self) -> Json {
2428 Some(ref value) => value.to_json()
2433 struct FormatShim<'a, 'b: 'a> {
2434 inner: &'a mut fmt::Formatter<'b>,
2437 impl<'a, 'b> fmt::Writer for FormatShim<'a, 'b> {
2438 fn write_str(&mut self, s: &str) -> fmt::Result {
2439 self.inner.write_str(s)
2443 impl fmt::String for Json {
2444 /// Encodes a json value into a string
2445 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2446 let mut shim = FormatShim { inner: f };
2447 let mut encoder = Encoder::new(&mut shim);
2448 self.encode(&mut encoder)
2452 impl<'a> fmt::String for PrettyJson<'a> {
2453 /// Encodes a json value into a string
2454 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2455 let mut shim = FormatShim { inner: f };
2456 let mut encoder = PrettyEncoder::new(&mut shim);
2457 self.inner.encode(&mut encoder)
2462 //NOTE(stage0): remove impl after snapshot
2463 impl<'a, T: Encodable> fmt::Show for AsJson<'a, T> {
2464 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2465 fmt::String::fmt(self, f)
2469 impl<'a, T: Encodable> fmt::String for AsJson<'a, T> {
2470 /// Encodes a json value into a string
2471 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2472 let mut shim = FormatShim { inner: f };
2473 let mut encoder = Encoder::new(&mut shim);
2474 self.inner.encode(&mut encoder)
2478 impl<'a, T> AsPrettyJson<'a, T> {
2479 /// Set the indentation level for the emitted JSON
2480 pub fn indent(mut self, indent: uint) -> AsPrettyJson<'a, T> {
2481 self.indent = Some(indent);
2486 impl<'a, T: Encodable> fmt::String for AsPrettyJson<'a, T> {
2487 /// Encodes a json value into a string
2488 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2489 let mut shim = FormatShim { inner: f };
2490 let mut encoder = PrettyEncoder::new(&mut shim);
2492 Some(n) => encoder.set_indent(n),
2495 self.inner.encode(&mut encoder)
2499 impl FromStr for Json {
2500 fn from_str(s: &str) -> Option<Json> {
2508 use self::Animal::*;
2509 use self::DecodeEnum::*;
2510 use self::test::Bencher;
2511 use {Encodable, Decodable};
2513 use super::ErrorCode::*;
2514 use super::ParserError::*;
2515 use super::DecoderError::*;
2516 use super::JsonEvent::*;
2517 use super::{Json, from_str, DecodeResult, DecoderError, JsonEvent, Parser,
2518 StackElement, Stack, Decoder};
2519 use std::{i64, u64, f32, f64, io};
2520 use std::collections::BTreeMap;
2521 use std::num::Float;
2522 use std::ops::Index;
2525 #[derive(RustcDecodable, Eq, PartialEq, Show)]
2531 fn test_decode_option_none() {
2533 let obj: OptionData = super::decode(s).unwrap();
2534 assert_eq!(obj, OptionData { opt: None });
2538 fn test_decode_option_some() {
2539 let s = "{ \"opt\": 10 }";
2540 let obj: OptionData = super::decode(s).unwrap();
2541 assert_eq!(obj, OptionData { opt: Some(10u) });
2545 fn test_decode_option_malformed() {
2546 check_err::<OptionData>("{ \"opt\": [] }",
2547 ExpectedError("Number".to_string(), "[]".to_string()));
2548 check_err::<OptionData>("{ \"opt\": false }",
2549 ExpectedError("Number".to_string(), "false".to_string()));
2552 #[derive(PartialEq, RustcEncodable, RustcDecodable, Show)]
2555 Frog(string::String, int)
2558 #[derive(PartialEq, RustcEncodable, RustcDecodable, Show)]
2562 c: Vec<string::String>,
2565 #[derive(PartialEq, RustcEncodable, RustcDecodable, Show)]
2570 fn mk_object(items: &[(string::String, Json)]) -> Json {
2571 let mut d = BTreeMap::new();
2573 for item in items.iter() {
2575 (ref key, ref value) => { d.insert((*key).clone(), (*value).clone()); },
2583 fn test_from_str_trait() {
2585 assert!(s.parse::<Json>().unwrap() == s.parse().unwrap());
2589 fn test_write_null() {
2590 assert_eq!(Null.to_string(), "null");
2591 assert_eq!(Null.pretty().to_string(), "null");
2595 fn test_write_i64() {
2596 assert_eq!(U64(0).to_string(), "0");
2597 assert_eq!(U64(0).pretty().to_string(), "0");
2599 assert_eq!(U64(1234).to_string(), "1234");
2600 assert_eq!(U64(1234).pretty().to_string(), "1234");
2602 assert_eq!(I64(-5678).to_string(), "-5678");
2603 assert_eq!(I64(-5678).pretty().to_string(), "-5678");
2605 assert_eq!(U64(7650007200025252000).to_string(), "7650007200025252000");
2606 assert_eq!(U64(7650007200025252000).pretty().to_string(), "7650007200025252000");
2610 fn test_write_f64() {
2611 assert_eq!(F64(3.0).to_string(), "3.0");
2612 assert_eq!(F64(3.0).pretty().to_string(), "3.0");
2614 assert_eq!(F64(3.1).to_string(), "3.1");
2615 assert_eq!(F64(3.1).pretty().to_string(), "3.1");
2617 assert_eq!(F64(-1.5).to_string(), "-1.5");
2618 assert_eq!(F64(-1.5).pretty().to_string(), "-1.5");
2620 assert_eq!(F64(0.5).to_string(), "0.5");
2621 assert_eq!(F64(0.5).pretty().to_string(), "0.5");
2623 assert_eq!(F64(f64::NAN).to_string(), "null");
2624 assert_eq!(F64(f64::NAN).pretty().to_string(), "null");
2626 assert_eq!(F64(f64::INFINITY).to_string(), "null");
2627 assert_eq!(F64(f64::INFINITY).pretty().to_string(), "null");
2629 assert_eq!(F64(f64::NEG_INFINITY).to_string(), "null");
2630 assert_eq!(F64(f64::NEG_INFINITY).pretty().to_string(), "null");
2634 fn test_write_str() {
2635 assert_eq!(String("".to_string()).to_string(), "\"\"");
2636 assert_eq!(String("".to_string()).pretty().to_string(), "\"\"");
2638 assert_eq!(String("homura".to_string()).to_string(), "\"homura\"");
2639 assert_eq!(String("madoka".to_string()).pretty().to_string(), "\"madoka\"");
2643 fn test_write_bool() {
2644 assert_eq!(Boolean(true).to_string(), "true");
2645 assert_eq!(Boolean(true).pretty().to_string(), "true");
2647 assert_eq!(Boolean(false).to_string(), "false");
2648 assert_eq!(Boolean(false).pretty().to_string(), "false");
2652 fn test_write_array() {
2653 assert_eq!(Array(vec![]).to_string(), "[]");
2654 assert_eq!(Array(vec![]).pretty().to_string(), "[]");
2656 assert_eq!(Array(vec![Boolean(true)]).to_string(), "[true]");
2658 Array(vec![Boolean(true)]).pretty().to_string(),
2665 let long_test_array = Array(vec![
2668 Array(vec![String("foo\nbar".to_string()), F64(3.5)])]);
2670 assert_eq!(long_test_array.to_string(),
2671 "[false,null,[\"foo\\nbar\",3.5]]");
2673 long_test_array.pretty().to_string(),
2687 fn test_write_object() {
2688 assert_eq!(mk_object(&[]).to_string(), "{}");
2689 assert_eq!(mk_object(&[]).pretty().to_string(), "{}");
2693 ("a".to_string(), Boolean(true))
2698 mk_object(&[("a".to_string(), Boolean(true))]).pretty().to_string(),
2705 let complex_obj = mk_object(&[
2706 ("b".to_string(), Array(vec![
2707 mk_object(&[("c".to_string(), String("\x0c\r".to_string()))]),
2708 mk_object(&[("d".to_string(), String("".to_string()))])
2713 complex_obj.to_string(),
2716 {\"c\":\"\\f\\r\"},\
2722 complex_obj.pretty().to_string(),
2727 \"c\": \"\\f\\r\"\n \
2736 let a = mk_object(&[
2737 ("a".to_string(), Boolean(true)),
2738 ("b".to_string(), Array(vec![
2739 mk_object(&[("c".to_string(), String("\x0c\r".to_string()))]),
2740 mk_object(&[("d".to_string(), String("".to_string()))])
2744 // We can't compare the strings directly because the object fields be
2745 // printed in a different order.
2746 assert_eq!(a.clone(), a.to_string().parse().unwrap());
2747 assert_eq!(a.clone(), a.pretty().to_string().parse().unwrap());
2751 fn test_write_enum() {
2754 format!("{}", super::as_json(&animal)),
2758 format!("{}", super::as_pretty_json(&animal)),
2762 let animal = Frog("Henry".to_string(), 349);
2764 format!("{}", super::as_json(&animal)),
2765 "{\"variant\":\"Frog\",\"fields\":[\"Henry\",349]}"
2768 format!("{}", super::as_pretty_json(&animal)),
2770 \"variant\": \"Frog\",\n \
2779 macro_rules! check_encoder_for_simple {
2780 ($value:expr, $expected:expr) => ({
2781 let s = format!("{}", super::as_json(&$value));
2782 assert_eq!(s, $expected);
2784 let s = format!("{}", super::as_pretty_json(&$value));
2785 assert_eq!(s, $expected);
2790 fn test_write_some() {
2791 check_encoder_for_simple!(Some("jodhpurs".to_string()), "\"jodhpurs\"");
2795 fn test_write_none() {
2796 check_encoder_for_simple!(None::<string::String>, "null");
2800 fn test_write_char() {
2801 check_encoder_for_simple!('a', "\"a\"");
2802 check_encoder_for_simple!('\t', "\"\\t\"");
2803 check_encoder_for_simple!('\u{0000}', "\"\\u0000\"");
2804 check_encoder_for_simple!('\u{001b}', "\"\\u001b\"");
2805 check_encoder_for_simple!('\u{007f}', "\"\\u007f\"");
2806 check_encoder_for_simple!('\u{00a0}', "\"\u{00a0}\"");
2807 check_encoder_for_simple!('\u{abcd}', "\"\u{abcd}\"");
2808 check_encoder_for_simple!('\u{10ffff}', "\"\u{10ffff}\"");
2812 fn test_trailing_characters() {
2813 assert_eq!(from_str("nulla"), Err(SyntaxError(TrailingCharacters, 1, 5)));
2814 assert_eq!(from_str("truea"), Err(SyntaxError(TrailingCharacters, 1, 5)));
2815 assert_eq!(from_str("falsea"), Err(SyntaxError(TrailingCharacters, 1, 6)));
2816 assert_eq!(from_str("1a"), Err(SyntaxError(TrailingCharacters, 1, 2)));
2817 assert_eq!(from_str("[]a"), Err(SyntaxError(TrailingCharacters, 1, 3)));
2818 assert_eq!(from_str("{}a"), Err(SyntaxError(TrailingCharacters, 1, 3)));
2822 fn test_read_identifiers() {
2823 assert_eq!(from_str("n"), Err(SyntaxError(InvalidSyntax, 1, 2)));
2824 assert_eq!(from_str("nul"), Err(SyntaxError(InvalidSyntax, 1, 4)));
2825 assert_eq!(from_str("t"), Err(SyntaxError(InvalidSyntax, 1, 2)));
2826 assert_eq!(from_str("truz"), Err(SyntaxError(InvalidSyntax, 1, 4)));
2827 assert_eq!(from_str("f"), Err(SyntaxError(InvalidSyntax, 1, 2)));
2828 assert_eq!(from_str("faz"), Err(SyntaxError(InvalidSyntax, 1, 3)));
2830 assert_eq!(from_str("null"), Ok(Null));
2831 assert_eq!(from_str("true"), Ok(Boolean(true)));
2832 assert_eq!(from_str("false"), Ok(Boolean(false)));
2833 assert_eq!(from_str(" null "), Ok(Null));
2834 assert_eq!(from_str(" true "), Ok(Boolean(true)));
2835 assert_eq!(from_str(" false "), Ok(Boolean(false)));
2839 fn test_decode_identifiers() {
2840 let v: () = super::decode("null").unwrap();
2843 let v: bool = super::decode("true").unwrap();
2844 assert_eq!(v, true);
2846 let v: bool = super::decode("false").unwrap();
2847 assert_eq!(v, false);
2851 fn test_read_number() {
2852 assert_eq!(from_str("+"), Err(SyntaxError(InvalidSyntax, 1, 1)));
2853 assert_eq!(from_str("."), Err(SyntaxError(InvalidSyntax, 1, 1)));
2854 assert_eq!(from_str("NaN"), Err(SyntaxError(InvalidSyntax, 1, 1)));
2855 assert_eq!(from_str("-"), Err(SyntaxError(InvalidNumber, 1, 2)));
2856 assert_eq!(from_str("00"), Err(SyntaxError(InvalidNumber, 1, 2)));
2857 assert_eq!(from_str("1."), Err(SyntaxError(InvalidNumber, 1, 3)));
2858 assert_eq!(from_str("1e"), Err(SyntaxError(InvalidNumber, 1, 3)));
2859 assert_eq!(from_str("1e+"), Err(SyntaxError(InvalidNumber, 1, 4)));
2861 assert_eq!(from_str("18446744073709551616"), Err(SyntaxError(InvalidNumber, 1, 20)));
2862 assert_eq!(from_str("-9223372036854775809"), Err(SyntaxError(InvalidNumber, 1, 21)));
2864 assert_eq!(from_str("3"), Ok(U64(3)));
2865 assert_eq!(from_str("3.1"), Ok(F64(3.1)));
2866 assert_eq!(from_str("-1.2"), Ok(F64(-1.2)));
2867 assert_eq!(from_str("0.4"), Ok(F64(0.4)));
2868 assert_eq!(from_str("0.4e5"), Ok(F64(0.4e5)));
2869 assert_eq!(from_str("0.4e+15"), Ok(F64(0.4e15)));
2870 assert_eq!(from_str("0.4e-01"), Ok(F64(0.4e-01)));
2871 assert_eq!(from_str(" 3 "), Ok(U64(3)));
2873 assert_eq!(from_str("-9223372036854775808"), Ok(I64(i64::MIN)));
2874 assert_eq!(from_str("9223372036854775807"), Ok(U64(i64::MAX as u64)));
2875 assert_eq!(from_str("18446744073709551615"), Ok(U64(u64::MAX)));
2879 fn test_decode_numbers() {
2880 let v: f64 = super::decode("3").unwrap();
2883 let v: f64 = super::decode("3.1").unwrap();
2886 let v: f64 = super::decode("-1.2").unwrap();
2887 assert_eq!(v, -1.2);
2889 let v: f64 = super::decode("0.4").unwrap();
2892 let v: f64 = super::decode("0.4e5").unwrap();
2893 assert_eq!(v, 0.4e5);
2895 let v: f64 = super::decode("0.4e15").unwrap();
2896 assert_eq!(v, 0.4e15);
2898 let v: f64 = super::decode("0.4e-01").unwrap();
2899 assert_eq!(v, 0.4e-01);
2901 let v: u64 = super::decode("0").unwrap();
2904 let v: u64 = super::decode("18446744073709551615").unwrap();
2905 assert_eq!(v, u64::MAX);
2907 let v: i64 = super::decode("-9223372036854775808").unwrap();
2908 assert_eq!(v, i64::MIN);
2910 let v: i64 = super::decode("9223372036854775807").unwrap();
2911 assert_eq!(v, i64::MAX);
2913 let res: DecodeResult<i64> = super::decode("765.25252");
2914 assert_eq!(res, Err(ExpectedError("Integer".to_string(),
2915 "765.25252".to_string())));
2919 fn test_read_str() {
2920 assert_eq!(from_str("\""), Err(SyntaxError(EOFWhileParsingString, 1, 2)));
2921 assert_eq!(from_str("\"lol"), Err(SyntaxError(EOFWhileParsingString, 1, 5)));
2923 assert_eq!(from_str("\"\""), Ok(String("".to_string())));
2924 assert_eq!(from_str("\"foo\""), Ok(String("foo".to_string())));
2925 assert_eq!(from_str("\"\\\"\""), Ok(String("\"".to_string())));
2926 assert_eq!(from_str("\"\\b\""), Ok(String("\x08".to_string())));
2927 assert_eq!(from_str("\"\\n\""), Ok(String("\n".to_string())));
2928 assert_eq!(from_str("\"\\r\""), Ok(String("\r".to_string())));
2929 assert_eq!(from_str("\"\\t\""), Ok(String("\t".to_string())));
2930 assert_eq!(from_str(" \"foo\" "), Ok(String("foo".to_string())));
2931 assert_eq!(from_str("\"\\u12ab\""), Ok(String("\u{12ab}".to_string())));
2932 assert_eq!(from_str("\"\\uAB12\""), Ok(String("\u{AB12}".to_string())));
2936 fn test_decode_str() {
2937 let s = [("\"\"", ""),
2940 ("\"\\b\"", "\x08"),
2944 ("\"\\u12ab\"", "\u{12ab}"),
2945 ("\"\\uAB12\"", "\u{AB12}")];
2947 for &(i, o) in s.iter() {
2948 let v: string::String = super::decode(i).unwrap();
2954 fn test_read_array() {
2955 assert_eq!(from_str("["), Err(SyntaxError(EOFWhileParsingValue, 1, 2)));
2956 assert_eq!(from_str("[1"), Err(SyntaxError(EOFWhileParsingArray, 1, 3)));
2957 assert_eq!(from_str("[1,"), Err(SyntaxError(EOFWhileParsingValue, 1, 4)));
2958 assert_eq!(from_str("[1,]"), Err(SyntaxError(InvalidSyntax, 1, 4)));
2959 assert_eq!(from_str("[6 7]"), Err(SyntaxError(InvalidSyntax, 1, 4)));
2961 assert_eq!(from_str("[]"), Ok(Array(vec![])));
2962 assert_eq!(from_str("[ ]"), Ok(Array(vec![])));
2963 assert_eq!(from_str("[true]"), Ok(Array(vec![Boolean(true)])));
2964 assert_eq!(from_str("[ false ]"), Ok(Array(vec![Boolean(false)])));
2965 assert_eq!(from_str("[null]"), Ok(Array(vec![Null])));
2966 assert_eq!(from_str("[3, 1]"),
2967 Ok(Array(vec![U64(3), U64(1)])));
2968 assert_eq!(from_str("\n[3, 2]\n"),
2969 Ok(Array(vec![U64(3), U64(2)])));
2970 assert_eq!(from_str("[2, [4, 1]]"),
2971 Ok(Array(vec![U64(2), Array(vec![U64(4), U64(1)])])));
2975 fn test_decode_array() {
2976 let v: Vec<()> = super::decode("[]").unwrap();
2977 assert_eq!(v, vec![]);
2979 let v: Vec<()> = super::decode("[null]").unwrap();
2980 assert_eq!(v, vec![()]);
2982 let v: Vec<bool> = super::decode("[true]").unwrap();
2983 assert_eq!(v, vec![true]);
2985 let v: Vec<int> = super::decode("[3, 1]").unwrap();
2986 assert_eq!(v, vec![3, 1]);
2988 let v: Vec<Vec<uint>> = super::decode("[[3], [1, 2]]").unwrap();
2989 assert_eq!(v, vec![vec![3], vec![1, 2]]);
2993 fn test_decode_tuple() {
2994 let t: (uint, uint, uint) = super::decode("[1, 2, 3]").unwrap();
2995 assert_eq!(t, (1u, 2, 3));
2997 let t: (uint, string::String) = super::decode("[1, \"two\"]").unwrap();
2998 assert_eq!(t, (1u, "two".to_string()));
3002 fn test_decode_tuple_malformed_types() {
3003 assert!(super::decode::<(uint, string::String)>("[1, 2]").is_err());
3007 fn test_decode_tuple_malformed_length() {
3008 assert!(super::decode::<(uint, uint)>("[1, 2, 3]").is_err());
3012 fn test_read_object() {
3013 assert_eq!(from_str("{"), Err(SyntaxError(EOFWhileParsingObject, 1, 2)));
3014 assert_eq!(from_str("{ "), Err(SyntaxError(EOFWhileParsingObject, 1, 3)));
3015 assert_eq!(from_str("{1"), Err(SyntaxError(KeyMustBeAString, 1, 2)));
3016 assert_eq!(from_str("{ \"a\""), Err(SyntaxError(EOFWhileParsingObject, 1, 6)));
3017 assert_eq!(from_str("{\"a\""), Err(SyntaxError(EOFWhileParsingObject, 1, 5)));
3018 assert_eq!(from_str("{\"a\" "), Err(SyntaxError(EOFWhileParsingObject, 1, 6)));
3020 assert_eq!(from_str("{\"a\" 1"), Err(SyntaxError(ExpectedColon, 1, 6)));
3021 assert_eq!(from_str("{\"a\":"), Err(SyntaxError(EOFWhileParsingValue, 1, 6)));
3022 assert_eq!(from_str("{\"a\":1"), Err(SyntaxError(EOFWhileParsingObject, 1, 7)));
3023 assert_eq!(from_str("{\"a\":1 1"), Err(SyntaxError(InvalidSyntax, 1, 8)));
3024 assert_eq!(from_str("{\"a\":1,"), Err(SyntaxError(EOFWhileParsingObject, 1, 8)));
3026 assert_eq!(from_str("{}").unwrap(), mk_object(&[]));
3027 assert_eq!(from_str("{\"a\": 3}").unwrap(),
3028 mk_object(&[("a".to_string(), U64(3))]));
3030 assert_eq!(from_str(
3031 "{ \"a\": null, \"b\" : true }").unwrap(),
3033 ("a".to_string(), Null),
3034 ("b".to_string(), Boolean(true))]));
3035 assert_eq!(from_str("\n{ \"a\": null, \"b\" : true }\n").unwrap(),
3037 ("a".to_string(), Null),
3038 ("b".to_string(), Boolean(true))]));
3039 assert_eq!(from_str(
3040 "{\"a\" : 1.0 ,\"b\": [ true ]}").unwrap(),
3042 ("a".to_string(), F64(1.0)),
3043 ("b".to_string(), Array(vec![Boolean(true)]))
3045 assert_eq!(from_str(
3051 { \"c\": {\"d\": null} } \
3055 ("a".to_string(), F64(1.0)),
3056 ("b".to_string(), Array(vec![
3058 String("foo\nbar".to_string()),
3060 ("c".to_string(), mk_object(&[("d".to_string(), Null)]))
3067 fn test_decode_struct() {
3070 { \"a\": null, \"b\": 2, \"c\": [\"abc\", \"xyz\"] }
3074 let v: Outer = super::decode(s).unwrap();
3079 Inner { a: (), b: 2, c: vec!["abc".to_string(), "xyz".to_string()] }
3085 #[derive(RustcDecodable)]
3086 struct FloatStruct {
3091 fn test_decode_struct_with_nan() {
3092 let s = "{\"f\":null,\"a\":[null,123]}";
3093 let obj: FloatStruct = super::decode(s).unwrap();
3094 assert!(obj.f.is_nan());
3095 assert!(obj.a[0].is_nan());
3096 assert_eq!(obj.a[1], 123f64);
3100 fn test_decode_option() {
3101 let value: Option<string::String> = super::decode("null").unwrap();
3102 assert_eq!(value, None);
3104 let value: Option<string::String> = super::decode("\"jodhpurs\"").unwrap();
3105 assert_eq!(value, Some("jodhpurs".to_string()));
3109 fn test_decode_enum() {
3110 let value: Animal = super::decode("\"Dog\"").unwrap();
3111 assert_eq!(value, Dog);
3113 let s = "{\"variant\":\"Frog\",\"fields\":[\"Henry\",349]}";
3114 let value: Animal = super::decode(s).unwrap();
3115 assert_eq!(value, Frog("Henry".to_string(), 349));
3119 fn test_decode_map() {
3120 let s = "{\"a\": \"Dog\", \"b\": {\"variant\":\"Frog\",\
3121 \"fields\":[\"Henry\", 349]}}";
3122 let mut map: BTreeMap<string::String, Animal> = super::decode(s).unwrap();
3124 assert_eq!(map.remove(&"a".to_string()), Some(Dog));
3125 assert_eq!(map.remove(&"b".to_string()), Some(Frog("Henry".to_string(), 349)));
3129 fn test_multiline_errors() {
3130 assert_eq!(from_str("{\n \"foo\":\n \"bar\""),
3131 Err(SyntaxError(EOFWhileParsingObject, 3u, 8u)));
3134 #[derive(RustcDecodable)]
3136 struct DecodeStruct {
3140 w: Vec<DecodeStruct>
3142 #[derive(RustcDecodable)]
3147 fn check_err<T: Decodable>(to_parse: &'static str, expected: DecoderError) {
3148 let res: DecodeResult<T> = match from_str(to_parse) {
3149 Err(e) => Err(ParseError(e)),
3150 Ok(json) => Decodable::decode(&mut Decoder::new(json))
3153 Ok(_) => panic!("`{:?}` parsed & decoded ok, expecting error `{:?}`",
3154 to_parse, expected),
3155 Err(ParseError(e)) => panic!("`{:?}` is not valid json: {:?}",
3158 assert_eq!(e, expected);
3163 fn test_decode_errors_struct() {
3164 check_err::<DecodeStruct>("[]", ExpectedError("Object".to_string(), "[]".to_string()));
3165 check_err::<DecodeStruct>("{\"x\": true, \"y\": true, \"z\": \"\", \"w\": []}",
3166 ExpectedError("Number".to_string(), "true".to_string()));
3167 check_err::<DecodeStruct>("{\"x\": 1, \"y\": [], \"z\": \"\", \"w\": []}",
3168 ExpectedError("Boolean".to_string(), "[]".to_string()));
3169 check_err::<DecodeStruct>("{\"x\": 1, \"y\": true, \"z\": {}, \"w\": []}",
3170 ExpectedError("String".to_string(), "{}".to_string()));
3171 check_err::<DecodeStruct>("{\"x\": 1, \"y\": true, \"z\": \"\", \"w\": null}",
3172 ExpectedError("Array".to_string(), "null".to_string()));
3173 check_err::<DecodeStruct>("{\"x\": 1, \"y\": true, \"z\": \"\"}",
3174 MissingFieldError("w".to_string()));
3177 fn test_decode_errors_enum() {
3178 check_err::<DecodeEnum>("{}",
3179 MissingFieldError("variant".to_string()));
3180 check_err::<DecodeEnum>("{\"variant\": 1}",
3181 ExpectedError("String".to_string(), "1".to_string()));
3182 check_err::<DecodeEnum>("{\"variant\": \"A\"}",
3183 MissingFieldError("fields".to_string()));
3184 check_err::<DecodeEnum>("{\"variant\": \"A\", \"fields\": null}",
3185 ExpectedError("Array".to_string(), "null".to_string()));
3186 check_err::<DecodeEnum>("{\"variant\": \"C\", \"fields\": []}",
3187 UnknownVariantError("C".to_string()));
3192 let json_value = from_str("{\"dog\" : \"cat\"}").unwrap();
3193 let found_str = json_value.find("dog");
3194 assert!(found_str.unwrap().as_string().unwrap() == "cat");
3198 fn test_find_path(){
3199 let json_value = from_str("{\"dog\":{\"cat\": {\"mouse\" : \"cheese\"}}}").unwrap();
3200 let found_str = json_value.find_path(&["dog", "cat", "mouse"]);
3201 assert!(found_str.unwrap().as_string().unwrap() == "cheese");
3206 let json_value = from_str("{\"dog\":{\"cat\": {\"mouse\" : \"cheese\"}}}").unwrap();
3207 let found_str = json_value.search("mouse").and_then(|j| j.as_string());
3208 assert!(found_str.unwrap() == "cheese");
3213 let json_value = from_str("{\"animals\":[\"dog\",\"cat\",\"mouse\"]}").unwrap();
3214 let ref array = json_value["animals"];
3215 assert_eq!(array[0].as_string().unwrap(), "dog");
3216 assert_eq!(array[1].as_string().unwrap(), "cat");
3217 assert_eq!(array[2].as_string().unwrap(), "mouse");
3221 fn test_is_object(){
3222 let json_value = from_str("{}").unwrap();
3223 assert!(json_value.is_object());
3227 fn test_as_object(){
3228 let json_value = from_str("{}").unwrap();
3229 let json_object = json_value.as_object();
3230 assert!(json_object.is_some());
3235 let json_value = from_str("[1, 2, 3]").unwrap();
3236 assert!(json_value.is_array());
3241 let json_value = from_str("[1, 2, 3]").unwrap();
3242 let json_array = json_value.as_array();
3243 let expected_length = 3;
3244 assert!(json_array.is_some() && json_array.unwrap().len() == expected_length);
3248 fn test_is_string(){
3249 let json_value = from_str("\"dog\"").unwrap();
3250 assert!(json_value.is_string());
3254 fn test_as_string(){
3255 let json_value = from_str("\"dog\"").unwrap();
3256 let json_str = json_value.as_string();
3257 let expected_str = "dog";
3258 assert_eq!(json_str, Some(expected_str));
3262 fn test_is_number(){
3263 let json_value = from_str("12").unwrap();
3264 assert!(json_value.is_number());
3269 let json_value = from_str("-12").unwrap();
3270 assert!(json_value.is_i64());
3272 let json_value = from_str("12").unwrap();
3273 assert!(!json_value.is_i64());
3275 let json_value = from_str("12.0").unwrap();
3276 assert!(!json_value.is_i64());
3281 let json_value = from_str("12").unwrap();
3282 assert!(json_value.is_u64());
3284 let json_value = from_str("-12").unwrap();
3285 assert!(!json_value.is_u64());
3287 let json_value = from_str("12.0").unwrap();
3288 assert!(!json_value.is_u64());
3293 let json_value = from_str("12").unwrap();
3294 assert!(!json_value.is_f64());
3296 let json_value = from_str("-12").unwrap();
3297 assert!(!json_value.is_f64());
3299 let json_value = from_str("12.0").unwrap();
3300 assert!(json_value.is_f64());
3302 let json_value = from_str("-12.0").unwrap();
3303 assert!(json_value.is_f64());
3308 let json_value = from_str("-12").unwrap();
3309 let json_num = json_value.as_i64();
3310 assert_eq!(json_num, Some(-12));
3315 let json_value = from_str("12").unwrap();
3316 let json_num = json_value.as_u64();
3317 assert_eq!(json_num, Some(12));
3322 let json_value = from_str("12.0").unwrap();
3323 let json_num = json_value.as_f64();
3324 assert_eq!(json_num, Some(12f64));
3328 fn test_is_boolean(){
3329 let json_value = from_str("false").unwrap();
3330 assert!(json_value.is_boolean());
3334 fn test_as_boolean(){
3335 let json_value = from_str("false").unwrap();
3336 let json_bool = json_value.as_boolean();
3337 let expected_bool = false;
3338 assert!(json_bool.is_some() && json_bool.unwrap() == expected_bool);
3343 let json_value = from_str("null").unwrap();
3344 assert!(json_value.is_null());
3349 let json_value = from_str("null").unwrap();
3350 let json_null = json_value.as_null();
3351 let expected_null = ();
3352 assert!(json_null.is_some() && json_null.unwrap() == expected_null);
3356 fn test_encode_hashmap_with_numeric_key() {
3357 use std::str::from_utf8;
3358 use std::io::Writer;
3359 use std::collections::HashMap;
3360 let mut hm: HashMap<uint, bool> = HashMap::new();
3362 let mut mem_buf = Vec::new();
3363 write!(&mut mem_buf, "{}", super::as_pretty_json(&hm)).unwrap();
3364 let json_str = from_utf8(mem_buf.index(&FullRange)).unwrap();
3365 match from_str(json_str) {
3366 Err(_) => panic!("Unable to parse json_str: {:?}", json_str),
3367 _ => {} // it parsed and we are good to go
3372 fn test_prettyencode_hashmap_with_numeric_key() {
3373 use std::str::from_utf8;
3374 use std::io::Writer;
3375 use std::collections::HashMap;
3376 let mut hm: HashMap<uint, bool> = HashMap::new();
3378 let mut mem_buf = Vec::new();
3379 write!(&mut mem_buf, "{}", super::as_pretty_json(&hm)).unwrap();
3380 let json_str = from_utf8(mem_buf.index(&FullRange)).unwrap();
3381 match from_str(json_str) {
3382 Err(_) => panic!("Unable to parse json_str: {:?}", json_str),
3383 _ => {} // it parsed and we are good to go
3388 fn test_prettyencoder_indent_level_param() {
3389 use std::str::from_utf8;
3390 use std::collections::BTreeMap;
3392 let mut tree = BTreeMap::new();
3394 tree.insert("hello".to_string(), String("guten tag".to_string()));
3395 tree.insert("goodbye".to_string(), String("sayonara".to_string()));
3398 // The following layout below should look a lot like
3399 // the pretty-printed JSON (indent * x)
3402 String("greetings".to_string()), // 1x
3403 Object(tree), // 1x + 2x + 2x + 1x
3405 // End JSON array (7 lines)
3408 // Helper function for counting indents
3409 fn indents(source: &str) -> uint {
3410 let trimmed = source.trim_left_matches(' ');
3411 source.len() - trimmed.len()
3414 // Test up to 4 spaces of indents (more?)
3415 for i in range(0, 4u) {
3416 let mut writer = Vec::new();
3417 write!(&mut writer, "{}",
3418 super::as_pretty_json(&json).indent(i)).unwrap();
3420 let printed = from_utf8(writer.index(&FullRange)).unwrap();
3422 // Check for indents at each line
3423 let lines: Vec<&str> = printed.lines().collect();
3424 assert_eq!(lines.len(), 7); // JSON should be 7 lines
3426 assert_eq!(indents(lines[0]), 0 * i); // [
3427 assert_eq!(indents(lines[1]), 1 * i); // "greetings",
3428 assert_eq!(indents(lines[2]), 1 * i); // {
3429 assert_eq!(indents(lines[3]), 2 * i); // "hello": "guten tag",
3430 assert_eq!(indents(lines[4]), 2 * i); // "goodbye": "sayonara"
3431 assert_eq!(indents(lines[5]), 1 * i); // },
3432 assert_eq!(indents(lines[6]), 0 * i); // ]
3434 // Finally, test that the pretty-printed JSON is valid
3435 from_str(printed).ok().expect("Pretty-printed JSON is invalid!");
3440 fn test_hashmap_with_numeric_key_can_handle_double_quote_delimited_key() {
3441 use std::collections::HashMap;
3443 let json_str = "{\"1\":true}";
3444 let json_obj = match from_str(json_str) {
3445 Err(_) => panic!("Unable to parse json_str: {:?}", json_str),
3448 let mut decoder = Decoder::new(json_obj);
3449 let _hm: HashMap<uint, bool> = Decodable::decode(&mut decoder).unwrap();
3453 fn test_hashmap_with_numeric_key_will_error_with_string_keys() {
3454 use std::collections::HashMap;
3456 let json_str = "{\"a\":true}";
3457 let json_obj = match from_str(json_str) {
3458 Err(_) => panic!("Unable to parse json_str: {:?}", json_str),
3461 let mut decoder = Decoder::new(json_obj);
3462 let result: Result<HashMap<uint, bool>, DecoderError> = Decodable::decode(&mut decoder);
3463 assert_eq!(result, Err(ExpectedError("Number".to_string(), "a".to_string())));
3466 fn assert_stream_equal(src: &str,
3467 expected: Vec<(JsonEvent, Vec<StackElement>)>) {
3468 let mut parser = Parser::new(src.chars());
3471 let evt = match parser.next() {
3475 let (ref expected_evt, ref expected_stack) = expected[i];
3476 if !parser.stack().is_equal_to(expected_stack.as_slice()) {
3477 panic!("Parser stack is not equal to {:?}", expected_stack);
3479 assert_eq!(&evt, expected_evt);
3484 #[cfg_attr(target_pointer_width = "32", ignore)] // FIXME(#14064)
3485 fn test_streaming_parser() {
3486 assert_stream_equal(
3487 r#"{ "foo":"bar", "array" : [0, 1, 2, 3, 4, 5], "idents":[null,true,false]}"#,
3489 (ObjectStart, vec![]),
3490 (StringValue("bar".to_string()), vec![StackElement::Key("foo")]),
3491 (ArrayStart, vec![StackElement::Key("array")]),
3492 (U64Value(0), vec![StackElement::Key("array"), StackElement::Index(0)]),
3493 (U64Value(1), vec![StackElement::Key("array"), StackElement::Index(1)]),
3494 (U64Value(2), vec![StackElement::Key("array"), StackElement::Index(2)]),
3495 (U64Value(3), vec![StackElement::Key("array"), StackElement::Index(3)]),
3496 (U64Value(4), vec![StackElement::Key("array"), StackElement::Index(4)]),
3497 (U64Value(5), vec![StackElement::Key("array"), StackElement::Index(5)]),
3498 (ArrayEnd, vec![StackElement::Key("array")]),
3499 (ArrayStart, vec![StackElement::Key("idents")]),
3500 (NullValue, vec![StackElement::Key("idents"),
3501 StackElement::Index(0)]),
3502 (BooleanValue(true), vec![StackElement::Key("idents"),
3503 StackElement::Index(1)]),
3504 (BooleanValue(false), vec![StackElement::Key("idents"),
3505 StackElement::Index(2)]),
3506 (ArrayEnd, vec![StackElement::Key("idents")]),
3507 (ObjectEnd, vec![]),
3511 fn last_event(src: &str) -> JsonEvent {
3512 let mut parser = Parser::new(src.chars());
3513 let mut evt = NullValue;
3515 evt = match parser.next() {
3523 #[cfg_attr(target_pointer_width = "32", ignore)] // FIXME(#14064)
3524 fn test_read_object_streaming() {
3525 assert_eq!(last_event("{ "), Error(SyntaxError(EOFWhileParsingObject, 1, 3)));
3526 assert_eq!(last_event("{1"), Error(SyntaxError(KeyMustBeAString, 1, 2)));
3527 assert_eq!(last_event("{ \"a\""), Error(SyntaxError(EOFWhileParsingObject, 1, 6)));
3528 assert_eq!(last_event("{\"a\""), Error(SyntaxError(EOFWhileParsingObject, 1, 5)));
3529 assert_eq!(last_event("{\"a\" "), Error(SyntaxError(EOFWhileParsingObject, 1, 6)));
3531 assert_eq!(last_event("{\"a\" 1"), Error(SyntaxError(ExpectedColon, 1, 6)));
3532 assert_eq!(last_event("{\"a\":"), Error(SyntaxError(EOFWhileParsingValue, 1, 6)));
3533 assert_eq!(last_event("{\"a\":1"), Error(SyntaxError(EOFWhileParsingObject, 1, 7)));
3534 assert_eq!(last_event("{\"a\":1 1"), Error(SyntaxError(InvalidSyntax, 1, 8)));
3535 assert_eq!(last_event("{\"a\":1,"), Error(SyntaxError(EOFWhileParsingObject, 1, 8)));
3536 assert_eq!(last_event("{\"a\":1,}"), Error(SyntaxError(TrailingComma, 1, 8)));
3538 assert_stream_equal(
3540 vec![(ObjectStart, vec![]), (ObjectEnd, vec![])]
3542 assert_stream_equal(
3545 (ObjectStart, vec![]),
3546 (U64Value(3), vec![StackElement::Key("a")]),
3547 (ObjectEnd, vec![]),
3550 assert_stream_equal(
3551 "{ \"a\": null, \"b\" : true }",
3553 (ObjectStart, vec![]),
3554 (NullValue, vec![StackElement::Key("a")]),
3555 (BooleanValue(true), vec![StackElement::Key("b")]),
3556 (ObjectEnd, vec![]),
3559 assert_stream_equal(
3560 "{\"a\" : 1.0 ,\"b\": [ true ]}",
3562 (ObjectStart, vec![]),
3563 (F64Value(1.0), vec![StackElement::Key("a")]),
3564 (ArrayStart, vec![StackElement::Key("b")]),
3565 (BooleanValue(true),vec![StackElement::Key("b"), StackElement::Index(0)]),
3566 (ArrayEnd, vec![StackElement::Key("b")]),
3567 (ObjectEnd, vec![]),
3570 assert_stream_equal(
3576 { "c": {"d": null} }
3580 (ObjectStart, vec![]),
3581 (F64Value(1.0), vec![StackElement::Key("a")]),
3582 (ArrayStart, vec![StackElement::Key("b")]),
3583 (BooleanValue(true), vec![StackElement::Key("b"),
3584 StackElement::Index(0)]),
3585 (StringValue("foo\nbar".to_string()), vec![StackElement::Key("b"),
3586 StackElement::Index(1)]),
3587 (ObjectStart, vec![StackElement::Key("b"),
3588 StackElement::Index(2)]),
3589 (ObjectStart, vec![StackElement::Key("b"),
3590 StackElement::Index(2),
3591 StackElement::Key("c")]),
3592 (NullValue, vec![StackElement::Key("b"),
3593 StackElement::Index(2),
3594 StackElement::Key("c"),
3595 StackElement::Key("d")]),
3596 (ObjectEnd, vec![StackElement::Key("b"),
3597 StackElement::Index(2),
3598 StackElement::Key("c")]),
3599 (ObjectEnd, vec![StackElement::Key("b"),
3600 StackElement::Index(2)]),
3601 (ArrayEnd, vec![StackElement::Key("b")]),
3602 (ObjectEnd, vec![]),
3607 #[cfg_attr(target_pointer_width = "32", ignore)] // FIXME(#14064)
3608 fn test_read_array_streaming() {
3609 assert_stream_equal(
3612 (ArrayStart, vec![]),
3616 assert_stream_equal(
3619 (ArrayStart, vec![]),
3623 assert_stream_equal(
3626 (ArrayStart, vec![]),
3627 (BooleanValue(true), vec![StackElement::Index(0)]),
3631 assert_stream_equal(
3634 (ArrayStart, vec![]),
3635 (BooleanValue(false), vec![StackElement::Index(0)]),
3639 assert_stream_equal(
3642 (ArrayStart, vec![]),
3643 (NullValue, vec![StackElement::Index(0)]),
3647 assert_stream_equal(
3650 (ArrayStart, vec![]),
3651 (U64Value(3), vec![StackElement::Index(0)]),
3652 (U64Value(1), vec![StackElement::Index(1)]),
3656 assert_stream_equal(
3659 (ArrayStart, vec![]),
3660 (U64Value(3), vec![StackElement::Index(0)]),
3661 (U64Value(2), vec![StackElement::Index(1)]),
3665 assert_stream_equal(
3668 (ArrayStart, vec![]),
3669 (U64Value(2), vec![StackElement::Index(0)]),
3670 (ArrayStart, vec![StackElement::Index(1)]),
3671 (U64Value(4), vec![StackElement::Index(1), StackElement::Index(0)]),
3672 (U64Value(1), vec![StackElement::Index(1), StackElement::Index(1)]),
3673 (ArrayEnd, vec![StackElement::Index(1)]),
3678 assert_eq!(last_event("["), Error(SyntaxError(EOFWhileParsingValue, 1, 2)));
3680 assert_eq!(from_str("["), Err(SyntaxError(EOFWhileParsingValue, 1, 2)));
3681 assert_eq!(from_str("[1"), Err(SyntaxError(EOFWhileParsingArray, 1, 3)));
3682 assert_eq!(from_str("[1,"), Err(SyntaxError(EOFWhileParsingValue, 1, 4)));
3683 assert_eq!(from_str("[1,]"), Err(SyntaxError(InvalidSyntax, 1, 4)));
3684 assert_eq!(from_str("[6 7]"), Err(SyntaxError(InvalidSyntax, 1, 4)));
3688 fn test_trailing_characters_streaming() {
3689 assert_eq!(last_event("nulla"), Error(SyntaxError(TrailingCharacters, 1, 5)));
3690 assert_eq!(last_event("truea"), Error(SyntaxError(TrailingCharacters, 1, 5)));
3691 assert_eq!(last_event("falsea"), Error(SyntaxError(TrailingCharacters, 1, 6)));
3692 assert_eq!(last_event("1a"), Error(SyntaxError(TrailingCharacters, 1, 2)));
3693 assert_eq!(last_event("[]a"), Error(SyntaxError(TrailingCharacters, 1, 3)));
3694 assert_eq!(last_event("{}a"), Error(SyntaxError(TrailingCharacters, 1, 3)));
3697 fn test_read_identifiers_streaming() {
3698 assert_eq!(Parser::new("null".chars()).next(), Some(NullValue));
3699 assert_eq!(Parser::new("true".chars()).next(), Some(BooleanValue(true)));
3700 assert_eq!(Parser::new("false".chars()).next(), Some(BooleanValue(false)));
3702 assert_eq!(last_event("n"), Error(SyntaxError(InvalidSyntax, 1, 2)));
3703 assert_eq!(last_event("nul"), Error(SyntaxError(InvalidSyntax, 1, 4)));
3704 assert_eq!(last_event("t"), Error(SyntaxError(InvalidSyntax, 1, 2)));
3705 assert_eq!(last_event("truz"), Error(SyntaxError(InvalidSyntax, 1, 4)));
3706 assert_eq!(last_event("f"), Error(SyntaxError(InvalidSyntax, 1, 2)));
3707 assert_eq!(last_event("faz"), Error(SyntaxError(InvalidSyntax, 1, 3)));
3712 let mut stack = Stack::new();
3714 assert!(stack.is_empty());
3715 assert!(stack.len() == 0);
3716 assert!(!stack.last_is_index());
3718 stack.push_index(0);
3721 assert!(stack.len() == 1);
3722 assert!(stack.is_equal_to(&[StackElement::Index(1)]));
3723 assert!(stack.starts_with(&[StackElement::Index(1)]));
3724 assert!(stack.ends_with(&[StackElement::Index(1)]));
3725 assert!(stack.last_is_index());
3726 assert!(stack.get(0) == StackElement::Index(1));
3728 stack.push_key("foo".to_string());
3730 assert!(stack.len() == 2);
3731 assert!(stack.is_equal_to(&[StackElement::Index(1), StackElement::Key("foo")]));
3732 assert!(stack.starts_with(&[StackElement::Index(1), StackElement::Key("foo")]));
3733 assert!(stack.starts_with(&[StackElement::Index(1)]));
3734 assert!(stack.ends_with(&[StackElement::Index(1), StackElement::Key("foo")]));
3735 assert!(stack.ends_with(&[StackElement::Key("foo")]));
3736 assert!(!stack.last_is_index());
3737 assert!(stack.get(0) == StackElement::Index(1));
3738 assert!(stack.get(1) == StackElement::Key("foo"));
3740 stack.push_key("bar".to_string());
3742 assert!(stack.len() == 3);
3743 assert!(stack.is_equal_to(&[StackElement::Index(1),
3744 StackElement::Key("foo"),
3745 StackElement::Key("bar")]));
3746 assert!(stack.starts_with(&[StackElement::Index(1)]));
3747 assert!(stack.starts_with(&[StackElement::Index(1), StackElement::Key("foo")]));
3748 assert!(stack.starts_with(&[StackElement::Index(1),
3749 StackElement::Key("foo"),
3750 StackElement::Key("bar")]));
3751 assert!(stack.ends_with(&[StackElement::Key("bar")]));
3752 assert!(stack.ends_with(&[StackElement::Key("foo"), StackElement::Key("bar")]));
3753 assert!(stack.ends_with(&[StackElement::Index(1),
3754 StackElement::Key("foo"),
3755 StackElement::Key("bar")]));
3756 assert!(!stack.last_is_index());
3757 assert!(stack.get(0) == StackElement::Index(1));
3758 assert!(stack.get(1) == StackElement::Key("foo"));
3759 assert!(stack.get(2) == StackElement::Key("bar"));
3763 assert!(stack.len() == 2);
3764 assert!(stack.is_equal_to(&[StackElement::Index(1), StackElement::Key("foo")]));
3765 assert!(stack.starts_with(&[StackElement::Index(1), StackElement::Key("foo")]));
3766 assert!(stack.starts_with(&[StackElement::Index(1)]));
3767 assert!(stack.ends_with(&[StackElement::Index(1), StackElement::Key("foo")]));
3768 assert!(stack.ends_with(&[StackElement::Key("foo")]));
3769 assert!(!stack.last_is_index());
3770 assert!(stack.get(0) == StackElement::Index(1));
3771 assert!(stack.get(1) == StackElement::Key("foo"));
3776 use std::collections::{HashMap,BTreeMap};
3779 let array2 = Array(vec!(U64(1), U64(2)));
3780 let array3 = Array(vec!(U64(1), U64(2), U64(3)));
3782 let mut tree_map = BTreeMap::new();
3783 tree_map.insert("a".to_string(), U64(1));
3784 tree_map.insert("b".to_string(), U64(2));
3788 assert_eq!(array2.to_json(), array2);
3789 assert_eq!(object.to_json(), object);
3790 assert_eq!(3_i.to_json(), I64(3));
3791 assert_eq!(4_i8.to_json(), I64(4));
3792 assert_eq!(5_i16.to_json(), I64(5));
3793 assert_eq!(6_i32.to_json(), I64(6));
3794 assert_eq!(7_i64.to_json(), I64(7));
3795 assert_eq!(8_u.to_json(), U64(8));
3796 assert_eq!(9_u8.to_json(), U64(9));
3797 assert_eq!(10_u16.to_json(), U64(10));
3798 assert_eq!(11_u32.to_json(), U64(11));
3799 assert_eq!(12_u64.to_json(), U64(12));
3800 assert_eq!(13.0_f32.to_json(), F64(13.0_f64));
3801 assert_eq!(14.0_f64.to_json(), F64(14.0_f64));
3802 assert_eq!(().to_json(), Null);
3803 assert_eq!(f32::INFINITY.to_json(), Null);
3804 assert_eq!(f64::NAN.to_json(), Null);
3805 assert_eq!(true.to_json(), Boolean(true));
3806 assert_eq!(false.to_json(), Boolean(false));
3807 assert_eq!("abc".to_json(), String("abc".to_string()));
3808 assert_eq!("abc".to_string().to_json(), String("abc".to_string()));
3809 assert_eq!((1u, 2u).to_json(), array2);
3810 assert_eq!((1u, 2u, 3u).to_json(), array3);
3811 assert_eq!([1u, 2].to_json(), array2);
3812 assert_eq!((&[1u, 2, 3]).to_json(), array3);
3813 assert_eq!((vec![1u, 2]).to_json(), array2);
3814 assert_eq!(vec!(1u, 2, 3).to_json(), array3);
3815 let mut tree_map = BTreeMap::new();
3816 tree_map.insert("a".to_string(), 1u);
3817 tree_map.insert("b".to_string(), 2);
3818 assert_eq!(tree_map.to_json(), object);
3819 let mut hash_map = HashMap::new();
3820 hash_map.insert("a".to_string(), 1u);
3821 hash_map.insert("b".to_string(), 2);
3822 assert_eq!(hash_map.to_json(), object);
3823 assert_eq!(Some(15i).to_json(), I64(15));
3824 assert_eq!(Some(15u).to_json(), U64(15));
3825 assert_eq!(None::<int>.to_json(), Null);
3829 fn bench_streaming_small(b: &mut Bencher) {
3831 let mut parser = Parser::new(
3837 { "c": {"d": null} }
3842 match parser.next() {
3850 fn bench_small(b: &mut Bencher) {
3852 let _ = from_str(r#"{
3857 { "c": {"d": null} }
3863 fn big_json() -> string::String {
3864 let mut src = "[\n".to_string();
3865 for _ in range(0i, 500) {
3866 src.push_str(r#"{ "a": true, "b": null, "c":3.1415, "d": "Hello world", "e": \
3869 src.push_str("{}]");
3874 fn bench_streaming_large(b: &mut Bencher) {
3875 let src = big_json();
3877 let mut parser = Parser::new(src.chars());
3879 match parser.next() {
3887 fn bench_large(b: &mut Bencher) {
3888 let src = big_json();
3889 b.iter( || { let _ = from_str(src.as_slice()); });