]> git.proxmox.com Git - rustc.git/blob - compiler/rustc_serialize/src/json.rs
New upstream version 1.53.0+dfsg1
[rustc.git] / compiler / rustc_serialize / src / json.rs
1 // Rust JSON serialization library.
2 // Copyright (c) 2011 Google Inc.
3
4 #![forbid(non_camel_case_types)]
5 #![allow(missing_docs)]
6
7 //! JSON parsing and serialization
8 //!
9 //! # What is JSON?
10 //!
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.
14 //!
15 //! Data types that can be encoded are JavaScript types (see the `Json` enum for more details):
16 //!
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
21 //! same array
22 //! * `Object`: equivalent to rust's `BTreeMap<String, json::Json>`
23 //! * `Null`
24 //!
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
28 //!
29 //! ```json
30 //! {
31 //! "FirstName": "John",
32 //! "LastName": "Doe",
33 //! "Age": 43,
34 //! "Address": {
35 //! "Street": "Downing Street 10",
36 //! "City": "London",
37 //! "Country": "Great Britain"
38 //! },
39 //! "PhoneNumbers": [
40 //! "+44 1234567",
41 //! "+44 2345678"
42 //! ]
43 //! }
44 //! ```
45 //!
46 //! # Rust Type-based Encoding and Decoding
47 //!
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::Encodable` trait.
51 //! To be able to decode a piece of data, it must implement the `serialize::Decodable` trait.
52 //! The Rust compiler provides an annotation to automatically generate the code for these traits:
53 //! `#[derive(Decodable, Encodable)]`
54 //!
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.
59 //!
60 //! When using `ToJson` the `Encodable` trait implementation is not mandatory.
61 //!
62 //! # Examples of use
63 //!
64 //! ## Using Autoserialization
65 //!
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.
68 //!
69 //! ```rust
70 //! # #![feature(rustc_private)]
71 //! use rustc_macros::{Decodable, Encodable};
72 //! use rustc_serialize::json;
73 //!
74 //! // Automatically generate `Decodable` and `Encodable` trait implementations
75 //! #[derive(Decodable, Encodable)]
76 //! pub struct TestStruct {
77 //! data_int: u8,
78 //! data_str: String,
79 //! data_vector: Vec<u8>,
80 //! }
81 //!
82 //! let object = TestStruct {
83 //! data_int: 1,
84 //! data_str: "homura".to_string(),
85 //! data_vector: vec![2,3,4,5],
86 //! };
87 //!
88 //! // Serialize using `json::encode`
89 //! let encoded = json::encode(&object).unwrap();
90 //!
91 //! // Deserialize using `json::decode`
92 //! let decoded: TestStruct = json::decode(&encoded[..]).unwrap();
93 //! ```
94 //!
95 //! ## Using the `ToJson` trait
96 //!
97 //! The examples above use the `ToJson` trait to generate the JSON string, which is required
98 //! for custom mappings.
99 //!
100 //! ### Simple example of `ToJson` usage
101 //!
102 //! ```rust
103 //! # #![feature(rustc_private)]
104 //! use rustc_macros::Encodable;
105 //! use rustc_serialize::json::{self, ToJson, Json};
106 //!
107 //! // A custom data structure
108 //! struct ComplexNum {
109 //! a: f64,
110 //! b: f64,
111 //! }
112 //!
113 //! // JSON value representation
114 //! impl ToJson for ComplexNum {
115 //! fn to_json(&self) -> Json {
116 //! Json::String(format!("{}+{}i", self.a, self.b))
117 //! }
118 //! }
119 //!
120 //! // Only generate `Encodable` trait implementation
121 //! #[derive(Encodable)]
122 //! pub struct ComplexNumRecord {
123 //! uid: u8,
124 //! dsc: String,
125 //! val: Json,
126 //! }
127 //!
128 //! let num = ComplexNum { a: 0.0001, b: 12.539 };
129 //! let data: String = json::encode(&ComplexNumRecord{
130 //! uid: 1,
131 //! dsc: "test".to_string(),
132 //! val: num.to_json(),
133 //! }).unwrap();
134 //! println!("data: {}", data);
135 //! // data: {"uid":1,"dsc":"test","val":"0.0001+12.539i"};
136 //! ```
137 //!
138 //! ### Verbose example of `ToJson` usage
139 //!
140 //! ```rust
141 //! # #![feature(rustc_private)]
142 //! use rustc_macros::Decodable;
143 //! use std::collections::BTreeMap;
144 //! use rustc_serialize::json::{self, Json, ToJson};
145 //!
146 //! // Only generate `Decodable` trait implementation
147 //! #[derive(Decodable)]
148 //! pub struct TestStruct {
149 //! data_int: u8,
150 //! data_str: String,
151 //! data_vector: Vec<u8>,
152 //! }
153 //!
154 //! // Specify encoding method manually
155 //! impl ToJson for TestStruct {
156 //! fn to_json(&self) -> Json {
157 //! let mut d = BTreeMap::new();
158 //! // All standard types implement `to_json()`, so use it
159 //! d.insert("data_int".to_string(), self.data_int.to_json());
160 //! d.insert("data_str".to_string(), self.data_str.to_json());
161 //! d.insert("data_vector".to_string(), self.data_vector.to_json());
162 //! Json::Object(d)
163 //! }
164 //! }
165 //!
166 //! // Serialize using `ToJson`
167 //! let input_data = TestStruct {
168 //! data_int: 1,
169 //! data_str: "madoka".to_string(),
170 //! data_vector: vec![2,3,4,5],
171 //! };
172 //! let json_obj: Json = input_data.to_json();
173 //! let json_str: String = json_obj.to_string();
174 //!
175 //! // Deserialize like before
176 //! let decoded: TestStruct = json::decode(&json_str).unwrap();
177 //! ```
178
179 use self::DecoderError::*;
180 use self::ErrorCode::*;
181 use self::InternalStackElement::*;
182 use self::JsonEvent::*;
183 use self::ParserError::*;
184 use self::ParserState::*;
185
186 use std::borrow::Cow;
187 use std::collections::{BTreeMap, HashMap};
188 use std::io;
189 use std::io::prelude::*;
190 use std::mem::swap;
191 use std::num::FpCategory as Fp;
192 use std::ops::Index;
193 use std::str::FromStr;
194 use std::string;
195 use std::{char, fmt, str};
196
197 use crate::Encodable;
198
199 /// Represents a json value
200 #[derive(Clone, PartialEq, PartialOrd, Debug)]
201 pub enum Json {
202 I64(i64),
203 U64(u64),
204 F64(f64),
205 String(string::String),
206 Boolean(bool),
207 Array(self::Array),
208 Object(self::Object),
209 Null,
210 }
211
212 pub type Array = Vec<Json>;
213 pub type Object = BTreeMap<string::String, Json>;
214
215 pub struct PrettyJson<'a> {
216 inner: &'a Json,
217 }
218
219 pub struct AsJson<'a, T> {
220 inner: &'a T,
221 }
222 pub struct AsPrettyJson<'a, T> {
223 inner: &'a T,
224 indent: Option<usize>,
225 }
226
227 /// The errors that can arise while parsing a JSON stream.
228 #[derive(Clone, Copy, PartialEq, Debug)]
229 pub enum ErrorCode {
230 InvalidSyntax,
231 InvalidNumber,
232 EOFWhileParsingObject,
233 EOFWhileParsingArray,
234 EOFWhileParsingValue,
235 EOFWhileParsingString,
236 KeyMustBeAString,
237 ExpectedColon,
238 TrailingCharacters,
239 TrailingComma,
240 InvalidEscape,
241 InvalidUnicodeCodePoint,
242 LoneLeadingSurrogateInHexEscape,
243 UnexpectedEndOfHexEscape,
244 UnrecognizedHex,
245 NotFourDigit,
246 NotUtf8,
247 }
248
249 #[derive(Clone, PartialEq, Debug)]
250 pub enum ParserError {
251 /// msg, line, col
252 SyntaxError(ErrorCode, usize, usize),
253 IoError(io::ErrorKind, String),
254 }
255
256 // Builder and Parser have the same errors.
257 pub type BuilderError = ParserError;
258
259 #[derive(Clone, PartialEq, Debug)]
260 pub enum DecoderError {
261 ParseError(ParserError),
262 ExpectedError(string::String, string::String),
263 MissingFieldError(string::String),
264 UnknownVariantError(string::String),
265 ApplicationError(string::String),
266 }
267
268 #[derive(Copy, Clone, Debug)]
269 pub enum EncoderError {
270 FmtError(fmt::Error),
271 BadHashmapKey,
272 }
273
274 /// Returns a readable error string for a given error code.
275 pub fn error_str(error: ErrorCode) -> &'static str {
276 match error {
277 InvalidSyntax => "invalid syntax",
278 InvalidNumber => "invalid number",
279 EOFWhileParsingObject => "EOF While parsing object",
280 EOFWhileParsingArray => "EOF While parsing array",
281 EOFWhileParsingValue => "EOF While parsing value",
282 EOFWhileParsingString => "EOF While parsing string",
283 KeyMustBeAString => "key must be a string",
284 ExpectedColon => "expected `:`",
285 TrailingCharacters => "trailing characters",
286 TrailingComma => "trailing comma",
287 InvalidEscape => "invalid escape",
288 UnrecognizedHex => "invalid \\u{ esc}ape (unrecognized hex)",
289 NotFourDigit => "invalid \\u{ esc}ape (not four digits)",
290 NotUtf8 => "contents not utf-8",
291 InvalidUnicodeCodePoint => "invalid Unicode code point",
292 LoneLeadingSurrogateInHexEscape => "lone leading surrogate in hex escape",
293 UnexpectedEndOfHexEscape => "unexpected end of hex escape",
294 }
295 }
296
297 /// Shortcut function to decode a JSON `&str` into an object
298 pub fn decode<T: crate::Decodable<Decoder>>(s: &str) -> DecodeResult<T> {
299 let json = match from_str(s) {
300 Ok(x) => x,
301 Err(e) => return Err(ParseError(e)),
302 };
303
304 let mut decoder = Decoder::new(json);
305 crate::Decodable::decode(&mut decoder)
306 }
307
308 /// Shortcut function to encode a `T` into a JSON `String`
309 pub fn encode<T: for<'r> crate::Encodable<Encoder<'r>>>(
310 object: &T,
311 ) -> Result<string::String, EncoderError> {
312 let mut s = String::new();
313 {
314 let mut encoder = Encoder::new(&mut s);
315 object.encode(&mut encoder)?;
316 }
317 Ok(s)
318 }
319
320 impl fmt::Display for ErrorCode {
321 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
322 error_str(*self).fmt(f)
323 }
324 }
325
326 fn io_error_to_error(io: io::Error) -> ParserError {
327 IoError(io.kind(), io.to_string())
328 }
329
330 impl fmt::Display for ParserError {
331 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
332 // FIXME this should be a nicer error
333 fmt::Debug::fmt(self, f)
334 }
335 }
336
337 impl fmt::Display for DecoderError {
338 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
339 // FIXME this should be a nicer error
340 fmt::Debug::fmt(self, f)
341 }
342 }
343
344 impl std::error::Error for DecoderError {}
345
346 impl fmt::Display for EncoderError {
347 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
348 // FIXME this should be a nicer error
349 fmt::Debug::fmt(self, f)
350 }
351 }
352
353 impl std::error::Error for EncoderError {}
354
355 impl From<fmt::Error> for EncoderError {
356 /// Converts a [`fmt::Error`] into `EncoderError`
357 ///
358 /// This conversion does not allocate memory.
359 fn from(err: fmt::Error) -> EncoderError {
360 EncoderError::FmtError(err)
361 }
362 }
363
364 pub type EncodeResult = Result<(), EncoderError>;
365 pub type DecodeResult<T> = Result<T, DecoderError>;
366
367 fn escape_str(wr: &mut dyn fmt::Write, v: &str) -> EncodeResult {
368 wr.write_str("\"")?;
369
370 let mut start = 0;
371
372 for (i, byte) in v.bytes().enumerate() {
373 let escaped = match byte {
374 b'"' => "\\\"",
375 b'\\' => "\\\\",
376 b'\x00' => "\\u0000",
377 b'\x01' => "\\u0001",
378 b'\x02' => "\\u0002",
379 b'\x03' => "\\u0003",
380 b'\x04' => "\\u0004",
381 b'\x05' => "\\u0005",
382 b'\x06' => "\\u0006",
383 b'\x07' => "\\u0007",
384 b'\x08' => "\\b",
385 b'\t' => "\\t",
386 b'\n' => "\\n",
387 b'\x0b' => "\\u000b",
388 b'\x0c' => "\\f",
389 b'\r' => "\\r",
390 b'\x0e' => "\\u000e",
391 b'\x0f' => "\\u000f",
392 b'\x10' => "\\u0010",
393 b'\x11' => "\\u0011",
394 b'\x12' => "\\u0012",
395 b'\x13' => "\\u0013",
396 b'\x14' => "\\u0014",
397 b'\x15' => "\\u0015",
398 b'\x16' => "\\u0016",
399 b'\x17' => "\\u0017",
400 b'\x18' => "\\u0018",
401 b'\x19' => "\\u0019",
402 b'\x1a' => "\\u001a",
403 b'\x1b' => "\\u001b",
404 b'\x1c' => "\\u001c",
405 b'\x1d' => "\\u001d",
406 b'\x1e' => "\\u001e",
407 b'\x1f' => "\\u001f",
408 b'\x7f' => "\\u007f",
409 _ => {
410 continue;
411 }
412 };
413
414 if start < i {
415 wr.write_str(&v[start..i])?;
416 }
417
418 wr.write_str(escaped)?;
419
420 start = i + 1;
421 }
422
423 if start != v.len() {
424 wr.write_str(&v[start..])?;
425 }
426
427 wr.write_str("\"")?;
428 Ok(())
429 }
430
431 fn escape_char(writer: &mut dyn fmt::Write, v: char) -> EncodeResult {
432 escape_str(writer, v.encode_utf8(&mut [0; 4]))
433 }
434
435 fn spaces(wr: &mut dyn fmt::Write, mut n: usize) -> EncodeResult {
436 const BUF: &str = " ";
437
438 while n >= BUF.len() {
439 wr.write_str(BUF)?;
440 n -= BUF.len();
441 }
442
443 if n > 0 {
444 wr.write_str(&BUF[..n])?;
445 }
446 Ok(())
447 }
448
449 fn fmt_number_or_null(v: f64) -> string::String {
450 match v.classify() {
451 Fp::Nan | Fp::Infinite => string::String::from("null"),
452 _ if v.fract() != 0f64 => v.to_string(),
453 _ => v.to_string() + ".0",
454 }
455 }
456
457 /// A structure for implementing serialization to JSON.
458 pub struct Encoder<'a> {
459 writer: &'a mut (dyn fmt::Write + 'a),
460 is_emitting_map_key: bool,
461 }
462
463 impl<'a> Encoder<'a> {
464 /// Creates a new JSON encoder whose output will be written to the writer
465 /// specified.
466 pub fn new(writer: &'a mut dyn fmt::Write) -> Encoder<'a> {
467 Encoder { writer, is_emitting_map_key: false }
468 }
469 }
470
471 macro_rules! emit_enquoted_if_mapkey {
472 ($enc:ident,$e:expr) => {{
473 if $enc.is_emitting_map_key {
474 write!($enc.writer, "\"{}\"", $e)?;
475 } else {
476 write!($enc.writer, "{}", $e)?;
477 }
478 Ok(())
479 }};
480 }
481
482 impl<'a> crate::Encoder for Encoder<'a> {
483 type Error = EncoderError;
484
485 fn emit_unit(&mut self) -> EncodeResult {
486 if self.is_emitting_map_key {
487 return Err(EncoderError::BadHashmapKey);
488 }
489 write!(self.writer, "null")?;
490 Ok(())
491 }
492
493 fn emit_usize(&mut self, v: usize) -> EncodeResult {
494 emit_enquoted_if_mapkey!(self, v)
495 }
496 fn emit_u128(&mut self, v: u128) -> EncodeResult {
497 emit_enquoted_if_mapkey!(self, v)
498 }
499 fn emit_u64(&mut self, v: u64) -> EncodeResult {
500 emit_enquoted_if_mapkey!(self, v)
501 }
502 fn emit_u32(&mut self, v: u32) -> EncodeResult {
503 emit_enquoted_if_mapkey!(self, v)
504 }
505 fn emit_u16(&mut self, v: u16) -> EncodeResult {
506 emit_enquoted_if_mapkey!(self, v)
507 }
508 fn emit_u8(&mut self, v: u8) -> EncodeResult {
509 emit_enquoted_if_mapkey!(self, v)
510 }
511
512 fn emit_isize(&mut self, v: isize) -> EncodeResult {
513 emit_enquoted_if_mapkey!(self, v)
514 }
515 fn emit_i128(&mut self, v: i128) -> EncodeResult {
516 emit_enquoted_if_mapkey!(self, v)
517 }
518 fn emit_i64(&mut self, v: i64) -> EncodeResult {
519 emit_enquoted_if_mapkey!(self, v)
520 }
521 fn emit_i32(&mut self, v: i32) -> EncodeResult {
522 emit_enquoted_if_mapkey!(self, v)
523 }
524 fn emit_i16(&mut self, v: i16) -> EncodeResult {
525 emit_enquoted_if_mapkey!(self, v)
526 }
527 fn emit_i8(&mut self, v: i8) -> EncodeResult {
528 emit_enquoted_if_mapkey!(self, v)
529 }
530
531 fn emit_bool(&mut self, v: bool) -> EncodeResult {
532 if self.is_emitting_map_key {
533 return Err(EncoderError::BadHashmapKey);
534 }
535 if v {
536 write!(self.writer, "true")?;
537 } else {
538 write!(self.writer, "false")?;
539 }
540 Ok(())
541 }
542
543 fn emit_f64(&mut self, v: f64) -> EncodeResult {
544 emit_enquoted_if_mapkey!(self, fmt_number_or_null(v))
545 }
546 fn emit_f32(&mut self, v: f32) -> EncodeResult {
547 self.emit_f64(f64::from(v))
548 }
549
550 fn emit_char(&mut self, v: char) -> EncodeResult {
551 escape_char(self.writer, v)
552 }
553 fn emit_str(&mut self, v: &str) -> EncodeResult {
554 escape_str(self.writer, v)
555 }
556 fn emit_raw_bytes(&mut self, s: &[u8]) -> Result<(), Self::Error> {
557 for &c in s.iter() {
558 self.emit_u8(c)?;
559 }
560 Ok(())
561 }
562
563 fn emit_enum<F>(&mut self, _name: &str, f: F) -> EncodeResult
564 where
565 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
566 {
567 f(self)
568 }
569
570 fn emit_enum_variant<F>(&mut self, name: &str, _id: usize, cnt: usize, f: F) -> EncodeResult
571 where
572 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
573 {
574 // enums are encoded as strings or objects
575 // Bunny => "Bunny"
576 // Kangaroo(34,"William") => {"variant": "Kangaroo", "fields": [34,"William"]}
577 if cnt == 0 {
578 escape_str(self.writer, name)
579 } else {
580 if self.is_emitting_map_key {
581 return Err(EncoderError::BadHashmapKey);
582 }
583 write!(self.writer, "{{\"variant\":")?;
584 escape_str(self.writer, name)?;
585 write!(self.writer, ",\"fields\":[")?;
586 f(self)?;
587 write!(self.writer, "]}}")?;
588 Ok(())
589 }
590 }
591
592 fn emit_enum_variant_arg<F>(&mut self, idx: usize, f: F) -> EncodeResult
593 where
594 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
595 {
596 if self.is_emitting_map_key {
597 return Err(EncoderError::BadHashmapKey);
598 }
599 if idx != 0 {
600 write!(self.writer, ",")?;
601 }
602 f(self)
603 }
604
605 fn emit_enum_struct_variant<F>(
606 &mut self,
607 name: &str,
608 id: usize,
609 cnt: usize,
610 f: F,
611 ) -> EncodeResult
612 where
613 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
614 {
615 if self.is_emitting_map_key {
616 return Err(EncoderError::BadHashmapKey);
617 }
618 self.emit_enum_variant(name, id, cnt, f)
619 }
620
621 fn emit_enum_struct_variant_field<F>(&mut self, _: &str, idx: usize, f: F) -> EncodeResult
622 where
623 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
624 {
625 if self.is_emitting_map_key {
626 return Err(EncoderError::BadHashmapKey);
627 }
628 self.emit_enum_variant_arg(idx, f)
629 }
630
631 fn emit_struct<F>(&mut self, _: &str, _: usize, f: F) -> EncodeResult
632 where
633 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
634 {
635 if self.is_emitting_map_key {
636 return Err(EncoderError::BadHashmapKey);
637 }
638 write!(self.writer, "{{")?;
639 f(self)?;
640 write!(self.writer, "}}")?;
641 Ok(())
642 }
643
644 fn emit_struct_field<F>(&mut self, name: &str, idx: usize, f: F) -> EncodeResult
645 where
646 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
647 {
648 if self.is_emitting_map_key {
649 return Err(EncoderError::BadHashmapKey);
650 }
651 if idx != 0 {
652 write!(self.writer, ",")?;
653 }
654 escape_str(self.writer, name)?;
655 write!(self.writer, ":")?;
656 f(self)
657 }
658
659 fn emit_tuple<F>(&mut self, len: usize, f: F) -> EncodeResult
660 where
661 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
662 {
663 if self.is_emitting_map_key {
664 return Err(EncoderError::BadHashmapKey);
665 }
666 self.emit_seq(len, f)
667 }
668 fn emit_tuple_arg<F>(&mut self, idx: usize, f: F) -> EncodeResult
669 where
670 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
671 {
672 if self.is_emitting_map_key {
673 return Err(EncoderError::BadHashmapKey);
674 }
675 self.emit_seq_elt(idx, f)
676 }
677
678 fn emit_tuple_struct<F>(&mut self, _name: &str, len: usize, f: F) -> EncodeResult
679 where
680 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
681 {
682 if self.is_emitting_map_key {
683 return Err(EncoderError::BadHashmapKey);
684 }
685 self.emit_seq(len, f)
686 }
687 fn emit_tuple_struct_arg<F>(&mut self, idx: usize, f: F) -> EncodeResult
688 where
689 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
690 {
691 if self.is_emitting_map_key {
692 return Err(EncoderError::BadHashmapKey);
693 }
694 self.emit_seq_elt(idx, f)
695 }
696
697 fn emit_option<F>(&mut self, f: F) -> EncodeResult
698 where
699 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
700 {
701 if self.is_emitting_map_key {
702 return Err(EncoderError::BadHashmapKey);
703 }
704 f(self)
705 }
706 fn emit_option_none(&mut self) -> EncodeResult {
707 if self.is_emitting_map_key {
708 return Err(EncoderError::BadHashmapKey);
709 }
710 self.emit_unit()
711 }
712 fn emit_option_some<F>(&mut self, f: F) -> EncodeResult
713 where
714 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
715 {
716 if self.is_emitting_map_key {
717 return Err(EncoderError::BadHashmapKey);
718 }
719 f(self)
720 }
721
722 fn emit_seq<F>(&mut self, _len: usize, f: F) -> EncodeResult
723 where
724 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
725 {
726 if self.is_emitting_map_key {
727 return Err(EncoderError::BadHashmapKey);
728 }
729 write!(self.writer, "[")?;
730 f(self)?;
731 write!(self.writer, "]")?;
732 Ok(())
733 }
734
735 fn emit_seq_elt<F>(&mut self, idx: usize, f: F) -> EncodeResult
736 where
737 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
738 {
739 if self.is_emitting_map_key {
740 return Err(EncoderError::BadHashmapKey);
741 }
742 if idx != 0 {
743 write!(self.writer, ",")?;
744 }
745 f(self)
746 }
747
748 fn emit_map<F>(&mut self, _len: usize, f: F) -> EncodeResult
749 where
750 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
751 {
752 if self.is_emitting_map_key {
753 return Err(EncoderError::BadHashmapKey);
754 }
755 write!(self.writer, "{{")?;
756 f(self)?;
757 write!(self.writer, "}}")?;
758 Ok(())
759 }
760
761 fn emit_map_elt_key<F>(&mut self, idx: usize, f: F) -> EncodeResult
762 where
763 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
764 {
765 if self.is_emitting_map_key {
766 return Err(EncoderError::BadHashmapKey);
767 }
768 if idx != 0 {
769 write!(self.writer, ",")?
770 }
771 self.is_emitting_map_key = true;
772 f(self)?;
773 self.is_emitting_map_key = false;
774 Ok(())
775 }
776
777 fn emit_map_elt_val<F>(&mut self, _idx: usize, f: F) -> EncodeResult
778 where
779 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
780 {
781 if self.is_emitting_map_key {
782 return Err(EncoderError::BadHashmapKey);
783 }
784 write!(self.writer, ":")?;
785 f(self)
786 }
787 }
788
789 /// Another encoder for JSON, but prints out human-readable JSON instead of
790 /// compact data
791 pub struct PrettyEncoder<'a> {
792 writer: &'a mut (dyn fmt::Write + 'a),
793 curr_indent: usize,
794 indent: usize,
795 is_emitting_map_key: bool,
796 }
797
798 impl<'a> PrettyEncoder<'a> {
799 /// Creates a new encoder whose output will be written to the specified writer
800 pub fn new(writer: &'a mut dyn fmt::Write) -> PrettyEncoder<'a> {
801 PrettyEncoder { writer, curr_indent: 0, indent: 2, is_emitting_map_key: false }
802 }
803
804 /// Sets the number of spaces to indent for each level.
805 /// This is safe to set during encoding.
806 pub fn set_indent(&mut self, indent: usize) {
807 // self.indent very well could be 0 so we need to use checked division.
808 let level = self.curr_indent.checked_div(self.indent).unwrap_or(0);
809 self.indent = indent;
810 self.curr_indent = level * self.indent;
811 }
812 }
813
814 impl<'a> crate::Encoder for PrettyEncoder<'a> {
815 type Error = EncoderError;
816
817 fn emit_unit(&mut self) -> EncodeResult {
818 if self.is_emitting_map_key {
819 return Err(EncoderError::BadHashmapKey);
820 }
821 write!(self.writer, "null")?;
822 Ok(())
823 }
824
825 fn emit_usize(&mut self, v: usize) -> EncodeResult {
826 emit_enquoted_if_mapkey!(self, v)
827 }
828 fn emit_u128(&mut self, v: u128) -> EncodeResult {
829 emit_enquoted_if_mapkey!(self, v)
830 }
831 fn emit_u64(&mut self, v: u64) -> EncodeResult {
832 emit_enquoted_if_mapkey!(self, v)
833 }
834 fn emit_u32(&mut self, v: u32) -> EncodeResult {
835 emit_enquoted_if_mapkey!(self, v)
836 }
837 fn emit_u16(&mut self, v: u16) -> EncodeResult {
838 emit_enquoted_if_mapkey!(self, v)
839 }
840 fn emit_u8(&mut self, v: u8) -> EncodeResult {
841 emit_enquoted_if_mapkey!(self, v)
842 }
843
844 fn emit_isize(&mut self, v: isize) -> EncodeResult {
845 emit_enquoted_if_mapkey!(self, v)
846 }
847 fn emit_i128(&mut self, v: i128) -> EncodeResult {
848 emit_enquoted_if_mapkey!(self, v)
849 }
850 fn emit_i64(&mut self, v: i64) -> EncodeResult {
851 emit_enquoted_if_mapkey!(self, v)
852 }
853 fn emit_i32(&mut self, v: i32) -> EncodeResult {
854 emit_enquoted_if_mapkey!(self, v)
855 }
856 fn emit_i16(&mut self, v: i16) -> EncodeResult {
857 emit_enquoted_if_mapkey!(self, v)
858 }
859 fn emit_i8(&mut self, v: i8) -> EncodeResult {
860 emit_enquoted_if_mapkey!(self, v)
861 }
862
863 fn emit_bool(&mut self, v: bool) -> EncodeResult {
864 if self.is_emitting_map_key {
865 return Err(EncoderError::BadHashmapKey);
866 }
867 if v {
868 write!(self.writer, "true")?;
869 } else {
870 write!(self.writer, "false")?;
871 }
872 Ok(())
873 }
874
875 fn emit_f64(&mut self, v: f64) -> EncodeResult {
876 emit_enquoted_if_mapkey!(self, fmt_number_or_null(v))
877 }
878 fn emit_f32(&mut self, v: f32) -> EncodeResult {
879 self.emit_f64(f64::from(v))
880 }
881
882 fn emit_char(&mut self, v: char) -> EncodeResult {
883 escape_char(self.writer, v)
884 }
885 fn emit_str(&mut self, v: &str) -> EncodeResult {
886 escape_str(self.writer, v)
887 }
888 fn emit_raw_bytes(&mut self, s: &[u8]) -> Result<(), Self::Error> {
889 for &c in s.iter() {
890 self.emit_u8(c)?;
891 }
892 Ok(())
893 }
894
895 fn emit_enum<F>(&mut self, _name: &str, f: F) -> EncodeResult
896 where
897 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
898 {
899 f(self)
900 }
901
902 fn emit_enum_variant<F>(&mut self, name: &str, _id: usize, cnt: usize, f: F) -> EncodeResult
903 where
904 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
905 {
906 if cnt == 0 {
907 escape_str(self.writer, name)
908 } else {
909 if self.is_emitting_map_key {
910 return Err(EncoderError::BadHashmapKey);
911 }
912 writeln!(self.writer, "{{")?;
913 self.curr_indent += self.indent;
914 spaces(self.writer, self.curr_indent)?;
915 write!(self.writer, "\"variant\": ")?;
916 escape_str(self.writer, name)?;
917 writeln!(self.writer, ",")?;
918 spaces(self.writer, self.curr_indent)?;
919 writeln!(self.writer, "\"fields\": [")?;
920 self.curr_indent += self.indent;
921 f(self)?;
922 self.curr_indent -= self.indent;
923 writeln!(self.writer)?;
924 spaces(self.writer, self.curr_indent)?;
925 self.curr_indent -= self.indent;
926 writeln!(self.writer, "]")?;
927 spaces(self.writer, self.curr_indent)?;
928 write!(self.writer, "}}")?;
929 Ok(())
930 }
931 }
932
933 fn emit_enum_variant_arg<F>(&mut self, idx: usize, f: F) -> EncodeResult
934 where
935 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
936 {
937 if self.is_emitting_map_key {
938 return Err(EncoderError::BadHashmapKey);
939 }
940 if idx != 0 {
941 writeln!(self.writer, ",")?;
942 }
943 spaces(self.writer, self.curr_indent)?;
944 f(self)
945 }
946
947 fn emit_enum_struct_variant<F>(
948 &mut self,
949 name: &str,
950 id: usize,
951 cnt: usize,
952 f: F,
953 ) -> EncodeResult
954 where
955 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
956 {
957 if self.is_emitting_map_key {
958 return Err(EncoderError::BadHashmapKey);
959 }
960 self.emit_enum_variant(name, id, cnt, f)
961 }
962
963 fn emit_enum_struct_variant_field<F>(&mut self, _: &str, idx: usize, f: F) -> EncodeResult
964 where
965 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
966 {
967 if self.is_emitting_map_key {
968 return Err(EncoderError::BadHashmapKey);
969 }
970 self.emit_enum_variant_arg(idx, f)
971 }
972
973 fn emit_struct<F>(&mut self, _: &str, len: usize, f: F) -> EncodeResult
974 where
975 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
976 {
977 if self.is_emitting_map_key {
978 return Err(EncoderError::BadHashmapKey);
979 }
980 if len == 0 {
981 write!(self.writer, "{{}}")?;
982 } else {
983 write!(self.writer, "{{")?;
984 self.curr_indent += self.indent;
985 f(self)?;
986 self.curr_indent -= self.indent;
987 writeln!(self.writer)?;
988 spaces(self.writer, self.curr_indent)?;
989 write!(self.writer, "}}")?;
990 }
991 Ok(())
992 }
993
994 fn emit_struct_field<F>(&mut self, name: &str, idx: usize, f: F) -> EncodeResult
995 where
996 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
997 {
998 if self.is_emitting_map_key {
999 return Err(EncoderError::BadHashmapKey);
1000 }
1001 if idx == 0 {
1002 writeln!(self.writer)?;
1003 } else {
1004 writeln!(self.writer, ",")?;
1005 }
1006 spaces(self.writer, self.curr_indent)?;
1007 escape_str(self.writer, name)?;
1008 write!(self.writer, ": ")?;
1009 f(self)
1010 }
1011
1012 fn emit_tuple<F>(&mut self, len: usize, f: F) -> EncodeResult
1013 where
1014 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
1015 {
1016 if self.is_emitting_map_key {
1017 return Err(EncoderError::BadHashmapKey);
1018 }
1019 self.emit_seq(len, f)
1020 }
1021 fn emit_tuple_arg<F>(&mut self, idx: usize, f: F) -> EncodeResult
1022 where
1023 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
1024 {
1025 if self.is_emitting_map_key {
1026 return Err(EncoderError::BadHashmapKey);
1027 }
1028 self.emit_seq_elt(idx, f)
1029 }
1030
1031 fn emit_tuple_struct<F>(&mut self, _: &str, len: usize, f: F) -> EncodeResult
1032 where
1033 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
1034 {
1035 if self.is_emitting_map_key {
1036 return Err(EncoderError::BadHashmapKey);
1037 }
1038 self.emit_seq(len, f)
1039 }
1040 fn emit_tuple_struct_arg<F>(&mut self, idx: usize, f: F) -> EncodeResult
1041 where
1042 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
1043 {
1044 if self.is_emitting_map_key {
1045 return Err(EncoderError::BadHashmapKey);
1046 }
1047 self.emit_seq_elt(idx, f)
1048 }
1049
1050 fn emit_option<F>(&mut self, f: F) -> EncodeResult
1051 where
1052 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
1053 {
1054 if self.is_emitting_map_key {
1055 return Err(EncoderError::BadHashmapKey);
1056 }
1057 f(self)
1058 }
1059 fn emit_option_none(&mut self) -> EncodeResult {
1060 if self.is_emitting_map_key {
1061 return Err(EncoderError::BadHashmapKey);
1062 }
1063 self.emit_unit()
1064 }
1065 fn emit_option_some<F>(&mut self, f: F) -> EncodeResult
1066 where
1067 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
1068 {
1069 if self.is_emitting_map_key {
1070 return Err(EncoderError::BadHashmapKey);
1071 }
1072 f(self)
1073 }
1074
1075 fn emit_seq<F>(&mut self, len: usize, f: F) -> EncodeResult
1076 where
1077 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
1078 {
1079 if self.is_emitting_map_key {
1080 return Err(EncoderError::BadHashmapKey);
1081 }
1082 if len == 0 {
1083 write!(self.writer, "[]")?;
1084 } else {
1085 write!(self.writer, "[")?;
1086 self.curr_indent += self.indent;
1087 f(self)?;
1088 self.curr_indent -= self.indent;
1089 writeln!(self.writer)?;
1090 spaces(self.writer, self.curr_indent)?;
1091 write!(self.writer, "]")?;
1092 }
1093 Ok(())
1094 }
1095
1096 fn emit_seq_elt<F>(&mut self, idx: usize, f: F) -> EncodeResult
1097 where
1098 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
1099 {
1100 if self.is_emitting_map_key {
1101 return Err(EncoderError::BadHashmapKey);
1102 }
1103 if idx == 0 {
1104 writeln!(self.writer)?;
1105 } else {
1106 writeln!(self.writer, ",")?;
1107 }
1108 spaces(self.writer, self.curr_indent)?;
1109 f(self)
1110 }
1111
1112 fn emit_map<F>(&mut self, len: usize, f: F) -> EncodeResult
1113 where
1114 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
1115 {
1116 if self.is_emitting_map_key {
1117 return Err(EncoderError::BadHashmapKey);
1118 }
1119 if len == 0 {
1120 write!(self.writer, "{{}}")?;
1121 } else {
1122 write!(self.writer, "{{")?;
1123 self.curr_indent += self.indent;
1124 f(self)?;
1125 self.curr_indent -= self.indent;
1126 writeln!(self.writer)?;
1127 spaces(self.writer, self.curr_indent)?;
1128 write!(self.writer, "}}")?;
1129 }
1130 Ok(())
1131 }
1132
1133 fn emit_map_elt_key<F>(&mut self, idx: usize, f: F) -> EncodeResult
1134 where
1135 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
1136 {
1137 if self.is_emitting_map_key {
1138 return Err(EncoderError::BadHashmapKey);
1139 }
1140 if idx == 0 {
1141 writeln!(self.writer)?;
1142 } else {
1143 writeln!(self.writer, ",")?;
1144 }
1145 spaces(self.writer, self.curr_indent)?;
1146 self.is_emitting_map_key = true;
1147 f(self)?;
1148 self.is_emitting_map_key = false;
1149 Ok(())
1150 }
1151
1152 fn emit_map_elt_val<F>(&mut self, _idx: usize, f: F) -> EncodeResult
1153 where
1154 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
1155 {
1156 if self.is_emitting_map_key {
1157 return Err(EncoderError::BadHashmapKey);
1158 }
1159 write!(self.writer, ": ")?;
1160 f(self)
1161 }
1162 }
1163
1164 impl<E: crate::Encoder> Encodable<E> for Json {
1165 fn encode(&self, e: &mut E) -> Result<(), E::Error> {
1166 match *self {
1167 Json::I64(v) => v.encode(e),
1168 Json::U64(v) => v.encode(e),
1169 Json::F64(v) => v.encode(e),
1170 Json::String(ref v) => v.encode(e),
1171 Json::Boolean(v) => v.encode(e),
1172 Json::Array(ref v) => v.encode(e),
1173 Json::Object(ref v) => v.encode(e),
1174 Json::Null => e.emit_unit(),
1175 }
1176 }
1177 }
1178
1179 /// Creates an `AsJson` wrapper which can be used to print a value as JSON
1180 /// on-the-fly via `write!`
1181 pub fn as_json<T>(t: &T) -> AsJson<'_, T> {
1182 AsJson { inner: t }
1183 }
1184
1185 /// Creates an `AsPrettyJson` wrapper which can be used to print a value as JSON
1186 /// on-the-fly via `write!`
1187 pub fn as_pretty_json<T>(t: &T) -> AsPrettyJson<'_, T> {
1188 AsPrettyJson { inner: t, indent: None }
1189 }
1190
1191 impl Json {
1192 /// Borrow this json object as a pretty object to generate a pretty
1193 /// representation for it via `Display`.
1194 pub fn pretty(&self) -> PrettyJson<'_> {
1195 PrettyJson { inner: self }
1196 }
1197
1198 /// If the Json value is an Object, returns the value associated with the provided key.
1199 /// Otherwise, returns None.
1200 pub fn find(&self, key: &str) -> Option<&Json> {
1201 match *self {
1202 Json::Object(ref map) => map.get(key),
1203 _ => None,
1204 }
1205 }
1206
1207 /// Attempts to get a nested Json Object for each key in `keys`.
1208 /// If any key is found not to exist, `find_path` will return `None`.
1209 /// Otherwise, it will return the Json value associated with the final key.
1210 pub fn find_path<'a>(&'a self, keys: &[&str]) -> Option<&'a Json> {
1211 let mut target = self;
1212 for key in keys {
1213 target = target.find(*key)?;
1214 }
1215 Some(target)
1216 }
1217
1218 /// If the Json value is an Object, performs a depth-first search until
1219 /// a value associated with the provided key is found. If no value is found
1220 /// or the Json value is not an Object, returns `None`.
1221 pub fn search(&self, key: &str) -> Option<&Json> {
1222 match *self {
1223 Json::Object(ref map) => match map.get(key) {
1224 Some(json_value) => Some(json_value),
1225 None => {
1226 for v in map.values() {
1227 match v.search(key) {
1228 x if x.is_some() => return x,
1229 _ => (),
1230 }
1231 }
1232 None
1233 }
1234 },
1235 _ => None,
1236 }
1237 }
1238
1239 /// Returns `true` if the Json value is an `Object`.
1240 pub fn is_object(&self) -> bool {
1241 self.as_object().is_some()
1242 }
1243
1244 /// If the Json value is an `Object`, returns the associated `BTreeMap`;
1245 /// returns `None` otherwise.
1246 pub fn as_object(&self) -> Option<&Object> {
1247 match *self {
1248 Json::Object(ref map) => Some(map),
1249 _ => None,
1250 }
1251 }
1252
1253 /// Returns `true` if the Json value is an `Array`.
1254 pub fn is_array(&self) -> bool {
1255 self.as_array().is_some()
1256 }
1257
1258 /// If the Json value is an `Array`, returns the associated vector;
1259 /// returns `None` otherwise.
1260 pub fn as_array(&self) -> Option<&Array> {
1261 match *self {
1262 Json::Array(ref array) => Some(&*array),
1263 _ => None,
1264 }
1265 }
1266
1267 /// Returns `true` if the Json value is a `String`.
1268 pub fn is_string(&self) -> bool {
1269 self.as_string().is_some()
1270 }
1271
1272 /// If the Json value is a `String`, returns the associated `str`;
1273 /// returns `None` otherwise.
1274 pub fn as_string(&self) -> Option<&str> {
1275 match *self {
1276 Json::String(ref s) => Some(&s[..]),
1277 _ => None,
1278 }
1279 }
1280
1281 /// Returns `true` if the Json value is a `Number`.
1282 pub fn is_number(&self) -> bool {
1283 matches!(*self, Json::I64(_) | Json::U64(_) | Json::F64(_))
1284 }
1285
1286 /// Returns `true` if the Json value is a `i64`.
1287 pub fn is_i64(&self) -> bool {
1288 matches!(*self, Json::I64(_))
1289 }
1290
1291 /// Returns `true` if the Json value is a `u64`.
1292 pub fn is_u64(&self) -> bool {
1293 matches!(*self, Json::U64(_))
1294 }
1295
1296 /// Returns `true` if the Json value is a `f64`.
1297 pub fn is_f64(&self) -> bool {
1298 matches!(*self, Json::F64(_))
1299 }
1300
1301 /// If the Json value is a number, returns or cast it to a `i64`;
1302 /// returns `None` otherwise.
1303 pub fn as_i64(&self) -> Option<i64> {
1304 match *self {
1305 Json::I64(n) => Some(n),
1306 Json::U64(n) => Some(n as i64),
1307 _ => None,
1308 }
1309 }
1310
1311 /// If the Json value is a number, returns or cast it to a `u64`;
1312 /// returns `None` otherwise.
1313 pub fn as_u64(&self) -> Option<u64> {
1314 match *self {
1315 Json::I64(n) => Some(n as u64),
1316 Json::U64(n) => Some(n),
1317 _ => None,
1318 }
1319 }
1320
1321 /// If the Json value is a number, returns or cast it to a `f64`;
1322 /// returns `None` otherwise.
1323 pub fn as_f64(&self) -> Option<f64> {
1324 match *self {
1325 Json::I64(n) => Some(n as f64),
1326 Json::U64(n) => Some(n as f64),
1327 Json::F64(n) => Some(n),
1328 _ => None,
1329 }
1330 }
1331
1332 /// Returns `true` if the Json value is a `Boolean`.
1333 pub fn is_boolean(&self) -> bool {
1334 self.as_boolean().is_some()
1335 }
1336
1337 /// If the Json value is a `Boolean`, returns the associated `bool`;
1338 /// returns `None` otherwise.
1339 pub fn as_boolean(&self) -> Option<bool> {
1340 match *self {
1341 Json::Boolean(b) => Some(b),
1342 _ => None,
1343 }
1344 }
1345
1346 /// Returns `true` if the Json value is a `Null`.
1347 pub fn is_null(&self) -> bool {
1348 self.as_null().is_some()
1349 }
1350
1351 /// If the Json value is a `Null`, returns `()`;
1352 /// returns `None` otherwise.
1353 pub fn as_null(&self) -> Option<()> {
1354 match *self {
1355 Json::Null => Some(()),
1356 _ => None,
1357 }
1358 }
1359 }
1360
1361 impl<'a> Index<&'a str> for Json {
1362 type Output = Json;
1363
1364 fn index(&self, idx: &'a str) -> &Json {
1365 self.find(idx).unwrap()
1366 }
1367 }
1368
1369 impl Index<usize> for Json {
1370 type Output = Json;
1371
1372 fn index(&self, idx: usize) -> &Json {
1373 match *self {
1374 Json::Array(ref v) => &v[idx],
1375 _ => panic!("can only index Json with usize if it is an array"),
1376 }
1377 }
1378 }
1379
1380 /// The output of the streaming parser.
1381 #[derive(PartialEq, Clone, Debug)]
1382 pub enum JsonEvent {
1383 ObjectStart,
1384 ObjectEnd,
1385 ArrayStart,
1386 ArrayEnd,
1387 BooleanValue(bool),
1388 I64Value(i64),
1389 U64Value(u64),
1390 F64Value(f64),
1391 StringValue(string::String),
1392 NullValue,
1393 Error(ParserError),
1394 }
1395
1396 #[derive(PartialEq, Debug)]
1397 enum ParserState {
1398 // Parse a value in an array, true means first element.
1399 ParseArray(bool),
1400 // Parse ',' or ']' after an element in an array.
1401 ParseArrayComma,
1402 // Parse a key:value in an object, true means first element.
1403 ParseObject(bool),
1404 // Parse ',' or ']' after an element in an object.
1405 ParseObjectComma,
1406 // Initial state.
1407 ParseStart,
1408 // Expecting the stream to end.
1409 ParseBeforeFinish,
1410 // Parsing can't continue.
1411 ParseFinished,
1412 }
1413
1414 /// A Stack represents the current position of the parser in the logical
1415 /// structure of the JSON stream.
1416 ///
1417 /// An example is `foo.bar[3].x`.
1418 #[derive(Default)]
1419 pub struct Stack {
1420 stack: Vec<InternalStackElement>,
1421 str_buffer: Vec<u8>,
1422 }
1423
1424 /// StackElements compose a Stack.
1425 ///
1426 /// As an example, `StackElement::Key("foo")`, `StackElement::Key("bar")`,
1427 /// `StackElement::Index(3)`, and `StackElement::Key("x")` are the
1428 /// StackElements composing the stack that represents `foo.bar[3].x`.
1429 #[derive(PartialEq, Clone, Debug)]
1430 pub enum StackElement<'l> {
1431 Index(u32),
1432 Key(&'l str),
1433 }
1434
1435 // Internally, Key elements are stored as indices in a buffer to avoid
1436 // allocating a string for every member of an object.
1437 #[derive(PartialEq, Clone, Debug)]
1438 enum InternalStackElement {
1439 InternalIndex(u32),
1440 InternalKey(u16, u16), // start, size
1441 }
1442
1443 impl Stack {
1444 pub fn new() -> Stack {
1445 Self::default()
1446 }
1447
1448 /// Returns The number of elements in the Stack.
1449 pub fn len(&self) -> usize {
1450 self.stack.len()
1451 }
1452
1453 /// Returns `true` if the stack is empty.
1454 pub fn is_empty(&self) -> bool {
1455 self.stack.is_empty()
1456 }
1457
1458 /// Provides access to the StackElement at a given index.
1459 /// lower indices are at the bottom of the stack while higher indices are
1460 /// at the top.
1461 pub fn get(&self, idx: usize) -> StackElement<'_> {
1462 match self.stack[idx] {
1463 InternalIndex(i) => StackElement::Index(i),
1464 InternalKey(start, size) => StackElement::Key(
1465 str::from_utf8(&self.str_buffer[start as usize..start as usize + size as usize])
1466 .unwrap(),
1467 ),
1468 }
1469 }
1470
1471 /// Compares this stack with an array of StackElement<'_>s.
1472 pub fn is_equal_to(&self, rhs: &[StackElement<'_>]) -> bool {
1473 if self.stack.len() != rhs.len() {
1474 return false;
1475 }
1476 for (i, r) in rhs.iter().enumerate() {
1477 if self.get(i) != *r {
1478 return false;
1479 }
1480 }
1481 true
1482 }
1483
1484 /// Returns `true` if the bottom-most elements of this stack are the same as
1485 /// the ones passed as parameter.
1486 pub fn starts_with(&self, rhs: &[StackElement<'_>]) -> bool {
1487 if self.stack.len() < rhs.len() {
1488 return false;
1489 }
1490 for (i, r) in rhs.iter().enumerate() {
1491 if self.get(i) != *r {
1492 return false;
1493 }
1494 }
1495 true
1496 }
1497
1498 /// Returns `true` if the top-most elements of this stack are the same as
1499 /// the ones passed as parameter.
1500 pub fn ends_with(&self, rhs: &[StackElement<'_>]) -> bool {
1501 if self.stack.len() < rhs.len() {
1502 return false;
1503 }
1504 let offset = self.stack.len() - rhs.len();
1505 for (i, r) in rhs.iter().enumerate() {
1506 if self.get(i + offset) != *r {
1507 return false;
1508 }
1509 }
1510 true
1511 }
1512
1513 /// Returns the top-most element (if any).
1514 pub fn top(&self) -> Option<StackElement<'_>> {
1515 match self.stack.last() {
1516 None => None,
1517 Some(&InternalIndex(i)) => Some(StackElement::Index(i)),
1518 Some(&InternalKey(start, size)) => Some(StackElement::Key(
1519 str::from_utf8(&self.str_buffer[start as usize..(start + size) as usize]).unwrap(),
1520 )),
1521 }
1522 }
1523
1524 // Used by Parser to insert StackElement::Key elements at the top of the stack.
1525 fn push_key(&mut self, key: string::String) {
1526 self.stack.push(InternalKey(self.str_buffer.len() as u16, key.len() as u16));
1527 self.str_buffer.extend(key.as_bytes());
1528 }
1529
1530 // Used by Parser to insert StackElement::Index elements at the top of the stack.
1531 fn push_index(&mut self, index: u32) {
1532 self.stack.push(InternalIndex(index));
1533 }
1534
1535 // Used by Parser to remove the top-most element of the stack.
1536 fn pop(&mut self) {
1537 assert!(!self.is_empty());
1538 match *self.stack.last().unwrap() {
1539 InternalKey(_, sz) => {
1540 let new_size = self.str_buffer.len() - sz as usize;
1541 self.str_buffer.truncate(new_size);
1542 }
1543 InternalIndex(_) => {}
1544 }
1545 self.stack.pop();
1546 }
1547
1548 // Used by Parser to test whether the top-most element is an index.
1549 fn last_is_index(&self) -> bool {
1550 matches!(self.stack.last(), Some(InternalIndex(_)))
1551 }
1552
1553 // Used by Parser to increment the index of the top-most element.
1554 fn bump_index(&mut self) {
1555 let len = self.stack.len();
1556 let idx = match *self.stack.last().unwrap() {
1557 InternalIndex(i) => i + 1,
1558 _ => {
1559 panic!();
1560 }
1561 };
1562 self.stack[len - 1] = InternalIndex(idx);
1563 }
1564 }
1565
1566 /// A streaming JSON parser implemented as an iterator of JsonEvent, consuming
1567 /// an iterator of char.
1568 pub struct Parser<T> {
1569 rdr: T,
1570 ch: Option<char>,
1571 line: usize,
1572 col: usize,
1573 // We maintain a stack representing where we are in the logical structure
1574 // of the JSON stream.
1575 stack: Stack,
1576 // A state machine is kept to make it possible to interrupt and resume parsing.
1577 state: ParserState,
1578 }
1579
1580 impl<T: Iterator<Item = char>> Iterator for Parser<T> {
1581 type Item = JsonEvent;
1582
1583 fn next(&mut self) -> Option<JsonEvent> {
1584 if self.state == ParseFinished {
1585 return None;
1586 }
1587
1588 if self.state == ParseBeforeFinish {
1589 self.parse_whitespace();
1590 // Make sure there is no trailing characters.
1591 if self.eof() {
1592 self.state = ParseFinished;
1593 return None;
1594 } else {
1595 return Some(self.error_event(TrailingCharacters));
1596 }
1597 }
1598
1599 Some(self.parse())
1600 }
1601 }
1602
1603 impl<T: Iterator<Item = char>> Parser<T> {
1604 /// Creates the JSON parser.
1605 pub fn new(rdr: T) -> Parser<T> {
1606 let mut p = Parser {
1607 rdr,
1608 ch: Some('\x00'),
1609 line: 1,
1610 col: 0,
1611 stack: Stack::new(),
1612 state: ParseStart,
1613 };
1614 p.bump();
1615 p
1616 }
1617
1618 /// Provides access to the current position in the logical structure of the
1619 /// JSON stream.
1620 pub fn stack(&self) -> &Stack {
1621 &self.stack
1622 }
1623
1624 fn eof(&self) -> bool {
1625 self.ch.is_none()
1626 }
1627 fn ch_or_null(&self) -> char {
1628 self.ch.unwrap_or('\x00')
1629 }
1630 fn bump(&mut self) {
1631 self.ch = self.rdr.next();
1632
1633 if self.ch_is('\n') {
1634 self.line += 1;
1635 self.col = 1;
1636 } else {
1637 self.col += 1;
1638 }
1639 }
1640
1641 fn next_char(&mut self) -> Option<char> {
1642 self.bump();
1643 self.ch
1644 }
1645 fn ch_is(&self, c: char) -> bool {
1646 self.ch == Some(c)
1647 }
1648
1649 fn error<U>(&self, reason: ErrorCode) -> Result<U, ParserError> {
1650 Err(SyntaxError(reason, self.line, self.col))
1651 }
1652
1653 fn parse_whitespace(&mut self) {
1654 while self.ch_is(' ') || self.ch_is('\n') || self.ch_is('\t') || self.ch_is('\r') {
1655 self.bump();
1656 }
1657 }
1658
1659 fn parse_number(&mut self) -> JsonEvent {
1660 let neg = if self.ch_is('-') {
1661 self.bump();
1662 true
1663 } else {
1664 false
1665 };
1666
1667 let res = match self.parse_u64() {
1668 Ok(res) => res,
1669 Err(e) => {
1670 return Error(e);
1671 }
1672 };
1673
1674 if self.ch_is('.') || self.ch_is('e') || self.ch_is('E') {
1675 let mut res = res as f64;
1676
1677 if self.ch_is('.') {
1678 res = match self.parse_decimal(res) {
1679 Ok(res) => res,
1680 Err(e) => {
1681 return Error(e);
1682 }
1683 };
1684 }
1685
1686 if self.ch_is('e') || self.ch_is('E') {
1687 res = match self.parse_exponent(res) {
1688 Ok(res) => res,
1689 Err(e) => {
1690 return Error(e);
1691 }
1692 };
1693 }
1694
1695 if neg {
1696 res *= -1.0;
1697 }
1698
1699 F64Value(res)
1700 } else if neg {
1701 let res = (res as i64).wrapping_neg();
1702
1703 // Make sure we didn't underflow.
1704 if res > 0 {
1705 Error(SyntaxError(InvalidNumber, self.line, self.col))
1706 } else {
1707 I64Value(res)
1708 }
1709 } else {
1710 U64Value(res)
1711 }
1712 }
1713
1714 fn parse_u64(&mut self) -> Result<u64, ParserError> {
1715 let mut accum = 0u64;
1716 let last_accum = 0; // necessary to detect overflow.
1717
1718 match self.ch_or_null() {
1719 '0' => {
1720 self.bump();
1721
1722 // A leading '0' must be the only digit before the decimal point.
1723 if let '0'..='9' = self.ch_or_null() {
1724 return self.error(InvalidNumber);
1725 }
1726 }
1727 '1'..='9' => {
1728 while !self.eof() {
1729 match self.ch_or_null() {
1730 c @ '0'..='9' => {
1731 accum = accum.wrapping_mul(10);
1732 accum = accum.wrapping_add((c as u64) - ('0' as u64));
1733
1734 // Detect overflow by comparing to the last value.
1735 if accum <= last_accum {
1736 return self.error(InvalidNumber);
1737 }
1738
1739 self.bump();
1740 }
1741 _ => break,
1742 }
1743 }
1744 }
1745 _ => return self.error(InvalidNumber),
1746 }
1747
1748 Ok(accum)
1749 }
1750
1751 fn parse_decimal(&mut self, mut res: f64) -> Result<f64, ParserError> {
1752 self.bump();
1753
1754 // Make sure a digit follows the decimal place.
1755 match self.ch_or_null() {
1756 '0'..='9' => (),
1757 _ => return self.error(InvalidNumber),
1758 }
1759
1760 let mut dec = 1.0;
1761 while !self.eof() {
1762 match self.ch_or_null() {
1763 c @ '0'..='9' => {
1764 dec /= 10.0;
1765 res += (((c as isize) - ('0' as isize)) as f64) * dec;
1766 self.bump();
1767 }
1768 _ => break,
1769 }
1770 }
1771
1772 Ok(res)
1773 }
1774
1775 fn parse_exponent(&mut self, mut res: f64) -> Result<f64, ParserError> {
1776 self.bump();
1777
1778 let mut exp = 0;
1779 let mut neg_exp = false;
1780
1781 if self.ch_is('+') {
1782 self.bump();
1783 } else if self.ch_is('-') {
1784 self.bump();
1785 neg_exp = true;
1786 }
1787
1788 // Make sure a digit follows the exponent place.
1789 match self.ch_or_null() {
1790 '0'..='9' => (),
1791 _ => return self.error(InvalidNumber),
1792 }
1793 while !self.eof() {
1794 match self.ch_or_null() {
1795 c @ '0'..='9' => {
1796 exp *= 10;
1797 exp += (c as usize) - ('0' as usize);
1798
1799 self.bump();
1800 }
1801 _ => break,
1802 }
1803 }
1804
1805 let exp = 10_f64.powi(exp as i32);
1806 if neg_exp {
1807 res /= exp;
1808 } else {
1809 res *= exp;
1810 }
1811
1812 Ok(res)
1813 }
1814
1815 fn decode_hex_escape(&mut self) -> Result<u16, ParserError> {
1816 let mut i = 0;
1817 let mut n = 0;
1818 while i < 4 && !self.eof() {
1819 self.bump();
1820 n = match self.ch_or_null() {
1821 c @ '0'..='9' => n * 16 + ((c as u16) - ('0' as u16)),
1822 'a' | 'A' => n * 16 + 10,
1823 'b' | 'B' => n * 16 + 11,
1824 'c' | 'C' => n * 16 + 12,
1825 'd' | 'D' => n * 16 + 13,
1826 'e' | 'E' => n * 16 + 14,
1827 'f' | 'F' => n * 16 + 15,
1828 _ => return self.error(InvalidEscape),
1829 };
1830
1831 i += 1;
1832 }
1833
1834 // Error out if we didn't parse 4 digits.
1835 if i != 4 {
1836 return self.error(InvalidEscape);
1837 }
1838
1839 Ok(n)
1840 }
1841
1842 fn parse_str(&mut self) -> Result<string::String, ParserError> {
1843 let mut escape = false;
1844 let mut res = string::String::new();
1845
1846 loop {
1847 self.bump();
1848 if self.eof() {
1849 return self.error(EOFWhileParsingString);
1850 }
1851
1852 if escape {
1853 match self.ch_or_null() {
1854 '"' => res.push('"'),
1855 '\\' => res.push('\\'),
1856 '/' => res.push('/'),
1857 'b' => res.push('\x08'),
1858 'f' => res.push('\x0c'),
1859 'n' => res.push('\n'),
1860 'r' => res.push('\r'),
1861 't' => res.push('\t'),
1862 'u' => match self.decode_hex_escape()? {
1863 0xDC00..=0xDFFF => return self.error(LoneLeadingSurrogateInHexEscape),
1864
1865 // Non-BMP characters are encoded as a sequence of
1866 // two hex escapes, representing UTF-16 surrogates.
1867 n1 @ 0xD800..=0xDBFF => {
1868 match (self.next_char(), self.next_char()) {
1869 (Some('\\'), Some('u')) => (),
1870 _ => return self.error(UnexpectedEndOfHexEscape),
1871 }
1872
1873 let n2 = self.decode_hex_escape()?;
1874 if !(0xDC00..=0xDFFF).contains(&n2) {
1875 return self.error(LoneLeadingSurrogateInHexEscape);
1876 }
1877 let c =
1878 (u32::from(n1 - 0xD800) << 10 | u32::from(n2 - 0xDC00)) + 0x1_0000;
1879 res.push(char::from_u32(c).unwrap());
1880 }
1881
1882 n => match char::from_u32(u32::from(n)) {
1883 Some(c) => res.push(c),
1884 None => return self.error(InvalidUnicodeCodePoint),
1885 },
1886 },
1887 _ => return self.error(InvalidEscape),
1888 }
1889 escape = false;
1890 } else if self.ch_is('\\') {
1891 escape = true;
1892 } else {
1893 match self.ch {
1894 Some('"') => {
1895 self.bump();
1896 return Ok(res);
1897 }
1898 Some(c) => res.push(c),
1899 None => unreachable!(),
1900 }
1901 }
1902 }
1903 }
1904
1905 // Invoked at each iteration, consumes the stream until it has enough
1906 // information to return a JsonEvent.
1907 // Manages an internal state so that parsing can be interrupted and resumed.
1908 // Also keeps track of the position in the logical structure of the json
1909 // stream isize the form of a stack that can be queried by the user using the
1910 // stack() method.
1911 fn parse(&mut self) -> JsonEvent {
1912 loop {
1913 // The only paths where the loop can spin a new iteration
1914 // are in the cases ParseArrayComma and ParseObjectComma if ','
1915 // is parsed. In these cases the state is set to (respectively)
1916 // ParseArray(false) and ParseObject(false), which always return,
1917 // so there is no risk of getting stuck in an infinite loop.
1918 // All other paths return before the end of the loop's iteration.
1919 self.parse_whitespace();
1920
1921 match self.state {
1922 ParseStart => {
1923 return self.parse_start();
1924 }
1925 ParseArray(first) => {
1926 return self.parse_array(first);
1927 }
1928 ParseArrayComma => {
1929 if let Some(evt) = self.parse_array_comma_or_end() {
1930 return evt;
1931 }
1932 }
1933 ParseObject(first) => {
1934 return self.parse_object(first);
1935 }
1936 ParseObjectComma => {
1937 self.stack.pop();
1938 if self.ch_is(',') {
1939 self.state = ParseObject(false);
1940 self.bump();
1941 } else {
1942 return self.parse_object_end();
1943 }
1944 }
1945 _ => {
1946 return self.error_event(InvalidSyntax);
1947 }
1948 }
1949 }
1950 }
1951
1952 fn parse_start(&mut self) -> JsonEvent {
1953 let val = self.parse_value();
1954 self.state = match val {
1955 Error(_) => ParseFinished,
1956 ArrayStart => ParseArray(true),
1957 ObjectStart => ParseObject(true),
1958 _ => ParseBeforeFinish,
1959 };
1960 val
1961 }
1962
1963 fn parse_array(&mut self, first: bool) -> JsonEvent {
1964 if self.ch_is(']') {
1965 if !first {
1966 self.error_event(InvalidSyntax)
1967 } else {
1968 self.state = if self.stack.is_empty() {
1969 ParseBeforeFinish
1970 } else if self.stack.last_is_index() {
1971 ParseArrayComma
1972 } else {
1973 ParseObjectComma
1974 };
1975 self.bump();
1976 ArrayEnd
1977 }
1978 } else {
1979 if first {
1980 self.stack.push_index(0);
1981 }
1982 let val = self.parse_value();
1983 self.state = match val {
1984 Error(_) => ParseFinished,
1985 ArrayStart => ParseArray(true),
1986 ObjectStart => ParseObject(true),
1987 _ => ParseArrayComma,
1988 };
1989 val
1990 }
1991 }
1992
1993 fn parse_array_comma_or_end(&mut self) -> Option<JsonEvent> {
1994 if self.ch_is(',') {
1995 self.stack.bump_index();
1996 self.state = ParseArray(false);
1997 self.bump();
1998 None
1999 } else if self.ch_is(']') {
2000 self.stack.pop();
2001 self.state = if self.stack.is_empty() {
2002 ParseBeforeFinish
2003 } else if self.stack.last_is_index() {
2004 ParseArrayComma
2005 } else {
2006 ParseObjectComma
2007 };
2008 self.bump();
2009 Some(ArrayEnd)
2010 } else if self.eof() {
2011 Some(self.error_event(EOFWhileParsingArray))
2012 } else {
2013 Some(self.error_event(InvalidSyntax))
2014 }
2015 }
2016
2017 fn parse_object(&mut self, first: bool) -> JsonEvent {
2018 if self.ch_is('}') {
2019 if !first {
2020 if self.stack.is_empty() {
2021 return self.error_event(TrailingComma);
2022 } else {
2023 self.stack.pop();
2024 }
2025 }
2026 self.state = if self.stack.is_empty() {
2027 ParseBeforeFinish
2028 } else if self.stack.last_is_index() {
2029 ParseArrayComma
2030 } else {
2031 ParseObjectComma
2032 };
2033 self.bump();
2034 return ObjectEnd;
2035 }
2036 if self.eof() {
2037 return self.error_event(EOFWhileParsingObject);
2038 }
2039 if !self.ch_is('"') {
2040 return self.error_event(KeyMustBeAString);
2041 }
2042 let s = match self.parse_str() {
2043 Ok(s) => s,
2044 Err(e) => {
2045 self.state = ParseFinished;
2046 return Error(e);
2047 }
2048 };
2049 self.parse_whitespace();
2050 if self.eof() {
2051 return self.error_event(EOFWhileParsingObject);
2052 } else if self.ch_or_null() != ':' {
2053 return self.error_event(ExpectedColon);
2054 }
2055 self.stack.push_key(s);
2056 self.bump();
2057 self.parse_whitespace();
2058
2059 let val = self.parse_value();
2060
2061 self.state = match val {
2062 Error(_) => ParseFinished,
2063 ArrayStart => ParseArray(true),
2064 ObjectStart => ParseObject(true),
2065 _ => ParseObjectComma,
2066 };
2067 val
2068 }
2069
2070 fn parse_object_end(&mut self) -> JsonEvent {
2071 if self.ch_is('}') {
2072 self.state = if self.stack.is_empty() {
2073 ParseBeforeFinish
2074 } else if self.stack.last_is_index() {
2075 ParseArrayComma
2076 } else {
2077 ParseObjectComma
2078 };
2079 self.bump();
2080 ObjectEnd
2081 } else if self.eof() {
2082 self.error_event(EOFWhileParsingObject)
2083 } else {
2084 self.error_event(InvalidSyntax)
2085 }
2086 }
2087
2088 fn parse_value(&mut self) -> JsonEvent {
2089 if self.eof() {
2090 return self.error_event(EOFWhileParsingValue);
2091 }
2092 match self.ch_or_null() {
2093 'n' => self.parse_ident("ull", NullValue),
2094 't' => self.parse_ident("rue", BooleanValue(true)),
2095 'f' => self.parse_ident("alse", BooleanValue(false)),
2096 '0'..='9' | '-' => self.parse_number(),
2097 '"' => match self.parse_str() {
2098 Ok(s) => StringValue(s),
2099 Err(e) => Error(e),
2100 },
2101 '[' => {
2102 self.bump();
2103 ArrayStart
2104 }
2105 '{' => {
2106 self.bump();
2107 ObjectStart
2108 }
2109 _ => self.error_event(InvalidSyntax),
2110 }
2111 }
2112
2113 fn parse_ident(&mut self, ident: &str, value: JsonEvent) -> JsonEvent {
2114 if ident.chars().all(|c| Some(c) == self.next_char()) {
2115 self.bump();
2116 value
2117 } else {
2118 Error(SyntaxError(InvalidSyntax, self.line, self.col))
2119 }
2120 }
2121
2122 fn error_event(&mut self, reason: ErrorCode) -> JsonEvent {
2123 self.state = ParseFinished;
2124 Error(SyntaxError(reason, self.line, self.col))
2125 }
2126 }
2127
2128 /// A Builder consumes a json::Parser to create a generic Json structure.
2129 pub struct Builder<T> {
2130 parser: Parser<T>,
2131 token: Option<JsonEvent>,
2132 }
2133
2134 impl<T: Iterator<Item = char>> Builder<T> {
2135 /// Creates a JSON Builder.
2136 pub fn new(src: T) -> Builder<T> {
2137 Builder { parser: Parser::new(src), token: None }
2138 }
2139
2140 // Decode a Json value from a Parser.
2141 pub fn build(&mut self) -> Result<Json, BuilderError> {
2142 self.bump();
2143 let result = self.build_value();
2144 self.bump();
2145 match self.token {
2146 None => {}
2147 Some(Error(ref e)) => {
2148 return Err(e.clone());
2149 }
2150 ref tok => {
2151 panic!("unexpected token {:?}", tok.clone());
2152 }
2153 }
2154 result
2155 }
2156
2157 fn bump(&mut self) {
2158 self.token = self.parser.next();
2159 }
2160
2161 fn build_value(&mut self) -> Result<Json, BuilderError> {
2162 match self.token {
2163 Some(NullValue) => Ok(Json::Null),
2164 Some(I64Value(n)) => Ok(Json::I64(n)),
2165 Some(U64Value(n)) => Ok(Json::U64(n)),
2166 Some(F64Value(n)) => Ok(Json::F64(n)),
2167 Some(BooleanValue(b)) => Ok(Json::Boolean(b)),
2168 Some(StringValue(ref mut s)) => {
2169 let mut temp = string::String::new();
2170 swap(s, &mut temp);
2171 Ok(Json::String(temp))
2172 }
2173 Some(Error(ref e)) => Err(e.clone()),
2174 Some(ArrayStart) => self.build_array(),
2175 Some(ObjectStart) => self.build_object(),
2176 Some(ObjectEnd) => self.parser.error(InvalidSyntax),
2177 Some(ArrayEnd) => self.parser.error(InvalidSyntax),
2178 None => self.parser.error(EOFWhileParsingValue),
2179 }
2180 }
2181
2182 fn build_array(&mut self) -> Result<Json, BuilderError> {
2183 self.bump();
2184 let mut values = Vec::new();
2185
2186 loop {
2187 if self.token == Some(ArrayEnd) {
2188 return Ok(Json::Array(values.into_iter().collect()));
2189 }
2190 match self.build_value() {
2191 Ok(v) => values.push(v),
2192 Err(e) => return Err(e),
2193 }
2194 self.bump();
2195 }
2196 }
2197
2198 fn build_object(&mut self) -> Result<Json, BuilderError> {
2199 self.bump();
2200
2201 let mut values = BTreeMap::new();
2202
2203 loop {
2204 match self.token {
2205 Some(ObjectEnd) => {
2206 return Ok(Json::Object(values));
2207 }
2208 Some(Error(ref e)) => {
2209 return Err(e.clone());
2210 }
2211 None => {
2212 break;
2213 }
2214 _ => {}
2215 }
2216 let key = match self.parser.stack().top() {
2217 Some(StackElement::Key(k)) => k.to_owned(),
2218 _ => {
2219 panic!("invalid state");
2220 }
2221 };
2222 match self.build_value() {
2223 Ok(value) => {
2224 values.insert(key, value);
2225 }
2226 Err(e) => {
2227 return Err(e);
2228 }
2229 }
2230 self.bump();
2231 }
2232 self.parser.error(EOFWhileParsingObject)
2233 }
2234 }
2235
2236 /// Decodes a json value from an `&mut io::Read`
2237 pub fn from_reader(rdr: &mut dyn Read) -> Result<Json, BuilderError> {
2238 let mut contents = Vec::new();
2239 match rdr.read_to_end(&mut contents) {
2240 Ok(c) => c,
2241 Err(e) => return Err(io_error_to_error(e)),
2242 };
2243 let s = match str::from_utf8(&contents).ok() {
2244 Some(s) => s,
2245 _ => return Err(SyntaxError(NotUtf8, 0, 0)),
2246 };
2247 let mut builder = Builder::new(s.chars());
2248 builder.build()
2249 }
2250
2251 /// Decodes a json value from a string
2252 pub fn from_str(s: &str) -> Result<Json, BuilderError> {
2253 let mut builder = Builder::new(s.chars());
2254 builder.build()
2255 }
2256
2257 /// A structure to decode JSON to values in rust.
2258 pub struct Decoder {
2259 stack: Vec<Json>,
2260 }
2261
2262 impl Decoder {
2263 /// Creates a new decoder instance for decoding the specified JSON value.
2264 pub fn new(json: Json) -> Decoder {
2265 Decoder { stack: vec![json] }
2266 }
2267
2268 fn pop(&mut self) -> Json {
2269 self.stack.pop().unwrap()
2270 }
2271 }
2272
2273 macro_rules! expect {
2274 ($e:expr, Null) => {{
2275 match $e {
2276 Json::Null => Ok(()),
2277 other => Err(ExpectedError("Null".to_owned(), other.to_string())),
2278 }
2279 }};
2280 ($e:expr, $t:ident) => {{
2281 match $e {
2282 Json::$t(v) => Ok(v),
2283 other => Err(ExpectedError(stringify!($t).to_owned(), other.to_string())),
2284 }
2285 }};
2286 }
2287
2288 macro_rules! read_primitive {
2289 ($name:ident, $ty:ty) => {
2290 fn $name(&mut self) -> DecodeResult<$ty> {
2291 match self.pop() {
2292 Json::I64(f) => Ok(f as $ty),
2293 Json::U64(f) => Ok(f as $ty),
2294 Json::F64(f) => Err(ExpectedError("Integer".to_owned(), f.to_string())),
2295 // re: #12967.. a type w/ numeric keys (ie HashMap<usize, V> etc)
2296 // is going to have a string here, as per JSON spec.
2297 Json::String(s) => match s.parse().ok() {
2298 Some(f) => Ok(f),
2299 None => Err(ExpectedError("Number".to_owned(), s)),
2300 },
2301 value => Err(ExpectedError("Number".to_owned(), value.to_string())),
2302 }
2303 }
2304 };
2305 }
2306
2307 impl crate::Decoder for Decoder {
2308 type Error = DecoderError;
2309
2310 fn read_nil(&mut self) -> DecodeResult<()> {
2311 expect!(self.pop(), Null)
2312 }
2313
2314 read_primitive! { read_usize, usize }
2315 read_primitive! { read_u8, u8 }
2316 read_primitive! { read_u16, u16 }
2317 read_primitive! { read_u32, u32 }
2318 read_primitive! { read_u64, u64 }
2319 read_primitive! { read_u128, u128 }
2320 read_primitive! { read_isize, isize }
2321 read_primitive! { read_i8, i8 }
2322 read_primitive! { read_i16, i16 }
2323 read_primitive! { read_i32, i32 }
2324 read_primitive! { read_i64, i64 }
2325 read_primitive! { read_i128, i128 }
2326
2327 fn read_f32(&mut self) -> DecodeResult<f32> {
2328 self.read_f64().map(|x| x as f32)
2329 }
2330
2331 fn read_f64(&mut self) -> DecodeResult<f64> {
2332 match self.pop() {
2333 Json::I64(f) => Ok(f as f64),
2334 Json::U64(f) => Ok(f as f64),
2335 Json::F64(f) => Ok(f),
2336 Json::String(s) => {
2337 // re: #12967.. a type w/ numeric keys (ie HashMap<usize, V> etc)
2338 // is going to have a string here, as per JSON spec.
2339 match s.parse().ok() {
2340 Some(f) => Ok(f),
2341 None => Err(ExpectedError("Number".to_owned(), s)),
2342 }
2343 }
2344 Json::Null => Ok(f64::NAN),
2345 value => Err(ExpectedError("Number".to_owned(), value.to_string())),
2346 }
2347 }
2348
2349 fn read_bool(&mut self) -> DecodeResult<bool> {
2350 expect!(self.pop(), Boolean)
2351 }
2352
2353 fn read_char(&mut self) -> DecodeResult<char> {
2354 let s = self.read_str()?;
2355 {
2356 let mut it = s.chars();
2357 if let (Some(c), None) = (it.next(), it.next()) {
2358 // exactly one character
2359 return Ok(c);
2360 }
2361 }
2362 Err(ExpectedError("single character string".to_owned(), s.to_string()))
2363 }
2364
2365 fn read_str(&mut self) -> DecodeResult<Cow<'_, str>> {
2366 expect!(self.pop(), String).map(Cow::Owned)
2367 }
2368
2369 fn read_raw_bytes_into(&mut self, s: &mut [u8]) -> Result<(), Self::Error> {
2370 for c in s.iter_mut() {
2371 *c = self.read_u8()?;
2372 }
2373 Ok(())
2374 }
2375
2376 fn read_enum<T, F>(&mut self, _name: &str, f: F) -> DecodeResult<T>
2377 where
2378 F: FnOnce(&mut Decoder) -> DecodeResult<T>,
2379 {
2380 f(self)
2381 }
2382
2383 fn read_enum_variant<T, F>(&mut self, names: &[&str], mut f: F) -> DecodeResult<T>
2384 where
2385 F: FnMut(&mut Decoder, usize) -> DecodeResult<T>,
2386 {
2387 let name = match self.pop() {
2388 Json::String(s) => s,
2389 Json::Object(mut o) => {
2390 let n = match o.remove(&"variant".to_owned()) {
2391 Some(Json::String(s)) => s,
2392 Some(val) => return Err(ExpectedError("String".to_owned(), val.to_string())),
2393 None => return Err(MissingFieldError("variant".to_owned())),
2394 };
2395 match o.remove(&"fields".to_string()) {
2396 Some(Json::Array(l)) => {
2397 self.stack.extend(l.into_iter().rev());
2398 }
2399 Some(val) => return Err(ExpectedError("Array".to_owned(), val.to_string())),
2400 None => return Err(MissingFieldError("fields".to_owned())),
2401 }
2402 n
2403 }
2404 json => return Err(ExpectedError("String or Object".to_owned(), json.to_string())),
2405 };
2406 let idx = match names.iter().position(|n| *n == &name[..]) {
2407 Some(idx) => idx,
2408 None => return Err(UnknownVariantError(name)),
2409 };
2410 f(self, idx)
2411 }
2412
2413 fn read_enum_variant_arg<T, F>(&mut self, _idx: usize, f: F) -> DecodeResult<T>
2414 where
2415 F: FnOnce(&mut Decoder) -> DecodeResult<T>,
2416 {
2417 f(self)
2418 }
2419
2420 fn read_enum_struct_variant<T, F>(&mut self, names: &[&str], f: F) -> DecodeResult<T>
2421 where
2422 F: FnMut(&mut Decoder, usize) -> DecodeResult<T>,
2423 {
2424 self.read_enum_variant(names, f)
2425 }
2426
2427 fn read_enum_struct_variant_field<T, F>(
2428 &mut self,
2429 _name: &str,
2430 idx: usize,
2431 f: F,
2432 ) -> DecodeResult<T>
2433 where
2434 F: FnOnce(&mut Decoder) -> DecodeResult<T>,
2435 {
2436 self.read_enum_variant_arg(idx, f)
2437 }
2438
2439 fn read_struct<T, F>(&mut self, _name: &str, _len: usize, f: F) -> DecodeResult<T>
2440 where
2441 F: FnOnce(&mut Decoder) -> DecodeResult<T>,
2442 {
2443 let value = f(self)?;
2444 self.pop();
2445 Ok(value)
2446 }
2447
2448 fn read_struct_field<T, F>(&mut self, name: &str, _idx: usize, f: F) -> DecodeResult<T>
2449 where
2450 F: FnOnce(&mut Decoder) -> DecodeResult<T>,
2451 {
2452 let mut obj = expect!(self.pop(), Object)?;
2453
2454 let value = match obj.remove(&name.to_string()) {
2455 None => {
2456 // Add a Null and try to parse it as an Option<_>
2457 // to get None as a default value.
2458 self.stack.push(Json::Null);
2459 match f(self) {
2460 Ok(x) => x,
2461 Err(_) => return Err(MissingFieldError(name.to_string())),
2462 }
2463 }
2464 Some(json) => {
2465 self.stack.push(json);
2466 f(self)?
2467 }
2468 };
2469 self.stack.push(Json::Object(obj));
2470 Ok(value)
2471 }
2472
2473 fn read_tuple<T, F>(&mut self, tuple_len: usize, f: F) -> DecodeResult<T>
2474 where
2475 F: FnOnce(&mut Decoder) -> DecodeResult<T>,
2476 {
2477 self.read_seq(move |d, len| {
2478 if len == tuple_len {
2479 f(d)
2480 } else {
2481 Err(ExpectedError(format!("Tuple{}", tuple_len), format!("Tuple{}", len)))
2482 }
2483 })
2484 }
2485
2486 fn read_tuple_arg<T, F>(&mut self, idx: usize, f: F) -> DecodeResult<T>
2487 where
2488 F: FnOnce(&mut Decoder) -> DecodeResult<T>,
2489 {
2490 self.read_seq_elt(idx, f)
2491 }
2492
2493 fn read_tuple_struct<T, F>(&mut self, _name: &str, len: usize, f: F) -> DecodeResult<T>
2494 where
2495 F: FnOnce(&mut Decoder) -> DecodeResult<T>,
2496 {
2497 self.read_tuple(len, f)
2498 }
2499
2500 fn read_tuple_struct_arg<T, F>(&mut self, idx: usize, f: F) -> DecodeResult<T>
2501 where
2502 F: FnOnce(&mut Decoder) -> DecodeResult<T>,
2503 {
2504 self.read_tuple_arg(idx, f)
2505 }
2506
2507 fn read_option<T, F>(&mut self, mut f: F) -> DecodeResult<T>
2508 where
2509 F: FnMut(&mut Decoder, bool) -> DecodeResult<T>,
2510 {
2511 match self.pop() {
2512 Json::Null => f(self, false),
2513 value => {
2514 self.stack.push(value);
2515 f(self, true)
2516 }
2517 }
2518 }
2519
2520 fn read_seq<T, F>(&mut self, f: F) -> DecodeResult<T>
2521 where
2522 F: FnOnce(&mut Decoder, usize) -> DecodeResult<T>,
2523 {
2524 let array = expect!(self.pop(), Array)?;
2525 let len = array.len();
2526 self.stack.extend(array.into_iter().rev());
2527 f(self, len)
2528 }
2529
2530 fn read_seq_elt<T, F>(&mut self, _idx: usize, f: F) -> DecodeResult<T>
2531 where
2532 F: FnOnce(&mut Decoder) -> DecodeResult<T>,
2533 {
2534 f(self)
2535 }
2536
2537 fn read_map<T, F>(&mut self, f: F) -> DecodeResult<T>
2538 where
2539 F: FnOnce(&mut Decoder, usize) -> DecodeResult<T>,
2540 {
2541 let obj = expect!(self.pop(), Object)?;
2542 let len = obj.len();
2543 for (key, value) in obj {
2544 self.stack.push(value);
2545 self.stack.push(Json::String(key));
2546 }
2547 f(self, len)
2548 }
2549
2550 fn read_map_elt_key<T, F>(&mut self, _idx: usize, f: F) -> DecodeResult<T>
2551 where
2552 F: FnOnce(&mut Decoder) -> DecodeResult<T>,
2553 {
2554 f(self)
2555 }
2556
2557 fn read_map_elt_val<T, F>(&mut self, _idx: usize, f: F) -> DecodeResult<T>
2558 where
2559 F: FnOnce(&mut Decoder) -> DecodeResult<T>,
2560 {
2561 f(self)
2562 }
2563
2564 fn error(&mut self, err: &str) -> DecoderError {
2565 ApplicationError(err.to_string())
2566 }
2567 }
2568
2569 /// A trait for converting values to JSON
2570 pub trait ToJson {
2571 /// Converts the value of `self` to an instance of JSON
2572 fn to_json(&self) -> Json;
2573 }
2574
2575 macro_rules! to_json_impl_i64 {
2576 ($($t:ty), +) => (
2577 $(impl ToJson for $t {
2578 fn to_json(&self) -> Json {
2579 Json::I64(*self as i64)
2580 }
2581 })+
2582 )
2583 }
2584
2585 to_json_impl_i64! { isize, i8, i16, i32, i64 }
2586
2587 macro_rules! to_json_impl_u64 {
2588 ($($t:ty), +) => (
2589 $(impl ToJson for $t {
2590 fn to_json(&self) -> Json {
2591 Json::U64(*self as u64)
2592 }
2593 })+
2594 )
2595 }
2596
2597 to_json_impl_u64! { usize, u8, u16, u32, u64 }
2598
2599 impl ToJson for Json {
2600 fn to_json(&self) -> Json {
2601 self.clone()
2602 }
2603 }
2604
2605 impl ToJson for f32 {
2606 fn to_json(&self) -> Json {
2607 f64::from(*self).to_json()
2608 }
2609 }
2610
2611 impl ToJson for f64 {
2612 fn to_json(&self) -> Json {
2613 match self.classify() {
2614 Fp::Nan | Fp::Infinite => Json::Null,
2615 _ => Json::F64(*self),
2616 }
2617 }
2618 }
2619
2620 impl ToJson for () {
2621 fn to_json(&self) -> Json {
2622 Json::Null
2623 }
2624 }
2625
2626 impl ToJson for bool {
2627 fn to_json(&self) -> Json {
2628 Json::Boolean(*self)
2629 }
2630 }
2631
2632 impl ToJson for str {
2633 fn to_json(&self) -> Json {
2634 Json::String(self.to_string())
2635 }
2636 }
2637
2638 impl ToJson for string::String {
2639 fn to_json(&self) -> Json {
2640 Json::String((*self).clone())
2641 }
2642 }
2643
2644 macro_rules! tuple_impl {
2645 // use variables to indicate the arity of the tuple
2646 ($($tyvar:ident),* ) => {
2647 // the trailing commas are for the 1 tuple
2648 impl<
2649 $( $tyvar : ToJson ),*
2650 > ToJson for ( $( $tyvar ),* , ) {
2651
2652 #[inline]
2653 #[allow(non_snake_case)]
2654 fn to_json(&self) -> Json {
2655 match *self {
2656 ($(ref $tyvar),*,) => Json::Array(vec![$($tyvar.to_json()),*])
2657 }
2658 }
2659 }
2660 }
2661 }
2662
2663 tuple_impl! {A}
2664 tuple_impl! {A, B}
2665 tuple_impl! {A, B, C}
2666 tuple_impl! {A, B, C, D}
2667 tuple_impl! {A, B, C, D, E}
2668 tuple_impl! {A, B, C, D, E, F}
2669 tuple_impl! {A, B, C, D, E, F, G}
2670 tuple_impl! {A, B, C, D, E, F, G, H}
2671 tuple_impl! {A, B, C, D, E, F, G, H, I}
2672 tuple_impl! {A, B, C, D, E, F, G, H, I, J}
2673 tuple_impl! {A, B, C, D, E, F, G, H, I, J, K}
2674 tuple_impl! {A, B, C, D, E, F, G, H, I, J, K, L}
2675
2676 impl<A: ToJson> ToJson for [A] {
2677 fn to_json(&self) -> Json {
2678 Json::Array(self.iter().map(|elt| elt.to_json()).collect())
2679 }
2680 }
2681
2682 impl<A: ToJson> ToJson for Vec<A> {
2683 fn to_json(&self) -> Json {
2684 Json::Array(self.iter().map(|elt| elt.to_json()).collect())
2685 }
2686 }
2687
2688 impl<T: ToString, A: ToJson> ToJson for BTreeMap<T, A> {
2689 fn to_json(&self) -> Json {
2690 let mut d = BTreeMap::new();
2691 for (key, value) in self {
2692 d.insert(key.to_string(), value.to_json());
2693 }
2694 Json::Object(d)
2695 }
2696 }
2697
2698 impl<A: ToJson> ToJson for HashMap<string::String, A> {
2699 fn to_json(&self) -> Json {
2700 let mut d = BTreeMap::new();
2701 for (key, value) in self {
2702 d.insert((*key).clone(), value.to_json());
2703 }
2704 Json::Object(d)
2705 }
2706 }
2707
2708 impl<A: ToJson> ToJson for Option<A> {
2709 fn to_json(&self) -> Json {
2710 match *self {
2711 None => Json::Null,
2712 Some(ref value) => value.to_json(),
2713 }
2714 }
2715 }
2716
2717 struct FormatShim<'a, 'b> {
2718 inner: &'a mut fmt::Formatter<'b>,
2719 }
2720
2721 impl<'a, 'b> fmt::Write for FormatShim<'a, 'b> {
2722 fn write_str(&mut self, s: &str) -> fmt::Result {
2723 match self.inner.write_str(s) {
2724 Ok(_) => Ok(()),
2725 Err(_) => Err(fmt::Error),
2726 }
2727 }
2728 }
2729
2730 impl fmt::Display for Json {
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.encode(&mut encoder) {
2736 Ok(_) => Ok(()),
2737 Err(_) => Err(fmt::Error),
2738 }
2739 }
2740 }
2741
2742 impl<'a> fmt::Display for PrettyJson<'a> {
2743 /// Encodes a json value into a string
2744 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2745 let mut shim = FormatShim { inner: f };
2746 let mut encoder = PrettyEncoder::new(&mut shim);
2747 match self.inner.encode(&mut encoder) {
2748 Ok(_) => Ok(()),
2749 Err(_) => Err(fmt::Error),
2750 }
2751 }
2752 }
2753
2754 impl<'a, T: for<'r> Encodable<Encoder<'r>>> fmt::Display for AsJson<'a, T> {
2755 /// Encodes a json value into a string
2756 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2757 let mut shim = FormatShim { inner: f };
2758 let mut encoder = Encoder::new(&mut shim);
2759 match self.inner.encode(&mut encoder) {
2760 Ok(_) => Ok(()),
2761 Err(_) => Err(fmt::Error),
2762 }
2763 }
2764 }
2765
2766 impl<'a, T> AsPrettyJson<'a, T> {
2767 /// Sets the indentation level for the emitted JSON
2768 pub fn indent(mut self, indent: usize) -> AsPrettyJson<'a, T> {
2769 self.indent = Some(indent);
2770 self
2771 }
2772 }
2773
2774 impl<'a, T: for<'x> Encodable<PrettyEncoder<'x>>> fmt::Display for AsPrettyJson<'a, T> {
2775 /// Encodes a json value into a string
2776 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2777 let mut shim = FormatShim { inner: f };
2778 let mut encoder = PrettyEncoder::new(&mut shim);
2779 if let Some(n) = self.indent {
2780 encoder.set_indent(n);
2781 }
2782 match self.inner.encode(&mut encoder) {
2783 Ok(_) => Ok(()),
2784 Err(_) => Err(fmt::Error),
2785 }
2786 }
2787 }
2788
2789 impl FromStr for Json {
2790 type Err = BuilderError;
2791 fn from_str(s: &str) -> Result<Json, BuilderError> {
2792 from_str(s)
2793 }
2794 }
2795
2796 #[cfg(test)]
2797 mod tests;