1 // Rust JSON serialization library
2 // Copyright (c) 2011 Google Inc.
4 #![forbid(non_camel_case_types)]
5 #![allow(missing_docs)]
7 //! JSON parsing and serialization
11 //! JSON (JavaScript Object Notation) is a way to write data in Javascript.
12 //! Like XML, it allows to encode structured data in a text format that can be easily read by humans
13 //! Its simple syntax and native compatibility with JavaScript have made it a widely used format.
15 //! Data types that can be encoded are JavaScript types (see the `Json` enum for more details):
17 //! * `Boolean`: equivalent to rust's `bool`
18 //! * `Number`: equivalent to rust's `f64`
19 //! * `String`: equivalent to rust's `String`
20 //! * `Array`: equivalent to rust's `Vec<T>`, but also allowing objects of different types in the
22 //! * `Object`: equivalent to rust's `BTreeMap<String, json::Json>`
25 //! An object is a series of string keys mapping to values, in `"key": value` format.
26 //! Arrays are enclosed in square brackets ([ ... ]) and objects in curly brackets ({ ... }).
27 //! A simple JSON document encoding a person, their age, address and phone numbers could look like
31 //! "FirstName": "John",
32 //! "LastName": "Doe",
35 //! "Street": "Downing Street 10",
37 //! "Country": "Great Britain"
46 //! # Rust Type-based Encoding and Decoding
48 //! Rust provides a mechanism for low boilerplate encoding & decoding of values to and from JSON via
49 //! the serialization API.
50 //! To be able to encode a piece of data, it must implement the `serialize::RustcEncodable` trait.
51 //! To be able to decode a piece of data, it must implement the `serialize::RustcDecodable` trait.
52 //! The Rust compiler provides an annotation to automatically generate the code for these traits:
53 //! `#[derive(RustcDecodable, RustcEncodable)]`
55 //! The JSON API provides an enum `json::Json` and a trait `ToJson` to encode objects.
56 //! The `ToJson` trait provides a `to_json` method to convert an object into a `json::Json` value.
57 //! A `json::Json` value can be encoded as a string or buffer using the functions described above.
58 //! You can also use the `json::Encoder` object, which implements the `Encoder` trait.
60 //! When using `ToJson` the `RustcEncodable` trait implementation is not mandatory.
64 //! ## Using Autoserialization
66 //! Create a struct called `TestStruct` and serialize and deserialize it to and from JSON using the
67 //! serialization API, using the derived serialization code.
70 //! # #![feature(rustc_private)]
71 //! extern crate serialize as rustc_serialize; // for the deriving below
72 //! use rustc_serialize::json;
74 //! // Automatically generate `Decodable` and `Encodable` trait implementations
75 //! #[derive(RustcDecodable, RustcEncodable)]
76 //! pub struct TestStruct {
79 //! data_vector: Vec<u8>,
83 //! let object = TestStruct {
85 //! data_str: "homura".to_string(),
86 //! data_vector: vec![2,3,4,5],
89 //! // Serialize using `json::encode`
90 //! let encoded = json::encode(&object).unwrap();
92 //! // Deserialize using `json::decode`
93 //! let decoded: TestStruct = json::decode(&encoded[..]).unwrap();
97 //! ## Using the `ToJson` trait
99 //! The examples above use the `ToJson` trait to generate the JSON string, which is required
100 //! for custom mappings.
102 //! ### Simple example of `ToJson` usage
105 //! # #![feature(rustc_private)]
106 //! extern crate serialize;
107 //! use serialize::json::{self, ToJson, Json};
109 //! // A custom data structure
110 //! struct ComplexNum {
115 //! // JSON value representation
116 //! impl ToJson for ComplexNum {
117 //! fn to_json(&self) -> Json {
118 //! Json::String(format!("{}+{}i", self.a, self.b))
122 //! // Only generate `RustcEncodable` trait implementation
123 //! #[derive(Encodable)]
124 //! pub struct ComplexNumRecord {
131 //! let num = ComplexNum { a: 0.0001, b: 12.539 };
132 //! let data: String = json::encode(&ComplexNumRecord{
134 //! dsc: "test".to_string(),
135 //! val: num.to_json(),
137 //! println!("data: {}", data);
138 //! // data: {"uid":1,"dsc":"test","val":"0.0001+12.539i"};
142 //! ### Verbose example of `ToJson` usage
145 //! # #![feature(rustc_private)]
146 //! extern crate serialize;
147 //! use std::collections::BTreeMap;
148 //! use serialize::json::{self, Json, ToJson};
150 //! // Only generate `Decodable` trait implementation
151 //! #[derive(Decodable)]
152 //! pub struct TestStruct {
154 //! data_str: String,
155 //! data_vector: Vec<u8>,
158 //! // Specify encoding method manually
159 //! impl ToJson for TestStruct {
160 //! fn to_json(&self) -> Json {
161 //! let mut d = BTreeMap::new();
162 //! // All standard types implement `to_json()`, so use it
163 //! d.insert("data_int".to_string(), self.data_int.to_json());
164 //! d.insert("data_str".to_string(), self.data_str.to_json());
165 //! d.insert("data_vector".to_string(), self.data_vector.to_json());
171 //! // Serialize using `ToJson`
172 //! let input_data = TestStruct {
174 //! data_str: "madoka".to_string(),
175 //! data_vector: vec![2,3,4,5],
177 //! let json_obj: Json = input_data.to_json();
178 //! let json_str: String = json_obj.to_string();
180 //! // Deserialize like before
181 //! let decoded: TestStruct = json::decode(&json_str).unwrap();
185 use self::JsonEvent::*;
186 use self::ErrorCode::*;
187 use self::ParserError::*;
188 use self::DecoderError::*;
189 use self::ParserState::*;
190 use self::InternalStackElement::*;
192 use std::borrow::Cow;
193 use std::collections::{HashMap, BTreeMap};
194 use std::io::prelude::*;
197 use std::num::FpCategory as Fp;
199 use std::str::FromStr;
201 use std::{char, f64, fmt, str};
206 /// Represents a json value
207 #[derive(Clone, PartialEq, PartialOrd, Debug)]
212 String(string::String),
215 Object(self::Object),
219 pub type Array = Vec<Json>;
220 pub type Object = BTreeMap<string::String, Json>;
222 pub struct PrettyJson<'a> { inner: &'a Json }
224 pub struct AsJson<'a, T: 'a> { inner: &'a T }
225 pub struct AsPrettyJson<'a, T: 'a> { inner: &'a T, indent: Option<usize> }
227 /// The errors that can arise while parsing a JSON stream.
228 #[derive(Clone, Copy, PartialEq, Debug)]
232 EOFWhileParsingObject,
233 EOFWhileParsingArray,
234 EOFWhileParsingValue,
235 EOFWhileParsingString,
241 InvalidUnicodeCodePoint,
242 LoneLeadingSurrogateInHexEscape,
243 UnexpectedEndOfHexEscape,
249 #[derive(Clone, PartialEq, Debug)]
250 pub enum ParserError {
252 SyntaxError(ErrorCode, usize, usize),
253 IoError(io::ErrorKind, String),
256 // Builder and Parser have the same errors.
257 pub type BuilderError = ParserError;
259 #[derive(Clone, PartialEq, Debug)]
260 pub enum DecoderError {
261 ParseError(ParserError),
262 ExpectedError(string::String, string::String),
263 MissingFieldError(string::String),
264 UnknownVariantError(string::String),
265 ApplicationError(string::String)
268 #[derive(Copy, Clone, Debug)]
269 pub enum EncoderError {
270 FmtError(fmt::Error),
274 /// Returns a readable error string for a given error code.
275 pub fn error_str(error: ErrorCode) -> &'static str {
277 InvalidSyntax => "invalid syntax",
278 InvalidNumber => "invalid number",
279 EOFWhileParsingObject => "EOF While parsing object",
280 EOFWhileParsingArray => "EOF While parsing array",
281 EOFWhileParsingValue => "EOF While parsing value",
282 EOFWhileParsingString => "EOF While parsing string",
283 KeyMustBeAString => "key must be a string",
284 ExpectedColon => "expected `:`",
285 TrailingCharacters => "trailing characters",
286 TrailingComma => "trailing comma",
287 InvalidEscape => "invalid escape",
288 UnrecognizedHex => "invalid \\u{ esc}ape (unrecognized hex)",
289 NotFourDigit => "invalid \\u{ esc}ape (not four digits)",
290 NotUtf8 => "contents not utf-8",
291 InvalidUnicodeCodePoint => "invalid Unicode code point",
292 LoneLeadingSurrogateInHexEscape => "lone leading surrogate in hex escape",
293 UnexpectedEndOfHexEscape => "unexpected end of hex escape",
297 /// Shortcut function to decode a JSON `&str` into an object
298 pub fn decode<T: ::Decodable>(s: &str) -> DecodeResult<T> {
299 let json = match from_str(s) {
301 Err(e) => return Err(ParseError(e))
304 let mut decoder = Decoder::new(json);
305 ::Decodable::decode(&mut decoder)
308 /// Shortcut function to encode a `T` into a JSON `String`
309 pub fn encode<T: ::Encodable>(object: &T) -> Result<string::String, EncoderError> {
310 let mut s = String::new();
312 let mut encoder = Encoder::new(&mut s);
313 object.encode(&mut encoder)?;
318 impl fmt::Display for ErrorCode {
319 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
320 error_str(*self).fmt(f)
324 fn io_error_to_error(io: io::Error) -> ParserError {
325 IoError(io.kind(), io.to_string())
328 impl fmt::Display for ParserError {
329 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
330 // FIXME this should be a nicer error
331 fmt::Debug::fmt(self, f)
335 impl fmt::Display for DecoderError {
336 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
337 // FIXME this should be a nicer error
338 fmt::Debug::fmt(self, f)
342 impl std::error::Error for DecoderError {
343 fn description(&self) -> &str { "decoder error" }
346 impl fmt::Display for EncoderError {
347 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
348 // FIXME this should be a nicer error
349 fmt::Debug::fmt(self, f)
353 impl std::error::Error for EncoderError {
354 fn description(&self) -> &str { "encoder error" }
357 impl From<fmt::Error> for EncoderError {
358 /// Converts a [`fmt::Error`] into `EncoderError`
360 /// This conversion does not allocate memory.
361 fn from(err: fmt::Error) -> EncoderError { EncoderError::FmtError(err) }
364 pub type EncodeResult = Result<(), EncoderError>;
365 pub type DecodeResult<T> = Result<T, DecoderError>;
367 fn escape_str(wr: &mut dyn fmt::Write, v: &str) -> EncodeResult {
372 for (i, byte) in v.bytes().enumerate() {
373 let escaped = match byte {
376 b'\x00' => "\\u0000",
377 b'\x01' => "\\u0001",
378 b'\x02' => "\\u0002",
379 b'\x03' => "\\u0003",
380 b'\x04' => "\\u0004",
381 b'\x05' => "\\u0005",
382 b'\x06' => "\\u0006",
383 b'\x07' => "\\u0007",
387 b'\x0b' => "\\u000b",
390 b'\x0e' => "\\u000e",
391 b'\x0f' => "\\u000f",
392 b'\x10' => "\\u0010",
393 b'\x11' => "\\u0011",
394 b'\x12' => "\\u0012",
395 b'\x13' => "\\u0013",
396 b'\x14' => "\\u0014",
397 b'\x15' => "\\u0015",
398 b'\x16' => "\\u0016",
399 b'\x17' => "\\u0017",
400 b'\x18' => "\\u0018",
401 b'\x19' => "\\u0019",
402 b'\x1a' => "\\u001a",
403 b'\x1b' => "\\u001b",
404 b'\x1c' => "\\u001c",
405 b'\x1d' => "\\u001d",
406 b'\x1e' => "\\u001e",
407 b'\x1f' => "\\u001f",
408 b'\x7f' => "\\u007f",
413 wr.write_str(&v[start..i])?;
416 wr.write_str(escaped)?;
421 if start != v.len() {
422 wr.write_str(&v[start..])?;
429 fn escape_char(writer: &mut dyn fmt::Write, v: char) -> EncodeResult {
430 escape_str(writer, v.encode_utf8(&mut [0; 4]))
433 fn spaces(wr: &mut dyn fmt::Write, mut n: usize) -> EncodeResult {
434 const BUF: &str = " ";
436 while n >= BUF.len() {
442 wr.write_str(&BUF[..n])?;
447 fn fmt_number_or_null(v: f64) -> string::String {
449 Fp::Nan | Fp::Infinite => string::String::from("null"),
450 _ if v.fract() != 0f64 => v.to_string(),
451 _ => v.to_string() + ".0",
455 /// A structure for implementing serialization to JSON.
456 pub struct Encoder<'a> {
457 writer: &'a mut (dyn fmt::Write+'a),
458 is_emitting_map_key: bool,
461 impl<'a> Encoder<'a> {
462 /// Creates a new JSON encoder whose output will be written to the writer
464 pub fn new(writer: &'a mut dyn fmt::Write) -> Encoder<'a> {
465 Encoder { writer: writer, is_emitting_map_key: false, }
469 macro_rules! emit_enquoted_if_mapkey {
470 ($enc:ident,$e:expr) => ({
471 if $enc.is_emitting_map_key {
472 write!($enc.writer, "\"{}\"", $e)?;
474 write!($enc.writer, "{}", $e)?;
480 impl<'a> ::Encoder for Encoder<'a> {
481 type Error = EncoderError;
483 fn emit_unit(&mut self) -> EncodeResult {
484 if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
485 write!(self.writer, "null")?;
489 fn emit_usize(&mut self, v: usize) -> EncodeResult { emit_enquoted_if_mapkey!(self, v) }
490 fn emit_u128(&mut self, v: u128) -> EncodeResult { emit_enquoted_if_mapkey!(self, v) }
491 fn emit_u64(&mut self, v: u64) -> EncodeResult { emit_enquoted_if_mapkey!(self, v) }
492 fn emit_u32(&mut self, v: u32) -> EncodeResult { emit_enquoted_if_mapkey!(self, v) }
493 fn emit_u16(&mut self, v: u16) -> EncodeResult { emit_enquoted_if_mapkey!(self, v) }
494 fn emit_u8(&mut self, v: u8) -> EncodeResult { emit_enquoted_if_mapkey!(self, v) }
496 fn emit_isize(&mut self, v: isize) -> EncodeResult { emit_enquoted_if_mapkey!(self, v) }
497 fn emit_i128(&mut self, v: i128) -> EncodeResult { emit_enquoted_if_mapkey!(self, v) }
498 fn emit_i64(&mut self, v: i64) -> EncodeResult { emit_enquoted_if_mapkey!(self, v) }
499 fn emit_i32(&mut self, v: i32) -> EncodeResult { emit_enquoted_if_mapkey!(self, v) }
500 fn emit_i16(&mut self, v: i16) -> EncodeResult { emit_enquoted_if_mapkey!(self, v) }
501 fn emit_i8(&mut self, v: i8) -> EncodeResult { emit_enquoted_if_mapkey!(self, v) }
503 fn emit_bool(&mut self, v: bool) -> EncodeResult {
504 if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
506 write!(self.writer, "true")?;
508 write!(self.writer, "false")?;
513 fn emit_f64(&mut self, v: f64) -> EncodeResult {
514 emit_enquoted_if_mapkey!(self, fmt_number_or_null(v))
516 fn emit_f32(&mut self, v: f32) -> EncodeResult {
517 self.emit_f64(v as f64)
520 fn emit_char(&mut self, v: char) -> EncodeResult {
521 escape_char(self.writer, v)
523 fn emit_str(&mut self, v: &str) -> EncodeResult {
524 escape_str(self.writer, v)
527 fn emit_enum<F>(&mut self, _name: &str, f: F) -> EncodeResult where
528 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
533 fn emit_enum_variant<F>(&mut self,
537 f: F) -> EncodeResult where
538 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
540 // enums are encoded as strings or objects
542 // Kangaroo(34,"William") => {"variant": "Kangaroo", "fields": [34,"William"]}
544 escape_str(self.writer, name)
546 if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
547 write!(self.writer, "{{\"variant\":")?;
548 escape_str(self.writer, name)?;
549 write!(self.writer, ",\"fields\":[")?;
551 write!(self.writer, "]}}")?;
556 fn emit_enum_variant_arg<F>(&mut self, idx: usize, f: F) -> EncodeResult where
557 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
559 if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
561 write!(self.writer, ",")?;
566 fn emit_enum_struct_variant<F>(&mut self,
570 f: F) -> EncodeResult where
571 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
573 if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
574 self.emit_enum_variant(name, id, cnt, f)
577 fn emit_enum_struct_variant_field<F>(&mut self,
580 f: F) -> EncodeResult where
581 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
583 if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
584 self.emit_enum_variant_arg(idx, f)
587 fn emit_struct<F>(&mut self, _: &str, _: usize, f: F) -> EncodeResult where
588 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
590 if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
591 write!(self.writer, "{{")?;
593 write!(self.writer, "}}")?;
597 fn emit_struct_field<F>(&mut self, name: &str, idx: usize, f: F) -> EncodeResult where
598 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
600 if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
601 if idx != 0 { write!(self.writer, ",")?; }
602 escape_str(self.writer, name)?;
603 write!(self.writer, ":")?;
607 fn emit_tuple<F>(&mut self, len: usize, f: F) -> EncodeResult where
608 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
610 if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
611 self.emit_seq(len, f)
613 fn emit_tuple_arg<F>(&mut self, idx: usize, f: F) -> EncodeResult where
614 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
616 if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
617 self.emit_seq_elt(idx, f)
620 fn emit_tuple_struct<F>(&mut self, _name: &str, len: usize, f: F) -> EncodeResult where
621 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
623 if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
624 self.emit_seq(len, f)
626 fn emit_tuple_struct_arg<F>(&mut self, idx: usize, f: F) -> EncodeResult where
627 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
629 if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
630 self.emit_seq_elt(idx, f)
633 fn emit_option<F>(&mut self, f: F) -> EncodeResult where
634 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
636 if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
639 fn emit_option_none(&mut self) -> EncodeResult {
640 if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
643 fn emit_option_some<F>(&mut self, f: F) -> EncodeResult where
644 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
646 if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
650 fn emit_seq<F>(&mut self, _len: usize, f: F) -> EncodeResult where
651 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
653 if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
654 write!(self.writer, "[")?;
656 write!(self.writer, "]")?;
660 fn emit_seq_elt<F>(&mut self, idx: usize, f: F) -> EncodeResult where
661 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
663 if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
665 write!(self.writer, ",")?;
670 fn emit_map<F>(&mut self, _len: usize, f: F) -> EncodeResult where
671 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
673 if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
674 write!(self.writer, "{{")?;
676 write!(self.writer, "}}")?;
680 fn emit_map_elt_key<F>(&mut self, idx: usize, f: F) -> EncodeResult where
681 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
683 if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
684 if idx != 0 { write!(self.writer, ",")? }
685 self.is_emitting_map_key = true;
687 self.is_emitting_map_key = false;
691 fn emit_map_elt_val<F>(&mut self, _idx: usize, f: F) -> EncodeResult where
692 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
694 if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
695 write!(self.writer, ":")?;
700 /// Another encoder for JSON, but prints out human-readable JSON instead of
702 pub struct PrettyEncoder<'a> {
703 writer: &'a mut (dyn fmt::Write+'a),
706 is_emitting_map_key: bool,
709 impl<'a> PrettyEncoder<'a> {
710 /// Creates a new encoder whose output will be written to the specified writer
711 pub fn new(writer: &'a mut dyn fmt::Write) -> PrettyEncoder<'a> {
716 is_emitting_map_key: false,
720 /// Set the number of spaces to indent for each level.
721 /// This is safe to set during encoding.
722 pub fn set_indent(&mut self, indent: usize) {
723 // self.indent very well could be 0 so we need to use checked division.
724 let level = self.curr_indent.checked_div(self.indent).unwrap_or(0);
725 self.indent = indent;
726 self.curr_indent = level * self.indent;
730 impl<'a> ::Encoder for PrettyEncoder<'a> {
731 type Error = EncoderError;
733 fn emit_unit(&mut self) -> EncodeResult {
734 if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
735 write!(self.writer, "null")?;
739 fn emit_usize(&mut self, v: usize) -> EncodeResult { emit_enquoted_if_mapkey!(self, v) }
740 fn emit_u128(&mut self, v: u128) -> EncodeResult { emit_enquoted_if_mapkey!(self, v) }
741 fn emit_u64(&mut self, v: u64) -> EncodeResult { emit_enquoted_if_mapkey!(self, v) }
742 fn emit_u32(&mut self, v: u32) -> EncodeResult { emit_enquoted_if_mapkey!(self, v) }
743 fn emit_u16(&mut self, v: u16) -> EncodeResult { emit_enquoted_if_mapkey!(self, v) }
744 fn emit_u8(&mut self, v: u8) -> EncodeResult { emit_enquoted_if_mapkey!(self, v) }
746 fn emit_isize(&mut self, v: isize) -> EncodeResult { emit_enquoted_if_mapkey!(self, v) }
747 fn emit_i128(&mut self, v: i128) -> EncodeResult { emit_enquoted_if_mapkey!(self, v) }
748 fn emit_i64(&mut self, v: i64) -> EncodeResult { emit_enquoted_if_mapkey!(self, v) }
749 fn emit_i32(&mut self, v: i32) -> EncodeResult { emit_enquoted_if_mapkey!(self, v) }
750 fn emit_i16(&mut self, v: i16) -> EncodeResult { emit_enquoted_if_mapkey!(self, v) }
751 fn emit_i8(&mut self, v: i8) -> EncodeResult { emit_enquoted_if_mapkey!(self, v) }
753 fn emit_bool(&mut self, v: bool) -> EncodeResult {
754 if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
756 write!(self.writer, "true")?;
758 write!(self.writer, "false")?;
763 fn emit_f64(&mut self, v: f64) -> EncodeResult {
764 emit_enquoted_if_mapkey!(self, fmt_number_or_null(v))
766 fn emit_f32(&mut self, v: f32) -> EncodeResult {
767 self.emit_f64(v as f64)
770 fn emit_char(&mut self, v: char) -> EncodeResult {
771 escape_char(self.writer, v)
773 fn emit_str(&mut self, v: &str) -> EncodeResult {
774 escape_str(self.writer, v)
777 fn emit_enum<F>(&mut self, _name: &str, f: F) -> EncodeResult where
778 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
783 fn emit_enum_variant<F>(&mut self,
788 -> EncodeResult where
789 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
792 escape_str(self.writer, name)
794 if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
795 writeln!(self.writer, "{{")?;
796 self.curr_indent += self.indent;
797 spaces(self.writer, self.curr_indent)?;
798 write!(self.writer, "\"variant\": ")?;
799 escape_str(self.writer, name)?;
800 writeln!(self.writer, ",")?;
801 spaces(self.writer, self.curr_indent)?;
802 writeln!(self.writer, "\"fields\": [")?;
803 self.curr_indent += self.indent;
805 self.curr_indent -= self.indent;
806 writeln!(self.writer)?;
807 spaces(self.writer, self.curr_indent)?;
808 self.curr_indent -= self.indent;
809 writeln!(self.writer, "]")?;
810 spaces(self.writer, self.curr_indent)?;
811 write!(self.writer, "}}")?;
816 fn emit_enum_variant_arg<F>(&mut self, idx: usize, f: F) -> EncodeResult where
817 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
819 if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
821 writeln!(self.writer, ",")?;
823 spaces(self.writer, self.curr_indent)?;
827 fn emit_enum_struct_variant<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(name, id, cnt, f)
838 fn emit_enum_struct_variant_field<F>(&mut self,
841 f: F) -> EncodeResult where
842 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
844 if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
845 self.emit_enum_variant_arg(idx, f)
849 fn emit_struct<F>(&mut self, _: &str, len: usize, f: F) -> EncodeResult where
850 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
852 if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
854 write!(self.writer, "{{}}")?;
856 write!(self.writer, "{{")?;
857 self.curr_indent += self.indent;
859 self.curr_indent -= self.indent;
860 writeln!(self.writer)?;
861 spaces(self.writer, self.curr_indent)?;
862 write!(self.writer, "}}")?;
867 fn emit_struct_field<F>(&mut self, name: &str, idx: usize, f: F) -> EncodeResult where
868 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
870 if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
872 writeln!(self.writer)?;
874 writeln!(self.writer, ",")?;
876 spaces(self.writer, self.curr_indent)?;
877 escape_str(self.writer, name)?;
878 write!(self.writer, ": ")?;
882 fn emit_tuple<F>(&mut self, len: usize, f: F) -> EncodeResult where
883 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
885 if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
886 self.emit_seq(len, f)
888 fn emit_tuple_arg<F>(&mut self, idx: usize, f: F) -> EncodeResult where
889 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
891 if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
892 self.emit_seq_elt(idx, f)
895 fn emit_tuple_struct<F>(&mut self, _: &str, len: usize, f: F) -> EncodeResult where
896 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
898 if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
899 self.emit_seq(len, f)
901 fn emit_tuple_struct_arg<F>(&mut self, idx: usize, f: F) -> EncodeResult where
902 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
904 if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
905 self.emit_seq_elt(idx, f)
908 fn emit_option<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); }
914 fn emit_option_none(&mut self) -> EncodeResult {
915 if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
918 fn emit_option_some<F>(&mut self, f: F) -> EncodeResult where
919 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
921 if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
925 fn emit_seq<F>(&mut self, len: usize, f: F) -> EncodeResult where
926 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
928 if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
930 write!(self.writer, "[]")?;
932 write!(self.writer, "[")?;
933 self.curr_indent += self.indent;
935 self.curr_indent -= self.indent;
936 writeln!(self.writer)?;
937 spaces(self.writer, self.curr_indent)?;
938 write!(self.writer, "]")?;
943 fn emit_seq_elt<F>(&mut self, idx: usize, f: F) -> EncodeResult where
944 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
946 if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
948 writeln!(self.writer)?;
950 writeln!(self.writer, ",")?;
952 spaces(self.writer, self.curr_indent)?;
956 fn emit_map<F>(&mut self, len: usize, f: F) -> EncodeResult where
957 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
959 if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
961 write!(self.writer, "{{}}")?;
963 write!(self.writer, "{{")?;
964 self.curr_indent += self.indent;
966 self.curr_indent -= self.indent;
967 writeln!(self.writer)?;
968 spaces(self.writer, self.curr_indent)?;
969 write!(self.writer, "}}")?;
974 fn emit_map_elt_key<F>(&mut self, idx: usize, f: F) -> EncodeResult where
975 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
977 if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
979 writeln!(self.writer)?;
981 writeln!(self.writer, ",")?;
983 spaces(self.writer, self.curr_indent)?;
984 self.is_emitting_map_key = true;
986 self.is_emitting_map_key = false;
990 fn emit_map_elt_val<F>(&mut self, _idx: usize, f: F) -> EncodeResult where
991 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
993 if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
994 write!(self.writer, ": ")?;
999 impl Encodable for Json {
1000 fn encode<E: ::Encoder>(&self, e: &mut E) -> Result<(), E::Error> {
1002 Json::I64(v) => v.encode(e),
1003 Json::U64(v) => v.encode(e),
1004 Json::F64(v) => v.encode(e),
1005 Json::String(ref v) => v.encode(e),
1006 Json::Boolean(v) => v.encode(e),
1007 Json::Array(ref v) => v.encode(e),
1008 Json::Object(ref v) => v.encode(e),
1009 Json::Null => e.emit_unit(),
1014 /// Create an `AsJson` wrapper which can be used to print a value as JSON
1015 /// on-the-fly via `write!`
1016 pub fn as_json<T>(t: &T) -> AsJson<T> {
1020 /// Create an `AsPrettyJson` wrapper which can be used to print a value as JSON
1021 /// on-the-fly via `write!`
1022 pub fn as_pretty_json<T>(t: &T) -> AsPrettyJson<T> {
1023 AsPrettyJson { inner: t, indent: None }
1027 /// Borrow this json object as a pretty object to generate a pretty
1028 /// representation for it via `Display`.
1029 pub fn pretty(&self) -> PrettyJson {
1030 PrettyJson { inner: self }
1033 /// If the Json value is an Object, returns the value associated with the provided key.
1034 /// Otherwise, returns None.
1035 pub fn find<'a>(&'a self, key: &str) -> Option<&'a Json>{
1037 Json::Object(ref map) => map.get(key),
1042 /// Attempts to get a nested Json Object for each key in `keys`.
1043 /// If any key is found not to exist, find_path will return None.
1044 /// Otherwise, it will return the Json value associated with the final key.
1045 pub fn find_path<'a>(&'a self, keys: &[&str]) -> Option<&'a Json>{
1046 let mut target = self;
1048 target = target.find(*key)?;
1053 /// If the Json value is an Object, performs a depth-first search until
1054 /// a value associated with the provided key is found. If no value is found
1055 /// or the Json value is not an Object, returns None.
1056 pub fn search<'a>(&'a self, key: &str) -> Option<&'a Json> {
1058 &Json::Object(ref map) => {
1059 match map.get(key) {
1060 Some(json_value) => Some(json_value),
1063 match v.search(key) {
1064 x if x.is_some() => return x,
1076 /// Returns true if the Json value is an Object. Returns false otherwise.
1077 pub fn is_object(&self) -> bool {
1078 self.as_object().is_some()
1081 /// If the Json value is an Object, returns the associated BTreeMap.
1082 /// Returns None otherwise.
1083 pub fn as_object(&self) -> Option<&Object> {
1085 Json::Object(ref map) => Some(map),
1090 /// Returns true if the Json value is an Array. Returns false otherwise.
1091 pub fn is_array(&self) -> bool {
1092 self.as_array().is_some()
1095 /// If the Json value is an Array, returns the associated vector.
1096 /// Returns None otherwise.
1097 pub fn as_array(&self) -> Option<&Array> {
1099 Json::Array(ref array) => Some(&*array),
1104 /// Returns true if the Json value is a String. Returns false otherwise.
1105 pub fn is_string(&self) -> bool {
1106 self.as_string().is_some()
1109 /// If the Json value is a String, returns the associated str.
1110 /// Returns None otherwise.
1111 pub fn as_string(&self) -> Option<&str> {
1113 Json::String(ref s) => Some(&s[..]),
1118 /// Returns true if the Json value is a Number. Returns false otherwise.
1119 pub fn is_number(&self) -> bool {
1121 Json::I64(_) | Json::U64(_) | Json::F64(_) => true,
1126 /// Returns true if the Json value is a i64. Returns false otherwise.
1127 pub fn is_i64(&self) -> bool {
1129 Json::I64(_) => true,
1134 /// Returns true if the Json value is a u64. Returns false otherwise.
1135 pub fn is_u64(&self) -> bool {
1137 Json::U64(_) => true,
1142 /// Returns true if the Json value is a f64. Returns false otherwise.
1143 pub fn is_f64(&self) -> bool {
1145 Json::F64(_) => true,
1150 /// If the Json value is a number, return or cast it to a i64.
1151 /// Returns None otherwise.
1152 pub fn as_i64(&self) -> Option<i64> {
1154 Json::I64(n) => Some(n),
1155 Json::U64(n) => Some(n as i64),
1160 /// If the Json value is a number, return or cast it to a u64.
1161 /// Returns None otherwise.
1162 pub fn as_u64(&self) -> Option<u64> {
1164 Json::I64(n) => Some(n as u64),
1165 Json::U64(n) => Some(n),
1170 /// If the Json value is a number, return or cast it to a f64.
1171 /// Returns None otherwise.
1172 pub fn as_f64(&self) -> Option<f64> {
1174 Json::I64(n) => Some(n as f64),
1175 Json::U64(n) => Some(n as f64),
1176 Json::F64(n) => Some(n),
1181 /// Returns true if the Json value is a Boolean. Returns false otherwise.
1182 pub fn is_boolean(&self) -> bool {
1183 self.as_boolean().is_some()
1186 /// If the Json value is a Boolean, returns the associated bool.
1187 /// Returns None otherwise.
1188 pub fn as_boolean(&self) -> Option<bool> {
1190 Json::Boolean(b) => Some(b),
1195 /// Returns true if the Json value is a Null. Returns false otherwise.
1196 pub fn is_null(&self) -> bool {
1197 self.as_null().is_some()
1200 /// If the Json value is a Null, returns ().
1201 /// Returns None otherwise.
1202 pub fn as_null(&self) -> Option<()> {
1204 Json::Null => Some(()),
1210 impl<'a> Index<&'a str> for Json {
1213 fn index(&self, idx: &'a str) -> &Json {
1214 self.find(idx).unwrap()
1218 impl Index<usize> for Json {
1221 fn index(&self, idx: usize) -> &Json {
1223 Json::Array(ref v) => &v[idx],
1224 _ => panic!("can only index Json with usize if it is an array")
1229 /// The output of the streaming parser.
1230 #[derive(PartialEq, Clone, Debug)]
1231 pub enum JsonEvent {
1240 StringValue(string::String),
1245 #[derive(PartialEq, Debug)]
1247 // Parse a value in an array, true means first element.
1249 // Parse ',' or ']' after an element in an array.
1251 // Parse a key:value in an object, true means first element.
1253 // Parse ',' or ']' after an element in an object.
1257 // Expecting the stream to end.
1259 // Parsing can't continue.
1263 /// A Stack represents the current position of the parser in the logical
1264 /// structure of the JSON stream.
1265 /// For example foo.bar[3].x
1267 stack: Vec<InternalStackElement>,
1268 str_buffer: Vec<u8>,
1271 /// StackElements compose a Stack.
1272 /// For example, StackElement::Key("foo"), StackElement::Key("bar"),
1273 /// StackElement::Index(3) and StackElement::Key("x") are the
1274 /// StackElements compositing the stack that represents foo.bar[3].x
1275 #[derive(PartialEq, Clone, Debug)]
1276 pub enum StackElement<'l> {
1281 // Internally, Key elements are stored as indices in a buffer to avoid
1282 // allocating a string for every member of an object.
1283 #[derive(PartialEq, Clone, Debug)]
1284 enum InternalStackElement {
1286 InternalKey(u16, u16), // start, size
1290 pub fn new() -> Stack {
1291 Stack { stack: Vec::new(), str_buffer: Vec::new() }
1294 /// Returns The number of elements in the Stack.
1295 pub fn len(&self) -> usize { self.stack.len() }
1297 /// Returns true if the stack is empty.
1298 pub fn is_empty(&self) -> bool { self.stack.is_empty() }
1300 /// Provides access to the StackElement at a given index.
1301 /// lower indices are at the bottom of the stack while higher indices are
1303 pub fn get(&self, idx: usize) -> StackElement {
1304 match self.stack[idx] {
1305 InternalIndex(i) => StackElement::Index(i),
1306 InternalKey(start, size) => {
1307 StackElement::Key(str::from_utf8(
1308 &self.str_buffer[start as usize .. start as usize + size as usize])
1314 /// Compares this stack with an array of StackElements.
1315 pub fn is_equal_to(&self, rhs: &[StackElement]) -> bool {
1316 if self.stack.len() != rhs.len() { return false; }
1317 for (i, r) in rhs.iter().enumerate() {
1318 if self.get(i) != *r { return false; }
1323 /// Returns true if the bottom-most elements of this stack are the same as
1324 /// the ones passed as parameter.
1325 pub fn starts_with(&self, rhs: &[StackElement]) -> bool {
1326 if self.stack.len() < rhs.len() { return false; }
1327 for (i, r) in rhs.iter().enumerate() {
1328 if self.get(i) != *r { return false; }
1333 /// Returns true if the top-most elements of this stack are the same as
1334 /// the ones passed as parameter.
1335 pub fn ends_with(&self, rhs: &[StackElement]) -> bool {
1336 if self.stack.len() < rhs.len() { return false; }
1337 let offset = self.stack.len() - rhs.len();
1338 for (i, r) in rhs.iter().enumerate() {
1339 if self.get(i + offset) != *r { return false; }
1344 /// Returns the top-most element (if any).
1345 pub fn top(&self) -> Option<StackElement> {
1346 match self.stack.last() {
1348 Some(&InternalIndex(i)) => Some(StackElement::Index(i)),
1349 Some(&InternalKey(start, size)) => {
1350 Some(StackElement::Key(str::from_utf8(
1351 &self.str_buffer[start as usize .. (start+size) as usize]
1357 // Used by Parser to insert StackElement::Key elements at the top of the stack.
1358 fn push_key(&mut self, key: string::String) {
1359 self.stack.push(InternalKey(self.str_buffer.len() as u16, key.len() as u16));
1360 self.str_buffer.extend(key.as_bytes());
1363 // Used by Parser to insert StackElement::Index elements at the top of the stack.
1364 fn push_index(&mut self, index: u32) {
1365 self.stack.push(InternalIndex(index));
1368 // Used by Parser to remove the top-most element of the stack.
1370 assert!(!self.is_empty());
1371 match *self.stack.last().unwrap() {
1372 InternalKey(_, sz) => {
1373 let new_size = self.str_buffer.len() - sz as usize;
1374 self.str_buffer.truncate(new_size);
1376 InternalIndex(_) => {}
1381 // Used by Parser to test whether the top-most element is an index.
1382 fn last_is_index(&self) -> bool {
1383 match self.stack.last() {
1384 Some(InternalIndex(_)) => true,
1389 // Used by Parser to increment the index of the top-most element.
1390 fn bump_index(&mut self) {
1391 let len = self.stack.len();
1392 let idx = match *self.stack.last().unwrap() {
1393 InternalIndex(i) => { i + 1 }
1396 self.stack[len - 1] = InternalIndex(idx);
1400 /// A streaming JSON parser implemented as an iterator of JsonEvent, consuming
1401 /// an iterator of char.
1402 pub struct Parser<T> {
1407 // We maintain a stack representing where we are in the logical structure
1408 // of the JSON stream.
1410 // A state machine is kept to make it possible to interrupt and resume parsing.
1414 impl<T: Iterator<Item=char>> Iterator for Parser<T> {
1415 type Item = JsonEvent;
1417 fn next(&mut self) -> Option<JsonEvent> {
1418 if self.state == ParseFinished {
1422 if self.state == ParseBeforeFinish {
1423 self.parse_whitespace();
1424 // Make sure there is no trailing characters.
1426 self.state = ParseFinished;
1429 return Some(self.error_event(TrailingCharacters));
1437 impl<T: Iterator<Item=char>> Parser<T> {
1438 /// Creates the JSON parser.
1439 pub fn new(rdr: T) -> Parser<T> {
1440 let mut p = Parser {
1445 stack: Stack::new(),
1452 /// Provides access to the current position in the logical structure of the
1454 pub fn stack(&self) -> &Stack {
1458 fn eof(&self) -> bool { self.ch.is_none() }
1459 fn ch_or_null(&self) -> char { self.ch.unwrap_or('\x00') }
1460 fn bump(&mut self) {
1461 self.ch = self.rdr.next();
1463 if self.ch_is('\n') {
1471 fn next_char(&mut self) -> Option<char> {
1475 fn ch_is(&self, c: char) -> bool {
1479 fn error<U>(&self, reason: ErrorCode) -> Result<U, ParserError> {
1480 Err(SyntaxError(reason, self.line, self.col))
1483 fn parse_whitespace(&mut self) {
1484 while self.ch_is(' ') ||
1487 self.ch_is('\r') { self.bump(); }
1490 fn parse_number(&mut self) -> JsonEvent {
1491 let mut neg = false;
1493 if self.ch_is('-') {
1498 let res = match self.parse_u64() {
1500 Err(e) => { return Error(e); }
1503 if self.ch_is('.') || self.ch_is('e') || self.ch_is('E') {
1504 let mut res = res as f64;
1506 if self.ch_is('.') {
1507 res = match self.parse_decimal(res) {
1509 Err(e) => { return Error(e); }
1513 if self.ch_is('e') || self.ch_is('E') {
1514 res = match self.parse_exponent(res) {
1516 Err(e) => { return Error(e); }
1526 let res = (res as i64).wrapping_neg();
1528 // Make sure we didn't underflow.
1530 Error(SyntaxError(InvalidNumber, self.line, self.col))
1539 fn parse_u64(&mut self) -> Result<u64, ParserError> {
1540 let mut accum = 0u64;
1541 let last_accum = 0; // necessary to detect overflow.
1543 match self.ch_or_null() {
1547 // A leading '0' must be the only digit before the decimal point.
1548 if let '0' ..= '9' = self.ch_or_null() {
1549 return self.error(InvalidNumber)
1554 match self.ch_or_null() {
1555 c @ '0' ..= '9' => {
1556 accum = accum.wrapping_mul(10);
1557 accum = accum.wrapping_add((c as u64) - ('0' as u64));
1559 // Detect overflow by comparing to the last value.
1560 if accum <= last_accum { return self.error(InvalidNumber); }
1568 _ => return self.error(InvalidNumber),
1574 fn parse_decimal(&mut self, mut res: f64) -> Result<f64, ParserError> {
1577 // Make sure a digit follows the decimal place.
1578 match self.ch_or_null() {
1580 _ => return self.error(InvalidNumber)
1585 match self.ch_or_null() {
1586 c @ '0' ..= '9' => {
1588 res += (((c as isize) - ('0' as isize)) as f64) * dec;
1598 fn parse_exponent(&mut self, mut res: f64) -> Result<f64, ParserError> {
1602 let mut neg_exp = false;
1604 if self.ch_is('+') {
1606 } else if self.ch_is('-') {
1611 // Make sure a digit follows the exponent place.
1612 match self.ch_or_null() {
1614 _ => return self.error(InvalidNumber)
1617 match self.ch_or_null() {
1618 c @ '0' ..= '9' => {
1620 exp += (c as usize) - ('0' as usize);
1628 let exp = 10_f64.powi(exp as i32);
1638 fn decode_hex_escape(&mut self) -> Result<u16, ParserError> {
1641 while i < 4 && !self.eof() {
1643 n = match self.ch_or_null() {
1644 c @ '0' ..= '9' => n * 16 + ((c as u16) - ('0' as u16)),
1645 'a' | 'A' => n * 16 + 10,
1646 'b' | 'B' => n * 16 + 11,
1647 'c' | 'C' => n * 16 + 12,
1648 'd' | 'D' => n * 16 + 13,
1649 'e' | 'E' => n * 16 + 14,
1650 'f' | 'F' => n * 16 + 15,
1651 _ => return self.error(InvalidEscape)
1657 // Error out if we didn't parse 4 digits.
1659 return self.error(InvalidEscape);
1665 fn parse_str(&mut self) -> Result<string::String, ParserError> {
1666 let mut escape = false;
1667 let mut res = string::String::new();
1672 return self.error(EOFWhileParsingString);
1676 match self.ch_or_null() {
1677 '"' => res.push('"'),
1678 '\\' => res.push('\\'),
1679 '/' => res.push('/'),
1680 'b' => res.push('\x08'),
1681 'f' => res.push('\x0c'),
1682 'n' => res.push('\n'),
1683 'r' => res.push('\r'),
1684 't' => res.push('\t'),
1685 'u' => match self.decode_hex_escape()? {
1686 0xDC00 ..= 0xDFFF => {
1687 return self.error(LoneLeadingSurrogateInHexEscape)
1690 // Non-BMP characters are encoded as a sequence of
1691 // two hex escapes, representing UTF-16 surrogates.
1692 n1 @ 0xD800 ..= 0xDBFF => {
1693 match (self.next_char(), self.next_char()) {
1694 (Some('\\'), Some('u')) => (),
1695 _ => return self.error(UnexpectedEndOfHexEscape),
1698 let n2 = self.decode_hex_escape()?;
1699 if n2 < 0xDC00 || n2 > 0xDFFF {
1700 return self.error(LoneLeadingSurrogateInHexEscape)
1702 let c = (((n1 - 0xD800) as u32) << 10 |
1703 (n2 - 0xDC00) as u32) + 0x1_0000;
1704 res.push(char::from_u32(c).unwrap());
1707 n => match char::from_u32(n as u32) {
1708 Some(c) => res.push(c),
1709 None => return self.error(InvalidUnicodeCodePoint),
1712 _ => return self.error(InvalidEscape),
1715 } else if self.ch_is('\\') {
1723 Some(c) => res.push(c),
1724 None => unreachable!()
1730 // Invoked at each iteration, consumes the stream until it has enough
1731 // information to return a JsonEvent.
1732 // Manages an internal state so that parsing can be interrupted and resumed.
1733 // Also keeps track of the position in the logical structure of the json
1734 // stream isize the form of a stack that can be queried by the user using the
1736 fn parse(&mut self) -> JsonEvent {
1738 // The only paths where the loop can spin a new iteration
1739 // are in the cases ParseArrayComma and ParseObjectComma if ','
1740 // is parsed. In these cases the state is set to (respectively)
1741 // ParseArray(false) and ParseObject(false), which always return,
1742 // so there is no risk of getting stuck in an infinite loop.
1743 // All other paths return before the end of the loop's iteration.
1744 self.parse_whitespace();
1748 return self.parse_start();
1750 ParseArray(first) => {
1751 return self.parse_array(first);
1753 ParseArrayComma => {
1754 if let Some(evt) = self.parse_array_comma_or_end() {
1758 ParseObject(first) => {
1759 return self.parse_object(first);
1761 ParseObjectComma => {
1763 if self.ch_is(',') {
1764 self.state = ParseObject(false);
1767 return self.parse_object_end();
1771 return self.error_event(InvalidSyntax);
1777 fn parse_start(&mut self) -> JsonEvent {
1778 let val = self.parse_value();
1779 self.state = match val {
1780 Error(_) => ParseFinished,
1781 ArrayStart => ParseArray(true),
1782 ObjectStart => ParseObject(true),
1783 _ => ParseBeforeFinish,
1788 fn parse_array(&mut self, first: bool) -> JsonEvent {
1789 if self.ch_is(']') {
1791 self.error_event(InvalidSyntax)
1793 self.state = if self.stack.is_empty() {
1795 } else if self.stack.last_is_index() {
1805 self.stack.push_index(0);
1807 let val = self.parse_value();
1808 self.state = match val {
1809 Error(_) => ParseFinished,
1810 ArrayStart => ParseArray(true),
1811 ObjectStart => ParseObject(true),
1812 _ => ParseArrayComma,
1818 fn parse_array_comma_or_end(&mut self) -> Option<JsonEvent> {
1819 if self.ch_is(',') {
1820 self.stack.bump_index();
1821 self.state = ParseArray(false);
1824 } else if self.ch_is(']') {
1826 self.state = if self.stack.is_empty() {
1828 } else if self.stack.last_is_index() {
1835 } else if self.eof() {
1836 Some(self.error_event(EOFWhileParsingArray))
1838 Some(self.error_event(InvalidSyntax))
1842 fn parse_object(&mut self, first: bool) -> JsonEvent {
1843 if self.ch_is('}') {
1845 if self.stack.is_empty() {
1846 return self.error_event(TrailingComma);
1851 self.state = if self.stack.is_empty() {
1853 } else if self.stack.last_is_index() {
1862 return self.error_event(EOFWhileParsingObject);
1864 if !self.ch_is('"') {
1865 return self.error_event(KeyMustBeAString);
1867 let s = match self.parse_str() {
1870 self.state = ParseFinished;
1874 self.parse_whitespace();
1876 return self.error_event(EOFWhileParsingObject);
1877 } else if self.ch_or_null() != ':' {
1878 return self.error_event(ExpectedColon);
1880 self.stack.push_key(s);
1882 self.parse_whitespace();
1884 let val = self.parse_value();
1886 self.state = match val {
1887 Error(_) => ParseFinished,
1888 ArrayStart => ParseArray(true),
1889 ObjectStart => ParseObject(true),
1890 _ => ParseObjectComma,
1895 fn parse_object_end(&mut self) -> JsonEvent {
1896 if self.ch_is('}') {
1897 self.state = if self.stack.is_empty() {
1899 } else if self.stack.last_is_index() {
1906 } else if self.eof() {
1907 self.error_event(EOFWhileParsingObject)
1909 self.error_event(InvalidSyntax)
1913 fn parse_value(&mut self) -> JsonEvent {
1914 if self.eof() { return self.error_event(EOFWhileParsingValue); }
1915 match self.ch_or_null() {
1916 'n' => { self.parse_ident("ull", NullValue) }
1917 't' => { self.parse_ident("rue", BooleanValue(true)) }
1918 'f' => { self.parse_ident("alse", BooleanValue(false)) }
1919 '0' ..= '9' | '-' => self.parse_number(),
1920 '"' => match self.parse_str() {
1921 Ok(s) => StringValue(s),
1932 _ => { self.error_event(InvalidSyntax) }
1936 fn parse_ident(&mut self, ident: &str, value: JsonEvent) -> JsonEvent {
1937 if ident.chars().all(|c| Some(c) == self.next_char()) {
1941 Error(SyntaxError(InvalidSyntax, self.line, self.col))
1945 fn error_event(&mut self, reason: ErrorCode) -> JsonEvent {
1946 self.state = ParseFinished;
1947 Error(SyntaxError(reason, self.line, self.col))
1951 /// A Builder consumes a json::Parser to create a generic Json structure.
1952 pub struct Builder<T> {
1954 token: Option<JsonEvent>,
1957 impl<T: Iterator<Item=char>> Builder<T> {
1958 /// Create a JSON Builder.
1959 pub fn new(src: T) -> Builder<T> {
1960 Builder { parser: Parser::new(src), token: None, }
1963 // Decode a Json value from a Parser.
1964 pub fn build(&mut self) -> Result<Json, BuilderError> {
1966 let result = self.build_value();
1970 Some(Error(ref e)) => { return Err(e.clone()); }
1971 ref tok => { panic!("unexpected token {:?}", tok.clone()); }
1976 fn bump(&mut self) {
1977 self.token = self.parser.next();
1980 fn build_value(&mut self) -> Result<Json, BuilderError> {
1982 Some(NullValue) => Ok(Json::Null),
1983 Some(I64Value(n)) => Ok(Json::I64(n)),
1984 Some(U64Value(n)) => Ok(Json::U64(n)),
1985 Some(F64Value(n)) => Ok(Json::F64(n)),
1986 Some(BooleanValue(b)) => Ok(Json::Boolean(b)),
1987 Some(StringValue(ref mut s)) => {
1988 let mut temp = string::String::new();
1990 Ok(Json::String(temp))
1992 Some(Error(ref e)) => Err(e.clone()),
1993 Some(ArrayStart) => self.build_array(),
1994 Some(ObjectStart) => self.build_object(),
1995 Some(ObjectEnd) => self.parser.error(InvalidSyntax),
1996 Some(ArrayEnd) => self.parser.error(InvalidSyntax),
1997 None => self.parser.error(EOFWhileParsingValue),
2001 fn build_array(&mut self) -> Result<Json, BuilderError> {
2003 let mut values = Vec::new();
2006 if self.token == Some(ArrayEnd) {
2007 return Ok(Json::Array(values.into_iter().collect()));
2009 match self.build_value() {
2010 Ok(v) => values.push(v),
2011 Err(e) => { return Err(e) }
2017 fn build_object(&mut self) -> Result<Json, BuilderError> {
2020 let mut values = BTreeMap::new();
2024 Some(ObjectEnd) => { return Ok(Json::Object(values)); }
2025 Some(Error(ref e)) => { return Err(e.clone()); }
2029 let key = match self.parser.stack().top() {
2030 Some(StackElement::Key(k)) => { k.to_owned() }
2031 _ => { panic!("invalid state"); }
2033 match self.build_value() {
2034 Ok(value) => { values.insert(key, value); }
2035 Err(e) => { return Err(e); }
2039 self.parser.error(EOFWhileParsingObject)
2043 /// Decodes a json value from an `&mut io::Read`
2044 pub fn from_reader(rdr: &mut dyn Read) -> Result<Json, BuilderError> {
2045 let mut contents = Vec::new();
2046 match rdr.read_to_end(&mut contents) {
2048 Err(e) => return Err(io_error_to_error(e))
2050 let s = match str::from_utf8(&contents).ok() {
2052 _ => return Err(SyntaxError(NotUtf8, 0, 0))
2054 let mut builder = Builder::new(s.chars());
2058 /// Decodes a json value from a string
2059 pub fn from_str(s: &str) -> Result<Json, BuilderError> {
2060 let mut builder = Builder::new(s.chars());
2064 /// A structure to decode JSON to values in rust.
2065 pub struct Decoder {
2070 /// Creates a new decoder instance for decoding the specified JSON value.
2071 pub fn new(json: Json) -> Decoder {
2072 Decoder { stack: vec![json] }
2075 fn pop(&mut self) -> Json {
2076 self.stack.pop().unwrap()
2080 macro_rules! expect {
2081 ($e:expr, Null) => ({
2083 Json::Null => Ok(()),
2084 other => Err(ExpectedError("Null".to_owned(),
2088 ($e:expr, $t:ident) => ({
2090 Json::$t(v) => Ok(v),
2092 Err(ExpectedError(stringify!($t).to_owned(),
2099 macro_rules! read_primitive {
2100 ($name:ident, $ty:ty) => {
2101 fn $name(&mut self) -> DecodeResult<$ty> {
2103 Json::I64(f) => Ok(f as $ty),
2104 Json::U64(f) => Ok(f as $ty),
2105 Json::F64(f) => Err(ExpectedError("Integer".to_owned(), f.to_string())),
2106 // re: #12967.. a type w/ numeric keys (ie HashMap<usize, V> etc)
2107 // is going to have a string here, as per JSON spec.
2108 Json::String(s) => match s.parse().ok() {
2110 None => Err(ExpectedError("Number".to_owned(), s)),
2112 value => Err(ExpectedError("Number".to_owned(), value.to_string())),
2118 impl ::Decoder for Decoder {
2119 type Error = DecoderError;
2121 fn read_nil(&mut self) -> DecodeResult<()> {
2122 expect!(self.pop(), Null)
2125 read_primitive! { read_usize, usize }
2126 read_primitive! { read_u8, u8 }
2127 read_primitive! { read_u16, u16 }
2128 read_primitive! { read_u32, u32 }
2129 read_primitive! { read_u64, u64 }
2130 read_primitive! { read_u128, u128 }
2131 read_primitive! { read_isize, isize }
2132 read_primitive! { read_i8, i8 }
2133 read_primitive! { read_i16, i16 }
2134 read_primitive! { read_i32, i32 }
2135 read_primitive! { read_i64, i64 }
2136 read_primitive! { read_i128, i128 }
2138 fn read_f32(&mut self) -> DecodeResult<f32> { self.read_f64().map(|x| x as f32) }
2140 fn read_f64(&mut self) -> DecodeResult<f64> {
2142 Json::I64(f) => Ok(f as f64),
2143 Json::U64(f) => Ok(f as f64),
2144 Json::F64(f) => Ok(f),
2145 Json::String(s) => {
2146 // re: #12967.. a type w/ numeric keys (ie HashMap<usize, V> etc)
2147 // is going to have a string here, as per JSON spec.
2148 match s.parse().ok() {
2150 None => Err(ExpectedError("Number".to_owned(), s)),
2153 Json::Null => Ok(f64::NAN),
2154 value => Err(ExpectedError("Number".to_owned(), value.to_string()))
2158 fn read_bool(&mut self) -> DecodeResult<bool> {
2159 expect!(self.pop(), Boolean)
2162 fn read_char(&mut self) -> DecodeResult<char> {
2163 let s = self.read_str()?;
2165 let mut it = s.chars();
2166 match (it.next(), it.next()) {
2167 // exactly one character
2168 (Some(c), None) => return Ok(c),
2172 Err(ExpectedError("single character string".to_owned(), s.to_string()))
2175 fn read_str(&mut self) -> DecodeResult<Cow<str>> {
2176 expect!(self.pop(), String).map(Cow::Owned)
2179 fn read_enum<T, F>(&mut self, _name: &str, f: F) -> DecodeResult<T> where
2180 F: FnOnce(&mut Decoder) -> DecodeResult<T>,
2185 fn read_enum_variant<T, F>(&mut self, names: &[&str],
2186 mut f: F) -> DecodeResult<T>
2187 where F: FnMut(&mut Decoder, usize) -> DecodeResult<T>,
2189 let name = match self.pop() {
2190 Json::String(s) => s,
2191 Json::Object(mut o) => {
2192 let n = match o.remove(&"variant".to_owned()) {
2193 Some(Json::String(s)) => s,
2195 return Err(ExpectedError("String".to_owned(), val.to_string()))
2198 return Err(MissingFieldError("variant".to_owned()))
2201 match o.remove(&"fields".to_string()) {
2202 Some(Json::Array(l)) => {
2203 self.stack.extend(l.into_iter().rev());
2206 return Err(ExpectedError("Array".to_owned(), val.to_string()))
2209 return Err(MissingFieldError("fields".to_owned()))
2215 return Err(ExpectedError("String or Object".to_owned(), json.to_string()))
2218 let idx = match names.iter().position(|n| *n == &name[..]) {
2220 None => return Err(UnknownVariantError(name))
2225 fn read_enum_variant_arg<T, F>(&mut self, _idx: usize, f: F) -> DecodeResult<T> where
2226 F: FnOnce(&mut Decoder) -> DecodeResult<T>,
2231 fn read_enum_struct_variant<T, F>(&mut self, names: &[&str], f: F) -> DecodeResult<T> where
2232 F: FnMut(&mut Decoder, usize) -> DecodeResult<T>,
2234 self.read_enum_variant(names, f)
2238 fn read_enum_struct_variant_field<T, F>(&mut self,
2242 -> DecodeResult<T> where
2243 F: FnOnce(&mut Decoder) -> DecodeResult<T>,
2245 self.read_enum_variant_arg(idx, f)
2248 fn read_struct<T, F>(&mut self, _name: &str, _len: usize, f: F) -> DecodeResult<T> where
2249 F: FnOnce(&mut Decoder) -> DecodeResult<T>,
2251 let value = f(self)?;
2256 fn read_struct_field<T, F>(&mut self,
2260 -> DecodeResult<T> where
2261 F: FnOnce(&mut Decoder) -> DecodeResult<T>,
2263 let mut obj = expect!(self.pop(), Object)?;
2265 let value = match obj.remove(&name.to_string()) {
2267 // Add a Null and try to parse it as an Option<_>
2268 // to get None as a default value.
2269 self.stack.push(Json::Null);
2272 Err(_) => return Err(MissingFieldError(name.to_string())),
2276 self.stack.push(json);
2280 self.stack.push(Json::Object(obj));
2284 fn read_tuple<T, F>(&mut self, tuple_len: usize, f: F) -> DecodeResult<T> where
2285 F: FnOnce(&mut Decoder) -> DecodeResult<T>,
2287 self.read_seq(move |d, len| {
2288 if len == tuple_len {
2291 Err(ExpectedError(format!("Tuple{}", tuple_len), format!("Tuple{}", len)))
2296 fn read_tuple_arg<T, F>(&mut self, idx: usize, f: F) -> DecodeResult<T> where
2297 F: FnOnce(&mut Decoder) -> DecodeResult<T>,
2299 self.read_seq_elt(idx, f)
2302 fn read_tuple_struct<T, F>(&mut self,
2306 -> DecodeResult<T> where
2307 F: FnOnce(&mut Decoder) -> DecodeResult<T>,
2309 self.read_tuple(len, f)
2312 fn read_tuple_struct_arg<T, F>(&mut self,
2315 -> DecodeResult<T> where
2316 F: FnOnce(&mut Decoder) -> DecodeResult<T>,
2318 self.read_tuple_arg(idx, f)
2321 fn read_option<T, F>(&mut self, mut f: F) -> DecodeResult<T> where
2322 F: FnMut(&mut Decoder, bool) -> DecodeResult<T>,
2325 Json::Null => f(self, false),
2326 value => { self.stack.push(value); f(self, true) }
2330 fn read_seq<T, F>(&mut self, f: F) -> DecodeResult<T> where
2331 F: FnOnce(&mut Decoder, usize) -> DecodeResult<T>,
2333 let array = expect!(self.pop(), Array)?;
2334 let len = array.len();
2335 self.stack.extend(array.into_iter().rev());
2339 fn read_seq_elt<T, F>(&mut self, _idx: usize, f: F) -> DecodeResult<T> where
2340 F: FnOnce(&mut Decoder) -> DecodeResult<T>,
2345 fn read_map<T, F>(&mut self, f: F) -> DecodeResult<T> where
2346 F: FnOnce(&mut Decoder, usize) -> DecodeResult<T>,
2348 let obj = expect!(self.pop(), Object)?;
2349 let len = obj.len();
2350 for (key, value) in obj {
2351 self.stack.push(value);
2352 self.stack.push(Json::String(key));
2357 fn read_map_elt_key<T, F>(&mut self, _idx: usize, f: F) -> DecodeResult<T> where
2358 F: FnOnce(&mut Decoder) -> DecodeResult<T>,
2363 fn read_map_elt_val<T, F>(&mut self, _idx: usize, f: F) -> DecodeResult<T> where
2364 F: FnOnce(&mut Decoder) -> DecodeResult<T>,
2369 fn error(&mut self, err: &str) -> DecoderError {
2370 ApplicationError(err.to_string())
2374 /// A trait for converting values to JSON
2376 /// Converts the value of `self` to an instance of JSON
2377 fn to_json(&self) -> Json;
2380 macro_rules! to_json_impl_i64 {
2382 $(impl ToJson for $t {
2383 fn to_json(&self) -> Json {
2384 Json::I64(*self as i64)
2390 to_json_impl_i64! { isize, i8, i16, i32, i64 }
2392 macro_rules! to_json_impl_u64 {
2394 $(impl ToJson for $t {
2395 fn to_json(&self) -> Json {
2396 Json::U64(*self as u64)
2402 to_json_impl_u64! { usize, u8, u16, u32, u64 }
2404 impl ToJson for Json {
2405 fn to_json(&self) -> Json { self.clone() }
2408 impl ToJson for f32 {
2409 fn to_json(&self) -> Json { (*self as f64).to_json() }
2412 impl ToJson for f64 {
2413 fn to_json(&self) -> Json {
2414 match self.classify() {
2415 Fp::Nan | Fp::Infinite => Json::Null,
2416 _ => Json::F64(*self)
2421 impl ToJson for () {
2422 fn to_json(&self) -> Json { Json::Null }
2425 impl ToJson for bool {
2426 fn to_json(&self) -> Json { Json::Boolean(*self) }
2429 impl ToJson for str {
2430 fn to_json(&self) -> Json { Json::String(self.to_string()) }
2433 impl ToJson for string::String {
2434 fn to_json(&self) -> Json { Json::String((*self).clone()) }
2437 macro_rules! tuple_impl {
2438 // use variables to indicate the arity of the tuple
2439 ($($tyvar:ident),* ) => {
2440 // the trailing commas are for the 1 tuple
2442 $( $tyvar : ToJson ),*
2443 > ToJson for ( $( $tyvar ),* , ) {
2446 #[allow(non_snake_case)]
2447 fn to_json(&self) -> Json {
2449 ($(ref $tyvar),*,) => Json::Array(vec![$($tyvar.to_json()),*])
2458 tuple_impl!{A, B, C}
2459 tuple_impl!{A, B, C, D}
2460 tuple_impl!{A, B, C, D, E}
2461 tuple_impl!{A, B, C, D, E, F}
2462 tuple_impl!{A, B, C, D, E, F, G}
2463 tuple_impl!{A, B, C, D, E, F, G, H}
2464 tuple_impl!{A, B, C, D, E, F, G, H, I}
2465 tuple_impl!{A, B, C, D, E, F, G, H, I, J}
2466 tuple_impl!{A, B, C, D, E, F, G, H, I, J, K}
2467 tuple_impl!{A, B, C, D, E, F, G, H, I, J, K, L}
2469 impl<A: ToJson> ToJson for [A] {
2470 fn to_json(&self) -> Json { Json::Array(self.iter().map(|elt| elt.to_json()).collect()) }
2473 impl<A: ToJson> ToJson for Vec<A> {
2474 fn to_json(&self) -> Json { Json::Array(self.iter().map(|elt| elt.to_json()).collect()) }
2477 impl<A: ToJson> ToJson for BTreeMap<string::String, A> {
2478 fn to_json(&self) -> Json {
2479 let mut d = BTreeMap::new();
2480 for (key, value) in self {
2481 d.insert((*key).clone(), value.to_json());
2487 impl<A: ToJson> ToJson for HashMap<string::String, A> {
2488 fn to_json(&self) -> Json {
2489 let mut d = BTreeMap::new();
2490 for (key, value) in self {
2491 d.insert((*key).clone(), value.to_json());
2497 impl<A:ToJson> ToJson for Option<A> {
2498 fn to_json(&self) -> Json {
2501 Some(ref value) => value.to_json()
2506 struct FormatShim<'a, 'b: 'a> {
2507 inner: &'a mut fmt::Formatter<'b>,
2510 impl<'a, 'b> fmt::Write for FormatShim<'a, 'b> {
2511 fn write_str(&mut self, s: &str) -> fmt::Result {
2512 match self.inner.write_str(s) {
2514 Err(_) => Err(fmt::Error)
2519 impl fmt::Display 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 match self.encode(&mut encoder) {
2526 Err(_) => Err(fmt::Error)
2531 impl<'a> fmt::Display for PrettyJson<'a> {
2532 /// Encodes a json value into a string
2533 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2534 let mut shim = FormatShim { inner: f };
2535 let mut encoder = PrettyEncoder::new(&mut shim);
2536 match self.inner.encode(&mut encoder) {
2538 Err(_) => Err(fmt::Error)
2543 impl<'a, T: Encodable> fmt::Display for AsJson<'a, T> {
2544 /// Encodes a json value into a string
2545 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2546 let mut shim = FormatShim { inner: f };
2547 let mut encoder = Encoder::new(&mut shim);
2548 match self.inner.encode(&mut encoder) {
2550 Err(_) => Err(fmt::Error)
2555 impl<'a, T> AsPrettyJson<'a, T> {
2556 /// Set the indentation level for the emitted JSON
2557 pub fn indent(mut self, indent: usize) -> AsPrettyJson<'a, T> {
2558 self.indent = Some(indent);
2563 impl<'a, T: Encodable> fmt::Display for AsPrettyJson<'a, T> {
2564 /// Encodes a json value into a string
2565 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2566 let mut shim = FormatShim { inner: f };
2567 let mut encoder = PrettyEncoder::new(&mut shim);
2568 if let Some(n) = self.indent {
2569 encoder.set_indent(n);
2571 match self.inner.encode(&mut encoder) {
2573 Err(_) => Err(fmt::Error)
2578 impl FromStr for Json {
2579 type Err = BuilderError;
2580 fn from_str(s: &str) -> Result<Json, BuilderError> {
2588 use self::Animal::*;
2589 use self::test::Bencher;
2590 use {Encodable, Decodable};
2592 use super::ErrorCode::*;
2593 use super::ParserError::*;
2594 use super::DecoderError::*;
2595 use super::JsonEvent::*;
2596 use super::{Json, from_str, DecodeResult, DecoderError, JsonEvent, Parser,
2597 StackElement, Stack, Decoder, Encoder, EncoderError};
2598 use std::{i64, u64, f32, f64};
2599 use std::io::prelude::*;
2600 use std::collections::BTreeMap;
2603 #[derive(RustcDecodable, Eq, PartialEq, Debug)]
2609 fn test_decode_option_none() {
2611 let obj: OptionData = super::decode(s).unwrap();
2612 assert_eq!(obj, OptionData { opt: None });
2616 fn test_decode_option_some() {
2617 let s = "{ \"opt\": 10 }";
2618 let obj: OptionData = super::decode(s).unwrap();
2619 assert_eq!(obj, OptionData { opt: Some(10) });
2623 fn test_decode_option_malformed() {
2624 check_err::<OptionData>("{ \"opt\": [] }",
2625 ExpectedError("Number".to_string(), "[]".to_string()));
2626 check_err::<OptionData>("{ \"opt\": false }",
2627 ExpectedError("Number".to_string(), "false".to_string()));
2630 #[derive(PartialEq, RustcEncodable, RustcDecodable, Debug)]
2633 Frog(string::String, isize)
2636 #[derive(PartialEq, RustcEncodable, RustcDecodable, Debug)]
2640 c: Vec<string::String>,
2643 #[derive(PartialEq, RustcEncodable, RustcDecodable, Debug)]
2648 fn mk_object(items: &[(string::String, Json)]) -> Json {
2649 let mut d = BTreeMap::new();
2653 (ref key, ref value) => { d.insert((*key).clone(), (*value).clone()); },
2661 fn test_from_str_trait() {
2663 assert!(s.parse::<Json>().unwrap() == s.parse().unwrap());
2667 fn test_write_null() {
2668 assert_eq!(Null.to_string(), "null");
2669 assert_eq!(Null.pretty().to_string(), "null");
2673 fn test_write_i64() {
2674 assert_eq!(U64(0).to_string(), "0");
2675 assert_eq!(U64(0).pretty().to_string(), "0");
2677 assert_eq!(U64(1234).to_string(), "1234");
2678 assert_eq!(U64(1234).pretty().to_string(), "1234");
2680 assert_eq!(I64(-5678).to_string(), "-5678");
2681 assert_eq!(I64(-5678).pretty().to_string(), "-5678");
2683 assert_eq!(U64(7650007200025252000).to_string(), "7650007200025252000");
2684 assert_eq!(U64(7650007200025252000).pretty().to_string(), "7650007200025252000");
2688 fn test_write_f64() {
2689 assert_eq!(F64(3.0).to_string(), "3.0");
2690 assert_eq!(F64(3.0).pretty().to_string(), "3.0");
2692 assert_eq!(F64(3.1).to_string(), "3.1");
2693 assert_eq!(F64(3.1).pretty().to_string(), "3.1");
2695 assert_eq!(F64(-1.5).to_string(), "-1.5");
2696 assert_eq!(F64(-1.5).pretty().to_string(), "-1.5");
2698 assert_eq!(F64(0.5).to_string(), "0.5");
2699 assert_eq!(F64(0.5).pretty().to_string(), "0.5");
2701 assert_eq!(F64(f64::NAN).to_string(), "null");
2702 assert_eq!(F64(f64::NAN).pretty().to_string(), "null");
2704 assert_eq!(F64(f64::INFINITY).to_string(), "null");
2705 assert_eq!(F64(f64::INFINITY).pretty().to_string(), "null");
2707 assert_eq!(F64(f64::NEG_INFINITY).to_string(), "null");
2708 assert_eq!(F64(f64::NEG_INFINITY).pretty().to_string(), "null");
2712 fn test_write_str() {
2713 assert_eq!(String("".to_string()).to_string(), "\"\"");
2714 assert_eq!(String("".to_string()).pretty().to_string(), "\"\"");
2716 assert_eq!(String("homura".to_string()).to_string(), "\"homura\"");
2717 assert_eq!(String("madoka".to_string()).pretty().to_string(), "\"madoka\"");
2721 fn test_write_bool() {
2722 assert_eq!(Boolean(true).to_string(), "true");
2723 assert_eq!(Boolean(true).pretty().to_string(), "true");
2725 assert_eq!(Boolean(false).to_string(), "false");
2726 assert_eq!(Boolean(false).pretty().to_string(), "false");
2730 fn test_write_array() {
2731 assert_eq!(Array(vec![]).to_string(), "[]");
2732 assert_eq!(Array(vec![]).pretty().to_string(), "[]");
2734 assert_eq!(Array(vec![Boolean(true)]).to_string(), "[true]");
2736 Array(vec![Boolean(true)]).pretty().to_string(),
2743 let long_test_array = Array(vec![
2746 Array(vec![String("foo\nbar".to_string()), F64(3.5)])]);
2748 assert_eq!(long_test_array.to_string(),
2749 "[false,null,[\"foo\\nbar\",3.5]]");
2751 long_test_array.pretty().to_string(),
2765 fn test_write_object() {
2766 assert_eq!(mk_object(&[]).to_string(), "{}");
2767 assert_eq!(mk_object(&[]).pretty().to_string(), "{}");
2771 ("a".to_string(), Boolean(true))
2776 mk_object(&[("a".to_string(), Boolean(true))]).pretty().to_string(),
2783 let complex_obj = mk_object(&[
2784 ("b".to_string(), Array(vec![
2785 mk_object(&[("c".to_string(), String("\x0c\r".to_string()))]),
2786 mk_object(&[("d".to_string(), String("".to_string()))])
2791 complex_obj.to_string(),
2794 {\"c\":\"\\f\\r\"},\
2800 complex_obj.pretty().to_string(),
2805 \"c\": \"\\f\\r\"\n \
2814 let a = mk_object(&[
2815 ("a".to_string(), Boolean(true)),
2816 ("b".to_string(), Array(vec![
2817 mk_object(&[("c".to_string(), String("\x0c\r".to_string()))]),
2818 mk_object(&[("d".to_string(), String("".to_string()))])
2822 // We can't compare the strings directly because the object fields be
2823 // printed in a different order.
2824 assert_eq!(a.clone(), a.to_string().parse().unwrap());
2825 assert_eq!(a.clone(), a.pretty().to_string().parse().unwrap());
2829 fn test_write_enum() {
2832 super::as_json(&animal).to_string(),
2836 super::as_pretty_json(&animal).to_string(),
2840 let animal = Frog("Henry".to_string(), 349);
2842 super::as_json(&animal).to_string(),
2843 "{\"variant\":\"Frog\",\"fields\":[\"Henry\",349]}"
2846 super::as_pretty_json(&animal).to_string(),
2848 \"variant\": \"Frog\",\n \
2857 macro_rules! check_encoder_for_simple {
2858 ($value:expr, $expected:expr) => ({
2859 let s = super::as_json(&$value).to_string();
2860 assert_eq!(s, $expected);
2862 let s = super::as_pretty_json(&$value).to_string();
2863 assert_eq!(s, $expected);
2868 fn test_write_some() {
2869 check_encoder_for_simple!(Some("jodhpurs".to_string()), "\"jodhpurs\"");
2873 fn test_write_none() {
2874 check_encoder_for_simple!(None::<string::String>, "null");
2878 fn test_write_char() {
2879 check_encoder_for_simple!('a', "\"a\"");
2880 check_encoder_for_simple!('\t', "\"\\t\"");
2881 check_encoder_for_simple!('\u{0000}', "\"\\u0000\"");
2882 check_encoder_for_simple!('\u{001b}', "\"\\u001b\"");
2883 check_encoder_for_simple!('\u{007f}', "\"\\u007f\"");
2884 check_encoder_for_simple!('\u{00a0}', "\"\u{00a0}\"");
2885 check_encoder_for_simple!('\u{abcd}', "\"\u{abcd}\"");
2886 check_encoder_for_simple!('\u{10ffff}', "\"\u{10ffff}\"");
2890 fn test_trailing_characters() {
2891 assert_eq!(from_str("nulla"), Err(SyntaxError(TrailingCharacters, 1, 5)));
2892 assert_eq!(from_str("truea"), Err(SyntaxError(TrailingCharacters, 1, 5)));
2893 assert_eq!(from_str("falsea"), Err(SyntaxError(TrailingCharacters, 1, 6)));
2894 assert_eq!(from_str("1a"), Err(SyntaxError(TrailingCharacters, 1, 2)));
2895 assert_eq!(from_str("[]a"), Err(SyntaxError(TrailingCharacters, 1, 3)));
2896 assert_eq!(from_str("{}a"), Err(SyntaxError(TrailingCharacters, 1, 3)));
2900 fn test_read_identifiers() {
2901 assert_eq!(from_str("n"), Err(SyntaxError(InvalidSyntax, 1, 2)));
2902 assert_eq!(from_str("nul"), Err(SyntaxError(InvalidSyntax, 1, 4)));
2903 assert_eq!(from_str("t"), Err(SyntaxError(InvalidSyntax, 1, 2)));
2904 assert_eq!(from_str("truz"), Err(SyntaxError(InvalidSyntax, 1, 4)));
2905 assert_eq!(from_str("f"), Err(SyntaxError(InvalidSyntax, 1, 2)));
2906 assert_eq!(from_str("faz"), Err(SyntaxError(InvalidSyntax, 1, 3)));
2908 assert_eq!(from_str("null"), Ok(Null));
2909 assert_eq!(from_str("true"), Ok(Boolean(true)));
2910 assert_eq!(from_str("false"), Ok(Boolean(false)));
2911 assert_eq!(from_str(" null "), Ok(Null));
2912 assert_eq!(from_str(" true "), Ok(Boolean(true)));
2913 assert_eq!(from_str(" false "), Ok(Boolean(false)));
2917 fn test_decode_identifiers() {
2918 let v: () = super::decode("null").unwrap();
2921 let v: bool = super::decode("true").unwrap();
2922 assert_eq!(v, true);
2924 let v: bool = super::decode("false").unwrap();
2925 assert_eq!(v, false);
2929 fn test_read_number() {
2930 assert_eq!(from_str("+"), Err(SyntaxError(InvalidSyntax, 1, 1)));
2931 assert_eq!(from_str("."), Err(SyntaxError(InvalidSyntax, 1, 1)));
2932 assert_eq!(from_str("NaN"), Err(SyntaxError(InvalidSyntax, 1, 1)));
2933 assert_eq!(from_str("-"), Err(SyntaxError(InvalidNumber, 1, 2)));
2934 assert_eq!(from_str("00"), Err(SyntaxError(InvalidNumber, 1, 2)));
2935 assert_eq!(from_str("1."), Err(SyntaxError(InvalidNumber, 1, 3)));
2936 assert_eq!(from_str("1e"), Err(SyntaxError(InvalidNumber, 1, 3)));
2937 assert_eq!(from_str("1e+"), Err(SyntaxError(InvalidNumber, 1, 4)));
2939 assert_eq!(from_str("18446744073709551616"), Err(SyntaxError(InvalidNumber, 1, 20)));
2940 assert_eq!(from_str("-9223372036854775809"), Err(SyntaxError(InvalidNumber, 1, 21)));
2942 assert_eq!(from_str("3"), Ok(U64(3)));
2943 assert_eq!(from_str("3.1"), Ok(F64(3.1)));
2944 assert_eq!(from_str("-1.2"), Ok(F64(-1.2)));
2945 assert_eq!(from_str("0.4"), Ok(F64(0.4)));
2946 assert_eq!(from_str("0.4e5"), Ok(F64(0.4e5)));
2947 assert_eq!(from_str("0.4e+15"), Ok(F64(0.4e15)));
2948 assert_eq!(from_str("0.4e-01"), Ok(F64(0.4e-01)));
2949 assert_eq!(from_str(" 3 "), Ok(U64(3)));
2951 assert_eq!(from_str("-9223372036854775808"), Ok(I64(i64::MIN)));
2952 assert_eq!(from_str("9223372036854775807"), Ok(U64(i64::MAX as u64)));
2953 assert_eq!(from_str("18446744073709551615"), Ok(U64(u64::MAX)));
2957 fn test_decode_numbers() {
2958 let v: f64 = super::decode("3").unwrap();
2961 let v: f64 = super::decode("3.1").unwrap();
2964 let v: f64 = super::decode("-1.2").unwrap();
2965 assert_eq!(v, -1.2);
2967 let v: f64 = super::decode("0.4").unwrap();
2970 let v: f64 = super::decode("0.4e5").unwrap();
2971 assert_eq!(v, 0.4e5);
2973 let v: f64 = super::decode("0.4e15").unwrap();
2974 assert_eq!(v, 0.4e15);
2976 let v: f64 = super::decode("0.4e-01").unwrap();
2977 assert_eq!(v, 0.4e-01);
2979 let v: u64 = super::decode("0").unwrap();
2982 let v: u64 = super::decode("18446744073709551615").unwrap();
2983 assert_eq!(v, u64::MAX);
2985 let v: i64 = super::decode("-9223372036854775808").unwrap();
2986 assert_eq!(v, i64::MIN);
2988 let v: i64 = super::decode("9223372036854775807").unwrap();
2989 assert_eq!(v, i64::MAX);
2991 let res: DecodeResult<i64> = super::decode("765.25");
2992 assert_eq!(res, Err(ExpectedError("Integer".to_string(),
2993 "765.25".to_string())));
2997 fn test_read_str() {
2998 assert_eq!(from_str("\""), Err(SyntaxError(EOFWhileParsingString, 1, 2)));
2999 assert_eq!(from_str("\"lol"), Err(SyntaxError(EOFWhileParsingString, 1, 5)));
3001 assert_eq!(from_str("\"\""), Ok(String("".to_string())));
3002 assert_eq!(from_str("\"foo\""), Ok(String("foo".to_string())));
3003 assert_eq!(from_str("\"\\\"\""), Ok(String("\"".to_string())));
3004 assert_eq!(from_str("\"\\b\""), Ok(String("\x08".to_string())));
3005 assert_eq!(from_str("\"\\n\""), Ok(String("\n".to_string())));
3006 assert_eq!(from_str("\"\\r\""), Ok(String("\r".to_string())));
3007 assert_eq!(from_str("\"\\t\""), Ok(String("\t".to_string())));
3008 assert_eq!(from_str(" \"foo\" "), Ok(String("foo".to_string())));
3009 assert_eq!(from_str("\"\\u12ab\""), Ok(String("\u{12ab}".to_string())));
3010 assert_eq!(from_str("\"\\uAB12\""), Ok(String("\u{AB12}".to_string())));
3014 fn test_decode_str() {
3015 let s = [("\"\"", ""),
3018 ("\"\\b\"", "\x08"),
3022 ("\"\\u12ab\"", "\u{12ab}"),
3023 ("\"\\uAB12\"", "\u{AB12}")];
3026 let v: string::String = super::decode(i).unwrap();
3032 fn test_read_array() {
3033 assert_eq!(from_str("["), Err(SyntaxError(EOFWhileParsingValue, 1, 2)));
3034 assert_eq!(from_str("[1"), Err(SyntaxError(EOFWhileParsingArray, 1, 3)));
3035 assert_eq!(from_str("[1,"), Err(SyntaxError(EOFWhileParsingValue, 1, 4)));
3036 assert_eq!(from_str("[1,]"), Err(SyntaxError(InvalidSyntax, 1, 4)));
3037 assert_eq!(from_str("[6 7]"), Err(SyntaxError(InvalidSyntax, 1, 4)));
3039 assert_eq!(from_str("[]"), Ok(Array(vec![])));
3040 assert_eq!(from_str("[ ]"), Ok(Array(vec![])));
3041 assert_eq!(from_str("[true]"), Ok(Array(vec![Boolean(true)])));
3042 assert_eq!(from_str("[ false ]"), Ok(Array(vec![Boolean(false)])));
3043 assert_eq!(from_str("[null]"), Ok(Array(vec![Null])));
3044 assert_eq!(from_str("[3, 1]"),
3045 Ok(Array(vec![U64(3), U64(1)])));
3046 assert_eq!(from_str("\n[3, 2]\n"),
3047 Ok(Array(vec![U64(3), U64(2)])));
3048 assert_eq!(from_str("[2, [4, 1]]"),
3049 Ok(Array(vec![U64(2), Array(vec![U64(4), U64(1)])])));
3053 fn test_decode_array() {
3054 let v: Vec<()> = super::decode("[]").unwrap();
3057 let v: Vec<()> = super::decode("[null]").unwrap();
3058 assert_eq!(v, [()]);
3060 let v: Vec<bool> = super::decode("[true]").unwrap();
3061 assert_eq!(v, [true]);
3063 let v: Vec<isize> = super::decode("[3, 1]").unwrap();
3064 assert_eq!(v, [3, 1]);
3066 let v: Vec<Vec<usize>> = super::decode("[[3], [1, 2]]").unwrap();
3067 assert_eq!(v, [vec![3], vec![1, 2]]);
3071 fn test_decode_tuple() {
3072 let t: (usize, usize, usize) = super::decode("[1, 2, 3]").unwrap();
3073 assert_eq!(t, (1, 2, 3));
3075 let t: (usize, string::String) = super::decode("[1, \"two\"]").unwrap();
3076 assert_eq!(t, (1, "two".to_string()));
3080 fn test_decode_tuple_malformed_types() {
3081 assert!(super::decode::<(usize, string::String)>("[1, 2]").is_err());
3085 fn test_decode_tuple_malformed_length() {
3086 assert!(super::decode::<(usize, usize)>("[1, 2, 3]").is_err());
3090 fn test_read_object() {
3091 assert_eq!(from_str("{"), Err(SyntaxError(EOFWhileParsingObject, 1, 2)));
3092 assert_eq!(from_str("{ "), Err(SyntaxError(EOFWhileParsingObject, 1, 3)));
3093 assert_eq!(from_str("{1"), Err(SyntaxError(KeyMustBeAString, 1, 2)));
3094 assert_eq!(from_str("{ \"a\""), Err(SyntaxError(EOFWhileParsingObject, 1, 6)));
3095 assert_eq!(from_str("{\"a\""), Err(SyntaxError(EOFWhileParsingObject, 1, 5)));
3096 assert_eq!(from_str("{\"a\" "), Err(SyntaxError(EOFWhileParsingObject, 1, 6)));
3098 assert_eq!(from_str("{\"a\" 1"), Err(SyntaxError(ExpectedColon, 1, 6)));
3099 assert_eq!(from_str("{\"a\":"), Err(SyntaxError(EOFWhileParsingValue, 1, 6)));
3100 assert_eq!(from_str("{\"a\":1"), Err(SyntaxError(EOFWhileParsingObject, 1, 7)));
3101 assert_eq!(from_str("{\"a\":1 1"), Err(SyntaxError(InvalidSyntax, 1, 8)));
3102 assert_eq!(from_str("{\"a\":1,"), Err(SyntaxError(EOFWhileParsingObject, 1, 8)));
3104 assert_eq!(from_str("{}").unwrap(), mk_object(&[]));
3105 assert_eq!(from_str("{\"a\": 3}").unwrap(),
3106 mk_object(&[("a".to_string(), U64(3))]));
3108 assert_eq!(from_str(
3109 "{ \"a\": null, \"b\" : true }").unwrap(),
3111 ("a".to_string(), Null),
3112 ("b".to_string(), Boolean(true))]));
3113 assert_eq!(from_str("\n{ \"a\": null, \"b\" : true }\n").unwrap(),
3115 ("a".to_string(), Null),
3116 ("b".to_string(), Boolean(true))]));
3117 assert_eq!(from_str(
3118 "{\"a\" : 1.0 ,\"b\": [ true ]}").unwrap(),
3120 ("a".to_string(), F64(1.0)),
3121 ("b".to_string(), Array(vec![Boolean(true)]))
3123 assert_eq!(from_str(
3129 { \"c\": {\"d\": null} } \
3133 ("a".to_string(), F64(1.0)),
3134 ("b".to_string(), Array(vec![
3136 String("foo\nbar".to_string()),
3138 ("c".to_string(), mk_object(&[("d".to_string(), Null)]))
3145 fn test_decode_struct() {
3148 { \"a\": null, \"b\": 2, \"c\": [\"abc\", \"xyz\"] }
3152 let v: Outer = super::decode(s).unwrap();
3157 Inner { a: (), b: 2, c: vec!["abc".to_string(), "xyz".to_string()] }
3163 #[derive(RustcDecodable)]
3164 struct FloatStruct {
3169 fn test_decode_struct_with_nan() {
3170 let s = "{\"f\":null,\"a\":[null,123]}";
3171 let obj: FloatStruct = super::decode(s).unwrap();
3172 assert!(obj.f.is_nan());
3173 assert!(obj.a[0].is_nan());
3174 assert_eq!(obj.a[1], 123f64);
3178 fn test_decode_option() {
3179 let value: Option<string::String> = super::decode("null").unwrap();
3180 assert_eq!(value, None);
3182 let value: Option<string::String> = super::decode("\"jodhpurs\"").unwrap();
3183 assert_eq!(value, Some("jodhpurs".to_string()));
3187 fn test_decode_enum() {
3188 let value: Animal = super::decode("\"Dog\"").unwrap();
3189 assert_eq!(value, Dog);
3191 let s = "{\"variant\":\"Frog\",\"fields\":[\"Henry\",349]}";
3192 let value: Animal = super::decode(s).unwrap();
3193 assert_eq!(value, Frog("Henry".to_string(), 349));
3197 fn test_decode_map() {
3198 let s = "{\"a\": \"Dog\", \"b\": {\"variant\":\"Frog\",\
3199 \"fields\":[\"Henry\", 349]}}";
3200 let mut map: BTreeMap<string::String, Animal> = super::decode(s).unwrap();
3202 assert_eq!(map.remove(&"a".to_string()), Some(Dog));
3203 assert_eq!(map.remove(&"b".to_string()), Some(Frog("Henry".to_string(), 349)));
3207 fn test_multiline_errors() {
3208 assert_eq!(from_str("{\n \"foo\":\n \"bar\""),
3209 Err(SyntaxError(EOFWhileParsingObject, 3, 8)));
3212 #[derive(RustcDecodable)]
3214 struct DecodeStruct {
3218 w: Vec<DecodeStruct>
3220 #[derive(RustcDecodable)]
3225 fn check_err<T: Decodable>(to_parse: &'static str, expected: DecoderError) {
3226 let res: DecodeResult<T> = match from_str(to_parse) {
3227 Err(e) => Err(ParseError(e)),
3228 Ok(json) => Decodable::decode(&mut Decoder::new(json))
3231 Ok(_) => panic!("`{:?}` parsed & decoded ok, expecting error `{:?}`",
3232 to_parse, expected),
3233 Err(ParseError(e)) => panic!("`{:?}` is not valid json: {:?}",
3236 assert_eq!(e, expected);
3241 fn test_decode_errors_struct() {
3242 check_err::<DecodeStruct>("[]", ExpectedError("Object".to_string(), "[]".to_string()));
3243 check_err::<DecodeStruct>("{\"x\": true, \"y\": true, \"z\": \"\", \"w\": []}",
3244 ExpectedError("Number".to_string(), "true".to_string()));
3245 check_err::<DecodeStruct>("{\"x\": 1, \"y\": [], \"z\": \"\", \"w\": []}",
3246 ExpectedError("Boolean".to_string(), "[]".to_string()));
3247 check_err::<DecodeStruct>("{\"x\": 1, \"y\": true, \"z\": {}, \"w\": []}",
3248 ExpectedError("String".to_string(), "{}".to_string()));
3249 check_err::<DecodeStruct>("{\"x\": 1, \"y\": true, \"z\": \"\", \"w\": null}",
3250 ExpectedError("Array".to_string(), "null".to_string()));
3251 check_err::<DecodeStruct>("{\"x\": 1, \"y\": true, \"z\": \"\"}",
3252 MissingFieldError("w".to_string()));
3255 fn test_decode_errors_enum() {
3256 check_err::<DecodeEnum>("{}",
3257 MissingFieldError("variant".to_string()));
3258 check_err::<DecodeEnum>("{\"variant\": 1}",
3259 ExpectedError("String".to_string(), "1".to_string()));
3260 check_err::<DecodeEnum>("{\"variant\": \"A\"}",
3261 MissingFieldError("fields".to_string()));
3262 check_err::<DecodeEnum>("{\"variant\": \"A\", \"fields\": null}",
3263 ExpectedError("Array".to_string(), "null".to_string()));
3264 check_err::<DecodeEnum>("{\"variant\": \"C\", \"fields\": []}",
3265 UnknownVariantError("C".to_string()));
3270 let json_value = from_str("{\"dog\" : \"cat\"}").unwrap();
3271 let found_str = json_value.find("dog");
3272 assert!(found_str.unwrap().as_string().unwrap() == "cat");
3276 fn test_find_path(){
3277 let json_value = from_str("{\"dog\":{\"cat\": {\"mouse\" : \"cheese\"}}}").unwrap();
3278 let found_str = json_value.find_path(&["dog", "cat", "mouse"]);
3279 assert!(found_str.unwrap().as_string().unwrap() == "cheese");
3284 let json_value = from_str("{\"dog\":{\"cat\": {\"mouse\" : \"cheese\"}}}").unwrap();
3285 let found_str = json_value.search("mouse").and_then(|j| j.as_string());
3286 assert!(found_str.unwrap() == "cheese");
3291 let json_value = from_str("{\"animals\":[\"dog\",\"cat\",\"mouse\"]}").unwrap();
3292 let ref array = json_value["animals"];
3293 assert_eq!(array[0].as_string().unwrap(), "dog");
3294 assert_eq!(array[1].as_string().unwrap(), "cat");
3295 assert_eq!(array[2].as_string().unwrap(), "mouse");
3299 fn test_is_object(){
3300 let json_value = from_str("{}").unwrap();
3301 assert!(json_value.is_object());
3305 fn test_as_object(){
3306 let json_value = from_str("{}").unwrap();
3307 let json_object = json_value.as_object();
3308 assert!(json_object.is_some());
3313 let json_value = from_str("[1, 2, 3]").unwrap();
3314 assert!(json_value.is_array());
3319 let json_value = from_str("[1, 2, 3]").unwrap();
3320 let json_array = json_value.as_array();
3321 let expected_length = 3;
3322 assert!(json_array.is_some() && json_array.unwrap().len() == expected_length);
3326 fn test_is_string(){
3327 let json_value = from_str("\"dog\"").unwrap();
3328 assert!(json_value.is_string());
3332 fn test_as_string(){
3333 let json_value = from_str("\"dog\"").unwrap();
3334 let json_str = json_value.as_string();
3335 let expected_str = "dog";
3336 assert_eq!(json_str, Some(expected_str));
3340 fn test_is_number(){
3341 let json_value = from_str("12").unwrap();
3342 assert!(json_value.is_number());
3347 let json_value = from_str("-12").unwrap();
3348 assert!(json_value.is_i64());
3350 let json_value = from_str("12").unwrap();
3351 assert!(!json_value.is_i64());
3353 let json_value = from_str("12.0").unwrap();
3354 assert!(!json_value.is_i64());
3359 let json_value = from_str("12").unwrap();
3360 assert!(json_value.is_u64());
3362 let json_value = from_str("-12").unwrap();
3363 assert!(!json_value.is_u64());
3365 let json_value = from_str("12.0").unwrap();
3366 assert!(!json_value.is_u64());
3371 let json_value = from_str("12").unwrap();
3372 assert!(!json_value.is_f64());
3374 let json_value = from_str("-12").unwrap();
3375 assert!(!json_value.is_f64());
3377 let json_value = from_str("12.0").unwrap();
3378 assert!(json_value.is_f64());
3380 let json_value = from_str("-12.0").unwrap();
3381 assert!(json_value.is_f64());
3386 let json_value = from_str("-12").unwrap();
3387 let json_num = json_value.as_i64();
3388 assert_eq!(json_num, Some(-12));
3393 let json_value = from_str("12").unwrap();
3394 let json_num = json_value.as_u64();
3395 assert_eq!(json_num, Some(12));
3400 let json_value = from_str("12.0").unwrap();
3401 let json_num = json_value.as_f64();
3402 assert_eq!(json_num, Some(12f64));
3406 fn test_is_boolean(){
3407 let json_value = from_str("false").unwrap();
3408 assert!(json_value.is_boolean());
3412 fn test_as_boolean(){
3413 let json_value = from_str("false").unwrap();
3414 let json_bool = json_value.as_boolean();
3415 let expected_bool = false;
3416 assert!(json_bool.is_some() && json_bool.unwrap() == expected_bool);
3421 let json_value = from_str("null").unwrap();
3422 assert!(json_value.is_null());
3427 let json_value = from_str("null").unwrap();
3428 let json_null = json_value.as_null();
3429 let expected_null = ();
3430 assert!(json_null.is_some() && json_null.unwrap() == expected_null);
3434 fn test_encode_hashmap_with_numeric_key() {
3435 use std::str::from_utf8;
3436 use std::collections::HashMap;
3437 let mut hm: HashMap<usize, bool> = HashMap::new();
3439 let mut mem_buf = Vec::new();
3440 write!(&mut mem_buf, "{}", super::as_pretty_json(&hm)).unwrap();
3441 let json_str = from_utf8(&mem_buf[..]).unwrap();
3442 match from_str(json_str) {
3443 Err(_) => panic!("Unable to parse json_str: {:?}", json_str),
3444 _ => {} // it parsed and we are good to go
3449 fn test_prettyencode_hashmap_with_numeric_key() {
3450 use std::str::from_utf8;
3451 use std::collections::HashMap;
3452 let mut hm: HashMap<usize, bool> = HashMap::new();
3454 let mut mem_buf = Vec::new();
3455 write!(&mut mem_buf, "{}", super::as_pretty_json(&hm)).unwrap();
3456 let json_str = from_utf8(&mem_buf[..]).unwrap();
3457 match from_str(json_str) {
3458 Err(_) => panic!("Unable to parse json_str: {:?}", json_str),
3459 _ => {} // it parsed and we are good to go
3464 fn test_prettyencoder_indent_level_param() {
3465 use std::str::from_utf8;
3466 use std::collections::BTreeMap;
3468 let mut tree = BTreeMap::new();
3470 tree.insert("hello".to_string(), String("guten tag".to_string()));
3471 tree.insert("goodbye".to_string(), String("sayonara".to_string()));
3474 // The following layout below should look a lot like
3475 // the pretty-printed JSON (indent * x)
3478 String("greetings".to_string()), // 1x
3479 Object(tree), // 1x + 2x + 2x + 1x
3481 // End JSON array (7 lines)
3484 // Helper function for counting indents
3485 fn indents(source: &str) -> usize {
3486 let trimmed = source.trim_start_matches(' ');
3487 source.len() - trimmed.len()
3490 // Test up to 4 spaces of indents (more?)
3492 let mut writer = Vec::new();
3493 write!(&mut writer, "{}",
3494 super::as_pretty_json(&json).indent(i)).unwrap();
3496 let printed = from_utf8(&writer[..]).unwrap();
3498 // Check for indents at each line
3499 let lines: Vec<&str> = printed.lines().collect();
3500 assert_eq!(lines.len(), 7); // JSON should be 7 lines
3502 assert_eq!(indents(lines[0]), 0 * i); // [
3503 assert_eq!(indents(lines[1]), 1 * i); // "greetings",
3504 assert_eq!(indents(lines[2]), 1 * i); // {
3505 assert_eq!(indents(lines[3]), 2 * i); // "hello": "guten tag",
3506 assert_eq!(indents(lines[4]), 2 * i); // "goodbye": "sayonara"
3507 assert_eq!(indents(lines[5]), 1 * i); // },
3508 assert_eq!(indents(lines[6]), 0 * i); // ]
3510 // Finally, test that the pretty-printed JSON is valid
3511 from_str(printed).ok().expect("Pretty-printed JSON is invalid!");
3516 fn test_hashmap_with_enum_key() {
3517 use std::collections::HashMap;
3519 #[derive(RustcEncodable, Eq, Hash, PartialEq, RustcDecodable, Debug)]
3525 let mut map = HashMap::new();
3526 map.insert(Enum::Foo, 0);
3527 let result = json::encode(&map).unwrap();
3528 assert_eq!(&result[..], r#"{"Foo":0}"#);
3529 let decoded: HashMap<Enum, _> = json::decode(&result).unwrap();
3530 assert_eq!(map, decoded);
3534 fn test_hashmap_with_numeric_key_can_handle_double_quote_delimited_key() {
3535 use std::collections::HashMap;
3537 let json_str = "{\"1\":true}";
3538 let json_obj = match from_str(json_str) {
3539 Err(_) => panic!("Unable to parse json_str: {:?}", json_str),
3542 let mut decoder = Decoder::new(json_obj);
3543 let _hm: HashMap<usize, bool> = Decodable::decode(&mut decoder).unwrap();
3547 fn test_hashmap_with_numeric_key_will_error_with_string_keys() {
3548 use std::collections::HashMap;
3550 let json_str = "{\"a\":true}";
3551 let json_obj = match from_str(json_str) {
3552 Err(_) => panic!("Unable to parse json_str: {:?}", json_str),
3555 let mut decoder = Decoder::new(json_obj);
3556 let result: Result<HashMap<usize, bool>, DecoderError> = Decodable::decode(&mut decoder);
3557 assert_eq!(result, Err(ExpectedError("Number".to_string(), "a".to_string())));
3560 fn assert_stream_equal(src: &str,
3561 expected: Vec<(JsonEvent, Vec<StackElement>)>) {
3562 let mut parser = Parser::new(src.chars());
3565 let evt = match parser.next() {
3569 let (ref expected_evt, ref expected_stack) = expected[i];
3570 if !parser.stack().is_equal_to(expected_stack) {
3571 panic!("Parser stack is not equal to {:?}", expected_stack);
3573 assert_eq!(&evt, expected_evt);
3578 fn test_streaming_parser() {
3579 assert_stream_equal(
3580 r#"{ "foo":"bar", "array" : [0, 1, 2, 3, 4, 5], "idents":[null,true,false]}"#,
3582 (ObjectStart, vec![]),
3583 (StringValue("bar".to_string()), vec![StackElement::Key("foo")]),
3584 (ArrayStart, vec![StackElement::Key("array")]),
3585 (U64Value(0), vec![StackElement::Key("array"), StackElement::Index(0)]),
3586 (U64Value(1), vec![StackElement::Key("array"), StackElement::Index(1)]),
3587 (U64Value(2), vec![StackElement::Key("array"), StackElement::Index(2)]),
3588 (U64Value(3), vec![StackElement::Key("array"), StackElement::Index(3)]),
3589 (U64Value(4), vec![StackElement::Key("array"), StackElement::Index(4)]),
3590 (U64Value(5), vec![StackElement::Key("array"), StackElement::Index(5)]),
3591 (ArrayEnd, vec![StackElement::Key("array")]),
3592 (ArrayStart, vec![StackElement::Key("idents")]),
3593 (NullValue, vec![StackElement::Key("idents"),
3594 StackElement::Index(0)]),
3595 (BooleanValue(true), vec![StackElement::Key("idents"),
3596 StackElement::Index(1)]),
3597 (BooleanValue(false), vec![StackElement::Key("idents"),
3598 StackElement::Index(2)]),
3599 (ArrayEnd, vec![StackElement::Key("idents")]),
3600 (ObjectEnd, vec![]),
3604 fn last_event(src: &str) -> JsonEvent {
3605 let mut parser = Parser::new(src.chars());
3606 let mut evt = NullValue;
3608 evt = match parser.next() {
3616 fn test_read_object_streaming() {
3617 assert_eq!(last_event("{ "), Error(SyntaxError(EOFWhileParsingObject, 1, 3)));
3618 assert_eq!(last_event("{1"), Error(SyntaxError(KeyMustBeAString, 1, 2)));
3619 assert_eq!(last_event("{ \"a\""), Error(SyntaxError(EOFWhileParsingObject, 1, 6)));
3620 assert_eq!(last_event("{\"a\""), Error(SyntaxError(EOFWhileParsingObject, 1, 5)));
3621 assert_eq!(last_event("{\"a\" "), Error(SyntaxError(EOFWhileParsingObject, 1, 6)));
3623 assert_eq!(last_event("{\"a\" 1"), Error(SyntaxError(ExpectedColon, 1, 6)));
3624 assert_eq!(last_event("{\"a\":"), Error(SyntaxError(EOFWhileParsingValue, 1, 6)));
3625 assert_eq!(last_event("{\"a\":1"), Error(SyntaxError(EOFWhileParsingObject, 1, 7)));
3626 assert_eq!(last_event("{\"a\":1 1"), Error(SyntaxError(InvalidSyntax, 1, 8)));
3627 assert_eq!(last_event("{\"a\":1,"), Error(SyntaxError(EOFWhileParsingObject, 1, 8)));
3628 assert_eq!(last_event("{\"a\":1,}"), Error(SyntaxError(TrailingComma, 1, 8)));
3630 assert_stream_equal(
3632 vec![(ObjectStart, vec![]), (ObjectEnd, vec![])]
3634 assert_stream_equal(
3637 (ObjectStart, vec![]),
3638 (U64Value(3), vec![StackElement::Key("a")]),
3639 (ObjectEnd, vec![]),
3642 assert_stream_equal(
3643 "{ \"a\": null, \"b\" : true }",
3645 (ObjectStart, vec![]),
3646 (NullValue, vec![StackElement::Key("a")]),
3647 (BooleanValue(true), vec![StackElement::Key("b")]),
3648 (ObjectEnd, vec![]),
3651 assert_stream_equal(
3652 "{\"a\" : 1.0 ,\"b\": [ true ]}",
3654 (ObjectStart, vec![]),
3655 (F64Value(1.0), vec![StackElement::Key("a")]),
3656 (ArrayStart, vec![StackElement::Key("b")]),
3657 (BooleanValue(true),vec![StackElement::Key("b"), StackElement::Index(0)]),
3658 (ArrayEnd, vec![StackElement::Key("b")]),
3659 (ObjectEnd, vec![]),
3662 assert_stream_equal(
3668 { "c": {"d": null} }
3672 (ObjectStart, vec![]),
3673 (F64Value(1.0), vec![StackElement::Key("a")]),
3674 (ArrayStart, vec![StackElement::Key("b")]),
3675 (BooleanValue(true), vec![StackElement::Key("b"),
3676 StackElement::Index(0)]),
3677 (StringValue("foo\nbar".to_string()), vec![StackElement::Key("b"),
3678 StackElement::Index(1)]),
3679 (ObjectStart, vec![StackElement::Key("b"),
3680 StackElement::Index(2)]),
3681 (ObjectStart, vec![StackElement::Key("b"),
3682 StackElement::Index(2),
3683 StackElement::Key("c")]),
3684 (NullValue, vec![StackElement::Key("b"),
3685 StackElement::Index(2),
3686 StackElement::Key("c"),
3687 StackElement::Key("d")]),
3688 (ObjectEnd, vec![StackElement::Key("b"),
3689 StackElement::Index(2),
3690 StackElement::Key("c")]),
3691 (ObjectEnd, vec![StackElement::Key("b"),
3692 StackElement::Index(2)]),
3693 (ArrayEnd, vec![StackElement::Key("b")]),
3694 (ObjectEnd, vec![]),
3699 fn test_read_array_streaming() {
3700 assert_stream_equal(
3703 (ArrayStart, vec![]),
3707 assert_stream_equal(
3710 (ArrayStart, vec![]),
3714 assert_stream_equal(
3717 (ArrayStart, vec![]),
3718 (BooleanValue(true), vec![StackElement::Index(0)]),
3722 assert_stream_equal(
3725 (ArrayStart, vec![]),
3726 (BooleanValue(false), vec![StackElement::Index(0)]),
3730 assert_stream_equal(
3733 (ArrayStart, vec![]),
3734 (NullValue, vec![StackElement::Index(0)]),
3738 assert_stream_equal(
3741 (ArrayStart, vec![]),
3742 (U64Value(3), vec![StackElement::Index(0)]),
3743 (U64Value(1), vec![StackElement::Index(1)]),
3747 assert_stream_equal(
3750 (ArrayStart, vec![]),
3751 (U64Value(3), vec![StackElement::Index(0)]),
3752 (U64Value(2), vec![StackElement::Index(1)]),
3756 assert_stream_equal(
3759 (ArrayStart, vec![]),
3760 (U64Value(2), vec![StackElement::Index(0)]),
3761 (ArrayStart, vec![StackElement::Index(1)]),
3762 (U64Value(4), vec![StackElement::Index(1), StackElement::Index(0)]),
3763 (U64Value(1), vec![StackElement::Index(1), StackElement::Index(1)]),
3764 (ArrayEnd, vec![StackElement::Index(1)]),
3769 assert_eq!(last_event("["), Error(SyntaxError(EOFWhileParsingValue, 1, 2)));
3771 assert_eq!(from_str("["), Err(SyntaxError(EOFWhileParsingValue, 1, 2)));
3772 assert_eq!(from_str("[1"), Err(SyntaxError(EOFWhileParsingArray, 1, 3)));
3773 assert_eq!(from_str("[1,"), Err(SyntaxError(EOFWhileParsingValue, 1, 4)));
3774 assert_eq!(from_str("[1,]"), Err(SyntaxError(InvalidSyntax, 1, 4)));
3775 assert_eq!(from_str("[6 7]"), Err(SyntaxError(InvalidSyntax, 1, 4)));
3779 fn test_trailing_characters_streaming() {
3780 assert_eq!(last_event("nulla"), Error(SyntaxError(TrailingCharacters, 1, 5)));
3781 assert_eq!(last_event("truea"), Error(SyntaxError(TrailingCharacters, 1, 5)));
3782 assert_eq!(last_event("falsea"), Error(SyntaxError(TrailingCharacters, 1, 6)));
3783 assert_eq!(last_event("1a"), Error(SyntaxError(TrailingCharacters, 1, 2)));
3784 assert_eq!(last_event("[]a"), Error(SyntaxError(TrailingCharacters, 1, 3)));
3785 assert_eq!(last_event("{}a"), Error(SyntaxError(TrailingCharacters, 1, 3)));
3788 fn test_read_identifiers_streaming() {
3789 assert_eq!(Parser::new("null".chars()).next(), Some(NullValue));
3790 assert_eq!(Parser::new("true".chars()).next(), Some(BooleanValue(true)));
3791 assert_eq!(Parser::new("false".chars()).next(), Some(BooleanValue(false)));
3793 assert_eq!(last_event("n"), Error(SyntaxError(InvalidSyntax, 1, 2)));
3794 assert_eq!(last_event("nul"), Error(SyntaxError(InvalidSyntax, 1, 4)));
3795 assert_eq!(last_event("t"), Error(SyntaxError(InvalidSyntax, 1, 2)));
3796 assert_eq!(last_event("truz"), Error(SyntaxError(InvalidSyntax, 1, 4)));
3797 assert_eq!(last_event("f"), Error(SyntaxError(InvalidSyntax, 1, 2)));
3798 assert_eq!(last_event("faz"), Error(SyntaxError(InvalidSyntax, 1, 3)));
3803 let mut stack = Stack::new();
3805 assert!(stack.is_empty());
3806 assert!(stack.is_empty());
3807 assert!(!stack.last_is_index());
3809 stack.push_index(0);
3812 assert!(stack.len() == 1);
3813 assert!(stack.is_equal_to(&[StackElement::Index(1)]));
3814 assert!(stack.starts_with(&[StackElement::Index(1)]));
3815 assert!(stack.ends_with(&[StackElement::Index(1)]));
3816 assert!(stack.last_is_index());
3817 assert!(stack.get(0) == StackElement::Index(1));
3819 stack.push_key("foo".to_string());
3821 assert!(stack.len() == 2);
3822 assert!(stack.is_equal_to(&[StackElement::Index(1), StackElement::Key("foo")]));
3823 assert!(stack.starts_with(&[StackElement::Index(1), StackElement::Key("foo")]));
3824 assert!(stack.starts_with(&[StackElement::Index(1)]));
3825 assert!(stack.ends_with(&[StackElement::Index(1), StackElement::Key("foo")]));
3826 assert!(stack.ends_with(&[StackElement::Key("foo")]));
3827 assert!(!stack.last_is_index());
3828 assert!(stack.get(0) == StackElement::Index(1));
3829 assert!(stack.get(1) == StackElement::Key("foo"));
3831 stack.push_key("bar".to_string());
3833 assert!(stack.len() == 3);
3834 assert!(stack.is_equal_to(&[StackElement::Index(1),
3835 StackElement::Key("foo"),
3836 StackElement::Key("bar")]));
3837 assert!(stack.starts_with(&[StackElement::Index(1)]));
3838 assert!(stack.starts_with(&[StackElement::Index(1), StackElement::Key("foo")]));
3839 assert!(stack.starts_with(&[StackElement::Index(1),
3840 StackElement::Key("foo"),
3841 StackElement::Key("bar")]));
3842 assert!(stack.ends_with(&[StackElement::Key("bar")]));
3843 assert!(stack.ends_with(&[StackElement::Key("foo"), StackElement::Key("bar")]));
3844 assert!(stack.ends_with(&[StackElement::Index(1),
3845 StackElement::Key("foo"),
3846 StackElement::Key("bar")]));
3847 assert!(!stack.last_is_index());
3848 assert!(stack.get(0) == StackElement::Index(1));
3849 assert!(stack.get(1) == StackElement::Key("foo"));
3850 assert!(stack.get(2) == StackElement::Key("bar"));
3854 assert!(stack.len() == 2);
3855 assert!(stack.is_equal_to(&[StackElement::Index(1), StackElement::Key("foo")]));
3856 assert!(stack.starts_with(&[StackElement::Index(1), StackElement::Key("foo")]));
3857 assert!(stack.starts_with(&[StackElement::Index(1)]));
3858 assert!(stack.ends_with(&[StackElement::Index(1), StackElement::Key("foo")]));
3859 assert!(stack.ends_with(&[StackElement::Key("foo")]));
3860 assert!(!stack.last_is_index());
3861 assert!(stack.get(0) == StackElement::Index(1));
3862 assert!(stack.get(1) == StackElement::Key("foo"));
3867 use std::collections::{HashMap,BTreeMap};
3870 let array2 = Array(vec![U64(1), U64(2)]);
3871 let array3 = Array(vec![U64(1), U64(2), U64(3)]);
3873 let mut tree_map = BTreeMap::new();
3874 tree_map.insert("a".to_string(), U64(1));
3875 tree_map.insert("b".to_string(), U64(2));
3879 assert_eq!(array2.to_json(), array2);
3880 assert_eq!(object.to_json(), object);
3881 assert_eq!(3_isize.to_json(), I64(3));
3882 assert_eq!(4_i8.to_json(), I64(4));
3883 assert_eq!(5_i16.to_json(), I64(5));
3884 assert_eq!(6_i32.to_json(), I64(6));
3885 assert_eq!(7_i64.to_json(), I64(7));
3886 assert_eq!(8_usize.to_json(), U64(8));
3887 assert_eq!(9_u8.to_json(), U64(9));
3888 assert_eq!(10_u16.to_json(), U64(10));
3889 assert_eq!(11_u32.to_json(), U64(11));
3890 assert_eq!(12_u64.to_json(), U64(12));
3891 assert_eq!(13.0_f32.to_json(), F64(13.0_f64));
3892 assert_eq!(14.0_f64.to_json(), F64(14.0_f64));
3893 assert_eq!(().to_json(), Null);
3894 assert_eq!(f32::INFINITY.to_json(), Null);
3895 assert_eq!(f64::NAN.to_json(), Null);
3896 assert_eq!(true.to_json(), Boolean(true));
3897 assert_eq!(false.to_json(), Boolean(false));
3898 assert_eq!("abc".to_json(), String("abc".to_string()));
3899 assert_eq!("abc".to_string().to_json(), String("abc".to_string()));
3900 assert_eq!((1_usize, 2_usize).to_json(), array2);
3901 assert_eq!((1_usize, 2_usize, 3_usize).to_json(), array3);
3902 assert_eq!([1_usize, 2_usize].to_json(), array2);
3903 assert_eq!((&[1_usize, 2_usize, 3_usize]).to_json(), array3);
3904 assert_eq!((vec![1_usize, 2_usize]).to_json(), array2);
3905 assert_eq!(vec![1_usize, 2_usize, 3_usize].to_json(), array3);
3906 let mut tree_map = BTreeMap::new();
3907 tree_map.insert("a".to_string(), 1 as usize);
3908 tree_map.insert("b".to_string(), 2);
3909 assert_eq!(tree_map.to_json(), object);
3910 let mut hash_map = HashMap::new();
3911 hash_map.insert("a".to_string(), 1 as usize);
3912 hash_map.insert("b".to_string(), 2);
3913 assert_eq!(hash_map.to_json(), object);
3914 assert_eq!(Some(15).to_json(), I64(15));
3915 assert_eq!(Some(15 as usize).to_json(), U64(15));
3916 assert_eq!(None::<isize>.to_json(), Null);
3920 fn test_encode_hashmap_with_arbitrary_key() {
3921 use std::collections::HashMap;
3922 #[derive(PartialEq, Eq, Hash, RustcEncodable)]
3923 struct ArbitraryType(usize);
3924 let mut hm: HashMap<ArbitraryType, bool> = HashMap::new();
3925 hm.insert(ArbitraryType(1), true);
3926 let mut mem_buf = string::String::new();
3927 let mut encoder = Encoder::new(&mut mem_buf);
3928 let result = hm.encode(&mut encoder);
3929 match result.unwrap_err() {
3930 EncoderError::BadHashmapKey => (),
3931 _ => panic!("expected bad hash map key")
3936 fn bench_streaming_small(b: &mut Bencher) {
3938 let mut parser = Parser::new(
3944 { "c": {"d": null} }
3949 match parser.next() {
3957 fn bench_small(b: &mut Bencher) {
3959 let _ = from_str(r#"{
3964 { "c": {"d": null} }
3970 fn big_json() -> string::String {
3971 let mut src = "[\n".to_string();
3973 src.push_str(r#"{ "a": true, "b": null, "c":3.1415, "d": "Hello world", "e": \
3976 src.push_str("{}]");
3981 fn bench_streaming_large(b: &mut Bencher) {
3982 let src = big_json();
3984 let mut parser = Parser::new(src.chars());
3986 match parser.next() {
3994 fn bench_large(b: &mut Bencher) {
3995 let src = big_json();
3996 b.iter( || { let _ = from_str(&src); });