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};
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 #[derive(Copy, Show)]
279 pub enum EncoderError {
280 FmtError(fmt::Error),
284 /// Returns a readable error string for a given error code.
285 pub fn error_str(error: ErrorCode) -> &'static str {
287 InvalidSyntax => "invalid syntax",
288 InvalidNumber => "invalid number",
289 EOFWhileParsingObject => "EOF While parsing object",
290 EOFWhileParsingArray => "EOF While parsing array",
291 EOFWhileParsingValue => "EOF While parsing value",
292 EOFWhileParsingString => "EOF While parsing string",
293 KeyMustBeAString => "key must be a string",
294 ExpectedColon => "expected `:`",
295 TrailingCharacters => "trailing characters",
296 TrailingComma => "trailing comma",
297 InvalidEscape => "invalid escape",
298 UnrecognizedHex => "invalid \\u{ esc}ape (unrecognized hex)",
299 NotFourDigit => "invalid \\u{ esc}ape (not four digits)",
300 NotUtf8 => "contents not utf-8",
301 InvalidUnicodeCodePoint => "invalid Unicode code point",
302 LoneLeadingSurrogateInHexEscape => "lone leading surrogate in hex escape",
303 UnexpectedEndOfHexEscape => "unexpected end of hex escape",
307 /// Shortcut function to decode a JSON `&str` into an object
308 pub fn decode<T: ::Decodable>(s: &str) -> DecodeResult<T> {
309 let json = match from_str(s) {
311 Err(e) => return Err(ParseError(e))
314 let mut decoder = Decoder::new(json);
315 ::Decodable::decode(&mut decoder)
318 /// Shortcut function to encode a `T` into a JSON `String`
319 pub fn encode<T: ::Encodable>(object: &T) -> string::String {
320 let mut s = String::new();
322 let mut encoder = Encoder::new(&mut s);
323 let _ = object.encode(&mut encoder);
328 impl fmt::Show for ErrorCode {
329 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
330 error_str(*self).fmt(f)
334 fn io_error_to_error(io: io::IoError) -> ParserError {
335 IoError(io.kind, io.desc)
338 impl std::error::Error for DecoderError {
339 fn description(&self) -> &str { "decoder error" }
340 fn detail(&self) -> Option<std::string::String> { Some(format!("{:?}", self)) }
343 impl std::error::Error for EncoderError {
344 fn description(&self) -> &str { "encoder error" }
345 fn detail(&self) -> Option<std::string::String> { Some(format!("{:?}", self)) }
348 impl std::error::FromError<fmt::Error> for EncoderError {
349 fn from_error(err: fmt::Error) -> EncoderError { EncoderError::FmtError(err) }
352 pub type EncodeResult = Result<(), EncoderError>;
353 pub type DecodeResult<T> = Result<T, DecoderError>;
355 fn escape_str(wr: &mut fmt::Writer, v: &str) -> EncodeResult {
356 try!(wr.write_str("\""));
360 for (i, byte) in v.bytes().enumerate() {
361 let escaped = match byte {
364 b'\x00' => "\\u0000",
365 b'\x01' => "\\u0001",
366 b'\x02' => "\\u0002",
367 b'\x03' => "\\u0003",
368 b'\x04' => "\\u0004",
369 b'\x05' => "\\u0005",
370 b'\x06' => "\\u0006",
371 b'\x07' => "\\u0007",
375 b'\x0b' => "\\u000b",
378 b'\x0e' => "\\u000e",
379 b'\x0f' => "\\u000f",
380 b'\x10' => "\\u0010",
381 b'\x11' => "\\u0011",
382 b'\x12' => "\\u0012",
383 b'\x13' => "\\u0013",
384 b'\x14' => "\\u0014",
385 b'\x15' => "\\u0015",
386 b'\x16' => "\\u0016",
387 b'\x17' => "\\u0017",
388 b'\x18' => "\\u0018",
389 b'\x19' => "\\u0019",
390 b'\x1a' => "\\u001a",
391 b'\x1b' => "\\u001b",
392 b'\x1c' => "\\u001c",
393 b'\x1d' => "\\u001d",
394 b'\x1e' => "\\u001e",
395 b'\x1f' => "\\u001f",
396 b'\x7f' => "\\u007f",
401 try!(wr.write_str(&v[start..i]));
404 try!(wr.write_str(escaped));
409 if start != v.len() {
410 try!(wr.write_str(&v[start..]));
413 try!(wr.write_str("\""));
417 fn escape_char(writer: &mut fmt::Writer, v: char) -> EncodeResult {
418 let mut buf = [0; 4];
419 let n = v.encode_utf8(&mut buf).unwrap();
420 let buf = unsafe { str::from_utf8_unchecked(&buf[..n]) };
421 escape_str(writer, buf)
424 fn spaces(wr: &mut fmt::Writer, mut n: uint) -> EncodeResult {
425 const BUF: &'static str = " ";
427 while n >= BUF.len() {
428 try!(wr.write_str(BUF));
433 try!(wr.write_str(&BUF[..n]));
438 fn fmt_number_or_null(v: f64) -> string::String {
440 Fp::Nan | Fp::Infinite => string::String::from_str("null"),
441 _ if v.fract() != 0f64 => f64::to_str_digits(v, 6u),
442 _ => f64::to_str_digits(v, 6u) + ".0",
446 /// A structure for implementing serialization to JSON.
447 pub struct Encoder<'a> {
448 writer: &'a mut (fmt::Writer+'a),
449 is_emitting_map_key: bool,
452 impl<'a> Encoder<'a> {
453 /// Creates a new JSON encoder whose output will be written to the writer
455 pub fn new(writer: &'a mut fmt::Writer) -> Encoder<'a> {
456 Encoder { writer: writer, is_emitting_map_key: false, }
460 macro_rules! emit_enquoted_if_mapkey {
461 ($enc:ident,$e:expr) => {
462 if $enc.is_emitting_map_key {
463 try!(write!($enc.writer, "\"{}\"", $e));
466 try!(write!($enc.writer, "{}", $e));
472 impl<'a> ::Encoder for Encoder<'a> {
473 type Error = EncoderError;
475 fn emit_nil(&mut self) -> EncodeResult {
476 if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
477 try!(write!(self.writer, "null"));
481 fn emit_uint(&mut self, v: uint) -> EncodeResult { emit_enquoted_if_mapkey!(self, v) }
482 fn emit_u64(&mut self, v: u64) -> EncodeResult { emit_enquoted_if_mapkey!(self, v) }
483 fn emit_u32(&mut self, v: u32) -> EncodeResult { emit_enquoted_if_mapkey!(self, v) }
484 fn emit_u16(&mut self, v: u16) -> EncodeResult { emit_enquoted_if_mapkey!(self, v) }
485 fn emit_u8(&mut self, v: u8) -> EncodeResult { emit_enquoted_if_mapkey!(self, v) }
487 fn emit_int(&mut self, v: int) -> EncodeResult { emit_enquoted_if_mapkey!(self, v) }
488 fn emit_i64(&mut self, v: i64) -> EncodeResult { emit_enquoted_if_mapkey!(self, v) }
489 fn emit_i32(&mut self, v: i32) -> EncodeResult { emit_enquoted_if_mapkey!(self, v) }
490 fn emit_i16(&mut self, v: i16) -> EncodeResult { emit_enquoted_if_mapkey!(self, v) }
491 fn emit_i8(&mut self, v: i8) -> EncodeResult { emit_enquoted_if_mapkey!(self, v) }
493 fn emit_bool(&mut self, v: bool) -> EncodeResult {
494 if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
496 try!(write!(self.writer, "true"));
498 try!(write!(self.writer, "false"));
503 fn emit_f64(&mut self, v: f64) -> EncodeResult {
504 emit_enquoted_if_mapkey!(self, fmt_number_or_null(v))
506 fn emit_f32(&mut self, v: f32) -> EncodeResult {
507 self.emit_f64(v as f64)
510 fn emit_char(&mut self, v: char) -> EncodeResult {
511 escape_char(self.writer, v)
513 fn emit_str(&mut self, v: &str) -> EncodeResult {
514 escape_str(self.writer, v)
517 fn emit_enum<F>(&mut self, _name: &str, f: F) -> EncodeResult where
518 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
520 if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
524 fn emit_enum_variant<F>(&mut self,
528 f: F) -> EncodeResult where
529 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
531 // enums are encoded as strings or objects
533 // Kangaroo(34,"William") => {"variant": "Kangaroo", "fields": [34,"William"]}
534 if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
536 escape_str(self.writer, name)
538 try!(write!(self.writer, "{{\"variant\":"));
539 try!(escape_str(self.writer, name));
540 try!(write!(self.writer, ",\"fields\":["));
542 try!(write!(self.writer, "]}}"));
547 fn emit_enum_variant_arg<F>(&mut self, idx: uint, f: F) -> EncodeResult where
548 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
550 if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
552 try!(write!(self.writer, ","));
557 fn emit_enum_struct_variant<F>(&mut self,
561 f: F) -> EncodeResult where
562 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
564 if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
565 self.emit_enum_variant(name, id, cnt, f)
568 fn emit_enum_struct_variant_field<F>(&mut self,
571 f: F) -> EncodeResult where
572 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
574 if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
575 self.emit_enum_variant_arg(idx, f)
578 fn emit_struct<F>(&mut self, _: &str, _: uint, f: F) -> EncodeResult where
579 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
581 if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
582 try!(write!(self.writer, "{{"));
584 try!(write!(self.writer, "}}"));
588 fn emit_struct_field<F>(&mut self, name: &str, idx: uint, f: F) -> EncodeResult where
589 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
591 if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
592 if idx != 0 { try!(write!(self.writer, ",")); }
593 try!(escape_str(self.writer, name));
594 try!(write!(self.writer, ":"));
598 fn emit_tuple<F>(&mut self, len: uint, f: F) -> EncodeResult where
599 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
601 if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
602 self.emit_seq(len, f)
604 fn emit_tuple_arg<F>(&mut self, idx: uint, f: F) -> EncodeResult where
605 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
607 if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
608 self.emit_seq_elt(idx, f)
611 fn emit_tuple_struct<F>(&mut self, _name: &str, len: uint, f: F) -> EncodeResult where
612 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
614 if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
615 self.emit_seq(len, f)
617 fn emit_tuple_struct_arg<F>(&mut self, idx: uint, f: F) -> EncodeResult where
618 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
620 if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
621 self.emit_seq_elt(idx, f)
624 fn emit_option<F>(&mut self, f: F) -> EncodeResult where
625 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
627 if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
630 fn emit_option_none(&mut self) -> EncodeResult {
631 if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
634 fn emit_option_some<F>(&mut self, f: F) -> EncodeResult where
635 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
637 if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
641 fn emit_seq<F>(&mut self, _len: uint, f: F) -> EncodeResult where
642 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
644 if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
645 try!(write!(self.writer, "["));
647 try!(write!(self.writer, "]"));
651 fn emit_seq_elt<F>(&mut self, idx: uint, f: F) -> EncodeResult where
652 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
654 if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
656 try!(write!(self.writer, ","));
661 fn emit_map<F>(&mut self, _len: uint, f: F) -> EncodeResult where
662 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
664 if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
665 try!(write!(self.writer, "{{"));
667 try!(write!(self.writer, "}}"));
671 fn emit_map_elt_key<F>(&mut self, idx: uint, f: F) -> EncodeResult where
672 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
674 if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
675 if idx != 0 { try!(write!(self.writer, ",")) }
676 self.is_emitting_map_key = true;
678 self.is_emitting_map_key = false;
682 fn emit_map_elt_val<F>(&mut self, _idx: uint, f: F) -> EncodeResult where
683 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
685 if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
686 try!(write!(self.writer, ":"));
691 /// Another encoder for JSON, but prints out human-readable JSON instead of
693 pub struct PrettyEncoder<'a> {
694 writer: &'a mut (fmt::Writer+'a),
697 is_emitting_map_key: bool,
700 impl<'a> PrettyEncoder<'a> {
701 /// Creates a new encoder whose output will be written to the specified writer
702 pub fn new(writer: &'a mut fmt::Writer) -> PrettyEncoder<'a> {
707 is_emitting_map_key: false,
711 /// Set the number of spaces to indent for each level.
712 /// This is safe to set during encoding.
713 pub fn set_indent(&mut self, indent: uint) {
714 // self.indent very well could be 0 so we need to use checked division.
715 let level = self.curr_indent.checked_div(self.indent).unwrap_or(0);
716 self.indent = indent;
717 self.curr_indent = level * self.indent;
721 impl<'a> ::Encoder for PrettyEncoder<'a> {
722 type Error = EncoderError;
724 fn emit_nil(&mut self) -> EncodeResult {
725 if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
726 try!(write!(self.writer, "null"));
730 fn emit_uint(&mut self, v: uint) -> EncodeResult { emit_enquoted_if_mapkey!(self, v) }
731 fn emit_u64(&mut self, v: u64) -> EncodeResult { emit_enquoted_if_mapkey!(self, v) }
732 fn emit_u32(&mut self, v: u32) -> EncodeResult { emit_enquoted_if_mapkey!(self, v) }
733 fn emit_u16(&mut self, v: u16) -> EncodeResult { emit_enquoted_if_mapkey!(self, v) }
734 fn emit_u8(&mut self, v: u8) -> EncodeResult { emit_enquoted_if_mapkey!(self, v) }
736 fn emit_int(&mut self, v: int) -> EncodeResult { emit_enquoted_if_mapkey!(self, v) }
737 fn emit_i64(&mut self, v: i64) -> EncodeResult { emit_enquoted_if_mapkey!(self, v) }
738 fn emit_i32(&mut self, v: i32) -> EncodeResult { emit_enquoted_if_mapkey!(self, v) }
739 fn emit_i16(&mut self, v: i16) -> EncodeResult { emit_enquoted_if_mapkey!(self, v) }
740 fn emit_i8(&mut self, v: i8) -> EncodeResult { emit_enquoted_if_mapkey!(self, v) }
742 fn emit_bool(&mut self, v: bool) -> EncodeResult {
743 if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
745 try!(write!(self.writer, "true"));
747 try!(write!(self.writer, "false"));
752 fn emit_f64(&mut self, v: f64) -> EncodeResult {
753 emit_enquoted_if_mapkey!(self, fmt_number_or_null(v))
755 fn emit_f32(&mut self, v: f32) -> EncodeResult {
756 self.emit_f64(v as f64)
759 fn emit_char(&mut self, v: char) -> EncodeResult {
760 escape_char(self.writer, v)
762 fn emit_str(&mut self, v: &str) -> EncodeResult {
763 escape_str(self.writer, v)
766 fn emit_enum<F>(&mut self, _name: &str, f: F) -> EncodeResult where
767 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
769 if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
773 fn emit_enum_variant<F>(&mut self,
778 -> EncodeResult where
779 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
781 if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
783 escape_str(self.writer, name)
785 try!(write!(self.writer, "{{\n"));
786 self.curr_indent += self.indent;
787 try!(spaces(self.writer, self.curr_indent));
788 try!(write!(self.writer, "\"variant\": "));
789 try!(escape_str(self.writer, name));
790 try!(write!(self.writer, ",\n"));
791 try!(spaces(self.writer, self.curr_indent));
792 try!(write!(self.writer, "\"fields\": [\n"));
793 self.curr_indent += self.indent;
795 self.curr_indent -= self.indent;
796 try!(write!(self.writer, "\n"));
797 try!(spaces(self.writer, self.curr_indent));
798 self.curr_indent -= self.indent;
799 try!(write!(self.writer, "]\n"));
800 try!(spaces(self.writer, self.curr_indent));
801 try!(write!(self.writer, "}}"));
806 fn emit_enum_variant_arg<F>(&mut self, idx: uint, f: F) -> EncodeResult where
807 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
809 if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
811 try!(write!(self.writer, ",\n"));
813 try!(spaces(self.writer, self.curr_indent));
817 fn emit_enum_struct_variant<F>(&mut self,
821 f: F) -> EncodeResult where
822 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
824 if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
825 self.emit_enum_variant(name, id, cnt, f)
828 fn emit_enum_struct_variant_field<F>(&mut self,
831 f: F) -> EncodeResult where
832 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
834 if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
835 self.emit_enum_variant_arg(idx, f)
839 fn emit_struct<F>(&mut self, _: &str, len: uint, f: F) -> EncodeResult where
840 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
842 if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
844 try!(write!(self.writer, "{{}}"));
846 try!(write!(self.writer, "{{"));
847 self.curr_indent += self.indent;
849 self.curr_indent -= self.indent;
850 try!(write!(self.writer, "\n"));
851 try!(spaces(self.writer, self.curr_indent));
852 try!(write!(self.writer, "}}"));
857 fn emit_struct_field<F>(&mut self, name: &str, idx: uint, f: F) -> EncodeResult where
858 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
860 if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
862 try!(write!(self.writer, "\n"));
864 try!(write!(self.writer, ",\n"));
866 try!(spaces(self.writer, self.curr_indent));
867 try!(escape_str(self.writer, name));
868 try!(write!(self.writer, ": "));
872 fn emit_tuple<F>(&mut self, len: uint, f: F) -> EncodeResult where
873 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
875 if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
876 self.emit_seq(len, f)
878 fn emit_tuple_arg<F>(&mut self, idx: uint, f: F) -> EncodeResult where
879 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
881 if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
882 self.emit_seq_elt(idx, f)
885 fn emit_tuple_struct<F>(&mut self, _: &str, len: uint, f: F) -> EncodeResult where
886 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
888 if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
889 self.emit_seq(len, f)
891 fn emit_tuple_struct_arg<F>(&mut self, idx: uint, f: F) -> EncodeResult where
892 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
894 if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
895 self.emit_seq_elt(idx, f)
898 fn emit_option<F>(&mut self, f: F) -> EncodeResult where
899 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
901 if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
904 fn emit_option_none(&mut self) -> EncodeResult {
905 if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
908 fn emit_option_some<F>(&mut self, f: F) -> EncodeResult where
909 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
911 if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
915 fn emit_seq<F>(&mut self, len: uint, f: F) -> EncodeResult where
916 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
918 if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
920 try!(write!(self.writer, "[]"));
922 try!(write!(self.writer, "["));
923 self.curr_indent += self.indent;
925 self.curr_indent -= self.indent;
926 try!(write!(self.writer, "\n"));
927 try!(spaces(self.writer, self.curr_indent));
928 try!(write!(self.writer, "]"));
933 fn emit_seq_elt<F>(&mut self, idx: uint, f: F) -> EncodeResult where
934 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
936 if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
938 try!(write!(self.writer, "\n"));
940 try!(write!(self.writer, ",\n"));
942 try!(spaces(self.writer, self.curr_indent));
946 fn emit_map<F>(&mut self, len: uint, f: F) -> EncodeResult where
947 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
949 if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
951 try!(write!(self.writer, "{{}}"));
953 try!(write!(self.writer, "{{"));
954 self.curr_indent += self.indent;
956 self.curr_indent -= self.indent;
957 try!(write!(self.writer, "\n"));
958 try!(spaces(self.writer, self.curr_indent));
959 try!(write!(self.writer, "}}"));
964 fn emit_map_elt_key<F>(&mut self, idx: uint, f: F) -> EncodeResult where
965 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
967 if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
969 try!(write!(self.writer, "\n"));
971 try!(write!(self.writer, ",\n"));
973 try!(spaces(self.writer, self.curr_indent));
974 self.is_emitting_map_key = true;
976 self.is_emitting_map_key = false;
980 fn emit_map_elt_val<F>(&mut self, _idx: uint, f: F) -> EncodeResult where
981 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
983 if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
984 try!(write!(self.writer, ": "));
989 impl Encodable for Json {
990 fn encode<E: ::Encoder>(&self, e: &mut E) -> Result<(), E::Error> {
992 Json::I64(v) => v.encode(e),
993 Json::U64(v) => v.encode(e),
994 Json::F64(v) => v.encode(e),
995 Json::String(ref v) => v.encode(e),
996 Json::Boolean(v) => v.encode(e),
997 Json::Array(ref v) => v.encode(e),
998 Json::Object(ref v) => v.encode(e),
999 Json::Null => e.emit_nil(),
1004 /// Create an `AsJson` wrapper which can be used to print a value as JSON
1005 /// on-the-fly via `write!`
1006 pub fn as_json<T>(t: &T) -> AsJson<T> {
1010 /// Create an `AsPrettyJson` wrapper which can be used to print a value as JSON
1011 /// on-the-fly via `write!`
1012 pub fn as_pretty_json<T>(t: &T) -> AsPrettyJson<T> {
1013 AsPrettyJson { inner: t, indent: None }
1017 /// Borrow this json object as a pretty object to generate a pretty
1018 /// representation for it via `Show`.
1019 pub fn pretty(&self) -> PrettyJson {
1020 PrettyJson { inner: self }
1023 /// If the Json value is an Object, returns the value associated with the provided key.
1024 /// Otherwise, returns None.
1025 pub fn find<'a>(&'a self, key: &str) -> Option<&'a Json>{
1027 &Json::Object(ref map) => map.get(key),
1032 /// Attempts to get a nested Json Object for each key in `keys`.
1033 /// If any key is found not to exist, find_path will return None.
1034 /// Otherwise, it will return the Json value associated with the final key.
1035 pub fn find_path<'a>(&'a self, keys: &[&str]) -> Option<&'a Json>{
1036 let mut target = self;
1037 for key in keys.iter() {
1038 match target.find(*key) {
1039 Some(t) => { target = t; },
1046 /// If the Json value is an Object, performs a depth-first search until
1047 /// a value associated with the provided key is found. If no value is found
1048 /// or the Json value is not an Object, returns None.
1049 pub fn search<'a>(&'a self, key: &str) -> Option<&'a Json> {
1051 &Json::Object(ref map) => {
1052 match map.get(key) {
1053 Some(json_value) => Some(json_value),
1055 for (_, v) in map.iter() {
1056 match v.search(key) {
1057 x if x.is_some() => return x,
1069 /// Returns true if the Json value is an Object. Returns false otherwise.
1070 pub fn is_object<'a>(&'a self) -> bool {
1071 self.as_object().is_some()
1074 /// If the Json value is an Object, returns the associated BTreeMap.
1075 /// Returns None otherwise.
1076 pub fn as_object<'a>(&'a self) -> Option<&'a Object> {
1078 &Json::Object(ref map) => Some(map),
1083 /// Returns true if the Json value is an Array. Returns false otherwise.
1084 pub fn is_array<'a>(&'a self) -> bool {
1085 self.as_array().is_some()
1088 /// If the Json value is an Array, returns the associated vector.
1089 /// Returns None otherwise.
1090 pub fn as_array<'a>(&'a self) -> Option<&'a Array> {
1092 &Json::Array(ref array) => Some(&*array),
1097 /// Returns true if the Json value is a String. Returns false otherwise.
1098 pub fn is_string<'a>(&'a self) -> bool {
1099 self.as_string().is_some()
1102 /// If the Json value is a String, returns the associated str.
1103 /// Returns None otherwise.
1104 pub fn as_string<'a>(&'a self) -> Option<&'a str> {
1106 Json::String(ref s) => Some(&s[]),
1111 /// Returns true if the Json value is a Number. Returns false otherwise.
1112 pub fn is_number(&self) -> bool {
1114 Json::I64(_) | Json::U64(_) | Json::F64(_) => true,
1119 /// Returns true if the Json value is a i64. Returns false otherwise.
1120 pub fn is_i64(&self) -> bool {
1122 Json::I64(_) => true,
1127 /// Returns true if the Json value is a u64. Returns false otherwise.
1128 pub fn is_u64(&self) -> bool {
1130 Json::U64(_) => true,
1135 /// Returns true if the Json value is a f64. Returns false otherwise.
1136 pub fn is_f64(&self) -> bool {
1138 Json::F64(_) => true,
1143 /// If the Json value is a number, return or cast it to a i64.
1144 /// Returns None otherwise.
1145 pub fn as_i64(&self) -> Option<i64> {
1147 Json::I64(n) => Some(n),
1148 Json::U64(n) => num::cast(n),
1153 /// If the Json value is a number, return or cast it to a u64.
1154 /// Returns None otherwise.
1155 pub fn as_u64(&self) -> Option<u64> {
1157 Json::I64(n) => num::cast(n),
1158 Json::U64(n) => Some(n),
1163 /// If the Json value is a number, return or cast it to a f64.
1164 /// Returns None otherwise.
1165 pub fn as_f64(&self) -> Option<f64> {
1167 Json::I64(n) => num::cast(n),
1168 Json::U64(n) => num::cast(n),
1169 Json::F64(n) => Some(n),
1174 /// Returns true if the Json value is a Boolean. Returns false otherwise.
1175 pub fn is_boolean(&self) -> bool {
1176 self.as_boolean().is_some()
1179 /// If the Json value is a Boolean, returns the associated bool.
1180 /// Returns None otherwise.
1181 pub fn as_boolean(&self) -> Option<bool> {
1183 &Json::Boolean(b) => Some(b),
1188 /// Returns true if the Json value is a Null. Returns false otherwise.
1189 pub fn is_null(&self) -> bool {
1190 self.as_null().is_some()
1193 /// If the Json value is a Null, returns ().
1194 /// Returns None otherwise.
1195 pub fn as_null(&self) -> Option<()> {
1197 &Json::Null => Some(()),
1203 impl<'a> Index<&'a str> for Json {
1206 fn index(&self, idx: & &str) -> &Json {
1207 self.find(*idx).unwrap()
1211 impl Index<uint> for Json {
1214 fn index<'a>(&'a self, idx: &uint) -> &'a Json {
1216 &Json::Array(ref v) => &v[*idx],
1217 _ => panic!("can only index Json with uint if it is an array")
1222 /// The output of the streaming parser.
1223 #[derive(PartialEq, Clone, Show)]
1224 pub enum JsonEvent {
1233 StringValue(string::String),
1238 #[derive(PartialEq, Show)]
1240 // Parse a value in an array, true means first element.
1242 // Parse ',' or ']' after an element in an array.
1244 // Parse a key:value in an object, true means first element.
1246 // Parse ',' or ']' after an element in an object.
1250 // Expecting the stream to end.
1252 // Parsing can't continue.
1256 /// A Stack represents the current position of the parser in the logical
1257 /// structure of the JSON stream.
1258 /// For example foo.bar[3].x
1260 stack: Vec<InternalStackElement>,
1261 str_buffer: Vec<u8>,
1264 /// StackElements compose a Stack.
1265 /// For example, StackElement::Key("foo"), StackElement::Key("bar"),
1266 /// StackElement::Index(3) and StackElement::Key("x") are the
1267 /// StackElements compositing the stack that represents foo.bar[3].x
1268 #[derive(PartialEq, Clone, Show)]
1269 pub enum StackElement<'l> {
1274 // Internally, Key elements are stored as indices in a buffer to avoid
1275 // allocating a string for every member of an object.
1276 #[derive(PartialEq, Clone, Show)]
1277 enum InternalStackElement {
1279 InternalKey(u16, u16), // start, size
1283 pub fn new() -> Stack {
1284 Stack { stack: Vec::new(), str_buffer: Vec::new() }
1287 /// Returns The number of elements in the Stack.
1288 pub fn len(&self) -> uint { self.stack.len() }
1290 /// Returns true if the stack is empty.
1291 pub fn is_empty(&self) -> bool { self.stack.is_empty() }
1293 /// Provides access to the StackElement at a given index.
1294 /// lower indices are at the bottom of the stack while higher indices are
1296 pub fn get<'l>(&'l self, idx: uint) -> StackElement<'l> {
1297 match self.stack[idx] {
1298 InternalIndex(i) => StackElement::Index(i),
1299 InternalKey(start, size) => {
1300 StackElement::Key(str::from_utf8(
1301 &self.str_buffer[(start as uint) .. (start as uint + size as uint)])
1307 /// Compares this stack with an array of StackElements.
1308 pub fn is_equal_to(&self, rhs: &[StackElement]) -> bool {
1309 if self.stack.len() != rhs.len() { return false; }
1310 for i in range(0, rhs.len()) {
1311 if self.get(i) != rhs[i] { return false; }
1316 /// Returns true if the bottom-most elements of this stack are the same as
1317 /// the ones passed as parameter.
1318 pub fn starts_with(&self, rhs: &[StackElement]) -> bool {
1319 if self.stack.len() < rhs.len() { return false; }
1320 for i in range(0, rhs.len()) {
1321 if self.get(i) != rhs[i] { return false; }
1326 /// Returns true if the top-most elements of this stack are the same as
1327 /// the ones passed as parameter.
1328 pub fn ends_with(&self, rhs: &[StackElement]) -> bool {
1329 if self.stack.len() < rhs.len() { return false; }
1330 let offset = self.stack.len() - rhs.len();
1331 for i in range(0, rhs.len()) {
1332 if self.get(i + offset) != rhs[i] { return false; }
1337 /// Returns the top-most element (if any).
1338 pub fn top<'l>(&'l self) -> Option<StackElement<'l>> {
1339 return match self.stack.last() {
1341 Some(&InternalIndex(i)) => Some(StackElement::Index(i)),
1342 Some(&InternalKey(start, size)) => {
1343 Some(StackElement::Key(str::from_utf8(
1344 &self.str_buffer[(start as uint) .. (start+size) as uint]
1350 // Used by Parser to insert StackElement::Key elements at the top of the stack.
1351 fn push_key(&mut self, key: string::String) {
1352 self.stack.push(InternalKey(self.str_buffer.len() as u16, key.len() as u16));
1353 for c in key.as_bytes().iter() {
1354 self.str_buffer.push(*c);
1358 // Used by Parser to insert StackElement::Index elements at the top of the stack.
1359 fn push_index(&mut self, index: u32) {
1360 self.stack.push(InternalIndex(index));
1363 // Used by Parser to remove the top-most element of the stack.
1365 assert!(!self.is_empty());
1366 match *self.stack.last().unwrap() {
1367 InternalKey(_, sz) => {
1368 let new_size = self.str_buffer.len() - sz as uint;
1369 self.str_buffer.truncate(new_size);
1371 InternalIndex(_) => {}
1376 // Used by Parser to test whether the top-most element is an index.
1377 fn last_is_index(&self) -> bool {
1378 if self.is_empty() { return false; }
1379 return match *self.stack.last().unwrap() {
1380 InternalIndex(_) => true,
1385 // Used by Parser to increment the index of the top-most element.
1386 fn bump_index(&mut self) {
1387 let len = self.stack.len();
1388 let idx = match *self.stack.last().unwrap() {
1389 InternalIndex(i) => { i + 1 }
1392 self.stack[len - 1] = InternalIndex(idx);
1396 /// A streaming JSON parser implemented as an iterator of JsonEvent, consuming
1397 /// an iterator of char.
1398 pub struct Parser<T> {
1403 // We maintain a stack representing where we are in the logical structure
1404 // of the JSON stream.
1406 // A state machine is kept to make it possible to interrupt and resume parsing.
1410 impl<T: Iterator<Item=char>> Iterator for Parser<T> {
1411 type Item = JsonEvent;
1413 fn next(&mut self) -> Option<JsonEvent> {
1414 if self.state == ParseFinished {
1418 if self.state == ParseBeforeFinish {
1419 self.parse_whitespace();
1420 // Make sure there is no trailing characters.
1422 self.state = ParseFinished;
1425 return Some(self.error_event(TrailingCharacters));
1429 return Some(self.parse());
1433 impl<T: Iterator<Item=char>> Parser<T> {
1434 /// Creates the JSON parser.
1435 pub fn new(rdr: T) -> Parser<T> {
1436 let mut p = Parser {
1441 stack: Stack::new(),
1448 /// Provides access to the current position in the logical structure of the
1450 pub fn stack<'l>(&'l self) -> &'l Stack {
1454 fn eof(&self) -> bool { self.ch.is_none() }
1455 fn ch_or_null(&self) -> char { self.ch.unwrap_or('\x00') }
1456 fn bump(&mut self) {
1457 self.ch = self.rdr.next();
1459 if self.ch_is('\n') {
1467 fn next_char(&mut self) -> Option<char> {
1471 fn ch_is(&self, c: char) -> bool {
1475 fn error<U>(&self, reason: ErrorCode) -> Result<U, ParserError> {
1476 Err(SyntaxError(reason, self.line, self.col))
1479 fn parse_whitespace(&mut self) {
1480 while self.ch_is(' ') ||
1483 self.ch_is('\r') { self.bump(); }
1486 fn parse_number(&mut self) -> JsonEvent {
1487 let mut neg = false;
1489 if self.ch_is('-') {
1494 let res = match self.parse_u64() {
1496 Err(e) => { return Error(e); }
1499 if self.ch_is('.') || self.ch_is('e') || self.ch_is('E') {
1500 let mut res = res as f64;
1502 if self.ch_is('.') {
1503 res = match self.parse_decimal(res) {
1505 Err(e) => { return Error(e); }
1509 if self.ch_is('e') || self.ch_is('E') {
1510 res = match self.parse_exponent(res) {
1512 Err(e) => { return Error(e); }
1523 let res = -(res as i64);
1525 // Make sure we didn't underflow.
1527 Error(SyntaxError(InvalidNumber, self.line, self.col))
1537 fn parse_u64(&mut self) -> Result<u64, ParserError> {
1539 let last_accum = 0; // necessary to detect overflow.
1541 match self.ch_or_null() {
1545 // A leading '0' must be the only digit before the decimal point.
1546 match self.ch_or_null() {
1547 '0' ... '9' => return self.error(InvalidNumber),
1553 match self.ch_or_null() {
1554 c @ '0' ... '9' => {
1556 accum += (c as u64) - ('0' as u64);
1558 // Detect overflow by comparing to the last value.
1559 if accum <= last_accum { return self.error(InvalidNumber); }
1567 _ => return self.error(InvalidNumber),
1573 fn parse_decimal(&mut self, mut res: f64) -> Result<f64, ParserError> {
1576 // Make sure a digit follows the decimal place.
1577 match self.ch_or_null() {
1579 _ => return self.error(InvalidNumber)
1584 match self.ch_or_null() {
1585 c @ '0' ... '9' => {
1587 res += (((c as int) - ('0' as int)) as f64) * dec;
1597 fn parse_exponent(&mut self, mut res: f64) -> Result<f64, ParserError> {
1601 let mut neg_exp = false;
1603 if self.ch_is('+') {
1605 } else if self.ch_is('-') {
1610 // Make sure a digit follows the exponent place.
1611 match self.ch_or_null() {
1613 _ => return self.error(InvalidNumber)
1616 match self.ch_or_null() {
1617 c @ '0' ... '9' => {
1619 exp += (c as uint) - ('0' as uint);
1627 let exp = 10_f64.powi(exp as i32);
1637 fn decode_hex_escape(&mut self) -> Result<u16, ParserError> {
1640 while i < 4 && !self.eof() {
1642 n = match self.ch_or_null() {
1643 c @ '0' ... '9' => n * 16 + ((c as u16) - ('0' as u16)),
1644 'a' | 'A' => n * 16 + 10,
1645 'b' | 'B' => n * 16 + 11,
1646 'c' | 'C' => n * 16 + 12,
1647 'd' | 'D' => n * 16 + 13,
1648 'e' | 'E' => n * 16 + 14,
1649 'f' | 'F' => n * 16 + 15,
1650 _ => return self.error(InvalidEscape)
1656 // Error out if we didn't parse 4 digits.
1658 return self.error(InvalidEscape);
1664 fn parse_str(&mut self) -> Result<string::String, ParserError> {
1665 let mut escape = false;
1666 let mut res = string::String::new();
1671 return self.error(EOFWhileParsingString);
1675 match self.ch_or_null() {
1676 '"' => res.push('"'),
1677 '\\' => res.push('\\'),
1678 '/' => res.push('/'),
1679 'b' => res.push('\x08'),
1680 'f' => res.push('\x0c'),
1681 'n' => res.push('\n'),
1682 'r' => res.push('\r'),
1683 't' => res.push('\t'),
1684 'u' => match try!(self.decode_hex_escape()) {
1685 0xDC00 ... 0xDFFF => {
1686 return self.error(LoneLeadingSurrogateInHexEscape)
1689 // Non-BMP characters are encoded as a sequence of
1690 // two hex escapes, representing UTF-16 surrogates.
1691 n1 @ 0xD800 ... 0xDBFF => {
1692 match (self.next_char(), self.next_char()) {
1693 (Some('\\'), Some('u')) => (),
1694 _ => return self.error(UnexpectedEndOfHexEscape),
1697 let buf = [n1, try!(self.decode_hex_escape())];
1698 match unicode_str::utf16_items(&buf).next() {
1699 Some(Utf16Item::ScalarValue(c)) => res.push(c),
1700 _ => return self.error(LoneLeadingSurrogateInHexEscape),
1704 n => match char::from_u32(n as u32) {
1705 Some(c) => res.push(c),
1706 None => return self.error(InvalidUnicodeCodePoint),
1709 _ => return self.error(InvalidEscape),
1712 } else if self.ch_is('\\') {
1720 Some(c) => res.push(c),
1721 None => unreachable!()
1727 // Invoked at each iteration, consumes the stream until it has enough
1728 // information to return a JsonEvent.
1729 // Manages an internal state so that parsing can be interrupted and resumed.
1730 // Also keeps track of the position in the logical structure of the json
1731 // stream int the form of a stack that can be queried by the user using the
1733 fn parse(&mut self) -> JsonEvent {
1735 // The only paths where the loop can spin a new iteration
1736 // are in the cases ParseArrayComma and ParseObjectComma if ','
1737 // is parsed. In these cases the state is set to (respectively)
1738 // ParseArray(false) and ParseObject(false), which always return,
1739 // so there is no risk of getting stuck in an infinite loop.
1740 // All other paths return before the end of the loop's iteration.
1741 self.parse_whitespace();
1745 return self.parse_start();
1747 ParseArray(first) => {
1748 return self.parse_array(first);
1750 ParseArrayComma => {
1751 match self.parse_array_comma_or_end() {
1752 Some(evt) => { return evt; }
1756 ParseObject(first) => {
1757 return self.parse_object(first);
1759 ParseObjectComma => {
1761 if self.ch_is(',') {
1762 self.state = ParseObject(false);
1765 return self.parse_object_end();
1769 return self.error_event(InvalidSyntax);
1775 fn parse_start(&mut self) -> JsonEvent {
1776 let val = self.parse_value();
1777 self.state = match val {
1778 Error(_) => ParseFinished,
1779 ArrayStart => ParseArray(true),
1780 ObjectStart => ParseObject(true),
1781 _ => ParseBeforeFinish,
1786 fn parse_array(&mut self, first: bool) -> JsonEvent {
1787 if self.ch_is(']') {
1789 self.error_event(InvalidSyntax)
1791 self.state = if self.stack.is_empty() {
1793 } else if self.stack.last_is_index() {
1803 self.stack.push_index(0);
1805 let val = self.parse_value();
1806 self.state = match val {
1807 Error(_) => ParseFinished,
1808 ArrayStart => ParseArray(true),
1809 ObjectStart => ParseObject(true),
1810 _ => ParseArrayComma,
1816 fn parse_array_comma_or_end(&mut self) -> Option<JsonEvent> {
1817 if self.ch_is(',') {
1818 self.stack.bump_index();
1819 self.state = ParseArray(false);
1822 } else if self.ch_is(']') {
1824 self.state = if self.stack.is_empty() {
1826 } else if self.stack.last_is_index() {
1833 } else if self.eof() {
1834 Some(self.error_event(EOFWhileParsingArray))
1836 Some(self.error_event(InvalidSyntax))
1840 fn parse_object(&mut self, first: bool) -> JsonEvent {
1841 if self.ch_is('}') {
1843 if self.stack.is_empty() {
1844 return self.error_event(TrailingComma);
1849 self.state = if self.stack.is_empty() {
1851 } else if self.stack.last_is_index() {
1860 return self.error_event(EOFWhileParsingObject);
1862 if !self.ch_is('"') {
1863 return self.error_event(KeyMustBeAString);
1865 let s = match self.parse_str() {
1868 self.state = ParseFinished;
1872 self.parse_whitespace();
1874 return self.error_event(EOFWhileParsingObject);
1875 } else if self.ch_or_null() != ':' {
1876 return self.error_event(ExpectedColon);
1878 self.stack.push_key(s);
1880 self.parse_whitespace();
1882 let val = self.parse_value();
1884 self.state = match val {
1885 Error(_) => ParseFinished,
1886 ArrayStart => ParseArray(true),
1887 ObjectStart => ParseObject(true),
1888 _ => ParseObjectComma,
1893 fn parse_object_end(&mut self) -> JsonEvent {
1894 if self.ch_is('}') {
1895 self.state = if self.stack.is_empty() {
1897 } else if self.stack.last_is_index() {
1904 } else if self.eof() {
1905 self.error_event(EOFWhileParsingObject)
1907 self.error_event(InvalidSyntax)
1911 fn parse_value(&mut self) -> JsonEvent {
1912 if self.eof() { return self.error_event(EOFWhileParsingValue); }
1913 match self.ch_or_null() {
1914 'n' => { self.parse_ident("ull", NullValue) }
1915 't' => { self.parse_ident("rue", BooleanValue(true)) }
1916 'f' => { self.parse_ident("alse", BooleanValue(false)) }
1917 '0' ... '9' | '-' => self.parse_number(),
1918 '"' => match self.parse_str() {
1919 Ok(s) => StringValue(s),
1930 _ => { self.error_event(InvalidSyntax) }
1934 fn parse_ident(&mut self, ident: &str, value: JsonEvent) -> JsonEvent {
1935 if ident.chars().all(|c| Some(c) == self.next_char()) {
1939 Error(SyntaxError(InvalidSyntax, self.line, self.col))
1943 fn error_event(&mut self, reason: ErrorCode) -> JsonEvent {
1944 self.state = ParseFinished;
1945 Error(SyntaxError(reason, self.line, self.col))
1949 /// A Builder consumes a json::Parser to create a generic Json structure.
1950 pub struct Builder<T> {
1952 token: Option<JsonEvent>,
1955 impl<T: Iterator<Item=char>> Builder<T> {
1956 /// Create a JSON Builder.
1957 pub fn new(src: T) -> Builder<T> {
1958 Builder { parser: Parser::new(src), token: None, }
1961 // Decode a Json value from a Parser.
1962 pub fn build(&mut self) -> Result<Json, BuilderError> {
1964 let result = self.build_value();
1968 Some(Error(e)) => { return Err(e); }
1969 ref tok => { panic!("unexpected token {:?}", tok.clone()); }
1974 fn bump(&mut self) {
1975 self.token = self.parser.next();
1978 fn build_value(&mut self) -> Result<Json, BuilderError> {
1979 return match self.token {
1980 Some(NullValue) => Ok(Json::Null),
1981 Some(I64Value(n)) => Ok(Json::I64(n)),
1982 Some(U64Value(n)) => Ok(Json::U64(n)),
1983 Some(F64Value(n)) => Ok(Json::F64(n)),
1984 Some(BooleanValue(b)) => Ok(Json::Boolean(b)),
1985 Some(StringValue(ref mut s)) => {
1986 let mut temp = string::String::new();
1988 Ok(Json::String(temp))
1990 Some(Error(e)) => Err(e),
1991 Some(ArrayStart) => self.build_array(),
1992 Some(ObjectStart) => self.build_object(),
1993 Some(ObjectEnd) => self.parser.error(InvalidSyntax),
1994 Some(ArrayEnd) => self.parser.error(InvalidSyntax),
1995 None => self.parser.error(EOFWhileParsingValue),
1999 fn build_array(&mut self) -> Result<Json, BuilderError> {
2001 let mut values = Vec::new();
2004 if self.token == Some(ArrayEnd) {
2005 return Ok(Json::Array(values.into_iter().collect()));
2007 match self.build_value() {
2008 Ok(v) => values.push(v),
2009 Err(e) => { return Err(e) }
2015 fn build_object(&mut self) -> Result<Json, BuilderError> {
2018 let mut values = BTreeMap::new();
2022 Some(ObjectEnd) => { return Ok(Json::Object(values)); }
2023 Some(Error(e)) => { return Err(e); }
2027 let key = match self.parser.stack().top() {
2028 Some(StackElement::Key(k)) => { k.to_string() }
2029 _ => { panic!("invalid state"); }
2031 match self.build_value() {
2032 Ok(value) => { values.insert(key, value); }
2033 Err(e) => { return Err(e); }
2037 return self.parser.error(EOFWhileParsingObject);
2041 /// Decodes a json value from an `&mut io::Reader`
2042 pub fn from_reader(rdr: &mut io::Reader) -> Result<Json, BuilderError> {
2043 let contents = match rdr.read_to_end() {
2045 Err(e) => return Err(io_error_to_error(e))
2047 let s = match str::from_utf8(contents.as_slice()).ok() {
2049 _ => return Err(SyntaxError(NotUtf8, 0, 0))
2051 let mut builder = Builder::new(s.chars());
2055 /// Decodes a json value from a string
2056 pub fn from_str(s: &str) -> Result<Json, BuilderError> {
2057 let mut builder = Builder::new(s.chars());
2061 /// A structure to decode JSON to values in rust.
2062 pub struct Decoder {
2067 /// Creates a new decoder instance for decoding the specified JSON value.
2068 pub fn new(json: Json) -> Decoder {
2069 Decoder { stack: vec![json] }
2074 fn pop(&mut self) -> Json {
2075 self.stack.pop().unwrap()
2079 macro_rules! expect {
2080 ($e:expr, Null) => ({
2082 Json::Null => Ok(()),
2083 other => Err(ExpectedError("Null".to_string(),
2084 format!("{}", other)))
2087 ($e:expr, $t:ident) => ({
2089 Json::$t(v) => Ok(v),
2091 Err(ExpectedError(stringify!($t).to_string(),
2092 format!("{}", other)))
2098 macro_rules! read_primitive {
2099 ($name:ident, $ty:ty) => {
2100 fn $name(&mut self) -> DecodeResult<$ty> {
2102 Json::I64(f) => match num::cast(f) {
2104 None => Err(ExpectedError("Number".to_string(), format!("{}", f))),
2106 Json::U64(f) => match num::cast(f) {
2108 None => Err(ExpectedError("Number".to_string(), format!("{}", f))),
2110 Json::F64(f) => Err(ExpectedError("Integer".to_string(), format!("{}", f))),
2111 // re: #12967.. a type w/ numeric keys (ie HashMap<uint, V> etc)
2112 // is going to have a string here, as per JSON spec.
2113 Json::String(s) => match s.parse() {
2115 None => Err(ExpectedError("Number".to_string(), s)),
2117 value => Err(ExpectedError("Number".to_string(), format!("{}", value))),
2123 impl ::Decoder for Decoder {
2124 type Error = DecoderError;
2126 fn read_nil(&mut self) -> DecodeResult<()> {
2127 expect!(self.pop(), Null)
2130 read_primitive! { read_uint, uint }
2131 read_primitive! { read_u8, u8 }
2132 read_primitive! { read_u16, u16 }
2133 read_primitive! { read_u32, u32 }
2134 read_primitive! { read_u64, u64 }
2135 read_primitive! { read_int, int }
2136 read_primitive! { read_i8, i8 }
2137 read_primitive! { read_i16, i16 }
2138 read_primitive! { read_i32, i32 }
2139 read_primitive! { read_i64, i64 }
2141 fn read_f32(&mut self) -> DecodeResult<f32> { self.read_f64().map(|x| x as f32) }
2143 fn read_f64(&mut self) -> DecodeResult<f64> {
2145 Json::I64(f) => Ok(f as f64),
2146 Json::U64(f) => Ok(f as f64),
2147 Json::F64(f) => Ok(f),
2148 Json::String(s) => {
2149 // re: #12967.. a type w/ numeric keys (ie HashMap<uint, V> etc)
2150 // is going to have a string here, as per JSON spec.
2153 None => Err(ExpectedError("Number".to_string(), s)),
2156 Json::Null => Ok(f64::NAN),
2157 value => Err(ExpectedError("Number".to_string(), format!("{}", value)))
2161 fn read_bool(&mut self) -> DecodeResult<bool> {
2162 expect!(self.pop(), Boolean)
2165 fn read_char(&mut self) -> DecodeResult<char> {
2166 let s = try!(self.read_str());
2168 let mut it = s.chars();
2169 match (it.next(), it.next()) {
2170 // exactly one character
2171 (Some(c), None) => return Ok(c),
2175 Err(ExpectedError("single character string".to_string(), format!("{}", s)))
2178 fn read_str(&mut self) -> DecodeResult<string::String> {
2179 expect!(self.pop(), String)
2182 fn read_enum<T, F>(&mut self, _name: &str, f: F) -> DecodeResult<T> where
2183 F: FnOnce(&mut Decoder) -> DecodeResult<T>,
2188 fn read_enum_variant<T, F>(&mut self, names: &[&str],
2189 mut f: F) -> DecodeResult<T>
2190 where F: FnMut(&mut Decoder, uint) -> DecodeResult<T>,
2192 let name = match self.pop() {
2193 Json::String(s) => s,
2194 Json::Object(mut o) => {
2195 let n = match o.remove(&"variant".to_string()) {
2196 Some(Json::String(s)) => s,
2198 return Err(ExpectedError("String".to_string(), format!("{}", val)))
2201 return Err(MissingFieldError("variant".to_string()))
2204 match o.remove(&"fields".to_string()) {
2205 Some(Json::Array(l)) => {
2206 for field in l.into_iter().rev() {
2207 self.stack.push(field);
2211 return Err(ExpectedError("Array".to_string(), format!("{}", val)))
2214 return Err(MissingFieldError("fields".to_string()))
2220 return Err(ExpectedError("String or Object".to_string(), format!("{}", json)))
2223 let idx = match names.iter().position(|n| *n == &name[]) {
2225 None => return Err(UnknownVariantError(name))
2230 fn read_enum_variant_arg<T, F>(&mut self, _idx: uint, f: F) -> DecodeResult<T> where
2231 F: FnOnce(&mut Decoder) -> DecodeResult<T>,
2236 fn read_enum_struct_variant<T, F>(&mut self, names: &[&str], f: F) -> DecodeResult<T> where
2237 F: FnMut(&mut Decoder, uint) -> DecodeResult<T>,
2239 self.read_enum_variant(names, f)
2243 fn read_enum_struct_variant_field<T, F>(&mut self,
2247 -> DecodeResult<T> where
2248 F: FnOnce(&mut Decoder) -> DecodeResult<T>,
2250 self.read_enum_variant_arg(idx, f)
2253 fn read_struct<T, F>(&mut self, _name: &str, _len: uint, f: F) -> DecodeResult<T> where
2254 F: FnOnce(&mut Decoder) -> DecodeResult<T>,
2256 let value = try!(f(self));
2261 fn read_struct_field<T, F>(&mut self,
2265 -> DecodeResult<T> where
2266 F: FnOnce(&mut Decoder) -> DecodeResult<T>,
2268 let mut obj = try!(expect!(self.pop(), Object));
2270 let value = match obj.remove(&name.to_string()) {
2272 // Add a Null and try to parse it as an Option<_>
2273 // to get None as a default value.
2274 self.stack.push(Json::Null);
2277 Err(_) => return Err(MissingFieldError(name.to_string())),
2281 self.stack.push(json);
2285 self.stack.push(Json::Object(obj));
2289 fn read_tuple<T, F>(&mut self, tuple_len: uint, f: F) -> DecodeResult<T> where
2290 F: FnOnce(&mut Decoder) -> DecodeResult<T>,
2292 self.read_seq(move |d, len| {
2293 if len == tuple_len {
2296 Err(ExpectedError(format!("Tuple{}", tuple_len), format!("Tuple{}", len)))
2301 fn read_tuple_arg<T, F>(&mut self, idx: uint, f: F) -> DecodeResult<T> where
2302 F: FnOnce(&mut Decoder) -> DecodeResult<T>,
2304 self.read_seq_elt(idx, f)
2307 fn read_tuple_struct<T, F>(&mut self,
2311 -> DecodeResult<T> where
2312 F: FnOnce(&mut Decoder) -> DecodeResult<T>,
2314 self.read_tuple(len, f)
2317 fn read_tuple_struct_arg<T, F>(&mut self,
2320 -> DecodeResult<T> where
2321 F: FnOnce(&mut Decoder) -> DecodeResult<T>,
2323 self.read_tuple_arg(idx, f)
2326 fn read_option<T, F>(&mut self, mut f: F) -> DecodeResult<T> where
2327 F: FnMut(&mut Decoder, bool) -> DecodeResult<T>,
2330 Json::Null => f(self, false),
2331 value => { self.stack.push(value); f(self, true) }
2335 fn read_seq<T, F>(&mut self, f: F) -> DecodeResult<T> where
2336 F: FnOnce(&mut Decoder, uint) -> DecodeResult<T>,
2338 let array = try!(expect!(self.pop(), Array));
2339 let len = array.len();
2340 for v in array.into_iter().rev() {
2346 fn read_seq_elt<T, F>(&mut self, _idx: uint, f: F) -> DecodeResult<T> where
2347 F: FnOnce(&mut Decoder) -> DecodeResult<T>,
2352 fn read_map<T, F>(&mut self, f: F) -> DecodeResult<T> where
2353 F: FnOnce(&mut Decoder, uint) -> DecodeResult<T>,
2355 let obj = try!(expect!(self.pop(), Object));
2356 let len = obj.len();
2357 for (key, value) in obj.into_iter() {
2358 self.stack.push(value);
2359 self.stack.push(Json::String(key));
2364 fn read_map_elt_key<T, F>(&mut self, _idx: uint, f: F) -> DecodeResult<T> where
2365 F: FnOnce(&mut Decoder) -> DecodeResult<T>,
2370 fn read_map_elt_val<T, F>(&mut self, _idx: uint, f: F) -> DecodeResult<T> where
2371 F: FnOnce(&mut Decoder) -> DecodeResult<T>,
2376 fn error(&mut self, err: &str) -> DecoderError {
2377 ApplicationError(err.to_string())
2381 /// A trait for converting values to JSON
2383 /// Converts the value of `self` to an instance of JSON
2384 fn to_json(&self) -> Json;
2387 macro_rules! to_json_impl_i64 {
2389 $(impl ToJson for $t {
2390 fn to_json(&self) -> Json { Json::I64(*self as i64) }
2395 to_json_impl_i64! { int, i8, i16, i32, i64 }
2397 macro_rules! to_json_impl_u64 {
2399 $(impl ToJson for $t {
2400 fn to_json(&self) -> Json { Json::U64(*self as u64) }
2405 to_json_impl_u64! { uint, u8, u16, u32, u64 }
2407 impl ToJson for Json {
2408 fn to_json(&self) -> Json { self.clone() }
2411 impl ToJson for f32 {
2412 fn to_json(&self) -> Json { (*self as f64).to_json() }
2415 impl ToJson for f64 {
2416 fn to_json(&self) -> Json {
2417 match self.classify() {
2418 Fp::Nan | Fp::Infinite => Json::Null,
2419 _ => Json::F64(*self)
2424 impl ToJson for () {
2425 fn to_json(&self) -> Json { Json::Null }
2428 impl ToJson for bool {
2429 fn to_json(&self) -> Json { Json::Boolean(*self) }
2432 impl ToJson for str {
2433 fn to_json(&self) -> Json { Json::String(self.to_string()) }
2436 impl ToJson for string::String {
2437 fn to_json(&self) -> Json { Json::String((*self).clone()) }
2440 macro_rules! tuple_impl {
2441 // use variables to indicate the arity of the tuple
2442 ($($tyvar:ident),* ) => {
2443 // the trailing commas are for the 1 tuple
2445 $( $tyvar : ToJson ),*
2446 > ToJson for ( $( $tyvar ),* , ) {
2449 #[allow(non_snake_case)]
2450 fn to_json(&self) -> Json {
2452 ($(ref $tyvar),*,) => Json::Array(vec![$($tyvar.to_json()),*])
2461 tuple_impl!{A, B, C}
2462 tuple_impl!{A, B, C, D}
2463 tuple_impl!{A, B, C, D, E}
2464 tuple_impl!{A, B, C, D, E, F}
2465 tuple_impl!{A, B, C, D, E, F, G}
2466 tuple_impl!{A, B, C, D, E, F, G, H}
2467 tuple_impl!{A, B, C, D, E, F, G, H, I}
2468 tuple_impl!{A, B, C, D, E, F, G, H, I, J}
2469 tuple_impl!{A, B, C, D, E, F, G, H, I, J, K}
2470 tuple_impl!{A, B, C, D, E, F, G, H, I, J, K, L}
2472 impl<A: ToJson> ToJson for [A] {
2473 fn to_json(&self) -> Json { Json::Array(self.iter().map(|elt| elt.to_json()).collect()) }
2476 impl<A: ToJson> ToJson for Vec<A> {
2477 fn to_json(&self) -> Json { Json::Array(self.iter().map(|elt| elt.to_json()).collect()) }
2480 impl<A: ToJson> ToJson for BTreeMap<string::String, A> {
2481 fn to_json(&self) -> Json {
2482 let mut d = BTreeMap::new();
2483 for (key, value) in self.iter() {
2484 d.insert((*key).clone(), value.to_json());
2490 impl<A: ToJson> ToJson for HashMap<string::String, A> {
2491 fn to_json(&self) -> Json {
2492 let mut d = BTreeMap::new();
2493 for (key, value) in self.iter() {
2494 d.insert((*key).clone(), value.to_json());
2500 impl<A:ToJson> ToJson for Option<A> {
2501 fn to_json(&self) -> Json {
2504 Some(ref value) => value.to_json()
2509 struct FormatShim<'a, 'b: 'a> {
2510 inner: &'a mut fmt::Formatter<'b>,
2513 impl<'a, 'b> fmt::Writer for FormatShim<'a, 'b> {
2514 fn write_str(&mut self, s: &str) -> fmt::Result {
2515 self.inner.write_str(s)
2519 impl fmt::String for Json {
2520 /// Encodes a json value into a string
2521 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2522 let mut shim = FormatShim { inner: f };
2523 let mut encoder = Encoder::new(&mut shim);
2524 self.encode(&mut encoder)
2528 impl<'a> fmt::String for PrettyJson<'a> {
2529 /// Encodes a json value into a string
2530 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2531 let mut shim = FormatShim { inner: f };
2532 let mut encoder = PrettyEncoder::new(&mut shim);
2533 self.inner.encode(&mut encoder)
2537 impl<'a, T: Encodable> fmt::String for AsJson<'a, T> {
2538 /// Encodes a json value into a string
2539 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2540 let mut shim = FormatShim { inner: f };
2541 let mut encoder = Encoder::new(&mut shim);
2542 self.inner.encode(&mut encoder)
2546 impl<'a, T> AsPrettyJson<'a, T> {
2547 /// Set the indentation level for the emitted JSON
2548 pub fn indent(mut self, indent: uint) -> AsPrettyJson<'a, T> {
2549 self.indent = Some(indent);
2554 impl<'a, T: Encodable> fmt::String for AsPrettyJson<'a, T> {
2555 /// Encodes a json value into a string
2556 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2557 let mut shim = FormatShim { inner: f };
2558 let mut encoder = PrettyEncoder::new(&mut shim);
2560 Some(n) => encoder.set_indent(n),
2563 self.inner.encode(&mut encoder)
2567 impl FromStr for Json {
2568 fn from_str(s: &str) -> Option<Json> {
2576 use self::Animal::*;
2577 use self::DecodeEnum::*;
2578 use self::test::Bencher;
2579 use {Encodable, Decodable};
2581 use super::ErrorCode::*;
2582 use super::ParserError::*;
2583 use super::DecoderError::*;
2584 use super::JsonEvent::*;
2585 use super::{Json, from_str, DecodeResult, DecoderError, JsonEvent, Parser,
2586 StackElement, Stack, Decoder, Encoder, EncoderError};
2587 use std::{i64, u64, f32, f64, io};
2588 use std::collections::BTreeMap;
2589 use std::num::Float;
2592 #[derive(RustcDecodable, Eq, PartialEq, Show)]
2598 fn test_decode_option_none() {
2600 let obj: OptionData = super::decode(s).unwrap();
2601 assert_eq!(obj, OptionData { opt: None });
2605 fn test_decode_option_some() {
2606 let s = "{ \"opt\": 10 }";
2607 let obj: OptionData = super::decode(s).unwrap();
2608 assert_eq!(obj, OptionData { opt: Some(10u) });
2612 fn test_decode_option_malformed() {
2613 check_err::<OptionData>("{ \"opt\": [] }",
2614 ExpectedError("Number".to_string(), "[]".to_string()));
2615 check_err::<OptionData>("{ \"opt\": false }",
2616 ExpectedError("Number".to_string(), "false".to_string()));
2619 #[derive(PartialEq, RustcEncodable, RustcDecodable, Show)]
2622 Frog(string::String, int)
2625 #[derive(PartialEq, RustcEncodable, RustcDecodable, Show)]
2629 c: Vec<string::String>,
2632 #[derive(PartialEq, RustcEncodable, RustcDecodable, Show)]
2637 fn mk_object(items: &[(string::String, Json)]) -> Json {
2638 let mut d = BTreeMap::new();
2640 for item in items.iter() {
2642 (ref key, ref value) => { d.insert((*key).clone(), (*value).clone()); },
2650 fn test_from_str_trait() {
2652 assert!(s.parse::<Json>().unwrap() == s.parse().unwrap());
2656 fn test_write_null() {
2657 assert_eq!(Null.to_string(), "null");
2658 assert_eq!(Null.pretty().to_string(), "null");
2662 fn test_write_i64() {
2663 assert_eq!(U64(0).to_string(), "0");
2664 assert_eq!(U64(0).pretty().to_string(), "0");
2666 assert_eq!(U64(1234).to_string(), "1234");
2667 assert_eq!(U64(1234).pretty().to_string(), "1234");
2669 assert_eq!(I64(-5678).to_string(), "-5678");
2670 assert_eq!(I64(-5678).pretty().to_string(), "-5678");
2672 assert_eq!(U64(7650007200025252000).to_string(), "7650007200025252000");
2673 assert_eq!(U64(7650007200025252000).pretty().to_string(), "7650007200025252000");
2677 fn test_write_f64() {
2678 assert_eq!(F64(3.0).to_string(), "3.0");
2679 assert_eq!(F64(3.0).pretty().to_string(), "3.0");
2681 assert_eq!(F64(3.1).to_string(), "3.1");
2682 assert_eq!(F64(3.1).pretty().to_string(), "3.1");
2684 assert_eq!(F64(-1.5).to_string(), "-1.5");
2685 assert_eq!(F64(-1.5).pretty().to_string(), "-1.5");
2687 assert_eq!(F64(0.5).to_string(), "0.5");
2688 assert_eq!(F64(0.5).pretty().to_string(), "0.5");
2690 assert_eq!(F64(f64::NAN).to_string(), "null");
2691 assert_eq!(F64(f64::NAN).pretty().to_string(), "null");
2693 assert_eq!(F64(f64::INFINITY).to_string(), "null");
2694 assert_eq!(F64(f64::INFINITY).pretty().to_string(), "null");
2696 assert_eq!(F64(f64::NEG_INFINITY).to_string(), "null");
2697 assert_eq!(F64(f64::NEG_INFINITY).pretty().to_string(), "null");
2701 fn test_write_str() {
2702 assert_eq!(String("".to_string()).to_string(), "\"\"");
2703 assert_eq!(String("".to_string()).pretty().to_string(), "\"\"");
2705 assert_eq!(String("homura".to_string()).to_string(), "\"homura\"");
2706 assert_eq!(String("madoka".to_string()).pretty().to_string(), "\"madoka\"");
2710 fn test_write_bool() {
2711 assert_eq!(Boolean(true).to_string(), "true");
2712 assert_eq!(Boolean(true).pretty().to_string(), "true");
2714 assert_eq!(Boolean(false).to_string(), "false");
2715 assert_eq!(Boolean(false).pretty().to_string(), "false");
2719 fn test_write_array() {
2720 assert_eq!(Array(vec![]).to_string(), "[]");
2721 assert_eq!(Array(vec![]).pretty().to_string(), "[]");
2723 assert_eq!(Array(vec![Boolean(true)]).to_string(), "[true]");
2725 Array(vec![Boolean(true)]).pretty().to_string(),
2732 let long_test_array = Array(vec![
2735 Array(vec![String("foo\nbar".to_string()), F64(3.5)])]);
2737 assert_eq!(long_test_array.to_string(),
2738 "[false,null,[\"foo\\nbar\",3.5]]");
2740 long_test_array.pretty().to_string(),
2754 fn test_write_object() {
2755 assert_eq!(mk_object(&[]).to_string(), "{}");
2756 assert_eq!(mk_object(&[]).pretty().to_string(), "{}");
2760 ("a".to_string(), Boolean(true))
2765 mk_object(&[("a".to_string(), Boolean(true))]).pretty().to_string(),
2772 let complex_obj = mk_object(&[
2773 ("b".to_string(), Array(vec![
2774 mk_object(&[("c".to_string(), String("\x0c\r".to_string()))]),
2775 mk_object(&[("d".to_string(), String("".to_string()))])
2780 complex_obj.to_string(),
2783 {\"c\":\"\\f\\r\"},\
2789 complex_obj.pretty().to_string(),
2794 \"c\": \"\\f\\r\"\n \
2803 let a = mk_object(&[
2804 ("a".to_string(), Boolean(true)),
2805 ("b".to_string(), Array(vec![
2806 mk_object(&[("c".to_string(), String("\x0c\r".to_string()))]),
2807 mk_object(&[("d".to_string(), String("".to_string()))])
2811 // We can't compare the strings directly because the object fields be
2812 // printed in a different order.
2813 assert_eq!(a.clone(), a.to_string().parse().unwrap());
2814 assert_eq!(a.clone(), a.pretty().to_string().parse().unwrap());
2818 fn test_write_enum() {
2821 format!("{}", super::as_json(&animal)),
2825 format!("{}", super::as_pretty_json(&animal)),
2829 let animal = Frog("Henry".to_string(), 349);
2831 format!("{}", super::as_json(&animal)),
2832 "{\"variant\":\"Frog\",\"fields\":[\"Henry\",349]}"
2835 format!("{}", super::as_pretty_json(&animal)),
2837 \"variant\": \"Frog\",\n \
2846 macro_rules! check_encoder_for_simple {
2847 ($value:expr, $expected:expr) => ({
2848 let s = format!("{}", super::as_json(&$value));
2849 assert_eq!(s, $expected);
2851 let s = format!("{}", super::as_pretty_json(&$value));
2852 assert_eq!(s, $expected);
2857 fn test_write_some() {
2858 check_encoder_for_simple!(Some("jodhpurs".to_string()), "\"jodhpurs\"");
2862 fn test_write_none() {
2863 check_encoder_for_simple!(None::<string::String>, "null");
2867 fn test_write_char() {
2868 check_encoder_for_simple!('a', "\"a\"");
2869 check_encoder_for_simple!('\t', "\"\\t\"");
2870 check_encoder_for_simple!('\u{0000}', "\"\\u0000\"");
2871 check_encoder_for_simple!('\u{001b}', "\"\\u001b\"");
2872 check_encoder_for_simple!('\u{007f}', "\"\\u007f\"");
2873 check_encoder_for_simple!('\u{00a0}', "\"\u{00a0}\"");
2874 check_encoder_for_simple!('\u{abcd}', "\"\u{abcd}\"");
2875 check_encoder_for_simple!('\u{10ffff}', "\"\u{10ffff}\"");
2879 fn test_trailing_characters() {
2880 assert_eq!(from_str("nulla"), Err(SyntaxError(TrailingCharacters, 1, 5)));
2881 assert_eq!(from_str("truea"), Err(SyntaxError(TrailingCharacters, 1, 5)));
2882 assert_eq!(from_str("falsea"), Err(SyntaxError(TrailingCharacters, 1, 6)));
2883 assert_eq!(from_str("1a"), Err(SyntaxError(TrailingCharacters, 1, 2)));
2884 assert_eq!(from_str("[]a"), Err(SyntaxError(TrailingCharacters, 1, 3)));
2885 assert_eq!(from_str("{}a"), Err(SyntaxError(TrailingCharacters, 1, 3)));
2889 fn test_read_identifiers() {
2890 assert_eq!(from_str("n"), Err(SyntaxError(InvalidSyntax, 1, 2)));
2891 assert_eq!(from_str("nul"), Err(SyntaxError(InvalidSyntax, 1, 4)));
2892 assert_eq!(from_str("t"), Err(SyntaxError(InvalidSyntax, 1, 2)));
2893 assert_eq!(from_str("truz"), Err(SyntaxError(InvalidSyntax, 1, 4)));
2894 assert_eq!(from_str("f"), Err(SyntaxError(InvalidSyntax, 1, 2)));
2895 assert_eq!(from_str("faz"), Err(SyntaxError(InvalidSyntax, 1, 3)));
2897 assert_eq!(from_str("null"), Ok(Null));
2898 assert_eq!(from_str("true"), Ok(Boolean(true)));
2899 assert_eq!(from_str("false"), Ok(Boolean(false)));
2900 assert_eq!(from_str(" null "), Ok(Null));
2901 assert_eq!(from_str(" true "), Ok(Boolean(true)));
2902 assert_eq!(from_str(" false "), Ok(Boolean(false)));
2906 fn test_decode_identifiers() {
2907 let v: () = super::decode("null").unwrap();
2910 let v: bool = super::decode("true").unwrap();
2911 assert_eq!(v, true);
2913 let v: bool = super::decode("false").unwrap();
2914 assert_eq!(v, false);
2918 fn test_read_number() {
2919 assert_eq!(from_str("+"), Err(SyntaxError(InvalidSyntax, 1, 1)));
2920 assert_eq!(from_str("."), Err(SyntaxError(InvalidSyntax, 1, 1)));
2921 assert_eq!(from_str("NaN"), Err(SyntaxError(InvalidSyntax, 1, 1)));
2922 assert_eq!(from_str("-"), Err(SyntaxError(InvalidNumber, 1, 2)));
2923 assert_eq!(from_str("00"), Err(SyntaxError(InvalidNumber, 1, 2)));
2924 assert_eq!(from_str("1."), Err(SyntaxError(InvalidNumber, 1, 3)));
2925 assert_eq!(from_str("1e"), Err(SyntaxError(InvalidNumber, 1, 3)));
2926 assert_eq!(from_str("1e+"), Err(SyntaxError(InvalidNumber, 1, 4)));
2928 assert_eq!(from_str("18446744073709551616"), Err(SyntaxError(InvalidNumber, 1, 20)));
2929 assert_eq!(from_str("-9223372036854775809"), Err(SyntaxError(InvalidNumber, 1, 21)));
2931 assert_eq!(from_str("3"), Ok(U64(3)));
2932 assert_eq!(from_str("3.1"), Ok(F64(3.1)));
2933 assert_eq!(from_str("-1.2"), Ok(F64(-1.2)));
2934 assert_eq!(from_str("0.4"), Ok(F64(0.4)));
2935 assert_eq!(from_str("0.4e5"), Ok(F64(0.4e5)));
2936 assert_eq!(from_str("0.4e+15"), Ok(F64(0.4e15)));
2937 assert_eq!(from_str("0.4e-01"), Ok(F64(0.4e-01)));
2938 assert_eq!(from_str(" 3 "), Ok(U64(3)));
2940 assert_eq!(from_str("-9223372036854775808"), Ok(I64(i64::MIN)));
2941 assert_eq!(from_str("9223372036854775807"), Ok(U64(i64::MAX as u64)));
2942 assert_eq!(from_str("18446744073709551615"), Ok(U64(u64::MAX)));
2946 fn test_decode_numbers() {
2947 let v: f64 = super::decode("3").unwrap();
2950 let v: f64 = super::decode("3.1").unwrap();
2953 let v: f64 = super::decode("-1.2").unwrap();
2954 assert_eq!(v, -1.2);
2956 let v: f64 = super::decode("0.4").unwrap();
2959 let v: f64 = super::decode("0.4e5").unwrap();
2960 assert_eq!(v, 0.4e5);
2962 let v: f64 = super::decode("0.4e15").unwrap();
2963 assert_eq!(v, 0.4e15);
2965 let v: f64 = super::decode("0.4e-01").unwrap();
2966 assert_eq!(v, 0.4e-01);
2968 let v: u64 = super::decode("0").unwrap();
2971 let v: u64 = super::decode("18446744073709551615").unwrap();
2972 assert_eq!(v, u64::MAX);
2974 let v: i64 = super::decode("-9223372036854775808").unwrap();
2975 assert_eq!(v, i64::MIN);
2977 let v: i64 = super::decode("9223372036854775807").unwrap();
2978 assert_eq!(v, i64::MAX);
2980 let res: DecodeResult<i64> = super::decode("765.25252");
2981 assert_eq!(res, Err(ExpectedError("Integer".to_string(),
2982 "765.25252".to_string())));
2986 fn test_read_str() {
2987 assert_eq!(from_str("\""), Err(SyntaxError(EOFWhileParsingString, 1, 2)));
2988 assert_eq!(from_str("\"lol"), Err(SyntaxError(EOFWhileParsingString, 1, 5)));
2990 assert_eq!(from_str("\"\""), Ok(String("".to_string())));
2991 assert_eq!(from_str("\"foo\""), Ok(String("foo".to_string())));
2992 assert_eq!(from_str("\"\\\"\""), Ok(String("\"".to_string())));
2993 assert_eq!(from_str("\"\\b\""), Ok(String("\x08".to_string())));
2994 assert_eq!(from_str("\"\\n\""), Ok(String("\n".to_string())));
2995 assert_eq!(from_str("\"\\r\""), Ok(String("\r".to_string())));
2996 assert_eq!(from_str("\"\\t\""), Ok(String("\t".to_string())));
2997 assert_eq!(from_str(" \"foo\" "), Ok(String("foo".to_string())));
2998 assert_eq!(from_str("\"\\u12ab\""), Ok(String("\u{12ab}".to_string())));
2999 assert_eq!(from_str("\"\\uAB12\""), Ok(String("\u{AB12}".to_string())));
3003 fn test_decode_str() {
3004 let s = [("\"\"", ""),
3007 ("\"\\b\"", "\x08"),
3011 ("\"\\u12ab\"", "\u{12ab}"),
3012 ("\"\\uAB12\"", "\u{AB12}")];
3014 for &(i, o) in s.iter() {
3015 let v: string::String = super::decode(i).unwrap();
3021 fn test_read_array() {
3022 assert_eq!(from_str("["), Err(SyntaxError(EOFWhileParsingValue, 1, 2)));
3023 assert_eq!(from_str("[1"), Err(SyntaxError(EOFWhileParsingArray, 1, 3)));
3024 assert_eq!(from_str("[1,"), Err(SyntaxError(EOFWhileParsingValue, 1, 4)));
3025 assert_eq!(from_str("[1,]"), Err(SyntaxError(InvalidSyntax, 1, 4)));
3026 assert_eq!(from_str("[6 7]"), Err(SyntaxError(InvalidSyntax, 1, 4)));
3028 assert_eq!(from_str("[]"), Ok(Array(vec![])));
3029 assert_eq!(from_str("[ ]"), Ok(Array(vec![])));
3030 assert_eq!(from_str("[true]"), Ok(Array(vec![Boolean(true)])));
3031 assert_eq!(from_str("[ false ]"), Ok(Array(vec![Boolean(false)])));
3032 assert_eq!(from_str("[null]"), Ok(Array(vec![Null])));
3033 assert_eq!(from_str("[3, 1]"),
3034 Ok(Array(vec![U64(3), U64(1)])));
3035 assert_eq!(from_str("\n[3, 2]\n"),
3036 Ok(Array(vec![U64(3), U64(2)])));
3037 assert_eq!(from_str("[2, [4, 1]]"),
3038 Ok(Array(vec![U64(2), Array(vec![U64(4), U64(1)])])));
3042 fn test_decode_array() {
3043 let v: Vec<()> = super::decode("[]").unwrap();
3044 assert_eq!(v, vec![]);
3046 let v: Vec<()> = super::decode("[null]").unwrap();
3047 assert_eq!(v, vec![()]);
3049 let v: Vec<bool> = super::decode("[true]").unwrap();
3050 assert_eq!(v, vec![true]);
3052 let v: Vec<int> = super::decode("[3, 1]").unwrap();
3053 assert_eq!(v, vec![3, 1]);
3055 let v: Vec<Vec<uint>> = super::decode("[[3], [1, 2]]").unwrap();
3056 assert_eq!(v, vec![vec![3], vec![1, 2]]);
3060 fn test_decode_tuple() {
3061 let t: (uint, uint, uint) = super::decode("[1, 2, 3]").unwrap();
3062 assert_eq!(t, (1u, 2, 3));
3064 let t: (uint, string::String) = super::decode("[1, \"two\"]").unwrap();
3065 assert_eq!(t, (1u, "two".to_string()));
3069 fn test_decode_tuple_malformed_types() {
3070 assert!(super::decode::<(uint, string::String)>("[1, 2]").is_err());
3074 fn test_decode_tuple_malformed_length() {
3075 assert!(super::decode::<(uint, uint)>("[1, 2, 3]").is_err());
3079 fn test_read_object() {
3080 assert_eq!(from_str("{"), Err(SyntaxError(EOFWhileParsingObject, 1, 2)));
3081 assert_eq!(from_str("{ "), Err(SyntaxError(EOFWhileParsingObject, 1, 3)));
3082 assert_eq!(from_str("{1"), Err(SyntaxError(KeyMustBeAString, 1, 2)));
3083 assert_eq!(from_str("{ \"a\""), Err(SyntaxError(EOFWhileParsingObject, 1, 6)));
3084 assert_eq!(from_str("{\"a\""), Err(SyntaxError(EOFWhileParsingObject, 1, 5)));
3085 assert_eq!(from_str("{\"a\" "), Err(SyntaxError(EOFWhileParsingObject, 1, 6)));
3087 assert_eq!(from_str("{\"a\" 1"), Err(SyntaxError(ExpectedColon, 1, 6)));
3088 assert_eq!(from_str("{\"a\":"), Err(SyntaxError(EOFWhileParsingValue, 1, 6)));
3089 assert_eq!(from_str("{\"a\":1"), Err(SyntaxError(EOFWhileParsingObject, 1, 7)));
3090 assert_eq!(from_str("{\"a\":1 1"), Err(SyntaxError(InvalidSyntax, 1, 8)));
3091 assert_eq!(from_str("{\"a\":1,"), Err(SyntaxError(EOFWhileParsingObject, 1, 8)));
3093 assert_eq!(from_str("{}").unwrap(), mk_object(&[]));
3094 assert_eq!(from_str("{\"a\": 3}").unwrap(),
3095 mk_object(&[("a".to_string(), U64(3))]));
3097 assert_eq!(from_str(
3098 "{ \"a\": null, \"b\" : true }").unwrap(),
3100 ("a".to_string(), Null),
3101 ("b".to_string(), Boolean(true))]));
3102 assert_eq!(from_str("\n{ \"a\": null, \"b\" : true }\n").unwrap(),
3104 ("a".to_string(), Null),
3105 ("b".to_string(), Boolean(true))]));
3106 assert_eq!(from_str(
3107 "{\"a\" : 1.0 ,\"b\": [ true ]}").unwrap(),
3109 ("a".to_string(), F64(1.0)),
3110 ("b".to_string(), Array(vec![Boolean(true)]))
3112 assert_eq!(from_str(
3118 { \"c\": {\"d\": null} } \
3122 ("a".to_string(), F64(1.0)),
3123 ("b".to_string(), Array(vec![
3125 String("foo\nbar".to_string()),
3127 ("c".to_string(), mk_object(&[("d".to_string(), Null)]))
3134 fn test_decode_struct() {
3137 { \"a\": null, \"b\": 2, \"c\": [\"abc\", \"xyz\"] }
3141 let v: Outer = super::decode(s).unwrap();
3146 Inner { a: (), b: 2, c: vec!["abc".to_string(), "xyz".to_string()] }
3152 #[derive(RustcDecodable)]
3153 struct FloatStruct {
3158 fn test_decode_struct_with_nan() {
3159 let s = "{\"f\":null,\"a\":[null,123]}";
3160 let obj: FloatStruct = super::decode(s).unwrap();
3161 assert!(obj.f.is_nan());
3162 assert!(obj.a[0].is_nan());
3163 assert_eq!(obj.a[1], 123f64);
3167 fn test_decode_option() {
3168 let value: Option<string::String> = super::decode("null").unwrap();
3169 assert_eq!(value, None);
3171 let value: Option<string::String> = super::decode("\"jodhpurs\"").unwrap();
3172 assert_eq!(value, Some("jodhpurs".to_string()));
3176 fn test_decode_enum() {
3177 let value: Animal = super::decode("\"Dog\"").unwrap();
3178 assert_eq!(value, Dog);
3180 let s = "{\"variant\":\"Frog\",\"fields\":[\"Henry\",349]}";
3181 let value: Animal = super::decode(s).unwrap();
3182 assert_eq!(value, Frog("Henry".to_string(), 349));
3186 fn test_decode_map() {
3187 let s = "{\"a\": \"Dog\", \"b\": {\"variant\":\"Frog\",\
3188 \"fields\":[\"Henry\", 349]}}";
3189 let mut map: BTreeMap<string::String, Animal> = super::decode(s).unwrap();
3191 assert_eq!(map.remove(&"a".to_string()), Some(Dog));
3192 assert_eq!(map.remove(&"b".to_string()), Some(Frog("Henry".to_string(), 349)));
3196 fn test_multiline_errors() {
3197 assert_eq!(from_str("{\n \"foo\":\n \"bar\""),
3198 Err(SyntaxError(EOFWhileParsingObject, 3u, 8u)));
3201 #[derive(RustcDecodable)]
3203 struct DecodeStruct {
3207 w: Vec<DecodeStruct>
3209 #[derive(RustcDecodable)]
3214 fn check_err<T: Decodable>(to_parse: &'static str, expected: DecoderError) {
3215 let res: DecodeResult<T> = match from_str(to_parse) {
3216 Err(e) => Err(ParseError(e)),
3217 Ok(json) => Decodable::decode(&mut Decoder::new(json))
3220 Ok(_) => panic!("`{:?}` parsed & decoded ok, expecting error `{:?}`",
3221 to_parse, expected),
3222 Err(ParseError(e)) => panic!("`{:?}` is not valid json: {:?}",
3225 assert_eq!(e, expected);
3230 fn test_decode_errors_struct() {
3231 check_err::<DecodeStruct>("[]", ExpectedError("Object".to_string(), "[]".to_string()));
3232 check_err::<DecodeStruct>("{\"x\": true, \"y\": true, \"z\": \"\", \"w\": []}",
3233 ExpectedError("Number".to_string(), "true".to_string()));
3234 check_err::<DecodeStruct>("{\"x\": 1, \"y\": [], \"z\": \"\", \"w\": []}",
3235 ExpectedError("Boolean".to_string(), "[]".to_string()));
3236 check_err::<DecodeStruct>("{\"x\": 1, \"y\": true, \"z\": {}, \"w\": []}",
3237 ExpectedError("String".to_string(), "{}".to_string()));
3238 check_err::<DecodeStruct>("{\"x\": 1, \"y\": true, \"z\": \"\", \"w\": null}",
3239 ExpectedError("Array".to_string(), "null".to_string()));
3240 check_err::<DecodeStruct>("{\"x\": 1, \"y\": true, \"z\": \"\"}",
3241 MissingFieldError("w".to_string()));
3244 fn test_decode_errors_enum() {
3245 check_err::<DecodeEnum>("{}",
3246 MissingFieldError("variant".to_string()));
3247 check_err::<DecodeEnum>("{\"variant\": 1}",
3248 ExpectedError("String".to_string(), "1".to_string()));
3249 check_err::<DecodeEnum>("{\"variant\": \"A\"}",
3250 MissingFieldError("fields".to_string()));
3251 check_err::<DecodeEnum>("{\"variant\": \"A\", \"fields\": null}",
3252 ExpectedError("Array".to_string(), "null".to_string()));
3253 check_err::<DecodeEnum>("{\"variant\": \"C\", \"fields\": []}",
3254 UnknownVariantError("C".to_string()));
3259 let json_value = from_str("{\"dog\" : \"cat\"}").unwrap();
3260 let found_str = json_value.find("dog");
3261 assert!(found_str.unwrap().as_string().unwrap() == "cat");
3265 fn test_find_path(){
3266 let json_value = from_str("{\"dog\":{\"cat\": {\"mouse\" : \"cheese\"}}}").unwrap();
3267 let found_str = json_value.find_path(&["dog", "cat", "mouse"]);
3268 assert!(found_str.unwrap().as_string().unwrap() == "cheese");
3273 let json_value = from_str("{\"dog\":{\"cat\": {\"mouse\" : \"cheese\"}}}").unwrap();
3274 let found_str = json_value.search("mouse").and_then(|j| j.as_string());
3275 assert!(found_str.unwrap() == "cheese");
3280 let json_value = from_str("{\"animals\":[\"dog\",\"cat\",\"mouse\"]}").unwrap();
3281 let ref array = json_value["animals"];
3282 assert_eq!(array[0].as_string().unwrap(), "dog");
3283 assert_eq!(array[1].as_string().unwrap(), "cat");
3284 assert_eq!(array[2].as_string().unwrap(), "mouse");
3288 fn test_is_object(){
3289 let json_value = from_str("{}").unwrap();
3290 assert!(json_value.is_object());
3294 fn test_as_object(){
3295 let json_value = from_str("{}").unwrap();
3296 let json_object = json_value.as_object();
3297 assert!(json_object.is_some());
3302 let json_value = from_str("[1, 2, 3]").unwrap();
3303 assert!(json_value.is_array());
3308 let json_value = from_str("[1, 2, 3]").unwrap();
3309 let json_array = json_value.as_array();
3310 let expected_length = 3;
3311 assert!(json_array.is_some() && json_array.unwrap().len() == expected_length);
3315 fn test_is_string(){
3316 let json_value = from_str("\"dog\"").unwrap();
3317 assert!(json_value.is_string());
3321 fn test_as_string(){
3322 let json_value = from_str("\"dog\"").unwrap();
3323 let json_str = json_value.as_string();
3324 let expected_str = "dog";
3325 assert_eq!(json_str, Some(expected_str));
3329 fn test_is_number(){
3330 let json_value = from_str("12").unwrap();
3331 assert!(json_value.is_number());
3336 let json_value = from_str("-12").unwrap();
3337 assert!(json_value.is_i64());
3339 let json_value = from_str("12").unwrap();
3340 assert!(!json_value.is_i64());
3342 let json_value = from_str("12.0").unwrap();
3343 assert!(!json_value.is_i64());
3348 let json_value = from_str("12").unwrap();
3349 assert!(json_value.is_u64());
3351 let json_value = from_str("-12").unwrap();
3352 assert!(!json_value.is_u64());
3354 let json_value = from_str("12.0").unwrap();
3355 assert!(!json_value.is_u64());
3360 let json_value = from_str("12").unwrap();
3361 assert!(!json_value.is_f64());
3363 let json_value = from_str("-12").unwrap();
3364 assert!(!json_value.is_f64());
3366 let json_value = from_str("12.0").unwrap();
3367 assert!(json_value.is_f64());
3369 let json_value = from_str("-12.0").unwrap();
3370 assert!(json_value.is_f64());
3375 let json_value = from_str("-12").unwrap();
3376 let json_num = json_value.as_i64();
3377 assert_eq!(json_num, Some(-12));
3382 let json_value = from_str("12").unwrap();
3383 let json_num = json_value.as_u64();
3384 assert_eq!(json_num, Some(12));
3389 let json_value = from_str("12.0").unwrap();
3390 let json_num = json_value.as_f64();
3391 assert_eq!(json_num, Some(12f64));
3395 fn test_is_boolean(){
3396 let json_value = from_str("false").unwrap();
3397 assert!(json_value.is_boolean());
3401 fn test_as_boolean(){
3402 let json_value = from_str("false").unwrap();
3403 let json_bool = json_value.as_boolean();
3404 let expected_bool = false;
3405 assert!(json_bool.is_some() && json_bool.unwrap() == expected_bool);
3410 let json_value = from_str("null").unwrap();
3411 assert!(json_value.is_null());
3416 let json_value = from_str("null").unwrap();
3417 let json_null = json_value.as_null();
3418 let expected_null = ();
3419 assert!(json_null.is_some() && json_null.unwrap() == expected_null);
3423 fn test_encode_hashmap_with_numeric_key() {
3424 use std::str::from_utf8;
3425 use std::io::Writer;
3426 use std::collections::HashMap;
3427 let mut hm: HashMap<uint, bool> = HashMap::new();
3429 let mut mem_buf = Vec::new();
3430 write!(&mut mem_buf, "{}", super::as_pretty_json(&hm)).unwrap();
3431 let json_str = from_utf8(&mem_buf[]).unwrap();
3432 match from_str(json_str) {
3433 Err(_) => panic!("Unable to parse json_str: {:?}", json_str),
3434 _ => {} // it parsed and we are good to go
3439 fn test_prettyencode_hashmap_with_numeric_key() {
3440 use std::str::from_utf8;
3441 use std::io::Writer;
3442 use std::collections::HashMap;
3443 let mut hm: HashMap<uint, bool> = HashMap::new();
3445 let mut mem_buf = Vec::new();
3446 write!(&mut mem_buf, "{}", super::as_pretty_json(&hm)).unwrap();
3447 let json_str = from_utf8(&mem_buf[]).unwrap();
3448 match from_str(json_str) {
3449 Err(_) => panic!("Unable to parse json_str: {:?}", json_str),
3450 _ => {} // it parsed and we are good to go
3455 fn test_prettyencoder_indent_level_param() {
3456 use std::str::from_utf8;
3457 use std::collections::BTreeMap;
3459 let mut tree = BTreeMap::new();
3461 tree.insert("hello".to_string(), String("guten tag".to_string()));
3462 tree.insert("goodbye".to_string(), String("sayonara".to_string()));
3465 // The following layout below should look a lot like
3466 // the pretty-printed JSON (indent * x)
3469 String("greetings".to_string()), // 1x
3470 Object(tree), // 1x + 2x + 2x + 1x
3472 // End JSON array (7 lines)
3475 // Helper function for counting indents
3476 fn indents(source: &str) -> uint {
3477 let trimmed = source.trim_left_matches(' ');
3478 source.len() - trimmed.len()
3481 // Test up to 4 spaces of indents (more?)
3482 for i in range(0, 4u) {
3483 let mut writer = Vec::new();
3484 write!(&mut writer, "{}",
3485 super::as_pretty_json(&json).indent(i)).unwrap();
3487 let printed = from_utf8(&writer[]).unwrap();
3489 // Check for indents at each line
3490 let lines: Vec<&str> = printed.lines().collect();
3491 assert_eq!(lines.len(), 7); // JSON should be 7 lines
3493 assert_eq!(indents(lines[0]), 0 * i); // [
3494 assert_eq!(indents(lines[1]), 1 * i); // "greetings",
3495 assert_eq!(indents(lines[2]), 1 * i); // {
3496 assert_eq!(indents(lines[3]), 2 * i); // "hello": "guten tag",
3497 assert_eq!(indents(lines[4]), 2 * i); // "goodbye": "sayonara"
3498 assert_eq!(indents(lines[5]), 1 * i); // },
3499 assert_eq!(indents(lines[6]), 0 * i); // ]
3501 // Finally, test that the pretty-printed JSON is valid
3502 from_str(printed).ok().expect("Pretty-printed JSON is invalid!");
3507 fn test_hashmap_with_numeric_key_can_handle_double_quote_delimited_key() {
3508 use std::collections::HashMap;
3510 let json_str = "{\"1\":true}";
3511 let json_obj = match from_str(json_str) {
3512 Err(_) => panic!("Unable to parse json_str: {:?}", json_str),
3515 let mut decoder = Decoder::new(json_obj);
3516 let _hm: HashMap<uint, bool> = Decodable::decode(&mut decoder).unwrap();
3520 fn test_hashmap_with_numeric_key_will_error_with_string_keys() {
3521 use std::collections::HashMap;
3523 let json_str = "{\"a\":true}";
3524 let json_obj = match from_str(json_str) {
3525 Err(_) => panic!("Unable to parse json_str: {:?}", json_str),
3528 let mut decoder = Decoder::new(json_obj);
3529 let result: Result<HashMap<uint, bool>, DecoderError> = Decodable::decode(&mut decoder);
3530 assert_eq!(result, Err(ExpectedError("Number".to_string(), "a".to_string())));
3533 fn assert_stream_equal(src: &str,
3534 expected: Vec<(JsonEvent, Vec<StackElement>)>) {
3535 let mut parser = Parser::new(src.chars());
3538 let evt = match parser.next() {
3542 let (ref expected_evt, ref expected_stack) = expected[i];
3543 if !parser.stack().is_equal_to(expected_stack.as_slice()) {
3544 panic!("Parser stack is not equal to {:?}", expected_stack);
3546 assert_eq!(&evt, expected_evt);
3551 #[cfg_attr(target_pointer_width = "32", ignore)] // FIXME(#14064)
3552 fn test_streaming_parser() {
3553 assert_stream_equal(
3554 r#"{ "foo":"bar", "array" : [0, 1, 2, 3, 4, 5], "idents":[null,true,false]}"#,
3556 (ObjectStart, vec![]),
3557 (StringValue("bar".to_string()), vec![StackElement::Key("foo")]),
3558 (ArrayStart, vec![StackElement::Key("array")]),
3559 (U64Value(0), vec![StackElement::Key("array"), StackElement::Index(0)]),
3560 (U64Value(1), vec![StackElement::Key("array"), StackElement::Index(1)]),
3561 (U64Value(2), vec![StackElement::Key("array"), StackElement::Index(2)]),
3562 (U64Value(3), vec![StackElement::Key("array"), StackElement::Index(3)]),
3563 (U64Value(4), vec![StackElement::Key("array"), StackElement::Index(4)]),
3564 (U64Value(5), vec![StackElement::Key("array"), StackElement::Index(5)]),
3565 (ArrayEnd, vec![StackElement::Key("array")]),
3566 (ArrayStart, vec![StackElement::Key("idents")]),
3567 (NullValue, vec![StackElement::Key("idents"),
3568 StackElement::Index(0)]),
3569 (BooleanValue(true), vec![StackElement::Key("idents"),
3570 StackElement::Index(1)]),
3571 (BooleanValue(false), vec![StackElement::Key("idents"),
3572 StackElement::Index(2)]),
3573 (ArrayEnd, vec![StackElement::Key("idents")]),
3574 (ObjectEnd, vec![]),
3578 fn last_event(src: &str) -> JsonEvent {
3579 let mut parser = Parser::new(src.chars());
3580 let mut evt = NullValue;
3582 evt = match parser.next() {
3590 #[cfg_attr(target_pointer_width = "32", ignore)] // FIXME(#14064)
3591 fn test_read_object_streaming() {
3592 assert_eq!(last_event("{ "), Error(SyntaxError(EOFWhileParsingObject, 1, 3)));
3593 assert_eq!(last_event("{1"), Error(SyntaxError(KeyMustBeAString, 1, 2)));
3594 assert_eq!(last_event("{ \"a\""), Error(SyntaxError(EOFWhileParsingObject, 1, 6)));
3595 assert_eq!(last_event("{\"a\""), Error(SyntaxError(EOFWhileParsingObject, 1, 5)));
3596 assert_eq!(last_event("{\"a\" "), Error(SyntaxError(EOFWhileParsingObject, 1, 6)));
3598 assert_eq!(last_event("{\"a\" 1"), Error(SyntaxError(ExpectedColon, 1, 6)));
3599 assert_eq!(last_event("{\"a\":"), Error(SyntaxError(EOFWhileParsingValue, 1, 6)));
3600 assert_eq!(last_event("{\"a\":1"), Error(SyntaxError(EOFWhileParsingObject, 1, 7)));
3601 assert_eq!(last_event("{\"a\":1 1"), Error(SyntaxError(InvalidSyntax, 1, 8)));
3602 assert_eq!(last_event("{\"a\":1,"), Error(SyntaxError(EOFWhileParsingObject, 1, 8)));
3603 assert_eq!(last_event("{\"a\":1,}"), Error(SyntaxError(TrailingComma, 1, 8)));
3605 assert_stream_equal(
3607 vec![(ObjectStart, vec![]), (ObjectEnd, vec![])]
3609 assert_stream_equal(
3612 (ObjectStart, vec![]),
3613 (U64Value(3), vec![StackElement::Key("a")]),
3614 (ObjectEnd, vec![]),
3617 assert_stream_equal(
3618 "{ \"a\": null, \"b\" : true }",
3620 (ObjectStart, vec![]),
3621 (NullValue, vec![StackElement::Key("a")]),
3622 (BooleanValue(true), vec![StackElement::Key("b")]),
3623 (ObjectEnd, vec![]),
3626 assert_stream_equal(
3627 "{\"a\" : 1.0 ,\"b\": [ true ]}",
3629 (ObjectStart, vec![]),
3630 (F64Value(1.0), vec![StackElement::Key("a")]),
3631 (ArrayStart, vec![StackElement::Key("b")]),
3632 (BooleanValue(true),vec![StackElement::Key("b"), StackElement::Index(0)]),
3633 (ArrayEnd, vec![StackElement::Key("b")]),
3634 (ObjectEnd, vec![]),
3637 assert_stream_equal(
3643 { "c": {"d": null} }
3647 (ObjectStart, vec![]),
3648 (F64Value(1.0), vec![StackElement::Key("a")]),
3649 (ArrayStart, vec![StackElement::Key("b")]),
3650 (BooleanValue(true), vec![StackElement::Key("b"),
3651 StackElement::Index(0)]),
3652 (StringValue("foo\nbar".to_string()), vec![StackElement::Key("b"),
3653 StackElement::Index(1)]),
3654 (ObjectStart, vec![StackElement::Key("b"),
3655 StackElement::Index(2)]),
3656 (ObjectStart, vec![StackElement::Key("b"),
3657 StackElement::Index(2),
3658 StackElement::Key("c")]),
3659 (NullValue, vec![StackElement::Key("b"),
3660 StackElement::Index(2),
3661 StackElement::Key("c"),
3662 StackElement::Key("d")]),
3663 (ObjectEnd, vec![StackElement::Key("b"),
3664 StackElement::Index(2),
3665 StackElement::Key("c")]),
3666 (ObjectEnd, vec![StackElement::Key("b"),
3667 StackElement::Index(2)]),
3668 (ArrayEnd, vec![StackElement::Key("b")]),
3669 (ObjectEnd, vec![]),
3674 #[cfg_attr(target_pointer_width = "32", ignore)] // FIXME(#14064)
3675 fn test_read_array_streaming() {
3676 assert_stream_equal(
3679 (ArrayStart, vec![]),
3683 assert_stream_equal(
3686 (ArrayStart, vec![]),
3690 assert_stream_equal(
3693 (ArrayStart, vec![]),
3694 (BooleanValue(true), vec![StackElement::Index(0)]),
3698 assert_stream_equal(
3701 (ArrayStart, vec![]),
3702 (BooleanValue(false), vec![StackElement::Index(0)]),
3706 assert_stream_equal(
3709 (ArrayStart, vec![]),
3710 (NullValue, vec![StackElement::Index(0)]),
3714 assert_stream_equal(
3717 (ArrayStart, vec![]),
3718 (U64Value(3), vec![StackElement::Index(0)]),
3719 (U64Value(1), vec![StackElement::Index(1)]),
3723 assert_stream_equal(
3726 (ArrayStart, vec![]),
3727 (U64Value(3), vec![StackElement::Index(0)]),
3728 (U64Value(2), vec![StackElement::Index(1)]),
3732 assert_stream_equal(
3735 (ArrayStart, vec![]),
3736 (U64Value(2), vec![StackElement::Index(0)]),
3737 (ArrayStart, vec![StackElement::Index(1)]),
3738 (U64Value(4), vec![StackElement::Index(1), StackElement::Index(0)]),
3739 (U64Value(1), vec![StackElement::Index(1), StackElement::Index(1)]),
3740 (ArrayEnd, vec![StackElement::Index(1)]),
3745 assert_eq!(last_event("["), Error(SyntaxError(EOFWhileParsingValue, 1, 2)));
3747 assert_eq!(from_str("["), Err(SyntaxError(EOFWhileParsingValue, 1, 2)));
3748 assert_eq!(from_str("[1"), Err(SyntaxError(EOFWhileParsingArray, 1, 3)));
3749 assert_eq!(from_str("[1,"), Err(SyntaxError(EOFWhileParsingValue, 1, 4)));
3750 assert_eq!(from_str("[1,]"), Err(SyntaxError(InvalidSyntax, 1, 4)));
3751 assert_eq!(from_str("[6 7]"), Err(SyntaxError(InvalidSyntax, 1, 4)));
3755 fn test_trailing_characters_streaming() {
3756 assert_eq!(last_event("nulla"), Error(SyntaxError(TrailingCharacters, 1, 5)));
3757 assert_eq!(last_event("truea"), Error(SyntaxError(TrailingCharacters, 1, 5)));
3758 assert_eq!(last_event("falsea"), Error(SyntaxError(TrailingCharacters, 1, 6)));
3759 assert_eq!(last_event("1a"), Error(SyntaxError(TrailingCharacters, 1, 2)));
3760 assert_eq!(last_event("[]a"), Error(SyntaxError(TrailingCharacters, 1, 3)));
3761 assert_eq!(last_event("{}a"), Error(SyntaxError(TrailingCharacters, 1, 3)));
3764 fn test_read_identifiers_streaming() {
3765 assert_eq!(Parser::new("null".chars()).next(), Some(NullValue));
3766 assert_eq!(Parser::new("true".chars()).next(), Some(BooleanValue(true)));
3767 assert_eq!(Parser::new("false".chars()).next(), Some(BooleanValue(false)));
3769 assert_eq!(last_event("n"), Error(SyntaxError(InvalidSyntax, 1, 2)));
3770 assert_eq!(last_event("nul"), Error(SyntaxError(InvalidSyntax, 1, 4)));
3771 assert_eq!(last_event("t"), Error(SyntaxError(InvalidSyntax, 1, 2)));
3772 assert_eq!(last_event("truz"), Error(SyntaxError(InvalidSyntax, 1, 4)));
3773 assert_eq!(last_event("f"), Error(SyntaxError(InvalidSyntax, 1, 2)));
3774 assert_eq!(last_event("faz"), Error(SyntaxError(InvalidSyntax, 1, 3)));
3779 let mut stack = Stack::new();
3781 assert!(stack.is_empty());
3782 assert!(stack.len() == 0);
3783 assert!(!stack.last_is_index());
3785 stack.push_index(0);
3788 assert!(stack.len() == 1);
3789 assert!(stack.is_equal_to(&[StackElement::Index(1)]));
3790 assert!(stack.starts_with(&[StackElement::Index(1)]));
3791 assert!(stack.ends_with(&[StackElement::Index(1)]));
3792 assert!(stack.last_is_index());
3793 assert!(stack.get(0) == StackElement::Index(1));
3795 stack.push_key("foo".to_string());
3797 assert!(stack.len() == 2);
3798 assert!(stack.is_equal_to(&[StackElement::Index(1), StackElement::Key("foo")]));
3799 assert!(stack.starts_with(&[StackElement::Index(1), StackElement::Key("foo")]));
3800 assert!(stack.starts_with(&[StackElement::Index(1)]));
3801 assert!(stack.ends_with(&[StackElement::Index(1), StackElement::Key("foo")]));
3802 assert!(stack.ends_with(&[StackElement::Key("foo")]));
3803 assert!(!stack.last_is_index());
3804 assert!(stack.get(0) == StackElement::Index(1));
3805 assert!(stack.get(1) == StackElement::Key("foo"));
3807 stack.push_key("bar".to_string());
3809 assert!(stack.len() == 3);
3810 assert!(stack.is_equal_to(&[StackElement::Index(1),
3811 StackElement::Key("foo"),
3812 StackElement::Key("bar")]));
3813 assert!(stack.starts_with(&[StackElement::Index(1)]));
3814 assert!(stack.starts_with(&[StackElement::Index(1), StackElement::Key("foo")]));
3815 assert!(stack.starts_with(&[StackElement::Index(1),
3816 StackElement::Key("foo"),
3817 StackElement::Key("bar")]));
3818 assert!(stack.ends_with(&[StackElement::Key("bar")]));
3819 assert!(stack.ends_with(&[StackElement::Key("foo"), StackElement::Key("bar")]));
3820 assert!(stack.ends_with(&[StackElement::Index(1),
3821 StackElement::Key("foo"),
3822 StackElement::Key("bar")]));
3823 assert!(!stack.last_is_index());
3824 assert!(stack.get(0) == StackElement::Index(1));
3825 assert!(stack.get(1) == StackElement::Key("foo"));
3826 assert!(stack.get(2) == StackElement::Key("bar"));
3830 assert!(stack.len() == 2);
3831 assert!(stack.is_equal_to(&[StackElement::Index(1), StackElement::Key("foo")]));
3832 assert!(stack.starts_with(&[StackElement::Index(1), StackElement::Key("foo")]));
3833 assert!(stack.starts_with(&[StackElement::Index(1)]));
3834 assert!(stack.ends_with(&[StackElement::Index(1), StackElement::Key("foo")]));
3835 assert!(stack.ends_with(&[StackElement::Key("foo")]));
3836 assert!(!stack.last_is_index());
3837 assert!(stack.get(0) == StackElement::Index(1));
3838 assert!(stack.get(1) == StackElement::Key("foo"));
3843 use std::collections::{HashMap,BTreeMap};
3846 let array2 = Array(vec!(U64(1), U64(2)));
3847 let array3 = Array(vec!(U64(1), U64(2), U64(3)));
3849 let mut tree_map = BTreeMap::new();
3850 tree_map.insert("a".to_string(), U64(1));
3851 tree_map.insert("b".to_string(), U64(2));
3855 assert_eq!(array2.to_json(), array2);
3856 assert_eq!(object.to_json(), object);
3857 assert_eq!(3_i.to_json(), I64(3));
3858 assert_eq!(4_i8.to_json(), I64(4));
3859 assert_eq!(5_i16.to_json(), I64(5));
3860 assert_eq!(6_i32.to_json(), I64(6));
3861 assert_eq!(7_i64.to_json(), I64(7));
3862 assert_eq!(8_u.to_json(), U64(8));
3863 assert_eq!(9_u8.to_json(), U64(9));
3864 assert_eq!(10_u16.to_json(), U64(10));
3865 assert_eq!(11_u32.to_json(), U64(11));
3866 assert_eq!(12_u64.to_json(), U64(12));
3867 assert_eq!(13.0_f32.to_json(), F64(13.0_f64));
3868 assert_eq!(14.0_f64.to_json(), F64(14.0_f64));
3869 assert_eq!(().to_json(), Null);
3870 assert_eq!(f32::INFINITY.to_json(), Null);
3871 assert_eq!(f64::NAN.to_json(), Null);
3872 assert_eq!(true.to_json(), Boolean(true));
3873 assert_eq!(false.to_json(), Boolean(false));
3874 assert_eq!("abc".to_json(), String("abc".to_string()));
3875 assert_eq!("abc".to_string().to_json(), String("abc".to_string()));
3876 assert_eq!((1u, 2u).to_json(), array2);
3877 assert_eq!((1u, 2u, 3u).to_json(), array3);
3878 assert_eq!([1u, 2].to_json(), array2);
3879 assert_eq!((&[1u, 2, 3]).to_json(), array3);
3880 assert_eq!((vec![1u, 2]).to_json(), array2);
3881 assert_eq!(vec!(1u, 2, 3).to_json(), array3);
3882 let mut tree_map = BTreeMap::new();
3883 tree_map.insert("a".to_string(), 1u);
3884 tree_map.insert("b".to_string(), 2);
3885 assert_eq!(tree_map.to_json(), object);
3886 let mut hash_map = HashMap::new();
3887 hash_map.insert("a".to_string(), 1u);
3888 hash_map.insert("b".to_string(), 2);
3889 assert_eq!(hash_map.to_json(), object);
3890 assert_eq!(Some(15i).to_json(), I64(15));
3891 assert_eq!(Some(15u).to_json(), U64(15));
3892 assert_eq!(None::<int>.to_json(), Null);
3896 fn test_encode_hashmap_with_arbitrary_key() {
3897 use std::str::from_utf8;
3898 use std::io::Writer;
3899 use std::collections::HashMap;
3901 #[derive(PartialEq, Eq, Hash, RustcEncodable)]
3902 struct ArbitraryType(uint);
3903 let mut hm: HashMap<ArbitraryType, bool> = HashMap::new();
3904 hm.insert(ArbitraryType(1), true);
3905 let mut mem_buf = Vec::new();
3906 let mut encoder = Encoder::new(&mut mem_buf as &mut fmt::Writer);
3907 let result = hm.encode(&mut encoder);
3908 match result.unwrap_err() {
3909 EncoderError::BadHashmapKey => (),
3910 _ => panic!("expected bad hash map key")
3915 fn bench_streaming_small(b: &mut Bencher) {
3917 let mut parser = Parser::new(
3923 { "c": {"d": null} }
3928 match parser.next() {
3936 fn bench_small(b: &mut Bencher) {
3938 let _ = from_str(r#"{
3943 { "c": {"d": null} }
3949 fn big_json() -> string::String {
3950 let mut src = "[\n".to_string();
3951 for _ in range(0i, 500) {
3952 src.push_str(r#"{ "a": true, "b": null, "c":3.1415, "d": "Hello world", "e": \
3955 src.push_str("{}]");
3960 fn bench_streaming_large(b: &mut Bencher) {
3961 let src = big_json();
3963 let mut parser = Parser::new(src.chars());
3965 match parser.next() {
3973 fn bench_large(b: &mut Bencher) {
3974 let src = big_json();
3975 b.iter( || { let _ = from_str(src.as_slice()); });