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 //! use rustc_serialize::json;
73 //! // Automatically generate `Decodable` and `Encodable` trait implementations
74 //! #[derive(RustcDecodable, RustcEncodable)]
75 //! pub struct TestStruct {
78 //! data_vector: Vec<u8>,
81 //! let object = TestStruct {
83 //! data_str: "homura".to_string(),
84 //! data_vector: vec![2,3,4,5],
87 //! // Serialize using `json::encode`
88 //! let encoded = json::encode(&object).unwrap();
90 //! // Deserialize using `json::decode`
91 //! let decoded: TestStruct = json::decode(&encoded[..]).unwrap();
94 //! ## Using the `ToJson` trait
96 //! The examples above use the `ToJson` trait to generate the JSON string, which is required
97 //! for custom mappings.
99 //! ### Simple example of `ToJson` usage
102 //! # #![feature(rustc_private)]
103 //! use rustc_serialize::json::{self, ToJson, Json};
105 //! // A custom data structure
106 //! struct ComplexNum {
111 //! // JSON value representation
112 //! impl ToJson for ComplexNum {
113 //! fn to_json(&self) -> Json {
114 //! Json::String(format!("{}+{}i", self.a, self.b))
118 //! // Only generate `RustcEncodable` trait implementation
119 //! #[derive(RustcEncodable)]
120 //! pub struct ComplexNumRecord {
126 //! let num = ComplexNum { a: 0.0001, b: 12.539 };
127 //! let data: String = json::encode(&ComplexNumRecord{
129 //! dsc: "test".to_string(),
130 //! val: num.to_json(),
132 //! println!("data: {}", data);
133 //! // data: {"uid":1,"dsc":"test","val":"0.0001+12.539i"};
136 //! ### Verbose example of `ToJson` usage
139 //! # #![feature(rustc_private)]
140 //! use std::collections::BTreeMap;
141 //! use rustc_serialize::json::{self, Json, ToJson};
143 //! // Only generate `RustcDecodable` trait implementation
144 //! #[derive(RustcDecodable)]
145 //! pub struct TestStruct {
147 //! data_str: String,
148 //! data_vector: Vec<u8>,
151 //! // Specify encoding method manually
152 //! impl ToJson for TestStruct {
153 //! fn to_json(&self) -> Json {
154 //! let mut d = BTreeMap::new();
155 //! // All standard types implement `to_json()`, so use it
156 //! d.insert("data_int".to_string(), self.data_int.to_json());
157 //! d.insert("data_str".to_string(), self.data_str.to_json());
158 //! d.insert("data_vector".to_string(), self.data_vector.to_json());
163 //! // Serialize using `ToJson`
164 //! let input_data = TestStruct {
166 //! data_str: "madoka".to_string(),
167 //! data_vector: vec![2,3,4,5],
169 //! let json_obj: Json = input_data.to_json();
170 //! let json_str: String = json_obj.to_string();
172 //! // Deserialize like before
173 //! let decoded: TestStruct = json::decode(&json_str).unwrap();
176 use self::DecoderError::*;
177 use self::ErrorCode::*;
178 use self::InternalStackElement::*;
179 use self::JsonEvent::*;
180 use self::ParserError::*;
181 use self::ParserState::*;
183 use std::borrow::Cow;
184 use std::collections::{BTreeMap, HashMap};
186 use std::io::prelude::*;
188 use std::num::FpCategory as Fp;
190 use std::str::FromStr;
192 use std::{char, fmt, str};
194 use crate::Encodable;
196 /// Represents a json value
197 #[derive(Clone, PartialEq, PartialOrd, Debug)]
202 String(string::String),
205 Object(self::Object),
209 pub type Array = Vec<Json>;
210 pub type Object = BTreeMap<string::String, Json>;
212 pub struct PrettyJson<'a> {
216 pub struct AsJson<'a, T> {
219 pub struct AsPrettyJson<'a, T> {
221 indent: Option<usize>,
224 /// The errors that can arise while parsing a JSON stream.
225 #[derive(Clone, Copy, PartialEq, Debug)]
229 EOFWhileParsingObject,
230 EOFWhileParsingArray,
231 EOFWhileParsingValue,
232 EOFWhileParsingString,
238 InvalidUnicodeCodePoint,
239 LoneLeadingSurrogateInHexEscape,
240 UnexpectedEndOfHexEscape,
246 #[derive(Clone, PartialEq, Debug)]
247 pub enum ParserError {
249 SyntaxError(ErrorCode, usize, usize),
250 IoError(io::ErrorKind, String),
253 // Builder and Parser have the same errors.
254 pub type BuilderError = ParserError;
256 #[derive(Clone, PartialEq, Debug)]
257 pub enum DecoderError {
258 ParseError(ParserError),
259 ExpectedError(string::String, string::String),
260 MissingFieldError(string::String),
261 UnknownVariantError(string::String),
262 ApplicationError(string::String),
265 #[derive(Copy, Clone, Debug)]
266 pub enum EncoderError {
267 FmtError(fmt::Error),
271 /// Returns a readable error string for a given error code.
272 pub fn error_str(error: ErrorCode) -> &'static str {
274 InvalidSyntax => "invalid syntax",
275 InvalidNumber => "invalid number",
276 EOFWhileParsingObject => "EOF While parsing object",
277 EOFWhileParsingArray => "EOF While parsing array",
278 EOFWhileParsingValue => "EOF While parsing value",
279 EOFWhileParsingString => "EOF While parsing string",
280 KeyMustBeAString => "key must be a string",
281 ExpectedColon => "expected `:`",
282 TrailingCharacters => "trailing characters",
283 TrailingComma => "trailing comma",
284 InvalidEscape => "invalid escape",
285 UnrecognizedHex => "invalid \\u{ esc}ape (unrecognized hex)",
286 NotFourDigit => "invalid \\u{ esc}ape (not four digits)",
287 NotUtf8 => "contents not utf-8",
288 InvalidUnicodeCodePoint => "invalid Unicode code point",
289 LoneLeadingSurrogateInHexEscape => "lone leading surrogate in hex escape",
290 UnexpectedEndOfHexEscape => "unexpected end of hex escape",
294 /// Shortcut function to decode a JSON `&str` into an object
295 pub fn decode<T: crate::Decodable>(s: &str) -> DecodeResult<T> {
296 let json = match from_str(s) {
298 Err(e) => return Err(ParseError(e)),
301 let mut decoder = Decoder::new(json);
302 crate::Decodable::decode(&mut decoder)
305 /// Shortcut function to encode a `T` into a JSON `String`
306 pub fn encode<T: crate::Encodable>(object: &T) -> Result<string::String, EncoderError> {
307 let mut s = String::new();
309 let mut encoder = Encoder::new(&mut s);
310 object.encode(&mut encoder)?;
315 impl fmt::Display for ErrorCode {
316 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
317 error_str(*self).fmt(f)
321 fn io_error_to_error(io: io::Error) -> ParserError {
322 IoError(io.kind(), io.to_string())
325 impl fmt::Display for ParserError {
326 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
327 // FIXME this should be a nicer error
328 fmt::Debug::fmt(self, f)
332 impl fmt::Display for DecoderError {
333 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
334 // FIXME this should be a nicer error
335 fmt::Debug::fmt(self, f)
339 impl std::error::Error for DecoderError {}
341 impl fmt::Display for EncoderError {
342 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
343 // FIXME this should be a nicer error
344 fmt::Debug::fmt(self, f)
348 impl std::error::Error for EncoderError {}
350 impl From<fmt::Error> for EncoderError {
351 /// Converts a [`fmt::Error`] into `EncoderError`
353 /// This conversion does not allocate memory.
354 fn from(err: fmt::Error) -> EncoderError {
355 EncoderError::FmtError(err)
359 pub type EncodeResult = Result<(), EncoderError>;
360 pub type DecodeResult<T> = Result<T, DecoderError>;
362 fn escape_str(wr: &mut dyn fmt::Write, v: &str) -> EncodeResult {
367 for (i, byte) in v.bytes().enumerate() {
368 let escaped = match byte {
371 b'\x00' => "\\u0000",
372 b'\x01' => "\\u0001",
373 b'\x02' => "\\u0002",
374 b'\x03' => "\\u0003",
375 b'\x04' => "\\u0004",
376 b'\x05' => "\\u0005",
377 b'\x06' => "\\u0006",
378 b'\x07' => "\\u0007",
382 b'\x0b' => "\\u000b",
385 b'\x0e' => "\\u000e",
386 b'\x0f' => "\\u000f",
387 b'\x10' => "\\u0010",
388 b'\x11' => "\\u0011",
389 b'\x12' => "\\u0012",
390 b'\x13' => "\\u0013",
391 b'\x14' => "\\u0014",
392 b'\x15' => "\\u0015",
393 b'\x16' => "\\u0016",
394 b'\x17' => "\\u0017",
395 b'\x18' => "\\u0018",
396 b'\x19' => "\\u0019",
397 b'\x1a' => "\\u001a",
398 b'\x1b' => "\\u001b",
399 b'\x1c' => "\\u001c",
400 b'\x1d' => "\\u001d",
401 b'\x1e' => "\\u001e",
402 b'\x1f' => "\\u001f",
403 b'\x7f' => "\\u007f",
410 wr.write_str(&v[start..i])?;
413 wr.write_str(escaped)?;
418 if start != v.len() {
419 wr.write_str(&v[start..])?;
426 fn escape_char(writer: &mut dyn fmt::Write, v: char) -> EncodeResult {
427 escape_str(writer, v.encode_utf8(&mut [0; 4]))
430 fn spaces(wr: &mut dyn fmt::Write, mut n: usize) -> EncodeResult {
431 const BUF: &str = " ";
433 while n >= BUF.len() {
439 wr.write_str(&BUF[..n])?;
444 fn fmt_number_or_null(v: f64) -> string::String {
446 Fp::Nan | Fp::Infinite => string::String::from("null"),
447 _ if v.fract() != 0f64 => v.to_string(),
448 _ => v.to_string() + ".0",
452 /// A structure for implementing serialization to JSON.
453 pub struct Encoder<'a> {
454 writer: &'a mut (dyn fmt::Write + 'a),
455 is_emitting_map_key: bool,
458 impl<'a> Encoder<'a> {
459 /// Creates a new JSON encoder whose output will be written to the writer
461 pub fn new(writer: &'a mut dyn fmt::Write) -> Encoder<'a> {
462 Encoder { writer, is_emitting_map_key: false }
466 macro_rules! emit_enquoted_if_mapkey {
467 ($enc:ident,$e:expr) => {{
468 if $enc.is_emitting_map_key {
469 write!($enc.writer, "\"{}\"", $e)?;
471 write!($enc.writer, "{}", $e)?;
477 impl<'a> crate::Encoder for Encoder<'a> {
478 type Error = EncoderError;
480 fn emit_unit(&mut self) -> EncodeResult {
481 if self.is_emitting_map_key {
482 return Err(EncoderError::BadHashmapKey);
484 write!(self.writer, "null")?;
488 fn emit_usize(&mut self, v: usize) -> EncodeResult {
489 emit_enquoted_if_mapkey!(self, v)
491 fn emit_u128(&mut self, v: u128) -> EncodeResult {
492 emit_enquoted_if_mapkey!(self, v)
494 fn emit_u64(&mut self, v: u64) -> EncodeResult {
495 emit_enquoted_if_mapkey!(self, v)
497 fn emit_u32(&mut self, v: u32) -> EncodeResult {
498 emit_enquoted_if_mapkey!(self, v)
500 fn emit_u16(&mut self, v: u16) -> EncodeResult {
501 emit_enquoted_if_mapkey!(self, v)
503 fn emit_u8(&mut self, v: u8) -> EncodeResult {
504 emit_enquoted_if_mapkey!(self, v)
507 fn emit_isize(&mut self, v: isize) -> EncodeResult {
508 emit_enquoted_if_mapkey!(self, v)
510 fn emit_i128(&mut self, v: i128) -> EncodeResult {
511 emit_enquoted_if_mapkey!(self, v)
513 fn emit_i64(&mut self, v: i64) -> EncodeResult {
514 emit_enquoted_if_mapkey!(self, v)
516 fn emit_i32(&mut self, v: i32) -> EncodeResult {
517 emit_enquoted_if_mapkey!(self, v)
519 fn emit_i16(&mut self, v: i16) -> EncodeResult {
520 emit_enquoted_if_mapkey!(self, v)
522 fn emit_i8(&mut self, v: i8) -> EncodeResult {
523 emit_enquoted_if_mapkey!(self, v)
526 fn emit_bool(&mut self, v: bool) -> EncodeResult {
527 if self.is_emitting_map_key {
528 return Err(EncoderError::BadHashmapKey);
531 write!(self.writer, "true")?;
533 write!(self.writer, "false")?;
538 fn emit_f64(&mut self, v: f64) -> EncodeResult {
539 emit_enquoted_if_mapkey!(self, fmt_number_or_null(v))
541 fn emit_f32(&mut self, v: f32) -> EncodeResult {
542 self.emit_f64(f64::from(v))
545 fn emit_char(&mut self, v: char) -> EncodeResult {
546 escape_char(self.writer, v)
548 fn emit_str(&mut self, v: &str) -> EncodeResult {
549 escape_str(self.writer, v)
552 fn emit_enum<F>(&mut self, _name: &str, f: F) -> EncodeResult
554 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
559 fn emit_enum_variant<F>(&mut self, name: &str, _id: usize, cnt: usize, f: F) -> EncodeResult
561 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
563 // enums are encoded as strings or objects
565 // Kangaroo(34,"William") => {"variant": "Kangaroo", "fields": [34,"William"]}
567 escape_str(self.writer, name)
569 if self.is_emitting_map_key {
570 return Err(EncoderError::BadHashmapKey);
572 write!(self.writer, "{{\"variant\":")?;
573 escape_str(self.writer, name)?;
574 write!(self.writer, ",\"fields\":[")?;
576 write!(self.writer, "]}}")?;
581 fn emit_enum_variant_arg<F>(&mut self, idx: usize, f: F) -> EncodeResult
583 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
585 if self.is_emitting_map_key {
586 return Err(EncoderError::BadHashmapKey);
589 write!(self.writer, ",")?;
594 fn emit_enum_struct_variant<F>(
602 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
604 if self.is_emitting_map_key {
605 return Err(EncoderError::BadHashmapKey);
607 self.emit_enum_variant(name, id, cnt, f)
610 fn emit_enum_struct_variant_field<F>(&mut self, _: &str, idx: usize, f: F) -> EncodeResult
612 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
614 if self.is_emitting_map_key {
615 return Err(EncoderError::BadHashmapKey);
617 self.emit_enum_variant_arg(idx, f)
620 fn emit_struct<F>(&mut self, _: &str, _: usize, f: F) -> EncodeResult
622 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
624 if self.is_emitting_map_key {
625 return Err(EncoderError::BadHashmapKey);
627 write!(self.writer, "{{")?;
629 write!(self.writer, "}}")?;
633 fn emit_struct_field<F>(&mut self, name: &str, idx: usize, f: F) -> EncodeResult
635 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
637 if self.is_emitting_map_key {
638 return Err(EncoderError::BadHashmapKey);
641 write!(self.writer, ",")?;
643 escape_str(self.writer, name)?;
644 write!(self.writer, ":")?;
648 fn emit_tuple<F>(&mut self, len: usize, f: F) -> EncodeResult
650 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
652 if self.is_emitting_map_key {
653 return Err(EncoderError::BadHashmapKey);
655 self.emit_seq(len, f)
657 fn emit_tuple_arg<F>(&mut self, idx: usize, f: F) -> EncodeResult
659 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
661 if self.is_emitting_map_key {
662 return Err(EncoderError::BadHashmapKey);
664 self.emit_seq_elt(idx, f)
667 fn emit_tuple_struct<F>(&mut self, _name: &str, len: usize, f: F) -> EncodeResult
669 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
671 if self.is_emitting_map_key {
672 return Err(EncoderError::BadHashmapKey);
674 self.emit_seq(len, f)
676 fn emit_tuple_struct_arg<F>(&mut self, idx: usize, f: F) -> EncodeResult
678 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
680 if self.is_emitting_map_key {
681 return Err(EncoderError::BadHashmapKey);
683 self.emit_seq_elt(idx, f)
686 fn emit_option<F>(&mut self, f: F) -> EncodeResult
688 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
690 if self.is_emitting_map_key {
691 return Err(EncoderError::BadHashmapKey);
695 fn emit_option_none(&mut self) -> EncodeResult {
696 if self.is_emitting_map_key {
697 return Err(EncoderError::BadHashmapKey);
701 fn emit_option_some<F>(&mut self, f: F) -> EncodeResult
703 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
705 if self.is_emitting_map_key {
706 return Err(EncoderError::BadHashmapKey);
711 fn emit_seq<F>(&mut self, _len: usize, f: F) -> EncodeResult
713 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
715 if self.is_emitting_map_key {
716 return Err(EncoderError::BadHashmapKey);
718 write!(self.writer, "[")?;
720 write!(self.writer, "]")?;
724 fn emit_seq_elt<F>(&mut self, idx: usize, f: F) -> EncodeResult
726 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
728 if self.is_emitting_map_key {
729 return Err(EncoderError::BadHashmapKey);
732 write!(self.writer, ",")?;
737 fn emit_map<F>(&mut self, _len: usize, f: F) -> EncodeResult
739 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
741 if self.is_emitting_map_key {
742 return Err(EncoderError::BadHashmapKey);
744 write!(self.writer, "{{")?;
746 write!(self.writer, "}}")?;
750 fn emit_map_elt_key<F>(&mut self, idx: usize, f: F) -> EncodeResult
752 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
754 if self.is_emitting_map_key {
755 return Err(EncoderError::BadHashmapKey);
758 write!(self.writer, ",")?
760 self.is_emitting_map_key = true;
762 self.is_emitting_map_key = false;
766 fn emit_map_elt_val<F>(&mut self, _idx: usize, f: F) -> EncodeResult
768 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
770 if self.is_emitting_map_key {
771 return Err(EncoderError::BadHashmapKey);
773 write!(self.writer, ":")?;
778 /// Another encoder for JSON, but prints out human-readable JSON instead of
780 pub struct PrettyEncoder<'a> {
781 writer: &'a mut (dyn fmt::Write + 'a),
784 is_emitting_map_key: bool,
787 impl<'a> PrettyEncoder<'a> {
788 /// Creates a new encoder whose output will be written to the specified writer
789 pub fn new(writer: &'a mut dyn fmt::Write) -> PrettyEncoder<'a> {
790 PrettyEncoder { writer, curr_indent: 0, indent: 2, is_emitting_map_key: false }
793 /// Sets the number of spaces to indent for each level.
794 /// This is safe to set during encoding.
795 pub fn set_indent(&mut self, indent: usize) {
796 // self.indent very well could be 0 so we need to use checked division.
797 let level = self.curr_indent.checked_div(self.indent).unwrap_or(0);
798 self.indent = indent;
799 self.curr_indent = level * self.indent;
803 impl<'a> crate::Encoder for PrettyEncoder<'a> {
804 type Error = EncoderError;
806 fn emit_unit(&mut self) -> EncodeResult {
807 if self.is_emitting_map_key {
808 return Err(EncoderError::BadHashmapKey);
810 write!(self.writer, "null")?;
814 fn emit_usize(&mut self, v: usize) -> EncodeResult {
815 emit_enquoted_if_mapkey!(self, v)
817 fn emit_u128(&mut self, v: u128) -> EncodeResult {
818 emit_enquoted_if_mapkey!(self, v)
820 fn emit_u64(&mut self, v: u64) -> EncodeResult {
821 emit_enquoted_if_mapkey!(self, v)
823 fn emit_u32(&mut self, v: u32) -> EncodeResult {
824 emit_enquoted_if_mapkey!(self, v)
826 fn emit_u16(&mut self, v: u16) -> EncodeResult {
827 emit_enquoted_if_mapkey!(self, v)
829 fn emit_u8(&mut self, v: u8) -> EncodeResult {
830 emit_enquoted_if_mapkey!(self, v)
833 fn emit_isize(&mut self, v: isize) -> EncodeResult {
834 emit_enquoted_if_mapkey!(self, v)
836 fn emit_i128(&mut self, v: i128) -> EncodeResult {
837 emit_enquoted_if_mapkey!(self, v)
839 fn emit_i64(&mut self, v: i64) -> EncodeResult {
840 emit_enquoted_if_mapkey!(self, v)
842 fn emit_i32(&mut self, v: i32) -> EncodeResult {
843 emit_enquoted_if_mapkey!(self, v)
845 fn emit_i16(&mut self, v: i16) -> EncodeResult {
846 emit_enquoted_if_mapkey!(self, v)
848 fn emit_i8(&mut self, v: i8) -> EncodeResult {
849 emit_enquoted_if_mapkey!(self, v)
852 fn emit_bool(&mut self, v: bool) -> EncodeResult {
853 if self.is_emitting_map_key {
854 return Err(EncoderError::BadHashmapKey);
857 write!(self.writer, "true")?;
859 write!(self.writer, "false")?;
864 fn emit_f64(&mut self, v: f64) -> EncodeResult {
865 emit_enquoted_if_mapkey!(self, fmt_number_or_null(v))
867 fn emit_f32(&mut self, v: f32) -> EncodeResult {
868 self.emit_f64(f64::from(v))
871 fn emit_char(&mut self, v: char) -> EncodeResult {
872 escape_char(self.writer, v)
874 fn emit_str(&mut self, v: &str) -> EncodeResult {
875 escape_str(self.writer, v)
878 fn emit_enum<F>(&mut self, _name: &str, f: F) -> EncodeResult
880 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
885 fn emit_enum_variant<F>(&mut self, name: &str, _id: usize, cnt: usize, f: F) -> EncodeResult
887 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
890 escape_str(self.writer, name)
892 if self.is_emitting_map_key {
893 return Err(EncoderError::BadHashmapKey);
895 writeln!(self.writer, "{{")?;
896 self.curr_indent += self.indent;
897 spaces(self.writer, self.curr_indent)?;
898 write!(self.writer, "\"variant\": ")?;
899 escape_str(self.writer, name)?;
900 writeln!(self.writer, ",")?;
901 spaces(self.writer, self.curr_indent)?;
902 writeln!(self.writer, "\"fields\": [")?;
903 self.curr_indent += self.indent;
905 self.curr_indent -= self.indent;
906 writeln!(self.writer)?;
907 spaces(self.writer, self.curr_indent)?;
908 self.curr_indent -= self.indent;
909 writeln!(self.writer, "]")?;
910 spaces(self.writer, self.curr_indent)?;
911 write!(self.writer, "}}")?;
916 fn emit_enum_variant_arg<F>(&mut self, idx: usize, f: F) -> EncodeResult
918 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
920 if self.is_emitting_map_key {
921 return Err(EncoderError::BadHashmapKey);
924 writeln!(self.writer, ",")?;
926 spaces(self.writer, self.curr_indent)?;
930 fn emit_enum_struct_variant<F>(
938 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
940 if self.is_emitting_map_key {
941 return Err(EncoderError::BadHashmapKey);
943 self.emit_enum_variant(name, id, cnt, f)
946 fn emit_enum_struct_variant_field<F>(&mut self, _: &str, idx: usize, f: F) -> EncodeResult
948 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
950 if self.is_emitting_map_key {
951 return Err(EncoderError::BadHashmapKey);
953 self.emit_enum_variant_arg(idx, f)
956 fn emit_struct<F>(&mut self, _: &str, len: usize, f: F) -> EncodeResult
958 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
960 if self.is_emitting_map_key {
961 return Err(EncoderError::BadHashmapKey);
964 write!(self.writer, "{{}}")?;
966 write!(self.writer, "{{")?;
967 self.curr_indent += self.indent;
969 self.curr_indent -= self.indent;
970 writeln!(self.writer)?;
971 spaces(self.writer, self.curr_indent)?;
972 write!(self.writer, "}}")?;
977 fn emit_struct_field<F>(&mut self, name: &str, idx: usize, f: F) -> EncodeResult
979 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
981 if self.is_emitting_map_key {
982 return Err(EncoderError::BadHashmapKey);
985 writeln!(self.writer)?;
987 writeln!(self.writer, ",")?;
989 spaces(self.writer, self.curr_indent)?;
990 escape_str(self.writer, name)?;
991 write!(self.writer, ": ")?;
995 fn emit_tuple<F>(&mut self, len: usize, f: F) -> EncodeResult
997 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
999 if self.is_emitting_map_key {
1000 return Err(EncoderError::BadHashmapKey);
1002 self.emit_seq(len, f)
1004 fn emit_tuple_arg<F>(&mut self, idx: usize, f: F) -> EncodeResult
1006 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
1008 if self.is_emitting_map_key {
1009 return Err(EncoderError::BadHashmapKey);
1011 self.emit_seq_elt(idx, f)
1014 fn emit_tuple_struct<F>(&mut self, _: &str, len: usize, f: F) -> EncodeResult
1016 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
1018 if self.is_emitting_map_key {
1019 return Err(EncoderError::BadHashmapKey);
1021 self.emit_seq(len, f)
1023 fn emit_tuple_struct_arg<F>(&mut self, idx: usize, f: F) -> EncodeResult
1025 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
1027 if self.is_emitting_map_key {
1028 return Err(EncoderError::BadHashmapKey);
1030 self.emit_seq_elt(idx, f)
1033 fn emit_option<F>(&mut self, f: F) -> EncodeResult
1035 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
1037 if self.is_emitting_map_key {
1038 return Err(EncoderError::BadHashmapKey);
1042 fn emit_option_none(&mut self) -> EncodeResult {
1043 if self.is_emitting_map_key {
1044 return Err(EncoderError::BadHashmapKey);
1048 fn emit_option_some<F>(&mut self, f: F) -> EncodeResult
1050 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
1052 if self.is_emitting_map_key {
1053 return Err(EncoderError::BadHashmapKey);
1058 fn emit_seq<F>(&mut self, len: usize, f: F) -> EncodeResult
1060 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
1062 if self.is_emitting_map_key {
1063 return Err(EncoderError::BadHashmapKey);
1066 write!(self.writer, "[]")?;
1068 write!(self.writer, "[")?;
1069 self.curr_indent += self.indent;
1071 self.curr_indent -= self.indent;
1072 writeln!(self.writer)?;
1073 spaces(self.writer, self.curr_indent)?;
1074 write!(self.writer, "]")?;
1079 fn emit_seq_elt<F>(&mut self, idx: usize, f: F) -> EncodeResult
1081 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
1083 if self.is_emitting_map_key {
1084 return Err(EncoderError::BadHashmapKey);
1087 writeln!(self.writer)?;
1089 writeln!(self.writer, ",")?;
1091 spaces(self.writer, self.curr_indent)?;
1095 fn emit_map<F>(&mut self, len: usize, f: F) -> EncodeResult
1097 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
1099 if self.is_emitting_map_key {
1100 return Err(EncoderError::BadHashmapKey);
1103 write!(self.writer, "{{}}")?;
1105 write!(self.writer, "{{")?;
1106 self.curr_indent += self.indent;
1108 self.curr_indent -= self.indent;
1109 writeln!(self.writer)?;
1110 spaces(self.writer, self.curr_indent)?;
1111 write!(self.writer, "}}")?;
1116 fn emit_map_elt_key<F>(&mut self, idx: usize, f: F) -> EncodeResult
1118 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
1120 if self.is_emitting_map_key {
1121 return Err(EncoderError::BadHashmapKey);
1124 writeln!(self.writer)?;
1126 writeln!(self.writer, ",")?;
1128 spaces(self.writer, self.curr_indent)?;
1129 self.is_emitting_map_key = true;
1131 self.is_emitting_map_key = false;
1135 fn emit_map_elt_val<F>(&mut self, _idx: usize, f: F) -> EncodeResult
1137 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
1139 if self.is_emitting_map_key {
1140 return Err(EncoderError::BadHashmapKey);
1142 write!(self.writer, ": ")?;
1147 impl Encodable for Json {
1148 fn encode<E: crate::Encoder>(&self, e: &mut E) -> Result<(), E::Error> {
1150 Json::I64(v) => v.encode(e),
1151 Json::U64(v) => v.encode(e),
1152 Json::F64(v) => v.encode(e),
1153 Json::String(ref v) => v.encode(e),
1154 Json::Boolean(v) => v.encode(e),
1155 Json::Array(ref v) => v.encode(e),
1156 Json::Object(ref v) => v.encode(e),
1157 Json::Null => e.emit_unit(),
1162 /// Creates an `AsJson` wrapper which can be used to print a value as JSON
1163 /// on-the-fly via `write!`
1164 pub fn as_json<T>(t: &T) -> AsJson<'_, T> {
1168 /// Creates an `AsPrettyJson` wrapper which can be used to print a value as JSON
1169 /// on-the-fly via `write!`
1170 pub fn as_pretty_json<T>(t: &T) -> AsPrettyJson<'_, T> {
1171 AsPrettyJson { inner: t, indent: None }
1175 /// Borrow this json object as a pretty object to generate a pretty
1176 /// representation for it via `Display`.
1177 pub fn pretty(&self) -> PrettyJson<'_> {
1178 PrettyJson { inner: self }
1181 /// If the Json value is an Object, returns the value associated with the provided key.
1182 /// Otherwise, returns None.
1183 pub fn find(&self, key: &str) -> Option<&Json> {
1185 Json::Object(ref map) => map.get(key),
1190 /// Attempts to get a nested Json Object for each key in `keys`.
1191 /// If any key is found not to exist, `find_path` will return `None`.
1192 /// Otherwise, it will return the Json value associated with the final key.
1193 pub fn find_path<'a>(&'a self, keys: &[&str]) -> Option<&'a Json> {
1194 let mut target = self;
1196 target = target.find(*key)?;
1201 /// If the Json value is an Object, performs a depth-first search until
1202 /// a value associated with the provided key is found. If no value is found
1203 /// or the Json value is not an Object, returns `None`.
1204 pub fn search(&self, key: &str) -> Option<&Json> {
1206 Json::Object(ref map) => match map.get(key) {
1207 Some(json_value) => Some(json_value),
1209 for v in map.values() {
1210 match v.search(key) {
1211 x if x.is_some() => return x,
1222 /// Returns `true` if the Json value is an `Object`.
1223 pub fn is_object(&self) -> bool {
1224 self.as_object().is_some()
1227 /// If the Json value is an `Object`, returns the associated `BTreeMap`;
1228 /// returns `None` otherwise.
1229 pub fn as_object(&self) -> Option<&Object> {
1231 Json::Object(ref map) => Some(map),
1236 /// Returns `true` if the Json value is an `Array`.
1237 pub fn is_array(&self) -> bool {
1238 self.as_array().is_some()
1241 /// If the Json value is an `Array`, returns the associated vector;
1242 /// returns `None` otherwise.
1243 pub fn as_array(&self) -> Option<&Array> {
1245 Json::Array(ref array) => Some(&*array),
1250 /// Returns `true` if the Json value is a `String`.
1251 pub fn is_string(&self) -> bool {
1252 self.as_string().is_some()
1255 /// If the Json value is a `String`, returns the associated `str`;
1256 /// returns `None` otherwise.
1257 pub fn as_string(&self) -> Option<&str> {
1259 Json::String(ref s) => Some(&s[..]),
1264 /// Returns `true` if the Json value is a `Number`.
1265 pub fn is_number(&self) -> bool {
1266 matches!(*self, Json::I64(_) | Json::U64(_) | Json::F64(_))
1269 /// Returns `true` if the Json value is a `i64`.
1270 pub fn is_i64(&self) -> bool {
1271 matches!(*self, Json::I64(_))
1274 /// Returns `true` if the Json value is a `u64`.
1275 pub fn is_u64(&self) -> bool {
1276 matches!(*self, Json::U64(_))
1279 /// Returns `true` if the Json value is a `f64`.
1280 pub fn is_f64(&self) -> bool {
1281 matches!(*self, Json::F64(_))
1284 /// If the Json value is a number, returns or cast it to a `i64`;
1285 /// returns `None` otherwise.
1286 pub fn as_i64(&self) -> Option<i64> {
1288 Json::I64(n) => Some(n),
1289 Json::U64(n) => Some(n as i64),
1294 /// If the Json value is a number, returns or cast it to a `u64`;
1295 /// returns `None` otherwise.
1296 pub fn as_u64(&self) -> Option<u64> {
1298 Json::I64(n) => Some(n as u64),
1299 Json::U64(n) => Some(n),
1304 /// If the Json value is a number, returns or cast it to a `f64`;
1305 /// returns `None` otherwise.
1306 pub fn as_f64(&self) -> Option<f64> {
1308 Json::I64(n) => Some(n as f64),
1309 Json::U64(n) => Some(n as f64),
1310 Json::F64(n) => Some(n),
1315 /// Returns `true` if the Json value is a `Boolean`.
1316 pub fn is_boolean(&self) -> bool {
1317 self.as_boolean().is_some()
1320 /// If the Json value is a `Boolean`, returns the associated `bool`;
1321 /// returns `None` otherwise.
1322 pub fn as_boolean(&self) -> Option<bool> {
1324 Json::Boolean(b) => Some(b),
1329 /// Returns `true` if the Json value is a `Null`.
1330 pub fn is_null(&self) -> bool {
1331 self.as_null().is_some()
1334 /// If the Json value is a `Null`, returns `()`;
1335 /// returns `None` otherwise.
1336 pub fn as_null(&self) -> Option<()> {
1338 Json::Null => Some(()),
1344 impl<'a> Index<&'a str> for Json {
1347 fn index(&self, idx: &'a str) -> &Json {
1348 self.find(idx).unwrap()
1352 impl Index<usize> for Json {
1355 fn index(&self, idx: usize) -> &Json {
1357 Json::Array(ref v) => &v[idx],
1358 _ => panic!("can only index Json with usize if it is an array"),
1363 /// The output of the streaming parser.
1364 #[derive(PartialEq, Clone, Debug)]
1365 pub enum JsonEvent {
1374 StringValue(string::String),
1379 #[derive(PartialEq, Debug)]
1381 // Parse a value in an array, true means first element.
1383 // Parse ',' or ']' after an element in an array.
1385 // Parse a key:value in an object, true means first element.
1387 // Parse ',' or ']' after an element in an object.
1391 // Expecting the stream to end.
1393 // Parsing can't continue.
1397 /// A Stack represents the current position of the parser in the logical
1398 /// structure of the JSON stream.
1400 /// An example is `foo.bar[3].x`.
1403 stack: Vec<InternalStackElement>,
1404 str_buffer: Vec<u8>,
1407 /// StackElements compose a Stack.
1409 /// As an example, `StackElement::Key("foo")`, `StackElement::Key("bar")`,
1410 /// `StackElement::Index(3)`, and `StackElement::Key("x")` are the
1411 /// StackElements composing the stack that represents `foo.bar[3].x`.
1412 #[derive(PartialEq, Clone, Debug)]
1413 pub enum StackElement<'l> {
1418 // Internally, Key elements are stored as indices in a buffer to avoid
1419 // allocating a string for every member of an object.
1420 #[derive(PartialEq, Clone, Debug)]
1421 enum InternalStackElement {
1423 InternalKey(u16, u16), // start, size
1427 pub fn new() -> Stack {
1431 /// Returns The number of elements in the Stack.
1432 pub fn len(&self) -> usize {
1436 /// Returns `true` if the stack is empty.
1437 pub fn is_empty(&self) -> bool {
1438 self.stack.is_empty()
1441 /// Provides access to the StackElement at a given index.
1442 /// lower indices are at the bottom of the stack while higher indices are
1444 pub fn get(&self, idx: usize) -> StackElement<'_> {
1445 match self.stack[idx] {
1446 InternalIndex(i) => StackElement::Index(i),
1447 InternalKey(start, size) => StackElement::Key(
1448 str::from_utf8(&self.str_buffer[start as usize..start as usize + size as usize])
1454 /// Compares this stack with an array of StackElement<'_>s.
1455 pub fn is_equal_to(&self, rhs: &[StackElement<'_>]) -> bool {
1456 if self.stack.len() != rhs.len() {
1459 for (i, r) in rhs.iter().enumerate() {
1460 if self.get(i) != *r {
1467 /// Returns `true` if the bottom-most elements of this stack are the same as
1468 /// the ones passed as parameter.
1469 pub fn starts_with(&self, rhs: &[StackElement<'_>]) -> bool {
1470 if self.stack.len() < rhs.len() {
1473 for (i, r) in rhs.iter().enumerate() {
1474 if self.get(i) != *r {
1481 /// Returns `true` if the top-most elements of this stack are the same as
1482 /// the ones passed as parameter.
1483 pub fn ends_with(&self, rhs: &[StackElement<'_>]) -> bool {
1484 if self.stack.len() < rhs.len() {
1487 let offset = self.stack.len() - rhs.len();
1488 for (i, r) in rhs.iter().enumerate() {
1489 if self.get(i + offset) != *r {
1496 /// Returns the top-most element (if any).
1497 pub fn top(&self) -> Option<StackElement<'_>> {
1498 match self.stack.last() {
1500 Some(&InternalIndex(i)) => Some(StackElement::Index(i)),
1501 Some(&InternalKey(start, size)) => Some(StackElement::Key(
1502 str::from_utf8(&self.str_buffer[start as usize..(start + size) as usize]).unwrap(),
1507 // Used by Parser to insert StackElement::Key elements at the top of the stack.
1508 fn push_key(&mut self, key: string::String) {
1509 self.stack.push(InternalKey(self.str_buffer.len() as u16, key.len() as u16));
1510 self.str_buffer.extend(key.as_bytes());
1513 // Used by Parser to insert StackElement::Index elements at the top of the stack.
1514 fn push_index(&mut self, index: u32) {
1515 self.stack.push(InternalIndex(index));
1518 // Used by Parser to remove the top-most element of the stack.
1520 assert!(!self.is_empty());
1521 match *self.stack.last().unwrap() {
1522 InternalKey(_, sz) => {
1523 let new_size = self.str_buffer.len() - sz as usize;
1524 self.str_buffer.truncate(new_size);
1526 InternalIndex(_) => {}
1531 // Used by Parser to test whether the top-most element is an index.
1532 fn last_is_index(&self) -> bool {
1533 matches!(self.stack.last(), Some(InternalIndex(_)))
1536 // Used by Parser to increment the index of the top-most element.
1537 fn bump_index(&mut self) {
1538 let len = self.stack.len();
1539 let idx = match *self.stack.last().unwrap() {
1540 InternalIndex(i) => i + 1,
1545 self.stack[len - 1] = InternalIndex(idx);
1549 /// A streaming JSON parser implemented as an iterator of JsonEvent, consuming
1550 /// an iterator of char.
1551 pub struct Parser<T> {
1556 // We maintain a stack representing where we are in the logical structure
1557 // of the JSON stream.
1559 // A state machine is kept to make it possible to interrupt and resume parsing.
1563 impl<T: Iterator<Item = char>> Iterator for Parser<T> {
1564 type Item = JsonEvent;
1566 fn next(&mut self) -> Option<JsonEvent> {
1567 if self.state == ParseFinished {
1571 if self.state == ParseBeforeFinish {
1572 self.parse_whitespace();
1573 // Make sure there is no trailing characters.
1575 self.state = ParseFinished;
1578 return Some(self.error_event(TrailingCharacters));
1586 impl<T: Iterator<Item = char>> Parser<T> {
1587 /// Creates the JSON parser.
1588 pub fn new(rdr: T) -> Parser<T> {
1589 let mut p = Parser {
1594 stack: Stack::new(),
1601 /// Provides access to the current position in the logical structure of the
1603 pub fn stack(&self) -> &Stack {
1607 fn eof(&self) -> bool {
1610 fn ch_or_null(&self) -> char {
1611 self.ch.unwrap_or('\x00')
1613 fn bump(&mut self) {
1614 self.ch = self.rdr.next();
1616 if self.ch_is('\n') {
1624 fn next_char(&mut self) -> Option<char> {
1628 fn ch_is(&self, c: char) -> bool {
1632 fn error<U>(&self, reason: ErrorCode) -> Result<U, ParserError> {
1633 Err(SyntaxError(reason, self.line, self.col))
1636 fn parse_whitespace(&mut self) {
1637 while self.ch_is(' ') || self.ch_is('\n') || self.ch_is('\t') || self.ch_is('\r') {
1642 fn parse_number(&mut self) -> JsonEvent {
1643 let neg = if self.ch_is('-') {
1650 let res = match self.parse_u64() {
1657 if self.ch_is('.') || self.ch_is('e') || self.ch_is('E') {
1658 let mut res = res as f64;
1660 if self.ch_is('.') {
1661 res = match self.parse_decimal(res) {
1669 if self.ch_is('e') || self.ch_is('E') {
1670 res = match self.parse_exponent(res) {
1684 let res = (res as i64).wrapping_neg();
1686 // Make sure we didn't underflow.
1688 Error(SyntaxError(InvalidNumber, self.line, self.col))
1697 fn parse_u64(&mut self) -> Result<u64, ParserError> {
1698 let mut accum = 0u64;
1699 let last_accum = 0; // necessary to detect overflow.
1701 match self.ch_or_null() {
1705 // A leading '0' must be the only digit before the decimal point.
1706 if let '0'..='9' = self.ch_or_null() {
1707 return self.error(InvalidNumber);
1712 match self.ch_or_null() {
1714 accum = accum.wrapping_mul(10);
1715 accum = accum.wrapping_add((c as u64) - ('0' as u64));
1717 // Detect overflow by comparing to the last value.
1718 if accum <= last_accum {
1719 return self.error(InvalidNumber);
1728 _ => return self.error(InvalidNumber),
1734 fn parse_decimal(&mut self, mut res: f64) -> Result<f64, ParserError> {
1737 // Make sure a digit follows the decimal place.
1738 match self.ch_or_null() {
1740 _ => return self.error(InvalidNumber),
1745 match self.ch_or_null() {
1748 res += (((c as isize) - ('0' as isize)) as f64) * dec;
1758 fn parse_exponent(&mut self, mut res: f64) -> Result<f64, ParserError> {
1762 let mut neg_exp = false;
1764 if self.ch_is('+') {
1766 } else if self.ch_is('-') {
1771 // Make sure a digit follows the exponent place.
1772 match self.ch_or_null() {
1774 _ => return self.error(InvalidNumber),
1777 match self.ch_or_null() {
1780 exp += (c as usize) - ('0' as usize);
1788 let exp = 10_f64.powi(exp as i32);
1798 fn decode_hex_escape(&mut self) -> Result<u16, ParserError> {
1801 while i < 4 && !self.eof() {
1803 n = match self.ch_or_null() {
1804 c @ '0'..='9' => n * 16 + ((c as u16) - ('0' as u16)),
1805 'a' | 'A' => n * 16 + 10,
1806 'b' | 'B' => n * 16 + 11,
1807 'c' | 'C' => n * 16 + 12,
1808 'd' | 'D' => n * 16 + 13,
1809 'e' | 'E' => n * 16 + 14,
1810 'f' | 'F' => n * 16 + 15,
1811 _ => return self.error(InvalidEscape),
1817 // Error out if we didn't parse 4 digits.
1819 return self.error(InvalidEscape);
1825 fn parse_str(&mut self) -> Result<string::String, ParserError> {
1826 let mut escape = false;
1827 let mut res = string::String::new();
1832 return self.error(EOFWhileParsingString);
1836 match self.ch_or_null() {
1837 '"' => res.push('"'),
1838 '\\' => res.push('\\'),
1839 '/' => res.push('/'),
1840 'b' => res.push('\x08'),
1841 'f' => res.push('\x0c'),
1842 'n' => res.push('\n'),
1843 'r' => res.push('\r'),
1844 't' => res.push('\t'),
1845 'u' => match self.decode_hex_escape()? {
1846 0xDC00..=0xDFFF => return self.error(LoneLeadingSurrogateInHexEscape),
1848 // Non-BMP characters are encoded as a sequence of
1849 // two hex escapes, representing UTF-16 surrogates.
1850 n1 @ 0xD800..=0xDBFF => {
1851 match (self.next_char(), self.next_char()) {
1852 (Some('\\'), Some('u')) => (),
1853 _ => return self.error(UnexpectedEndOfHexEscape),
1856 let n2 = self.decode_hex_escape()?;
1857 if n2 < 0xDC00 || n2 > 0xDFFF {
1858 return self.error(LoneLeadingSurrogateInHexEscape);
1861 (u32::from(n1 - 0xD800) << 10 | u32::from(n2 - 0xDC00)) + 0x1_0000;
1862 res.push(char::from_u32(c).unwrap());
1865 n => match char::from_u32(u32::from(n)) {
1866 Some(c) => res.push(c),
1867 None => return self.error(InvalidUnicodeCodePoint),
1870 _ => return self.error(InvalidEscape),
1873 } else if self.ch_is('\\') {
1881 Some(c) => res.push(c),
1882 None => unreachable!(),
1888 // Invoked at each iteration, consumes the stream until it has enough
1889 // information to return a JsonEvent.
1890 // Manages an internal state so that parsing can be interrupted and resumed.
1891 // Also keeps track of the position in the logical structure of the json
1892 // stream isize the form of a stack that can be queried by the user using the
1894 fn parse(&mut self) -> JsonEvent {
1896 // The only paths where the loop can spin a new iteration
1897 // are in the cases ParseArrayComma and ParseObjectComma if ','
1898 // is parsed. In these cases the state is set to (respectively)
1899 // ParseArray(false) and ParseObject(false), which always return,
1900 // so there is no risk of getting stuck in an infinite loop.
1901 // All other paths return before the end of the loop's iteration.
1902 self.parse_whitespace();
1906 return self.parse_start();
1908 ParseArray(first) => {
1909 return self.parse_array(first);
1911 ParseArrayComma => {
1912 if let Some(evt) = self.parse_array_comma_or_end() {
1916 ParseObject(first) => {
1917 return self.parse_object(first);
1919 ParseObjectComma => {
1921 if self.ch_is(',') {
1922 self.state = ParseObject(false);
1925 return self.parse_object_end();
1929 return self.error_event(InvalidSyntax);
1935 fn parse_start(&mut self) -> JsonEvent {
1936 let val = self.parse_value();
1937 self.state = match val {
1938 Error(_) => ParseFinished,
1939 ArrayStart => ParseArray(true),
1940 ObjectStart => ParseObject(true),
1941 _ => ParseBeforeFinish,
1946 fn parse_array(&mut self, first: bool) -> JsonEvent {
1947 if self.ch_is(']') {
1949 self.error_event(InvalidSyntax)
1951 self.state = if self.stack.is_empty() {
1953 } else if self.stack.last_is_index() {
1963 self.stack.push_index(0);
1965 let val = self.parse_value();
1966 self.state = match val {
1967 Error(_) => ParseFinished,
1968 ArrayStart => ParseArray(true),
1969 ObjectStart => ParseObject(true),
1970 _ => ParseArrayComma,
1976 fn parse_array_comma_or_end(&mut self) -> Option<JsonEvent> {
1977 if self.ch_is(',') {
1978 self.stack.bump_index();
1979 self.state = ParseArray(false);
1982 } else if self.ch_is(']') {
1984 self.state = if self.stack.is_empty() {
1986 } else if self.stack.last_is_index() {
1993 } else if self.eof() {
1994 Some(self.error_event(EOFWhileParsingArray))
1996 Some(self.error_event(InvalidSyntax))
2000 fn parse_object(&mut self, first: bool) -> JsonEvent {
2001 if self.ch_is('}') {
2003 if self.stack.is_empty() {
2004 return self.error_event(TrailingComma);
2009 self.state = if self.stack.is_empty() {
2011 } else if self.stack.last_is_index() {
2020 return self.error_event(EOFWhileParsingObject);
2022 if !self.ch_is('"') {
2023 return self.error_event(KeyMustBeAString);
2025 let s = match self.parse_str() {
2028 self.state = ParseFinished;
2032 self.parse_whitespace();
2034 return self.error_event(EOFWhileParsingObject);
2035 } else if self.ch_or_null() != ':' {
2036 return self.error_event(ExpectedColon);
2038 self.stack.push_key(s);
2040 self.parse_whitespace();
2042 let val = self.parse_value();
2044 self.state = match val {
2045 Error(_) => ParseFinished,
2046 ArrayStart => ParseArray(true),
2047 ObjectStart => ParseObject(true),
2048 _ => ParseObjectComma,
2053 fn parse_object_end(&mut self) -> JsonEvent {
2054 if self.ch_is('}') {
2055 self.state = if self.stack.is_empty() {
2057 } else if self.stack.last_is_index() {
2064 } else if self.eof() {
2065 self.error_event(EOFWhileParsingObject)
2067 self.error_event(InvalidSyntax)
2071 fn parse_value(&mut self) -> JsonEvent {
2073 return self.error_event(EOFWhileParsingValue);
2075 match self.ch_or_null() {
2076 'n' => self.parse_ident("ull", NullValue),
2077 't' => self.parse_ident("rue", BooleanValue(true)),
2078 'f' => self.parse_ident("alse", BooleanValue(false)),
2079 '0'..='9' | '-' => self.parse_number(),
2080 '"' => match self.parse_str() {
2081 Ok(s) => StringValue(s),
2092 _ => self.error_event(InvalidSyntax),
2096 fn parse_ident(&mut self, ident: &str, value: JsonEvent) -> JsonEvent {
2097 if ident.chars().all(|c| Some(c) == self.next_char()) {
2101 Error(SyntaxError(InvalidSyntax, self.line, self.col))
2105 fn error_event(&mut self, reason: ErrorCode) -> JsonEvent {
2106 self.state = ParseFinished;
2107 Error(SyntaxError(reason, self.line, self.col))
2111 /// A Builder consumes a json::Parser to create a generic Json structure.
2112 pub struct Builder<T> {
2114 token: Option<JsonEvent>,
2117 impl<T: Iterator<Item = char>> Builder<T> {
2118 /// Creates a JSON Builder.
2119 pub fn new(src: T) -> Builder<T> {
2120 Builder { parser: Parser::new(src), token: None }
2123 // Decode a Json value from a Parser.
2124 pub fn build(&mut self) -> Result<Json, BuilderError> {
2126 let result = self.build_value();
2130 Some(Error(ref e)) => {
2131 return Err(e.clone());
2134 panic!("unexpected token {:?}", tok.clone());
2140 fn bump(&mut self) {
2141 self.token = self.parser.next();
2144 fn build_value(&mut self) -> Result<Json, BuilderError> {
2146 Some(NullValue) => Ok(Json::Null),
2147 Some(I64Value(n)) => Ok(Json::I64(n)),
2148 Some(U64Value(n)) => Ok(Json::U64(n)),
2149 Some(F64Value(n)) => Ok(Json::F64(n)),
2150 Some(BooleanValue(b)) => Ok(Json::Boolean(b)),
2151 Some(StringValue(ref mut s)) => {
2152 let mut temp = string::String::new();
2154 Ok(Json::String(temp))
2156 Some(Error(ref e)) => Err(e.clone()),
2157 Some(ArrayStart) => self.build_array(),
2158 Some(ObjectStart) => self.build_object(),
2159 Some(ObjectEnd) => self.parser.error(InvalidSyntax),
2160 Some(ArrayEnd) => self.parser.error(InvalidSyntax),
2161 None => self.parser.error(EOFWhileParsingValue),
2165 fn build_array(&mut self) -> Result<Json, BuilderError> {
2167 let mut values = Vec::new();
2170 if self.token == Some(ArrayEnd) {
2171 return Ok(Json::Array(values.into_iter().collect()));
2173 match self.build_value() {
2174 Ok(v) => values.push(v),
2175 Err(e) => return Err(e),
2181 fn build_object(&mut self) -> Result<Json, BuilderError> {
2184 let mut values = BTreeMap::new();
2188 Some(ObjectEnd) => {
2189 return Ok(Json::Object(values));
2191 Some(Error(ref e)) => {
2192 return Err(e.clone());
2199 let key = match self.parser.stack().top() {
2200 Some(StackElement::Key(k)) => k.to_owned(),
2202 panic!("invalid state");
2205 match self.build_value() {
2207 values.insert(key, value);
2215 self.parser.error(EOFWhileParsingObject)
2219 /// Decodes a json value from an `&mut io::Read`
2220 pub fn from_reader(rdr: &mut dyn Read) -> Result<Json, BuilderError> {
2221 let mut contents = Vec::new();
2222 match rdr.read_to_end(&mut contents) {
2224 Err(e) => return Err(io_error_to_error(e)),
2226 let s = match str::from_utf8(&contents).ok() {
2228 _ => return Err(SyntaxError(NotUtf8, 0, 0)),
2230 let mut builder = Builder::new(s.chars());
2234 /// Decodes a json value from a string
2235 pub fn from_str(s: &str) -> Result<Json, BuilderError> {
2236 let mut builder = Builder::new(s.chars());
2240 /// A structure to decode JSON to values in rust.
2241 pub struct Decoder {
2246 /// Creates a new decoder instance for decoding the specified JSON value.
2247 pub fn new(json: Json) -> Decoder {
2248 Decoder { stack: vec![json] }
2251 fn pop(&mut self) -> Json {
2252 self.stack.pop().unwrap()
2256 macro_rules! expect {
2257 ($e:expr, Null) => {{
2259 Json::Null => Ok(()),
2260 other => Err(ExpectedError("Null".to_owned(), other.to_string())),
2263 ($e:expr, $t:ident) => {{
2265 Json::$t(v) => Ok(v),
2266 other => Err(ExpectedError(stringify!($t).to_owned(), other.to_string())),
2271 macro_rules! read_primitive {
2272 ($name:ident, $ty:ty) => {
2273 fn $name(&mut self) -> DecodeResult<$ty> {
2275 Json::I64(f) => Ok(f as $ty),
2276 Json::U64(f) => Ok(f as $ty),
2277 Json::F64(f) => Err(ExpectedError("Integer".to_owned(), f.to_string())),
2278 // re: #12967.. a type w/ numeric keys (ie HashMap<usize, V> etc)
2279 // is going to have a string here, as per JSON spec.
2280 Json::String(s) => match s.parse().ok() {
2282 None => Err(ExpectedError("Number".to_owned(), s)),
2284 value => Err(ExpectedError("Number".to_owned(), value.to_string())),
2290 impl crate::Decoder for Decoder {
2291 type Error = DecoderError;
2293 fn read_nil(&mut self) -> DecodeResult<()> {
2294 expect!(self.pop(), Null)
2297 read_primitive! { read_usize, usize }
2298 read_primitive! { read_u8, u8 }
2299 read_primitive! { read_u16, u16 }
2300 read_primitive! { read_u32, u32 }
2301 read_primitive! { read_u64, u64 }
2302 read_primitive! { read_u128, u128 }
2303 read_primitive! { read_isize, isize }
2304 read_primitive! { read_i8, i8 }
2305 read_primitive! { read_i16, i16 }
2306 read_primitive! { read_i32, i32 }
2307 read_primitive! { read_i64, i64 }
2308 read_primitive! { read_i128, i128 }
2310 fn read_f32(&mut self) -> DecodeResult<f32> {
2311 self.read_f64().map(|x| x as f32)
2314 fn read_f64(&mut self) -> DecodeResult<f64> {
2316 Json::I64(f) => Ok(f as f64),
2317 Json::U64(f) => Ok(f as f64),
2318 Json::F64(f) => Ok(f),
2319 Json::String(s) => {
2320 // re: #12967.. a type w/ numeric keys (ie HashMap<usize, V> etc)
2321 // is going to have a string here, as per JSON spec.
2322 match s.parse().ok() {
2324 None => Err(ExpectedError("Number".to_owned(), s)),
2327 Json::Null => Ok(f64::NAN),
2328 value => Err(ExpectedError("Number".to_owned(), value.to_string())),
2332 fn read_bool(&mut self) -> DecodeResult<bool> {
2333 expect!(self.pop(), Boolean)
2336 fn read_char(&mut self) -> DecodeResult<char> {
2337 let s = self.read_str()?;
2339 let mut it = s.chars();
2340 if let (Some(c), None) = (it.next(), it.next()) {
2341 // exactly one character
2345 Err(ExpectedError("single character string".to_owned(), s.to_string()))
2348 fn read_str(&mut self) -> DecodeResult<Cow<'_, str>> {
2349 expect!(self.pop(), String).map(Cow::Owned)
2352 fn read_enum<T, F>(&mut self, _name: &str, f: F) -> DecodeResult<T>
2354 F: FnOnce(&mut Decoder) -> DecodeResult<T>,
2359 fn read_enum_variant<T, F>(&mut self, names: &[&str], mut f: F) -> DecodeResult<T>
2361 F: FnMut(&mut Decoder, usize) -> DecodeResult<T>,
2363 let name = match self.pop() {
2364 Json::String(s) => s,
2365 Json::Object(mut o) => {
2366 let n = match o.remove(&"variant".to_owned()) {
2367 Some(Json::String(s)) => s,
2368 Some(val) => return Err(ExpectedError("String".to_owned(), val.to_string())),
2369 None => return Err(MissingFieldError("variant".to_owned())),
2371 match o.remove(&"fields".to_string()) {
2372 Some(Json::Array(l)) => {
2373 self.stack.extend(l.into_iter().rev());
2375 Some(val) => return Err(ExpectedError("Array".to_owned(), val.to_string())),
2376 None => return Err(MissingFieldError("fields".to_owned())),
2380 json => return Err(ExpectedError("String or Object".to_owned(), json.to_string())),
2382 let idx = match names.iter().position(|n| *n == &name[..]) {
2384 None => return Err(UnknownVariantError(name)),
2389 fn read_enum_variant_arg<T, F>(&mut self, _idx: usize, f: F) -> DecodeResult<T>
2391 F: FnOnce(&mut Decoder) -> DecodeResult<T>,
2396 fn read_enum_struct_variant<T, F>(&mut self, names: &[&str], f: F) -> DecodeResult<T>
2398 F: FnMut(&mut Decoder, usize) -> DecodeResult<T>,
2400 self.read_enum_variant(names, f)
2403 fn read_enum_struct_variant_field<T, F>(
2408 ) -> DecodeResult<T>
2410 F: FnOnce(&mut Decoder) -> DecodeResult<T>,
2412 self.read_enum_variant_arg(idx, f)
2415 fn read_struct<T, F>(&mut self, _name: &str, _len: usize, f: F) -> DecodeResult<T>
2417 F: FnOnce(&mut Decoder) -> DecodeResult<T>,
2419 let value = f(self)?;
2424 fn read_struct_field<T, F>(&mut self, name: &str, _idx: usize, f: F) -> DecodeResult<T>
2426 F: FnOnce(&mut Decoder) -> DecodeResult<T>,
2428 let mut obj = expect!(self.pop(), Object)?;
2430 let value = match obj.remove(&name.to_string()) {
2432 // Add a Null and try to parse it as an Option<_>
2433 // to get None as a default value.
2434 self.stack.push(Json::Null);
2437 Err(_) => return Err(MissingFieldError(name.to_string())),
2441 self.stack.push(json);
2445 self.stack.push(Json::Object(obj));
2449 fn read_tuple<T, F>(&mut self, tuple_len: usize, f: F) -> DecodeResult<T>
2451 F: FnOnce(&mut Decoder) -> DecodeResult<T>,
2453 self.read_seq(move |d, len| {
2454 if len == tuple_len {
2457 Err(ExpectedError(format!("Tuple{}", tuple_len), format!("Tuple{}", len)))
2462 fn read_tuple_arg<T, F>(&mut self, idx: usize, f: F) -> DecodeResult<T>
2464 F: FnOnce(&mut Decoder) -> DecodeResult<T>,
2466 self.read_seq_elt(idx, f)
2469 fn read_tuple_struct<T, F>(&mut self, _name: &str, len: usize, f: F) -> DecodeResult<T>
2471 F: FnOnce(&mut Decoder) -> DecodeResult<T>,
2473 self.read_tuple(len, f)
2476 fn read_tuple_struct_arg<T, F>(&mut self, idx: usize, f: F) -> DecodeResult<T>
2478 F: FnOnce(&mut Decoder) -> DecodeResult<T>,
2480 self.read_tuple_arg(idx, f)
2483 fn read_option<T, F>(&mut self, mut f: F) -> DecodeResult<T>
2485 F: FnMut(&mut Decoder, bool) -> DecodeResult<T>,
2488 Json::Null => f(self, false),
2490 self.stack.push(value);
2496 fn read_seq<T, F>(&mut self, f: F) -> DecodeResult<T>
2498 F: FnOnce(&mut Decoder, usize) -> DecodeResult<T>,
2500 let array = expect!(self.pop(), Array)?;
2501 let len = array.len();
2502 self.stack.extend(array.into_iter().rev());
2506 fn read_seq_elt<T, F>(&mut self, _idx: usize, f: F) -> DecodeResult<T>
2508 F: FnOnce(&mut Decoder) -> DecodeResult<T>,
2513 fn read_map<T, F>(&mut self, f: F) -> DecodeResult<T>
2515 F: FnOnce(&mut Decoder, usize) -> DecodeResult<T>,
2517 let obj = expect!(self.pop(), Object)?;
2518 let len = obj.len();
2519 for (key, value) in obj {
2520 self.stack.push(value);
2521 self.stack.push(Json::String(key));
2526 fn read_map_elt_key<T, F>(&mut self, _idx: usize, f: F) -> DecodeResult<T>
2528 F: FnOnce(&mut Decoder) -> DecodeResult<T>,
2533 fn read_map_elt_val<T, F>(&mut self, _idx: usize, f: F) -> DecodeResult<T>
2535 F: FnOnce(&mut Decoder) -> DecodeResult<T>,
2540 fn error(&mut self, err: &str) -> DecoderError {
2541 ApplicationError(err.to_string())
2545 /// A trait for converting values to JSON
2547 /// Converts the value of `self` to an instance of JSON
2548 fn to_json(&self) -> Json;
2551 macro_rules! to_json_impl_i64 {
2553 $(impl ToJson for $t {
2554 fn to_json(&self) -> Json {
2555 Json::I64(*self as i64)
2561 to_json_impl_i64! { isize, i8, i16, i32, i64 }
2563 macro_rules! to_json_impl_u64 {
2565 $(impl ToJson for $t {
2566 fn to_json(&self) -> Json {
2567 Json::U64(*self as u64)
2573 to_json_impl_u64! { usize, u8, u16, u32, u64 }
2575 impl ToJson for Json {
2576 fn to_json(&self) -> Json {
2581 impl ToJson for f32 {
2582 fn to_json(&self) -> Json {
2583 f64::from(*self).to_json()
2587 impl ToJson for f64 {
2588 fn to_json(&self) -> Json {
2589 match self.classify() {
2590 Fp::Nan | Fp::Infinite => Json::Null,
2591 _ => Json::F64(*self),
2596 impl ToJson for () {
2597 fn to_json(&self) -> Json {
2602 impl ToJson for bool {
2603 fn to_json(&self) -> Json {
2604 Json::Boolean(*self)
2608 impl ToJson for str {
2609 fn to_json(&self) -> Json {
2610 Json::String(self.to_string())
2614 impl ToJson for string::String {
2615 fn to_json(&self) -> Json {
2616 Json::String((*self).clone())
2620 macro_rules! tuple_impl {
2621 // use variables to indicate the arity of the tuple
2622 ($($tyvar:ident),* ) => {
2623 // the trailing commas are for the 1 tuple
2625 $( $tyvar : ToJson ),*
2626 > ToJson for ( $( $tyvar ),* , ) {
2629 #[allow(non_snake_case)]
2630 fn to_json(&self) -> Json {
2632 ($(ref $tyvar),*,) => Json::Array(vec![$($tyvar.to_json()),*])
2641 tuple_impl! {A, B, C}
2642 tuple_impl! {A, B, C, D}
2643 tuple_impl! {A, B, C, D, E}
2644 tuple_impl! {A, B, C, D, E, F}
2645 tuple_impl! {A, B, C, D, E, F, G}
2646 tuple_impl! {A, B, C, D, E, F, G, H}
2647 tuple_impl! {A, B, C, D, E, F, G, H, I}
2648 tuple_impl! {A, B, C, D, E, F, G, H, I, J}
2649 tuple_impl! {A, B, C, D, E, F, G, H, I, J, K}
2650 tuple_impl! {A, B, C, D, E, F, G, H, I, J, K, L}
2652 impl<A: ToJson> ToJson for [A] {
2653 fn to_json(&self) -> Json {
2654 Json::Array(self.iter().map(|elt| elt.to_json()).collect())
2658 impl<A: ToJson> ToJson for Vec<A> {
2659 fn to_json(&self) -> Json {
2660 Json::Array(self.iter().map(|elt| elt.to_json()).collect())
2664 impl<T: ToString, A: ToJson> ToJson for BTreeMap<T, A> {
2665 fn to_json(&self) -> Json {
2666 let mut d = BTreeMap::new();
2667 for (key, value) in self {
2668 d.insert(key.to_string(), value.to_json());
2674 impl<A: ToJson> ToJson for HashMap<string::String, A> {
2675 fn to_json(&self) -> Json {
2676 let mut d = BTreeMap::new();
2677 for (key, value) in self {
2678 d.insert((*key).clone(), value.to_json());
2684 impl<A: ToJson> ToJson for Option<A> {
2685 fn to_json(&self) -> Json {
2688 Some(ref value) => value.to_json(),
2693 struct FormatShim<'a, 'b> {
2694 inner: &'a mut fmt::Formatter<'b>,
2697 impl<'a, 'b> fmt::Write for FormatShim<'a, 'b> {
2698 fn write_str(&mut self, s: &str) -> fmt::Result {
2699 match self.inner.write_str(s) {
2701 Err(_) => Err(fmt::Error),
2706 impl fmt::Display for Json {
2707 /// Encodes a json value into a string
2708 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2709 let mut shim = FormatShim { inner: f };
2710 let mut encoder = Encoder::new(&mut shim);
2711 match self.encode(&mut encoder) {
2713 Err(_) => Err(fmt::Error),
2718 impl<'a> fmt::Display for PrettyJson<'a> {
2719 /// Encodes a json value into a string
2720 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2721 let mut shim = FormatShim { inner: f };
2722 let mut encoder = PrettyEncoder::new(&mut shim);
2723 match self.inner.encode(&mut encoder) {
2725 Err(_) => Err(fmt::Error),
2730 impl<'a, T: Encodable> fmt::Display for AsJson<'a, T> {
2731 /// Encodes a json value into a string
2732 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2733 let mut shim = FormatShim { inner: f };
2734 let mut encoder = Encoder::new(&mut shim);
2735 match self.inner.encode(&mut encoder) {
2737 Err(_) => Err(fmt::Error),
2742 impl<'a, T> AsPrettyJson<'a, T> {
2743 /// Sets the indentation level for the emitted JSON
2744 pub fn indent(mut self, indent: usize) -> AsPrettyJson<'a, T> {
2745 self.indent = Some(indent);
2750 impl<'a, T: Encodable> fmt::Display for AsPrettyJson<'a, T> {
2751 /// Encodes a json value into a string
2752 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2753 let mut shim = FormatShim { inner: f };
2754 let mut encoder = PrettyEncoder::new(&mut shim);
2755 if let Some(n) = self.indent {
2756 encoder.set_indent(n);
2758 match self.inner.encode(&mut encoder) {
2760 Err(_) => Err(fmt::Error),
2765 impl FromStr for Json {
2766 type Err = BuilderError;
2767 fn from_str(s: &str) -> Result<Json, BuilderError> {