]> git.proxmox.com Git - rustc.git/blame - src/libserialize/json.rs
New upstream version 1.14.0+dfsg1
[rustc.git] / src / libserialize / json.rs
CommitLineData
1a4d82fc
JJ
1// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2// file at the top-level directory of this distribution and at
3// http://rust-lang.org/COPYRIGHT.
4//
5// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8// option. This file may not be copied, modified, or distributed
9// except according to those terms.
10
11// Rust JSON serialization library
12// Copyright (c) 2011 Google Inc.
13
14#![forbid(non_camel_case_types)]
15#![allow(missing_docs)]
16
17//! JSON parsing and serialization
18//!
19//! # What is JSON?
20//!
21//! JSON (JavaScript Object Notation) is a way to write data in Javascript.
22//! Like XML, it allows to encode structured data in a text format that can be easily read by humans
23//! Its simple syntax and native compatibility with JavaScript have made it a widely used format.
24//!
25//! Data types that can be encoded are JavaScript types (see the `Json` enum for more details):
26//!
27//! * `Boolean`: equivalent to rust's `bool`
28//! * `Number`: equivalent to rust's `f64`
29//! * `String`: equivalent to rust's `String`
30//! * `Array`: equivalent to rust's `Vec<T>`, but also allowing objects of different types in the
31//! same array
32//! * `Object`: equivalent to rust's `BTreeMap<String, json::Json>`
33//! * `Null`
34//!
35//! An object is a series of string keys mapping to values, in `"key": value` format.
36//! Arrays are enclosed in square brackets ([ ... ]) and objects in curly brackets ({ ... }).
85aaf69f 37//! A simple JSON document encoding a person, their age, address and phone numbers could look like
1a4d82fc
JJ
38//!
39//! ```ignore
40//! {
41//! "FirstName": "John",
42//! "LastName": "Doe",
43//! "Age": 43,
44//! "Address": {
45//! "Street": "Downing Street 10",
46//! "City": "London",
47//! "Country": "Great Britain"
48//! },
49//! "PhoneNumbers": [
50//! "+44 1234567",
51//! "+44 2345678"
52//! ]
53//! }
54//! ```
55//!
56//! # Rust Type-based Encoding and Decoding
57//!
58//! Rust provides a mechanism for low boilerplate encoding & decoding of values to and from JSON via
59//! the serialization API.
60//! To be able to encode a piece of data, it must implement the `serialize::RustcEncodable` trait.
61//! To be able to decode a piece of data, it must implement the `serialize::RustcDecodable` trait.
62//! The Rust compiler provides an annotation to automatically generate the code for these traits:
63//! `#[derive(RustcDecodable, RustcEncodable)]`
64//!
65//! The JSON API provides an enum `json::Json` and a trait `ToJson` to encode objects.
66//! The `ToJson` trait provides a `to_json` method to convert an object into a `json::Json` value.
67//! A `json::Json` value can be encoded as a string or buffer using the functions described above.
68//! You can also use the `json::Encoder` object, which implements the `Encoder` trait.
69//!
70//! When using `ToJson` the `RustcEncodable` trait implementation is not mandatory.
71//!
72//! # Examples of use
73//!
74//! ## Using Autoserialization
75//!
76//! Create a struct called `TestStruct` and serialize and deserialize it to and from JSON using the
77//! serialization API, using the derived serialization code.
78//!
b039eaaf 79//! ```rust
92a42be0
SL
80//! # #![feature(rustc_private)]
81//! extern crate serialize as rustc_serialize; // for the deriving below
82//! use rustc_serialize::json;
1a4d82fc
JJ
83//!
84//! // Automatically generate `Decodable` and `Encodable` trait implementations
85//! #[derive(RustcDecodable, RustcEncodable)]
86//! pub struct TestStruct {
87//! data_int: u8,
88//! data_str: String,
89//! data_vector: Vec<u8>,
90//! }
91//!
92//! fn main() {
93//! let object = TestStruct {
94//! data_int: 1,
95//! data_str: "homura".to_string(),
96//! data_vector: vec![2,3,4,5],
97//! };
98//!
99//! // Serialize using `json::encode`
85aaf69f 100//! let encoded = json::encode(&object).unwrap();
1a4d82fc
JJ
101//!
102//! // Deserialize using `json::decode`
c34b1796 103//! let decoded: TestStruct = json::decode(&encoded[..]).unwrap();
1a4d82fc
JJ
104//! }
105//! ```
106//!
107//! ## Using the `ToJson` trait
108//!
109//! The examples above use the `ToJson` trait to generate the JSON string, which is required
110//! for custom mappings.
111//!
112//! ### Simple example of `ToJson` usage
113//!
b039eaaf 114//! ```rust
92a42be0 115//! # #![feature(rustc_private)]
1a4d82fc
JJ
116//! extern crate serialize;
117//! use serialize::json::{self, ToJson, Json};
118//!
119//! // A custom data structure
120//! struct ComplexNum {
121//! a: f64,
122//! b: f64,
123//! }
124//!
125//! // JSON value representation
126//! impl ToJson for ComplexNum {
127//! fn to_json(&self) -> Json {
128//! Json::String(format!("{}+{}i", self.a, self.b))
129//! }
130//! }
131//!
132//! // Only generate `RustcEncodable` trait implementation
133//! #[derive(Encodable)]
134//! pub struct ComplexNumRecord {
135//! uid: u8,
136//! dsc: String,
137//! val: Json,
138//! }
139//!
140//! fn main() {
141//! let num = ComplexNum { a: 0.0001, b: 12.539 };
142//! let data: String = json::encode(&ComplexNumRecord{
143//! uid: 1,
144//! dsc: "test".to_string(),
145//! val: num.to_json(),
85aaf69f 146//! }).unwrap();
1a4d82fc 147//! println!("data: {}", data);
62682a34 148//! // data: {"uid":1,"dsc":"test","val":"0.0001+12.539i"};
1a4d82fc
JJ
149//! }
150//! ```
151//!
152//! ### Verbose example of `ToJson` usage
153//!
b039eaaf 154//! ```rust
92a42be0 155//! # #![feature(rustc_private)]
1a4d82fc
JJ
156//! extern crate serialize;
157//! use std::collections::BTreeMap;
158//! use serialize::json::{self, Json, ToJson};
159//!
160//! // Only generate `Decodable` trait implementation
161//! #[derive(Decodable)]
162//! pub struct TestStruct {
163//! data_int: u8,
164//! data_str: String,
165//! data_vector: Vec<u8>,
166//! }
167//!
168//! // Specify encoding method manually
169//! impl ToJson for TestStruct {
170//! fn to_json(&self) -> Json {
171//! let mut d = BTreeMap::new();
172//! // All standard types implement `to_json()`, so use it
173//! d.insert("data_int".to_string(), self.data_int.to_json());
174//! d.insert("data_str".to_string(), self.data_str.to_json());
175//! d.insert("data_vector".to_string(), self.data_vector.to_json());
176//! Json::Object(d)
177//! }
178//! }
179//!
180//! fn main() {
181//! // Serialize using `ToJson`
182//! let input_data = TestStruct {
183//! data_int: 1,
184//! data_str: "madoka".to_string(),
185//! data_vector: vec![2,3,4,5],
186//! };
187//! let json_obj: Json = input_data.to_json();
188//! let json_str: String = json_obj.to_string();
189//!
190//! // Deserialize like before
92a42be0 191//! let decoded: TestStruct = json::decode(&json_str).unwrap();
1a4d82fc
JJ
192//! }
193//! ```
194
195use self::JsonEvent::*;
196use self::ErrorCode::*;
197use self::ParserError::*;
198use self::DecoderError::*;
199use self::ParserState::*;
200use self::InternalStackElement::*;
201
c30ab7b3 202use std::borrow::Cow;
1a4d82fc 203use std::collections::{HashMap, BTreeMap};
c34b1796
AL
204use std::io::prelude::*;
205use std::io;
206use std::mem::swap;
1a4d82fc 207use std::num::FpCategory as Fp;
c34b1796 208use std::ops::Index;
1a4d82fc
JJ
209use std::str::FromStr;
210use std::string;
9346a6ac 211use std::{char, f64, fmt, str};
c34b1796 212use std;
1a4d82fc
JJ
213
214use Encodable;
215
216/// Represents a json value
85aaf69f 217#[derive(Clone, PartialEq, PartialOrd, Debug)]
1a4d82fc
JJ
218pub enum Json {
219 I64(i64),
220 U64(u64),
221 F64(f64),
222 String(string::String),
223 Boolean(bool),
224 Array(self::Array),
225 Object(self::Object),
226 Null,
227}
228
229pub type Array = Vec<Json>;
230pub type Object = BTreeMap<string::String, Json>;
231
232pub struct PrettyJson<'a> { inner: &'a Json }
233
234pub struct AsJson<'a, T: 'a> { inner: &'a T }
c34b1796 235pub struct AsPrettyJson<'a, T: 'a> { inner: &'a T, indent: Option<usize> }
1a4d82fc
JJ
236
237/// The errors that can arise while parsing a JSON stream.
85aaf69f 238#[derive(Clone, Copy, PartialEq, Debug)]
1a4d82fc
JJ
239pub enum ErrorCode {
240 InvalidSyntax,
241 InvalidNumber,
242 EOFWhileParsingObject,
243 EOFWhileParsingArray,
244 EOFWhileParsingValue,
245 EOFWhileParsingString,
246 KeyMustBeAString,
247 ExpectedColon,
248 TrailingCharacters,
249 TrailingComma,
250 InvalidEscape,
251 InvalidUnicodeCodePoint,
252 LoneLeadingSurrogateInHexEscape,
253 UnexpectedEndOfHexEscape,
254 UnrecognizedHex,
255 NotFourDigit,
256 NotUtf8,
257}
258
c34b1796 259#[derive(Clone, PartialEq, Debug)]
1a4d82fc
JJ
260pub enum ParserError {
261 /// msg, line, col
c34b1796
AL
262 SyntaxError(ErrorCode, usize, usize),
263 IoError(io::ErrorKind, String),
1a4d82fc
JJ
264}
265
266// Builder and Parser have the same errors.
267pub type BuilderError = ParserError;
268
85aaf69f 269#[derive(Clone, PartialEq, Debug)]
1a4d82fc
JJ
270pub enum DecoderError {
271 ParseError(ParserError),
272 ExpectedError(string::String, string::String),
273 MissingFieldError(string::String),
274 UnknownVariantError(string::String),
275 ApplicationError(string::String)
276}
277
c34b1796 278#[derive(Copy, Clone, Debug)]
85aaf69f
SL
279pub enum EncoderError {
280 FmtError(fmt::Error),
281 BadHashmapKey,
282}
283
1a4d82fc
JJ
284/// Returns a readable error string for a given error code.
285pub fn error_str(error: ErrorCode) -> &'static str {
286 match error {
287 InvalidSyntax => "invalid syntax",
288 InvalidNumber => "invalid number",
289 EOFWhileParsingObject => "EOF While parsing object",
290 EOFWhileParsingArray => "EOF While parsing array",
291 EOFWhileParsingValue => "EOF While parsing value",
292 EOFWhileParsingString => "EOF While parsing string",
293 KeyMustBeAString => "key must be a string",
294 ExpectedColon => "expected `:`",
295 TrailingCharacters => "trailing characters",
296 TrailingComma => "trailing comma",
297 InvalidEscape => "invalid escape",
298 UnrecognizedHex => "invalid \\u{ esc}ape (unrecognized hex)",
299 NotFourDigit => "invalid \\u{ esc}ape (not four digits)",
300 NotUtf8 => "contents not utf-8",
301 InvalidUnicodeCodePoint => "invalid Unicode code point",
302 LoneLeadingSurrogateInHexEscape => "lone leading surrogate in hex escape",
303 UnexpectedEndOfHexEscape => "unexpected end of hex escape",
304 }
305}
306
307/// Shortcut function to decode a JSON `&str` into an object
308pub fn decode<T: ::Decodable>(s: &str) -> DecodeResult<T> {
309 let json = match from_str(s) {
310 Ok(x) => x,
311 Err(e) => return Err(ParseError(e))
312 };
313
314 let mut decoder = Decoder::new(json);
315 ::Decodable::decode(&mut decoder)
316}
317
318/// Shortcut function to encode a `T` into a JSON `String`
85aaf69f 319pub fn encode<T: ::Encodable>(object: &T) -> Result<string::String, EncoderError> {
1a4d82fc
JJ
320 let mut s = String::new();
321 {
322 let mut encoder = Encoder::new(&mut s);
54a0048b 323 object.encode(&mut encoder)?;
1a4d82fc 324 }
85aaf69f 325 Ok(s)
1a4d82fc
JJ
326}
327
85aaf69f 328impl fmt::Display for ErrorCode {
1a4d82fc
JJ
329 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
330 error_str(*self).fmt(f)
331 }
332}
333
c34b1796
AL
334fn io_error_to_error(io: io::Error) -> ParserError {
335 IoError(io.kind(), io.to_string())
1a4d82fc
JJ
336}
337
85aaf69f
SL
338impl fmt::Display for ParserError {
339 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
340 // FIXME this should be a nicer error
341 fmt::Debug::fmt(self, f)
342 }
343}
344
345impl fmt::Display for DecoderError {
346 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
347 // FIXME this should be a nicer error
348 fmt::Debug::fmt(self, f)
349 }
350}
351
1a4d82fc
JJ
352impl std::error::Error for DecoderError {
353 fn description(&self) -> &str { "decoder error" }
1a4d82fc
JJ
354}
355
85aaf69f
SL
356impl fmt::Display for EncoderError {
357 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
358 // FIXME this should be a nicer error
359 fmt::Debug::fmt(self, f)
360 }
361}
362
363impl std::error::Error for EncoderError {
364 fn description(&self) -> &str { "encoder error" }
365}
366
c34b1796
AL
367impl From<fmt::Error> for EncoderError {
368 fn from(err: fmt::Error) -> EncoderError { EncoderError::FmtError(err) }
85aaf69f
SL
369}
370
371pub type EncodeResult = Result<(), EncoderError>;
1a4d82fc
JJ
372pub type DecodeResult<T> = Result<T, DecoderError>;
373
85aaf69f 374fn escape_str(wr: &mut fmt::Write, v: &str) -> EncodeResult {
54a0048b 375 wr.write_str("\"")?;
1a4d82fc
JJ
376
377 let mut start = 0;
378
379 for (i, byte) in v.bytes().enumerate() {
380 let escaped = match byte {
381 b'"' => "\\\"",
382 b'\\' => "\\\\",
383 b'\x00' => "\\u0000",
384 b'\x01' => "\\u0001",
385 b'\x02' => "\\u0002",
386 b'\x03' => "\\u0003",
387 b'\x04' => "\\u0004",
388 b'\x05' => "\\u0005",
389 b'\x06' => "\\u0006",
390 b'\x07' => "\\u0007",
391 b'\x08' => "\\b",
392 b'\t' => "\\t",
393 b'\n' => "\\n",
394 b'\x0b' => "\\u000b",
395 b'\x0c' => "\\f",
396 b'\r' => "\\r",
397 b'\x0e' => "\\u000e",
398 b'\x0f' => "\\u000f",
399 b'\x10' => "\\u0010",
400 b'\x11' => "\\u0011",
401 b'\x12' => "\\u0012",
402 b'\x13' => "\\u0013",
403 b'\x14' => "\\u0014",
404 b'\x15' => "\\u0015",
405 b'\x16' => "\\u0016",
406 b'\x17' => "\\u0017",
407 b'\x18' => "\\u0018",
408 b'\x19' => "\\u0019",
409 b'\x1a' => "\\u001a",
410 b'\x1b' => "\\u001b",
411 b'\x1c' => "\\u001c",
412 b'\x1d' => "\\u001d",
413 b'\x1e' => "\\u001e",
414 b'\x1f' => "\\u001f",
415 b'\x7f' => "\\u007f",
416 _ => { continue; }
417 };
418
419 if start < i {
54a0048b 420 wr.write_str(&v[start..i])?;
1a4d82fc
JJ
421 }
422
54a0048b 423 wr.write_str(escaped)?;
1a4d82fc
JJ
424
425 start = i + 1;
426 }
427
428 if start != v.len() {
54a0048b 429 wr.write_str(&v[start..])?;
1a4d82fc
JJ
430 }
431
54a0048b 432 wr.write_str("\"")?;
85aaf69f 433 Ok(())
1a4d82fc
JJ
434}
435
85aaf69f 436fn escape_char(writer: &mut fmt::Write, v: char) -> EncodeResult {
c30ab7b3 437 escape_str(writer, v.encode_utf8(&mut [0; 4]))
1a4d82fc
JJ
438}
439
c34b1796 440fn spaces(wr: &mut fmt::Write, mut n: usize) -> EncodeResult {
1a4d82fc
JJ
441 const BUF: &'static str = " ";
442
443 while n >= BUF.len() {
54a0048b 444 wr.write_str(BUF)?;
1a4d82fc
JJ
445 n -= BUF.len();
446 }
447
448 if n > 0 {
54a0048b 449 wr.write_str(&BUF[..n])?;
1a4d82fc 450 }
85aaf69f 451 Ok(())
1a4d82fc
JJ
452}
453
454fn fmt_number_or_null(v: f64) -> string::String {
455 match v.classify() {
62682a34 456 Fp::Nan | Fp::Infinite => string::String::from("null"),
9346a6ac
AL
457 _ if v.fract() != 0f64 => v.to_string(),
458 _ => v.to_string() + ".0",
1a4d82fc
JJ
459 }
460}
461
462/// A structure for implementing serialization to JSON.
463pub struct Encoder<'a> {
85aaf69f
SL
464 writer: &'a mut (fmt::Write+'a),
465 is_emitting_map_key: bool,
1a4d82fc
JJ
466}
467
468impl<'a> Encoder<'a> {
469 /// Creates a new JSON encoder whose output will be written to the writer
470 /// specified.
85aaf69f
SL
471 pub fn new(writer: &'a mut fmt::Write) -> Encoder<'a> {
472 Encoder { writer: writer, is_emitting_map_key: false, }
473 }
474}
475
476macro_rules! emit_enquoted_if_mapkey {
9e0c209e 477 ($enc:ident,$e:expr) => ({
85aaf69f 478 if $enc.is_emitting_map_key {
9e0c209e 479 write!($enc.writer, "\"{}\"", $e)?;
85aaf69f 480 } else {
9e0c209e 481 write!($enc.writer, "{}", $e)?;
85aaf69f 482 }
9e0c209e
SL
483 Ok(())
484 })
1a4d82fc
JJ
485}
486
487impl<'a> ::Encoder for Encoder<'a> {
85aaf69f 488 type Error = EncoderError;
1a4d82fc 489
85aaf69f
SL
490 fn emit_nil(&mut self) -> EncodeResult {
491 if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
54a0048b 492 write!(self.writer, "null")?;
85aaf69f
SL
493 Ok(())
494 }
1a4d82fc 495
9e0c209e 496 fn emit_usize(&mut self, v: usize) -> EncodeResult { emit_enquoted_if_mapkey!(self, v) }
85aaf69f
SL
497 fn emit_u64(&mut self, v: u64) -> EncodeResult { emit_enquoted_if_mapkey!(self, v) }
498 fn emit_u32(&mut self, v: u32) -> EncodeResult { emit_enquoted_if_mapkey!(self, v) }
499 fn emit_u16(&mut self, v: u16) -> EncodeResult { emit_enquoted_if_mapkey!(self, v) }
500 fn emit_u8(&mut self, v: u8) -> EncodeResult { emit_enquoted_if_mapkey!(self, v) }
1a4d82fc 501
9e0c209e 502 fn emit_isize(&mut self, v: isize) -> EncodeResult { emit_enquoted_if_mapkey!(self, v) }
85aaf69f
SL
503 fn emit_i64(&mut self, v: i64) -> EncodeResult { emit_enquoted_if_mapkey!(self, v) }
504 fn emit_i32(&mut self, v: i32) -> EncodeResult { emit_enquoted_if_mapkey!(self, v) }
505 fn emit_i16(&mut self, v: i16) -> EncodeResult { emit_enquoted_if_mapkey!(self, v) }
506 fn emit_i8(&mut self, v: i8) -> EncodeResult { emit_enquoted_if_mapkey!(self, v) }
1a4d82fc
JJ
507
508 fn emit_bool(&mut self, v: bool) -> EncodeResult {
85aaf69f 509 if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
1a4d82fc 510 if v {
54a0048b 511 write!(self.writer, "true")?;
1a4d82fc 512 } else {
54a0048b 513 write!(self.writer, "false")?;
1a4d82fc 514 }
85aaf69f 515 Ok(())
1a4d82fc
JJ
516 }
517
518 fn emit_f64(&mut self, v: f64) -> EncodeResult {
85aaf69f 519 emit_enquoted_if_mapkey!(self, fmt_number_or_null(v))
1a4d82fc
JJ
520 }
521 fn emit_f32(&mut self, v: f32) -> EncodeResult {
522 self.emit_f64(v as f64)
523 }
524
525 fn emit_char(&mut self, v: char) -> EncodeResult {
526 escape_char(self.writer, v)
527 }
528 fn emit_str(&mut self, v: &str) -> EncodeResult {
529 escape_str(self.writer, v)
530 }
531
532 fn emit_enum<F>(&mut self, _name: &str, f: F) -> EncodeResult where
533 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
534 {
535 f(self)
536 }
537
538 fn emit_enum_variant<F>(&mut self,
539 name: &str,
c34b1796
AL
540 _id: usize,
541 cnt: usize,
1a4d82fc
JJ
542 f: F) -> EncodeResult where
543 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
544 {
545 // enums are encoded as strings or objects
546 // Bunny => "Bunny"
547 // Kangaroo(34,"William") => {"variant": "Kangaroo", "fields": [34,"William"]}
548 if cnt == 0 {
549 escape_str(self.writer, name)
550 } else {
85aaf69f 551 if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
54a0048b
SL
552 write!(self.writer, "{{\"variant\":")?;
553 escape_str(self.writer, name)?;
554 write!(self.writer, ",\"fields\":[")?;
555 f(self)?;
556 write!(self.writer, "]}}")?;
85aaf69f 557 Ok(())
1a4d82fc
JJ
558 }
559 }
560
c34b1796 561 fn emit_enum_variant_arg<F>(&mut self, idx: usize, f: F) -> EncodeResult where
1a4d82fc
JJ
562 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
563 {
85aaf69f 564 if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
1a4d82fc 565 if idx != 0 {
54a0048b 566 write!(self.writer, ",")?;
1a4d82fc
JJ
567 }
568 f(self)
569 }
570
571 fn emit_enum_struct_variant<F>(&mut self,
572 name: &str,
c34b1796
AL
573 id: usize,
574 cnt: usize,
1a4d82fc
JJ
575 f: F) -> EncodeResult where
576 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
577 {
85aaf69f 578 if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
1a4d82fc
JJ
579 self.emit_enum_variant(name, id, cnt, f)
580 }
581
582 fn emit_enum_struct_variant_field<F>(&mut self,
583 _: &str,
c34b1796 584 idx: usize,
1a4d82fc
JJ
585 f: F) -> EncodeResult where
586 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
587 {
85aaf69f 588 if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
1a4d82fc
JJ
589 self.emit_enum_variant_arg(idx, f)
590 }
591
c34b1796 592 fn emit_struct<F>(&mut self, _: &str, _: usize, f: F) -> EncodeResult where
1a4d82fc
JJ
593 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
594 {
85aaf69f 595 if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
54a0048b
SL
596 write!(self.writer, "{{")?;
597 f(self)?;
598 write!(self.writer, "}}")?;
85aaf69f 599 Ok(())
1a4d82fc
JJ
600 }
601
c34b1796 602 fn emit_struct_field<F>(&mut self, name: &str, idx: usize, f: F) -> EncodeResult where
1a4d82fc
JJ
603 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
604 {
85aaf69f 605 if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
54a0048b
SL
606 if idx != 0 { write!(self.writer, ",")?; }
607 escape_str(self.writer, name)?;
608 write!(self.writer, ":")?;
1a4d82fc
JJ
609 f(self)
610 }
611
c34b1796 612 fn emit_tuple<F>(&mut self, len: usize, f: F) -> EncodeResult where
1a4d82fc
JJ
613 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
614 {
85aaf69f 615 if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
1a4d82fc
JJ
616 self.emit_seq(len, f)
617 }
c34b1796 618 fn emit_tuple_arg<F>(&mut self, idx: usize, f: F) -> EncodeResult where
1a4d82fc
JJ
619 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
620 {
85aaf69f 621 if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
1a4d82fc
JJ
622 self.emit_seq_elt(idx, f)
623 }
624
c34b1796 625 fn emit_tuple_struct<F>(&mut self, _name: &str, len: usize, f: F) -> EncodeResult where
1a4d82fc
JJ
626 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
627 {
85aaf69f 628 if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
1a4d82fc
JJ
629 self.emit_seq(len, f)
630 }
c34b1796 631 fn emit_tuple_struct_arg<F>(&mut self, idx: usize, f: F) -> EncodeResult where
1a4d82fc
JJ
632 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
633 {
85aaf69f 634 if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
1a4d82fc
JJ
635 self.emit_seq_elt(idx, f)
636 }
637
638 fn emit_option<F>(&mut self, f: F) -> EncodeResult where
639 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
640 {
85aaf69f 641 if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
1a4d82fc
JJ
642 f(self)
643 }
85aaf69f
SL
644 fn emit_option_none(&mut self) -> EncodeResult {
645 if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
646 self.emit_nil()
647 }
1a4d82fc
JJ
648 fn emit_option_some<F>(&mut self, f: F) -> EncodeResult where
649 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
650 {
85aaf69f 651 if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
1a4d82fc
JJ
652 f(self)
653 }
654
c34b1796 655 fn emit_seq<F>(&mut self, _len: usize, f: F) -> EncodeResult where
1a4d82fc
JJ
656 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
657 {
85aaf69f 658 if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
54a0048b
SL
659 write!(self.writer, "[")?;
660 f(self)?;
661 write!(self.writer, "]")?;
85aaf69f 662 Ok(())
1a4d82fc
JJ
663 }
664
c34b1796 665 fn emit_seq_elt<F>(&mut self, idx: usize, f: F) -> EncodeResult where
1a4d82fc
JJ
666 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
667 {
85aaf69f 668 if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
1a4d82fc 669 if idx != 0 {
54a0048b 670 write!(self.writer, ",")?;
1a4d82fc
JJ
671 }
672 f(self)
673 }
674
c34b1796 675 fn emit_map<F>(&mut self, _len: usize, f: F) -> EncodeResult where
1a4d82fc
JJ
676 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
677 {
85aaf69f 678 if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
54a0048b
SL
679 write!(self.writer, "{{")?;
680 f(self)?;
681 write!(self.writer, "}}")?;
85aaf69f 682 Ok(())
1a4d82fc
JJ
683 }
684
c34b1796 685 fn emit_map_elt_key<F>(&mut self, idx: usize, f: F) -> EncodeResult where
85aaf69f 686 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
1a4d82fc 687 {
85aaf69f 688 if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
54a0048b 689 if idx != 0 { write!(self.writer, ",")? }
85aaf69f 690 self.is_emitting_map_key = true;
54a0048b 691 f(self)?;
85aaf69f 692 self.is_emitting_map_key = false;
1a4d82fc
JJ
693 Ok(())
694 }
695
c34b1796 696 fn emit_map_elt_val<F>(&mut self, _idx: usize, f: F) -> EncodeResult where
1a4d82fc
JJ
697 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
698 {
85aaf69f 699 if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
54a0048b 700 write!(self.writer, ":")?;
1a4d82fc
JJ
701 f(self)
702 }
703}
704
705/// Another encoder for JSON, but prints out human-readable JSON instead of
706/// compact data
707pub struct PrettyEncoder<'a> {
85aaf69f 708 writer: &'a mut (fmt::Write+'a),
c34b1796
AL
709 curr_indent: usize,
710 indent: usize,
85aaf69f 711 is_emitting_map_key: bool,
1a4d82fc
JJ
712}
713
714impl<'a> PrettyEncoder<'a> {
715 /// Creates a new encoder whose output will be written to the specified writer
85aaf69f
SL
716 pub fn new(writer: &'a mut fmt::Write) -> PrettyEncoder<'a> {
717 PrettyEncoder {
718 writer: writer,
719 curr_indent: 0,
720 indent: 2,
721 is_emitting_map_key: false,
722 }
1a4d82fc
JJ
723 }
724
725 /// Set the number of spaces to indent for each level.
726 /// This is safe to set during encoding.
c34b1796 727 pub fn set_indent(&mut self, indent: usize) {
1a4d82fc
JJ
728 // self.indent very well could be 0 so we need to use checked division.
729 let level = self.curr_indent.checked_div(self.indent).unwrap_or(0);
730 self.indent = indent;
731 self.curr_indent = level * self.indent;
732 }
733}
734
735impl<'a> ::Encoder for PrettyEncoder<'a> {
85aaf69f 736 type Error = EncoderError;
1a4d82fc 737
85aaf69f
SL
738 fn emit_nil(&mut self) -> EncodeResult {
739 if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
54a0048b 740 write!(self.writer, "null")?;
85aaf69f
SL
741 Ok(())
742 }
1a4d82fc 743
9e0c209e 744 fn emit_usize(&mut self, v: usize) -> EncodeResult { emit_enquoted_if_mapkey!(self, v) }
85aaf69f
SL
745 fn emit_u64(&mut self, v: u64) -> EncodeResult { emit_enquoted_if_mapkey!(self, v) }
746 fn emit_u32(&mut self, v: u32) -> EncodeResult { emit_enquoted_if_mapkey!(self, v) }
747 fn emit_u16(&mut self, v: u16) -> EncodeResult { emit_enquoted_if_mapkey!(self, v) }
748 fn emit_u8(&mut self, v: u8) -> EncodeResult { emit_enquoted_if_mapkey!(self, v) }
1a4d82fc 749
9e0c209e 750 fn emit_isize(&mut self, v: isize) -> EncodeResult { emit_enquoted_if_mapkey!(self, v) }
85aaf69f
SL
751 fn emit_i64(&mut self, v: i64) -> EncodeResult { emit_enquoted_if_mapkey!(self, v) }
752 fn emit_i32(&mut self, v: i32) -> EncodeResult { emit_enquoted_if_mapkey!(self, v) }
753 fn emit_i16(&mut self, v: i16) -> EncodeResult { emit_enquoted_if_mapkey!(self, v) }
754 fn emit_i8(&mut self, v: i8) -> EncodeResult { emit_enquoted_if_mapkey!(self, v) }
1a4d82fc
JJ
755
756 fn emit_bool(&mut self, v: bool) -> EncodeResult {
85aaf69f 757 if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
1a4d82fc 758 if v {
54a0048b 759 write!(self.writer, "true")?;
1a4d82fc 760 } else {
54a0048b 761 write!(self.writer, "false")?;
1a4d82fc 762 }
85aaf69f 763 Ok(())
1a4d82fc
JJ
764 }
765
766 fn emit_f64(&mut self, v: f64) -> EncodeResult {
85aaf69f 767 emit_enquoted_if_mapkey!(self, fmt_number_or_null(v))
1a4d82fc
JJ
768 }
769 fn emit_f32(&mut self, v: f32) -> EncodeResult {
770 self.emit_f64(v as f64)
771 }
772
773 fn emit_char(&mut self, v: char) -> EncodeResult {
774 escape_char(self.writer, v)
775 }
776 fn emit_str(&mut self, v: &str) -> EncodeResult {
777 escape_str(self.writer, v)
778 }
779
780 fn emit_enum<F>(&mut self, _name: &str, f: F) -> EncodeResult where
781 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
782 {
783 f(self)
784 }
785
786 fn emit_enum_variant<F>(&mut self,
787 name: &str,
c34b1796
AL
788 _id: usize,
789 cnt: usize,
1a4d82fc
JJ
790 f: F)
791 -> EncodeResult where
792 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
793 {
794 if cnt == 0 {
795 escape_str(self.writer, name)
796 } else {
85aaf69f 797 if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
54a0048b 798 write!(self.writer, "{{\n")?;
1a4d82fc 799 self.curr_indent += self.indent;
54a0048b
SL
800 spaces(self.writer, self.curr_indent)?;
801 write!(self.writer, "\"variant\": ")?;
802 escape_str(self.writer, name)?;
803 write!(self.writer, ",\n")?;
804 spaces(self.writer, self.curr_indent)?;
805 write!(self.writer, "\"fields\": [\n")?;
1a4d82fc 806 self.curr_indent += self.indent;
54a0048b 807 f(self)?;
1a4d82fc 808 self.curr_indent -= self.indent;
54a0048b
SL
809 write!(self.writer, "\n")?;
810 spaces(self.writer, self.curr_indent)?;
1a4d82fc 811 self.curr_indent -= self.indent;
54a0048b
SL
812 write!(self.writer, "]\n")?;
813 spaces(self.writer, self.curr_indent)?;
814 write!(self.writer, "}}")?;
85aaf69f 815 Ok(())
1a4d82fc
JJ
816 }
817 }
818
c34b1796 819 fn emit_enum_variant_arg<F>(&mut self, idx: usize, f: F) -> EncodeResult where
1a4d82fc
JJ
820 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
821 {
85aaf69f 822 if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
1a4d82fc 823 if idx != 0 {
54a0048b 824 write!(self.writer, ",\n")?;
1a4d82fc 825 }
54a0048b 826 spaces(self.writer, self.curr_indent)?;
1a4d82fc
JJ
827 f(self)
828 }
829
830 fn emit_enum_struct_variant<F>(&mut self,
831 name: &str,
c34b1796
AL
832 id: usize,
833 cnt: usize,
1a4d82fc
JJ
834 f: F) -> EncodeResult where
835 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
836 {
85aaf69f 837 if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
1a4d82fc
JJ
838 self.emit_enum_variant(name, id, cnt, f)
839 }
840
841 fn emit_enum_struct_variant_field<F>(&mut self,
842 _: &str,
c34b1796 843 idx: usize,
1a4d82fc
JJ
844 f: F) -> EncodeResult where
845 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
846 {
85aaf69f 847 if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
1a4d82fc
JJ
848 self.emit_enum_variant_arg(idx, f)
849 }
850
851
c34b1796 852 fn emit_struct<F>(&mut self, _: &str, len: usize, f: F) -> EncodeResult where
1a4d82fc
JJ
853 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
854 {
85aaf69f 855 if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
1a4d82fc 856 if len == 0 {
54a0048b 857 write!(self.writer, "{{}}")?;
1a4d82fc 858 } else {
54a0048b 859 write!(self.writer, "{{")?;
1a4d82fc 860 self.curr_indent += self.indent;
54a0048b 861 f(self)?;
1a4d82fc 862 self.curr_indent -= self.indent;
54a0048b
SL
863 write!(self.writer, "\n")?;
864 spaces(self.writer, self.curr_indent)?;
865 write!(self.writer, "}}")?;
1a4d82fc 866 }
85aaf69f 867 Ok(())
1a4d82fc
JJ
868 }
869
c34b1796 870 fn emit_struct_field<F>(&mut self, name: &str, idx: usize, f: F) -> EncodeResult where
1a4d82fc
JJ
871 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
872 {
85aaf69f 873 if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
1a4d82fc 874 if idx == 0 {
54a0048b 875 write!(self.writer, "\n")?;
1a4d82fc 876 } else {
54a0048b 877 write!(self.writer, ",\n")?;
1a4d82fc 878 }
54a0048b
SL
879 spaces(self.writer, self.curr_indent)?;
880 escape_str(self.writer, name)?;
881 write!(self.writer, ": ")?;
1a4d82fc
JJ
882 f(self)
883 }
884
c34b1796 885 fn emit_tuple<F>(&mut self, len: usize, f: F) -> EncodeResult where
1a4d82fc
JJ
886 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
887 {
85aaf69f 888 if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
1a4d82fc
JJ
889 self.emit_seq(len, f)
890 }
c34b1796 891 fn emit_tuple_arg<F>(&mut self, idx: usize, f: F) -> EncodeResult where
1a4d82fc
JJ
892 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
893 {
85aaf69f 894 if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
1a4d82fc
JJ
895 self.emit_seq_elt(idx, f)
896 }
897
c34b1796 898 fn emit_tuple_struct<F>(&mut self, _: &str, len: usize, f: F) -> EncodeResult where
1a4d82fc
JJ
899 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
900 {
85aaf69f 901 if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
1a4d82fc
JJ
902 self.emit_seq(len, f)
903 }
c34b1796 904 fn emit_tuple_struct_arg<F>(&mut self, idx: usize, f: F) -> EncodeResult where
1a4d82fc
JJ
905 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
906 {
85aaf69f 907 if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
1a4d82fc
JJ
908 self.emit_seq_elt(idx, f)
909 }
910
911 fn emit_option<F>(&mut self, f: F) -> EncodeResult where
912 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
913 {
85aaf69f 914 if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
1a4d82fc
JJ
915 f(self)
916 }
85aaf69f
SL
917 fn emit_option_none(&mut self) -> EncodeResult {
918 if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
919 self.emit_nil()
920 }
1a4d82fc
JJ
921 fn emit_option_some<F>(&mut self, f: F) -> EncodeResult where
922 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
923 {
85aaf69f 924 if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
1a4d82fc
JJ
925 f(self)
926 }
927
c34b1796 928 fn emit_seq<F>(&mut self, len: usize, f: F) -> EncodeResult where
1a4d82fc
JJ
929 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
930 {
85aaf69f 931 if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
1a4d82fc 932 if len == 0 {
54a0048b 933 write!(self.writer, "[]")?;
1a4d82fc 934 } else {
54a0048b 935 write!(self.writer, "[")?;
1a4d82fc 936 self.curr_indent += self.indent;
54a0048b 937 f(self)?;
1a4d82fc 938 self.curr_indent -= self.indent;
54a0048b
SL
939 write!(self.writer, "\n")?;
940 spaces(self.writer, self.curr_indent)?;
941 write!(self.writer, "]")?;
1a4d82fc 942 }
85aaf69f 943 Ok(())
1a4d82fc
JJ
944 }
945
c34b1796 946 fn emit_seq_elt<F>(&mut self, idx: usize, f: F) -> EncodeResult where
1a4d82fc
JJ
947 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
948 {
85aaf69f 949 if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
1a4d82fc 950 if idx == 0 {
54a0048b 951 write!(self.writer, "\n")?;
1a4d82fc 952 } else {
54a0048b 953 write!(self.writer, ",\n")?;
1a4d82fc 954 }
54a0048b 955 spaces(self.writer, self.curr_indent)?;
1a4d82fc
JJ
956 f(self)
957 }
958
c34b1796 959 fn emit_map<F>(&mut self, len: usize, f: F) -> EncodeResult where
1a4d82fc
JJ
960 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
961 {
85aaf69f 962 if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
1a4d82fc 963 if len == 0 {
54a0048b 964 write!(self.writer, "{{}}")?;
1a4d82fc 965 } else {
54a0048b 966 write!(self.writer, "{{")?;
1a4d82fc 967 self.curr_indent += self.indent;
54a0048b 968 f(self)?;
1a4d82fc 969 self.curr_indent -= self.indent;
54a0048b
SL
970 write!(self.writer, "\n")?;
971 spaces(self.writer, self.curr_indent)?;
972 write!(self.writer, "}}")?;
1a4d82fc 973 }
85aaf69f 974 Ok(())
1a4d82fc
JJ
975 }
976
c34b1796 977 fn emit_map_elt_key<F>(&mut self, idx: usize, f: F) -> EncodeResult where
85aaf69f 978 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
1a4d82fc 979 {
85aaf69f 980 if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
1a4d82fc 981 if idx == 0 {
54a0048b 982 write!(self.writer, "\n")?;
1a4d82fc 983 } else {
54a0048b 984 write!(self.writer, ",\n")?;
1a4d82fc 985 }
54a0048b 986 spaces(self.writer, self.curr_indent)?;
85aaf69f 987 self.is_emitting_map_key = true;
54a0048b 988 f(self)?;
85aaf69f 989 self.is_emitting_map_key = false;
1a4d82fc
JJ
990 Ok(())
991 }
992
c34b1796 993 fn emit_map_elt_val<F>(&mut self, _idx: usize, f: F) -> EncodeResult where
1a4d82fc
JJ
994 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
995 {
85aaf69f 996 if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
54a0048b 997 write!(self.writer, ": ")?;
1a4d82fc
JJ
998 f(self)
999 }
1000}
1001
1002impl Encodable for Json {
1003 fn encode<E: ::Encoder>(&self, e: &mut E) -> Result<(), E::Error> {
1004 match *self {
1005 Json::I64(v) => v.encode(e),
1006 Json::U64(v) => v.encode(e),
1007 Json::F64(v) => v.encode(e),
1008 Json::String(ref v) => v.encode(e),
1009 Json::Boolean(v) => v.encode(e),
1010 Json::Array(ref v) => v.encode(e),
1011 Json::Object(ref v) => v.encode(e),
1012 Json::Null => e.emit_nil(),
1013 }
1014 }
1015}
1016
1017/// Create an `AsJson` wrapper which can be used to print a value as JSON
1018/// on-the-fly via `write!`
1019pub fn as_json<T>(t: &T) -> AsJson<T> {
1020 AsJson { inner: t }
1021}
1022
1023/// Create an `AsPrettyJson` wrapper which can be used to print a value as JSON
1024/// on-the-fly via `write!`
1025pub fn as_pretty_json<T>(t: &T) -> AsPrettyJson<T> {
1026 AsPrettyJson { inner: t, indent: None }
1027}
1028
1029impl Json {
1030 /// Borrow this json object as a pretty object to generate a pretty
85aaf69f 1031 /// representation for it via `Display`.
1a4d82fc
JJ
1032 pub fn pretty(&self) -> PrettyJson {
1033 PrettyJson { inner: self }
1034 }
1035
1036 /// If the Json value is an Object, returns the value associated with the provided key.
1037 /// Otherwise, returns None.
1038 pub fn find<'a>(&'a self, key: &str) -> Option<&'a Json>{
e9174d1e
SL
1039 match *self {
1040 Json::Object(ref map) => map.get(key),
1a4d82fc
JJ
1041 _ => None
1042 }
1043 }
1044
1045 /// Attempts to get a nested Json Object for each key in `keys`.
1046 /// If any key is found not to exist, find_path will return None.
1047 /// Otherwise, it will return the Json value associated with the final key.
1048 pub fn find_path<'a>(&'a self, keys: &[&str]) -> Option<&'a Json>{
1049 let mut target = self;
85aaf69f 1050 for key in keys {
1a4d82fc
JJ
1051 match target.find(*key) {
1052 Some(t) => { target = t; },
1053 None => return None
1054 }
1055 }
1056 Some(target)
1057 }
1058
1059 /// If the Json value is an Object, performs a depth-first search until
1060 /// a value associated with the provided key is found. If no value is found
1061 /// or the Json value is not an Object, returns None.
1062 pub fn search<'a>(&'a self, key: &str) -> Option<&'a Json> {
1063 match self {
1064 &Json::Object(ref map) => {
1065 match map.get(key) {
1066 Some(json_value) => Some(json_value),
1067 None => {
85aaf69f 1068 for (_, v) in map {
1a4d82fc
JJ
1069 match v.search(key) {
1070 x if x.is_some() => return x,
1071 _ => ()
1072 }
1073 }
1074 None
1075 }
1076 }
1077 },
1078 _ => None
1079 }
1080 }
1081
1082 /// Returns true if the Json value is an Object. Returns false otherwise.
e9174d1e 1083 pub fn is_object(&self) -> bool {
1a4d82fc
JJ
1084 self.as_object().is_some()
1085 }
1086
1087 /// If the Json value is an Object, returns the associated BTreeMap.
1088 /// Returns None otherwise.
e9174d1e
SL
1089 pub fn as_object(&self) -> Option<&Object> {
1090 match *self {
1091 Json::Object(ref map) => Some(map),
1a4d82fc
JJ
1092 _ => None
1093 }
1094 }
1095
1096 /// Returns true if the Json value is an Array. Returns false otherwise.
e9174d1e 1097 pub fn is_array(&self) -> bool {
1a4d82fc
JJ
1098 self.as_array().is_some()
1099 }
1100
1101 /// If the Json value is an Array, returns the associated vector.
1102 /// Returns None otherwise.
e9174d1e
SL
1103 pub fn as_array(&self) -> Option<&Array> {
1104 match *self {
1105 Json::Array(ref array) => Some(&*array),
1a4d82fc
JJ
1106 _ => None
1107 }
1108 }
1109
1110 /// Returns true if the Json value is a String. Returns false otherwise.
e9174d1e 1111 pub fn is_string(&self) -> bool {
1a4d82fc
JJ
1112 self.as_string().is_some()
1113 }
1114
1115 /// If the Json value is a String, returns the associated str.
1116 /// Returns None otherwise.
e9174d1e 1117 pub fn as_string(&self) -> Option<&str> {
1a4d82fc 1118 match *self {
85aaf69f 1119 Json::String(ref s) => Some(&s[..]),
1a4d82fc
JJ
1120 _ => None
1121 }
1122 }
1123
1124 /// Returns true if the Json value is a Number. Returns false otherwise.
1125 pub fn is_number(&self) -> bool {
1126 match *self {
1127 Json::I64(_) | Json::U64(_) | Json::F64(_) => true,
1128 _ => false,
1129 }
1130 }
1131
1132 /// Returns true if the Json value is a i64. Returns false otherwise.
1133 pub fn is_i64(&self) -> bool {
1134 match *self {
1135 Json::I64(_) => true,
1136 _ => false,
1137 }
1138 }
1139
1140 /// Returns true if the Json value is a u64. Returns false otherwise.
1141 pub fn is_u64(&self) -> bool {
1142 match *self {
1143 Json::U64(_) => true,
1144 _ => false,
1145 }
1146 }
1147
1148 /// Returns true if the Json value is a f64. Returns false otherwise.
1149 pub fn is_f64(&self) -> bool {
1150 match *self {
1151 Json::F64(_) => true,
1152 _ => false,
1153 }
1154 }
1155
1156 /// If the Json value is a number, return or cast it to a i64.
1157 /// Returns None otherwise.
1158 pub fn as_i64(&self) -> Option<i64> {
1159 match *self {
1160 Json::I64(n) => Some(n),
9346a6ac 1161 Json::U64(n) => Some(n as i64),
1a4d82fc
JJ
1162 _ => None
1163 }
1164 }
1165
1166 /// If the Json value is a number, return or cast it to a u64.
1167 /// Returns None otherwise.
1168 pub fn as_u64(&self) -> Option<u64> {
1169 match *self {
9346a6ac 1170 Json::I64(n) => Some(n as u64),
1a4d82fc
JJ
1171 Json::U64(n) => Some(n),
1172 _ => None
1173 }
1174 }
1175
1176 /// If the Json value is a number, return or cast it to a f64.
1177 /// Returns None otherwise.
1178 pub fn as_f64(&self) -> Option<f64> {
1179 match *self {
9346a6ac
AL
1180 Json::I64(n) => Some(n as f64),
1181 Json::U64(n) => Some(n as f64),
1a4d82fc
JJ
1182 Json::F64(n) => Some(n),
1183 _ => None
1184 }
1185 }
1186
1187 /// Returns true if the Json value is a Boolean. Returns false otherwise.
1188 pub fn is_boolean(&self) -> bool {
1189 self.as_boolean().is_some()
1190 }
1191
1192 /// If the Json value is a Boolean, returns the associated bool.
1193 /// Returns None otherwise.
1194 pub fn as_boolean(&self) -> Option<bool> {
e9174d1e
SL
1195 match *self {
1196 Json::Boolean(b) => Some(b),
1a4d82fc
JJ
1197 _ => None
1198 }
1199 }
1200
1201 /// Returns true if the Json value is a Null. Returns false otherwise.
1202 pub fn is_null(&self) -> bool {
1203 self.as_null().is_some()
1204 }
1205
1206 /// If the Json value is a Null, returns ().
1207 /// Returns None otherwise.
1208 pub fn as_null(&self) -> Option<()> {
e9174d1e
SL
1209 match *self {
1210 Json::Null => Some(()),
1a4d82fc
JJ
1211 _ => None
1212 }
1213 }
1214}
1215
1216impl<'a> Index<&'a str> for Json {
1217 type Output = Json;
1218
c34b1796
AL
1219 fn index(&self, idx: &'a str) -> &Json {
1220 self.find(idx).unwrap()
1a4d82fc
JJ
1221 }
1222}
1223
c34b1796 1224impl Index<usize> for Json {
1a4d82fc
JJ
1225 type Output = Json;
1226
7453a54e 1227 fn index(&self, idx: usize) -> &Json {
e9174d1e
SL
1228 match *self {
1229 Json::Array(ref v) => &v[idx],
c34b1796 1230 _ => panic!("can only index Json with usize if it is an array")
1a4d82fc
JJ
1231 }
1232 }
1233}
1234
1235/// The output of the streaming parser.
85aaf69f 1236#[derive(PartialEq, Clone, Debug)]
1a4d82fc
JJ
1237pub enum JsonEvent {
1238 ObjectStart,
1239 ObjectEnd,
1240 ArrayStart,
1241 ArrayEnd,
1242 BooleanValue(bool),
1243 I64Value(i64),
1244 U64Value(u64),
1245 F64Value(f64),
1246 StringValue(string::String),
1247 NullValue,
1248 Error(ParserError),
1249}
1250
85aaf69f 1251#[derive(PartialEq, Debug)]
1a4d82fc
JJ
1252enum ParserState {
1253 // Parse a value in an array, true means first element.
1254 ParseArray(bool),
1255 // Parse ',' or ']' after an element in an array.
1256 ParseArrayComma,
1257 // Parse a key:value in an object, true means first element.
1258 ParseObject(bool),
1259 // Parse ',' or ']' after an element in an object.
1260 ParseObjectComma,
1261 // Initial state.
1262 ParseStart,
1263 // Expecting the stream to end.
1264 ParseBeforeFinish,
1265 // Parsing can't continue.
1266 ParseFinished,
1267}
1268
1269/// A Stack represents the current position of the parser in the logical
1270/// structure of the JSON stream.
1271/// For example foo.bar[3].x
1272pub struct Stack {
1273 stack: Vec<InternalStackElement>,
1274 str_buffer: Vec<u8>,
1275}
1276
1277/// StackElements compose a Stack.
1278/// For example, StackElement::Key("foo"), StackElement::Key("bar"),
1279/// StackElement::Index(3) and StackElement::Key("x") are the
1280/// StackElements compositing the stack that represents foo.bar[3].x
85aaf69f 1281#[derive(PartialEq, Clone, Debug)]
1a4d82fc
JJ
1282pub enum StackElement<'l> {
1283 Index(u32),
1284 Key(&'l str),
1285}
1286
1287// Internally, Key elements are stored as indices in a buffer to avoid
1288// allocating a string for every member of an object.
85aaf69f 1289#[derive(PartialEq, Clone, Debug)]
1a4d82fc
JJ
1290enum InternalStackElement {
1291 InternalIndex(u32),
1292 InternalKey(u16, u16), // start, size
1293}
1294
1295impl Stack {
1296 pub fn new() -> Stack {
1297 Stack { stack: Vec::new(), str_buffer: Vec::new() }
1298 }
1299
1300 /// Returns The number of elements in the Stack.
c34b1796 1301 pub fn len(&self) -> usize { self.stack.len() }
1a4d82fc
JJ
1302
1303 /// Returns true if the stack is empty.
1304 pub fn is_empty(&self) -> bool { self.stack.is_empty() }
1305
1306 /// Provides access to the StackElement at a given index.
1307 /// lower indices are at the bottom of the stack while higher indices are
1308 /// at the top.
7453a54e 1309 pub fn get(&self, idx: usize) -> StackElement {
1a4d82fc
JJ
1310 match self.stack[idx] {
1311 InternalIndex(i) => StackElement::Index(i),
1312 InternalKey(start, size) => {
1313 StackElement::Key(str::from_utf8(
c34b1796 1314 &self.str_buffer[start as usize .. start as usize + size as usize])
1a4d82fc
JJ
1315 .unwrap())
1316 }
1317 }
1318 }
1319
1320 /// Compares this stack with an array of StackElements.
1321 pub fn is_equal_to(&self, rhs: &[StackElement]) -> bool {
1322 if self.stack.len() != rhs.len() { return false; }
e9174d1e
SL
1323 for (i, r) in rhs.iter().enumerate() {
1324 if self.get(i) != *r { return false; }
1a4d82fc 1325 }
e9174d1e 1326 true
1a4d82fc
JJ
1327 }
1328
1329 /// Returns true if the bottom-most elements of this stack are the same as
1330 /// the ones passed as parameter.
1331 pub fn starts_with(&self, rhs: &[StackElement]) -> bool {
1332 if self.stack.len() < rhs.len() { return false; }
e9174d1e
SL
1333 for (i, r) in rhs.iter().enumerate() {
1334 if self.get(i) != *r { return false; }
1a4d82fc 1335 }
e9174d1e 1336 true
1a4d82fc
JJ
1337 }
1338
1339 /// Returns true if the top-most elements of this stack are the same as
1340 /// the ones passed as parameter.
1341 pub fn ends_with(&self, rhs: &[StackElement]) -> bool {
1342 if self.stack.len() < rhs.len() { return false; }
1343 let offset = self.stack.len() - rhs.len();
e9174d1e
SL
1344 for (i, r) in rhs.iter().enumerate() {
1345 if self.get(i + offset) != *r { return false; }
1a4d82fc 1346 }
e9174d1e 1347 true
1a4d82fc
JJ
1348 }
1349
1350 /// Returns the top-most element (if any).
7453a54e 1351 pub fn top(&self) -> Option<StackElement> {
e9174d1e 1352 match self.stack.last() {
1a4d82fc
JJ
1353 None => None,
1354 Some(&InternalIndex(i)) => Some(StackElement::Index(i)),
1355 Some(&InternalKey(start, size)) => {
1356 Some(StackElement::Key(str::from_utf8(
c34b1796 1357 &self.str_buffer[start as usize .. (start+size) as usize]
1a4d82fc
JJ
1358 ).unwrap()))
1359 }
1360 }
1361 }
1362
1363 // Used by Parser to insert StackElement::Key elements at the top of the stack.
1364 fn push_key(&mut self, key: string::String) {
1365 self.stack.push(InternalKey(self.str_buffer.len() as u16, key.len() as u16));
85aaf69f 1366 for c in key.as_bytes() {
1a4d82fc
JJ
1367 self.str_buffer.push(*c);
1368 }
1369 }
1370
1371 // Used by Parser to insert StackElement::Index elements at the top of the stack.
1372 fn push_index(&mut self, index: u32) {
1373 self.stack.push(InternalIndex(index));
1374 }
1375
1376 // Used by Parser to remove the top-most element of the stack.
1377 fn pop(&mut self) {
1378 assert!(!self.is_empty());
1379 match *self.stack.last().unwrap() {
1380 InternalKey(_, sz) => {
c34b1796 1381 let new_size = self.str_buffer.len() - sz as usize;
1a4d82fc
JJ
1382 self.str_buffer.truncate(new_size);
1383 }
1384 InternalIndex(_) => {}
1385 }
1386 self.stack.pop();
1387 }
1388
1389 // Used by Parser to test whether the top-most element is an index.
1390 fn last_is_index(&self) -> bool {
1391 if self.is_empty() { return false; }
1392 return match *self.stack.last().unwrap() {
1393 InternalIndex(_) => true,
1394 _ => false,
1395 }
1396 }
1397
1398 // Used by Parser to increment the index of the top-most element.
1399 fn bump_index(&mut self) {
1400 let len = self.stack.len();
1401 let idx = match *self.stack.last().unwrap() {
1402 InternalIndex(i) => { i + 1 }
1403 _ => { panic!(); }
1404 };
1405 self.stack[len - 1] = InternalIndex(idx);
1406 }
1407}
1408
1409/// A streaming JSON parser implemented as an iterator of JsonEvent, consuming
1410/// an iterator of char.
1411pub struct Parser<T> {
1412 rdr: T,
1413 ch: Option<char>,
c34b1796
AL
1414 line: usize,
1415 col: usize,
1a4d82fc
JJ
1416 // We maintain a stack representing where we are in the logical structure
1417 // of the JSON stream.
1418 stack: Stack,
1419 // A state machine is kept to make it possible to interrupt and resume parsing.
1420 state: ParserState,
1421}
1422
1423impl<T: Iterator<Item=char>> Iterator for Parser<T> {
1424 type Item = JsonEvent;
1425
1426 fn next(&mut self) -> Option<JsonEvent> {
1427 if self.state == ParseFinished {
1428 return None;
1429 }
1430
1431 if self.state == ParseBeforeFinish {
1432 self.parse_whitespace();
1433 // Make sure there is no trailing characters.
1434 if self.eof() {
1435 self.state = ParseFinished;
1436 return None;
1437 } else {
1438 return Some(self.error_event(TrailingCharacters));
1439 }
1440 }
1441
e9174d1e 1442 Some(self.parse())
1a4d82fc
JJ
1443 }
1444}
1445
1446impl<T: Iterator<Item=char>> Parser<T> {
1447 /// Creates the JSON parser.
1448 pub fn new(rdr: T) -> Parser<T> {
1449 let mut p = Parser {
1450 rdr: rdr,
1451 ch: Some('\x00'),
1452 line: 1,
1453 col: 0,
1454 stack: Stack::new(),
1455 state: ParseStart,
1456 };
1457 p.bump();
e9174d1e 1458 p
1a4d82fc
JJ
1459 }
1460
1461 /// Provides access to the current position in the logical structure of the
1462 /// JSON stream.
7453a54e 1463 pub fn stack(&self) -> &Stack {
e9174d1e 1464 &self.stack
1a4d82fc
JJ
1465 }
1466
1467 fn eof(&self) -> bool { self.ch.is_none() }
1468 fn ch_or_null(&self) -> char { self.ch.unwrap_or('\x00') }
1469 fn bump(&mut self) {
1470 self.ch = self.rdr.next();
1471
1472 if self.ch_is('\n') {
85aaf69f
SL
1473 self.line += 1;
1474 self.col = 1;
1a4d82fc 1475 } else {
85aaf69f 1476 self.col += 1;
1a4d82fc
JJ
1477 }
1478 }
1479
1480 fn next_char(&mut self) -> Option<char> {
1481 self.bump();
1482 self.ch
1483 }
1484 fn ch_is(&self, c: char) -> bool {
1485 self.ch == Some(c)
1486 }
1487
1488 fn error<U>(&self, reason: ErrorCode) -> Result<U, ParserError> {
1489 Err(SyntaxError(reason, self.line, self.col))
1490 }
1491
1492 fn parse_whitespace(&mut self) {
1493 while self.ch_is(' ') ||
1494 self.ch_is('\n') ||
1495 self.ch_is('\t') ||
1496 self.ch_is('\r') { self.bump(); }
1497 }
1498
1499 fn parse_number(&mut self) -> JsonEvent {
1500 let mut neg = false;
1501
1502 if self.ch_is('-') {
1503 self.bump();
1504 neg = true;
1505 }
1506
1507 let res = match self.parse_u64() {
1508 Ok(res) => res,
1509 Err(e) => { return Error(e); }
1510 };
1511
1512 if self.ch_is('.') || self.ch_is('e') || self.ch_is('E') {
1513 let mut res = res as f64;
1514
1515 if self.ch_is('.') {
1516 res = match self.parse_decimal(res) {
1517 Ok(res) => res,
1518 Err(e) => { return Error(e); }
1519 };
1520 }
1521
1522 if self.ch_is('e') || self.ch_is('E') {
1523 res = match self.parse_exponent(res) {
1524 Ok(res) => res,
1525 Err(e) => { return Error(e); }
1526 };
1527 }
1528
1529 if neg {
1530 res *= -1.0;
1531 }
1532
1533 F64Value(res)
1534 } else {
1535 if neg {
d9579d0f 1536 let res = (res as i64).wrapping_neg();
1a4d82fc
JJ
1537
1538 // Make sure we didn't underflow.
1539 if res > 0 {
1540 Error(SyntaxError(InvalidNumber, self.line, self.col))
1541 } else {
1542 I64Value(res)
1543 }
1544 } else {
1545 U64Value(res)
1546 }
1547 }
1548 }
1549
1550 fn parse_u64(&mut self) -> Result<u64, ParserError> {
9346a6ac 1551 let mut accum = 0u64;
1a4d82fc
JJ
1552 let last_accum = 0; // necessary to detect overflow.
1553
1554 match self.ch_or_null() {
1555 '0' => {
1556 self.bump();
1557
1558 // A leading '0' must be the only digit before the decimal point.
e9174d1e
SL
1559 if let '0' ... '9' = self.ch_or_null() {
1560 return self.error(InvalidNumber)
1a4d82fc
JJ
1561 }
1562 },
1563 '1' ... '9' => {
1564 while !self.eof() {
1565 match self.ch_or_null() {
1566 c @ '0' ... '9' => {
c34b1796
AL
1567 accum = accum.wrapping_mul(10);
1568 accum = accum.wrapping_add((c as u64) - ('0' as u64));
1a4d82fc
JJ
1569
1570 // Detect overflow by comparing to the last value.
1571 if accum <= last_accum { return self.error(InvalidNumber); }
1572
1573 self.bump();
1574 }
1575 _ => break,
1576 }
1577 }
1578 }
1579 _ => return self.error(InvalidNumber),
1580 }
1581
1582 Ok(accum)
1583 }
1584
1585 fn parse_decimal(&mut self, mut res: f64) -> Result<f64, ParserError> {
1586 self.bump();
1587
1588 // Make sure a digit follows the decimal place.
1589 match self.ch_or_null() {
1590 '0' ... '9' => (),
1591 _ => return self.error(InvalidNumber)
1592 }
1593
1594 let mut dec = 1.0;
1595 while !self.eof() {
1596 match self.ch_or_null() {
1597 c @ '0' ... '9' => {
1598 dec /= 10.0;
c34b1796 1599 res += (((c as isize) - ('0' as isize)) as f64) * dec;
1a4d82fc
JJ
1600 self.bump();
1601 }
1602 _ => break,
1603 }
1604 }
1605
1606 Ok(res)
1607 }
1608
1609 fn parse_exponent(&mut self, mut res: f64) -> Result<f64, ParserError> {
1610 self.bump();
1611
85aaf69f 1612 let mut exp = 0;
1a4d82fc
JJ
1613 let mut neg_exp = false;
1614
1615 if self.ch_is('+') {
1616 self.bump();
1617 } else if self.ch_is('-') {
1618 self.bump();
1619 neg_exp = true;
1620 }
1621
1622 // Make sure a digit follows the exponent place.
1623 match self.ch_or_null() {
1624 '0' ... '9' => (),
1625 _ => return self.error(InvalidNumber)
1626 }
1627 while !self.eof() {
1628 match self.ch_or_null() {
1629 c @ '0' ... '9' => {
1630 exp *= 10;
c34b1796 1631 exp += (c as usize) - ('0' as usize);
1a4d82fc
JJ
1632
1633 self.bump();
1634 }
1635 _ => break
1636 }
1637 }
1638
1639 let exp = 10_f64.powi(exp as i32);
1640 if neg_exp {
1641 res /= exp;
1642 } else {
1643 res *= exp;
1644 }
1645
1646 Ok(res)
1647 }
1648
1649 fn decode_hex_escape(&mut self) -> Result<u16, ParserError> {
85aaf69f 1650 let mut i = 0;
c34b1796 1651 let mut n = 0;
1a4d82fc
JJ
1652 while i < 4 && !self.eof() {
1653 self.bump();
1654 n = match self.ch_or_null() {
1655 c @ '0' ... '9' => n * 16 + ((c as u16) - ('0' as u16)),
1656 'a' | 'A' => n * 16 + 10,
1657 'b' | 'B' => n * 16 + 11,
1658 'c' | 'C' => n * 16 + 12,
1659 'd' | 'D' => n * 16 + 13,
1660 'e' | 'E' => n * 16 + 14,
1661 'f' | 'F' => n * 16 + 15,
1662 _ => return self.error(InvalidEscape)
1663 };
1664
85aaf69f 1665 i += 1;
1a4d82fc
JJ
1666 }
1667
1668 // Error out if we didn't parse 4 digits.
1669 if i != 4 {
1670 return self.error(InvalidEscape);
1671 }
1672
1673 Ok(n)
1674 }
1675
1676 fn parse_str(&mut self) -> Result<string::String, ParserError> {
1677 let mut escape = false;
1678 let mut res = string::String::new();
1679
1680 loop {
1681 self.bump();
1682 if self.eof() {
1683 return self.error(EOFWhileParsingString);
1684 }
1685
1686 if escape {
1687 match self.ch_or_null() {
1688 '"' => res.push('"'),
1689 '\\' => res.push('\\'),
1690 '/' => res.push('/'),
1691 'b' => res.push('\x08'),
1692 'f' => res.push('\x0c'),
1693 'n' => res.push('\n'),
1694 'r' => res.push('\r'),
1695 't' => res.push('\t'),
54a0048b 1696 'u' => match self.decode_hex_escape()? {
1a4d82fc
JJ
1697 0xDC00 ... 0xDFFF => {
1698 return self.error(LoneLeadingSurrogateInHexEscape)
1699 }
1700
1701 // Non-BMP characters are encoded as a sequence of
1702 // two hex escapes, representing UTF-16 surrogates.
1703 n1 @ 0xD800 ... 0xDBFF => {
1704 match (self.next_char(), self.next_char()) {
1705 (Some('\\'), Some('u')) => (),
1706 _ => return self.error(UnexpectedEndOfHexEscape),
1707 }
1708
54a0048b 1709 let n2 = self.decode_hex_escape()?;
e9174d1e
SL
1710 if n2 < 0xDC00 || n2 > 0xDFFF {
1711 return self.error(LoneLeadingSurrogateInHexEscape)
1a4d82fc 1712 }
e9174d1e
SL
1713 let c = (((n1 - 0xD800) as u32) << 10 |
1714 (n2 - 0xDC00) as u32) + 0x1_0000;
1715 res.push(char::from_u32(c).unwrap());
1a4d82fc
JJ
1716 }
1717
1718 n => match char::from_u32(n as u32) {
1719 Some(c) => res.push(c),
1720 None => return self.error(InvalidUnicodeCodePoint),
1721 },
1722 },
1723 _ => return self.error(InvalidEscape),
1724 }
1725 escape = false;
1726 } else if self.ch_is('\\') {
1727 escape = true;
1728 } else {
1729 match self.ch {
1730 Some('"') => {
1731 self.bump();
1732 return Ok(res);
1733 },
1734 Some(c) => res.push(c),
1735 None => unreachable!()
1736 }
1737 }
1738 }
1739 }
1740
1741 // Invoked at each iteration, consumes the stream until it has enough
1742 // information to return a JsonEvent.
1743 // Manages an internal state so that parsing can be interrupted and resumed.
1744 // Also keeps track of the position in the logical structure of the json
c34b1796 1745 // stream isize the form of a stack that can be queried by the user using the
1a4d82fc
JJ
1746 // stack() method.
1747 fn parse(&mut self) -> JsonEvent {
1748 loop {
1749 // The only paths where the loop can spin a new iteration
1750 // are in the cases ParseArrayComma and ParseObjectComma if ','
1751 // is parsed. In these cases the state is set to (respectively)
1752 // ParseArray(false) and ParseObject(false), which always return,
1753 // so there is no risk of getting stuck in an infinite loop.
1754 // All other paths return before the end of the loop's iteration.
1755 self.parse_whitespace();
1756
1757 match self.state {
1758 ParseStart => {
1759 return self.parse_start();
1760 }
1761 ParseArray(first) => {
1762 return self.parse_array(first);
1763 }
1764 ParseArrayComma => {
3157f602
XL
1765 if let Some(evt) = self.parse_array_comma_or_end() {
1766 return evt;
1a4d82fc
JJ
1767 }
1768 }
1769 ParseObject(first) => {
1770 return self.parse_object(first);
1771 }
1772 ParseObjectComma => {
1773 self.stack.pop();
1774 if self.ch_is(',') {
1775 self.state = ParseObject(false);
1776 self.bump();
1777 } else {
1778 return self.parse_object_end();
1779 }
1780 }
1781 _ => {
1782 return self.error_event(InvalidSyntax);
1783 }
1784 }
1785 }
1786 }
1787
1788 fn parse_start(&mut self) -> JsonEvent {
1789 let val = self.parse_value();
1790 self.state = match val {
1791 Error(_) => ParseFinished,
1792 ArrayStart => ParseArray(true),
1793 ObjectStart => ParseObject(true),
1794 _ => ParseBeforeFinish,
1795 };
e9174d1e 1796 val
1a4d82fc
JJ
1797 }
1798
1799 fn parse_array(&mut self, first: bool) -> JsonEvent {
1800 if self.ch_is(']') {
1801 if !first {
1802 self.error_event(InvalidSyntax)
1803 } else {
1804 self.state = if self.stack.is_empty() {
1805 ParseBeforeFinish
1806 } else if self.stack.last_is_index() {
1807 ParseArrayComma
1808 } else {
1809 ParseObjectComma
1810 };
1811 self.bump();
1812 ArrayEnd
1813 }
1814 } else {
1815 if first {
1816 self.stack.push_index(0);
1817 }
1818 let val = self.parse_value();
1819 self.state = match val {
1820 Error(_) => ParseFinished,
1821 ArrayStart => ParseArray(true),
1822 ObjectStart => ParseObject(true),
1823 _ => ParseArrayComma,
1824 };
1825 val
1826 }
1827 }
1828
1829 fn parse_array_comma_or_end(&mut self) -> Option<JsonEvent> {
1830 if self.ch_is(',') {
1831 self.stack.bump_index();
1832 self.state = ParseArray(false);
1833 self.bump();
1834 None
1835 } else if self.ch_is(']') {
1836 self.stack.pop();
1837 self.state = if self.stack.is_empty() {
1838 ParseBeforeFinish
1839 } else if self.stack.last_is_index() {
1840 ParseArrayComma
1841 } else {
1842 ParseObjectComma
1843 };
1844 self.bump();
1845 Some(ArrayEnd)
1846 } else if self.eof() {
1847 Some(self.error_event(EOFWhileParsingArray))
1848 } else {
1849 Some(self.error_event(InvalidSyntax))
1850 }
1851 }
1852
1853 fn parse_object(&mut self, first: bool) -> JsonEvent {
1854 if self.ch_is('}') {
1855 if !first {
1856 if self.stack.is_empty() {
1857 return self.error_event(TrailingComma);
1858 } else {
1859 self.stack.pop();
1860 }
1861 }
1862 self.state = if self.stack.is_empty() {
1863 ParseBeforeFinish
1864 } else if self.stack.last_is_index() {
1865 ParseArrayComma
1866 } else {
1867 ParseObjectComma
1868 };
1869 self.bump();
1870 return ObjectEnd;
1871 }
1872 if self.eof() {
1873 return self.error_event(EOFWhileParsingObject);
1874 }
1875 if !self.ch_is('"') {
1876 return self.error_event(KeyMustBeAString);
1877 }
1878 let s = match self.parse_str() {
1879 Ok(s) => s,
1880 Err(e) => {
1881 self.state = ParseFinished;
1882 return Error(e);
1883 }
1884 };
1885 self.parse_whitespace();
1886 if self.eof() {
1887 return self.error_event(EOFWhileParsingObject);
1888 } else if self.ch_or_null() != ':' {
1889 return self.error_event(ExpectedColon);
1890 }
1891 self.stack.push_key(s);
1892 self.bump();
1893 self.parse_whitespace();
1894
1895 let val = self.parse_value();
1896
1897 self.state = match val {
1898 Error(_) => ParseFinished,
1899 ArrayStart => ParseArray(true),
1900 ObjectStart => ParseObject(true),
1901 _ => ParseObjectComma,
1902 };
e9174d1e 1903 val
1a4d82fc
JJ
1904 }
1905
1906 fn parse_object_end(&mut self) -> JsonEvent {
1907 if self.ch_is('}') {
1908 self.state = if self.stack.is_empty() {
1909 ParseBeforeFinish
1910 } else if self.stack.last_is_index() {
1911 ParseArrayComma
1912 } else {
1913 ParseObjectComma
1914 };
1915 self.bump();
1916 ObjectEnd
1917 } else if self.eof() {
1918 self.error_event(EOFWhileParsingObject)
1919 } else {
1920 self.error_event(InvalidSyntax)
1921 }
1922 }
1923
1924 fn parse_value(&mut self) -> JsonEvent {
1925 if self.eof() { return self.error_event(EOFWhileParsingValue); }
1926 match self.ch_or_null() {
1927 'n' => { self.parse_ident("ull", NullValue) }
1928 't' => { self.parse_ident("rue", BooleanValue(true)) }
1929 'f' => { self.parse_ident("alse", BooleanValue(false)) }
1930 '0' ... '9' | '-' => self.parse_number(),
1931 '"' => match self.parse_str() {
1932 Ok(s) => StringValue(s),
1933 Err(e) => Error(e),
1934 },
1935 '[' => {
1936 self.bump();
1937 ArrayStart
1938 }
1939 '{' => {
1940 self.bump();
1941 ObjectStart
1942 }
1943 _ => { self.error_event(InvalidSyntax) }
1944 }
1945 }
1946
1947 fn parse_ident(&mut self, ident: &str, value: JsonEvent) -> JsonEvent {
1948 if ident.chars().all(|c| Some(c) == self.next_char()) {
1949 self.bump();
1950 value
1951 } else {
1952 Error(SyntaxError(InvalidSyntax, self.line, self.col))
1953 }
1954 }
1955
1956 fn error_event(&mut self, reason: ErrorCode) -> JsonEvent {
1957 self.state = ParseFinished;
1958 Error(SyntaxError(reason, self.line, self.col))
1959 }
1960}
1961
1962/// A Builder consumes a json::Parser to create a generic Json structure.
1963pub struct Builder<T> {
1964 parser: Parser<T>,
1965 token: Option<JsonEvent>,
1966}
1967
1968impl<T: Iterator<Item=char>> Builder<T> {
1969 /// Create a JSON Builder.
1970 pub fn new(src: T) -> Builder<T> {
1971 Builder { parser: Parser::new(src), token: None, }
1972 }
1973
1974 // Decode a Json value from a Parser.
1975 pub fn build(&mut self) -> Result<Json, BuilderError> {
1976 self.bump();
1977 let result = self.build_value();
1978 self.bump();
1979 match self.token {
1980 None => {}
c34b1796 1981 Some(Error(ref e)) => { return Err(e.clone()); }
1a4d82fc
JJ
1982 ref tok => { panic!("unexpected token {:?}", tok.clone()); }
1983 }
1984 result
1985 }
1986
1987 fn bump(&mut self) {
1988 self.token = self.parser.next();
1989 }
1990
1991 fn build_value(&mut self) -> Result<Json, BuilderError> {
e9174d1e 1992 match self.token {
1a4d82fc
JJ
1993 Some(NullValue) => Ok(Json::Null),
1994 Some(I64Value(n)) => Ok(Json::I64(n)),
1995 Some(U64Value(n)) => Ok(Json::U64(n)),
1996 Some(F64Value(n)) => Ok(Json::F64(n)),
1997 Some(BooleanValue(b)) => Ok(Json::Boolean(b)),
1998 Some(StringValue(ref mut s)) => {
1999 let mut temp = string::String::new();
2000 swap(s, &mut temp);
2001 Ok(Json::String(temp))
2002 }
c34b1796 2003 Some(Error(ref e)) => Err(e.clone()),
1a4d82fc
JJ
2004 Some(ArrayStart) => self.build_array(),
2005 Some(ObjectStart) => self.build_object(),
2006 Some(ObjectEnd) => self.parser.error(InvalidSyntax),
2007 Some(ArrayEnd) => self.parser.error(InvalidSyntax),
2008 None => self.parser.error(EOFWhileParsingValue),
2009 }
2010 }
2011
2012 fn build_array(&mut self) -> Result<Json, BuilderError> {
2013 self.bump();
2014 let mut values = Vec::new();
2015
2016 loop {
2017 if self.token == Some(ArrayEnd) {
2018 return Ok(Json::Array(values.into_iter().collect()));
2019 }
2020 match self.build_value() {
2021 Ok(v) => values.push(v),
2022 Err(e) => { return Err(e) }
2023 }
2024 self.bump();
2025 }
2026 }
2027
2028 fn build_object(&mut self) -> Result<Json, BuilderError> {
2029 self.bump();
2030
2031 let mut values = BTreeMap::new();
2032
2033 loop {
2034 match self.token {
2035 Some(ObjectEnd) => { return Ok(Json::Object(values)); }
c34b1796 2036 Some(Error(ref e)) => { return Err(e.clone()); }
1a4d82fc
JJ
2037 None => { break; }
2038 _ => {}
2039 }
2040 let key = match self.parser.stack().top() {
e9174d1e 2041 Some(StackElement::Key(k)) => { k.to_owned() }
1a4d82fc
JJ
2042 _ => { panic!("invalid state"); }
2043 };
2044 match self.build_value() {
2045 Ok(value) => { values.insert(key, value); }
2046 Err(e) => { return Err(e); }
2047 }
2048 self.bump();
2049 }
e9174d1e 2050 self.parser.error(EOFWhileParsingObject)
1a4d82fc
JJ
2051 }
2052}
2053
d9579d0f 2054/// Decodes a json value from an `&mut io::Read`
c34b1796
AL
2055pub fn from_reader(rdr: &mut Read) -> Result<Json, BuilderError> {
2056 let mut contents = Vec::new();
2057 match rdr.read_to_end(&mut contents) {
1a4d82fc
JJ
2058 Ok(c) => c,
2059 Err(e) => return Err(io_error_to_error(e))
2060 };
85aaf69f 2061 let s = match str::from_utf8(&contents).ok() {
1a4d82fc
JJ
2062 Some(s) => s,
2063 _ => return Err(SyntaxError(NotUtf8, 0, 0))
2064 };
2065 let mut builder = Builder::new(s.chars());
2066 builder.build()
2067}
2068
2069/// Decodes a json value from a string
2070pub fn from_str(s: &str) -> Result<Json, BuilderError> {
2071 let mut builder = Builder::new(s.chars());
2072 builder.build()
2073}
2074
2075/// A structure to decode JSON to values in rust.
2076pub struct Decoder {
2077 stack: Vec<Json>,
2078}
2079
2080impl Decoder {
2081 /// Creates a new decoder instance for decoding the specified JSON value.
2082 pub fn new(json: Json) -> Decoder {
2083 Decoder { stack: vec![json] }
2084 }
1a4d82fc 2085
1a4d82fc
JJ
2086 fn pop(&mut self) -> Json {
2087 self.stack.pop().unwrap()
2088 }
2089}
2090
2091macro_rules! expect {
2092 ($e:expr, Null) => ({
2093 match $e {
2094 Json::Null => Ok(()),
e9174d1e 2095 other => Err(ExpectedError("Null".to_owned(),
1a4d82fc
JJ
2096 format!("{}", other)))
2097 }
2098 });
2099 ($e:expr, $t:ident) => ({
2100 match $e {
2101 Json::$t(v) => Ok(v),
2102 other => {
e9174d1e 2103 Err(ExpectedError(stringify!($t).to_owned(),
1a4d82fc
JJ
2104 format!("{}", other)))
2105 }
2106 }
2107 })
2108}
2109
2110macro_rules! read_primitive {
2111 ($name:ident, $ty:ty) => {
2112 fn $name(&mut self) -> DecodeResult<$ty> {
2113 match self.pop() {
9346a6ac
AL
2114 Json::I64(f) => Ok(f as $ty),
2115 Json::U64(f) => Ok(f as $ty),
e9174d1e 2116 Json::F64(f) => Err(ExpectedError("Integer".to_owned(), format!("{}", f))),
c34b1796 2117 // re: #12967.. a type w/ numeric keys (ie HashMap<usize, V> etc)
1a4d82fc 2118 // is going to have a string here, as per JSON spec.
85aaf69f 2119 Json::String(s) => match s.parse().ok() {
1a4d82fc 2120 Some(f) => Ok(f),
e9174d1e 2121 None => Err(ExpectedError("Number".to_owned(), s)),
1a4d82fc 2122 },
e9174d1e 2123 value => Err(ExpectedError("Number".to_owned(), format!("{}", value))),
1a4d82fc
JJ
2124 }
2125 }
2126 }
2127}
2128
2129impl ::Decoder for Decoder {
2130 type Error = DecoderError;
2131
2132 fn read_nil(&mut self) -> DecodeResult<()> {
2133 expect!(self.pop(), Null)
2134 }
2135
9e0c209e 2136 read_primitive! { read_usize, usize }
1a4d82fc
JJ
2137 read_primitive! { read_u8, u8 }
2138 read_primitive! { read_u16, u16 }
2139 read_primitive! { read_u32, u32 }
2140 read_primitive! { read_u64, u64 }
9e0c209e 2141 read_primitive! { read_isize, isize }
1a4d82fc
JJ
2142 read_primitive! { read_i8, i8 }
2143 read_primitive! { read_i16, i16 }
2144 read_primitive! { read_i32, i32 }
2145 read_primitive! { read_i64, i64 }
2146
2147 fn read_f32(&mut self) -> DecodeResult<f32> { self.read_f64().map(|x| x as f32) }
2148
2149 fn read_f64(&mut self) -> DecodeResult<f64> {
2150 match self.pop() {
2151 Json::I64(f) => Ok(f as f64),
2152 Json::U64(f) => Ok(f as f64),
2153 Json::F64(f) => Ok(f),
2154 Json::String(s) => {
c34b1796 2155 // re: #12967.. a type w/ numeric keys (ie HashMap<usize, V> etc)
1a4d82fc 2156 // is going to have a string here, as per JSON spec.
85aaf69f 2157 match s.parse().ok() {
1a4d82fc 2158 Some(f) => Ok(f),
e9174d1e 2159 None => Err(ExpectedError("Number".to_owned(), s)),
1a4d82fc
JJ
2160 }
2161 },
2162 Json::Null => Ok(f64::NAN),
e9174d1e 2163 value => Err(ExpectedError("Number".to_owned(), format!("{}", value)))
1a4d82fc
JJ
2164 }
2165 }
2166
2167 fn read_bool(&mut self) -> DecodeResult<bool> {
2168 expect!(self.pop(), Boolean)
2169 }
2170
2171 fn read_char(&mut self) -> DecodeResult<char> {
54a0048b 2172 let s = self.read_str()?;
1a4d82fc
JJ
2173 {
2174 let mut it = s.chars();
2175 match (it.next(), it.next()) {
2176 // exactly one character
2177 (Some(c), None) => return Ok(c),
2178 _ => ()
2179 }
2180 }
e9174d1e 2181 Err(ExpectedError("single character string".to_owned(), format!("{}", s)))
1a4d82fc
JJ
2182 }
2183
c30ab7b3
SL
2184 fn read_str(&mut self) -> DecodeResult<Cow<str>> {
2185 expect!(self.pop(), String).map(Cow::Owned)
1a4d82fc
JJ
2186 }
2187
2188 fn read_enum<T, F>(&mut self, _name: &str, f: F) -> DecodeResult<T> where
2189 F: FnOnce(&mut Decoder) -> DecodeResult<T>,
2190 {
2191 f(self)
2192 }
2193
2194 fn read_enum_variant<T, F>(&mut self, names: &[&str],
2195 mut f: F) -> DecodeResult<T>
c34b1796 2196 where F: FnMut(&mut Decoder, usize) -> DecodeResult<T>,
1a4d82fc
JJ
2197 {
2198 let name = match self.pop() {
2199 Json::String(s) => s,
2200 Json::Object(mut o) => {
e9174d1e 2201 let n = match o.remove(&"variant".to_owned()) {
1a4d82fc
JJ
2202 Some(Json::String(s)) => s,
2203 Some(val) => {
e9174d1e 2204 return Err(ExpectedError("String".to_owned(), format!("{}", val)))
1a4d82fc
JJ
2205 }
2206 None => {
e9174d1e 2207 return Err(MissingFieldError("variant".to_owned()))
1a4d82fc
JJ
2208 }
2209 };
2210 match o.remove(&"fields".to_string()) {
2211 Some(Json::Array(l)) => {
2212 for field in l.into_iter().rev() {
2213 self.stack.push(field);
2214 }
2215 },
2216 Some(val) => {
e9174d1e 2217 return Err(ExpectedError("Array".to_owned(), format!("{}", val)))
1a4d82fc
JJ
2218 }
2219 None => {
e9174d1e 2220 return Err(MissingFieldError("fields".to_owned()))
1a4d82fc
JJ
2221 }
2222 }
2223 n
2224 }
2225 json => {
e9174d1e 2226 return Err(ExpectedError("String or Object".to_owned(), format!("{}", json)))
1a4d82fc
JJ
2227 }
2228 };
85aaf69f 2229 let idx = match names.iter().position(|n| *n == &name[..]) {
1a4d82fc
JJ
2230 Some(idx) => idx,
2231 None => return Err(UnknownVariantError(name))
2232 };
2233 f(self, idx)
2234 }
2235
c34b1796 2236 fn read_enum_variant_arg<T, F>(&mut self, _idx: usize, f: F) -> DecodeResult<T> where
1a4d82fc
JJ
2237 F: FnOnce(&mut Decoder) -> DecodeResult<T>,
2238 {
2239 f(self)
2240 }
2241
2242 fn read_enum_struct_variant<T, F>(&mut self, names: &[&str], f: F) -> DecodeResult<T> where
c34b1796 2243 F: FnMut(&mut Decoder, usize) -> DecodeResult<T>,
1a4d82fc
JJ
2244 {
2245 self.read_enum_variant(names, f)
2246 }
2247
2248
2249 fn read_enum_struct_variant_field<T, F>(&mut self,
2250 _name: &str,
c34b1796 2251 idx: usize,
1a4d82fc
JJ
2252 f: F)
2253 -> DecodeResult<T> where
2254 F: FnOnce(&mut Decoder) -> DecodeResult<T>,
2255 {
2256 self.read_enum_variant_arg(idx, f)
2257 }
2258
c34b1796 2259 fn read_struct<T, F>(&mut self, _name: &str, _len: usize, f: F) -> DecodeResult<T> where
1a4d82fc
JJ
2260 F: FnOnce(&mut Decoder) -> DecodeResult<T>,
2261 {
54a0048b 2262 let value = f(self)?;
1a4d82fc
JJ
2263 self.pop();
2264 Ok(value)
2265 }
2266
2267 fn read_struct_field<T, F>(&mut self,
2268 name: &str,
c34b1796 2269 _idx: usize,
1a4d82fc
JJ
2270 f: F)
2271 -> DecodeResult<T> where
2272 F: FnOnce(&mut Decoder) -> DecodeResult<T>,
2273 {
54a0048b 2274 let mut obj = expect!(self.pop(), Object)?;
1a4d82fc
JJ
2275
2276 let value = match obj.remove(&name.to_string()) {
2277 None => {
2278 // Add a Null and try to parse it as an Option<_>
2279 // to get None as a default value.
2280 self.stack.push(Json::Null);
2281 match f(self) {
2282 Ok(x) => x,
2283 Err(_) => return Err(MissingFieldError(name.to_string())),
2284 }
2285 },
2286 Some(json) => {
2287 self.stack.push(json);
54a0048b 2288 f(self)?
1a4d82fc
JJ
2289 }
2290 };
2291 self.stack.push(Json::Object(obj));
2292 Ok(value)
2293 }
2294
c34b1796 2295 fn read_tuple<T, F>(&mut self, tuple_len: usize, f: F) -> DecodeResult<T> where
1a4d82fc
JJ
2296 F: FnOnce(&mut Decoder) -> DecodeResult<T>,
2297 {
2298 self.read_seq(move |d, len| {
2299 if len == tuple_len {
2300 f(d)
2301 } else {
2302 Err(ExpectedError(format!("Tuple{}", tuple_len), format!("Tuple{}", len)))
2303 }
2304 })
2305 }
2306
c34b1796 2307 fn read_tuple_arg<T, F>(&mut self, idx: usize, f: F) -> DecodeResult<T> where
1a4d82fc
JJ
2308 F: FnOnce(&mut Decoder) -> DecodeResult<T>,
2309 {
2310 self.read_seq_elt(idx, f)
2311 }
2312
2313 fn read_tuple_struct<T, F>(&mut self,
2314 _name: &str,
c34b1796 2315 len: usize,
1a4d82fc
JJ
2316 f: F)
2317 -> DecodeResult<T> where
2318 F: FnOnce(&mut Decoder) -> DecodeResult<T>,
2319 {
2320 self.read_tuple(len, f)
2321 }
2322
2323 fn read_tuple_struct_arg<T, F>(&mut self,
c34b1796 2324 idx: usize,
1a4d82fc
JJ
2325 f: F)
2326 -> DecodeResult<T> where
2327 F: FnOnce(&mut Decoder) -> DecodeResult<T>,
2328 {
2329 self.read_tuple_arg(idx, f)
2330 }
2331
2332 fn read_option<T, F>(&mut self, mut f: F) -> DecodeResult<T> where
2333 F: FnMut(&mut Decoder, bool) -> DecodeResult<T>,
2334 {
2335 match self.pop() {
2336 Json::Null => f(self, false),
2337 value => { self.stack.push(value); f(self, true) }
2338 }
2339 }
2340
2341 fn read_seq<T, F>(&mut self, f: F) -> DecodeResult<T> where
c34b1796 2342 F: FnOnce(&mut Decoder, usize) -> DecodeResult<T>,
1a4d82fc 2343 {
54a0048b 2344 let array = expect!(self.pop(), Array)?;
1a4d82fc
JJ
2345 let len = array.len();
2346 for v in array.into_iter().rev() {
2347 self.stack.push(v);
2348 }
2349 f(self, len)
2350 }
2351
c34b1796 2352 fn read_seq_elt<T, F>(&mut self, _idx: usize, f: F) -> DecodeResult<T> where
1a4d82fc
JJ
2353 F: FnOnce(&mut Decoder) -> DecodeResult<T>,
2354 {
2355 f(self)
2356 }
2357
2358 fn read_map<T, F>(&mut self, f: F) -> DecodeResult<T> where
c34b1796 2359 F: FnOnce(&mut Decoder, usize) -> DecodeResult<T>,
1a4d82fc 2360 {
54a0048b 2361 let obj = expect!(self.pop(), Object)?;
1a4d82fc 2362 let len = obj.len();
85aaf69f 2363 for (key, value) in obj {
1a4d82fc
JJ
2364 self.stack.push(value);
2365 self.stack.push(Json::String(key));
2366 }
2367 f(self, len)
2368 }
2369
c34b1796 2370 fn read_map_elt_key<T, F>(&mut self, _idx: usize, f: F) -> DecodeResult<T> where
1a4d82fc
JJ
2371 F: FnOnce(&mut Decoder) -> DecodeResult<T>,
2372 {
2373 f(self)
2374 }
2375
c34b1796 2376 fn read_map_elt_val<T, F>(&mut self, _idx: usize, f: F) -> DecodeResult<T> where
1a4d82fc
JJ
2377 F: FnOnce(&mut Decoder) -> DecodeResult<T>,
2378 {
2379 f(self)
2380 }
2381
2382 fn error(&mut self, err: &str) -> DecoderError {
2383 ApplicationError(err.to_string())
2384 }
2385}
2386
2387/// A trait for converting values to JSON
2388pub trait ToJson {
2389 /// Converts the value of `self` to an instance of JSON
2390 fn to_json(&self) -> Json;
2391}
2392
2393macro_rules! to_json_impl_i64 {
2394 ($($t:ty), +) => (
2395 $(impl ToJson for $t {
c34b1796
AL
2396 fn to_json(&self) -> Json {
2397 Json::I64(*self as i64)
2398 }
1a4d82fc
JJ
2399 })+
2400 )
2401}
2402
c34b1796 2403to_json_impl_i64! { isize, i8, i16, i32, i64 }
1a4d82fc
JJ
2404
2405macro_rules! to_json_impl_u64 {
2406 ($($t:ty), +) => (
2407 $(impl ToJson for $t {
c34b1796
AL
2408 fn to_json(&self) -> Json {
2409 Json::U64(*self as u64)
2410 }
1a4d82fc
JJ
2411 })+
2412 )
2413}
2414
c34b1796 2415to_json_impl_u64! { usize, u8, u16, u32, u64 }
1a4d82fc
JJ
2416
2417impl ToJson for Json {
2418 fn to_json(&self) -> Json { self.clone() }
2419}
2420
2421impl ToJson for f32 {
2422 fn to_json(&self) -> Json { (*self as f64).to_json() }
2423}
2424
2425impl ToJson for f64 {
2426 fn to_json(&self) -> Json {
2427 match self.classify() {
2428 Fp::Nan | Fp::Infinite => Json::Null,
2429 _ => Json::F64(*self)
2430 }
2431 }
2432}
2433
2434impl ToJson for () {
2435 fn to_json(&self) -> Json { Json::Null }
2436}
2437
2438impl ToJson for bool {
2439 fn to_json(&self) -> Json { Json::Boolean(*self) }
2440}
2441
2442impl ToJson for str {
2443 fn to_json(&self) -> Json { Json::String(self.to_string()) }
2444}
2445
2446impl ToJson for string::String {
2447 fn to_json(&self) -> Json { Json::String((*self).clone()) }
2448}
2449
2450macro_rules! tuple_impl {
2451 // use variables to indicate the arity of the tuple
2452 ($($tyvar:ident),* ) => {
2453 // the trailing commas are for the 1 tuple
2454 impl<
2455 $( $tyvar : ToJson ),*
2456 > ToJson for ( $( $tyvar ),* , ) {
2457
2458 #[inline]
2459 #[allow(non_snake_case)]
2460 fn to_json(&self) -> Json {
2461 match *self {
2462 ($(ref $tyvar),*,) => Json::Array(vec![$($tyvar.to_json()),*])
2463 }
2464 }
2465 }
2466 }
2467}
2468
2469tuple_impl!{A}
2470tuple_impl!{A, B}
2471tuple_impl!{A, B, C}
2472tuple_impl!{A, B, C, D}
2473tuple_impl!{A, B, C, D, E}
2474tuple_impl!{A, B, C, D, E, F}
2475tuple_impl!{A, B, C, D, E, F, G}
2476tuple_impl!{A, B, C, D, E, F, G, H}
2477tuple_impl!{A, B, C, D, E, F, G, H, I}
2478tuple_impl!{A, B, C, D, E, F, G, H, I, J}
2479tuple_impl!{A, B, C, D, E, F, G, H, I, J, K}
2480tuple_impl!{A, B, C, D, E, F, G, H, I, J, K, L}
2481
2482impl<A: ToJson> ToJson for [A] {
2483 fn to_json(&self) -> Json { Json::Array(self.iter().map(|elt| elt.to_json()).collect()) }
2484}
2485
2486impl<A: ToJson> ToJson for Vec<A> {
2487 fn to_json(&self) -> Json { Json::Array(self.iter().map(|elt| elt.to_json()).collect()) }
2488}
2489
2490impl<A: ToJson> ToJson for BTreeMap<string::String, A> {
2491 fn to_json(&self) -> Json {
2492 let mut d = BTreeMap::new();
85aaf69f 2493 for (key, value) in self {
1a4d82fc
JJ
2494 d.insert((*key).clone(), value.to_json());
2495 }
2496 Json::Object(d)
2497 }
2498}
2499
2500impl<A: ToJson> ToJson for HashMap<string::String, A> {
2501 fn to_json(&self) -> Json {
2502 let mut d = BTreeMap::new();
85aaf69f 2503 for (key, value) in self {
1a4d82fc
JJ
2504 d.insert((*key).clone(), value.to_json());
2505 }
2506 Json::Object(d)
2507 }
2508}
2509
2510impl<A:ToJson> ToJson for Option<A> {
2511 fn to_json(&self) -> Json {
2512 match *self {
2513 None => Json::Null,
2514 Some(ref value) => value.to_json()
2515 }
2516 }
2517}
2518
2519struct FormatShim<'a, 'b: 'a> {
2520 inner: &'a mut fmt::Formatter<'b>,
2521}
2522
85aaf69f 2523impl<'a, 'b> fmt::Write for FormatShim<'a, 'b> {
1a4d82fc 2524 fn write_str(&mut self, s: &str) -> fmt::Result {
85aaf69f
SL
2525 match self.inner.write_str(s) {
2526 Ok(_) => Ok(()),
2527 Err(_) => Err(fmt::Error)
2528 }
1a4d82fc
JJ
2529 }
2530}
2531
85aaf69f 2532impl fmt::Display for Json {
1a4d82fc
JJ
2533 /// Encodes a json value into a string
2534 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2535 let mut shim = FormatShim { inner: f };
2536 let mut encoder = Encoder::new(&mut shim);
85aaf69f
SL
2537 match self.encode(&mut encoder) {
2538 Ok(_) => Ok(()),
2539 Err(_) => Err(fmt::Error)
2540 }
1a4d82fc
JJ
2541 }
2542}
2543
85aaf69f 2544impl<'a> fmt::Display for PrettyJson<'a> {
1a4d82fc
JJ
2545 /// Encodes a json value into a string
2546 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2547 let mut shim = FormatShim { inner: f };
2548 let mut encoder = PrettyEncoder::new(&mut shim);
85aaf69f
SL
2549 match self.inner.encode(&mut encoder) {
2550 Ok(_) => Ok(()),
2551 Err(_) => Err(fmt::Error)
2552 }
1a4d82fc
JJ
2553 }
2554}
2555
85aaf69f 2556impl<'a, T: Encodable> fmt::Display for AsJson<'a, T> {
1a4d82fc
JJ
2557 /// Encodes a json value into a string
2558 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2559 let mut shim = FormatShim { inner: f };
2560 let mut encoder = Encoder::new(&mut shim);
85aaf69f
SL
2561 match self.inner.encode(&mut encoder) {
2562 Ok(_) => Ok(()),
2563 Err(_) => Err(fmt::Error)
2564 }
1a4d82fc
JJ
2565 }
2566}
2567
2568impl<'a, T> AsPrettyJson<'a, T> {
2569 /// Set the indentation level for the emitted JSON
c34b1796 2570 pub fn indent(mut self, indent: usize) -> AsPrettyJson<'a, T> {
1a4d82fc
JJ
2571 self.indent = Some(indent);
2572 self
2573 }
2574}
2575
85aaf69f 2576impl<'a, T: Encodable> fmt::Display for AsPrettyJson<'a, T> {
1a4d82fc
JJ
2577 /// Encodes a json value into a string
2578 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2579 let mut shim = FormatShim { inner: f };
2580 let mut encoder = PrettyEncoder::new(&mut shim);
3157f602
XL
2581 if let Some(n) = self.indent {
2582 encoder.set_indent(n);
1a4d82fc 2583 }
85aaf69f
SL
2584 match self.inner.encode(&mut encoder) {
2585 Ok(_) => Ok(()),
2586 Err(_) => Err(fmt::Error)
2587 }
1a4d82fc
JJ
2588 }
2589}
2590
2591impl FromStr for Json {
85aaf69f
SL
2592 type Err = BuilderError;
2593 fn from_str(s: &str) -> Result<Json, BuilderError> {
2594 from_str(s)
1a4d82fc
JJ
2595 }
2596}
2597
2598#[cfg(test)]
2599mod tests {
2600 extern crate test;
2601 use self::Animal::*;
1a4d82fc
JJ
2602 use self::test::Bencher;
2603 use {Encodable, Decodable};
2604 use super::Json::*;
2605 use super::ErrorCode::*;
2606 use super::ParserError::*;
2607 use super::DecoderError::*;
2608 use super::JsonEvent::*;
2609 use super::{Json, from_str, DecodeResult, DecoderError, JsonEvent, Parser,
85aaf69f
SL
2610 StackElement, Stack, Decoder, Encoder, EncoderError};
2611 use std::{i64, u64, f32, f64};
9346a6ac 2612 use std::io::prelude::*;
1a4d82fc 2613 use std::collections::BTreeMap;
1a4d82fc
JJ
2614 use std::string;
2615
85aaf69f 2616 #[derive(RustcDecodable, Eq, PartialEq, Debug)]
1a4d82fc 2617 struct OptionData {
c34b1796 2618 opt: Option<usize>,
1a4d82fc
JJ
2619 }
2620
2621 #[test]
2622 fn test_decode_option_none() {
2623 let s ="{}";
2624 let obj: OptionData = super::decode(s).unwrap();
2625 assert_eq!(obj, OptionData { opt: None });
2626 }
2627
2628 #[test]
2629 fn test_decode_option_some() {
2630 let s = "{ \"opt\": 10 }";
2631 let obj: OptionData = super::decode(s).unwrap();
85aaf69f 2632 assert_eq!(obj, OptionData { opt: Some(10) });
1a4d82fc
JJ
2633 }
2634
2635 #[test]
2636 fn test_decode_option_malformed() {
2637 check_err::<OptionData>("{ \"opt\": [] }",
2638 ExpectedError("Number".to_string(), "[]".to_string()));
2639 check_err::<OptionData>("{ \"opt\": false }",
2640 ExpectedError("Number".to_string(), "false".to_string()));
2641 }
2642
85aaf69f 2643 #[derive(PartialEq, RustcEncodable, RustcDecodable, Debug)]
1a4d82fc
JJ
2644 enum Animal {
2645 Dog,
c34b1796 2646 Frog(string::String, isize)
1a4d82fc
JJ
2647 }
2648
85aaf69f 2649 #[derive(PartialEq, RustcEncodable, RustcDecodable, Debug)]
1a4d82fc
JJ
2650 struct Inner {
2651 a: (),
c34b1796 2652 b: usize,
1a4d82fc
JJ
2653 c: Vec<string::String>,
2654 }
2655
85aaf69f 2656 #[derive(PartialEq, RustcEncodable, RustcDecodable, Debug)]
1a4d82fc
JJ
2657 struct Outer {
2658 inner: Vec<Inner>,
2659 }
2660
2661 fn mk_object(items: &[(string::String, Json)]) -> Json {
2662 let mut d = BTreeMap::new();
2663
85aaf69f 2664 for item in items {
1a4d82fc
JJ
2665 match *item {
2666 (ref key, ref value) => { d.insert((*key).clone(), (*value).clone()); },
2667 }
2668 };
2669
2670 Object(d)
2671 }
2672
2673 #[test]
2674 fn test_from_str_trait() {
2675 let s = "null";
2676 assert!(s.parse::<Json>().unwrap() == s.parse().unwrap());
2677 }
2678
2679 #[test]
2680 fn test_write_null() {
2681 assert_eq!(Null.to_string(), "null");
2682 assert_eq!(Null.pretty().to_string(), "null");
2683 }
2684
2685 #[test]
2686 fn test_write_i64() {
2687 assert_eq!(U64(0).to_string(), "0");
2688 assert_eq!(U64(0).pretty().to_string(), "0");
2689
2690 assert_eq!(U64(1234).to_string(), "1234");
2691 assert_eq!(U64(1234).pretty().to_string(), "1234");
2692
2693 assert_eq!(I64(-5678).to_string(), "-5678");
2694 assert_eq!(I64(-5678).pretty().to_string(), "-5678");
2695
2696 assert_eq!(U64(7650007200025252000).to_string(), "7650007200025252000");
2697 assert_eq!(U64(7650007200025252000).pretty().to_string(), "7650007200025252000");
2698 }
2699
2700 #[test]
2701 fn test_write_f64() {
2702 assert_eq!(F64(3.0).to_string(), "3.0");
2703 assert_eq!(F64(3.0).pretty().to_string(), "3.0");
2704
2705 assert_eq!(F64(3.1).to_string(), "3.1");
2706 assert_eq!(F64(3.1).pretty().to_string(), "3.1");
2707
2708 assert_eq!(F64(-1.5).to_string(), "-1.5");
2709 assert_eq!(F64(-1.5).pretty().to_string(), "-1.5");
2710
2711 assert_eq!(F64(0.5).to_string(), "0.5");
2712 assert_eq!(F64(0.5).pretty().to_string(), "0.5");
2713
2714 assert_eq!(F64(f64::NAN).to_string(), "null");
2715 assert_eq!(F64(f64::NAN).pretty().to_string(), "null");
2716
2717 assert_eq!(F64(f64::INFINITY).to_string(), "null");
2718 assert_eq!(F64(f64::INFINITY).pretty().to_string(), "null");
2719
2720 assert_eq!(F64(f64::NEG_INFINITY).to_string(), "null");
2721 assert_eq!(F64(f64::NEG_INFINITY).pretty().to_string(), "null");
2722 }
2723
2724 #[test]
2725 fn test_write_str() {
2726 assert_eq!(String("".to_string()).to_string(), "\"\"");
2727 assert_eq!(String("".to_string()).pretty().to_string(), "\"\"");
2728
2729 assert_eq!(String("homura".to_string()).to_string(), "\"homura\"");
2730 assert_eq!(String("madoka".to_string()).pretty().to_string(), "\"madoka\"");
2731 }
2732
2733 #[test]
2734 fn test_write_bool() {
2735 assert_eq!(Boolean(true).to_string(), "true");
2736 assert_eq!(Boolean(true).pretty().to_string(), "true");
2737
2738 assert_eq!(Boolean(false).to_string(), "false");
2739 assert_eq!(Boolean(false).pretty().to_string(), "false");
2740 }
2741
2742 #[test]
2743 fn test_write_array() {
2744 assert_eq!(Array(vec![]).to_string(), "[]");
2745 assert_eq!(Array(vec![]).pretty().to_string(), "[]");
2746
2747 assert_eq!(Array(vec![Boolean(true)]).to_string(), "[true]");
2748 assert_eq!(
2749 Array(vec![Boolean(true)]).pretty().to_string(),
2750 "\
2751 [\n \
2752 true\n\
2753 ]"
2754 );
2755
2756 let long_test_array = Array(vec![
2757 Boolean(false),
2758 Null,
2759 Array(vec![String("foo\nbar".to_string()), F64(3.5)])]);
2760
2761 assert_eq!(long_test_array.to_string(),
2762 "[false,null,[\"foo\\nbar\",3.5]]");
2763 assert_eq!(
2764 long_test_array.pretty().to_string(),
2765 "\
2766 [\n \
2767 false,\n \
2768 null,\n \
2769 [\n \
2770 \"foo\\nbar\",\n \
2771 3.5\n \
2772 ]\n\
2773 ]"
2774 );
2775 }
2776
2777 #[test]
2778 fn test_write_object() {
2779 assert_eq!(mk_object(&[]).to_string(), "{}");
2780 assert_eq!(mk_object(&[]).pretty().to_string(), "{}");
2781
2782 assert_eq!(
2783 mk_object(&[
2784 ("a".to_string(), Boolean(true))
2785 ]).to_string(),
2786 "{\"a\":true}"
2787 );
2788 assert_eq!(
2789 mk_object(&[("a".to_string(), Boolean(true))]).pretty().to_string(),
2790 "\
2791 {\n \
2792 \"a\": true\n\
2793 }"
2794 );
2795
2796 let complex_obj = mk_object(&[
2797 ("b".to_string(), Array(vec![
2798 mk_object(&[("c".to_string(), String("\x0c\r".to_string()))]),
2799 mk_object(&[("d".to_string(), String("".to_string()))])
2800 ]))
2801 ]);
2802
2803 assert_eq!(
2804 complex_obj.to_string(),
2805 "{\
2806 \"b\":[\
2807 {\"c\":\"\\f\\r\"},\
2808 {\"d\":\"\"}\
2809 ]\
2810 }"
2811 );
2812 assert_eq!(
2813 complex_obj.pretty().to_string(),
2814 "\
2815 {\n \
2816 \"b\": [\n \
2817 {\n \
2818 \"c\": \"\\f\\r\"\n \
2819 },\n \
2820 {\n \
2821 \"d\": \"\"\n \
2822 }\n \
2823 ]\n\
2824 }"
2825 );
2826
2827 let a = mk_object(&[
2828 ("a".to_string(), Boolean(true)),
2829 ("b".to_string(), Array(vec![
2830 mk_object(&[("c".to_string(), String("\x0c\r".to_string()))]),
2831 mk_object(&[("d".to_string(), String("".to_string()))])
2832 ]))
2833 ]);
2834
2835 // We can't compare the strings directly because the object fields be
2836 // printed in a different order.
2837 assert_eq!(a.clone(), a.to_string().parse().unwrap());
2838 assert_eq!(a.clone(), a.pretty().to_string().parse().unwrap());
2839 }
2840
2841 #[test]
2842 fn test_write_enum() {
2843 let animal = Dog;
2844 assert_eq!(
2845 format!("{}", super::as_json(&animal)),
2846 "\"Dog\""
2847 );
2848 assert_eq!(
2849 format!("{}", super::as_pretty_json(&animal)),
2850 "\"Dog\""
2851 );
2852
2853 let animal = Frog("Henry".to_string(), 349);
2854 assert_eq!(
2855 format!("{}", super::as_json(&animal)),
2856 "{\"variant\":\"Frog\",\"fields\":[\"Henry\",349]}"
2857 );
2858 assert_eq!(
2859 format!("{}", super::as_pretty_json(&animal)),
2860 "{\n \
2861 \"variant\": \"Frog\",\n \
2862 \"fields\": [\n \
2863 \"Henry\",\n \
2864 349\n \
2865 ]\n\
2866 }"
2867 );
2868 }
2869
2870 macro_rules! check_encoder_for_simple {
2871 ($value:expr, $expected:expr) => ({
2872 let s = format!("{}", super::as_json(&$value));
2873 assert_eq!(s, $expected);
2874
2875 let s = format!("{}", super::as_pretty_json(&$value));
2876 assert_eq!(s, $expected);
2877 })
2878 }
2879
2880 #[test]
2881 fn test_write_some() {
2882 check_encoder_for_simple!(Some("jodhpurs".to_string()), "\"jodhpurs\"");
2883 }
2884
2885 #[test]
2886 fn test_write_none() {
2887 check_encoder_for_simple!(None::<string::String>, "null");
2888 }
2889
2890 #[test]
2891 fn test_write_char() {
2892 check_encoder_for_simple!('a', "\"a\"");
2893 check_encoder_for_simple!('\t', "\"\\t\"");
2894 check_encoder_for_simple!('\u{0000}', "\"\\u0000\"");
2895 check_encoder_for_simple!('\u{001b}', "\"\\u001b\"");
2896 check_encoder_for_simple!('\u{007f}', "\"\\u007f\"");
2897 check_encoder_for_simple!('\u{00a0}', "\"\u{00a0}\"");
2898 check_encoder_for_simple!('\u{abcd}', "\"\u{abcd}\"");
2899 check_encoder_for_simple!('\u{10ffff}', "\"\u{10ffff}\"");
2900 }
2901
2902 #[test]
2903 fn test_trailing_characters() {
2904 assert_eq!(from_str("nulla"), Err(SyntaxError(TrailingCharacters, 1, 5)));
2905 assert_eq!(from_str("truea"), Err(SyntaxError(TrailingCharacters, 1, 5)));
2906 assert_eq!(from_str("falsea"), Err(SyntaxError(TrailingCharacters, 1, 6)));
2907 assert_eq!(from_str("1a"), Err(SyntaxError(TrailingCharacters, 1, 2)));
2908 assert_eq!(from_str("[]a"), Err(SyntaxError(TrailingCharacters, 1, 3)));
2909 assert_eq!(from_str("{}a"), Err(SyntaxError(TrailingCharacters, 1, 3)));
2910 }
2911
2912 #[test]
2913 fn test_read_identifiers() {
2914 assert_eq!(from_str("n"), Err(SyntaxError(InvalidSyntax, 1, 2)));
2915 assert_eq!(from_str("nul"), Err(SyntaxError(InvalidSyntax, 1, 4)));
2916 assert_eq!(from_str("t"), Err(SyntaxError(InvalidSyntax, 1, 2)));
2917 assert_eq!(from_str("truz"), Err(SyntaxError(InvalidSyntax, 1, 4)));
2918 assert_eq!(from_str("f"), Err(SyntaxError(InvalidSyntax, 1, 2)));
2919 assert_eq!(from_str("faz"), Err(SyntaxError(InvalidSyntax, 1, 3)));
2920
2921 assert_eq!(from_str("null"), Ok(Null));
2922 assert_eq!(from_str("true"), Ok(Boolean(true)));
2923 assert_eq!(from_str("false"), Ok(Boolean(false)));
2924 assert_eq!(from_str(" null "), Ok(Null));
2925 assert_eq!(from_str(" true "), Ok(Boolean(true)));
2926 assert_eq!(from_str(" false "), Ok(Boolean(false)));
2927 }
2928
2929 #[test]
2930 fn test_decode_identifiers() {
2931 let v: () = super::decode("null").unwrap();
2932 assert_eq!(v, ());
2933
2934 let v: bool = super::decode("true").unwrap();
2935 assert_eq!(v, true);
2936
2937 let v: bool = super::decode("false").unwrap();
2938 assert_eq!(v, false);
2939 }
2940
2941 #[test]
2942 fn test_read_number() {
2943 assert_eq!(from_str("+"), Err(SyntaxError(InvalidSyntax, 1, 1)));
2944 assert_eq!(from_str("."), Err(SyntaxError(InvalidSyntax, 1, 1)));
2945 assert_eq!(from_str("NaN"), Err(SyntaxError(InvalidSyntax, 1, 1)));
2946 assert_eq!(from_str("-"), Err(SyntaxError(InvalidNumber, 1, 2)));
2947 assert_eq!(from_str("00"), Err(SyntaxError(InvalidNumber, 1, 2)));
2948 assert_eq!(from_str("1."), Err(SyntaxError(InvalidNumber, 1, 3)));
2949 assert_eq!(from_str("1e"), Err(SyntaxError(InvalidNumber, 1, 3)));
2950 assert_eq!(from_str("1e+"), Err(SyntaxError(InvalidNumber, 1, 4)));
2951
2952 assert_eq!(from_str("18446744073709551616"), Err(SyntaxError(InvalidNumber, 1, 20)));
2953 assert_eq!(from_str("-9223372036854775809"), Err(SyntaxError(InvalidNumber, 1, 21)));
2954
2955 assert_eq!(from_str("3"), Ok(U64(3)));
2956 assert_eq!(from_str("3.1"), Ok(F64(3.1)));
2957 assert_eq!(from_str("-1.2"), Ok(F64(-1.2)));
2958 assert_eq!(from_str("0.4"), Ok(F64(0.4)));
2959 assert_eq!(from_str("0.4e5"), Ok(F64(0.4e5)));
2960 assert_eq!(from_str("0.4e+15"), Ok(F64(0.4e15)));
2961 assert_eq!(from_str("0.4e-01"), Ok(F64(0.4e-01)));
2962 assert_eq!(from_str(" 3 "), Ok(U64(3)));
2963
2964 assert_eq!(from_str("-9223372036854775808"), Ok(I64(i64::MIN)));
2965 assert_eq!(from_str("9223372036854775807"), Ok(U64(i64::MAX as u64)));
2966 assert_eq!(from_str("18446744073709551615"), Ok(U64(u64::MAX)));
2967 }
2968
2969 #[test]
2970 fn test_decode_numbers() {
2971 let v: f64 = super::decode("3").unwrap();
2972 assert_eq!(v, 3.0);
2973
2974 let v: f64 = super::decode("3.1").unwrap();
2975 assert_eq!(v, 3.1);
2976
2977 let v: f64 = super::decode("-1.2").unwrap();
2978 assert_eq!(v, -1.2);
2979
2980 let v: f64 = super::decode("0.4").unwrap();
2981 assert_eq!(v, 0.4);
2982
2983 let v: f64 = super::decode("0.4e5").unwrap();
2984 assert_eq!(v, 0.4e5);
2985
2986 let v: f64 = super::decode("0.4e15").unwrap();
2987 assert_eq!(v, 0.4e15);
2988
2989 let v: f64 = super::decode("0.4e-01").unwrap();
2990 assert_eq!(v, 0.4e-01);
2991
2992 let v: u64 = super::decode("0").unwrap();
2993 assert_eq!(v, 0);
2994
2995 let v: u64 = super::decode("18446744073709551615").unwrap();
2996 assert_eq!(v, u64::MAX);
2997
2998 let v: i64 = super::decode("-9223372036854775808").unwrap();
2999 assert_eq!(v, i64::MIN);
3000
3001 let v: i64 = super::decode("9223372036854775807").unwrap();
3002 assert_eq!(v, i64::MAX);
3003
d9579d0f 3004 let res: DecodeResult<i64> = super::decode("765.25");
1a4d82fc 3005 assert_eq!(res, Err(ExpectedError("Integer".to_string(),
d9579d0f 3006 "765.25".to_string())));
1a4d82fc
JJ
3007 }
3008
3009 #[test]
3010 fn test_read_str() {
3011 assert_eq!(from_str("\""), Err(SyntaxError(EOFWhileParsingString, 1, 2)));
3012 assert_eq!(from_str("\"lol"), Err(SyntaxError(EOFWhileParsingString, 1, 5)));
3013
3014 assert_eq!(from_str("\"\""), Ok(String("".to_string())));
3015 assert_eq!(from_str("\"foo\""), Ok(String("foo".to_string())));
3016 assert_eq!(from_str("\"\\\"\""), Ok(String("\"".to_string())));
3017 assert_eq!(from_str("\"\\b\""), Ok(String("\x08".to_string())));
3018 assert_eq!(from_str("\"\\n\""), Ok(String("\n".to_string())));
3019 assert_eq!(from_str("\"\\r\""), Ok(String("\r".to_string())));
3020 assert_eq!(from_str("\"\\t\""), Ok(String("\t".to_string())));
3021 assert_eq!(from_str(" \"foo\" "), Ok(String("foo".to_string())));
3022 assert_eq!(from_str("\"\\u12ab\""), Ok(String("\u{12ab}".to_string())));
3023 assert_eq!(from_str("\"\\uAB12\""), Ok(String("\u{AB12}".to_string())));
3024 }
3025
3026 #[test]
3027 fn test_decode_str() {
3028 let s = [("\"\"", ""),
3029 ("\"foo\"", "foo"),
3030 ("\"\\\"\"", "\""),
3031 ("\"\\b\"", "\x08"),
3032 ("\"\\n\"", "\n"),
3033 ("\"\\r\"", "\r"),
3034 ("\"\\t\"", "\t"),
3035 ("\"\\u12ab\"", "\u{12ab}"),
3036 ("\"\\uAB12\"", "\u{AB12}")];
3037
85aaf69f 3038 for &(i, o) in &s {
1a4d82fc
JJ
3039 let v: string::String = super::decode(i).unwrap();
3040 assert_eq!(v, o);
3041 }
3042 }
3043
3044 #[test]
3045 fn test_read_array() {
3046 assert_eq!(from_str("["), Err(SyntaxError(EOFWhileParsingValue, 1, 2)));
3047 assert_eq!(from_str("[1"), Err(SyntaxError(EOFWhileParsingArray, 1, 3)));
3048 assert_eq!(from_str("[1,"), Err(SyntaxError(EOFWhileParsingValue, 1, 4)));
3049 assert_eq!(from_str("[1,]"), Err(SyntaxError(InvalidSyntax, 1, 4)));
3050 assert_eq!(from_str("[6 7]"), Err(SyntaxError(InvalidSyntax, 1, 4)));
3051
3052 assert_eq!(from_str("[]"), Ok(Array(vec![])));
3053 assert_eq!(from_str("[ ]"), Ok(Array(vec![])));
3054 assert_eq!(from_str("[true]"), Ok(Array(vec![Boolean(true)])));
3055 assert_eq!(from_str("[ false ]"), Ok(Array(vec![Boolean(false)])));
3056 assert_eq!(from_str("[null]"), Ok(Array(vec![Null])));
3057 assert_eq!(from_str("[3, 1]"),
3058 Ok(Array(vec![U64(3), U64(1)])));
3059 assert_eq!(from_str("\n[3, 2]\n"),
3060 Ok(Array(vec![U64(3), U64(2)])));
3061 assert_eq!(from_str("[2, [4, 1]]"),
3062 Ok(Array(vec![U64(2), Array(vec![U64(4), U64(1)])])));
3063 }
3064
3065 #[test]
3066 fn test_decode_array() {
3067 let v: Vec<()> = super::decode("[]").unwrap();
c34b1796 3068 assert_eq!(v, []);
1a4d82fc
JJ
3069
3070 let v: Vec<()> = super::decode("[null]").unwrap();
c34b1796 3071 assert_eq!(v, [()]);
1a4d82fc
JJ
3072
3073 let v: Vec<bool> = super::decode("[true]").unwrap();
c34b1796 3074 assert_eq!(v, [true]);
1a4d82fc 3075
c34b1796
AL
3076 let v: Vec<isize> = super::decode("[3, 1]").unwrap();
3077 assert_eq!(v, [3, 1]);
1a4d82fc 3078
c34b1796
AL
3079 let v: Vec<Vec<usize>> = super::decode("[[3], [1, 2]]").unwrap();
3080 assert_eq!(v, [vec![3], vec![1, 2]]);
1a4d82fc
JJ
3081 }
3082
3083 #[test]
3084 fn test_decode_tuple() {
c34b1796 3085 let t: (usize, usize, usize) = super::decode("[1, 2, 3]").unwrap();
85aaf69f 3086 assert_eq!(t, (1, 2, 3));
1a4d82fc 3087
c34b1796 3088 let t: (usize, string::String) = super::decode("[1, \"two\"]").unwrap();
85aaf69f 3089 assert_eq!(t, (1, "two".to_string()));
1a4d82fc
JJ
3090 }
3091
3092 #[test]
3093 fn test_decode_tuple_malformed_types() {
c34b1796 3094 assert!(super::decode::<(usize, string::String)>("[1, 2]").is_err());
1a4d82fc
JJ
3095 }
3096
3097 #[test]
3098 fn test_decode_tuple_malformed_length() {
c34b1796 3099 assert!(super::decode::<(usize, usize)>("[1, 2, 3]").is_err());
1a4d82fc
JJ
3100 }
3101
3102 #[test]
3103 fn test_read_object() {
3104 assert_eq!(from_str("{"), Err(SyntaxError(EOFWhileParsingObject, 1, 2)));
3105 assert_eq!(from_str("{ "), Err(SyntaxError(EOFWhileParsingObject, 1, 3)));
3106 assert_eq!(from_str("{1"), Err(SyntaxError(KeyMustBeAString, 1, 2)));
3107 assert_eq!(from_str("{ \"a\""), Err(SyntaxError(EOFWhileParsingObject, 1, 6)));
3108 assert_eq!(from_str("{\"a\""), Err(SyntaxError(EOFWhileParsingObject, 1, 5)));
3109 assert_eq!(from_str("{\"a\" "), Err(SyntaxError(EOFWhileParsingObject, 1, 6)));
3110
3111 assert_eq!(from_str("{\"a\" 1"), Err(SyntaxError(ExpectedColon, 1, 6)));
3112 assert_eq!(from_str("{\"a\":"), Err(SyntaxError(EOFWhileParsingValue, 1, 6)));
3113 assert_eq!(from_str("{\"a\":1"), Err(SyntaxError(EOFWhileParsingObject, 1, 7)));
3114 assert_eq!(from_str("{\"a\":1 1"), Err(SyntaxError(InvalidSyntax, 1, 8)));
3115 assert_eq!(from_str("{\"a\":1,"), Err(SyntaxError(EOFWhileParsingObject, 1, 8)));
3116
3117 assert_eq!(from_str("{}").unwrap(), mk_object(&[]));
3118 assert_eq!(from_str("{\"a\": 3}").unwrap(),
3119 mk_object(&[("a".to_string(), U64(3))]));
3120
3121 assert_eq!(from_str(
3122 "{ \"a\": null, \"b\" : true }").unwrap(),
3123 mk_object(&[
3124 ("a".to_string(), Null),
3125 ("b".to_string(), Boolean(true))]));
3126 assert_eq!(from_str("\n{ \"a\": null, \"b\" : true }\n").unwrap(),
3127 mk_object(&[
3128 ("a".to_string(), Null),
3129 ("b".to_string(), Boolean(true))]));
3130 assert_eq!(from_str(
3131 "{\"a\" : 1.0 ,\"b\": [ true ]}").unwrap(),
3132 mk_object(&[
3133 ("a".to_string(), F64(1.0)),
3134 ("b".to_string(), Array(vec![Boolean(true)]))
3135 ]));
3136 assert_eq!(from_str(
3137 "{\
3138 \"a\": 1.0, \
3139 \"b\": [\
3140 true,\
3141 \"foo\\nbar\", \
3142 { \"c\": {\"d\": null} } \
3143 ]\
3144 }").unwrap(),
3145 mk_object(&[
3146 ("a".to_string(), F64(1.0)),
3147 ("b".to_string(), Array(vec![
3148 Boolean(true),
3149 String("foo\nbar".to_string()),
3150 mk_object(&[
3151 ("c".to_string(), mk_object(&[("d".to_string(), Null)]))
3152 ])
3153 ]))
3154 ]));
3155 }
3156
3157 #[test]
3158 fn test_decode_struct() {
3159 let s = "{
3160 \"inner\": [
3161 { \"a\": null, \"b\": 2, \"c\": [\"abc\", \"xyz\"] }
3162 ]
3163 }";
3164
3165 let v: Outer = super::decode(s).unwrap();
3166 assert_eq!(
3167 v,
3168 Outer {
3169 inner: vec![
3170 Inner { a: (), b: 2, c: vec!["abc".to_string(), "xyz".to_string()] }
3171 ]
3172 }
3173 );
3174 }
3175
3176 #[derive(RustcDecodable)]
3177 struct FloatStruct {
3178 f: f64,
3179 a: Vec<f64>
3180 }
3181 #[test]
3182 fn test_decode_struct_with_nan() {
3183 let s = "{\"f\":null,\"a\":[null,123]}";
3184 let obj: FloatStruct = super::decode(s).unwrap();
3185 assert!(obj.f.is_nan());
3186 assert!(obj.a[0].is_nan());
3187 assert_eq!(obj.a[1], 123f64);
3188 }
3189
3190 #[test]
3191 fn test_decode_option() {
3192 let value: Option<string::String> = super::decode("null").unwrap();
3193 assert_eq!(value, None);
3194
3195 let value: Option<string::String> = super::decode("\"jodhpurs\"").unwrap();
3196 assert_eq!(value, Some("jodhpurs".to_string()));
3197 }
3198
3199 #[test]
3200 fn test_decode_enum() {
3201 let value: Animal = super::decode("\"Dog\"").unwrap();
3202 assert_eq!(value, Dog);
3203
3204 let s = "{\"variant\":\"Frog\",\"fields\":[\"Henry\",349]}";
3205 let value: Animal = super::decode(s).unwrap();
3206 assert_eq!(value, Frog("Henry".to_string(), 349));
3207 }
3208
3209 #[test]
3210 fn test_decode_map() {
3211 let s = "{\"a\": \"Dog\", \"b\": {\"variant\":\"Frog\",\
3212 \"fields\":[\"Henry\", 349]}}";
3213 let mut map: BTreeMap<string::String, Animal> = super::decode(s).unwrap();
3214
3215 assert_eq!(map.remove(&"a".to_string()), Some(Dog));
3216 assert_eq!(map.remove(&"b".to_string()), Some(Frog("Henry".to_string(), 349)));
3217 }
3218
3219 #[test]
3220 fn test_multiline_errors() {
3221 assert_eq!(from_str("{\n \"foo\":\n \"bar\""),
85aaf69f 3222 Err(SyntaxError(EOFWhileParsingObject, 3, 8)));
1a4d82fc
JJ
3223 }
3224
3225 #[derive(RustcDecodable)]
3226 #[allow(dead_code)]
3227 struct DecodeStruct {
3228 x: f64,
3229 y: bool,
3230 z: string::String,
3231 w: Vec<DecodeStruct>
3232 }
3233 #[derive(RustcDecodable)]
3234 enum DecodeEnum {
3235 A(f64),
3236 B(string::String)
3237 }
3238 fn check_err<T: Decodable>(to_parse: &'static str, expected: DecoderError) {
3239 let res: DecodeResult<T> = match from_str(to_parse) {
3240 Err(e) => Err(ParseError(e)),
3241 Ok(json) => Decodable::decode(&mut Decoder::new(json))
3242 };
3243 match res {
3244 Ok(_) => panic!("`{:?}` parsed & decoded ok, expecting error `{:?}`",
3245 to_parse, expected),
3246 Err(ParseError(e)) => panic!("`{:?}` is not valid json: {:?}",
3247 to_parse, e),
3248 Err(e) => {
3249 assert_eq!(e, expected);
3250 }
3251 }
3252 }
3253 #[test]
3254 fn test_decode_errors_struct() {
3255 check_err::<DecodeStruct>("[]", ExpectedError("Object".to_string(), "[]".to_string()));
3256 check_err::<DecodeStruct>("{\"x\": true, \"y\": true, \"z\": \"\", \"w\": []}",
3257 ExpectedError("Number".to_string(), "true".to_string()));
3258 check_err::<DecodeStruct>("{\"x\": 1, \"y\": [], \"z\": \"\", \"w\": []}",
3259 ExpectedError("Boolean".to_string(), "[]".to_string()));
3260 check_err::<DecodeStruct>("{\"x\": 1, \"y\": true, \"z\": {}, \"w\": []}",
3261 ExpectedError("String".to_string(), "{}".to_string()));
3262 check_err::<DecodeStruct>("{\"x\": 1, \"y\": true, \"z\": \"\", \"w\": null}",
3263 ExpectedError("Array".to_string(), "null".to_string()));
3264 check_err::<DecodeStruct>("{\"x\": 1, \"y\": true, \"z\": \"\"}",
3265 MissingFieldError("w".to_string()));
3266 }
3267 #[test]
3268 fn test_decode_errors_enum() {
3269 check_err::<DecodeEnum>("{}",
3270 MissingFieldError("variant".to_string()));
3271 check_err::<DecodeEnum>("{\"variant\": 1}",
3272 ExpectedError("String".to_string(), "1".to_string()));
3273 check_err::<DecodeEnum>("{\"variant\": \"A\"}",
3274 MissingFieldError("fields".to_string()));
3275 check_err::<DecodeEnum>("{\"variant\": \"A\", \"fields\": null}",
3276 ExpectedError("Array".to_string(), "null".to_string()));
3277 check_err::<DecodeEnum>("{\"variant\": \"C\", \"fields\": []}",
3278 UnknownVariantError("C".to_string()));
3279 }
3280
3281 #[test]
3282 fn test_find(){
3283 let json_value = from_str("{\"dog\" : \"cat\"}").unwrap();
3284 let found_str = json_value.find("dog");
3285 assert!(found_str.unwrap().as_string().unwrap() == "cat");
3286 }
3287
3288 #[test]
3289 fn test_find_path(){
3290 let json_value = from_str("{\"dog\":{\"cat\": {\"mouse\" : \"cheese\"}}}").unwrap();
3291 let found_str = json_value.find_path(&["dog", "cat", "mouse"]);
3292 assert!(found_str.unwrap().as_string().unwrap() == "cheese");
3293 }
3294
3295 #[test]
3296 fn test_search(){
3297 let json_value = from_str("{\"dog\":{\"cat\": {\"mouse\" : \"cheese\"}}}").unwrap();
3298 let found_str = json_value.search("mouse").and_then(|j| j.as_string());
3299 assert!(found_str.unwrap() == "cheese");
3300 }
3301
3302 #[test]
3303 fn test_index(){
3304 let json_value = from_str("{\"animals\":[\"dog\",\"cat\",\"mouse\"]}").unwrap();
3305 let ref array = json_value["animals"];
3306 assert_eq!(array[0].as_string().unwrap(), "dog");
3307 assert_eq!(array[1].as_string().unwrap(), "cat");
3308 assert_eq!(array[2].as_string().unwrap(), "mouse");
3309 }
3310
3311 #[test]
3312 fn test_is_object(){
3313 let json_value = from_str("{}").unwrap();
3314 assert!(json_value.is_object());
3315 }
3316
3317 #[test]
3318 fn test_as_object(){
3319 let json_value = from_str("{}").unwrap();
3320 let json_object = json_value.as_object();
3321 assert!(json_object.is_some());
3322 }
3323
3324 #[test]
3325 fn test_is_array(){
3326 let json_value = from_str("[1, 2, 3]").unwrap();
3327 assert!(json_value.is_array());
3328 }
3329
3330 #[test]
3331 fn test_as_array(){
3332 let json_value = from_str("[1, 2, 3]").unwrap();
3333 let json_array = json_value.as_array();
3334 let expected_length = 3;
3335 assert!(json_array.is_some() && json_array.unwrap().len() == expected_length);
3336 }
3337
3338 #[test]
3339 fn test_is_string(){
3340 let json_value = from_str("\"dog\"").unwrap();
3341 assert!(json_value.is_string());
3342 }
3343
3344 #[test]
3345 fn test_as_string(){
3346 let json_value = from_str("\"dog\"").unwrap();
3347 let json_str = json_value.as_string();
3348 let expected_str = "dog";
3349 assert_eq!(json_str, Some(expected_str));
3350 }
3351
3352 #[test]
3353 fn test_is_number(){
3354 let json_value = from_str("12").unwrap();
3355 assert!(json_value.is_number());
3356 }
3357
3358 #[test]
3359 fn test_is_i64(){
3360 let json_value = from_str("-12").unwrap();
3361 assert!(json_value.is_i64());
3362
3363 let json_value = from_str("12").unwrap();
3364 assert!(!json_value.is_i64());
3365
3366 let json_value = from_str("12.0").unwrap();
3367 assert!(!json_value.is_i64());
3368 }
3369
3370 #[test]
3371 fn test_is_u64(){
3372 let json_value = from_str("12").unwrap();
3373 assert!(json_value.is_u64());
3374
3375 let json_value = from_str("-12").unwrap();
3376 assert!(!json_value.is_u64());
3377
3378 let json_value = from_str("12.0").unwrap();
3379 assert!(!json_value.is_u64());
3380 }
3381
3382 #[test]
3383 fn test_is_f64(){
3384 let json_value = from_str("12").unwrap();
3385 assert!(!json_value.is_f64());
3386
3387 let json_value = from_str("-12").unwrap();
3388 assert!(!json_value.is_f64());
3389
3390 let json_value = from_str("12.0").unwrap();
3391 assert!(json_value.is_f64());
3392
3393 let json_value = from_str("-12.0").unwrap();
3394 assert!(json_value.is_f64());
3395 }
3396
3397 #[test]
3398 fn test_as_i64(){
3399 let json_value = from_str("-12").unwrap();
3400 let json_num = json_value.as_i64();
3401 assert_eq!(json_num, Some(-12));
3402 }
3403
3404 #[test]
3405 fn test_as_u64(){
3406 let json_value = from_str("12").unwrap();
3407 let json_num = json_value.as_u64();
3408 assert_eq!(json_num, Some(12));
3409 }
3410
3411 #[test]
3412 fn test_as_f64(){
3413 let json_value = from_str("12.0").unwrap();
3414 let json_num = json_value.as_f64();
3415 assert_eq!(json_num, Some(12f64));
3416 }
3417
3418 #[test]
3419 fn test_is_boolean(){
3420 let json_value = from_str("false").unwrap();
3421 assert!(json_value.is_boolean());
3422 }
3423
3424 #[test]
3425 fn test_as_boolean(){
3426 let json_value = from_str("false").unwrap();
3427 let json_bool = json_value.as_boolean();
3428 let expected_bool = false;
3429 assert!(json_bool.is_some() && json_bool.unwrap() == expected_bool);
3430 }
3431
3432 #[test]
3433 fn test_is_null(){
3434 let json_value = from_str("null").unwrap();
3435 assert!(json_value.is_null());
3436 }
3437
3438 #[test]
3439 fn test_as_null(){
3440 let json_value = from_str("null").unwrap();
3441 let json_null = json_value.as_null();
3442 let expected_null = ();
3443 assert!(json_null.is_some() && json_null.unwrap() == expected_null);
3444 }
3445
3446 #[test]
3447 fn test_encode_hashmap_with_numeric_key() {
3448 use std::str::from_utf8;
1a4d82fc 3449 use std::collections::HashMap;
c34b1796 3450 let mut hm: HashMap<usize, bool> = HashMap::new();
1a4d82fc
JJ
3451 hm.insert(1, true);
3452 let mut mem_buf = Vec::new();
3453 write!(&mut mem_buf, "{}", super::as_pretty_json(&hm)).unwrap();
85aaf69f 3454 let json_str = from_utf8(&mem_buf[..]).unwrap();
1a4d82fc
JJ
3455 match from_str(json_str) {
3456 Err(_) => panic!("Unable to parse json_str: {:?}", json_str),
3457 _ => {} // it parsed and we are good to go
3458 }
3459 }
3460
3461 #[test]
3462 fn test_prettyencode_hashmap_with_numeric_key() {
3463 use std::str::from_utf8;
1a4d82fc 3464 use std::collections::HashMap;
c34b1796 3465 let mut hm: HashMap<usize, bool> = HashMap::new();
1a4d82fc
JJ
3466 hm.insert(1, true);
3467 let mut mem_buf = Vec::new();
3468 write!(&mut mem_buf, "{}", super::as_pretty_json(&hm)).unwrap();
85aaf69f 3469 let json_str = from_utf8(&mem_buf[..]).unwrap();
1a4d82fc
JJ
3470 match from_str(json_str) {
3471 Err(_) => panic!("Unable to parse json_str: {:?}", json_str),
3472 _ => {} // it parsed and we are good to go
3473 }
3474 }
3475
3476 #[test]
3477 fn test_prettyencoder_indent_level_param() {
3478 use std::str::from_utf8;
3479 use std::collections::BTreeMap;
3480
3481 let mut tree = BTreeMap::new();
3482
3483 tree.insert("hello".to_string(), String("guten tag".to_string()));
3484 tree.insert("goodbye".to_string(), String("sayonara".to_string()));
3485
3486 let json = Array(
3487 // The following layout below should look a lot like
3488 // the pretty-printed JSON (indent * x)
3489 vec!
3490 ( // 0x
3491 String("greetings".to_string()), // 1x
3492 Object(tree), // 1x + 2x + 2x + 1x
3493 ) // 0x
3494 // End JSON array (7 lines)
3495 );
3496
3497 // Helper function for counting indents
c34b1796 3498 fn indents(source: &str) -> usize {
1a4d82fc
JJ
3499 let trimmed = source.trim_left_matches(' ');
3500 source.len() - trimmed.len()
3501 }
3502
3503 // Test up to 4 spaces of indents (more?)
85aaf69f 3504 for i in 0..4 {
1a4d82fc
JJ
3505 let mut writer = Vec::new();
3506 write!(&mut writer, "{}",
3507 super::as_pretty_json(&json).indent(i)).unwrap();
3508
85aaf69f 3509 let printed = from_utf8(&writer[..]).unwrap();
1a4d82fc
JJ
3510
3511 // Check for indents at each line
3512 let lines: Vec<&str> = printed.lines().collect();
3513 assert_eq!(lines.len(), 7); // JSON should be 7 lines
3514
3515 assert_eq!(indents(lines[0]), 0 * i); // [
3516 assert_eq!(indents(lines[1]), 1 * i); // "greetings",
3517 assert_eq!(indents(lines[2]), 1 * i); // {
3518 assert_eq!(indents(lines[3]), 2 * i); // "hello": "guten tag",
3519 assert_eq!(indents(lines[4]), 2 * i); // "goodbye": "sayonara"
3520 assert_eq!(indents(lines[5]), 1 * i); // },
3521 assert_eq!(indents(lines[6]), 0 * i); // ]
3522
3523 // Finally, test that the pretty-printed JSON is valid
3524 from_str(printed).ok().expect("Pretty-printed JSON is invalid!");
3525 }
3526 }
3527
85aaf69f
SL
3528 #[test]
3529 fn test_hashmap_with_enum_key() {
3530 use std::collections::HashMap;
3531 use json;
3532 #[derive(RustcEncodable, Eq, Hash, PartialEq, RustcDecodable, Debug)]
3533 enum Enum {
3534 Foo,
3535 #[allow(dead_code)]
3536 Bar,
3537 }
3538 let mut map = HashMap::new();
3539 map.insert(Enum::Foo, 0);
3540 let result = json::encode(&map).unwrap();
3541 assert_eq!(&result[..], r#"{"Foo":0}"#);
3542 let decoded: HashMap<Enum, _> = json::decode(&result).unwrap();
3543 assert_eq!(map, decoded);
3544 }
3545
1a4d82fc
JJ
3546 #[test]
3547 fn test_hashmap_with_numeric_key_can_handle_double_quote_delimited_key() {
3548 use std::collections::HashMap;
3549 use Decodable;
3550 let json_str = "{\"1\":true}";
3551 let json_obj = match from_str(json_str) {
3552 Err(_) => panic!("Unable to parse json_str: {:?}", json_str),
3553 Ok(o) => o
3554 };
3555 let mut decoder = Decoder::new(json_obj);
c34b1796 3556 let _hm: HashMap<usize, bool> = Decodable::decode(&mut decoder).unwrap();
1a4d82fc
JJ
3557 }
3558
3559 #[test]
3560 fn test_hashmap_with_numeric_key_will_error_with_string_keys() {
3561 use std::collections::HashMap;
3562 use Decodable;
3563 let json_str = "{\"a\":true}";
3564 let json_obj = match from_str(json_str) {
3565 Err(_) => panic!("Unable to parse json_str: {:?}", json_str),
3566 Ok(o) => o
3567 };
3568 let mut decoder = Decoder::new(json_obj);
c34b1796 3569 let result: Result<HashMap<usize, bool>, DecoderError> = Decodable::decode(&mut decoder);
1a4d82fc
JJ
3570 assert_eq!(result, Err(ExpectedError("Number".to_string(), "a".to_string())));
3571 }
3572
3573 fn assert_stream_equal(src: &str,
3574 expected: Vec<(JsonEvent, Vec<StackElement>)>) {
3575 let mut parser = Parser::new(src.chars());
3576 let mut i = 0;
3577 loop {
3578 let evt = match parser.next() {
3579 Some(e) => e,
3580 None => { break; }
3581 };
3582 let (ref expected_evt, ref expected_stack) = expected[i];
85aaf69f 3583 if !parser.stack().is_equal_to(expected_stack) {
1a4d82fc
JJ
3584 panic!("Parser stack is not equal to {:?}", expected_stack);
3585 }
3586 assert_eq!(&evt, expected_evt);
3587 i+=1;
3588 }
3589 }
3590 #[test]
1a4d82fc
JJ
3591 fn test_streaming_parser() {
3592 assert_stream_equal(
3593 r#"{ "foo":"bar", "array" : [0, 1, 2, 3, 4, 5], "idents":[null,true,false]}"#,
3594 vec![
3595 (ObjectStart, vec![]),
3596 (StringValue("bar".to_string()), vec![StackElement::Key("foo")]),
3597 (ArrayStart, vec![StackElement::Key("array")]),
3598 (U64Value(0), vec![StackElement::Key("array"), StackElement::Index(0)]),
3599 (U64Value(1), vec![StackElement::Key("array"), StackElement::Index(1)]),
3600 (U64Value(2), vec![StackElement::Key("array"), StackElement::Index(2)]),
3601 (U64Value(3), vec![StackElement::Key("array"), StackElement::Index(3)]),
3602 (U64Value(4), vec![StackElement::Key("array"), StackElement::Index(4)]),
3603 (U64Value(5), vec![StackElement::Key("array"), StackElement::Index(5)]),
3604 (ArrayEnd, vec![StackElement::Key("array")]),
3605 (ArrayStart, vec![StackElement::Key("idents")]),
3606 (NullValue, vec![StackElement::Key("idents"),
3607 StackElement::Index(0)]),
3608 (BooleanValue(true), vec![StackElement::Key("idents"),
3609 StackElement::Index(1)]),
3610 (BooleanValue(false), vec![StackElement::Key("idents"),
3611 StackElement::Index(2)]),
3612 (ArrayEnd, vec![StackElement::Key("idents")]),
3613 (ObjectEnd, vec![]),
3614 ]
3615 );
3616 }
3617 fn last_event(src: &str) -> JsonEvent {
3618 let mut parser = Parser::new(src.chars());
3619 let mut evt = NullValue;
3620 loop {
3621 evt = match parser.next() {
3622 Some(e) => e,
3623 None => return evt,
3624 }
3625 }
3626 }
3627
3628 #[test]
1a4d82fc
JJ
3629 fn test_read_object_streaming() {
3630 assert_eq!(last_event("{ "), Error(SyntaxError(EOFWhileParsingObject, 1, 3)));
3631 assert_eq!(last_event("{1"), Error(SyntaxError(KeyMustBeAString, 1, 2)));
3632 assert_eq!(last_event("{ \"a\""), Error(SyntaxError(EOFWhileParsingObject, 1, 6)));
3633 assert_eq!(last_event("{\"a\""), Error(SyntaxError(EOFWhileParsingObject, 1, 5)));
3634 assert_eq!(last_event("{\"a\" "), Error(SyntaxError(EOFWhileParsingObject, 1, 6)));
3635
3636 assert_eq!(last_event("{\"a\" 1"), Error(SyntaxError(ExpectedColon, 1, 6)));
3637 assert_eq!(last_event("{\"a\":"), Error(SyntaxError(EOFWhileParsingValue, 1, 6)));
3638 assert_eq!(last_event("{\"a\":1"), Error(SyntaxError(EOFWhileParsingObject, 1, 7)));
3639 assert_eq!(last_event("{\"a\":1 1"), Error(SyntaxError(InvalidSyntax, 1, 8)));
3640 assert_eq!(last_event("{\"a\":1,"), Error(SyntaxError(EOFWhileParsingObject, 1, 8)));
3641 assert_eq!(last_event("{\"a\":1,}"), Error(SyntaxError(TrailingComma, 1, 8)));
3642
3643 assert_stream_equal(
3644 "{}",
3645 vec![(ObjectStart, vec![]), (ObjectEnd, vec![])]
3646 );
3647 assert_stream_equal(
3648 "{\"a\": 3}",
3649 vec![
3650 (ObjectStart, vec![]),
3651 (U64Value(3), vec![StackElement::Key("a")]),
3652 (ObjectEnd, vec![]),
3653 ]
3654 );
3655 assert_stream_equal(
3656 "{ \"a\": null, \"b\" : true }",
3657 vec![
3658 (ObjectStart, vec![]),
3659 (NullValue, vec![StackElement::Key("a")]),
3660 (BooleanValue(true), vec![StackElement::Key("b")]),
3661 (ObjectEnd, vec![]),
3662 ]
3663 );
3664 assert_stream_equal(
3665 "{\"a\" : 1.0 ,\"b\": [ true ]}",
3666 vec![
3667 (ObjectStart, vec![]),
3668 (F64Value(1.0), vec![StackElement::Key("a")]),
3669 (ArrayStart, vec![StackElement::Key("b")]),
3670 (BooleanValue(true),vec![StackElement::Key("b"), StackElement::Index(0)]),
3671 (ArrayEnd, vec![StackElement::Key("b")]),
3672 (ObjectEnd, vec![]),
3673 ]
3674 );
3675 assert_stream_equal(
3676 r#"{
3677 "a": 1.0,
3678 "b": [
3679 true,
3680 "foo\nbar",
3681 { "c": {"d": null} }
3682 ]
3683 }"#,
3684 vec![
3685 (ObjectStart, vec![]),
3686 (F64Value(1.0), vec![StackElement::Key("a")]),
3687 (ArrayStart, vec![StackElement::Key("b")]),
3688 (BooleanValue(true), vec![StackElement::Key("b"),
3689 StackElement::Index(0)]),
3690 (StringValue("foo\nbar".to_string()), vec![StackElement::Key("b"),
3691 StackElement::Index(1)]),
3692 (ObjectStart, vec![StackElement::Key("b"),
3693 StackElement::Index(2)]),
3694 (ObjectStart, vec![StackElement::Key("b"),
3695 StackElement::Index(2),
3696 StackElement::Key("c")]),
3697 (NullValue, vec![StackElement::Key("b"),
3698 StackElement::Index(2),
3699 StackElement::Key("c"),
3700 StackElement::Key("d")]),
3701 (ObjectEnd, vec![StackElement::Key("b"),
3702 StackElement::Index(2),
3703 StackElement::Key("c")]),
3704 (ObjectEnd, vec![StackElement::Key("b"),
3705 StackElement::Index(2)]),
3706 (ArrayEnd, vec![StackElement::Key("b")]),
3707 (ObjectEnd, vec![]),
3708 ]
3709 );
3710 }
3711 #[test]
1a4d82fc
JJ
3712 fn test_read_array_streaming() {
3713 assert_stream_equal(
3714 "[]",
3715 vec![
3716 (ArrayStart, vec![]),
3717 (ArrayEnd, vec![]),
3718 ]
3719 );
3720 assert_stream_equal(
3721 "[ ]",
3722 vec![
3723 (ArrayStart, vec![]),
3724 (ArrayEnd, vec![]),
3725 ]
3726 );
3727 assert_stream_equal(
3728 "[true]",
3729 vec![
3730 (ArrayStart, vec![]),
3731 (BooleanValue(true), vec![StackElement::Index(0)]),
3732 (ArrayEnd, vec![]),
3733 ]
3734 );
3735 assert_stream_equal(
3736 "[ false ]",
3737 vec![
3738 (ArrayStart, vec![]),
3739 (BooleanValue(false), vec![StackElement::Index(0)]),
3740 (ArrayEnd, vec![]),
3741 ]
3742 );
3743 assert_stream_equal(
3744 "[null]",
3745 vec![
3746 (ArrayStart, vec![]),
3747 (NullValue, vec![StackElement::Index(0)]),
3748 (ArrayEnd, vec![]),
3749 ]
3750 );
3751 assert_stream_equal(
3752 "[3, 1]",
3753 vec![
3754 (ArrayStart, vec![]),
3755 (U64Value(3), vec![StackElement::Index(0)]),
3756 (U64Value(1), vec![StackElement::Index(1)]),
3757 (ArrayEnd, vec![]),
3758 ]
3759 );
3760 assert_stream_equal(
3761 "\n[3, 2]\n",
3762 vec![
3763 (ArrayStart, vec![]),
3764 (U64Value(3), vec![StackElement::Index(0)]),
3765 (U64Value(2), vec![StackElement::Index(1)]),
3766 (ArrayEnd, vec![]),
3767 ]
3768 );
3769 assert_stream_equal(
3770 "[2, [4, 1]]",
3771 vec![
3772 (ArrayStart, vec![]),
3773 (U64Value(2), vec![StackElement::Index(0)]),
3774 (ArrayStart, vec![StackElement::Index(1)]),
3775 (U64Value(4), vec![StackElement::Index(1), StackElement::Index(0)]),
3776 (U64Value(1), vec![StackElement::Index(1), StackElement::Index(1)]),
3777 (ArrayEnd, vec![StackElement::Index(1)]),
3778 (ArrayEnd, vec![]),
3779 ]
3780 );
3781
3782 assert_eq!(last_event("["), Error(SyntaxError(EOFWhileParsingValue, 1, 2)));
3783
3784 assert_eq!(from_str("["), Err(SyntaxError(EOFWhileParsingValue, 1, 2)));
3785 assert_eq!(from_str("[1"), Err(SyntaxError(EOFWhileParsingArray, 1, 3)));
3786 assert_eq!(from_str("[1,"), Err(SyntaxError(EOFWhileParsingValue, 1, 4)));
3787 assert_eq!(from_str("[1,]"), Err(SyntaxError(InvalidSyntax, 1, 4)));
3788 assert_eq!(from_str("[6 7]"), Err(SyntaxError(InvalidSyntax, 1, 4)));
3789
3790 }
3791 #[test]
3792 fn test_trailing_characters_streaming() {
3793 assert_eq!(last_event("nulla"), Error(SyntaxError(TrailingCharacters, 1, 5)));
3794 assert_eq!(last_event("truea"), Error(SyntaxError(TrailingCharacters, 1, 5)));
3795 assert_eq!(last_event("falsea"), Error(SyntaxError(TrailingCharacters, 1, 6)));
3796 assert_eq!(last_event("1a"), Error(SyntaxError(TrailingCharacters, 1, 2)));
3797 assert_eq!(last_event("[]a"), Error(SyntaxError(TrailingCharacters, 1, 3)));
3798 assert_eq!(last_event("{}a"), Error(SyntaxError(TrailingCharacters, 1, 3)));
3799 }
3800 #[test]
3801 fn test_read_identifiers_streaming() {
3802 assert_eq!(Parser::new("null".chars()).next(), Some(NullValue));
3803 assert_eq!(Parser::new("true".chars()).next(), Some(BooleanValue(true)));
3804 assert_eq!(Parser::new("false".chars()).next(), Some(BooleanValue(false)));
3805
3806 assert_eq!(last_event("n"), Error(SyntaxError(InvalidSyntax, 1, 2)));
3807 assert_eq!(last_event("nul"), Error(SyntaxError(InvalidSyntax, 1, 4)));
3808 assert_eq!(last_event("t"), Error(SyntaxError(InvalidSyntax, 1, 2)));
3809 assert_eq!(last_event("truz"), Error(SyntaxError(InvalidSyntax, 1, 4)));
3810 assert_eq!(last_event("f"), Error(SyntaxError(InvalidSyntax, 1, 2)));
3811 assert_eq!(last_event("faz"), Error(SyntaxError(InvalidSyntax, 1, 3)));
3812 }
3813
3814 #[test]
3815 fn test_stack() {
3816 let mut stack = Stack::new();
3817
3818 assert!(stack.is_empty());
9346a6ac 3819 assert!(stack.is_empty());
1a4d82fc
JJ
3820 assert!(!stack.last_is_index());
3821
3822 stack.push_index(0);
3823 stack.bump_index();
3824
3825 assert!(stack.len() == 1);
3826 assert!(stack.is_equal_to(&[StackElement::Index(1)]));
3827 assert!(stack.starts_with(&[StackElement::Index(1)]));
3828 assert!(stack.ends_with(&[StackElement::Index(1)]));
3829 assert!(stack.last_is_index());
3830 assert!(stack.get(0) == StackElement::Index(1));
3831
3832 stack.push_key("foo".to_string());
3833
3834 assert!(stack.len() == 2);
3835 assert!(stack.is_equal_to(&[StackElement::Index(1), StackElement::Key("foo")]));
3836 assert!(stack.starts_with(&[StackElement::Index(1), StackElement::Key("foo")]));
3837 assert!(stack.starts_with(&[StackElement::Index(1)]));
3838 assert!(stack.ends_with(&[StackElement::Index(1), StackElement::Key("foo")]));
3839 assert!(stack.ends_with(&[StackElement::Key("foo")]));
3840 assert!(!stack.last_is_index());
3841 assert!(stack.get(0) == StackElement::Index(1));
3842 assert!(stack.get(1) == StackElement::Key("foo"));
3843
3844 stack.push_key("bar".to_string());
3845
3846 assert!(stack.len() == 3);
3847 assert!(stack.is_equal_to(&[StackElement::Index(1),
3848 StackElement::Key("foo"),
3849 StackElement::Key("bar")]));
3850 assert!(stack.starts_with(&[StackElement::Index(1)]));
3851 assert!(stack.starts_with(&[StackElement::Index(1), StackElement::Key("foo")]));
3852 assert!(stack.starts_with(&[StackElement::Index(1),
3853 StackElement::Key("foo"),
3854 StackElement::Key("bar")]));
3855 assert!(stack.ends_with(&[StackElement::Key("bar")]));
3856 assert!(stack.ends_with(&[StackElement::Key("foo"), StackElement::Key("bar")]));
3857 assert!(stack.ends_with(&[StackElement::Index(1),
3858 StackElement::Key("foo"),
3859 StackElement::Key("bar")]));
3860 assert!(!stack.last_is_index());
3861 assert!(stack.get(0) == StackElement::Index(1));
3862 assert!(stack.get(1) == StackElement::Key("foo"));
3863 assert!(stack.get(2) == StackElement::Key("bar"));
3864
3865 stack.pop();
3866
3867 assert!(stack.len() == 2);
3868 assert!(stack.is_equal_to(&[StackElement::Index(1), StackElement::Key("foo")]));
3869 assert!(stack.starts_with(&[StackElement::Index(1), StackElement::Key("foo")]));
3870 assert!(stack.starts_with(&[StackElement::Index(1)]));
3871 assert!(stack.ends_with(&[StackElement::Index(1), StackElement::Key("foo")]));
3872 assert!(stack.ends_with(&[StackElement::Key("foo")]));
3873 assert!(!stack.last_is_index());
3874 assert!(stack.get(0) == StackElement::Index(1));
3875 assert!(stack.get(1) == StackElement::Key("foo"));
3876 }
3877
3878 #[test]
3879 fn test_to_json() {
3880 use std::collections::{HashMap,BTreeMap};
3881 use super::ToJson;
3882
c30ab7b3
SL
3883 let array2 = Array(vec![U64(1), U64(2)]);
3884 let array3 = Array(vec![U64(1), U64(2), U64(3)]);
1a4d82fc
JJ
3885 let object = {
3886 let mut tree_map = BTreeMap::new();
3887 tree_map.insert("a".to_string(), U64(1));
3888 tree_map.insert("b".to_string(), U64(2));
3889 Object(tree_map)
3890 };
3891
3892 assert_eq!(array2.to_json(), array2);
3893 assert_eq!(object.to_json(), object);
85aaf69f 3894 assert_eq!(3_isize.to_json(), I64(3));
1a4d82fc
JJ
3895 assert_eq!(4_i8.to_json(), I64(4));
3896 assert_eq!(5_i16.to_json(), I64(5));
3897 assert_eq!(6_i32.to_json(), I64(6));
3898 assert_eq!(7_i64.to_json(), I64(7));
85aaf69f 3899 assert_eq!(8_usize.to_json(), U64(8));
1a4d82fc
JJ
3900 assert_eq!(9_u8.to_json(), U64(9));
3901 assert_eq!(10_u16.to_json(), U64(10));
3902 assert_eq!(11_u32.to_json(), U64(11));
3903 assert_eq!(12_u64.to_json(), U64(12));
3904 assert_eq!(13.0_f32.to_json(), F64(13.0_f64));
3905 assert_eq!(14.0_f64.to_json(), F64(14.0_f64));
3906 assert_eq!(().to_json(), Null);
3907 assert_eq!(f32::INFINITY.to_json(), Null);
3908 assert_eq!(f64::NAN.to_json(), Null);
3909 assert_eq!(true.to_json(), Boolean(true));
3910 assert_eq!(false.to_json(), Boolean(false));
3911 assert_eq!("abc".to_json(), String("abc".to_string()));
3912 assert_eq!("abc".to_string().to_json(), String("abc".to_string()));
85aaf69f
SL
3913 assert_eq!((1_usize, 2_usize).to_json(), array2);
3914 assert_eq!((1_usize, 2_usize, 3_usize).to_json(), array3);
3915 assert_eq!([1_usize, 2_usize].to_json(), array2);
3916 assert_eq!((&[1_usize, 2_usize, 3_usize]).to_json(), array3);
3917 assert_eq!((vec![1_usize, 2_usize]).to_json(), array2);
c30ab7b3 3918 assert_eq!(vec![1_usize, 2_usize, 3_usize].to_json(), array3);
1a4d82fc 3919 let mut tree_map = BTreeMap::new();
85aaf69f 3920 tree_map.insert("a".to_string(), 1 as usize);
1a4d82fc
JJ
3921 tree_map.insert("b".to_string(), 2);
3922 assert_eq!(tree_map.to_json(), object);
3923 let mut hash_map = HashMap::new();
85aaf69f 3924 hash_map.insert("a".to_string(), 1 as usize);
1a4d82fc
JJ
3925 hash_map.insert("b".to_string(), 2);
3926 assert_eq!(hash_map.to_json(), object);
85aaf69f
SL
3927 assert_eq!(Some(15).to_json(), I64(15));
3928 assert_eq!(Some(15 as usize).to_json(), U64(15));
c34b1796 3929 assert_eq!(None::<isize>.to_json(), Null);
1a4d82fc
JJ
3930 }
3931
85aaf69f
SL
3932 #[test]
3933 fn test_encode_hashmap_with_arbitrary_key() {
85aaf69f 3934 use std::collections::HashMap;
85aaf69f 3935 #[derive(PartialEq, Eq, Hash, RustcEncodable)]
c34b1796 3936 struct ArbitraryType(usize);
85aaf69f
SL
3937 let mut hm: HashMap<ArbitraryType, bool> = HashMap::new();
3938 hm.insert(ArbitraryType(1), true);
3939 let mut mem_buf = string::String::new();
3940 let mut encoder = Encoder::new(&mut mem_buf);
3941 let result = hm.encode(&mut encoder);
a7813a04 3942 match result.unwrap_err() {
85aaf69f
SL
3943 EncoderError::BadHashmapKey => (),
3944 _ => panic!("expected bad hash map key")
3945 }
3946 }
3947
1a4d82fc
JJ
3948 #[bench]
3949 fn bench_streaming_small(b: &mut Bencher) {
3950 b.iter( || {
3951 let mut parser = Parser::new(
3952 r#"{
3953 "a": 1.0,
3954 "b": [
3955 true,
3956 "foo\nbar",
3957 { "c": {"d": null} }
3958 ]
3959 }"#.chars()
3960 );
3961 loop {
3962 match parser.next() {
3963 None => return,
3964 _ => {}
3965 }
3966 }
3967 });
3968 }
3969 #[bench]
3970 fn bench_small(b: &mut Bencher) {
3971 b.iter( || {
3972 let _ = from_str(r#"{
3973 "a": 1.0,
3974 "b": [
3975 true,
3976 "foo\nbar",
3977 { "c": {"d": null} }
3978 ]
3979 }"#);
3980 });
3981 }
3982
3983 fn big_json() -> string::String {
3984 let mut src = "[\n".to_string();
85aaf69f 3985 for _ in 0..500 {
1a4d82fc
JJ
3986 src.push_str(r#"{ "a": true, "b": null, "c":3.1415, "d": "Hello world", "e": \
3987 [1,2,3]},"#);
3988 }
3989 src.push_str("{}]");
3990 return src;
3991 }
3992
3993 #[bench]
3994 fn bench_streaming_large(b: &mut Bencher) {
3995 let src = big_json();
3996 b.iter( || {
3997 let mut parser = Parser::new(src.chars());
3998 loop {
3999 match parser.next() {
4000 None => return,
4001 _ => {}
4002 }
4003 }
4004 });
4005 }
4006 #[bench]
4007 fn bench_large(b: &mut Bencher) {
4008 let src = big_json();
85aaf69f 4009 b.iter( || { let _ = from_str(&src); });
1a4d82fc
JJ
4010 }
4011}