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
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
//! Easily deserialize whitespace seperated data into any rust data structure supported by serde.
//! Useful for demos, programming contests, and the like.
//! 
//! current issues:
//!  * no support for enums with struct variants
//!  * structs or tuples cannot contain an unbounded container, like a `Vec` or `HashMap`.
//!
//! future features:
//!  * defining custom whitespace characters
//!  * `scanf` style formatting for more complex inputs
//!
//! ## Example
//!
//! ```rust
//! extern crate serde;
//! extern crate serde_scan;
//! 
//! #[macro_use]
//! extern crate serde_derive;
//! 
//! #[derive(Deserialize, Debug, PartialEq)]
//! struct Triple {
//!     a: u32,
//!     b: u32,
//!     c: u32,
//! }
//! 
//! #[derive(Deserialize, Debug, PartialEq)]
//! enum Command {
//!     Q,
//!     Help,
//!     Size(usize, usize),
//!     Color(u8),
//! }
//! 
//! fn main() {
//!     let s = "1 2 3";
//! 
//!     let a: [u32; 3] = serde_scan::from_str(s).unwrap();
//!     assert_eq!(a, [1, 2, 3]);
//! 
//!     let b: (u32, u32, u32) = serde_scan::from_str(s).unwrap();
//!     assert_eq!(b, (1, 2, 3));
//! 
//!     let c: Triple = serde_scan::from_str(s).unwrap();
//!     assert_eq!(c, Triple { a: 1, b: 2, c: 3 });
//! 
//!     let s = "Size 1 2";
//!     let size: Command = serde_scan::from_str(s).unwrap();
//!     assert_eq!(size, Command::Size(1, 2));
//! }
//! ```

extern crate serde;

#[cfg(test)]
#[cfg_attr(test, macro_use)]
extern crate serde_derive;

mod de;

mod errors {
    use std::io;
    use std::error::Error;
    use std::fmt::{self, Display};
    use serde::de;

    // TODO: make this better


    #[derive(Debug)]
    pub enum ScanError {
        Io( io::Error ),
        De,
        EOF,
        NS(&'static str)
    }

    impl From<io::Error> for ScanError {
        fn from(e: io::Error) -> Self {
            ScanError::Io(e)
        }
    }

    impl Display for ScanError {
        fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
            match *self {
                ScanError::Io(ref e) => write!(f, "io: {}", e),
                ScanError::De => write!(f, "deserialization error"),
                ScanError::EOF => write!(f, "unexpected end of input"),
                ScanError::NS(val) => write!(f, "deseralizing `{}` is not supported at this time.", val),
            }
        }
    }

    impl Error for ScanError {
        fn description(&self) -> &str {
            match *self {
                ScanError::Io(ref e) => e.description(),
                ScanError::De => "deserialization error",
                ScanError::EOF => "unexpected end of input",
                ScanError::NS(_) => "unsupported format",
            }
        }
    }

    impl de::Error for ScanError {
        fn custom<T: Display>(_msg: T) -> Self {
            ScanError::De
        }
    }
}

use errors::*;

use serde::de::{Deserialize, DeserializeOwned};


/// Get a line of input from stdin, and parse it. 
/// 
/// Extra data not needed for parsing `T` is thrown out.
/// 
pub fn next_line<T: DeserializeOwned>() -> Result<T, ScanError> {
    use std::io;
    
    let input = io::stdin();
    let mut buf = String::new();

    input.read_line(&mut buf)?;

    from_str(&buf)
}

/// Parse a string contaning whitespace seperated data.
/// 
pub fn from_str<'a, T: Deserialize<'a>>(s: &'a str) -> Result<T, ScanError> {
    let mut de = de::Deserializer::from_str(s);

    T::deserialize(&mut de)
} 


#[cfg(test)]
mod tests {
    use super::*;
    #[test]
    fn numbers() {

        let a: u64 = from_str("64").unwrap();
        let b: i64 = from_str("-64").unwrap();

        assert_eq!(a, 64);
        assert_eq!(b, -64);
    }

    #[test]
    fn tuples() {

        let a: (f32,) = from_str("  45.34 ").unwrap();
        let b: (u8, u8) = from_str("   3 4   ").unwrap();
        let c: (u32, String, u32) = from_str(" 413 plus 612 ").unwrap();

        assert_eq!(a.0, 45.34);
        assert_eq!(b, (3, 4));
        assert_eq!(c, (413, String::from("plus"), 612));
    }

    #[test]
    fn options() {
        let a: Result<u32, ScanError> = from_str("    ");
        let b: Option<u32> = from_str("   ").unwrap();
        let c: Option<u32> = from_str(" 7 ").unwrap();

        assert!(a.is_err());
        assert_eq!(b, None);
        assert_eq!(c, Some(7));
    }

    #[test]
    fn three_ways() {

        #[derive(Deserialize, Debug, PartialEq)]
        struct Triple {
            a: u32,
            b: u32,
            c: u32,
        }


        let s = r#" 1 
                2 
        3 "#;

        let a: [u32; 3] = from_str(s).unwrap();
        assert_eq!(a, [1, 2, 3]);

        let b: (u32, u32, u32) = from_str(s).unwrap();
        assert_eq!(b, (1, 2, 3));

        let c: Triple = from_str(s).unwrap();
        assert_eq!(c, Triple { a: 1, b: 2, c: 3 });
    }

    #[test]
    fn enums() {
        let color_list = r#"
            red
            blue
            green
            green
            red
            blue
        "#;

        #[derive(Deserialize, Debug, PartialEq)]
        #[serde(rename_all = "snake_case")]
        enum Color {
            Red,
            Blue,
            Green,
        }

        let colors: Vec<Color> = from_str(color_list).unwrap();

        assert_eq!(colors.len(), 6);
        assert_eq!(colors[3], Color::Green);

    }

    #[test]
    fn enum_tuple() {
        #[derive(Deserialize, Debug, PartialEq)]
        #[serde(rename_all = "snake_case")]
        enum EnumTuple {
            Variant(i32),
            Tuple(String, String, usize),
        }

        // this might work in the future
        let a: EnumTuple = from_str("variant 1").unwrap();
        let b: EnumTuple = from_str("tuple two three 4").unwrap();

        assert_eq!(a, EnumTuple::Variant(1));
        assert_eq!(b, EnumTuple::Tuple("two".to_string(), "three".to_string(), 4));
    }

    #[test]
    fn byte_bufs() {
        // maybe: add support for 0x, 0o, 0b
        let bytes: Vec<u8> = from_str("0 1 2 255").unwrap();
        assert_eq!(bytes[0], 0x00);
        assert_eq!(bytes.len(), 4);

        let borrowed: Result<&[u8], _> = from_str("0 1 2 255");
        assert!(borrowed.is_err());
    }

    #[test]
    fn unsupported() {
        #[derive(Deserialize, Debug, PartialEq)]
        #[serde(rename_all = "snake_case")]
        enum Bad {
            StructVariant {
                a: f64,
                b: f64,
            },
        }

        // this might work in the future
        let c: Result<Bad, _> = from_str("struct_variant 0.4 0.5");

        assert!(c.is_err());

        #[derive(Deserialize, Debug, PartialEq)]
        struct VecWithStuff {
            vec: Vec<u32>,
            stuff: String,
        }

        // this will work in the future
        let d: Result<VecWithStuff, _> = from_str("1 2 3 4 6 Stuff");
        assert!(d.is_err())

    }
}