json/
decoder.rs

1//! JSON ([RFC 7159](http://tools.ietf.org/html/rfc7159))
2//! decoder implementation.
3//!
4//! The decoder supports direct decoding into Rust types (providing
5//! helper macros such as `object!`) as well as generic decoding
6//! using an intermediate representation.
7//!
8//! # Example 1: Generic decoding
9//!
10//! ```
11//! use json::{Decoder, Json};
12//! use json::ast::Ref;
13//!
14//! let json = r#"
15//! { "field1": true,
16//!   "field2": { "nested": [42, 73] }
17//! }"#;
18//!
19//! let mut d = Decoder::default(json.chars());
20//! let     v = d.decode().unwrap();
21//! let     r = Ref::new(&v);
22//! assert_eq!(true, r.get("field1").bool().unwrap());
23//! assert_eq!(73f64, r.get("field2").get("nested").at(1).number().unwrap());
24//!
25//! ```
26//! # Example 2: Direct decoding using macros
27//!
28//! ```
29//! #
30//! #[macro_use] extern crate json;
31//! # fn main() {
32//!
33//! use json::Decoder;
34//!
35//! const JSON: &'static str =
36//! r#"
37//! {
38//!     "Width":  800,
39//!     "Height": 600,
40//!     "Title":  "View from 15th Floor",
41//!     "Thumbnail": {
42//!         "Url":    "http://www.example.com/image/481989943",
43//!         "Height": 125,
44//!         "Width":  100
45//!     },
46//!     "Animated" : false,
47//!     "IDs": [116, 943, 234, 38793]
48//! }
49//! "#;
50//!
51//! struct Image {
52//!     width:     usize,
53//!     height:    usize,
54//!     title:     String,
55//!     thumbnail: Thumbnail,
56//!     animated:  bool,
57//!     ids:       Vec<u32>,
58//!     geo:       Option<(f64, f64)>
59//! }
60//!
61//! struct Thumbnail {
62//!     url:    String,
63//!     height: u16,
64//!     width:  u16
65//! }
66//!
67//! let mut d = Decoder::default(JSON.chars());
68//! let image = object! {
69//!     let decoder = d;
70//!     Image {
71//!         width:     req. "Width"     => d.usize(),
72//!         height:    req. "Height"    => d.usize(),
73//!         title:     req. "Title"     => d.string(),
74//!         thumbnail: req. "Thumbnail" => object! {
75//!             let decoder = d;
76//!             Thumbnail {
77//!                 url:    req. "Url"    => d.string(),
78//!                 height: req. "Height" => d.u16(),
79//!                 width:  req. "Width"  => d.u16()
80//!             }
81//!         },
82//!         animated:  req. "Animated" => d.bool(),
83//!         ids:       req. "IDs"      => array!(d, d.u32()),
84//!         geo:       opt. "Geo"      => d.optional(|d| {
85//!             let lat = d.f64()?;
86//!             let lon = d.f64()?;
87//!             Ok((lat, lon))
88//!         })
89//!     }
90//! };
91//! assert!(image.is_ok());
92//! # }
93//! ```
94
95use std::borrow::Cow;
96use std::char;
97use std::collections::HashMap;
98use std::error::Error;
99use std::f64;
100use std::fmt;
101use std::io::Read;
102use std::marker::PhantomData;
103use std::str;
104use std::{i8, i16, i32, i64, isize};
105use std::{u8, u16, u32, u64, usize};
106
107use ast::Json;
108use buffer::{Buffer, Utf8Buffer};
109use stack::{Scope, Stack};
110use utf8;
111pub use utf8::ReadError;
112
113// FromJson trait ///////////////////////////////////////////////////////////
114
115pub trait FromJson {
116    fn decode<I: Iterator<Item=char>>(d: &mut Decoder<I>) -> DecodeResult<Self>
117        where Self: Sized;
118}
119
120macro_rules! instance {
121    ($name: ident) => {
122        impl FromJson for $name {
123            fn decode<I: Iterator<Item=char>>(d: &mut Decoder<I>) -> DecodeResult<Self> {
124                d.$name()
125            }
126        }
127    }
128}
129
130instance!(bool);
131instance!(u8);
132instance!(u16);
133instance!(u32);
134instance!(u64);
135instance!(usize);
136instance!(i8);
137instance!(i16);
138instance!(i32);
139instance!(i64);
140instance!(isize);
141instance!(f64);
142
143impl FromJson for String {
144    fn decode<I: Iterator<Item=char>>(d: &mut Decoder<I>) -> DecodeResult<Self> {
145        d.string()
146    }
147}
148
149impl FromJson for Json {
150    fn decode<I: Iterator<Item=char>>(d: &mut Decoder<I>) -> DecodeResult<Self> {
151        d.decode()
152    }
153}
154
155impl<T: FromJson> FromJson for Option<T> {
156    fn decode<I: Iterator<Item=char>>(d: &mut Decoder<I>) -> DecodeResult<Self> {
157        d.optional(FromJson::decode)
158    }
159}
160
161impl<'a, T: FromJson + Clone> FromJson for Cow<'a, T> {
162    fn decode<I: Iterator<Item=char>>(d: &mut Decoder<I>) -> DecodeResult<Self> {
163        Ok(Cow::Owned(FromJson::decode(d)?))
164    }
165}
166
167impl<T: FromJson> FromJson for Vec<T> {
168    fn decode<I: Iterator<Item=char>>(d: &mut Decoder<I>) -> DecodeResult<Self> {
169        d.array()?;
170        let mut v = Vec::new();
171        while d.has_more()? {
172            let x = d.from_json()?;
173            v.push(x)
174        }
175        Ok(v)
176    }
177}
178
179// Decoder //////////////////////////////////////////////////////////////////
180
181/// JSON decoder over `char` iterators.
182pub struct Decoder<I: Iterator> {
183    chars:  Source<I>,
184    config: Config,
185    buffer: [u8; 512],
186    stack:  Stack
187}
188
189#[derive(Clone, Debug, PartialEq, Eq)]
190/// Decoder configuration.
191pub struct Config {
192    /// Maximum recursion steps when decoding generic `Json`
193    pub max_nesting: usize
194}
195
196const DEFAULT_CONFIG: Config = Config { max_nesting: 16 };
197
198impl Config {
199    /// Create default configuration with
200    /// - `max_nesting` = 16
201    pub fn default() -> Config { DEFAULT_CONFIG }
202}
203
204// Macros ///////////////////////////////////////////////////////////////////
205
206macro_rules! require {
207    ($e: expr) => {
208        match $e {
209            Some(c) => c,
210            None    => return Err(DecodeError::EndOfInput)
211        }
212    }
213}
214
215macro_rules! integral {
216    ($name: ident, $ty: ty, false) => {
217        pub fn $name(&mut self) -> DecodeResult<$ty> {
218            self.skip_whitespace();
219            let digit =
220                require!(self.chars.next())
221                    .to_digit(10)
222                    .ok_or(DecodeError::Expected("digit"))?;
223            let mut dec = digit as $ty;
224            while let Some(c) = self.chars.next() {
225                match c.to_digit(10) {
226                    Some(n) => {
227                        if dec > ($name::MAX - n as $ty) / 10 {
228                            return Err(DecodeError::IntOverflow)
229                        }
230                        dec = dec * 10 + n as $ty;
231                    }
232                    None => {
233                        self.chars.put_back(c);
234                        break
235                    }
236                }
237            }
238            Ok(dec)
239        }
240    };
241    ($name: ident, $ty: ty, true) => {
242        pub fn $name(&mut self) -> DecodeResult<$ty> {
243            self.skip_whitespace();
244            let is_neg =
245                match self.chars.peek() {
246                    Some('-') => {
247                        self.chars.next();
248                        true
249                    }
250                    _ => false
251                };
252            let digit =
253                require!(self.chars.next())
254                    .to_digit(10)
255                    .ok_or(DecodeError::Expected("digit"))?;
256            let mut dec = -(digit as $ty);
257            while let Some(c) = self.chars.next() {
258                match c.to_digit(10) {
259                    Some(n) => {
260                        if dec < ($name::MIN + n as $ty) / 10 {
261                            return Err(DecodeError::IntOverflow)
262                        }
263                        dec = dec * 10 - n as $ty;
264                    }
265                    None => {
266                        self.chars.put_back(c);
267                        break
268                    }
269                }
270            }
271            Ok(if is_neg {dec} else {-dec})
272        }
273    }
274}
275
276impl<I: Iterator<Item=char>> Decoder<I> {
277    pub fn new(c: Config, i: I) -> Decoder<I> {
278        Decoder {
279            chars:  Source::new(i),
280            config: c,
281            buffer: [0; 512],
282            stack:  Stack::new()
283        }
284    }
285
286    /// Create decoder with default `Config`.
287    pub fn default(i: I) -> Decoder<I> {
288        Decoder::new(Config::default(), i)
289    }
290
291    /// Have we exhausted the iterator?
292    pub fn is_end(&mut self) -> bool {
293        self.skip_whitespace();
294        self.chars.peek().is_none()
295    }
296
297    pub fn into_iter(self) -> I {
298        self.chars.into_iter()
299    }
300
301    pub fn iter_mut(&mut self) -> &mut I {
302        self.chars.iter_mut()
303    }
304
305    /// Generic conversion from JSON to an instance of `FromJson`.
306    pub fn from_json<T: FromJson>(&mut self) -> DecodeResult<T> {
307        FromJson::decode(self)
308    }
309
310    /// Decode into `Json` AST value.
311    pub fn decode(&mut self) -> DecodeResult<Json> {
312        let n = self.config.max_nesting;
313        self.decode_json(n)
314    }
315
316    fn decode_json(&mut self, level: usize) -> DecodeResult<Json> {
317        if level == 0 {
318            return Err(DecodeError::MaxRecursion)
319        }
320        self.skip_whitespace();
321        match require!(self.chars.peek()) {
322            '"'               => self.string().map(Json::String),
323            't' | 'f'         => self.bool().map(Json::Bool),
324            'n'               => self.null().map(|_| Json::Null),
325            '0' ... '9' | '-' => self.f64().map(Json::Number),
326            '[' => {
327                self.array()?;
328                let mut v = Vec::new();
329                while self.has_more()? {
330                    let x = self.decode_json(level - 1)?;
331                    v.push(x)
332                }
333                Ok(Json::Array(v))
334            }
335            '{' => {
336                self.object()?;
337                let mut m = HashMap::new();
338                while self.has_more()? {
339                    let k = self.key()?;
340                    let v = self.decode_json(level - 1)?;
341                    m.insert(k, v);
342                }
343                Ok(Json::Object(m))
344            }
345            chr => return Err(DecodeError::Unexpected(chr))
346        }
347    }
348
349    /// Decode as generic Json but ignore the result.
350    ///
351    /// Semantically this method is equivalent to `Decoder::decode`
352    /// but potentially more efficient as it tries to avoid allocating
353    /// intermediate values.
354    pub fn skip(&mut self) -> DecodeResult<()> {
355        let     n = self.config.max_nesting;
356        let mut b = [0; 0];
357        let mut u = Utf8Buffer::new(&mut b);
358        self.skip_json(&mut u, n)
359    }
360
361    fn skip_json(&mut self, b: &mut Utf8Buffer, level: usize) -> DecodeResult<()> {
362        if level == 0 {
363            return Err(DecodeError::MaxRecursion)
364        }
365        self.skip_whitespace();
366        match require!(self.chars.peek()) {
367            '"'               => self.str(b, false).map(|_| ()),
368            't' | 'f'         => self.bool().map(|_| ()),
369            'n'               => self.null().map(|_| ()),
370            '0' ... '9' | '-' => self.f64().map(|_| ()),
371            '[' => {
372                self.array()?;
373                while self.has_more()? {
374                    self.skip_json(b, level - 1)?;
375                }
376                Ok(())
377            }
378            '{' => {
379                self.object()?;
380                while self.has_more()? {
381                    self.key_str(b, false)?;
382                    self.skip_json(b, level - 1)?;
383                }
384                Ok(())
385            }
386            chr => return Err(DecodeError::Unexpected(chr))
387        }
388    }
389
390    integral!(u8,    u8,    false);
391    integral!(u16,   u16,   false);
392    integral!(u32,   u32,   false);
393    integral!(u64,   u64,   false);
394    integral!(usize, usize, false);
395
396    integral!(i8,    i8,    true);
397    integral!(i16,   i16,   true);
398    integral!(i32,   i32,   true);
399    integral!(i64,   i64,   true);
400    integral!(isize, isize, true);
401
402    pub fn f64(&mut self) -> DecodeResult<f64> {
403        fn is_valid(x: char) -> bool {
404            match x {
405                '0'...'9'|'.'|'e'|'E'|'+'|'-' => true,
406                _                             => false
407            }
408        }
409        self.skip_whitespace();
410        let is_neg =
411            match self.chars.peek() {
412                Some('-') => {
413                    self.chars.next();
414                    true
415                }
416                _ => false
417            };
418        let d = require!(self.chars.next());
419        if !d.is_digit(10) {
420            return Err(DecodeError::Unexpected(d))
421        }
422        let mut buf = Utf8Buffer::new(&mut self.buffer);
423        buf.push(d);
424        while let Some(c) = self.chars.next() {
425            if is_valid(c) {
426                buf.push(c)
427            } else {
428                self.chars.put_back(c);
429                break
430            }
431        }
432        match buf.as_str().parse::<f64>() {
433            Err(_)                   => Err(DecodeError::Number),
434            Ok(n) if n.is_nan()      => Err(DecodeError::Number),
435            Ok(n) if n.is_infinite() => Err(DecodeError::Number),
436            Ok(n)                    => Ok(if is_neg {-n} else {n})
437        }
438    }
439
440    pub fn null(&mut self) -> DecodeResult<()> {
441        self.skip_whitespace();
442        self.matches("null")
443    }
444
445    pub fn bool(&mut self) -> DecodeResult<bool> {
446        self.skip_whitespace();
447        match require!(self.chars.next()) {
448            't' => self.matches("rue").map(|_| true),
449            'f' => self.matches("alse").map(|_| false),
450            chr => Err(DecodeError::Unexpected(chr)),
451        }
452    }
453
454    pub fn string(&mut self) -> DecodeResult<String> {
455        let mut s = String::new();
456        self.string_into(&mut s, false)?;
457        Ok(s)
458    }
459
460    /// Decode a JSON string into the given `Utf8Buffer`.
461    ///
462    /// If the actual string does not fit into the provided buffer
463    /// and `overflow_err` is `true`, `DecodeError::BufferOverflow`
464    /// is returned immediately. If `overflow_err` is false we
465    /// continue decoding the string, but the buffer will only
466    /// contain as much as fits into it.
467    pub fn str(&mut self, b: &mut Utf8Buffer, overflow_err: bool) -> DecodeResult<()> {
468        self.string_into(b, overflow_err)
469    }
470
471    fn string_into<B: Buffer>(&mut self, s: &mut B, overflow_err: bool) -> DecodeResult<()> {
472        self.skip_whitespace();
473        if self.chars.next() != Some('"') {
474            return Err(DecodeError::Expected("\""))
475        }
476        let mut escaped = false;
477        loop {
478            match require!(self.chars.next()) {
479                chr if escaped => {
480                    match chr {
481                        '"'  => s.push('"'),
482                        '/'  => s.push('/'),
483                        '\\' => s.push('\\'),
484                        'b'  => s.push('\x08'),
485                        'f'  => s.push('\x0C'),
486                        'n'  => s.push('\n'),
487                        'r'  => s.push('\r'),
488                        't'  => s.push('\t'),
489                        'u'  => match self.hex_unicode()? {
490                            hi @ 0xD800 ... 0xDBFF => {
491                                self.matches("\\u")?;
492                                let lo = self.hex_unicode()?;
493                                if lo < 0xDC00 || lo > 0xDFFF {
494                                    return Err(DecodeError::UnicodeEscape)
495                                }
496                                let c = (((hi - 0xD800) as u32) << 10 | (lo - 0xDC00) as u32) + 0x10000;
497                                s.push(char::from_u32(c).unwrap())
498                            }
499                            0xDC00 ... 0xDFFF => return Err(DecodeError::UnicodeEscape),
500                            x => match char::from_u32(x as u32) {
501                                Some(c) => s.push(c),
502                                None    => return Err(DecodeError::UnicodeEscape)
503                            }
504                        },
505                        c => return Err(DecodeError::Unexpected(c))
506                    }
507                    escaped = false
508                }
509                '\\' => escaped = true,
510                '"'  => break,
511                chr  => s.push(chr)
512            }
513            if overflow_err && s.is_full() {
514                return Err(DecodeError::BufferOverflow)
515            }
516        }
517        Ok(())
518    }
519
520    /// Decode `null` (which is mapped to `None`) or some other
521    /// JSON value (mapped to `Some`).
522    pub fn optional<A, F>(&mut self, mut f: F) -> DecodeResult<Option<A>>
523        where F: FnMut(&mut Decoder<I>) -> DecodeResult<A>
524    {
525        self.skip_whitespace();
526        match require!(self.chars.peek()) {
527            'n' => self.null().map(|_| None),
528             _  => f(self).map(Some)
529        }
530    }
531
532    /// When parsing JSON arrays and objects this needs to be
533    /// called in between to check if the array / object end has been
534    /// reached. E.g.
535    ///
536    /// ```
537    /// use json::{Decoder, DecodeResult};
538    ///
539    /// fn foo<I: Iterator<Item=char>>(d: &mut Decoder<I>) -> DecodeResult<Vec<u8>> {
540    ///     d.array()?;
541    ///     let mut v = Vec::new();
542    ///     while d.has_more()? {
543    ///         v.push(d.u8()?)
544    ///     }
545    ///     Ok(v)
546    /// }
547    /// ```
548    pub fn has_more(&mut self) -> DecodeResult<bool> {
549        self.skip_whitespace();
550        match self.stack.top() {
551            Some(Scope::A(false)) => match self.chars.peek() {
552                Some(']') => {
553                    self.chars.next();
554                    self.stack.pop();
555                    Ok(false)
556                }
557                Some(_) => {
558                    self.stack.set();
559                    Ok(true)
560                }
561                None => Err(DecodeError::EndOfInput)
562            },
563            Some(Scope::A(true)) => match self.chars.next() {
564                Some(',') => Ok(true),
565                Some(']') => {
566                    self.stack.pop();
567                    Ok(false)
568                }
569                _ => Err(DecodeError::Expected("',' or ']'"))
570            },
571            Some(Scope::O(false)) => match self.chars.peek() {
572                Some('}') => {
573                    self.chars.next();
574                    self.stack.pop();
575                    Ok(false)
576                }
577                Some(_) => {
578                    self.stack.set();
579                    Ok(true)
580                }
581                None => Err(DecodeError::EndOfInput)
582            },
583            Some(Scope::O(true)) => match self.chars.next() {
584                Some(',') => Ok(true),
585                Some('}') => {
586                    self.stack.pop();
587                    Ok(false)
588                }
589                _ => Err(DecodeError::Expected("',' or '}'"))
590            },
591            None => Ok(false)
592        }
593    }
594
595    /// Begin parsing a JSON array.
596    ///
597    /// Before each element is parsed, `Decoder::has_more`
598    /// needs to be queried.
599    pub fn array(&mut self) -> DecodeResult<()> {
600        self.skip_whitespace();
601        self.matches("[")?;
602        self.stack.push(Scope::A(false));
603        Ok(())
604    }
605
606    /// Create a JSON array iterator to decode a homogenous array.
607    ///
608    /// ```
609    /// use json::Decoder;
610    ///
611    /// let mut d = Decoder::default("[1,2,3,4]".chars());
612    /// let mut v: Vec<u8> = Vec::new();
613    ///
614    /// for i in d.array_iter().unwrap() {
615    ///     v.push(i.unwrap())
616    /// }
617    /// ```
618    pub fn array_iter<A: FromJson>(&mut self) -> DecodeResult<ArrayIter<A, I>> {
619        self.array()?;
620        Ok(ArrayIter::new(self))
621    }
622
623    /// Begin parsing a JSON object.
624    ///
625    /// Before each key is parsed, `Decoder::has_more`
626    /// needs to be queried.
627    pub fn object(&mut self) -> DecodeResult<()> {
628        self.skip_whitespace();
629        self.matches("{")?;
630        self.stack.push(Scope::O(false));
631        Ok(())
632    }
633
634    /// Decode a JSON object key.
635    pub fn key(&mut self) -> DecodeResult<String> {
636        let mut s = String::new();
637        self.key_into(&mut s, false)?;
638        Ok(s)
639    }
640
641    /// Decode a JSON object key into the given buffer.
642    pub fn key_str(&mut self, b: &mut Utf8Buffer, overflow_err: bool) -> DecodeResult<()> {
643        self.key_into(b, overflow_err)
644    }
645
646    fn key_into<B: Buffer>(&mut self, s: &mut B, overflow_err: bool) -> DecodeResult<()> {
647        self.string_into(s, overflow_err)?;
648        self.skip_whitespace();
649        if self.chars.next() != Some(':') {
650            return Err(DecodeError::Expected(":"))
651        }
652        Ok(())
653    }
654
655    fn skip_whitespace(&mut self) {
656        while let Some(c) = self.chars.next() {
657            if !c.is_whitespace() {
658                self.chars.put_back(c);
659                break
660            }
661        }
662    }
663
664    fn hex_unicode(&mut self) -> DecodeResult<u16> {
665        let a = hex_byte(require!(self.chars.next()))?;
666        let b = hex_byte(require!(self.chars.next()))?;
667        let c = hex_byte(require!(self.chars.next()))?;
668        let d = hex_byte(require!(self.chars.next()))?;
669        Ok(a as u16 * 0x1000 + b as u16 * 0x100 + c as u16 * 0x10 + d as u16)
670    }
671
672    fn matches(&mut self, pattern: &str) -> DecodeResult<()> {
673        for a in pattern.chars() {
674            let b = require!(self.chars.next());
675            if a != b {
676                return Err(DecodeError::Unexpected(b))
677            }
678        }
679        Ok(())
680    }
681}
682
683fn hex_byte(digit: char) -> DecodeResult<u8> {
684    match digit {
685        '0'       => Ok(0),
686        '1'       => Ok(1),
687        '2'       => Ok(2),
688        '3'       => Ok(3),
689        '4'       => Ok(4),
690        '5'       => Ok(5),
691        '6'       => Ok(6),
692        '7'       => Ok(7),
693        '8'       => Ok(8),
694        '9'       => Ok(9),
695        'A' | 'a' => Ok(10),
696        'B' | 'b' => Ok(11),
697        'C' | 'c' => Ok(12),
698        'D' | 'd' => Ok(13),
699        'E' | 'e' => Ok(14),
700        'F' | 'f' => Ok(15),
701        chr       => Err(DecodeError::Unexpected(chr))
702    }
703}
704
705// DecodeError //////////////////////////////////////////////////////////////
706
707pub type DecodeResult<A> = Result<A, DecodeError>;
708
709#[derive(Debug)]
710pub enum DecodeError {
711    /// The underlying iterator stopped giving us new values.
712    EndOfInput,
713    /// An expectation was not met while decoding.
714    Expected(&'static str),
715    /// During generic JSON decoding too many nesting levels had
716    /// been encountered. See `Config` for details.
717    MaxRecursion,
718    /// When decoding integer values, the actual JSON digits exceeded
719    /// the possible value range.
720    IntOverflow,
721    /// An unexpected character was encountered.
722    Unexpected(char),
723    /// An invalid unicode escape sequence was found when
724    /// decoding a JSON string.
725    UnicodeEscape,
726    /// Decoding a numeric value failed.
727    Number,
728    /// A JSON string did not fit into the provided `Utf8Buffer`.
729    BufferOverflow,
730    /// Generic error message.
731    Message(&'static str),
732    /// Some other `Error` trait impl.
733    Other(Box<Error + Send + Sync>)
734}
735
736impl fmt::Display for DecodeError {
737    fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
738        match *self {
739            DecodeError::EndOfInput     => write!(f, "end of input"),
740            DecodeError::Expected(e)    => write!(f, "expected \"{}\"", e),
741            DecodeError::MaxRecursion   => write!(f, "max. number of recursions reached"),
742            DecodeError::IntOverflow    => write!(f, "integer overflow"),
743            DecodeError::Unexpected(c)  => write!(f, "unexpected \"{}\"", c),
744            DecodeError::UnicodeEscape  => write!(f, "invalid unicode escape"),
745            DecodeError::Number         => write!(f, "failed to parse number"),
746            DecodeError::BufferOverflow => write!(f, "buffer overflow"),
747            DecodeError::Message(m)     => write!(f, "error: {}", m),
748            DecodeError::Other(ref e)   => write!(f, "other: {}", e)
749        }
750    }
751}
752
753impl Error for DecodeError {
754    fn description(&self) -> &str {
755        match *self {
756            DecodeError::EndOfInput     => "end of input",
757            DecodeError::Expected(_)    => "expected some string",
758            DecodeError::MaxRecursion   => "objects/arrays are too deeply nested",
759            DecodeError::IntOverflow    => "integer overflow",
760            DecodeError::Unexpected(_)  => "unexpected char",
761            DecodeError::UnicodeEscape  => "invalid unicode escape sequence",
762            DecodeError::Number         => "failed to decode number",
763            DecodeError::BufferOverflow => "buffer too small to hold value",
764            DecodeError::Message(_)     => "generic error message",
765            DecodeError::Other(_)       => "other error"
766        }
767    }
768
769    fn cause(&self) -> Option<&Error> {
770        match *self {
771            DecodeError::Other(ref e) => Some(&**e),
772            _                         => None
773        }
774    }
775}
776
777// Source ///////////////////////////////////////////////////////////////////
778
779struct Source<I: Iterator> {
780    iter:  I,
781    front: Option<I::Item>
782}
783
784impl<I: Iterator> Source<I> {
785    fn new(i: I) -> Source<I> {
786        Source { iter: i, front: None }
787    }
788
789    fn put_back(&mut self, i: I::Item) {
790        self.front = Some(i)
791    }
792
793    fn peek(&mut self) -> Option<I::Item> where I::Item: Copy {
794        self.next().map(|c| { self.put_back(c); c })
795    }
796
797    fn into_iter(self) -> I {
798        self.iter
799    }
800
801    fn iter_mut(&mut self) -> &mut I {
802        &mut self.iter
803    }
804}
805
806impl<I: Iterator> Iterator for Source<I> {
807    type Item = I::Item;
808
809    fn next(&mut self) -> Option<I::Item> {
810        self.front.take().or_else(|| self.iter.next())
811    }
812}
813
814// ArrayIter /////////////////////////////////////////////////////////////////
815
816/// Iterator over JSON array elements.
817///
818/// Used in conjunction with homogenous JSON arrays.
819pub struct ArrayIter<'r, A, I> where I: Iterator<Item=char> + 'r {
820    dec: &'r mut Decoder<I>,
821    _ty: PhantomData<A>
822}
823
824impl<'r, A, I> ArrayIter<'r, A, I> where I: Iterator<Item=char> + 'r {
825    fn new(d: &'r mut Decoder<I>) -> ArrayIter<'r, A, I> {
826        ArrayIter {
827            dec: d,
828            _ty: PhantomData
829        }
830    }
831}
832
833impl<'r, A, I> Iterator for ArrayIter<'r, A, I>
834    where I: Iterator<Item=char> + 'r,
835          A: FromJson
836{
837    type Item = DecodeResult<A>;
838
839    fn next(&mut self) -> Option<DecodeResult<A>> {
840        match self.dec.has_more() {
841            Ok(true)  => Some(self.dec.from_json()),
842            Ok(false) => None,
843            Err(e)    => Some(Err(e))
844        }
845    }
846}
847
848// ReadIter /////////////////////////////////////////////////////////////////
849
850/// Iterator over characters read from any `Read`-type.
851///
852/// Uses the `chars` method of the `Read` interface. Since `Decoder`s
853/// expect iterators over plain `char`s this iterator yields `None`
854/// whenever the underlying `Chars` iterator returned an error.
855pub struct ReadIter<R: Read> {
856    iter:  utf8::Chars<R>,
857    error: Option<ReadError>
858}
859
860impl<R: Read> ReadIter<R> {
861    pub fn new(r: R) -> ReadIter<R> {
862        ReadIter {
863            iter:  utf8::Chars::new(r),
864            error: None
865        }
866    }
867
868    /// Get the error that has been encountered (if any).
869    pub fn error(&self) -> Option<&utf8::ReadError> {
870        self.error.as_ref()
871    }
872
873    /// Get and remove the error that has been encountered (if any).
874    pub fn take_error(&mut self) -> Option<utf8::ReadError> {
875        self.error.take()
876    }
877}
878
879impl<R: Read> Iterator for ReadIter<R> {
880    type Item = char;
881
882    fn next(&mut self) -> Option<char> {
883        match self.iter.next() {
884            Some(Ok(c))  => Some(c),
885            Some(Err(e)) => {
886                self.error = Some(e);
887                None
888            }
889            None => None
890        }
891    }
892}
893
894// Tests ////////////////////////////////////////////////////////////////////
895
896#[cfg(test)]
897mod tests {
898    use super::*;
899
900    #[test]
901    fn empty1() {
902        let mut d = Decoder::default(r#"[{}]"#.chars());
903        d.decode().unwrap();
904    }
905
906    #[test]
907    fn empty2() {
908        let mut d = Decoder::default(r#"[]"#.chars());
909        d.array().unwrap();
910        assert!(!d.has_more().unwrap())
911    }
912
913    #[test]
914    fn object() {
915        let mut d = Decoder::default(r#" {"outer": {"inner": 32 } } "#.chars());
916        d.object().unwrap();
917        assert!(d.has_more().unwrap());
918        let k = d.key().unwrap();
919        assert_eq!("outer", &k);
920        d.object().unwrap();
921        assert!(d.has_more().unwrap());
922        let k = d.key().unwrap();
923        assert_eq!("inner", &k);
924        let v = d.isize().unwrap();
925        assert_eq!(32, v);
926        assert!(!d.has_more().unwrap());
927        assert!(!d.has_more().unwrap());
928    }
929
930    #[test]
931    fn array() {
932        let mut d = Decoder::default(" [ [   [1, 2  ,3], 42 ] ]   ".chars());
933        d.array().unwrap();
934        assert!(d.has_more().unwrap());
935        d.array().unwrap();
936        assert!(d.has_more().unwrap());
937        d.array().unwrap();
938        assert!(d.has_more().unwrap());
939        let a = d.isize().unwrap();
940        assert!(d.has_more().unwrap());
941        let b = d.isize().unwrap();
942        assert!(d.has_more().unwrap());
943        let c = d.isize().unwrap();
944        assert!(!d.has_more().unwrap());
945        assert!(d.has_more().unwrap());
946        let x = d.isize().unwrap();
947        assert!(!d.has_more().unwrap());
948        assert!(!d.has_more().unwrap());
949        assert_eq!((1, 2, 3, 42), (a, b, c, x))
950    }
951
952    #[test]
953    fn array_iter() {
954        let mut d = Decoder::new(Config::default(), "[ true, false, true ]".chars());
955        let mut v = Vec::new();
956        for x in d.array_iter().unwrap() {
957            v.push(x.unwrap())
958        }
959        assert_eq!(vec![true, false, true], v)
960    }
961
962    #[test]
963    fn array_macro() {
964        fn read_array() -> DecodeResult<Vec<bool>> {
965            let mut d = Decoder::new(Config::default(), "[ true, false, true ]".chars());
966            array!(d, d.bool())
967        }
968        assert_eq!(vec![true, false, true], read_array().unwrap())
969    }
970
971    #[test]
972    fn numbers() {
973        let mut d = Decoder::default("1 0 -1 18446744073709551615 -9223372036854775808 255 256".chars());
974        assert_eq!(1, d.u8().unwrap());
975        assert_eq!(0, d.u8().unwrap());
976        assert_eq!(-1, d.i8().unwrap());
977        assert_eq!(18446744073709551615, d.u64().unwrap());
978        assert_eq!(-9223372036854775808, d.i64().unwrap());
979        assert_eq!(255, d.u8().unwrap());
980        match d.u8() {
981            Err(DecodeError::IntOverflow) => (),
982            other => panic!("unexpected result: {:?}", other)
983        }
984    }
985
986    #[test]
987    fn generic() {
988        let mut d = Decoder::default("null".chars());
989        assert_eq!(None, d.from_json::<Option<u8>>().unwrap());
990
991        let mut d = Decoder::default("100".chars());
992        assert_eq!(Some(100u8), d.from_json().unwrap())
993    }
994}