PageRenderTime 38ms CodeModel.GetById 13ms RepoModel.GetById 1ms app.codeStats 0ms

/src/libserialize/json.rs

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