1 // Rust JSON serialization library.
2 // Copyright (c) 2011 Google Inc.
4 #![forbid(non_camel_case_types)]
5 #![allow(missing_docs)]
7 //! JSON parsing and serialization
11 //! JSON (JavaScript Object Notation) is a way to write data in Javascript.
12 //! Like XML, it allows to encode structured data in a text format that can be easily read by humans
13 //! Its simple syntax and native compatibility with JavaScript have made it a widely used format.
15 //! Data types that can be encoded are JavaScript types (see the `Json` enum for more details):
17 //! * `Boolean`: equivalent to rust's `bool`
18 //! * `Number`: equivalent to rust's `f64`
19 //! * `String`: equivalent to rust's `String`
20 //! * `Array`: equivalent to rust's `Vec<T>`, but also allowing objects of different types in the
22 //! * `Object`: equivalent to rust's `BTreeMap<String, json::Json>`
25 //! An object is a series of string keys mapping to values, in `"key": value` format.
26 //! Arrays are enclosed in square brackets ([ ... ]) and objects in curly brackets ({ ... }).
27 //! A simple JSON document encoding a person, their age, address and phone numbers could look like
31 //! "FirstName": "John",
32 //! "LastName": "Doe",
35 //! "Street": "Downing Street 10",
37 //! "Country": "Great Britain"
46 //! # Rust Type-based Encoding and Decoding
48 //! Rust provides a mechanism for low boilerplate encoding & decoding of values to and from JSON via
49 //! the serialization API.
50 //! To be able to encode a piece of data, it must implement the `serialize::RustcEncodable` trait.
51 //! To be able to decode a piece of data, it must implement the `serialize::RustcDecodable` trait.
52 //! The Rust compiler provides an annotation to automatically generate the code for these traits:
53 //! `#[derive(RustcDecodable, RustcEncodable)]`
55 //! The JSON API provides an enum `json::Json` and a trait `ToJson` to encode objects.
56 //! The `ToJson` trait provides a `to_json` method to convert an object into a `json::Json` value.
57 //! A `json::Json` value can be encoded as a string or buffer using the functions described above.
58 //! You can also use the `json::Encoder` object, which implements the `Encoder` trait.
60 //! When using `ToJson` the `RustcEncodable` trait implementation is not mandatory.
64 //! ## Using Autoserialization
66 //! Create a struct called `TestStruct` and serialize and deserialize it to and from JSON using the
67 //! serialization API, using the derived serialization code.
70 //! # #![feature(rustc_private)]
71 //! extern crate serialize as rustc_serialize; // for the deriving below
72 //! use rustc_serialize::json;
74 //! // Automatically generate `Decodable` and `Encodable` trait implementations
75 //! #[derive(RustcDecodable, RustcEncodable)]
76 //! pub struct TestStruct {
79 //! data_vector: Vec<u8>,
83 //! let object = TestStruct {
85 //! data_str: "homura".to_string(),
86 //! data_vector: vec![2,3,4,5],
89 //! // Serialize using `json::encode`
90 //! let encoded = json::encode(&object).unwrap();
92 //! // Deserialize using `json::decode`
93 //! let decoded: TestStruct = json::decode(&encoded[..]).unwrap();
97 //! ## Using the `ToJson` trait
99 //! The examples above use the `ToJson` trait to generate the JSON string, which is required
100 //! for custom mappings.
102 //! ### Simple example of `ToJson` usage
105 //! # #![feature(rustc_private)]
106 //! extern crate serialize;
107 //! use serialize::json::{self, ToJson, Json};
109 //! // A custom data structure
110 //! struct ComplexNum {
115 //! // JSON value representation
116 //! impl ToJson for ComplexNum {
117 //! fn to_json(&self) -> Json {
118 //! Json::String(format!("{}+{}i", self.a, self.b))
122 //! // Only generate `RustcEncodable` trait implementation
123 //! #[derive(Encodable)]
124 //! pub struct ComplexNumRecord {
131 //! let num = ComplexNum { a: 0.0001, b: 12.539 };
132 //! let data: String = json::encode(&ComplexNumRecord{
134 //! dsc: "test".to_string(),
135 //! val: num.to_json(),
137 //! println!("data: {}", data);
138 //! // data: {"uid":1,"dsc":"test","val":"0.0001+12.539i"};
142 //! ### Verbose example of `ToJson` usage
145 //! # #![feature(rustc_private)]
146 //! extern crate serialize;
147 //! use std::collections::BTreeMap;
148 //! use serialize::json::{self, Json, ToJson};
150 //! // Only generate `Decodable` trait implementation
151 //! #[derive(Decodable)]
152 //! pub struct TestStruct {
154 //! data_str: String,
155 //! data_vector: Vec<u8>,
158 //! // Specify encoding method manually
159 //! impl ToJson for TestStruct {
160 //! fn to_json(&self) -> Json {
161 //! let mut d = BTreeMap::new();
162 //! // All standard types implement `to_json()`, so use it
163 //! d.insert("data_int".to_string(), self.data_int.to_json());
164 //! d.insert("data_str".to_string(), self.data_str.to_json());
165 //! d.insert("data_vector".to_string(), self.data_vector.to_json());
171 //! // Serialize using `ToJson`
172 //! let input_data = TestStruct {
174 //! data_str: "madoka".to_string(),
175 //! data_vector: vec![2,3,4,5],
177 //! let json_obj: Json = input_data.to_json();
178 //! let json_str: String = json_obj.to_string();
180 //! // Deserialize like before
181 //! let decoded: TestStruct = json::decode(&json_str).unwrap();
185 use self::JsonEvent::*;
186 use self::ErrorCode::*;
187 use self::ParserError::*;
188 use self::DecoderError::*;
189 use self::ParserState::*;
190 use self::InternalStackElement::*;
192 use std::borrow::Cow;
193 use std::collections::{HashMap, BTreeMap};
194 use std::io::prelude::*;
197 use std::num::FpCategory as Fp;
199 use std::str::FromStr;
201 use std::{char, f64, fmt, str};
203 use crate::Encodable;
205 /// Represents a json value
206 #[derive(Clone, PartialEq, PartialOrd, Debug)]
211 String(string::String),
214 Object(self::Object),
218 pub type Array = Vec<Json>;
219 pub type Object = BTreeMap<string::String, Json>;
221 pub struct PrettyJson<'a> { inner: &'a Json }
223 pub struct AsJson<'a, T> { inner: &'a T }
224 pub struct AsPrettyJson<'a, T> { inner: &'a T, indent: Option<usize> }
226 /// The errors that can arise while parsing a JSON stream.
227 #[derive(Clone, Copy, PartialEq, Debug)]
231 EOFWhileParsingObject,
232 EOFWhileParsingArray,
233 EOFWhileParsingValue,
234 EOFWhileParsingString,
240 InvalidUnicodeCodePoint,
241 LoneLeadingSurrogateInHexEscape,
242 UnexpectedEndOfHexEscape,
248 #[derive(Clone, PartialEq, Debug)]
249 pub enum ParserError {
251 SyntaxError(ErrorCode, usize, usize),
252 IoError(io::ErrorKind, String),
255 // Builder and Parser have the same errors.
256 pub type BuilderError = ParserError;
258 #[derive(Clone, PartialEq, Debug)]
259 pub enum DecoderError {
260 ParseError(ParserError),
261 ExpectedError(string::String, string::String),
262 MissingFieldError(string::String),
263 UnknownVariantError(string::String),
264 ApplicationError(string::String)
267 #[derive(Copy, Clone, Debug)]
268 pub enum EncoderError {
269 FmtError(fmt::Error),
273 /// Returns a readable error string for a given error code.
274 pub fn error_str(error: ErrorCode) -> &'static str {
276 InvalidSyntax => "invalid syntax",
277 InvalidNumber => "invalid number",
278 EOFWhileParsingObject => "EOF While parsing object",
279 EOFWhileParsingArray => "EOF While parsing array",
280 EOFWhileParsingValue => "EOF While parsing value",
281 EOFWhileParsingString => "EOF While parsing string",
282 KeyMustBeAString => "key must be a string",
283 ExpectedColon => "expected `:`",
284 TrailingCharacters => "trailing characters",
285 TrailingComma => "trailing comma",
286 InvalidEscape => "invalid escape",
287 UnrecognizedHex => "invalid \\u{ esc}ape (unrecognized hex)",
288 NotFourDigit => "invalid \\u{ esc}ape (not four digits)",
289 NotUtf8 => "contents not utf-8",
290 InvalidUnicodeCodePoint => "invalid Unicode code point",
291 LoneLeadingSurrogateInHexEscape => "lone leading surrogate in hex escape",
292 UnexpectedEndOfHexEscape => "unexpected end of hex escape",
296 /// Shortcut function to decode a JSON `&str` into an object
297 pub fn decode<T: crate::Decodable>(s: &str) -> DecodeResult<T> {
298 let json = match from_str(s) {
300 Err(e) => return Err(ParseError(e))
303 let mut decoder = Decoder::new(json);
304 crate::Decodable::decode(&mut decoder)
307 /// Shortcut function to encode a `T` into a JSON `String`
308 pub fn encode<T: crate::Encodable>(object: &T) -> Result<string::String, EncoderError> {
309 let mut s = String::new();
311 let mut encoder = Encoder::new(&mut s);
312 object.encode(&mut encoder)?;
317 impl fmt::Display for ErrorCode {
318 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
319 error_str(*self).fmt(f)
323 fn io_error_to_error(io: io::Error) -> ParserError {
324 IoError(io.kind(), io.to_string())
327 impl fmt::Display for ParserError {
328 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
329 // FIXME this should be a nicer error
330 fmt::Debug::fmt(self, f)
334 impl fmt::Display for DecoderError {
335 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
336 // FIXME this should be a nicer error
337 fmt::Debug::fmt(self, f)
341 impl std::error::Error for DecoderError {
342 fn description(&self) -> &str { "decoder error" }
345 impl fmt::Display for EncoderError {
346 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
347 // FIXME this should be a nicer error
348 fmt::Debug::fmt(self, f)
352 impl std::error::Error for EncoderError {
353 fn description(&self) -> &str { "encoder error" }
356 impl From<fmt::Error> for EncoderError {
357 /// Converts a [`fmt::Error`] into `EncoderError`
359 /// This conversion does not allocate memory.
360 fn from(err: fmt::Error) -> EncoderError { EncoderError::FmtError(err) }
363 pub type EncodeResult = Result<(), EncoderError>;
364 pub type DecodeResult<T> = Result<T, DecoderError>;
366 fn escape_str(wr: &mut dyn fmt::Write, v: &str) -> EncodeResult {
371 for (i, byte) in v.bytes().enumerate() {
372 let escaped = match byte {
375 b'\x00' => "\\u0000",
376 b'\x01' => "\\u0001",
377 b'\x02' => "\\u0002",
378 b'\x03' => "\\u0003",
379 b'\x04' => "\\u0004",
380 b'\x05' => "\\u0005",
381 b'\x06' => "\\u0006",
382 b'\x07' => "\\u0007",
386 b'\x0b' => "\\u000b",
389 b'\x0e' => "\\u000e",
390 b'\x0f' => "\\u000f",
391 b'\x10' => "\\u0010",
392 b'\x11' => "\\u0011",
393 b'\x12' => "\\u0012",
394 b'\x13' => "\\u0013",
395 b'\x14' => "\\u0014",
396 b'\x15' => "\\u0015",
397 b'\x16' => "\\u0016",
398 b'\x17' => "\\u0017",
399 b'\x18' => "\\u0018",
400 b'\x19' => "\\u0019",
401 b'\x1a' => "\\u001a",
402 b'\x1b' => "\\u001b",
403 b'\x1c' => "\\u001c",
404 b'\x1d' => "\\u001d",
405 b'\x1e' => "\\u001e",
406 b'\x1f' => "\\u001f",
407 b'\x7f' => "\\u007f",
412 wr.write_str(&v[start..i])?;
415 wr.write_str(escaped)?;
420 if start != v.len() {
421 wr.write_str(&v[start..])?;
428 fn escape_char(writer: &mut dyn fmt::Write, v: char) -> EncodeResult {
429 escape_str(writer, v.encode_utf8(&mut [0; 4]))
432 fn spaces(wr: &mut dyn fmt::Write, mut n: usize) -> EncodeResult {
433 const BUF: &str = " ";
435 while n >= BUF.len() {
441 wr.write_str(&BUF[..n])?;
446 fn fmt_number_or_null(v: f64) -> string::String {
448 Fp::Nan | Fp::Infinite => string::String::from("null"),
449 _ if v.fract() != 0f64 => v.to_string(),
450 _ => v.to_string() + ".0",
454 /// A structure for implementing serialization to JSON.
455 pub struct Encoder<'a> {
456 writer: &'a mut (dyn fmt::Write+'a),
457 is_emitting_map_key: bool,
460 impl<'a> Encoder<'a> {
461 /// Creates a new JSON encoder whose output will be written to the writer
463 pub fn new(writer: &'a mut dyn fmt::Write) -> Encoder<'a> {
464 Encoder { writer: writer, is_emitting_map_key: false, }
468 macro_rules! emit_enquoted_if_mapkey {
469 ($enc:ident,$e:expr) => ({
470 if $enc.is_emitting_map_key {
471 write!($enc.writer, "\"{}\"", $e)?;
473 write!($enc.writer, "{}", $e)?;
479 impl<'a> crate::Encoder for Encoder<'a> {
480 type Error = EncoderError;
482 fn emit_unit(&mut self) -> EncodeResult {
483 if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
484 write!(self.writer, "null")?;
488 fn emit_usize(&mut self, v: usize) -> EncodeResult { emit_enquoted_if_mapkey!(self, v) }
489 fn emit_u128(&mut self, v: u128) -> EncodeResult { emit_enquoted_if_mapkey!(self, v) }
490 fn emit_u64(&mut self, v: u64) -> EncodeResult { emit_enquoted_if_mapkey!(self, v) }
491 fn emit_u32(&mut self, v: u32) -> EncodeResult { emit_enquoted_if_mapkey!(self, v) }
492 fn emit_u16(&mut self, v: u16) -> EncodeResult { emit_enquoted_if_mapkey!(self, v) }
493 fn emit_u8(&mut self, v: u8) -> EncodeResult { emit_enquoted_if_mapkey!(self, v) }
495 fn emit_isize(&mut self, v: isize) -> EncodeResult { emit_enquoted_if_mapkey!(self, v) }
496 fn emit_i128(&mut self, v: i128) -> EncodeResult { emit_enquoted_if_mapkey!(self, v) }
497 fn emit_i64(&mut self, v: i64) -> EncodeResult { emit_enquoted_if_mapkey!(self, v) }
498 fn emit_i32(&mut self, v: i32) -> EncodeResult { emit_enquoted_if_mapkey!(self, v) }
499 fn emit_i16(&mut self, v: i16) -> EncodeResult { emit_enquoted_if_mapkey!(self, v) }
500 fn emit_i8(&mut self, v: i8) -> EncodeResult { emit_enquoted_if_mapkey!(self, v) }
502 fn emit_bool(&mut self, v: bool) -> EncodeResult {
503 if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
505 write!(self.writer, "true")?;
507 write!(self.writer, "false")?;
512 fn emit_f64(&mut self, v: f64) -> EncodeResult {
513 emit_enquoted_if_mapkey!(self, fmt_number_or_null(v))
515 fn emit_f32(&mut self, v: f32) -> EncodeResult {
516 self.emit_f64(v as f64)
519 fn emit_char(&mut self, v: char) -> EncodeResult {
520 escape_char(self.writer, v)
522 fn emit_str(&mut self, v: &str) -> EncodeResult {
523 escape_str(self.writer, v)
526 fn emit_enum<F>(&mut self, _name: &str, f: F) -> EncodeResult where
527 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
532 fn emit_enum_variant<F>(&mut self,
536 f: F) -> EncodeResult where
537 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
539 // enums are encoded as strings or objects
541 // Kangaroo(34,"William") => {"variant": "Kangaroo", "fields": [34,"William"]}
543 escape_str(self.writer, name)
545 if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
546 write!(self.writer, "{{\"variant\":")?;
547 escape_str(self.writer, name)?;
548 write!(self.writer, ",\"fields\":[")?;
550 write!(self.writer, "]}}")?;
555 fn emit_enum_variant_arg<F>(&mut self, idx: usize, f: F) -> EncodeResult where
556 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
558 if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
560 write!(self.writer, ",")?;
565 fn emit_enum_struct_variant<F>(&mut self,
569 f: F) -> EncodeResult where
570 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
572 if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
573 self.emit_enum_variant(name, id, cnt, f)
576 fn emit_enum_struct_variant_field<F>(&mut self,
579 f: F) -> EncodeResult where
580 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
582 if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
583 self.emit_enum_variant_arg(idx, f)
586 fn emit_struct<F>(&mut self, _: &str, _: usize, f: F) -> EncodeResult where
587 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
589 if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
590 write!(self.writer, "{{")?;
592 write!(self.writer, "}}")?;
596 fn emit_struct_field<F>(&mut self, name: &str, idx: usize, f: F) -> EncodeResult where
597 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
599 if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
600 if idx != 0 { write!(self.writer, ",")?; }
601 escape_str(self.writer, name)?;
602 write!(self.writer, ":")?;
606 fn emit_tuple<F>(&mut self, len: usize, f: F) -> EncodeResult where
607 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
609 if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
610 self.emit_seq(len, f)
612 fn emit_tuple_arg<F>(&mut self, idx: usize, f: F) -> EncodeResult where
613 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
615 if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
616 self.emit_seq_elt(idx, f)
619 fn emit_tuple_struct<F>(&mut self, _name: &str, len: usize, f: F) -> EncodeResult where
620 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
622 if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
623 self.emit_seq(len, f)
625 fn emit_tuple_struct_arg<F>(&mut self, idx: usize, f: F) -> EncodeResult where
626 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
628 if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
629 self.emit_seq_elt(idx, f)
632 fn emit_option<F>(&mut self, f: F) -> EncodeResult where
633 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
635 if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
638 fn emit_option_none(&mut self) -> EncodeResult {
639 if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
642 fn emit_option_some<F>(&mut self, f: F) -> EncodeResult where
643 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
645 if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
649 fn emit_seq<F>(&mut self, _len: usize, f: F) -> EncodeResult where
650 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
652 if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
653 write!(self.writer, "[")?;
655 write!(self.writer, "]")?;
659 fn emit_seq_elt<F>(&mut self, idx: usize, f: F) -> EncodeResult where
660 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
662 if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
664 write!(self.writer, ",")?;
669 fn emit_map<F>(&mut self, _len: usize, f: F) -> EncodeResult where
670 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
672 if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
673 write!(self.writer, "{{")?;
675 write!(self.writer, "}}")?;
679 fn emit_map_elt_key<F>(&mut self, idx: usize, f: F) -> EncodeResult where
680 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
682 if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
683 if idx != 0 { write!(self.writer, ",")? }
684 self.is_emitting_map_key = true;
686 self.is_emitting_map_key = false;
690 fn emit_map_elt_val<F>(&mut self, _idx: usize, f: F) -> EncodeResult where
691 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
693 if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
694 write!(self.writer, ":")?;
699 /// Another encoder for JSON, but prints out human-readable JSON instead of
701 pub struct PrettyEncoder<'a> {
702 writer: &'a mut (dyn fmt::Write+'a),
705 is_emitting_map_key: bool,
708 impl<'a> PrettyEncoder<'a> {
709 /// Creates a new encoder whose output will be written to the specified writer
710 pub fn new(writer: &'a mut dyn fmt::Write) -> PrettyEncoder<'a> {
715 is_emitting_map_key: false,
719 /// Sets the number of spaces to indent for each level.
720 /// This is safe to set during encoding.
721 pub fn set_indent(&mut self, indent: usize) {
722 // self.indent very well could be 0 so we need to use checked division.
723 let level = self.curr_indent.checked_div(self.indent).unwrap_or(0);
724 self.indent = indent;
725 self.curr_indent = level * self.indent;
729 impl<'a> crate::Encoder for PrettyEncoder<'a> {
730 type Error = EncoderError;
732 fn emit_unit(&mut self) -> EncodeResult {
733 if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
734 write!(self.writer, "null")?;
738 fn emit_usize(&mut self, v: usize) -> EncodeResult { emit_enquoted_if_mapkey!(self, v) }
739 fn emit_u128(&mut self, v: u128) -> EncodeResult { emit_enquoted_if_mapkey!(self, v) }
740 fn emit_u64(&mut self, v: u64) -> EncodeResult { emit_enquoted_if_mapkey!(self, v) }
741 fn emit_u32(&mut self, v: u32) -> EncodeResult { emit_enquoted_if_mapkey!(self, v) }
742 fn emit_u16(&mut self, v: u16) -> EncodeResult { emit_enquoted_if_mapkey!(self, v) }
743 fn emit_u8(&mut self, v: u8) -> EncodeResult { emit_enquoted_if_mapkey!(self, v) }
745 fn emit_isize(&mut self, v: isize) -> EncodeResult { emit_enquoted_if_mapkey!(self, v) }
746 fn emit_i128(&mut self, v: i128) -> EncodeResult { emit_enquoted_if_mapkey!(self, v) }
747 fn emit_i64(&mut self, v: i64) -> EncodeResult { emit_enquoted_if_mapkey!(self, v) }
748 fn emit_i32(&mut self, v: i32) -> EncodeResult { emit_enquoted_if_mapkey!(self, v) }
749 fn emit_i16(&mut self, v: i16) -> EncodeResult { emit_enquoted_if_mapkey!(self, v) }
750 fn emit_i8(&mut self, v: i8) -> EncodeResult { emit_enquoted_if_mapkey!(self, v) }
752 fn emit_bool(&mut self, v: bool) -> EncodeResult {
753 if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
755 write!(self.writer, "true")?;
757 write!(self.writer, "false")?;
762 fn emit_f64(&mut self, v: f64) -> EncodeResult {
763 emit_enquoted_if_mapkey!(self, fmt_number_or_null(v))
765 fn emit_f32(&mut self, v: f32) -> EncodeResult {
766 self.emit_f64(v as f64)
769 fn emit_char(&mut self, v: char) -> EncodeResult {
770 escape_char(self.writer, v)
772 fn emit_str(&mut self, v: &str) -> EncodeResult {
773 escape_str(self.writer, v)
776 fn emit_enum<F>(&mut self, _name: &str, f: F) -> EncodeResult where
777 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
782 fn emit_enum_variant<F>(&mut self,
787 -> EncodeResult where
788 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
791 escape_str(self.writer, name)
793 if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
794 writeln!(self.writer, "{{")?;
795 self.curr_indent += self.indent;
796 spaces(self.writer, self.curr_indent)?;
797 write!(self.writer, "\"variant\": ")?;
798 escape_str(self.writer, name)?;
799 writeln!(self.writer, ",")?;
800 spaces(self.writer, self.curr_indent)?;
801 writeln!(self.writer, "\"fields\": [")?;
802 self.curr_indent += self.indent;
804 self.curr_indent -= self.indent;
805 writeln!(self.writer)?;
806 spaces(self.writer, self.curr_indent)?;
807 self.curr_indent -= self.indent;
808 writeln!(self.writer, "]")?;
809 spaces(self.writer, self.curr_indent)?;
810 write!(self.writer, "}}")?;
815 fn emit_enum_variant_arg<F>(&mut self, idx: usize, f: F) -> EncodeResult where
816 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
818 if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
820 writeln!(self.writer, ",")?;
822 spaces(self.writer, self.curr_indent)?;
826 fn emit_enum_struct_variant<F>(&mut self,
830 f: F) -> EncodeResult where
831 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
833 if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
834 self.emit_enum_variant(name, id, cnt, f)
837 fn emit_enum_struct_variant_field<F>(&mut self,
840 f: F) -> EncodeResult where
841 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
843 if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
844 self.emit_enum_variant_arg(idx, f)
848 fn emit_struct<F>(&mut self, _: &str, len: usize, f: F) -> EncodeResult where
849 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
851 if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
853 write!(self.writer, "{{}}")?;
855 write!(self.writer, "{{")?;
856 self.curr_indent += self.indent;
858 self.curr_indent -= self.indent;
859 writeln!(self.writer)?;
860 spaces(self.writer, self.curr_indent)?;
861 write!(self.writer, "}}")?;
866 fn emit_struct_field<F>(&mut self, name: &str, idx: usize, f: F) -> EncodeResult where
867 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
869 if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
871 writeln!(self.writer)?;
873 writeln!(self.writer, ",")?;
875 spaces(self.writer, self.curr_indent)?;
876 escape_str(self.writer, name)?;
877 write!(self.writer, ": ")?;
881 fn emit_tuple<F>(&mut self, len: usize, f: F) -> EncodeResult where
882 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
884 if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
885 self.emit_seq(len, f)
887 fn emit_tuple_arg<F>(&mut self, idx: usize, f: F) -> EncodeResult where
888 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
890 if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
891 self.emit_seq_elt(idx, f)
894 fn emit_tuple_struct<F>(&mut self, _: &str, len: usize, f: F) -> EncodeResult where
895 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
897 if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
898 self.emit_seq(len, f)
900 fn emit_tuple_struct_arg<F>(&mut self, idx: usize, f: F) -> EncodeResult where
901 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
903 if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
904 self.emit_seq_elt(idx, f)
907 fn emit_option<F>(&mut self, f: F) -> EncodeResult where
908 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
910 if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
913 fn emit_option_none(&mut self) -> EncodeResult {
914 if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
917 fn emit_option_some<F>(&mut self, f: F) -> EncodeResult where
918 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
920 if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
924 fn emit_seq<F>(&mut self, len: usize, f: F) -> EncodeResult where
925 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
927 if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
929 write!(self.writer, "[]")?;
931 write!(self.writer, "[")?;
932 self.curr_indent += self.indent;
934 self.curr_indent -= self.indent;
935 writeln!(self.writer)?;
936 spaces(self.writer, self.curr_indent)?;
937 write!(self.writer, "]")?;
942 fn emit_seq_elt<F>(&mut self, idx: usize, f: F) -> EncodeResult where
943 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
945 if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
947 writeln!(self.writer)?;
949 writeln!(self.writer, ",")?;
951 spaces(self.writer, self.curr_indent)?;
955 fn emit_map<F>(&mut self, len: usize, f: F) -> EncodeResult where
956 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
958 if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
960 write!(self.writer, "{{}}")?;
962 write!(self.writer, "{{")?;
963 self.curr_indent += self.indent;
965 self.curr_indent -= self.indent;
966 writeln!(self.writer)?;
967 spaces(self.writer, self.curr_indent)?;
968 write!(self.writer, "}}")?;
973 fn emit_map_elt_key<F>(&mut self, idx: usize, f: F) -> EncodeResult where
974 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
976 if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
978 writeln!(self.writer)?;
980 writeln!(self.writer, ",")?;
982 spaces(self.writer, self.curr_indent)?;
983 self.is_emitting_map_key = true;
985 self.is_emitting_map_key = false;
989 fn emit_map_elt_val<F>(&mut self, _idx: usize, f: F) -> EncodeResult where
990 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
992 if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
993 write!(self.writer, ": ")?;
998 impl Encodable for Json {
999 fn encode<E: crate::Encoder>(&self, e: &mut E) -> Result<(), E::Error> {
1001 Json::I64(v) => v.encode(e),
1002 Json::U64(v) => v.encode(e),
1003 Json::F64(v) => v.encode(e),
1004 Json::String(ref v) => v.encode(e),
1005 Json::Boolean(v) => v.encode(e),
1006 Json::Array(ref v) => v.encode(e),
1007 Json::Object(ref v) => v.encode(e),
1008 Json::Null => e.emit_unit(),
1013 /// Creates an `AsJson` wrapper which can be used to print a value as JSON
1014 /// on-the-fly via `write!`
1015 pub fn as_json<T>(t: &T) -> AsJson<'_, T> {
1019 /// Creates an `AsPrettyJson` wrapper which can be used to print a value as JSON
1020 /// on-the-fly via `write!`
1021 pub fn as_pretty_json<T>(t: &T) -> AsPrettyJson<'_, T> {
1022 AsPrettyJson { inner: t, indent: None }
1026 /// Borrow this json object as a pretty object to generate a pretty
1027 /// representation for it via `Display`.
1028 pub fn pretty(&self) -> PrettyJson<'_> {
1029 PrettyJson { inner: self }
1032 /// If the Json value is an Object, returns the value associated with the provided key.
1033 /// Otherwise, returns None.
1034 pub fn find<'a>(&'a self, key: &str) -> Option<&'a Json>{
1036 Json::Object(ref map) => map.get(key),
1041 /// Attempts to get a nested Json Object for each key in `keys`.
1042 /// If any key is found not to exist, `find_path` will return `None`.
1043 /// Otherwise, it will return the Json value associated with the final key.
1044 pub fn find_path<'a>(&'a self, keys: &[&str]) -> Option<&'a Json>{
1045 let mut target = self;
1047 target = target.find(*key)?;
1052 /// If the Json value is an Object, performs a depth-first search until
1053 /// a value associated with the provided key is found. If no value is found
1054 /// or the Json value is not an Object, returns `None`.
1055 pub fn search<'a>(&'a self, key: &str) -> Option<&'a Json> {
1057 &Json::Object(ref map) => {
1058 match map.get(key) {
1059 Some(json_value) => Some(json_value),
1062 match v.search(key) {
1063 x if x.is_some() => return x,
1075 /// Returns `true` if the Json value is an `Object`.
1076 pub fn is_object(&self) -> bool {
1077 self.as_object().is_some()
1080 /// If the Json value is an `Object`, returns the associated `BTreeMap`;
1081 /// returns `None` otherwise.
1082 pub fn as_object(&self) -> Option<&Object> {
1084 Json::Object(ref map) => Some(map),
1089 /// Returns `true` if the Json value is an `Array`.
1090 pub fn is_array(&self) -> bool {
1091 self.as_array().is_some()
1094 /// If the Json value is an `Array`, returns the associated vector;
1095 /// returns `None` otherwise.
1096 pub fn as_array(&self) -> Option<&Array> {
1098 Json::Array(ref array) => Some(&*array),
1103 /// Returns `true` if the Json value is a `String`.
1104 pub fn is_string(&self) -> bool {
1105 self.as_string().is_some()
1108 /// If the Json value is a `String`, returns the associated `str`;
1109 /// returns `None` otherwise.
1110 pub fn as_string(&self) -> Option<&str> {
1112 Json::String(ref s) => Some(&s[..]),
1117 /// Returns `true` if the Json value is a `Number`.
1118 pub fn is_number(&self) -> bool {
1120 Json::I64(_) | Json::U64(_) | Json::F64(_) => true,
1125 /// Returns `true` if the Json value is a `i64`.
1126 pub fn is_i64(&self) -> bool {
1128 Json::I64(_) => true,
1133 /// Returns `true` if the Json value is a `u64`.
1134 pub fn is_u64(&self) -> bool {
1136 Json::U64(_) => true,
1141 /// Returns `true` if the Json value is a `f64`.
1142 pub fn is_f64(&self) -> bool {
1144 Json::F64(_) => true,
1149 /// If the Json value is a number, returns or cast it to a `i64`;
1150 /// returns `None` otherwise.
1151 pub fn as_i64(&self) -> Option<i64> {
1153 Json::I64(n) => Some(n),
1154 Json::U64(n) => Some(n as i64),
1159 /// If the Json value is a number, returns or cast it to a `u64`;
1160 /// returns `None` otherwise.
1161 pub fn as_u64(&self) -> Option<u64> {
1163 Json::I64(n) => Some(n as u64),
1164 Json::U64(n) => Some(n),
1169 /// If the Json value is a number, returns or cast it to a `f64`;
1170 /// returns `None` otherwise.
1171 pub fn as_f64(&self) -> Option<f64> {
1173 Json::I64(n) => Some(n as f64),
1174 Json::U64(n) => Some(n as f64),
1175 Json::F64(n) => Some(n),
1180 /// Returns `true` if the Json value is a `Boolean`.
1181 pub fn is_boolean(&self) -> bool {
1182 self.as_boolean().is_some()
1185 /// If the Json value is a `Boolean`, returns the associated `bool`;
1186 /// returns `None` otherwise.
1187 pub fn as_boolean(&self) -> Option<bool> {
1189 Json::Boolean(b) => Some(b),
1194 /// Returns `true` if the Json value is a `Null`.
1195 pub fn is_null(&self) -> bool {
1196 self.as_null().is_some()
1199 /// If the Json value is a `Null`, returns `()`;
1200 /// returns `None` otherwise.
1201 pub fn as_null(&self) -> Option<()> {
1203 Json::Null => Some(()),
1209 impl<'a> Index<&'a str> for Json {
1212 fn index(&self, idx: &'a str) -> &Json {
1213 self.find(idx).unwrap()
1217 impl Index<usize> for Json {
1220 fn index(&self, idx: usize) -> &Json {
1222 Json::Array(ref v) => &v[idx],
1223 _ => panic!("can only index Json with usize if it is an array")
1228 /// The output of the streaming parser.
1229 #[derive(PartialEq, Clone, Debug)]
1230 pub enum JsonEvent {
1239 StringValue(string::String),
1244 #[derive(PartialEq, Debug)]
1246 // Parse a value in an array, true means first element.
1248 // Parse ',' or ']' after an element in an array.
1250 // Parse a key:value in an object, true means first element.
1252 // Parse ',' or ']' after an element in an object.
1256 // Expecting the stream to end.
1258 // Parsing can't continue.
1262 /// A Stack represents the current position of the parser in the logical
1263 /// structure of the JSON stream.
1264 /// For example foo.bar[3].x
1266 stack: Vec<InternalStackElement>,
1267 str_buffer: Vec<u8>,
1270 /// StackElements compose a Stack.
1271 /// For example, StackElement::Key("foo"), StackElement::Key("bar"),
1272 /// StackElement::Index(3) and StackElement::Key("x") are the
1273 /// StackElements compositing the stack that represents foo.bar[3].x
1274 #[derive(PartialEq, Clone, Debug)]
1275 pub enum StackElement<'l> {
1280 // Internally, Key elements are stored as indices in a buffer to avoid
1281 // allocating a string for every member of an object.
1282 #[derive(PartialEq, Clone, Debug)]
1283 enum InternalStackElement {
1285 InternalKey(u16, u16), // start, size
1289 pub fn new() -> Stack {
1290 Stack { stack: Vec::new(), str_buffer: Vec::new() }
1293 /// Returns The number of elements in the Stack.
1294 pub fn len(&self) -> usize { self.stack.len() }
1296 /// Returns `true` if the stack is empty.
1297 pub fn is_empty(&self) -> bool { self.stack.is_empty() }
1299 /// Provides access to the StackElement at a given index.
1300 /// lower indices are at the bottom of the stack while higher indices are
1302 pub fn get(&self, idx: usize) -> StackElement<'_> {
1303 match self.stack[idx] {
1304 InternalIndex(i) => StackElement::Index(i),
1305 InternalKey(start, size) => {
1306 StackElement::Key(str::from_utf8(
1307 &self.str_buffer[start as usize .. start as usize + size as usize])
1313 /// Compares this stack with an array of StackElement<'_>s.
1314 pub fn is_equal_to(&self, rhs: &[StackElement<'_>]) -> bool {
1315 if self.stack.len() != rhs.len() { return false; }
1316 for (i, r) in rhs.iter().enumerate() {
1317 if self.get(i) != *r { return false; }
1322 /// Returns `true` if the bottom-most elements of this stack are the same as
1323 /// the ones passed as parameter.
1324 pub fn starts_with(&self, rhs: &[StackElement<'_>]) -> bool {
1325 if self.stack.len() < rhs.len() { return false; }
1326 for (i, r) in rhs.iter().enumerate() {
1327 if self.get(i) != *r { return false; }
1332 /// Returns `true` if the top-most elements of this stack are the same as
1333 /// the ones passed as parameter.
1334 pub fn ends_with(&self, rhs: &[StackElement<'_>]) -> bool {
1335 if self.stack.len() < rhs.len() { return false; }
1336 let offset = self.stack.len() - rhs.len();
1337 for (i, r) in rhs.iter().enumerate() {
1338 if self.get(i + offset) != *r { return false; }
1343 /// Returns the top-most element (if any).
1344 pub fn top(&self) -> Option<StackElement<'_>> {
1345 match self.stack.last() {
1347 Some(&InternalIndex(i)) => Some(StackElement::Index(i)),
1348 Some(&InternalKey(start, size)) => {
1349 Some(StackElement::Key(str::from_utf8(
1350 &self.str_buffer[start as usize .. (start+size) as usize]
1356 // Used by Parser to insert StackElement::Key elements at the top of the stack.
1357 fn push_key(&mut self, key: string::String) {
1358 self.stack.push(InternalKey(self.str_buffer.len() as u16, key.len() as u16));
1359 self.str_buffer.extend(key.as_bytes());
1362 // Used by Parser to insert StackElement::Index elements at the top of the stack.
1363 fn push_index(&mut self, index: u32) {
1364 self.stack.push(InternalIndex(index));
1367 // Used by Parser to remove the top-most element of the stack.
1369 assert!(!self.is_empty());
1370 match *self.stack.last().unwrap() {
1371 InternalKey(_, sz) => {
1372 let new_size = self.str_buffer.len() - sz as usize;
1373 self.str_buffer.truncate(new_size);
1375 InternalIndex(_) => {}
1380 // Used by Parser to test whether the top-most element is an index.
1381 fn last_is_index(&self) -> bool {
1382 match self.stack.last() {
1383 Some(InternalIndex(_)) => true,
1388 // Used by Parser to increment the index of the top-most element.
1389 fn bump_index(&mut self) {
1390 let len = self.stack.len();
1391 let idx = match *self.stack.last().unwrap() {
1392 InternalIndex(i) => { i + 1 }
1395 self.stack[len - 1] = InternalIndex(idx);
1399 /// A streaming JSON parser implemented as an iterator of JsonEvent, consuming
1400 /// an iterator of char.
1401 pub struct Parser<T> {
1406 // We maintain a stack representing where we are in the logical structure
1407 // of the JSON stream.
1409 // A state machine is kept to make it possible to interrupt and resume parsing.
1413 impl<T: Iterator<Item=char>> Iterator for Parser<T> {
1414 type Item = JsonEvent;
1416 fn next(&mut self) -> Option<JsonEvent> {
1417 if self.state == ParseFinished {
1421 if self.state == ParseBeforeFinish {
1422 self.parse_whitespace();
1423 // Make sure there is no trailing characters.
1425 self.state = ParseFinished;
1428 return Some(self.error_event(TrailingCharacters));
1436 impl<T: Iterator<Item=char>> Parser<T> {
1437 /// Creates the JSON parser.
1438 pub fn new(rdr: T) -> Parser<T> {
1439 let mut p = Parser {
1444 stack: Stack::new(),
1451 /// Provides access to the current position in the logical structure of the
1453 pub fn stack(&self) -> &Stack {
1457 fn eof(&self) -> bool { self.ch.is_none() }
1458 fn ch_or_null(&self) -> char { self.ch.unwrap_or('\x00') }
1459 fn bump(&mut self) {
1460 self.ch = self.rdr.next();
1462 if self.ch_is('\n') {
1470 fn next_char(&mut self) -> Option<char> {
1474 fn ch_is(&self, c: char) -> bool {
1478 fn error<U>(&self, reason: ErrorCode) -> Result<U, ParserError> {
1479 Err(SyntaxError(reason, self.line, self.col))
1482 fn parse_whitespace(&mut self) {
1483 while self.ch_is(' ') ||
1486 self.ch_is('\r') { self.bump(); }
1489 fn parse_number(&mut self) -> JsonEvent {
1490 let mut neg = false;
1492 if self.ch_is('-') {
1497 let res = match self.parse_u64() {
1499 Err(e) => { return Error(e); }
1502 if self.ch_is('.') || self.ch_is('e') || self.ch_is('E') {
1503 let mut res = res as f64;
1505 if self.ch_is('.') {
1506 res = match self.parse_decimal(res) {
1508 Err(e) => { return Error(e); }
1512 if self.ch_is('e') || self.ch_is('E') {
1513 res = match self.parse_exponent(res) {
1515 Err(e) => { return Error(e); }
1525 let res = (res as i64).wrapping_neg();
1527 // Make sure we didn't underflow.
1529 Error(SyntaxError(InvalidNumber, self.line, self.col))
1538 fn parse_u64(&mut self) -> Result<u64, ParserError> {
1539 let mut accum = 0u64;
1540 let last_accum = 0; // necessary to detect overflow.
1542 match self.ch_or_null() {
1546 // A leading '0' must be the only digit before the decimal point.
1547 if let '0' ..= '9' = self.ch_or_null() {
1548 return self.error(InvalidNumber)
1553 match self.ch_or_null() {
1554 c @ '0' ..= '9' => {
1555 accum = accum.wrapping_mul(10);
1556 accum = accum.wrapping_add((c as u64) - ('0' as u64));
1558 // Detect overflow by comparing to the last value.
1559 if accum <= last_accum { return self.error(InvalidNumber); }
1567 _ => return self.error(InvalidNumber),
1573 fn parse_decimal(&mut self, mut res: f64) -> Result<f64, ParserError> {
1576 // Make sure a digit follows the decimal place.
1577 match self.ch_or_null() {
1579 _ => return self.error(InvalidNumber)
1584 match self.ch_or_null() {
1585 c @ '0' ..= '9' => {
1587 res += (((c as isize) - ('0' as isize)) as f64) * dec;
1597 fn parse_exponent(&mut self, mut res: f64) -> Result<f64, ParserError> {
1601 let mut neg_exp = false;
1603 if self.ch_is('+') {
1605 } else if self.ch_is('-') {
1610 // Make sure a digit follows the exponent place.
1611 match self.ch_or_null() {
1613 _ => return self.error(InvalidNumber)
1616 match self.ch_or_null() {
1617 c @ '0' ..= '9' => {
1619 exp += (c as usize) - ('0' as usize);
1627 let exp = 10_f64.powi(exp as i32);
1637 fn decode_hex_escape(&mut self) -> Result<u16, ParserError> {
1640 while i < 4 && !self.eof() {
1642 n = match self.ch_or_null() {
1643 c @ '0' ..= '9' => n * 16 + ((c as u16) - ('0' as u16)),
1644 'a' | 'A' => n * 16 + 10,
1645 'b' | 'B' => n * 16 + 11,
1646 'c' | 'C' => n * 16 + 12,
1647 'd' | 'D' => n * 16 + 13,
1648 'e' | 'E' => n * 16 + 14,
1649 'f' | 'F' => n * 16 + 15,
1650 _ => return self.error(InvalidEscape)
1656 // Error out if we didn't parse 4 digits.
1658 return self.error(InvalidEscape);
1664 fn parse_str(&mut self) -> Result<string::String, ParserError> {
1665 let mut escape = false;
1666 let mut res = string::String::new();
1671 return self.error(EOFWhileParsingString);
1675 match self.ch_or_null() {
1676 '"' => res.push('"'),
1677 '\\' => res.push('\\'),
1678 '/' => res.push('/'),
1679 'b' => res.push('\x08'),
1680 'f' => res.push('\x0c'),
1681 'n' => res.push('\n'),
1682 'r' => res.push('\r'),
1683 't' => res.push('\t'),
1684 'u' => match self.decode_hex_escape()? {
1685 0xDC00 ..= 0xDFFF => {
1686 return self.error(LoneLeadingSurrogateInHexEscape)
1689 // Non-BMP characters are encoded as a sequence of
1690 // two hex escapes, representing UTF-16 surrogates.
1691 n1 @ 0xD800 ..= 0xDBFF => {
1692 match (self.next_char(), self.next_char()) {
1693 (Some('\\'), Some('u')) => (),
1694 _ => return self.error(UnexpectedEndOfHexEscape),
1697 let n2 = self.decode_hex_escape()?;
1698 if n2 < 0xDC00 || n2 > 0xDFFF {
1699 return self.error(LoneLeadingSurrogateInHexEscape)
1701 let c = (((n1 - 0xD800) as u32) << 10 |
1702 (n2 - 0xDC00) as u32) + 0x1_0000;
1703 res.push(char::from_u32(c).unwrap());
1706 n => match char::from_u32(n as u32) {
1707 Some(c) => res.push(c),
1708 None => return self.error(InvalidUnicodeCodePoint),
1711 _ => return self.error(InvalidEscape),
1714 } else if self.ch_is('\\') {
1722 Some(c) => res.push(c),
1723 None => unreachable!()
1729 // Invoked at each iteration, consumes the stream until it has enough
1730 // information to return a JsonEvent.
1731 // Manages an internal state so that parsing can be interrupted and resumed.
1732 // Also keeps track of the position in the logical structure of the json
1733 // stream isize the form of a stack that can be queried by the user using the
1735 fn parse(&mut self) -> JsonEvent {
1737 // The only paths where the loop can spin a new iteration
1738 // are in the cases ParseArrayComma and ParseObjectComma if ','
1739 // is parsed. In these cases the state is set to (respectively)
1740 // ParseArray(false) and ParseObject(false), which always return,
1741 // so there is no risk of getting stuck in an infinite loop.
1742 // All other paths return before the end of the loop's iteration.
1743 self.parse_whitespace();
1747 return self.parse_start();
1749 ParseArray(first) => {
1750 return self.parse_array(first);
1752 ParseArrayComma => {
1753 if let Some(evt) = self.parse_array_comma_or_end() {
1757 ParseObject(first) => {
1758 return self.parse_object(first);
1760 ParseObjectComma => {
1762 if self.ch_is(',') {
1763 self.state = ParseObject(false);
1766 return self.parse_object_end();
1770 return self.error_event(InvalidSyntax);
1776 fn parse_start(&mut self) -> JsonEvent {
1777 let val = self.parse_value();
1778 self.state = match val {
1779 Error(_) => ParseFinished,
1780 ArrayStart => ParseArray(true),
1781 ObjectStart => ParseObject(true),
1782 _ => ParseBeforeFinish,
1787 fn parse_array(&mut self, first: bool) -> JsonEvent {
1788 if self.ch_is(']') {
1790 self.error_event(InvalidSyntax)
1792 self.state = if self.stack.is_empty() {
1794 } else if self.stack.last_is_index() {
1804 self.stack.push_index(0);
1806 let val = self.parse_value();
1807 self.state = match val {
1808 Error(_) => ParseFinished,
1809 ArrayStart => ParseArray(true),
1810 ObjectStart => ParseObject(true),
1811 _ => ParseArrayComma,
1817 fn parse_array_comma_or_end(&mut self) -> Option<JsonEvent> {
1818 if self.ch_is(',') {
1819 self.stack.bump_index();
1820 self.state = ParseArray(false);
1823 } else if self.ch_is(']') {
1825 self.state = if self.stack.is_empty() {
1827 } else if self.stack.last_is_index() {
1834 } else if self.eof() {
1835 Some(self.error_event(EOFWhileParsingArray))
1837 Some(self.error_event(InvalidSyntax))
1841 fn parse_object(&mut self, first: bool) -> JsonEvent {
1842 if self.ch_is('}') {
1844 if self.stack.is_empty() {
1845 return self.error_event(TrailingComma);
1850 self.state = if self.stack.is_empty() {
1852 } else if self.stack.last_is_index() {
1861 return self.error_event(EOFWhileParsingObject);
1863 if !self.ch_is('"') {
1864 return self.error_event(KeyMustBeAString);
1866 let s = match self.parse_str() {
1869 self.state = ParseFinished;
1873 self.parse_whitespace();
1875 return self.error_event(EOFWhileParsingObject);
1876 } else if self.ch_or_null() != ':' {
1877 return self.error_event(ExpectedColon);
1879 self.stack.push_key(s);
1881 self.parse_whitespace();
1883 let val = self.parse_value();
1885 self.state = match val {
1886 Error(_) => ParseFinished,
1887 ArrayStart => ParseArray(true),
1888 ObjectStart => ParseObject(true),
1889 _ => ParseObjectComma,
1894 fn parse_object_end(&mut self) -> JsonEvent {
1895 if self.ch_is('}') {
1896 self.state = if self.stack.is_empty() {
1898 } else if self.stack.last_is_index() {
1905 } else if self.eof() {
1906 self.error_event(EOFWhileParsingObject)
1908 self.error_event(InvalidSyntax)
1912 fn parse_value(&mut self) -> JsonEvent {
1913 if self.eof() { return self.error_event(EOFWhileParsingValue); }
1914 match self.ch_or_null() {
1915 'n' => { self.parse_ident("ull", NullValue) }
1916 't' => { self.parse_ident("rue", BooleanValue(true)) }
1917 'f' => { self.parse_ident("alse", BooleanValue(false)) }
1918 '0' ..= '9' | '-' => self.parse_number(),
1919 '"' => match self.parse_str() {
1920 Ok(s) => StringValue(s),
1931 _ => { self.error_event(InvalidSyntax) }
1935 fn parse_ident(&mut self, ident: &str, value: JsonEvent) -> JsonEvent {
1936 if ident.chars().all(|c| Some(c) == self.next_char()) {
1940 Error(SyntaxError(InvalidSyntax, self.line, self.col))
1944 fn error_event(&mut self, reason: ErrorCode) -> JsonEvent {
1945 self.state = ParseFinished;
1946 Error(SyntaxError(reason, self.line, self.col))
1950 /// A Builder consumes a json::Parser to create a generic Json structure.
1951 pub struct Builder<T> {
1953 token: Option<JsonEvent>,
1956 impl<T: Iterator<Item=char>> Builder<T> {
1957 /// Creates a JSON Builder.
1958 pub fn new(src: T) -> Builder<T> {
1959 Builder { parser: Parser::new(src), token: None, }
1962 // Decode a Json value from a Parser.
1963 pub fn build(&mut self) -> Result<Json, BuilderError> {
1965 let result = self.build_value();
1969 Some(Error(ref e)) => { return Err(e.clone()); }
1970 ref tok => { panic!("unexpected token {:?}", tok.clone()); }
1975 fn bump(&mut self) {
1976 self.token = self.parser.next();
1979 fn build_value(&mut self) -> Result<Json, BuilderError> {
1981 Some(NullValue) => Ok(Json::Null),
1982 Some(I64Value(n)) => Ok(Json::I64(n)),
1983 Some(U64Value(n)) => Ok(Json::U64(n)),
1984 Some(F64Value(n)) => Ok(Json::F64(n)),
1985 Some(BooleanValue(b)) => Ok(Json::Boolean(b)),
1986 Some(StringValue(ref mut s)) => {
1987 let mut temp = string::String::new();
1989 Ok(Json::String(temp))
1991 Some(Error(ref e)) => Err(e.clone()),
1992 Some(ArrayStart) => self.build_array(),
1993 Some(ObjectStart) => self.build_object(),
1994 Some(ObjectEnd) => self.parser.error(InvalidSyntax),
1995 Some(ArrayEnd) => self.parser.error(InvalidSyntax),
1996 None => self.parser.error(EOFWhileParsingValue),
2000 fn build_array(&mut self) -> Result<Json, BuilderError> {
2002 let mut values = Vec::new();
2005 if self.token == Some(ArrayEnd) {
2006 return Ok(Json::Array(values.into_iter().collect()));
2008 match self.build_value() {
2009 Ok(v) => values.push(v),
2010 Err(e) => { return Err(e) }
2016 fn build_object(&mut self) -> Result<Json, BuilderError> {
2019 let mut values = BTreeMap::new();
2023 Some(ObjectEnd) => { return Ok(Json::Object(values)); }
2024 Some(Error(ref e)) => { return Err(e.clone()); }
2028 let key = match self.parser.stack().top() {
2029 Some(StackElement::Key(k)) => { k.to_owned() }
2030 _ => { panic!("invalid state"); }
2032 match self.build_value() {
2033 Ok(value) => { values.insert(key, value); }
2034 Err(e) => { return Err(e); }
2038 self.parser.error(EOFWhileParsingObject)
2042 /// Decodes a json value from an `&mut io::Read`
2043 pub fn from_reader(rdr: &mut dyn Read) -> Result<Json, BuilderError> {
2044 let mut contents = Vec::new();
2045 match rdr.read_to_end(&mut contents) {
2047 Err(e) => return Err(io_error_to_error(e))
2049 let s = match str::from_utf8(&contents).ok() {
2051 _ => return Err(SyntaxError(NotUtf8, 0, 0))
2053 let mut builder = Builder::new(s.chars());
2057 /// Decodes a json value from a string
2058 pub fn from_str(s: &str) -> Result<Json, BuilderError> {
2059 let mut builder = Builder::new(s.chars());
2063 /// A structure to decode JSON to values in rust.
2064 pub struct Decoder {
2069 /// Creates a new decoder instance for decoding the specified JSON value.
2070 pub fn new(json: Json) -> Decoder {
2071 Decoder { stack: vec![json] }
2074 fn pop(&mut self) -> Json {
2075 self.stack.pop().unwrap()
2079 macro_rules! expect {
2080 ($e:expr, Null) => ({
2082 Json::Null => Ok(()),
2083 other => Err(ExpectedError("Null".to_owned(),
2087 ($e:expr, $t:ident) => ({
2089 Json::$t(v) => Ok(v),
2091 Err(ExpectedError(stringify!($t).to_owned(),
2098 macro_rules! read_primitive {
2099 ($name:ident, $ty:ty) => {
2100 fn $name(&mut self) -> DecodeResult<$ty> {
2102 Json::I64(f) => Ok(f as $ty),
2103 Json::U64(f) => Ok(f as $ty),
2104 Json::F64(f) => Err(ExpectedError("Integer".to_owned(), f.to_string())),
2105 // re: #12967.. a type w/ numeric keys (ie HashMap<usize, V> etc)
2106 // is going to have a string here, as per JSON spec.
2107 Json::String(s) => match s.parse().ok() {
2109 None => Err(ExpectedError("Number".to_owned(), s)),
2111 value => Err(ExpectedError("Number".to_owned(), value.to_string())),
2117 impl crate::Decoder for Decoder {
2118 type Error = DecoderError;
2120 fn read_nil(&mut self) -> DecodeResult<()> {
2121 expect!(self.pop(), Null)
2124 read_primitive! { read_usize, usize }
2125 read_primitive! { read_u8, u8 }
2126 read_primitive! { read_u16, u16 }
2127 read_primitive! { read_u32, u32 }
2128 read_primitive! { read_u64, u64 }
2129 read_primitive! { read_u128, u128 }
2130 read_primitive! { read_isize, isize }
2131 read_primitive! { read_i8, i8 }
2132 read_primitive! { read_i16, i16 }
2133 read_primitive! { read_i32, i32 }
2134 read_primitive! { read_i64, i64 }
2135 read_primitive! { read_i128, i128 }
2137 fn read_f32(&mut self) -> DecodeResult<f32> { self.read_f64().map(|x| x as f32) }
2139 fn read_f64(&mut self) -> DecodeResult<f64> {
2141 Json::I64(f) => Ok(f as f64),
2142 Json::U64(f) => Ok(f as f64),
2143 Json::F64(f) => Ok(f),
2144 Json::String(s) => {
2145 // re: #12967.. a type w/ numeric keys (ie HashMap<usize, V> etc)
2146 // is going to have a string here, as per JSON spec.
2147 match s.parse().ok() {
2149 None => Err(ExpectedError("Number".to_owned(), s)),
2152 Json::Null => Ok(f64::NAN),
2153 value => Err(ExpectedError("Number".to_owned(), value.to_string()))
2157 fn read_bool(&mut self) -> DecodeResult<bool> {
2158 expect!(self.pop(), Boolean)
2161 fn read_char(&mut self) -> DecodeResult<char> {
2162 let s = self.read_str()?;
2164 let mut it = s.chars();
2165 match (it.next(), it.next()) {
2166 // exactly one character
2167 (Some(c), None) => return Ok(c),
2171 Err(ExpectedError("single character string".to_owned(), s.to_string()))
2174 fn read_str(&mut self) -> DecodeResult<Cow<'_, str>> {
2175 expect!(self.pop(), String).map(Cow::Owned)
2178 fn read_enum<T, F>(&mut self, _name: &str, f: F) -> DecodeResult<T> where
2179 F: FnOnce(&mut Decoder) -> DecodeResult<T>,
2184 fn read_enum_variant<T, F>(&mut self, names: &[&str],
2185 mut f: F) -> DecodeResult<T>
2186 where F: FnMut(&mut Decoder, usize) -> DecodeResult<T>,
2188 let name = match self.pop() {
2189 Json::String(s) => s,
2190 Json::Object(mut o) => {
2191 let n = match o.remove(&"variant".to_owned()) {
2192 Some(Json::String(s)) => s,
2194 return Err(ExpectedError("String".to_owned(), val.to_string()))
2197 return Err(MissingFieldError("variant".to_owned()))
2200 match o.remove(&"fields".to_string()) {
2201 Some(Json::Array(l)) => {
2202 self.stack.extend(l.into_iter().rev());
2205 return Err(ExpectedError("Array".to_owned(), val.to_string()))
2208 return Err(MissingFieldError("fields".to_owned()))
2214 return Err(ExpectedError("String or Object".to_owned(), json.to_string()))
2217 let idx = match names.iter().position(|n| *n == &name[..]) {
2219 None => return Err(UnknownVariantError(name))
2224 fn read_enum_variant_arg<T, F>(&mut self, _idx: usize, f: F) -> DecodeResult<T> where
2225 F: FnOnce(&mut Decoder) -> DecodeResult<T>,
2230 fn read_enum_struct_variant<T, F>(&mut self, names: &[&str], f: F) -> DecodeResult<T> where
2231 F: FnMut(&mut Decoder, usize) -> DecodeResult<T>,
2233 self.read_enum_variant(names, f)
2237 fn read_enum_struct_variant_field<T, F>(&mut self,
2241 -> DecodeResult<T> where
2242 F: FnOnce(&mut Decoder) -> DecodeResult<T>,
2244 self.read_enum_variant_arg(idx, f)
2247 fn read_struct<T, F>(&mut self, _name: &str, _len: usize, f: F) -> DecodeResult<T> where
2248 F: FnOnce(&mut Decoder) -> DecodeResult<T>,
2250 let value = f(self)?;
2255 fn read_struct_field<T, F>(&mut self,
2259 -> DecodeResult<T> where
2260 F: FnOnce(&mut Decoder) -> DecodeResult<T>,
2262 let mut obj = expect!(self.pop(), Object)?;
2264 let value = match obj.remove(&name.to_string()) {
2266 // Add a Null and try to parse it as an Option<_>
2267 // to get None as a default value.
2268 self.stack.push(Json::Null);
2271 Err(_) => return Err(MissingFieldError(name.to_string())),
2275 self.stack.push(json);
2279 self.stack.push(Json::Object(obj));
2283 fn read_tuple<T, F>(&mut self, tuple_len: usize, f: F) -> DecodeResult<T> where
2284 F: FnOnce(&mut Decoder) -> DecodeResult<T>,
2286 self.read_seq(move |d, len| {
2287 if len == tuple_len {
2290 Err(ExpectedError(format!("Tuple{}", tuple_len), format!("Tuple{}", len)))
2295 fn read_tuple_arg<T, F>(&mut self, idx: usize, f: F) -> DecodeResult<T> where
2296 F: FnOnce(&mut Decoder) -> DecodeResult<T>,
2298 self.read_seq_elt(idx, f)
2301 fn read_tuple_struct<T, F>(&mut self,
2305 -> DecodeResult<T> where
2306 F: FnOnce(&mut Decoder) -> DecodeResult<T>,
2308 self.read_tuple(len, f)
2311 fn read_tuple_struct_arg<T, F>(&mut self,
2314 -> DecodeResult<T> where
2315 F: FnOnce(&mut Decoder) -> DecodeResult<T>,
2317 self.read_tuple_arg(idx, f)
2320 fn read_option<T, F>(&mut self, mut f: F) -> DecodeResult<T> where
2321 F: FnMut(&mut Decoder, bool) -> DecodeResult<T>,
2324 Json::Null => f(self, false),
2325 value => { self.stack.push(value); f(self, true) }
2329 fn read_seq<T, F>(&mut self, f: F) -> DecodeResult<T> where
2330 F: FnOnce(&mut Decoder, usize) -> DecodeResult<T>,
2332 let array = expect!(self.pop(), Array)?;
2333 let len = array.len();
2334 self.stack.extend(array.into_iter().rev());
2338 fn read_seq_elt<T, F>(&mut self, _idx: usize, f: F) -> DecodeResult<T> where
2339 F: FnOnce(&mut Decoder) -> DecodeResult<T>,
2344 fn read_map<T, F>(&mut self, f: F) -> DecodeResult<T> where
2345 F: FnOnce(&mut Decoder, usize) -> DecodeResult<T>,
2347 let obj = expect!(self.pop(), Object)?;
2348 let len = obj.len();
2349 for (key, value) in obj {
2350 self.stack.push(value);
2351 self.stack.push(Json::String(key));
2356 fn read_map_elt_key<T, F>(&mut self, _idx: usize, f: F) -> DecodeResult<T> where
2357 F: FnOnce(&mut Decoder) -> DecodeResult<T>,
2362 fn read_map_elt_val<T, F>(&mut self, _idx: usize, f: F) -> DecodeResult<T> where
2363 F: FnOnce(&mut Decoder) -> DecodeResult<T>,
2368 fn error(&mut self, err: &str) -> DecoderError {
2369 ApplicationError(err.to_string())
2373 /// A trait for converting values to JSON
2375 /// Converts the value of `self` to an instance of JSON
2376 fn to_json(&self) -> Json;
2379 macro_rules! to_json_impl_i64 {
2381 $(impl ToJson for $t {
2382 fn to_json(&self) -> Json {
2383 Json::I64(*self as i64)
2389 to_json_impl_i64! { isize, i8, i16, i32, i64 }
2391 macro_rules! to_json_impl_u64 {
2393 $(impl ToJson for $t {
2394 fn to_json(&self) -> Json {
2395 Json::U64(*self as u64)
2401 to_json_impl_u64! { usize, u8, u16, u32, u64 }
2403 impl ToJson for Json {
2404 fn to_json(&self) -> Json { self.clone() }
2407 impl ToJson for f32 {
2408 fn to_json(&self) -> Json { (*self as f64).to_json() }
2411 impl ToJson for f64 {
2412 fn to_json(&self) -> Json {
2413 match self.classify() {
2414 Fp::Nan | Fp::Infinite => Json::Null,
2415 _ => Json::F64(*self)
2420 impl ToJson for () {
2421 fn to_json(&self) -> Json { Json::Null }
2424 impl ToJson for bool {
2425 fn to_json(&self) -> Json { Json::Boolean(*self) }
2428 impl ToJson for str {
2429 fn to_json(&self) -> Json { Json::String(self.to_string()) }
2432 impl ToJson for string::String {
2433 fn to_json(&self) -> Json { Json::String((*self).clone()) }
2436 macro_rules! tuple_impl {
2437 // use variables to indicate the arity of the tuple
2438 ($($tyvar:ident),* ) => {
2439 // the trailing commas are for the 1 tuple
2441 $( $tyvar : ToJson ),*
2442 > ToJson for ( $( $tyvar ),* , ) {
2445 #[allow(non_snake_case)]
2446 fn to_json(&self) -> Json {
2448 ($(ref $tyvar),*,) => Json::Array(vec![$($tyvar.to_json()),*])
2457 tuple_impl!{A, B, C}
2458 tuple_impl!{A, B, C, D}
2459 tuple_impl!{A, B, C, D, E}
2460 tuple_impl!{A, B, C, D, E, F}
2461 tuple_impl!{A, B, C, D, E, F, G}
2462 tuple_impl!{A, B, C, D, E, F, G, H}
2463 tuple_impl!{A, B, C, D, E, F, G, H, I}
2464 tuple_impl!{A, B, C, D, E, F, G, H, I, J}
2465 tuple_impl!{A, B, C, D, E, F, G, H, I, J, K}
2466 tuple_impl!{A, B, C, D, E, F, G, H, I, J, K, L}
2468 impl<A: ToJson> ToJson for [A] {
2469 fn to_json(&self) -> Json { Json::Array(self.iter().map(|elt| elt.to_json()).collect()) }
2472 impl<A: ToJson> ToJson for Vec<A> {
2473 fn to_json(&self) -> Json { Json::Array(self.iter().map(|elt| elt.to_json()).collect()) }
2476 impl<A: ToJson> ToJson for BTreeMap<string::String, A> {
2477 fn to_json(&self) -> Json {
2478 let mut d = BTreeMap::new();
2479 for (key, value) in self {
2480 d.insert((*key).clone(), value.to_json());
2486 impl<A: ToJson> ToJson for HashMap<string::String, A> {
2487 fn to_json(&self) -> Json {
2488 let mut d = BTreeMap::new();
2489 for (key, value) in self {
2490 d.insert((*key).clone(), value.to_json());
2496 impl<A:ToJson> ToJson for Option<A> {
2497 fn to_json(&self) -> Json {
2500 Some(ref value) => value.to_json()
2505 struct FormatShim<'a, 'b: 'a> {
2506 inner: &'a mut fmt::Formatter<'b>,
2509 impl<'a, 'b> fmt::Write for FormatShim<'a, 'b> {
2510 fn write_str(&mut self, s: &str) -> fmt::Result {
2511 match self.inner.write_str(s) {
2513 Err(_) => Err(fmt::Error)
2518 impl fmt::Display for Json {
2519 /// Encodes a json value into a string
2520 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2521 let mut shim = FormatShim { inner: f };
2522 let mut encoder = Encoder::new(&mut shim);
2523 match self.encode(&mut encoder) {
2525 Err(_) => Err(fmt::Error)
2530 impl<'a> fmt::Display for PrettyJson<'a> {
2531 /// Encodes a json value into a string
2532 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2533 let mut shim = FormatShim { inner: f };
2534 let mut encoder = PrettyEncoder::new(&mut shim);
2535 match self.inner.encode(&mut encoder) {
2537 Err(_) => Err(fmt::Error)
2542 impl<'a, T: Encodable> fmt::Display for AsJson<'a, T> {
2543 /// Encodes a json value into a string
2544 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2545 let mut shim = FormatShim { inner: f };
2546 let mut encoder = Encoder::new(&mut shim);
2547 match self.inner.encode(&mut encoder) {
2549 Err(_) => Err(fmt::Error)
2554 impl<'a, T> AsPrettyJson<'a, T> {
2555 /// Sets the indentation level for the emitted JSON
2556 pub fn indent(mut self, indent: usize) -> AsPrettyJson<'a, T> {
2557 self.indent = Some(indent);
2562 impl<'a, T: Encodable> fmt::Display for AsPrettyJson<'a, T> {
2563 /// Encodes a json value into a string
2564 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2565 let mut shim = FormatShim { inner: f };
2566 let mut encoder = PrettyEncoder::new(&mut shim);
2567 if let Some(n) = self.indent {
2568 encoder.set_indent(n);
2570 match self.inner.encode(&mut encoder) {
2572 Err(_) => Err(fmt::Error)
2577 impl FromStr for Json {
2578 type Err = BuilderError;
2579 fn from_str(s: &str) -> Result<Json, BuilderError> {
2586 // Benchmarks and tests that require private items
2590 use super::{from_str, Parser, StackElement, Stack};
2595 let mut stack = Stack::new();
2597 assert!(stack.is_empty());
2598 assert!(stack.is_empty());
2599 assert!(!stack.last_is_index());
2601 stack.push_index(0);
2604 assert!(stack.len() == 1);
2605 assert!(stack.is_equal_to(&[StackElement::Index(1)]));
2606 assert!(stack.starts_with(&[StackElement::Index(1)]));
2607 assert!(stack.ends_with(&[StackElement::Index(1)]));
2608 assert!(stack.last_is_index());
2609 assert!(stack.get(0) == StackElement::Index(1));
2611 stack.push_key("foo".to_string());
2613 assert!(stack.len() == 2);
2614 assert!(stack.is_equal_to(&[StackElement::Index(1), StackElement::Key("foo")]));
2615 assert!(stack.starts_with(&[StackElement::Index(1), StackElement::Key("foo")]));
2616 assert!(stack.starts_with(&[StackElement::Index(1)]));
2617 assert!(stack.ends_with(&[StackElement::Index(1), StackElement::Key("foo")]));
2618 assert!(stack.ends_with(&[StackElement::Key("foo")]));
2619 assert!(!stack.last_is_index());
2620 assert!(stack.get(0) == StackElement::Index(1));
2621 assert!(stack.get(1) == StackElement::Key("foo"));
2623 stack.push_key("bar".to_string());
2625 assert!(stack.len() == 3);
2626 assert!(stack.is_equal_to(&[StackElement::Index(1),
2627 StackElement::Key("foo"),
2628 StackElement::Key("bar")]));
2629 assert!(stack.starts_with(&[StackElement::Index(1)]));
2630 assert!(stack.starts_with(&[StackElement::Index(1), StackElement::Key("foo")]));
2631 assert!(stack.starts_with(&[StackElement::Index(1),
2632 StackElement::Key("foo"),
2633 StackElement::Key("bar")]));
2634 assert!(stack.ends_with(&[StackElement::Key("bar")]));
2635 assert!(stack.ends_with(&[StackElement::Key("foo"), StackElement::Key("bar")]));
2636 assert!(stack.ends_with(&[StackElement::Index(1),
2637 StackElement::Key("foo"),
2638 StackElement::Key("bar")]));
2639 assert!(!stack.last_is_index());
2640 assert!(stack.get(0) == StackElement::Index(1));
2641 assert!(stack.get(1) == StackElement::Key("foo"));
2642 assert!(stack.get(2) == StackElement::Key("bar"));
2646 assert!(stack.len() == 2);
2647 assert!(stack.is_equal_to(&[StackElement::Index(1), StackElement::Key("foo")]));
2648 assert!(stack.starts_with(&[StackElement::Index(1), StackElement::Key("foo")]));
2649 assert!(stack.starts_with(&[StackElement::Index(1)]));
2650 assert!(stack.ends_with(&[StackElement::Index(1), StackElement::Key("foo")]));
2651 assert!(stack.ends_with(&[StackElement::Key("foo")]));
2652 assert!(!stack.last_is_index());
2653 assert!(stack.get(0) == StackElement::Index(1));
2654 assert!(stack.get(1) == StackElement::Key("foo"));
2658 fn bench_streaming_small(b: &mut Bencher) {
2660 let mut parser = Parser::new(
2666 { "c": {"d": null} }
2671 match parser.next() {
2679 fn bench_small(b: &mut Bencher) {
2681 let _ = from_str(r#"{
2686 { "c": {"d": null} }
2692 fn big_json() -> string::String {
2693 let mut src = "[\n".to_string();
2695 src.push_str(r#"{ "a": true, "b": null, "c":3.1415, "d": "Hello world", "e": \
2698 src.push_str("{}]");
2703 fn bench_streaming_large(b: &mut Bencher) {
2704 let src = big_json();
2706 let mut parser = Parser::new(src.chars());
2708 match parser.next() {
2716 fn bench_large(b: &mut Bencher) {
2717 let src = big_json();
2718 b.iter( || { let _ = from_str(&src); });