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
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
#![feature(pattern)]
#![feature(type_ascription)]
#![feature(proc_macro_hygiene)]

extern crate darkly_macros;

// Questions
// Can we impl Iterator for Scanner

// TODO
//   delimited scanning
//   non-line-broken scanning

// References
// https://doc.rust-lang.org/nightly/std/fmt/index.html
// https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html
// https://en.wikipedia.org/wiki/Scanf_format_string
// https://github.com/DanielKeep/rust-scan

pub use darkly_macros::{scanln, scanlns, sscanln, sscanlns, fscanln, fscanlns};

use std::cmp::min;
use std::io::{Read, BufReader, BufRead};
use std::str::pattern::Pattern;
use std::str::FromStr;

use crate as darkly;

// TODO Serde
pub trait Deserialize {}

pub trait Scanner {
    fn expect<'a, P: Pattern<'a>>(&'a mut self, p: P) -> Result<usize, String>;
    fn expect_whitespace<'a>(&'a mut self) -> Result<usize, String>;

    fn has_next(&mut self) -> bool;
    // Err case is always empty string
    fn next(&mut self) -> Result<char, String>;

    // Reads until str is full or to break.
    // It is undefined behaviour for `result` to overlap in memory with the data
    // underlying the Scanner.
    fn scan_str(&mut self, result: &mut str) -> Result<usize, String>;
    fn scan_str_to<'a, P: Pattern<'a>>(&'a mut self, result: &mut str, next: P) -> Result<usize, String>;
    fn scan_str_to_whitespace<'a>(&'a mut self, result: &mut str) -> Result<usize, String>;

    fn scan<T: FromStr>(&mut self) -> Result<T, String>;
    fn scan_to<'a, T: FromStr, P: Pattern<'a>>(&'a mut self, next: P) -> Result<T, String>;
    fn scan_to_whitespace<'a, T: FromStr>(&'a mut self) -> Result<T, String>;

    fn scan_de<T: Deserialize>(&mut self) -> Result<T, String> { unimplemented!(); }
    fn scan_de_to<'a, T: Deserialize, P: Pattern<'a>>(&'a mut self, _next: P) -> Result<T, String> { unimplemented!(); }
    fn scan_de_to_whitespace<'a, T: Deserialize>(&'a mut self) -> Result<T, String> { unimplemented!(); }
}

pub fn scan_str<'a>(input: &'a str) -> impl Scanner + 'a {
    LineReadScanner::new(input.as_bytes())
}

pub fn scan_stdin<'a>() -> impl Scanner + 'a {
    LineReadScanner::new(::std::io::stdin())
}

pub fn scan_file<'a>(input: &'a ::std::fs::File) -> impl Scanner + 'a {
    LineReadScanner::new(input)
}

/// Panics if we can't open the file pointed to by path.
pub fn scan_file_from_path(path: &::std::path::Path) -> impl Scanner {
    LineReadScanner::new(::std::fs::File::open(path).unwrap())
}


// Is not kept in a state of readiness - you must call advance_line to re-establish
// invariants.
// Invariants:
// cur_line.is_some() => cur_pos < cur_line.unwrap().len()
// cur_line.is_some() <=> data to read
// cur_line does not include the terminating newline
pub struct LineReadScanner<R: Read> {
    reader: BufReader<R>,
    cur_line: Option<String>,
    cur_pos: usize,
}

impl<R: Read> LineReadScanner<R> {
    pub fn new(reader: R) -> LineReadScanner<R> {
        LineReadScanner {
            reader: BufReader::new(reader),
            cur_line: None,
            cur_pos: 0,
        }
    }

    fn read_line(&mut self) {
        let mut s = String::new();
        match self.reader.read_line(&mut s) {
            Ok(n) if n == 0 => self.cur_line = None,
            Err(_) => self.cur_line = None,
            Ok(_) => {
                if &s[s.len() - 1..] == "\n" {
                    self.cur_line = Some(s[..s.len() - 1].to_owned());
                } else {
                    self.cur_line = Some(s.to_owned());                    
                }
            }
        }
        self.cur_pos = 0;
    }

    // Assures that we are in a canonical state, i.e., either we can read, or
    // self.cur_line.is_none();
    fn advance_line(&mut self) {
        loop {
            if let Some(ref line) = self.cur_line {
                if self.cur_pos < line.len() {
                    break;
                }
            }

            self.read_line();
            if self.cur_line.is_none() || self.cur_line.as_ref().unwrap().is_empty() {
                break;
            }
        }
    }

    fn with_cur_line<'a, F, T>(&'a mut self, f: F) -> Result<T, String>
        where F: FnOnce(&'a str, &mut usize) -> Result<T, String>
    {
        self.advance_line();
        if let Some(ref line) = self.cur_line {
            f(line, &mut self.cur_pos)
        } else {
            Err(String::new())
        }
    }

    fn scan_internal<T: FromStr>(input: &str) -> Result<T, String> {
        FromStr::from_str(input).map_err(|_| input.to_owned())
    }
}

impl<R: Read> Scanner for LineReadScanner<R> {
    fn expect<'a, P: Pattern<'a>>(&'a mut self, p: P) -> Result<usize, String> {
        self.with_cur_line(|line, cur_pos| {
            let rest = &line[*cur_pos..];
            if let Some((0, s)) = rest.match_indices(p).next() {
                *cur_pos += s.len();
                Ok(s.len())
            } else {
                Err(rest.to_owned())
            }            
        })
    }

    fn expect_whitespace<'a>(&'a mut self) -> Result<usize, String> {
        self.with_cur_line(|line, cur_pos| {
            let mut count = 0;
            loop {
                let rest = &line[*cur_pos..];
                if let Some(c) = rest.chars().next() {
                    if c.is_whitespace() && c != '\n' {
                        let width = c.len_utf8();
                        *cur_pos += width;
                        count += width;
                        continue;
                    }
                }
                break;
            }
            Ok(count)
        }).or(Ok(0))
    }

    fn has_next(&mut self) -> bool {
        self.advance_line();
        self.cur_line.is_some()
    }

    fn next(&mut self) -> Result<char, String> {
        let result = self.with_cur_line(|line, cur_pos| {
            let rest = &line[*cur_pos..];
            if let Some(c) = rest.chars().next() {
                *cur_pos += c.len_utf8();
                Ok(c)
            } else {
                Err(rest.to_owned())
            }
        });

        if result.is_err() {
            self.cur_line = None;
        }

        result
    }

    fn scan_str(&mut self, result: &mut str) -> Result<usize, String> {
        self.with_cur_line(|line, cur_pos| {
            let rest = &line[*cur_pos..];
            let end = min(result.len(), rest.len());
            copy_str(rest, result, end);
            *cur_pos += end;
            Ok(result.len())
        })
    }

    fn scan_str_to<'a, P: Pattern<'a>>(&'a mut self, result: &mut str, next: P) -> Result<usize, String> {
        self.with_cur_line(|line, cur_pos| {
            let rest = &line[*cur_pos..];
            match rest.match_indices(next).next() {
                Some((index, s)) => {
                    let end = min(result.len(), index);
                    copy_str(rest, result, end);
                    *cur_pos += index + s.len();
                }
                None => {
                    return Err(rest.to_owned());
                    // The below code gives the correct behaviour for scan_to_or_end
                    // let end = min(result.len(), rest.len());
                    // copy_str(rest, result, end);
                    // *cur_pos = line.len();
                }
            }
            Ok(result.len())
        })        
    }

    fn scan_str_to_whitespace<'a>(&'a mut self, _result: &mut str) -> Result<usize, String> {
        unimplemented!();
    }

    fn scan<T: FromStr>(&mut self) -> Result<T, String> {
        let result = self.with_cur_line(|line, cur_pos| {
            let rest = &line[*cur_pos..];
            LineReadScanner::<R>::scan_internal(rest)
        });
        self.cur_line = None;
        result
    }

    // TODO should panic if we run out of text before we hit `next`
    fn scan_to<'a, T: FromStr, P: Pattern<'a>>(&'a mut self, next: P) -> Result<T, String> {
        self.with_cur_line(|line, cur_pos| {
            let rest = &line[*cur_pos..];
            match rest.match_indices(next).next() {
                Some((i, s)) => {
                    *cur_pos += i + s.len() - 1;
                    LineReadScanner::<R>::scan_internal(&rest[..i])
                }
                None => {
                    Err(rest.to_owned())
                    // The below code gives the correct behaviour for scan_to_or_end
                    // *cur_pos = line.len();
                    // LineReadScanner::<R>::scan_internal(rest)
                }
            }
        })
    }

    fn scan_to_whitespace<'a, T: FromStr>(&'a mut self) -> Result<T, String> {
        let result = self.with_cur_line(|line, cur_pos| {
            let rest = &line[*cur_pos..];
            match rest.match_indices(|c: char| c.is_whitespace() && c != '\n').next() {
                Some((i, s)) => {
                    *cur_pos += i + s.len();
                    LineReadScanner::<R>::scan_internal(&rest[..i])
                }
                None => {
                    *cur_pos = line.len();
                    LineReadScanner::<R>::scan_internal(rest)
                }
            }
        })?;
        self.expect_whitespace()?;
        Ok(result)
    }
}

// `from` and `to` must not overlap.
fn copy_str(from: &str, to: &mut str, count: usize) {
    assert!(count <= to.len());
    unsafe {
        let mfrom = from.as_bytes().as_ptr();
        let mto = ::std::mem::transmute::<&mut str, &mut [u8]>(to).as_mut_ptr();
        ::std::ptr::copy_nonoverlapping(mfrom, mto, count);
    }
}


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

    #[test]
    fn test_scan() {
        let mut ss = scan_str("Hello, world!");
        assert!(ss.scan_to(",").unwrap(): String == "Hello");
        assert!(ss.next().unwrap() == ',');
        assert!(ss.next().unwrap() == ' ');
        assert!(ss.scan().unwrap(): String == "world!");
    }

    #[test]
    fn test_scan_to_int() {
        let mut ss = scan_str("Hello: 42!");
        assert!(ss.scan_to(":").unwrap(): String == "Hello");
        assert!(ss.next().unwrap() == ':');
        assert!(ss.next().unwrap() == ' ');
        assert!(ss.scan_to("!").unwrap(): u32 == 42);
    }

    #[test]
    fn test_scan_to_ws() {
        let mut ss = scan_str("Hello  42!0");
        assert!(ss.scan_to_whitespace().unwrap(): String == "Hello");
        assert!(ss.scan_to("!").unwrap(): u32 == 42);
        assert!(ss.next().unwrap() == '!');
        assert!(ss.scan_to_whitespace().unwrap(): i32 == 0);
    }

    #[test]
    fn test_len() {
        let mut ss = scan_str("Hello, world!");
        assert!(ss.expect("Hello").unwrap() == 5);
        ss.next().unwrap();
        ss.next().unwrap();
        // TODO match world?
    }

    #[test]
    fn test_scan_str() {
        let mut ss = scan_str("Hello, world!");

        assert!(ss.next().unwrap() == 'H');
        assert!(ss.next().unwrap() == 'e');

        let mut s = "     ".to_owned();
        ss.scan_str(&mut s).unwrap();
        assert!(s == "llo, ");

        ss.scan_str_to(&mut s, "d").unwrap();
        assert!(s == "worl ");
        assert!(ss.next().is_ok());
        assert!(!ss.has_next());
    }

    #[test]
    fn test_expect() {
        let mut ss = scan_str("Hello, world!");

        ss.expect("Hello").unwrap();
        ss.expect(',').unwrap();
        ss.expect(' ').unwrap();
        assert!(ss.next() == Ok('w'));
    }

    #[test]
    fn test_expect_ws() {
        let mut ss = scan_str("   Hello, world!");

        assert_eq!(ss.expect_whitespace().unwrap(), 3);
        ss.expect("Hello").unwrap();
        ss.expect(',').unwrap();
        assert_eq!(ss.expect_whitespace().unwrap(), 1);
        assert!(ss.next() == Ok('w'));
        assert_eq!(ss.expect_whitespace().unwrap(), 0);
    }

    #[test]
    fn test_macro_ws() {
        {sscanln!("hello 42", "hello {} ", x: u32);
        assert_eq!(x, 42);}
        {sscanln!("hello   42", "hello {} ", x: u32);
        assert_eq!(x, 42);}
        {sscanln!("hello42", "hello {} ", x: u32);
        assert_eq!(x, 42);}
        {sscanln!("hello   42     ", "hello {} ", x: u32);
        assert_eq!(x, 42);}
        {sscanln!("42 hello", " {} hello", x: u32);
        assert_eq!(x, 42);}
        {sscanln!("42   hello", " {} hello", x: u32);
        assert_eq!(x, 42);}
        // FIXME() robust parsing
        // we should know that the `hello` chunk is coming up and pass it to expect ws, so it can accept zero ws
        // {sscanln!("42hello", " {} hello", x: u32);
        // assert_eq!(x, 42);}
        {sscanln!("   42  hello", " {} hello", x: u32);
        assert_eq!(x, 42);}
    }

    #[test]
    fn test_macro_smoke() {
        sscanln!("position=<-51031,  41143>", "position=< {}, {}>", a, b);
        println!("{} {}", a: i32, b: i32);
    }
}