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