1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
use std::error;
use std::fmt;
use Value;
use self::DecodeErrorKind::*;

#[cfg(feature = "rustc-serialize")] mod rustc_serialize;
#[cfg(feature = "serde")] mod serde; // TODO

pub struct Decoder {
    value: Option<Value>,
    cur_field: Option<String>,
}

#[derive(Debug)]
pub struct DecodeError {
    pub field: Option<String>,
    pub kind: DecodeErrorKind,
}

/// Enumeration of possible errors which can occur while decoding a structure.
#[allow(dead_code)]
#[derive(PartialEq, Debug)]
pub enum DecodeErrorKind {
    /// An error flagged by the application, e.g. value out of range
    ApplicationError(String),
    /// A field was expected, but none was found.
    ExpectedField(/* type */ Option<&'static str>),
    /// A field was found, but it was not an expected one.
    UnknownField,
    /// A field was found, but it had the wrong type.
    ExpectedType(/* expected */ &'static str, /* found */ &'static str),
    //// The nth map key was expected, but none was found.
    ExpectedMapKey(usize),
    /// The nth map element was expected, but none was found.
    ExpectedMapElement(usize),
    /// An enum decoding was requested, but no variants were supplied
    NoEnumVariants,
    /// The unit type was being decoded, but a non-zero length string was found
    NilTooLong,
    /// There was an error with the syntactical structure of the TOML.
    SyntaxError,
    /// The end of the TOML input was reached too soon
    EndOfStream,
}

impl error::Error for DecodeError {
    fn description(&self) -> &str {
        match self.kind {
            ApplicationError(ref s) => &**s,
            ExpectedField(..) => "expected a field",
            UnknownField => "found an unknown field",
            ExpectedType(..) => "expected a type",
            ExpectedMapKey(..) => "expected a map key",
            ExpectedMapElement(..) => "expected a map element",
            NoEnumVariants => "no enum variants to decode to",
            NilTooLong => "nonzero length string representing nil",
            SyntaxError => "syntax error",
            EndOfStream => "end of stream",
        }
    }
}

impl fmt::Display for DecodeError {
    #[allow(dead_code)]
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        try!(match self.kind {
            ApplicationError(ref err) => {
                write!(f, "{}", err)
            }
            ExpectedField(expected_type) => {
                match expected_type {
                    Some("table") => write!(f, "expected a section"),
                    Some("field") => write!(f, "expected the field"),
                    Some(e) => write!(f, "expected a value of type `{}`", e),
                    None => write!(f, "expected a value"),
                }
            }
            UnknownField => write!(f, "unknown field"),
            ExpectedType(expected, found) => {
                fn humanize(s: &str) -> String {
                    if s == "section" {
                        format!("a section")
                    } else {
                        format!("a value of type `{}`", s)
                    }
                }
                write!(f, "expected {}, but found {}",
                       humanize(expected),
                       humanize(found))
            }
            ExpectedMapKey(idx) => {
                write!(f, "expected at least {} keys", idx + 1)
            }
            ExpectedMapElement(idx) => {
                write!(f, "expected at least {} elements", idx + 1)
            }
            NoEnumVariants => {
                write!(f, "expected an enum variant to decode to")
            }
            NilTooLong => {
                write!(f, "expected 0-length string")
            }
            SyntaxError => {
                write!(f, "syntax error")
            }
            EndOfStream => {
                write!(f, "end of stream")
            }
        });
        match self.field {
            Some(ref s) => {
                write!(f, " for the key `{}`", s)
            }
            None => Ok(())
        }
    }
}

impl Decoder {
    pub fn new(value: Value) -> Decoder {
        Decoder {
            value: Some(value),
            cur_field: None
        }
    }

    fn err(&self, kind: DecodeErrorKind) -> DecodeError {
        DecodeError {
            field: self.cur_field.clone(),
            kind: kind,
        }
    }

    fn mismatch(&self, expected: &'static str,
                found: &Option<Value>) -> DecodeError{
        match *found {
            Some(ref val) => self.err(ExpectedType(expected, val.type_str())),
            None => self.err(ExpectedField(Some(expected))),
        }
    }

    fn sub_decoder(&self, value: Option<Value>, field: &str) -> Decoder {
        Decoder {
            value: value,
            cur_field: if field.len() == 0 {
                self.cur_field.clone()
            } else {
                match self.cur_field {
                    None => Some(format!("{}", field)),
                    Some(ref s) => Some(format!("{}.{}", s, field))
                }
            }
        }
    }
}

pub fn decode<T: ::rustc_serialize::Decodable + fmt::Debug>(value: Value) -> Result<T, DecodeError> {
    ::rustc_serialize::Decodable::decode(&mut Decoder::new(value.to_owned()))
}

pub fn decode_from_vec<T: ::rustc_serialize::Decodable + fmt::Debug>(vec: Vec<Value>) -> Result<T, DecodeError> {
    decode(Value::Array(vec))
}

#[cfg(test)]
mod tests {
    use ion::decode_from_vec;
    use ::rustc_serialize as rs;
    use Value;

    #[derive(Debug, PartialEq)]
    struct Bar {
        foo: u32
    }

    impl rs::Decodable for Bar {
        fn decode<D: rs::Decoder>(d: &mut D) -> Result<Bar, D::Error> {
            let foo = try!(d.read_u32());
            Ok(Bar { foo: foo})
        }
    }

    #[derive(Debug, PartialEq, RustcDecodable)]
    struct Foo {
        int: u32,
        string: String,
        opt_string: Option<String>,
        yesno: bool,
        nested: Bar,
        ary: Vec<u32>
    }

    #[test]
    fn test_decode() {
        let row : Vec<_> = "1|foo|some|true|1|1,2".split("|").map(|s| Value::String(s.to_owned())).collect();
        let foo : Foo = decode_from_vec(row).expect("decode");

        assert_eq!(1, foo.int);
        assert_eq!("foo", foo.string);
        assert_eq!(Some("some".to_owned()), foo.opt_string);
        assert_eq!(true, foo.yesno);
        assert_eq!(Bar { foo: 1 }, foo.nested);
        assert_eq!(vec![1, 2], foo.ary);
    }
}