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