1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 // Rust JSON serialization library
12 // Copyright (c) 2011 Google Inc.
14 #![forbid(non_camel_case_types)]
15 #![allow(missing_docs)]
17 //! JSON parsing and serialization
21 //! JSON (JavaScript Object Notation) is a way to write data in Javascript.
22 //! Like XML, it allows to encode structured data in a text format that can be easily read by humans
23 //! Its simple syntax and native compatibility with JavaScript have made it a widely used format.
25 //! Data types that can be encoded are JavaScript types (see the `Json` enum for more details):
27 //! * `Boolean`: equivalent to rust's `bool`
28 //! * `Number`: equivalent to rust's `f64`
29 //! * `String`: equivalent to rust's `String`
30 //! * `Array`: equivalent to rust's `Vec<T>`, but also allowing objects of different types in the
32 //! * `Object`: equivalent to rust's `Treemap<String, json::Json>`
35 //! An object is a series of string keys mapping to values, in `"key": value` format.
36 //! Arrays are enclosed in square brackets ([ ... ]) and objects in curly brackets ({ ... }).
37 //! A simple JSON document encoding a person, his/her age, address and phone numbers could look like
41 //! "FirstName": "John",
42 //! "LastName": "Doe",
45 //! "Street": "Downing Street 10",
47 //! "Country": "Great Britain"
56 //! # Rust Type-based Encoding and Decoding
58 //! Rust provides a mechanism for low boilerplate encoding & decoding of values to and from JSON via
59 //! the serialization API.
60 //! To be able to encode a piece of data, it must implement the `serialize::Encodable` trait.
61 //! To be able to decode a piece of data, it must implement the `serialize::Decodable` trait.
62 //! The Rust compiler provides an annotation to automatically generate the code for these traits:
63 //! `#[deriving(Decodable, Encodable)]`
65 //! The JSON API provides an enum `json::Json` and a trait `ToJson` to encode objects.
66 //! The `ToJson` trait provides a `to_json` method to convert an object into a `json::Json` value.
67 //! A `json::Json` value can be encoded as a string or buffer using the functions described above.
68 //! You can also use the `json::Encoder` object, which implements the `Encoder` trait.
70 //! When using `ToJson` the `Encodable` trait implementation is not mandatory.
74 //! ## Using Autoserialization
76 //! Create a struct called `TestStruct` and serialize and deserialize it to and from JSON using the
77 //! serialization API, using the derived serialization code.
80 //! extern crate serialize;
81 //! use serialize::json;
83 //! // Automatically generate `Decodable` and `Encodable` trait implementations
84 //! #[deriving(Decodable, Encodable)]
85 //! pub struct TestStruct {
88 //! data_vector: Vec<u8>,
92 //! let object = TestStruct {
94 //! data_str: "homura".to_string(),
95 //! data_vector: vec![2,3,4,5],
98 //! // Serialize using `json::encode`
99 //! let encoded = json::encode(&object);
101 //! // Deserialize using `json::decode`
102 //! let decoded: TestStruct = json::decode(encoded.as_slice()).unwrap();
106 //! ## Using the `ToJson` trait
108 //! The examples above use the `ToJson` trait to generate the JSON string, which is required
109 //! for custom mappings.
111 //! ### Simple example of `ToJson` usage
114 //! extern crate serialize;
115 //! use serialize::json::{mod, ToJson, Json};
117 //! // A custom data structure
118 //! struct ComplexNum {
123 //! // JSON value representation
124 //! impl ToJson for ComplexNum {
125 //! fn to_json(&self) -> Json {
126 //! Json::String(format!("{}+{}i", self.a, self.b))
130 //! // Only generate `Encodable` trait implementation
131 //! #[deriving(Encodable)]
132 //! pub struct ComplexNumRecord {
139 //! let num = ComplexNum { a: 0.0001, b: 12.539 };
140 //! let data: String = json::encode(&ComplexNumRecord{
142 //! dsc: "test".to_string(),
143 //! val: num.to_json(),
145 //! println!("data: {}", data);
146 //! // data: {"uid":1,"dsc":"test","val":"0.0001+12.539j"};
150 //! ### Verbose example of `ToJson` usage
153 //! extern crate serialize;
154 //! use std::collections::TreeMap;
155 //! use serialize::json::{mod, Json, ToJson};
157 //! // Only generate `Decodable` trait implementation
158 //! #[deriving(Decodable)]
159 //! pub struct TestStruct {
161 //! data_str: String,
162 //! data_vector: Vec<u8>,
165 //! // Specify encoding method manually
166 //! impl ToJson for TestStruct {
167 //! fn to_json(&self) -> Json {
168 //! let mut d = TreeMap::new();
169 //! // All standard types implement `to_json()`, so use it
170 //! d.insert("data_int".to_string(), self.data_int.to_json());
171 //! d.insert("data_str".to_string(), self.data_str.to_json());
172 //! d.insert("data_vector".to_string(), self.data_vector.to_json());
178 //! // Serialize using `ToJson`
179 //! let input_data = TestStruct {
181 //! data_str: "madoka".to_string(),
182 //! data_vector: vec![2,3,4,5],
184 //! let json_obj: Json = input_data.to_json();
185 //! let json_str: String = json_obj.to_string();
187 //! // Deserialize like before
188 //! let decoded: TestStruct = json::decode(json_str.as_slice()).unwrap();
192 use self::JsonEvent::*;
193 use self::StackElement::*;
194 use self::ErrorCode::*;
195 use self::ParserError::*;
196 use self::DecoderError::*;
197 use self::ParserState::*;
198 use self::InternalStackElement::*;
201 use std::collections::{HashMap, TreeMap};
202 use std::{char, f64, fmt, io, num, str};
203 use std::mem::{swap, transmute};
204 use std::num::{Float, FPNaN, FPInfinite, Int};
205 use std::str::{FromStr, ScalarValue};
212 /// Represents a json value
213 #[deriving(Clone, PartialEq, PartialOrd)]
218 String(string::String),
221 Object(self::Object),
225 pub type Array = Vec<Json>;
226 pub type Object = TreeMap<string::String, Json>;
228 /// The errors that can arise while parsing a JSON stream.
229 #[deriving(Clone, PartialEq)]
233 EOFWhileParsingObject,
234 EOFWhileParsingArray,
235 EOFWhileParsingValue,
236 EOFWhileParsingString,
242 InvalidUnicodeCodePoint,
243 LoneLeadingSurrogateInHexEscape,
244 UnexpectedEndOfHexEscape,
250 #[deriving(Clone, PartialEq, Show)]
251 pub enum ParserError {
253 SyntaxError(ErrorCode, uint, uint),
254 IoError(io::IoErrorKind, &'static str),
257 // Builder and Parser have the same errors.
258 pub type BuilderError = ParserError;
260 #[deriving(Clone, PartialEq, Show)]
261 pub enum DecoderError {
262 ParseError(ParserError),
263 ExpectedError(string::String, string::String),
264 MissingFieldError(string::String),
265 UnknownVariantError(string::String),
266 ApplicationError(string::String)
269 /// Returns a readable error string for a given error code.
270 pub fn error_str(error: ErrorCode) -> &'static str {
272 InvalidSyntax => "invalid syntax",
273 InvalidNumber => "invalid number",
274 EOFWhileParsingObject => "EOF While parsing object",
275 EOFWhileParsingArray => "EOF While parsing array",
276 EOFWhileParsingValue => "EOF While parsing value",
277 EOFWhileParsingString => "EOF While parsing string",
278 KeyMustBeAString => "key must be a string",
279 ExpectedColon => "expected `:`",
280 TrailingCharacters => "trailing characters",
281 TrailingComma => "trailing comma",
282 InvalidEscape => "invalid escape",
283 UnrecognizedHex => "invalid \\u escape (unrecognized hex)",
284 NotFourDigit => "invalid \\u escape (not four digits)",
285 NotUtf8 => "contents not utf-8",
286 InvalidUnicodeCodePoint => "invalid Unicode code point",
287 LoneLeadingSurrogateInHexEscape => "lone leading surrogate in hex escape",
288 UnexpectedEndOfHexEscape => "unexpected end of hex escape",
292 /// Shortcut function to decode a JSON `&str` into an object
293 pub fn decode<T: ::Decodable<Decoder, DecoderError>>(s: &str) -> DecodeResult<T> {
294 let json = match from_str(s) {
296 Err(e) => return Err(ParseError(e))
299 let mut decoder = Decoder::new(json);
300 ::Decodable::decode(&mut decoder)
303 /// Shortcut function to encode a `T` into a JSON `String`
304 pub fn encode<'a, T: Encodable<Encoder<'a>, io::IoError>>(object: &T) -> string::String {
305 let buff = Encoder::buffer_encode(object);
306 string::String::from_utf8(buff).unwrap()
309 impl fmt::Show for ErrorCode {
310 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
311 error_str(*self).fmt(f)
315 fn io_error_to_error(io: io::IoError) -> ParserError {
316 IoError(io.kind, io.desc)
319 impl std::error::Error for DecoderError {
320 fn description(&self) -> &str { "decoder error" }
321 fn detail(&self) -> Option<std::string::String> { Some(self.to_string()) }
324 pub type EncodeResult = io::IoResult<()>;
325 pub type DecodeResult<T> = Result<T, DecoderError>;
327 pub fn escape_bytes(wr: &mut io::Writer, bytes: &[u8]) -> Result<(), io::IoError> {
328 try!(wr.write_str("\""));
332 for (i, byte) in bytes.iter().enumerate() {
333 let escaped = match *byte {
345 try!(wr.write(bytes[start..i]));
348 try!(wr.write_str(escaped));
353 if start != bytes.len() {
354 try!(wr.write(bytes[start..]));
360 fn escape_str(writer: &mut io::Writer, v: &str) -> Result<(), io::IoError> {
361 escape_bytes(writer, v.as_bytes())
364 fn escape_char(writer: &mut io::Writer, v: char) -> Result<(), io::IoError> {
365 let mut buf = [0, .. 4];
366 v.encode_utf8(&mut buf);
367 escape_bytes(writer, &mut buf)
370 fn spaces(wr: &mut io::Writer, mut n: uint) -> Result<(), io::IoError> {
371 const LEN: uint = 16;
372 static BUF: [u8, ..LEN] = [b' ', ..LEN];
375 try!(wr.write(&BUF));
386 fn fmt_number_or_null(v: f64) -> string::String {
388 FPNaN | FPInfinite => string::String::from_str("null"),
389 _ if v.fract() != 0f64 => f64::to_str_digits(v, 6u),
390 _ => f64::to_str_digits(v, 6u) + ".0",
394 /// A structure for implementing serialization to JSON.
395 pub struct Encoder<'a> {
396 writer: &'a mut (io::Writer+'a),
399 impl<'a> Encoder<'a> {
400 /// Creates a new JSON encoder whose output will be written to the writer
402 pub fn new(writer: &'a mut io::Writer) -> Encoder<'a> {
403 Encoder { writer: writer }
406 /// Encode the specified struct into a json [u8]
407 pub fn buffer_encode<T:Encodable<Encoder<'a>, io::IoError>>(object: &T) -> Vec<u8> {
408 //Serialize the object in a string using a writer
409 let mut m = Vec::new();
410 // FIXME(14302) remove the transmute and unsafe block.
412 let mut encoder = Encoder::new(&mut m as &mut io::Writer);
413 // Vec<u8> never Errs
414 let _ = object.encode(transmute(&mut encoder));
420 impl<'a> ::Encoder<io::IoError> for Encoder<'a> {
421 fn emit_nil(&mut self) -> EncodeResult { write!(self.writer, "null") }
423 fn emit_uint(&mut self, v: uint) -> EncodeResult { write!(self.writer, "{}", v) }
424 fn emit_u64(&mut self, v: u64) -> EncodeResult { write!(self.writer, "{}", v) }
425 fn emit_u32(&mut self, v: u32) -> EncodeResult { write!(self.writer, "{}", v) }
426 fn emit_u16(&mut self, v: u16) -> EncodeResult { write!(self.writer, "{}", v) }
427 fn emit_u8(&mut self, v: u8) -> EncodeResult { write!(self.writer, "{}", v) }
429 fn emit_int(&mut self, v: int) -> EncodeResult { write!(self.writer, "{}", v) }
430 fn emit_i64(&mut self, v: i64) -> EncodeResult { write!(self.writer, "{}", v) }
431 fn emit_i32(&mut self, v: i32) -> EncodeResult { write!(self.writer, "{}", v) }
432 fn emit_i16(&mut self, v: i16) -> EncodeResult { write!(self.writer, "{}", v) }
433 fn emit_i8(&mut self, v: i8) -> EncodeResult { write!(self.writer, "{}", v) }
435 fn emit_bool(&mut self, v: bool) -> EncodeResult {
437 write!(self.writer, "true")
439 write!(self.writer, "false")
443 fn emit_f64(&mut self, v: f64) -> EncodeResult {
444 write!(self.writer, "{}", fmt_number_or_null(v))
446 fn emit_f32(&mut self, v: f32) -> EncodeResult {
447 self.emit_f64(v as f64)
450 fn emit_char(&mut self, v: char) -> EncodeResult {
451 escape_char(self.writer, v)
453 fn emit_str(&mut self, v: &str) -> EncodeResult {
454 escape_str(self.writer, v)
457 fn emit_enum(&mut self,
459 f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
463 fn emit_enum_variant(&mut self,
467 f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
468 // enums are encoded as strings or objects
470 // Kangaroo(34,"William") => {"variant": "Kangaroo", "fields": [34,"William"]}
472 escape_str(self.writer, name)
474 try!(write!(self.writer, "{{\"variant\":"));
475 try!(escape_str(self.writer, name));
476 try!(write!(self.writer, ",\"fields\":["));
478 write!(self.writer, "]}}")
482 fn emit_enum_variant_arg(&mut self,
484 f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
486 try!(write!(self.writer, ","));
491 fn emit_enum_struct_variant(&mut self,
495 f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
496 self.emit_enum_variant(name, id, cnt, f)
499 fn emit_enum_struct_variant_field(&mut self,
502 f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
503 self.emit_enum_variant_arg(idx, f)
506 fn emit_struct(&mut self,
509 f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
510 try!(write!(self.writer, "{{"));
512 write!(self.writer, "}}")
515 fn emit_struct_field(&mut self,
518 f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
519 if idx != 0 { try!(write!(self.writer, ",")); }
520 try!(escape_str(self.writer, name));
521 try!(write!(self.writer, ":"));
525 fn emit_tuple(&mut self, len: uint, f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
526 self.emit_seq(len, f)
528 fn emit_tuple_arg(&mut self,
530 f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
531 self.emit_seq_elt(idx, f)
534 fn emit_tuple_struct(&mut self,
537 f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
538 self.emit_seq(len, f)
540 fn emit_tuple_struct_arg(&mut self,
542 f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
543 self.emit_seq_elt(idx, f)
546 fn emit_option(&mut self, f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
549 fn emit_option_none(&mut self) -> EncodeResult { self.emit_nil() }
550 fn emit_option_some(&mut self, f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
554 fn emit_seq(&mut self, _len: uint, f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
555 try!(write!(self.writer, "["));
557 write!(self.writer, "]")
560 fn emit_seq_elt(&mut self, idx: uint, f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
562 try!(write!(self.writer, ","));
567 fn emit_map(&mut self, _len: uint, f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
568 try!(write!(self.writer, "{{"));
570 write!(self.writer, "}}")
573 fn emit_map_elt_key(&mut self,
575 f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
576 if idx != 0 { try!(write!(self.writer, ",")) }
577 // ref #12967, make sure to wrap a key in double quotes,
578 // in the event that its of a type that omits them (eg numbers)
579 let mut buf = Vec::new();
580 // FIXME(14302) remove the transmute and unsafe block.
582 let mut check_encoder = Encoder::new(&mut buf);
583 try!(f(transmute(&mut check_encoder)));
585 let out = str::from_utf8(buf[]).unwrap();
586 let needs_wrapping = out.char_at(0) != '"' && out.char_at_reverse(out.len()) != '"';
587 if needs_wrapping { try!(write!(self.writer, "\"")); }
589 if needs_wrapping { try!(write!(self.writer, "\"")); }
593 fn emit_map_elt_val(&mut self,
595 f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
596 try!(write!(self.writer, ":"));
601 /// Another encoder for JSON, but prints out human-readable JSON instead of
603 pub struct PrettyEncoder<'a> {
604 writer: &'a mut (io::Writer+'a),
609 impl<'a> PrettyEncoder<'a> {
610 /// Creates a new encoder whose output will be written to the specified writer
611 pub fn new<'a>(writer: &'a mut io::Writer) -> PrettyEncoder<'a> {
612 PrettyEncoder { writer: writer, curr_indent: 0, indent: 2, }
615 /// Set the number of spaces to indent for each level.
616 /// This is safe to set during encoding.
617 pub fn set_indent<'a>(&mut self, indent: uint) {
618 // self.indent very well could be 0 so we need to use checked division.
619 let level = self.curr_indent.checked_div(self.indent).unwrap_or(0);
620 self.indent = indent;
621 self.curr_indent = level * self.indent;
625 impl<'a> ::Encoder<io::IoError> for PrettyEncoder<'a> {
626 fn emit_nil(&mut self) -> EncodeResult { write!(self.writer, "null") }
628 fn emit_uint(&mut self, v: uint) -> EncodeResult { write!(self.writer, "{}", v) }
629 fn emit_u64(&mut self, v: u64) -> EncodeResult { write!(self.writer, "{}", v) }
630 fn emit_u32(&mut self, v: u32) -> EncodeResult { write!(self.writer, "{}", v) }
631 fn emit_u16(&mut self, v: u16) -> EncodeResult { write!(self.writer, "{}", v) }
632 fn emit_u8(&mut self, v: u8) -> EncodeResult { write!(self.writer, "{}", v) }
634 fn emit_int(&mut self, v: int) -> EncodeResult { write!(self.writer, "{}", v) }
635 fn emit_i64(&mut self, v: i64) -> EncodeResult { write!(self.writer, "{}", v) }
636 fn emit_i32(&mut self, v: i32) -> EncodeResult { write!(self.writer, "{}", v) }
637 fn emit_i16(&mut self, v: i16) -> EncodeResult { write!(self.writer, "{}", v) }
638 fn emit_i8(&mut self, v: i8) -> EncodeResult { write!(self.writer, "{}", v) }
640 fn emit_bool(&mut self, v: bool) -> EncodeResult {
642 write!(self.writer, "true")
644 write!(self.writer, "false")
648 fn emit_f64(&mut self, v: f64) -> EncodeResult {
649 write!(self.writer, "{}", fmt_number_or_null(v))
651 fn emit_f32(&mut self, v: f32) -> EncodeResult {
652 self.emit_f64(v as f64)
655 fn emit_char(&mut self, v: char) -> EncodeResult {
656 escape_char(self.writer, v)
658 fn emit_str(&mut self, v: &str) -> EncodeResult {
659 escape_str(self.writer, v)
662 fn emit_enum(&mut self,
664 f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
668 fn emit_enum_variant(&mut self,
672 f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
674 escape_str(self.writer, name)
676 try!(write!(self.writer, "{{\n"));
677 self.curr_indent += self.indent;
678 try!(spaces(self.writer, self.curr_indent));
679 try!(write!(self.writer, "\"variant\": "));
680 try!(escape_str(self.writer, name));
681 try!(write!(self.writer, ",\n"));
682 try!(spaces(self.writer, self.curr_indent));
683 try!(write!(self.writer, "\"fields\": [\n"));
684 self.curr_indent += self.indent;
686 self.curr_indent -= self.indent;
687 try!(write!(self.writer, "\n"));
688 try!(spaces(self.writer, self.curr_indent));
689 self.curr_indent -= self.indent;
690 try!(write!(self.writer, "]\n"));
691 try!(spaces(self.writer, self.curr_indent));
692 write!(self.writer, "}}")
696 fn emit_enum_variant_arg(&mut self,
698 f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
700 try!(write!(self.writer, ",\n"));
702 try!(spaces(self.writer, self.curr_indent));
706 fn emit_enum_struct_variant(&mut self,
710 f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
711 self.emit_enum_variant(name, id, cnt, f)
714 fn emit_enum_struct_variant_field(&mut self,
717 f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
718 self.emit_enum_variant_arg(idx, f)
722 fn emit_struct(&mut self,
725 f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
727 write!(self.writer, "{{}}")
729 try!(write!(self.writer, "{{"));
730 self.curr_indent += self.indent;
732 self.curr_indent -= self.indent;
733 try!(write!(self.writer, "\n"));
734 try!(spaces(self.writer, self.curr_indent));
735 write!(self.writer, "}}")
739 fn emit_struct_field(&mut self,
742 f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
744 try!(write!(self.writer, "\n"));
746 try!(write!(self.writer, ",\n"));
748 try!(spaces(self.writer, self.curr_indent));
749 try!(escape_str(self.writer, name));
750 try!(write!(self.writer, ": "));
754 fn emit_tuple(&mut self,
756 f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
757 self.emit_seq(len, f)
759 fn emit_tuple_arg(&mut self,
761 f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
762 self.emit_seq_elt(idx, f)
765 fn emit_tuple_struct(&mut self,
768 f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
769 self.emit_seq(len, f)
771 fn emit_tuple_struct_arg(&mut self,
773 f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
774 self.emit_seq_elt(idx, f)
777 fn emit_option(&mut self, f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
780 fn emit_option_none(&mut self) -> EncodeResult { self.emit_nil() }
781 fn emit_option_some(&mut self, f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
785 fn emit_seq(&mut self,
787 f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
789 write!(self.writer, "[]")
791 try!(write!(self.writer, "["));
792 self.curr_indent += self.indent;
794 self.curr_indent -= self.indent;
795 try!(write!(self.writer, "\n"));
796 try!(spaces(self.writer, self.curr_indent));
797 write!(self.writer, "]")
801 fn emit_seq_elt(&mut self,
803 f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
805 try!(write!(self.writer, "\n"));
807 try!(write!(self.writer, ",\n"));
809 try!(spaces(self.writer, self.curr_indent));
813 fn emit_map(&mut self,
815 f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
817 write!(self.writer, "{{}}")
819 try!(write!(self.writer, "{{"));
820 self.curr_indent += self.indent;
822 self.curr_indent -= self.indent;
823 try!(write!(self.writer, "\n"));
824 try!(spaces(self.writer, self.curr_indent));
825 write!(self.writer, "}}")
829 fn emit_map_elt_key(&mut self,
831 f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
833 try!(write!(self.writer, "\n"));
835 try!(write!(self.writer, ",\n"));
837 try!(spaces(self.writer, self.curr_indent));
838 // ref #12967, make sure to wrap a key in double quotes,
839 // in the event that its of a type that omits them (eg numbers)
840 let mut buf = Vec::new();
841 // FIXME(14302) remove the transmute and unsafe block.
843 let mut check_encoder = PrettyEncoder::new(&mut buf);
844 try!(f(transmute(&mut check_encoder)));
846 let out = str::from_utf8(buf[]).unwrap();
847 let needs_wrapping = out.char_at(0) != '"' && out.char_at_reverse(out.len()) != '"';
848 if needs_wrapping { try!(write!(self.writer, "\"")); }
850 if needs_wrapping { try!(write!(self.writer, "\"")); }
854 fn emit_map_elt_val(&mut self,
856 f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
857 try!(write!(self.writer, ": "));
862 impl<E: ::Encoder<S>, S> Encodable<E, S> for Json {
863 fn encode(&self, e: &mut E) -> Result<(), S> {
865 Json::I64(v) => v.encode(e),
866 Json::U64(v) => v.encode(e),
867 Json::F64(v) => v.encode(e),
868 Json::String(ref v) => v.encode(e),
869 Json::Boolean(v) => v.encode(e),
870 Json::Array(ref v) => v.encode(e),
871 Json::Object(ref v) => v.encode(e),
872 Json::Null => e.emit_nil(),
878 /// Encodes a json value into an io::writer. Uses a single line.
879 pub fn to_writer(&self, writer: &mut io::Writer) -> EncodeResult {
880 let mut encoder = Encoder::new(writer);
881 self.encode(&mut encoder)
884 /// Encodes a json value into an io::writer.
885 /// Pretty-prints in a more readable format.
886 pub fn to_pretty_writer(&self, writer: &mut io::Writer) -> EncodeResult {
887 let mut encoder = PrettyEncoder::new(writer);
888 self.encode(&mut encoder)
891 /// Encodes a json value into a string
892 pub fn to_pretty_str(&self) -> string::String {
893 let mut s = Vec::new();
894 self.to_pretty_writer(&mut s as &mut io::Writer).unwrap();
895 string::String::from_utf8(s).unwrap()
898 /// If the Json value is an Object, returns the value associated with the provided key.
899 /// Otherwise, returns None.
900 pub fn find<'a>(&'a self, key: &str) -> Option<&'a Json>{
902 &Json::Object(ref map) => map.get(key),
907 /// Attempts to get a nested Json Object for each key in `keys`.
908 /// If any key is found not to exist, find_path will return None.
909 /// Otherwise, it will return the Json value associated with the final key.
910 pub fn find_path<'a>(&'a self, keys: &[&str]) -> Option<&'a Json>{
911 let mut target = self;
912 for key in keys.iter() {
913 match target.find(*key) {
914 Some(t) => { target = t; },
921 /// If the Json value is an Object, performs a depth-first search until
922 /// a value associated with the provided key is found. If no value is found
923 /// or the Json value is not an Object, returns None.
924 pub fn search<'a>(&'a self, key: &str) -> Option<&'a Json> {
926 &Json::Object(ref map) => {
928 Some(json_value) => Some(json_value),
930 for (_, v) in map.iter() {
931 match v.search(key) {
932 x if x.is_some() => return x,
944 /// Returns true if the Json value is an Object. Returns false otherwise.
945 pub fn is_object<'a>(&'a self) -> bool {
946 self.as_object().is_some()
949 /// If the Json value is an Object, returns the associated TreeMap.
950 /// Returns None otherwise.
951 pub fn as_object<'a>(&'a self) -> Option<&'a Object> {
953 &Json::Object(ref map) => Some(map),
958 /// Returns true if the Json value is an Array. Returns false otherwise.
959 pub fn is_array<'a>(&'a self) -> bool {
960 self.as_array().is_some()
963 /// If the Json value is an Array, returns the associated vector.
964 /// Returns None otherwise.
965 pub fn as_array<'a>(&'a self) -> Option<&'a Array> {
967 &Json::Array(ref array) => Some(&*array),
972 /// Returns true if the Json value is a String. Returns false otherwise.
973 pub fn is_string<'a>(&'a self) -> bool {
974 self.as_string().is_some()
977 /// If the Json value is a String, returns the associated str.
978 /// Returns None otherwise.
979 pub fn as_string<'a>(&'a self) -> Option<&'a str> {
981 Json::String(ref s) => Some(s.as_slice()),
986 /// Returns true if the Json value is a Number. Returns false otherwise.
987 pub fn is_number(&self) -> bool {
989 Json::I64(_) | Json::U64(_) | Json::F64(_) => true,
994 /// Returns true if the Json value is a i64. Returns false otherwise.
995 pub fn is_i64(&self) -> bool {
997 Json::I64(_) => true,
1002 /// Returns true if the Json value is a u64. Returns false otherwise.
1003 pub fn is_u64(&self) -> bool {
1005 Json::U64(_) => true,
1010 /// Returns true if the Json value is a f64. Returns false otherwise.
1011 pub fn is_f64(&self) -> bool {
1013 Json::F64(_) => true,
1018 /// If the Json value is a number, return or cast it to a i64.
1019 /// Returns None otherwise.
1020 pub fn as_i64(&self) -> Option<i64> {
1022 Json::I64(n) => Some(n),
1023 Json::U64(n) => num::cast(n),
1028 /// If the Json value is a number, return or cast it to a u64.
1029 /// Returns None otherwise.
1030 pub fn as_u64(&self) -> Option<u64> {
1032 Json::I64(n) => num::cast(n),
1033 Json::U64(n) => Some(n),
1038 /// If the Json value is a number, return or cast it to a f64.
1039 /// Returns None otherwise.
1040 pub fn as_f64(&self) -> Option<f64> {
1042 Json::I64(n) => num::cast(n),
1043 Json::U64(n) => num::cast(n),
1044 Json::F64(n) => Some(n),
1049 /// Returns true if the Json value is a Boolean. Returns false otherwise.
1050 pub fn is_boolean(&self) -> bool {
1051 self.as_boolean().is_some()
1054 /// If the Json value is a Boolean, returns the associated bool.
1055 /// Returns None otherwise.
1056 pub fn as_boolean(&self) -> Option<bool> {
1058 &Json::Boolean(b) => Some(b),
1063 /// Returns true if the Json value is a Null. Returns false otherwise.
1064 pub fn is_null(&self) -> bool {
1065 self.as_null().is_some()
1068 /// If the Json value is a Null, returns ().
1069 /// Returns None otherwise.
1070 pub fn as_null(&self) -> Option<()> {
1072 &Json::Null => Some(()),
1078 impl<'a> ops::Index<&'a str, Json> for Json {
1079 fn index<'a>(&'a self, idx: & &str) -> &'a Json {
1080 self.find(*idx).unwrap()
1084 impl ops::Index<uint, Json> for Json {
1085 fn index<'a>(&'a self, idx: &uint) -> &'a Json {
1087 &Json::Array(ref v) => v.index(idx),
1088 _ => panic!("can only index Json with uint if it is an array")
1093 /// The output of the streaming parser.
1094 #[deriving(PartialEq, Clone, Show)]
1095 pub enum JsonEvent {
1104 StringValue(string::String),
1109 #[deriving(PartialEq, Show)]
1111 // Parse a value in an array, true means first element.
1113 // Parse ',' or ']' after an element in an array.
1115 // Parse a key:value in an object, true means first element.
1117 // Parse ',' or ']' after an element in an object.
1121 // Expecting the stream to end.
1123 // Parsing can't continue.
1127 /// A Stack represents the current position of the parser in the logical
1128 /// structure of the JSON stream.
1129 /// For example foo.bar[3].x
1131 stack: Vec<InternalStackElement>,
1132 str_buffer: Vec<u8>,
1135 /// StackElements compose a Stack.
1136 /// For example, Key("foo"), Key("bar"), Index(3) and Key("x") are the
1137 /// StackElements compositing the stack that represents foo.bar[3].x
1138 #[deriving(PartialEq, Clone, Show)]
1139 pub enum StackElement<'l> {
1144 // Internally, Key elements are stored as indices in a buffer to avoid
1145 // allocating a string for every member of an object.
1146 #[deriving(PartialEq, Clone, Show)]
1147 enum InternalStackElement {
1149 InternalKey(u16, u16), // start, size
1153 pub fn new() -> Stack {
1154 Stack { stack: Vec::new(), str_buffer: Vec::new() }
1157 /// Returns The number of elements in the Stack.
1158 pub fn len(&self) -> uint { self.stack.len() }
1160 /// Returns true if the stack is empty.
1161 pub fn is_empty(&self) -> bool { self.stack.is_empty() }
1163 /// Provides access to the StackElement at a given index.
1164 /// lower indices are at the bottom of the stack while higher indices are
1166 pub fn get<'l>(&'l self, idx: uint) -> StackElement<'l> {
1167 match self.stack[idx] {
1168 InternalIndex(i) => Index(i),
1169 InternalKey(start, size) => {
1171 self.str_buffer[start as uint .. start as uint + size as uint]).unwrap())
1176 /// Compares this stack with an array of StackElements.
1177 pub fn is_equal_to(&self, rhs: &[StackElement]) -> bool {
1178 if self.stack.len() != rhs.len() { return false; }
1179 for i in range(0, rhs.len()) {
1180 if self.get(i) != rhs[i] { return false; }
1185 /// Returns true if the bottom-most elements of this stack are the same as
1186 /// the ones passed as parameter.
1187 pub fn starts_with(&self, rhs: &[StackElement]) -> bool {
1188 if self.stack.len() < rhs.len() { return false; }
1189 for i in range(0, rhs.len()) {
1190 if self.get(i) != rhs[i] { return false; }
1195 /// Returns true if the top-most elements of this stack are the same as
1196 /// the ones passed as parameter.
1197 pub fn ends_with(&self, rhs: &[StackElement]) -> bool {
1198 if self.stack.len() < rhs.len() { return false; }
1199 let offset = self.stack.len() - rhs.len();
1200 for i in range(0, rhs.len()) {
1201 if self.get(i + offset) != rhs[i] { return false; }
1206 /// Returns the top-most element (if any).
1207 pub fn top<'l>(&'l self) -> Option<StackElement<'l>> {
1208 return match self.stack.last() {
1210 Some(&InternalIndex(i)) => Some(Index(i)),
1211 Some(&InternalKey(start, size)) => {
1212 Some(Key(str::from_utf8(
1213 self.str_buffer[start as uint .. (start+size) as uint]
1219 // Used by Parser to insert Key elements at the top of the stack.
1220 fn push_key(&mut self, key: string::String) {
1221 self.stack.push(InternalKey(self.str_buffer.len() as u16, key.len() as u16));
1222 for c in key.as_bytes().iter() {
1223 self.str_buffer.push(*c);
1227 // Used by Parser to insert Index elements at the top of the stack.
1228 fn push_index(&mut self, index: u32) {
1229 self.stack.push(InternalIndex(index));
1232 // Used by Parser to remove the top-most element of the stack.
1234 assert!(!self.is_empty());
1235 match *self.stack.last().unwrap() {
1236 InternalKey(_, sz) => {
1237 let new_size = self.str_buffer.len() - sz as uint;
1238 self.str_buffer.truncate(new_size);
1240 InternalIndex(_) => {}
1245 // Used by Parser to test whether the top-most element is an index.
1246 fn last_is_index(&self) -> bool {
1247 if self.is_empty() { return false; }
1248 return match *self.stack.last().unwrap() {
1249 InternalIndex(_) => true,
1254 // Used by Parser to increment the index of the top-most element.
1255 fn bump_index(&mut self) {
1256 let len = self.stack.len();
1257 let idx = match *self.stack.last().unwrap() {
1258 InternalIndex(i) => { i + 1 }
1261 self.stack[len - 1] = InternalIndex(idx);
1265 /// A streaming JSON parser implemented as an iterator of JsonEvent, consuming
1266 /// an iterator of char.
1267 pub struct Parser<T> {
1272 // We maintain a stack representing where we are in the logical structure
1273 // of the JSON stream.
1275 // A state machine is kept to make it possible to interrupt and resume parsing.
1279 impl<T: Iterator<char>> Iterator<JsonEvent> for Parser<T> {
1280 fn next(&mut self) -> Option<JsonEvent> {
1281 if self.state == ParseFinished {
1285 if self.state == ParseBeforeFinish {
1286 self.parse_whitespace();
1287 // Make sure there is no trailing characters.
1289 self.state = ParseFinished;
1292 return Some(self.error_event(TrailingCharacters));
1296 return Some(self.parse());
1300 impl<T: Iterator<char>> Parser<T> {
1301 /// Creates the JSON parser.
1302 pub fn new(rdr: T) -> Parser<T> {
1303 let mut p = Parser {
1308 stack: Stack::new(),
1315 /// Provides access to the current position in the logical structure of the
1317 pub fn stack<'l>(&'l self) -> &'l Stack {
1321 fn eof(&self) -> bool { self.ch.is_none() }
1322 fn ch_or_null(&self) -> char { self.ch.unwrap_or('\x00') }
1323 fn bump(&mut self) {
1324 self.ch = self.rdr.next();
1326 if self.ch_is('\n') {
1334 fn next_char(&mut self) -> Option<char> {
1338 fn ch_is(&self, c: char) -> bool {
1342 fn error<T>(&self, reason: ErrorCode) -> Result<T, ParserError> {
1343 Err(SyntaxError(reason, self.line, self.col))
1346 fn parse_whitespace(&mut self) {
1347 while self.ch_is(' ') ||
1350 self.ch_is('\r') { self.bump(); }
1353 fn parse_number(&mut self) -> JsonEvent {
1354 let mut neg = false;
1356 if self.ch_is('-') {
1361 let res = match self.parse_u64() {
1363 Err(e) => { return Error(e); }
1366 if self.ch_is('.') || self.ch_is('e') || self.ch_is('E') {
1367 let mut res = res as f64;
1369 if self.ch_is('.') {
1370 res = match self.parse_decimal(res) {
1372 Err(e) => { return Error(e); }
1376 if self.ch_is('e') || self.ch_is('E') {
1377 res = match self.parse_exponent(res) {
1379 Err(e) => { return Error(e); }
1390 let res = -(res as i64);
1392 // Make sure we didn't underflow.
1394 Error(SyntaxError(InvalidNumber, self.line, self.col))
1404 fn parse_u64(&mut self) -> Result<u64, ParserError> {
1406 let last_accum = 0; // necessary to detect overflow.
1408 match self.ch_or_null() {
1412 // A leading '0' must be the only digit before the decimal point.
1413 match self.ch_or_null() {
1414 '0' ... '9' => return self.error(InvalidNumber),
1420 match self.ch_or_null() {
1421 c @ '0' ... '9' => {
1423 accum += (c as u64) - ('0' as u64);
1425 // Detect overflow by comparing to the last value.
1426 if accum <= last_accum { return self.error(InvalidNumber); }
1434 _ => return self.error(InvalidNumber),
1440 fn parse_decimal(&mut self, mut res: f64) -> Result<f64, ParserError> {
1443 // Make sure a digit follows the decimal place.
1444 match self.ch_or_null() {
1446 _ => return self.error(InvalidNumber)
1451 match self.ch_or_null() {
1452 c @ '0' ... '9' => {
1454 res += (((c as int) - ('0' as int)) as f64) * dec;
1464 fn parse_exponent(&mut self, mut res: f64) -> Result<f64, ParserError> {
1468 let mut neg_exp = false;
1470 if self.ch_is('+') {
1472 } else if self.ch_is('-') {
1477 // Make sure a digit follows the exponent place.
1478 match self.ch_or_null() {
1480 _ => return self.error(InvalidNumber)
1483 match self.ch_or_null() {
1484 c @ '0' ... '9' => {
1486 exp += (c as uint) - ('0' as uint);
1494 let exp = 10_f64.powi(exp as i32);
1504 fn decode_hex_escape(&mut self) -> Result<u16, ParserError> {
1507 while i < 4 && !self.eof() {
1509 n = match self.ch_or_null() {
1510 c @ '0' ... '9' => n * 16 + ((c as u16) - ('0' as u16)),
1511 'a' | 'A' => n * 16 + 10,
1512 'b' | 'B' => n * 16 + 11,
1513 'c' | 'C' => n * 16 + 12,
1514 'd' | 'D' => n * 16 + 13,
1515 'e' | 'E' => n * 16 + 14,
1516 'f' | 'F' => n * 16 + 15,
1517 _ => return self.error(InvalidEscape)
1523 // Error out if we didn't parse 4 digits.
1525 return self.error(InvalidEscape);
1531 fn parse_str(&mut self) -> Result<string::String, ParserError> {
1532 let mut escape = false;
1533 let mut res = string::String::new();
1538 return self.error(EOFWhileParsingString);
1542 match self.ch_or_null() {
1543 '"' => res.push('"'),
1544 '\\' => res.push('\\'),
1545 '/' => res.push('/'),
1546 'b' => res.push('\x08'),
1547 'f' => res.push('\x0c'),
1548 'n' => res.push('\n'),
1549 'r' => res.push('\r'),
1550 't' => res.push('\t'),
1551 'u' => match try!(self.decode_hex_escape()) {
1552 0xDC00 ... 0xDFFF => {
1553 return self.error(LoneLeadingSurrogateInHexEscape)
1556 // Non-BMP characters are encoded as a sequence of
1557 // two hex escapes, representing UTF-16 surrogates.
1558 n1 @ 0xD800 ... 0xDBFF => {
1559 match (self.next_char(), self.next_char()) {
1560 (Some('\\'), Some('u')) => (),
1561 _ => return self.error(UnexpectedEndOfHexEscape),
1564 let buf = [n1, try!(self.decode_hex_escape())];
1565 match str::utf16_items(buf.as_slice()).next() {
1566 Some(ScalarValue(c)) => res.push(c),
1567 _ => return self.error(LoneLeadingSurrogateInHexEscape),
1571 n => match char::from_u32(n as u32) {
1572 Some(c) => res.push(c),
1573 None => return self.error(InvalidUnicodeCodePoint),
1576 _ => return self.error(InvalidEscape),
1579 } else if self.ch_is('\\') {
1587 Some(c) => res.push(c),
1588 None => unreachable!()
1594 // Invoked at each iteration, consumes the stream until it has enough
1595 // information to return a JsonEvent.
1596 // Manages an internal state so that parsing can be interrupted and resumed.
1597 // Also keeps track of the position in the logical structure of the json
1598 // stream int the form of a stack that can be queried by the user using the
1600 fn parse(&mut self) -> JsonEvent {
1602 // The only paths where the loop can spin a new iteration
1603 // are in the cases ParseArrayComma and ParseObjectComma if ','
1604 // is parsed. In these cases the state is set to (respectively)
1605 // ParseArray(false) and ParseObject(false), which always return,
1606 // so there is no risk of getting stuck in an infinite loop.
1607 // All other paths return before the end of the loop's iteration.
1608 self.parse_whitespace();
1612 return self.parse_start();
1614 ParseArray(first) => {
1615 return self.parse_array(first);
1617 ParseArrayComma => {
1618 match self.parse_array_comma_or_end() {
1619 Some(evt) => { return evt; }
1623 ParseObject(first) => {
1624 return self.parse_object(first);
1626 ParseObjectComma => {
1628 if self.ch_is(',') {
1629 self.state = ParseObject(false);
1632 return self.parse_object_end();
1636 return self.error_event(InvalidSyntax);
1642 fn parse_start(&mut self) -> JsonEvent {
1643 let val = self.parse_value();
1644 self.state = match val {
1645 Error(_) => ParseFinished,
1646 ArrayStart => ParseArray(true),
1647 ObjectStart => ParseObject(true),
1648 _ => ParseBeforeFinish,
1653 fn parse_array(&mut self, first: bool) -> JsonEvent {
1654 if self.ch_is(']') {
1656 self.error_event(InvalidSyntax)
1658 self.state = if self.stack.is_empty() {
1660 } else if self.stack.last_is_index() {
1670 self.stack.push_index(0);
1672 let val = self.parse_value();
1673 self.state = match val {
1674 Error(_) => ParseFinished,
1675 ArrayStart => ParseArray(true),
1676 ObjectStart => ParseObject(true),
1677 _ => ParseArrayComma,
1683 fn parse_array_comma_or_end(&mut self) -> Option<JsonEvent> {
1684 if self.ch_is(',') {
1685 self.stack.bump_index();
1686 self.state = ParseArray(false);
1689 } else if self.ch_is(']') {
1691 self.state = if self.stack.is_empty() {
1693 } else if self.stack.last_is_index() {
1700 } else if self.eof() {
1701 Some(self.error_event(EOFWhileParsingArray))
1703 Some(self.error_event(InvalidSyntax))
1707 fn parse_object(&mut self, first: bool) -> JsonEvent {
1708 if self.ch_is('}') {
1710 if self.stack.is_empty() {
1711 return self.error_event(TrailingComma);
1716 self.state = if self.stack.is_empty() {
1718 } else if self.stack.last_is_index() {
1727 return self.error_event(EOFWhileParsingObject);
1729 if !self.ch_is('"') {
1730 return self.error_event(KeyMustBeAString);
1732 let s = match self.parse_str() {
1735 self.state = ParseFinished;
1739 self.parse_whitespace();
1741 return self.error_event(EOFWhileParsingObject);
1742 } else if self.ch_or_null() != ':' {
1743 return self.error_event(ExpectedColon);
1745 self.stack.push_key(s);
1747 self.parse_whitespace();
1749 let val = self.parse_value();
1751 self.state = match val {
1752 Error(_) => ParseFinished,
1753 ArrayStart => ParseArray(true),
1754 ObjectStart => ParseObject(true),
1755 _ => ParseObjectComma,
1760 fn parse_object_end(&mut self) -> JsonEvent {
1761 if self.ch_is('}') {
1762 self.state = if self.stack.is_empty() {
1764 } else if self.stack.last_is_index() {
1771 } else if self.eof() {
1772 self.error_event(EOFWhileParsingObject)
1774 self.error_event(InvalidSyntax)
1778 fn parse_value(&mut self) -> JsonEvent {
1779 if self.eof() { return self.error_event(EOFWhileParsingValue); }
1780 match self.ch_or_null() {
1781 'n' => { self.parse_ident("ull", NullValue) }
1782 't' => { self.parse_ident("rue", BooleanValue(true)) }
1783 'f' => { self.parse_ident("alse", BooleanValue(false)) }
1784 '0' ... '9' | '-' => self.parse_number(),
1785 '"' => match self.parse_str() {
1786 Ok(s) => StringValue(s),
1797 _ => { self.error_event(InvalidSyntax) }
1801 fn parse_ident(&mut self, ident: &str, value: JsonEvent) -> JsonEvent {
1802 if ident.chars().all(|c| Some(c) == self.next_char()) {
1806 Error(SyntaxError(InvalidSyntax, self.line, self.col))
1810 fn error_event(&mut self, reason: ErrorCode) -> JsonEvent {
1811 self.state = ParseFinished;
1812 Error(SyntaxError(reason, self.line, self.col))
1816 /// A Builder consumes a json::Parser to create a generic Json structure.
1817 pub struct Builder<T> {
1819 token: Option<JsonEvent>,
1822 impl<T: Iterator<char>> Builder<T> {
1823 /// Create a JSON Builder.
1824 pub fn new(src: T) -> Builder<T> {
1825 Builder { parser: Parser::new(src), token: None, }
1828 // Decode a Json value from a Parser.
1829 pub fn build(&mut self) -> Result<Json, BuilderError> {
1831 let result = self.build_value();
1835 Some(Error(e)) => { return Err(e); }
1836 ref tok => { panic!("unexpected token {}", tok.clone()); }
1841 fn bump(&mut self) {
1842 self.token = self.parser.next();
1845 fn build_value(&mut self) -> Result<Json, BuilderError> {
1846 return match self.token {
1847 Some(NullValue) => Ok(Json::Null),
1848 Some(I64Value(n)) => Ok(Json::I64(n)),
1849 Some(U64Value(n)) => Ok(Json::U64(n)),
1850 Some(F64Value(n)) => Ok(Json::F64(n)),
1851 Some(BooleanValue(b)) => Ok(Json::Boolean(b)),
1852 Some(StringValue(ref mut s)) => {
1853 let mut temp = string::String::new();
1855 Ok(Json::String(temp))
1857 Some(Error(e)) => Err(e),
1858 Some(ArrayStart) => self.build_array(),
1859 Some(ObjectStart) => self.build_object(),
1860 Some(ObjectEnd) => self.parser.error(InvalidSyntax),
1861 Some(ArrayEnd) => self.parser.error(InvalidSyntax),
1862 None => self.parser.error(EOFWhileParsingValue),
1866 fn build_array(&mut self) -> Result<Json, BuilderError> {
1868 let mut values = Vec::new();
1871 if self.token == Some(ArrayEnd) {
1872 return Ok(Json::Array(values.into_iter().collect()));
1874 match self.build_value() {
1875 Ok(v) => values.push(v),
1876 Err(e) => { return Err(e) }
1882 fn build_object(&mut self) -> Result<Json, BuilderError> {
1885 let mut values = TreeMap::new();
1889 Some(ObjectEnd) => { return Ok(Json::Object(values)); }
1890 Some(Error(e)) => { return Err(e); }
1894 let key = match self.parser.stack().top() {
1895 Some(Key(k)) => { k.to_string() }
1896 _ => { panic!("invalid state"); }
1898 match self.build_value() {
1899 Ok(value) => { values.insert(key, value); }
1900 Err(e) => { return Err(e); }
1904 return self.parser.error(EOFWhileParsingObject);
1908 /// Decodes a json value from an `&mut io::Reader`
1909 pub fn from_reader(rdr: &mut io::Reader) -> Result<Json, BuilderError> {
1910 let contents = match rdr.read_to_end() {
1912 Err(e) => return Err(io_error_to_error(e))
1914 let s = match str::from_utf8(contents.as_slice()) {
1916 _ => return Err(SyntaxError(NotUtf8, 0, 0))
1918 let mut builder = Builder::new(s.chars());
1922 /// Decodes a json value from a string
1923 pub fn from_str(s: &str) -> Result<Json, BuilderError> {
1924 let mut builder = Builder::new(s.chars());
1928 /// A structure to decode JSON to values in rust.
1929 pub struct Decoder {
1934 /// Creates a new decoder instance for decoding the specified JSON value.
1935 pub fn new(json: Json) -> Decoder {
1936 Decoder { stack: vec![json] }
1941 fn pop(&mut self) -> Json {
1942 self.stack.pop().unwrap()
1946 macro_rules! expect(
1947 ($e:expr, Null) => ({
1949 Json::Null => Ok(()),
1950 other => Err(ExpectedError("Null".to_string(),
1951 format!("{}", other)))
1954 ($e:expr, $t:ident) => ({
1956 Json::$t(v) => Ok(v),
1958 Err(ExpectedError(stringify!($t).to_string(),
1959 format!("{}", other)))
1965 macro_rules! read_primitive {
1966 ($name:ident, $ty:ty) => {
1967 fn $name(&mut self) -> DecodeResult<$ty> {
1969 Json::I64(f) => match num::cast(f) {
1971 None => Err(ExpectedError("Number".to_string(), format!("{}", f))),
1973 Json::U64(f) => match num::cast(f) {
1975 None => Err(ExpectedError("Number".to_string(), format!("{}", f))),
1977 Json::F64(f) => Err(ExpectedError("Integer".to_string(), format!("{}", f))),
1978 // re: #12967.. a type w/ numeric keys (ie HashMap<uint, V> etc)
1979 // is going to have a string here, as per JSON spec.
1980 Json::String(s) => match std::str::from_str(s.as_slice()) {
1982 None => Err(ExpectedError("Number".to_string(), s)),
1984 value => Err(ExpectedError("Number".to_string(), format!("{}", value))),
1990 impl ::Decoder<DecoderError> for Decoder {
1991 fn read_nil(&mut self) -> DecodeResult<()> {
1993 expect!(self.pop(), Null)
1996 read_primitive!(read_uint, uint)
1997 read_primitive!(read_u8, u8)
1998 read_primitive!(read_u16, u16)
1999 read_primitive!(read_u32, u32)
2000 read_primitive!(read_u64, u64)
2001 read_primitive!(read_int, int)
2002 read_primitive!(read_i8, i8)
2003 read_primitive!(read_i16, i16)
2004 read_primitive!(read_i32, i32)
2005 read_primitive!(read_i64, i64)
2007 fn read_f32(&mut self) -> DecodeResult<f32> { self.read_f64().map(|x| x as f32) }
2009 fn read_f64(&mut self) -> DecodeResult<f64> {
2012 Json::I64(f) => Ok(f as f64),
2013 Json::U64(f) => Ok(f as f64),
2014 Json::F64(f) => Ok(f),
2015 Json::String(s) => {
2016 // re: #12967.. a type w/ numeric keys (ie HashMap<uint, V> etc)
2017 // is going to have a string here, as per JSON spec.
2018 match std::str::from_str(s.as_slice()) {
2020 None => Err(ExpectedError("Number".to_string(), s)),
2023 Json::Null => Ok(f64::NAN),
2024 value => Err(ExpectedError("Number".to_string(), format!("{}", value)))
2028 fn read_bool(&mut self) -> DecodeResult<bool> {
2029 debug!("read_bool");
2030 expect!(self.pop(), Boolean)
2033 fn read_char(&mut self) -> DecodeResult<char> {
2034 let s = try!(self.read_str());
2036 let mut it = s.chars();
2037 match (it.next(), it.next()) {
2038 // exactly one character
2039 (Some(c), None) => return Ok(c),
2043 Err(ExpectedError("single character string".to_string(), format!("{}", s)))
2046 fn read_str(&mut self) -> DecodeResult<string::String> {
2048 expect!(self.pop(), String)
2051 fn read_enum<T>(&mut self,
2053 f: |&mut Decoder| -> DecodeResult<T>) -> DecodeResult<T> {
2054 debug!("read_enum({})", name);
2058 fn read_enum_variant<T>(&mut self,
2060 f: |&mut Decoder, uint| -> DecodeResult<T>)
2061 -> DecodeResult<T> {
2062 debug!("read_enum_variant(names={})", names);
2063 let name = match self.pop() {
2064 Json::String(s) => s,
2065 Json::Object(mut o) => {
2066 let n = match o.remove(&"variant".to_string()) {
2067 Some(Json::String(s)) => s,
2069 return Err(ExpectedError("String".to_string(), format!("{}", val)))
2072 return Err(MissingFieldError("variant".to_string()))
2075 match o.remove(&"fields".to_string()) {
2076 Some(Json::Array(l)) => {
2077 for field in l.into_iter().rev() {
2078 self.stack.push(field);
2082 return Err(ExpectedError("Array".to_string(), format!("{}", val)))
2085 return Err(MissingFieldError("fields".to_string()))
2091 return Err(ExpectedError("String or Object".to_string(), format!("{}", json)))
2094 let idx = match names.iter()
2095 .position(|n| str::eq_slice(*n, name.as_slice())) {
2097 None => return Err(UnknownVariantError(name))
2102 fn read_enum_variant_arg<T>(&mut self, idx: uint, f: |&mut Decoder| -> DecodeResult<T>)
2103 -> DecodeResult<T> {
2104 debug!("read_enum_variant_arg(idx={})", idx);
2108 fn read_enum_struct_variant<T>(&mut self,
2110 f: |&mut Decoder, uint| -> DecodeResult<T>)
2111 -> DecodeResult<T> {
2112 debug!("read_enum_struct_variant(names={})", names);
2113 self.read_enum_variant(names, f)
2117 fn read_enum_struct_variant_field<T>(&mut self,
2120 f: |&mut Decoder| -> DecodeResult<T>)
2121 -> DecodeResult<T> {
2122 debug!("read_enum_struct_variant_field(name={}, idx={})", name, idx);
2123 self.read_enum_variant_arg(idx, f)
2126 fn read_struct<T>(&mut self,
2129 f: |&mut Decoder| -> DecodeResult<T>)
2130 -> DecodeResult<T> {
2131 debug!("read_struct(name={}, len={})", name, len);
2132 let value = try!(f(self));
2137 fn read_struct_field<T>(&mut self,
2140 f: |&mut Decoder| -> DecodeResult<T>)
2141 -> DecodeResult<T> {
2142 debug!("read_struct_field(name={}, idx={})", name, idx);
2143 let mut obj = try!(expect!(self.pop(), Object));
2145 let value = match obj.remove(&name.to_string()) {
2147 // Add a Null and try to parse it as an Option<_>
2148 // to get None as a default value.
2149 self.stack.push(Json::Null);
2152 Err(_) => return Err(MissingFieldError(name.to_string())),
2156 self.stack.push(json);
2160 self.stack.push(Json::Object(obj));
2164 fn read_tuple<T>(&mut self,
2166 f: |&mut Decoder| -> DecodeResult<T>)
2167 -> DecodeResult<T> {
2168 debug!("read_tuple()");
2169 self.read_seq(|d, len| {
2170 if len == tuple_len {
2173 Err(ExpectedError(format!("Tuple{}", tuple_len), format!("Tuple{}", len)))
2178 fn read_tuple_arg<T>(&mut self,
2180 f: |&mut Decoder| -> DecodeResult<T>) -> DecodeResult<T> {
2181 debug!("read_tuple_arg(idx={})", idx);
2182 self.read_seq_elt(idx, f)
2185 fn read_tuple_struct<T>(&mut self,
2188 f: |&mut Decoder| -> DecodeResult<T>)
2189 -> DecodeResult<T> {
2190 debug!("read_tuple_struct(name={})", name);
2191 self.read_tuple(len, f)
2194 fn read_tuple_struct_arg<T>(&mut self,
2196 f: |&mut Decoder| -> DecodeResult<T>)
2197 -> DecodeResult<T> {
2198 debug!("read_tuple_struct_arg(idx={})", idx);
2199 self.read_tuple_arg(idx, f)
2202 fn read_option<T>(&mut self, f: |&mut Decoder, bool| -> DecodeResult<T>) -> DecodeResult<T> {
2203 debug!("read_option()");
2205 Json::Null => f(self, false),
2206 value => { self.stack.push(value); f(self, true) }
2210 fn read_seq<T>(&mut self, f: |&mut Decoder, uint| -> DecodeResult<T>) -> DecodeResult<T> {
2211 debug!("read_seq()");
2212 let array = try!(expect!(self.pop(), Array));
2213 let len = array.len();
2214 for v in array.into_iter().rev() {
2220 fn read_seq_elt<T>(&mut self,
2222 f: |&mut Decoder| -> DecodeResult<T>) -> DecodeResult<T> {
2223 debug!("read_seq_elt(idx={})", idx);
2227 fn read_map<T>(&mut self, f: |&mut Decoder, uint| -> DecodeResult<T>) -> DecodeResult<T> {
2228 debug!("read_map()");
2229 let obj = try!(expect!(self.pop(), Object));
2230 let len = obj.len();
2231 for (key, value) in obj.into_iter() {
2232 self.stack.push(value);
2233 self.stack.push(Json::String(key));
2238 fn read_map_elt_key<T>(&mut self, idx: uint, f: |&mut Decoder| -> DecodeResult<T>)
2239 -> DecodeResult<T> {
2240 debug!("read_map_elt_key(idx={})", idx);
2244 fn read_map_elt_val<T>(&mut self, idx: uint, f: |&mut Decoder| -> DecodeResult<T>)
2245 -> DecodeResult<T> {
2246 debug!("read_map_elt_val(idx={})", idx);
2250 fn error(&mut self, err: &str) -> DecoderError {
2251 ApplicationError(err.to_string())
2255 /// A trait for converting values to JSON
2256 pub trait ToJson for Sized? {
2257 /// Converts the value of `self` to an instance of JSON
2258 fn to_json(&self) -> Json;
2261 macro_rules! to_json_impl_i64(
2263 $(impl ToJson for $t {
2264 fn to_json(&self) -> Json { Json::I64(*self as i64) }
2269 to_json_impl_i64!(int, i8, i16, i32, i64)
2271 macro_rules! to_json_impl_u64(
2273 $(impl ToJson for $t {
2274 fn to_json(&self) -> Json { Json::U64(*self as u64) }
2279 to_json_impl_u64!(uint, u8, u16, u32, u64)
2281 impl ToJson for Json {
2282 fn to_json(&self) -> Json { self.clone() }
2285 impl ToJson for f32 {
2286 fn to_json(&self) -> Json { (*self as f64).to_json() }
2289 impl ToJson for f64 {
2290 fn to_json(&self) -> Json {
2291 match self.classify() {
2292 FPNaN | FPInfinite => Json::Null,
2293 _ => Json::F64(*self)
2298 impl ToJson for () {
2299 fn to_json(&self) -> Json { Json::Null }
2302 impl ToJson for bool {
2303 fn to_json(&self) -> Json { Json::Boolean(*self) }
2306 impl ToJson for str {
2307 fn to_json(&self) -> Json { Json::String(self.into_string()) }
2310 impl ToJson for string::String {
2311 fn to_json(&self) -> Json { Json::String((*self).clone()) }
2314 macro_rules! tuple_impl {
2315 // use variables to indicate the arity of the tuple
2316 ($($tyvar:ident),* ) => {
2317 // the trailing commas are for the 1 tuple
2319 $( $tyvar : ToJson ),*
2320 > ToJson for ( $( $tyvar ),* , ) {
2323 #[allow(non_snake_case)]
2324 fn to_json(&self) -> Json {
2326 ($(ref $tyvar),*,) => Json::Array(vec![$($tyvar.to_json()),*])
2335 tuple_impl!{A, B, C}
2336 tuple_impl!{A, B, C, D}
2337 tuple_impl!{A, B, C, D, E}
2338 tuple_impl!{A, B, C, D, E, F}
2339 tuple_impl!{A, B, C, D, E, F, G}
2340 tuple_impl!{A, B, C, D, E, F, G, H}
2341 tuple_impl!{A, B, C, D, E, F, G, H, I}
2342 tuple_impl!{A, B, C, D, E, F, G, H, I, J}
2343 tuple_impl!{A, B, C, D, E, F, G, H, I, J, K}
2344 tuple_impl!{A, B, C, D, E, F, G, H, I, J, K, L}
2346 impl<A: ToJson> ToJson for [A] {
2347 fn to_json(&self) -> Json { Json::Array(self.iter().map(|elt| elt.to_json()).collect()) }
2350 impl<A: ToJson> ToJson for Vec<A> {
2351 fn to_json(&self) -> Json { Json::Array(self.iter().map(|elt| elt.to_json()).collect()) }
2354 impl<A: ToJson> ToJson for TreeMap<string::String, A> {
2355 fn to_json(&self) -> Json {
2356 let mut d = TreeMap::new();
2357 for (key, value) in self.iter() {
2358 d.insert((*key).clone(), value.to_json());
2364 impl<A: ToJson> ToJson for HashMap<string::String, A> {
2365 fn to_json(&self) -> Json {
2366 let mut d = TreeMap::new();
2367 for (key, value) in self.iter() {
2368 d.insert((*key).clone(), value.to_json());
2374 impl<A:ToJson> ToJson for Option<A> {
2375 fn to_json(&self) -> Json {
2378 Some(ref value) => value.to_json()
2383 impl fmt::Show for Json {
2384 /// Encodes a json value into a string
2385 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2386 self.to_writer(f).map_err(|_| fmt::Error)
2390 impl FromStr for Json {
2391 fn from_str(s: &str) -> Option<Json> {
2399 use self::Animal::*;
2400 use self::DecodeEnum::*;
2401 use self::test::Bencher;
2402 use {Encodable, Decodable};
2404 use super::ErrorCode::*;
2405 use super::ParserError::*;
2406 use super::DecoderError::*;
2407 use super::JsonEvent::*;
2408 use super::ParserState::*;
2409 use super::StackElement::*;
2410 use super::InternalStackElement::*;
2411 use super::{PrettyEncoder, Json, from_str, DecodeResult, DecoderError, JsonEvent, Parser,
2412 StackElement, Stack, Encoder, Decoder};
2413 use std::{i64, u64, f32, f64, io};
2414 use std::collections::TreeMap;
2415 use std::num::Float;
2418 #[deriving(Decodable, Eq, PartialEq, Show)]
2424 fn test_decode_option_none() {
2426 let obj: OptionData = super::decode(s).unwrap();
2427 assert_eq!(obj, OptionData { opt: None });
2431 fn test_decode_option_some() {
2432 let s = "{ \"opt\": 10 }";
2433 let obj: OptionData = super::decode(s).unwrap();
2434 assert_eq!(obj, OptionData { opt: Some(10u) });
2438 fn test_decode_option_malformed() {
2439 check_err::<OptionData>("{ \"opt\": [] }",
2440 ExpectedError("Number".to_string(), "[]".to_string()));
2441 check_err::<OptionData>("{ \"opt\": false }",
2442 ExpectedError("Number".to_string(), "false".to_string()));
2445 #[deriving(PartialEq, Encodable, Decodable, Show)]
2448 Frog(string::String, int)
2451 #[deriving(PartialEq, Encodable, Decodable, Show)]
2455 c: Vec<string::String>,
2458 #[deriving(PartialEq, Encodable, Decodable, Show)]
2463 fn mk_object(items: &[(string::String, Json)]) -> Json {
2464 let mut d = TreeMap::new();
2466 for item in items.iter() {
2468 (ref key, ref value) => { d.insert((*key).clone(), (*value).clone()); },
2476 fn test_from_str_trait() {
2478 assert!(::std::str::from_str::<Json>(s).unwrap() == from_str(s).unwrap());
2482 fn test_write_null() {
2483 assert_eq!(Null.to_string(), "null");
2484 assert_eq!(Null.to_pretty_str(), "null");
2488 fn test_write_i64() {
2489 assert_eq!(U64(0).to_string(), "0");
2490 assert_eq!(U64(0).to_pretty_str(), "0");
2492 assert_eq!(U64(1234).to_string(), "1234");
2493 assert_eq!(U64(1234).to_pretty_str(), "1234");
2495 assert_eq!(I64(-5678).to_string(), "-5678");
2496 assert_eq!(I64(-5678).to_pretty_str(), "-5678");
2498 assert_eq!(U64(7650007200025252000).to_string(), "7650007200025252000");
2499 assert_eq!(U64(7650007200025252000).to_pretty_str(), "7650007200025252000");
2503 fn test_write_f64() {
2504 assert_eq!(F64(3.0).to_string(), "3.0");
2505 assert_eq!(F64(3.0).to_pretty_str(), "3.0");
2507 assert_eq!(F64(3.1).to_string(), "3.1");
2508 assert_eq!(F64(3.1).to_pretty_str(), "3.1");
2510 assert_eq!(F64(-1.5).to_string(), "-1.5");
2511 assert_eq!(F64(-1.5).to_pretty_str(), "-1.5");
2513 assert_eq!(F64(0.5).to_string(), "0.5");
2514 assert_eq!(F64(0.5).to_pretty_str(), "0.5");
2516 assert_eq!(F64(f64::NAN).to_string(), "null");
2517 assert_eq!(F64(f64::NAN).to_pretty_str(), "null");
2519 assert_eq!(F64(f64::INFINITY).to_string(), "null");
2520 assert_eq!(F64(f64::INFINITY).to_pretty_str(), "null");
2522 assert_eq!(F64(f64::NEG_INFINITY).to_string(), "null");
2523 assert_eq!(F64(f64::NEG_INFINITY).to_pretty_str(), "null");
2527 fn test_write_str() {
2528 assert_eq!(String("".to_string()).to_string(), "\"\"");
2529 assert_eq!(String("".to_string()).to_pretty_str(), "\"\"");
2531 assert_eq!(String("homura".to_string()).to_string(), "\"homura\"");
2532 assert_eq!(String("madoka".to_string()).to_pretty_str(), "\"madoka\"");
2536 fn test_write_bool() {
2537 assert_eq!(Boolean(true).to_string(), "true");
2538 assert_eq!(Boolean(true).to_pretty_str(), "true");
2540 assert_eq!(Boolean(false).to_string(), "false");
2541 assert_eq!(Boolean(false).to_pretty_str(), "false");
2545 fn test_write_array() {
2546 assert_eq!(Array(vec![]).to_string(), "[]");
2547 assert_eq!(Array(vec![]).to_pretty_str(), "[]");
2549 assert_eq!(Array(vec![Boolean(true)]).to_string(), "[true]");
2551 Array(vec![Boolean(true)]).to_pretty_str(),
2558 let long_test_array = Array(vec![
2561 Array(vec![String("foo\nbar".to_string()), F64(3.5)])]);
2563 assert_eq!(long_test_array.to_string(),
2564 "[false,null,[\"foo\\nbar\",3.5]]");
2566 long_test_array.to_pretty_str(),
2580 fn test_write_object() {
2581 assert_eq!(mk_object(&[]).to_string(), "{}");
2582 assert_eq!(mk_object(&[]).to_pretty_str(), "{}");
2586 ("a".to_string(), Boolean(true))
2591 mk_object(&[("a".to_string(), Boolean(true))]).to_pretty_str(),
2598 let complex_obj = mk_object(&[
2599 ("b".to_string(), Array(vec![
2600 mk_object(&[("c".to_string(), String("\x0c\r".to_string()))]),
2601 mk_object(&[("d".to_string(), String("".to_string()))])
2606 complex_obj.to_string(),
2609 {\"c\":\"\\f\\r\"},\
2615 complex_obj.to_pretty_str(),
2620 \"c\": \"\\f\\r\"\n \
2629 let a = mk_object(&[
2630 ("a".to_string(), Boolean(true)),
2631 ("b".to_string(), Array(vec![
2632 mk_object(&[("c".to_string(), String("\x0c\r".to_string()))]),
2633 mk_object(&[("d".to_string(), String("".to_string()))])
2637 // We can't compare the strings directly because the object fields be
2638 // printed in a different order.
2639 assert_eq!(a.clone(), from_str(a.to_string().as_slice()).unwrap());
2640 assert_eq!(a.clone(),
2641 from_str(a.to_pretty_str().as_slice()).unwrap());
2644 fn with_str_writer(f: |&mut io::Writer|) -> string::String {
2647 let mut m = Vec::new();
2648 f(&mut m as &mut io::Writer);
2649 string::String::from_utf8(m).unwrap()
2653 fn test_write_enum() {
2656 with_str_writer(|writer| {
2657 let mut encoder = Encoder::new(writer);
2658 animal.encode(&mut encoder).unwrap();
2663 with_str_writer(|writer| {
2664 let mut encoder = PrettyEncoder::new(writer);
2665 animal.encode(&mut encoder).unwrap();
2670 let animal = Frog("Henry".to_string(), 349);
2672 with_str_writer(|writer| {
2673 let mut encoder = Encoder::new(writer);
2674 animal.encode(&mut encoder).unwrap();
2676 "{\"variant\":\"Frog\",\"fields\":[\"Henry\",349]}"
2679 with_str_writer(|writer| {
2680 let mut encoder = PrettyEncoder::new(writer);
2681 animal.encode(&mut encoder).unwrap();
2684 \"variant\": \"Frog\",\n \
2694 fn test_write_some() {
2695 let value = Some("jodhpurs".to_string());
2696 let s = with_str_writer(|writer| {
2697 let mut encoder = Encoder::new(writer);
2698 value.encode(&mut encoder).unwrap();
2700 assert_eq!(s, "\"jodhpurs\"");
2702 let value = Some("jodhpurs".to_string());
2703 let s = with_str_writer(|writer| {
2704 let mut encoder = PrettyEncoder::new(writer);
2705 value.encode(&mut encoder).unwrap();
2707 assert_eq!(s, "\"jodhpurs\"");
2711 fn test_write_none() {
2712 let value: Option<string::String> = None;
2713 let s = with_str_writer(|writer| {
2714 let mut encoder = Encoder::new(writer);
2715 value.encode(&mut encoder).unwrap();
2717 assert_eq!(s, "null");
2719 let s = with_str_writer(|writer| {
2720 let mut encoder = Encoder::new(writer);
2721 value.encode(&mut encoder).unwrap();
2723 assert_eq!(s, "null");
2727 fn test_trailing_characters() {
2728 assert_eq!(from_str("nulla"), Err(SyntaxError(TrailingCharacters, 1, 5)));
2729 assert_eq!(from_str("truea"), Err(SyntaxError(TrailingCharacters, 1, 5)));
2730 assert_eq!(from_str("falsea"), Err(SyntaxError(TrailingCharacters, 1, 6)));
2731 assert_eq!(from_str("1a"), Err(SyntaxError(TrailingCharacters, 1, 2)));
2732 assert_eq!(from_str("[]a"), Err(SyntaxError(TrailingCharacters, 1, 3)));
2733 assert_eq!(from_str("{}a"), Err(SyntaxError(TrailingCharacters, 1, 3)));
2737 fn test_read_identifiers() {
2738 assert_eq!(from_str("n"), Err(SyntaxError(InvalidSyntax, 1, 2)));
2739 assert_eq!(from_str("nul"), Err(SyntaxError(InvalidSyntax, 1, 4)));
2740 assert_eq!(from_str("t"), Err(SyntaxError(InvalidSyntax, 1, 2)));
2741 assert_eq!(from_str("truz"), Err(SyntaxError(InvalidSyntax, 1, 4)));
2742 assert_eq!(from_str("f"), Err(SyntaxError(InvalidSyntax, 1, 2)));
2743 assert_eq!(from_str("faz"), Err(SyntaxError(InvalidSyntax, 1, 3)));
2745 assert_eq!(from_str("null"), Ok(Null));
2746 assert_eq!(from_str("true"), Ok(Boolean(true)));
2747 assert_eq!(from_str("false"), Ok(Boolean(false)));
2748 assert_eq!(from_str(" null "), Ok(Null));
2749 assert_eq!(from_str(" true "), Ok(Boolean(true)));
2750 assert_eq!(from_str(" false "), Ok(Boolean(false)));
2754 fn test_decode_identifiers() {
2755 let v: () = super::decode("null").unwrap();
2758 let v: bool = super::decode("true").unwrap();
2759 assert_eq!(v, true);
2761 let v: bool = super::decode("false").unwrap();
2762 assert_eq!(v, false);
2766 fn test_read_number() {
2767 assert_eq!(from_str("+"), Err(SyntaxError(InvalidSyntax, 1, 1)));
2768 assert_eq!(from_str("."), Err(SyntaxError(InvalidSyntax, 1, 1)));
2769 assert_eq!(from_str("NaN"), Err(SyntaxError(InvalidSyntax, 1, 1)));
2770 assert_eq!(from_str("-"), Err(SyntaxError(InvalidNumber, 1, 2)));
2771 assert_eq!(from_str("00"), Err(SyntaxError(InvalidNumber, 1, 2)));
2772 assert_eq!(from_str("1."), Err(SyntaxError(InvalidNumber, 1, 3)));
2773 assert_eq!(from_str("1e"), Err(SyntaxError(InvalidNumber, 1, 3)));
2774 assert_eq!(from_str("1e+"), Err(SyntaxError(InvalidNumber, 1, 4)));
2776 assert_eq!(from_str("18446744073709551616"), Err(SyntaxError(InvalidNumber, 1, 20)));
2777 assert_eq!(from_str("-9223372036854775809"), Err(SyntaxError(InvalidNumber, 1, 21)));
2779 assert_eq!(from_str("3"), Ok(U64(3)));
2780 assert_eq!(from_str("3.1"), Ok(F64(3.1)));
2781 assert_eq!(from_str("-1.2"), Ok(F64(-1.2)));
2782 assert_eq!(from_str("0.4"), Ok(F64(0.4)));
2783 assert_eq!(from_str("0.4e5"), Ok(F64(0.4e5)));
2784 assert_eq!(from_str("0.4e+15"), Ok(F64(0.4e15)));
2785 assert_eq!(from_str("0.4e-01"), Ok(F64(0.4e-01)));
2786 assert_eq!(from_str(" 3 "), Ok(U64(3)));
2788 assert_eq!(from_str("-9223372036854775808"), Ok(I64(i64::MIN)));
2789 assert_eq!(from_str("9223372036854775807"), Ok(U64(i64::MAX as u64)));
2790 assert_eq!(from_str("18446744073709551615"), Ok(U64(u64::MAX)));
2794 fn test_decode_numbers() {
2795 let v: f64 = super::decode("3").unwrap();
2798 let v: f64 = super::decode("3.1").unwrap();
2801 let v: f64 = super::decode("-1.2").unwrap();
2802 assert_eq!(v, -1.2);
2804 let v: f64 = super::decode("0.4").unwrap();
2807 let v: f64 = super::decode("0.4e5").unwrap();
2808 assert_eq!(v, 0.4e5);
2810 let v: f64 = super::decode("0.4e15").unwrap();
2811 assert_eq!(v, 0.4e15);
2813 let v: f64 = super::decode("0.4e-01").unwrap();
2814 assert_eq!(v, 0.4e-01);
2816 let v: u64 = super::decode("0").unwrap();
2819 let v: u64 = super::decode("18446744073709551615").unwrap();
2820 assert_eq!(v, u64::MAX);
2822 let v: i64 = super::decode("-9223372036854775808").unwrap();
2823 assert_eq!(v, i64::MIN);
2825 let v: i64 = super::decode("9223372036854775807").unwrap();
2826 assert_eq!(v, i64::MAX);
2828 let res: DecodeResult<i64> = super::decode("765.25252");
2829 assert_eq!(res, Err(ExpectedError("Integer".into_string(), "765.25252".into_string())));
2833 fn test_read_str() {
2834 assert_eq!(from_str("\""), Err(SyntaxError(EOFWhileParsingString, 1, 2)));
2835 assert_eq!(from_str("\"lol"), Err(SyntaxError(EOFWhileParsingString, 1, 5)));
2837 assert_eq!(from_str("\"\""), Ok(String("".to_string())));
2838 assert_eq!(from_str("\"foo\""), Ok(String("foo".to_string())));
2839 assert_eq!(from_str("\"\\\"\""), Ok(String("\"".to_string())));
2840 assert_eq!(from_str("\"\\b\""), Ok(String("\x08".to_string())));
2841 assert_eq!(from_str("\"\\n\""), Ok(String("\n".to_string())));
2842 assert_eq!(from_str("\"\\r\""), Ok(String("\r".to_string())));
2843 assert_eq!(from_str("\"\\t\""), Ok(String("\t".to_string())));
2844 assert_eq!(from_str(" \"foo\" "), Ok(String("foo".to_string())));
2845 assert_eq!(from_str("\"\\u12ab\""), Ok(String("\u12ab".to_string())));
2846 assert_eq!(from_str("\"\\uAB12\""), Ok(String("\uAB12".to_string())));
2850 fn test_decode_str() {
2851 let s = [("\"\"", ""),
2854 ("\"\\b\"", "\x08"),
2858 ("\"\\u12ab\"", "\u12ab"),
2859 ("\"\\uAB12\"", "\uAB12")];
2861 for &(i, o) in s.iter() {
2862 let v: string::String = super::decode(i).unwrap();
2868 fn test_read_array() {
2869 assert_eq!(from_str("["), Err(SyntaxError(EOFWhileParsingValue, 1, 2)));
2870 assert_eq!(from_str("[1"), Err(SyntaxError(EOFWhileParsingArray, 1, 3)));
2871 assert_eq!(from_str("[1,"), Err(SyntaxError(EOFWhileParsingValue, 1, 4)));
2872 assert_eq!(from_str("[1,]"), Err(SyntaxError(InvalidSyntax, 1, 4)));
2873 assert_eq!(from_str("[6 7]"), Err(SyntaxError(InvalidSyntax, 1, 4)));
2875 assert_eq!(from_str("[]"), Ok(Array(vec![])));
2876 assert_eq!(from_str("[ ]"), Ok(Array(vec![])));
2877 assert_eq!(from_str("[true]"), Ok(Array(vec![Boolean(true)])));
2878 assert_eq!(from_str("[ false ]"), Ok(Array(vec![Boolean(false)])));
2879 assert_eq!(from_str("[null]"), Ok(Array(vec![Null])));
2880 assert_eq!(from_str("[3, 1]"),
2881 Ok(Array(vec![U64(3), U64(1)])));
2882 assert_eq!(from_str("\n[3, 2]\n"),
2883 Ok(Array(vec![U64(3), U64(2)])));
2884 assert_eq!(from_str("[2, [4, 1]]"),
2885 Ok(Array(vec![U64(2), Array(vec![U64(4), U64(1)])])));
2889 fn test_decode_array() {
2890 let v: Vec<()> = super::decode("[]").unwrap();
2891 assert_eq!(v, vec![]);
2893 let v: Vec<()> = super::decode("[null]").unwrap();
2894 assert_eq!(v, vec![()]);
2896 let v: Vec<bool> = super::decode("[true]").unwrap();
2897 assert_eq!(v, vec![true]);
2899 let v: Vec<int> = super::decode("[3, 1]").unwrap();
2900 assert_eq!(v, vec![3, 1]);
2902 let v: Vec<Vec<uint>> = super::decode("[[3], [1, 2]]").unwrap();
2903 assert_eq!(v, vec![vec![3], vec![1, 2]]);
2907 fn test_decode_tuple() {
2908 let t: (uint, uint, uint) = super::decode("[1, 2, 3]").unwrap();
2909 assert_eq!(t, (1u, 2, 3))
2911 let t: (uint, string::String) = super::decode("[1, \"two\"]").unwrap();
2912 assert_eq!(t, (1u, "two".to_string()));
2916 fn test_decode_tuple_malformed_types() {
2917 assert!(super::decode::<(uint, string::String)>("[1, 2]").is_err());
2921 fn test_decode_tuple_malformed_length() {
2922 assert!(super::decode::<(uint, uint)>("[1, 2, 3]").is_err());
2926 fn test_read_object() {
2927 assert_eq!(from_str("{"), Err(SyntaxError(EOFWhileParsingObject, 1, 2)));
2928 assert_eq!(from_str("{ "), Err(SyntaxError(EOFWhileParsingObject, 1, 3)));
2929 assert_eq!(from_str("{1"), Err(SyntaxError(KeyMustBeAString, 1, 2)));
2930 assert_eq!(from_str("{ \"a\""), Err(SyntaxError(EOFWhileParsingObject, 1, 6)));
2931 assert_eq!(from_str("{\"a\""), Err(SyntaxError(EOFWhileParsingObject, 1, 5)));
2932 assert_eq!(from_str("{\"a\" "), Err(SyntaxError(EOFWhileParsingObject, 1, 6)));
2934 assert_eq!(from_str("{\"a\" 1"), Err(SyntaxError(ExpectedColon, 1, 6)));
2935 assert_eq!(from_str("{\"a\":"), Err(SyntaxError(EOFWhileParsingValue, 1, 6)));
2936 assert_eq!(from_str("{\"a\":1"), Err(SyntaxError(EOFWhileParsingObject, 1, 7)));
2937 assert_eq!(from_str("{\"a\":1 1"), Err(SyntaxError(InvalidSyntax, 1, 8)));
2938 assert_eq!(from_str("{\"a\":1,"), Err(SyntaxError(EOFWhileParsingObject, 1, 8)));
2940 assert_eq!(from_str("{}").unwrap(), mk_object(&[]));
2941 assert_eq!(from_str("{\"a\": 3}").unwrap(),
2942 mk_object(&[("a".to_string(), U64(3))]));
2944 assert_eq!(from_str(
2945 "{ \"a\": null, \"b\" : true }").unwrap(),
2947 ("a".to_string(), Null),
2948 ("b".to_string(), Boolean(true))]));
2949 assert_eq!(from_str("\n{ \"a\": null, \"b\" : true }\n").unwrap(),
2951 ("a".to_string(), Null),
2952 ("b".to_string(), Boolean(true))]));
2953 assert_eq!(from_str(
2954 "{\"a\" : 1.0 ,\"b\": [ true ]}").unwrap(),
2956 ("a".to_string(), F64(1.0)),
2957 ("b".to_string(), Array(vec![Boolean(true)]))
2959 assert_eq!(from_str(
2965 { \"c\": {\"d\": null} } \
2969 ("a".to_string(), F64(1.0)),
2970 ("b".to_string(), Array(vec![
2972 String("foo\nbar".to_string()),
2974 ("c".to_string(), mk_object(&[("d".to_string(), Null)]))
2981 fn test_decode_struct() {
2984 { \"a\": null, \"b\": 2, \"c\": [\"abc\", \"xyz\"] }
2988 let v: Outer = super::decode(s).unwrap();
2993 Inner { a: (), b: 2, c: vec!["abc".to_string(), "xyz".to_string()] }
2999 #[deriving(Decodable)]
3000 struct FloatStruct {
3005 fn test_decode_struct_with_nan() {
3006 let s = "{\"f\":null,\"a\":[null,123]}";
3007 let obj: FloatStruct = super::decode(s).unwrap();
3008 assert!(obj.f.is_nan());
3009 assert!(obj.a[0].is_nan());
3010 assert_eq!(obj.a[1], 123f64);
3014 fn test_decode_option() {
3015 let value: Option<string::String> = super::decode("null").unwrap();
3016 assert_eq!(value, None);
3018 let value: Option<string::String> = super::decode("\"jodhpurs\"").unwrap();
3019 assert_eq!(value, Some("jodhpurs".to_string()));
3023 fn test_decode_enum() {
3024 let value: Animal = super::decode("\"Dog\"").unwrap();
3025 assert_eq!(value, Dog);
3027 let s = "{\"variant\":\"Frog\",\"fields\":[\"Henry\",349]}";
3028 let value: Animal = super::decode(s).unwrap();
3029 assert_eq!(value, Frog("Henry".to_string(), 349));
3033 fn test_decode_map() {
3034 let s = "{\"a\": \"Dog\", \"b\": {\"variant\":\"Frog\",\
3035 \"fields\":[\"Henry\", 349]}}";
3036 let mut map: TreeMap<string::String, Animal> = super::decode(s).unwrap();
3038 assert_eq!(map.remove(&"a".to_string()), Some(Dog));
3039 assert_eq!(map.remove(&"b".to_string()), Some(Frog("Henry".to_string(), 349)));
3043 fn test_multiline_errors() {
3044 assert_eq!(from_str("{\n \"foo\":\n \"bar\""),
3045 Err(SyntaxError(EOFWhileParsingObject, 3u, 8u)));
3048 #[deriving(Decodable)]
3050 struct DecodeStruct {
3054 w: Vec<DecodeStruct>
3056 #[deriving(Decodable)]
3061 fn check_err<T: Decodable<Decoder, DecoderError>>(to_parse: &'static str,
3062 expected: DecoderError) {
3063 let res: DecodeResult<T> = match from_str(to_parse) {
3064 Err(e) => Err(ParseError(e)),
3065 Ok(json) => Decodable::decode(&mut Decoder::new(json))
3068 Ok(_) => panic!("`{}` parsed & decoded ok, expecting error `{}`",
3069 to_parse, expected),
3070 Err(ParseError(e)) => panic!("`{}` is not valid json: {}",
3073 assert_eq!(e, expected);
3078 fn test_decode_errors_struct() {
3079 check_err::<DecodeStruct>("[]", ExpectedError("Object".to_string(), "[]".to_string()));
3080 check_err::<DecodeStruct>("{\"x\": true, \"y\": true, \"z\": \"\", \"w\": []}",
3081 ExpectedError("Number".to_string(), "true".to_string()));
3082 check_err::<DecodeStruct>("{\"x\": 1, \"y\": [], \"z\": \"\", \"w\": []}",
3083 ExpectedError("Boolean".to_string(), "[]".to_string()));
3084 check_err::<DecodeStruct>("{\"x\": 1, \"y\": true, \"z\": {}, \"w\": []}",
3085 ExpectedError("String".to_string(), "{}".to_string()));
3086 check_err::<DecodeStruct>("{\"x\": 1, \"y\": true, \"z\": \"\", \"w\": null}",
3087 ExpectedError("Array".to_string(), "null".to_string()));
3088 check_err::<DecodeStruct>("{\"x\": 1, \"y\": true, \"z\": \"\"}",
3089 MissingFieldError("w".to_string()));
3092 fn test_decode_errors_enum() {
3093 check_err::<DecodeEnum>("{}",
3094 MissingFieldError("variant".to_string()));
3095 check_err::<DecodeEnum>("{\"variant\": 1}",
3096 ExpectedError("String".to_string(), "1".to_string()));
3097 check_err::<DecodeEnum>("{\"variant\": \"A\"}",
3098 MissingFieldError("fields".to_string()));
3099 check_err::<DecodeEnum>("{\"variant\": \"A\", \"fields\": null}",
3100 ExpectedError("Array".to_string(), "null".to_string()));
3101 check_err::<DecodeEnum>("{\"variant\": \"C\", \"fields\": []}",
3102 UnknownVariantError("C".to_string()));
3107 let json_value = from_str("{\"dog\" : \"cat\"}").unwrap();
3108 let found_str = json_value.find("dog");
3109 assert!(found_str.unwrap().as_string().unwrap() == "cat");
3113 fn test_find_path(){
3114 let json_value = from_str("{\"dog\":{\"cat\": {\"mouse\" : \"cheese\"}}}").unwrap();
3115 let found_str = json_value.find_path(&["dog", "cat", "mouse"]);
3116 assert!(found_str.unwrap().as_string().unwrap() == "cheese");
3121 let json_value = from_str("{\"dog\":{\"cat\": {\"mouse\" : \"cheese\"}}}").unwrap();
3122 let found_str = json_value.search("mouse").and_then(|j| j.as_string());
3123 assert!(found_str.unwrap() == "cheese");
3128 let json_value = from_str("{\"animals\":[\"dog\",\"cat\",\"mouse\"]}").unwrap();
3129 let ref array = json_value["animals"];
3130 assert_eq!(array[0].as_string().unwrap(), "dog");
3131 assert_eq!(array[1].as_string().unwrap(), "cat");
3132 assert_eq!(array[2].as_string().unwrap(), "mouse");
3136 fn test_is_object(){
3137 let json_value = from_str("{}").unwrap();
3138 assert!(json_value.is_object());
3142 fn test_as_object(){
3143 let json_value = from_str("{}").unwrap();
3144 let json_object = json_value.as_object();
3145 assert!(json_object.is_some());
3150 let json_value = from_str("[1, 2, 3]").unwrap();
3151 assert!(json_value.is_array());
3156 let json_value = from_str("[1, 2, 3]").unwrap();
3157 let json_array = json_value.as_array();
3158 let expected_length = 3;
3159 assert!(json_array.is_some() && json_array.unwrap().len() == expected_length);
3163 fn test_is_string(){
3164 let json_value = from_str("\"dog\"").unwrap();
3165 assert!(json_value.is_string());
3169 fn test_as_string(){
3170 let json_value = from_str("\"dog\"").unwrap();
3171 let json_str = json_value.as_string();
3172 let expected_str = "dog";
3173 assert_eq!(json_str, Some(expected_str));
3177 fn test_is_number(){
3178 let json_value = from_str("12").unwrap();
3179 assert!(json_value.is_number());
3184 let json_value = from_str("-12").unwrap();
3185 assert!(json_value.is_i64());
3187 let json_value = from_str("12").unwrap();
3188 assert!(!json_value.is_i64());
3190 let json_value = from_str("12.0").unwrap();
3191 assert!(!json_value.is_i64());
3196 let json_value = from_str("12").unwrap();
3197 assert!(json_value.is_u64());
3199 let json_value = from_str("-12").unwrap();
3200 assert!(!json_value.is_u64());
3202 let json_value = from_str("12.0").unwrap();
3203 assert!(!json_value.is_u64());
3208 let json_value = from_str("12").unwrap();
3209 assert!(!json_value.is_f64());
3211 let json_value = from_str("-12").unwrap();
3212 assert!(!json_value.is_f64());
3214 let json_value = from_str("12.0").unwrap();
3215 assert!(json_value.is_f64());
3217 let json_value = from_str("-12.0").unwrap();
3218 assert!(json_value.is_f64());
3223 let json_value = from_str("-12").unwrap();
3224 let json_num = json_value.as_i64();
3225 assert_eq!(json_num, Some(-12));
3230 let json_value = from_str("12").unwrap();
3231 let json_num = json_value.as_u64();
3232 assert_eq!(json_num, Some(12));
3237 let json_value = from_str("12.0").unwrap();
3238 let json_num = json_value.as_f64();
3239 assert_eq!(json_num, Some(12f64));
3243 fn test_is_boolean(){
3244 let json_value = from_str("false").unwrap();
3245 assert!(json_value.is_boolean());
3249 fn test_as_boolean(){
3250 let json_value = from_str("false").unwrap();
3251 let json_bool = json_value.as_boolean();
3252 let expected_bool = false;
3253 assert!(json_bool.is_some() && json_bool.unwrap() == expected_bool);
3258 let json_value = from_str("null").unwrap();
3259 assert!(json_value.is_null());
3264 let json_value = from_str("null").unwrap();
3265 let json_null = json_value.as_null();
3266 let expected_null = ();
3267 assert!(json_null.is_some() && json_null.unwrap() == expected_null);
3271 fn test_encode_hashmap_with_numeric_key() {
3272 use std::str::from_utf8;
3273 use std::io::Writer;
3274 use std::collections::HashMap;
3275 let mut hm: HashMap<uint, bool> = HashMap::new();
3277 let mut mem_buf = Vec::new();
3279 let mut encoder = Encoder::new(&mut mem_buf as &mut io::Writer);
3280 hm.encode(&mut encoder).unwrap();
3282 let json_str = from_utf8(mem_buf[]).unwrap();
3283 match from_str(json_str) {
3284 Err(_) => panic!("Unable to parse json_str: {}", json_str),
3285 _ => {} // it parsed and we are good to go
3290 fn test_prettyencode_hashmap_with_numeric_key() {
3291 use std::str::from_utf8;
3292 use std::io::Writer;
3293 use std::collections::HashMap;
3294 let mut hm: HashMap<uint, bool> = HashMap::new();
3296 let mut mem_buf = Vec::new();
3298 let mut encoder = PrettyEncoder::new(&mut mem_buf as &mut io::Writer);
3299 hm.encode(&mut encoder).unwrap()
3301 let json_str = from_utf8(mem_buf[]).unwrap();
3302 match from_str(json_str) {
3303 Err(_) => panic!("Unable to parse json_str: {}", json_str),
3304 _ => {} // it parsed and we are good to go
3309 fn test_prettyencoder_indent_level_param() {
3310 use std::str::from_utf8;
3311 use std::collections::TreeMap;
3313 let mut tree = TreeMap::new();
3315 tree.insert("hello".into_string(), String("guten tag".into_string()));
3316 tree.insert("goodbye".into_string(), String("sayonara".into_string()));
3319 // The following layout below should look a lot like
3320 // the pretty-printed JSON (indent * x)
3323 String("greetings".into_string()), // 1x
3324 Object(tree), // 1x + 2x + 2x + 1x
3326 // End JSON array (7 lines)
3329 // Helper function for counting indents
3330 fn indents(source: &str) -> uint {
3331 let trimmed = source.trim_left_chars(' ');
3332 source.len() - trimmed.len()
3335 // Test up to 4 spaces of indents (more?)
3336 for i in range(0, 4u) {
3337 let mut writer = Vec::new();
3339 let ref mut encoder = PrettyEncoder::new(&mut writer);
3340 encoder.set_indent(i);
3341 json.encode(encoder).unwrap();
3344 let printed = from_utf8(writer[]).unwrap();
3346 // Check for indents at each line
3347 let lines: Vec<&str> = printed.lines().collect();
3348 assert_eq!(lines.len(), 7); // JSON should be 7 lines
3350 assert_eq!(indents(lines[0]), 0 * i); // [
3351 assert_eq!(indents(lines[1]), 1 * i); // "greetings",
3352 assert_eq!(indents(lines[2]), 1 * i); // {
3353 assert_eq!(indents(lines[3]), 2 * i); // "hello": "guten tag",
3354 assert_eq!(indents(lines[4]), 2 * i); // "goodbye": "sayonara"
3355 assert_eq!(indents(lines[5]), 1 * i); // },
3356 assert_eq!(indents(lines[6]), 0 * i); // ]
3358 // Finally, test that the pretty-printed JSON is valid
3359 from_str(printed).ok().expect("Pretty-printed JSON is invalid!");
3364 fn test_hashmap_with_numeric_key_can_handle_double_quote_delimited_key() {
3365 use std::collections::HashMap;
3367 let json_str = "{\"1\":true}";
3368 let json_obj = match from_str(json_str) {
3369 Err(_) => panic!("Unable to parse json_str: {}", json_str),
3372 let mut decoder = Decoder::new(json_obj);
3373 let _hm: HashMap<uint, bool> = Decodable::decode(&mut decoder).unwrap();
3377 fn test_hashmap_with_numeric_key_will_error_with_string_keys() {
3378 use std::collections::HashMap;
3380 let json_str = "{\"a\":true}";
3381 let json_obj = match from_str(json_str) {
3382 Err(_) => panic!("Unable to parse json_str: {}", json_str),
3385 let mut decoder = Decoder::new(json_obj);
3386 let result: Result<HashMap<uint, bool>, DecoderError> = Decodable::decode(&mut decoder);
3387 assert_eq!(result, Err(ExpectedError("Number".to_string(), "a".to_string())));
3390 fn assert_stream_equal(src: &str,
3391 expected: Vec<(JsonEvent, Vec<StackElement>)>) {
3392 let mut parser = Parser::new(src.chars());
3395 let evt = match parser.next() {
3399 let (ref expected_evt, ref expected_stack) = expected[i];
3400 if !parser.stack().is_equal_to(expected_stack.as_slice()) {
3401 panic!("Parser stack is not equal to {}", expected_stack);
3403 assert_eq!(&evt, expected_evt);
3408 #[cfg_attr(target_word_size = "32", ignore)] // FIXME(#14064)
3409 fn test_streaming_parser() {
3410 assert_stream_equal(
3411 r#"{ "foo":"bar", "array" : [0, 1, 2, 3, 4, 5], "idents":[null,true,false]}"#,
3413 (ObjectStart, vec![]),
3414 (StringValue("bar".to_string()), vec![Key("foo")]),
3415 (ArrayStart, vec![Key("array")]),
3416 (U64Value(0), vec![Key("array"), Index(0)]),
3417 (U64Value(1), vec![Key("array"), Index(1)]),
3418 (U64Value(2), vec![Key("array"), Index(2)]),
3419 (U64Value(3), vec![Key("array"), Index(3)]),
3420 (U64Value(4), vec![Key("array"), Index(4)]),
3421 (U64Value(5), vec![Key("array"), Index(5)]),
3422 (ArrayEnd, vec![Key("array")]),
3423 (ArrayStart, vec![Key("idents")]),
3424 (NullValue, vec![Key("idents"), Index(0)]),
3425 (BooleanValue(true), vec![Key("idents"), Index(1)]),
3426 (BooleanValue(false), vec![Key("idents"), Index(2)]),
3427 (ArrayEnd, vec![Key("idents")]),
3428 (ObjectEnd, vec![]),
3432 fn last_event(src: &str) -> JsonEvent {
3433 let mut parser = Parser::new(src.chars());
3434 let mut evt = NullValue;
3436 evt = match parser.next() {
3444 #[cfg_attr(target_word_size = "32", ignore)] // FIXME(#14064)
3445 fn test_read_object_streaming() {
3446 assert_eq!(last_event("{ "), Error(SyntaxError(EOFWhileParsingObject, 1, 3)));
3447 assert_eq!(last_event("{1"), Error(SyntaxError(KeyMustBeAString, 1, 2)));
3448 assert_eq!(last_event("{ \"a\""), Error(SyntaxError(EOFWhileParsingObject, 1, 6)));
3449 assert_eq!(last_event("{\"a\""), Error(SyntaxError(EOFWhileParsingObject, 1, 5)));
3450 assert_eq!(last_event("{\"a\" "), Error(SyntaxError(EOFWhileParsingObject, 1, 6)));
3452 assert_eq!(last_event("{\"a\" 1"), Error(SyntaxError(ExpectedColon, 1, 6)));
3453 assert_eq!(last_event("{\"a\":"), Error(SyntaxError(EOFWhileParsingValue, 1, 6)));
3454 assert_eq!(last_event("{\"a\":1"), Error(SyntaxError(EOFWhileParsingObject, 1, 7)));
3455 assert_eq!(last_event("{\"a\":1 1"), Error(SyntaxError(InvalidSyntax, 1, 8)));
3456 assert_eq!(last_event("{\"a\":1,"), Error(SyntaxError(EOFWhileParsingObject, 1, 8)));
3457 assert_eq!(last_event("{\"a\":1,}"), Error(SyntaxError(TrailingComma, 1, 8)));
3459 assert_stream_equal(
3461 vec![(ObjectStart, vec![]), (ObjectEnd, vec![])]
3463 assert_stream_equal(
3466 (ObjectStart, vec![]),
3467 (U64Value(3), vec![Key("a")]),
3468 (ObjectEnd, vec![]),
3471 assert_stream_equal(
3472 "{ \"a\": null, \"b\" : true }",
3474 (ObjectStart, vec![]),
3475 (NullValue, vec![Key("a")]),
3476 (BooleanValue(true), vec![Key("b")]),
3477 (ObjectEnd, vec![]),
3480 assert_stream_equal(
3481 "{\"a\" : 1.0 ,\"b\": [ true ]}",
3483 (ObjectStart, vec![]),
3484 (F64Value(1.0), vec![Key("a")]),
3485 (ArrayStart, vec![Key("b")]),
3486 (BooleanValue(true),vec![Key("b"), Index(0)]),
3487 (ArrayEnd, vec![Key("b")]),
3488 (ObjectEnd, vec![]),
3491 assert_stream_equal(
3497 { "c": {"d": null} }
3501 (ObjectStart, vec![]),
3502 (F64Value(1.0), vec![Key("a")]),
3503 (ArrayStart, vec![Key("b")]),
3504 (BooleanValue(true), vec![Key("b"), Index(0)]),
3505 (StringValue("foo\nbar".to_string()), vec![Key("b"), Index(1)]),
3506 (ObjectStart, vec![Key("b"), Index(2)]),
3507 (ObjectStart, vec![Key("b"), Index(2), Key("c")]),
3508 (NullValue, vec![Key("b"), Index(2), Key("c"), Key("d")]),
3509 (ObjectEnd, vec![Key("b"), Index(2), Key("c")]),
3510 (ObjectEnd, vec![Key("b"), Index(2)]),
3511 (ArrayEnd, vec![Key("b")]),
3512 (ObjectEnd, vec![]),
3517 #[cfg_attr(target_word_size = "32", ignore)] // FIXME(#14064)
3518 fn test_read_array_streaming() {
3519 assert_stream_equal(
3522 (ArrayStart, vec![]),
3526 assert_stream_equal(
3529 (ArrayStart, vec![]),
3533 assert_stream_equal(
3536 (ArrayStart, vec![]),
3537 (BooleanValue(true), vec![Index(0)]),
3541 assert_stream_equal(
3544 (ArrayStart, vec![]),
3545 (BooleanValue(false), vec![Index(0)]),
3549 assert_stream_equal(
3552 (ArrayStart, vec![]),
3553 (NullValue, vec![Index(0)]),
3557 assert_stream_equal(
3560 (ArrayStart, vec![]),
3561 (U64Value(3), vec![Index(0)]),
3562 (U64Value(1), vec![Index(1)]),
3566 assert_stream_equal(
3569 (ArrayStart, vec![]),
3570 (U64Value(3), vec![Index(0)]),
3571 (U64Value(2), vec![Index(1)]),
3575 assert_stream_equal(
3578 (ArrayStart, vec![]),
3579 (U64Value(2), vec![Index(0)]),
3580 (ArrayStart, vec![Index(1)]),
3581 (U64Value(4), vec![Index(1), Index(0)]),
3582 (U64Value(1), vec![Index(1), Index(1)]),
3583 (ArrayEnd, vec![Index(1)]),
3588 assert_eq!(last_event("["), Error(SyntaxError(EOFWhileParsingValue, 1, 2)));
3590 assert_eq!(from_str("["), Err(SyntaxError(EOFWhileParsingValue, 1, 2)));
3591 assert_eq!(from_str("[1"), Err(SyntaxError(EOFWhileParsingArray, 1, 3)));
3592 assert_eq!(from_str("[1,"), Err(SyntaxError(EOFWhileParsingValue, 1, 4)));
3593 assert_eq!(from_str("[1,]"), Err(SyntaxError(InvalidSyntax, 1, 4)));
3594 assert_eq!(from_str("[6 7]"), Err(SyntaxError(InvalidSyntax, 1, 4)));
3598 fn test_trailing_characters_streaming() {
3599 assert_eq!(last_event("nulla"), Error(SyntaxError(TrailingCharacters, 1, 5)));
3600 assert_eq!(last_event("truea"), Error(SyntaxError(TrailingCharacters, 1, 5)));
3601 assert_eq!(last_event("falsea"), Error(SyntaxError(TrailingCharacters, 1, 6)));
3602 assert_eq!(last_event("1a"), Error(SyntaxError(TrailingCharacters, 1, 2)));
3603 assert_eq!(last_event("[]a"), Error(SyntaxError(TrailingCharacters, 1, 3)));
3604 assert_eq!(last_event("{}a"), Error(SyntaxError(TrailingCharacters, 1, 3)));
3607 fn test_read_identifiers_streaming() {
3608 assert_eq!(Parser::new("null".chars()).next(), Some(NullValue));
3609 assert_eq!(Parser::new("true".chars()).next(), Some(BooleanValue(true)));
3610 assert_eq!(Parser::new("false".chars()).next(), Some(BooleanValue(false)));
3612 assert_eq!(last_event("n"), Error(SyntaxError(InvalidSyntax, 1, 2)));
3613 assert_eq!(last_event("nul"), Error(SyntaxError(InvalidSyntax, 1, 4)));
3614 assert_eq!(last_event("t"), Error(SyntaxError(InvalidSyntax, 1, 2)));
3615 assert_eq!(last_event("truz"), Error(SyntaxError(InvalidSyntax, 1, 4)));
3616 assert_eq!(last_event("f"), Error(SyntaxError(InvalidSyntax, 1, 2)));
3617 assert_eq!(last_event("faz"), Error(SyntaxError(InvalidSyntax, 1, 3)));
3622 let mut stack = Stack::new();
3624 assert!(stack.is_empty());
3625 assert!(stack.len() == 0);
3626 assert!(!stack.last_is_index());
3628 stack.push_index(0);
3631 assert!(stack.len() == 1);
3632 assert!(stack.is_equal_to(&[Index(1)]));
3633 assert!(stack.starts_with(&[Index(1)]));
3634 assert!(stack.ends_with(&[Index(1)]));
3635 assert!(stack.last_is_index());
3636 assert!(stack.get(0) == Index(1));
3638 stack.push_key("foo".to_string());
3640 assert!(stack.len() == 2);
3641 assert!(stack.is_equal_to(&[Index(1), Key("foo")]));
3642 assert!(stack.starts_with(&[Index(1), Key("foo")]));
3643 assert!(stack.starts_with(&[Index(1)]));
3644 assert!(stack.ends_with(&[Index(1), Key("foo")]));
3645 assert!(stack.ends_with(&[Key("foo")]));
3646 assert!(!stack.last_is_index());
3647 assert!(stack.get(0) == Index(1));
3648 assert!(stack.get(1) == Key("foo"));
3650 stack.push_key("bar".to_string());
3652 assert!(stack.len() == 3);
3653 assert!(stack.is_equal_to(&[Index(1), Key("foo"), Key("bar")]));
3654 assert!(stack.starts_with(&[Index(1)]));
3655 assert!(stack.starts_with(&[Index(1), Key("foo")]));
3656 assert!(stack.starts_with(&[Index(1), Key("foo"), Key("bar")]));
3657 assert!(stack.ends_with(&[Key("bar")]));
3658 assert!(stack.ends_with(&[Key("foo"), Key("bar")]));
3659 assert!(stack.ends_with(&[Index(1), Key("foo"), Key("bar")]));
3660 assert!(!stack.last_is_index());
3661 assert!(stack.get(0) == Index(1));
3662 assert!(stack.get(1) == Key("foo"));
3663 assert!(stack.get(2) == Key("bar"));
3667 assert!(stack.len() == 2);
3668 assert!(stack.is_equal_to(&[Index(1), Key("foo")]));
3669 assert!(stack.starts_with(&[Index(1), Key("foo")]));
3670 assert!(stack.starts_with(&[Index(1)]));
3671 assert!(stack.ends_with(&[Index(1), Key("foo")]));
3672 assert!(stack.ends_with(&[Key("foo")]));
3673 assert!(!stack.last_is_index());
3674 assert!(stack.get(0) == Index(1));
3675 assert!(stack.get(1) == Key("foo"));
3680 use std::collections::{HashMap,TreeMap};
3683 let array2 = Array(vec!(U64(1), U64(2)));
3684 let array3 = Array(vec!(U64(1), U64(2), U64(3)));
3686 let mut tree_map = TreeMap::new();
3687 tree_map.insert("a".to_string(), U64(1));
3688 tree_map.insert("b".to_string(), U64(2));
3692 assert_eq!(array2.to_json(), array2);
3693 assert_eq!(object.to_json(), object);
3694 assert_eq!(3_i.to_json(), I64(3));
3695 assert_eq!(4_i8.to_json(), I64(4));
3696 assert_eq!(5_i16.to_json(), I64(5));
3697 assert_eq!(6_i32.to_json(), I64(6));
3698 assert_eq!(7_i64.to_json(), I64(7));
3699 assert_eq!(8_u.to_json(), U64(8));
3700 assert_eq!(9_u8.to_json(), U64(9));
3701 assert_eq!(10_u16.to_json(), U64(10));
3702 assert_eq!(11_u32.to_json(), U64(11));
3703 assert_eq!(12_u64.to_json(), U64(12));
3704 assert_eq!(13.0_f32.to_json(), F64(13.0_f64));
3705 assert_eq!(14.0_f64.to_json(), F64(14.0_f64));
3706 assert_eq!(().to_json(), Null);
3707 assert_eq!(f32::INFINITY.to_json(), Null);
3708 assert_eq!(f64::NAN.to_json(), Null);
3709 assert_eq!(true.to_json(), Boolean(true));
3710 assert_eq!(false.to_json(), Boolean(false));
3711 assert_eq!("abc".to_json(), String("abc".into_string()));
3712 assert_eq!("abc".into_string().to_json(), String("abc".into_string()));
3713 assert_eq!((1u, 2u).to_json(), array2);
3714 assert_eq!((1u, 2u, 3u).to_json(), array3);
3715 assert_eq!([1u, 2].to_json(), array2);
3716 assert_eq!((&[1u, 2, 3]).to_json(), array3);
3717 assert_eq!((vec![1u, 2]).to_json(), array2);
3718 assert_eq!(vec!(1u, 2, 3).to_json(), array3);
3719 let mut tree_map = TreeMap::new();
3720 tree_map.insert("a".to_string(), 1u);
3721 tree_map.insert("b".to_string(), 2);
3722 assert_eq!(tree_map.to_json(), object);
3723 let mut hash_map = HashMap::new();
3724 hash_map.insert("a".to_string(), 1u);
3725 hash_map.insert("b".to_string(), 2);
3726 assert_eq!(hash_map.to_json(), object);
3727 assert_eq!(Some(15i).to_json(), I64(15));
3728 assert_eq!(Some(15u).to_json(), U64(15));
3729 assert_eq!(None::<int>.to_json(), Null);
3733 fn bench_streaming_small(b: &mut Bencher) {
3735 let mut parser = Parser::new(
3741 { "c": {"d": null} }
3746 match parser.next() {
3754 fn bench_small(b: &mut Bencher) {
3756 let _ = from_str(r#"{
3761 { "c": {"d": null} }
3767 fn big_json() -> string::String {
3768 let mut src = "[\n".to_string();
3769 for _ in range(0i, 500) {
3770 src.push_str(r#"{ "a": true, "b": null, "c":3.1415, "d": "Hello world", "e": \
3773 src.push_str("{}]");
3778 fn bench_streaming_large(b: &mut Bencher) {
3779 let src = big_json();
3781 let mut parser = Parser::new(src.chars());
3783 match parser.next() {
3791 fn bench_large(b: &mut Bencher) {
3792 let src = big_json();
3793 b.iter( || { let _ = from_str(src.as_slice()); });