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
use super::Source;
use std::io::BufRead;
use std::iter::Peekable;
use std::str::SplitWhitespace;
pub struct LineSource<R: BufRead> {
tokens: Peekable<SplitWhitespace<'static>>,
current_context: Box<str>,
reader: R,
}
impl<R: BufRead> LineSource<R> {
pub fn new(reader: R) -> LineSource<R> {
LineSource {
current_context: "".to_string().into_boxed_str(),
tokens: "".split_whitespace().peekable(),
reader,
}
}
fn prepare(&mut self) {
while self.tokens.peek().is_none() {
let mut line = String::new();
let num_bytes = self
.reader
.read_line(&mut line)
.expect("failed to get linel maybe an IO error.");
if num_bytes == 0 {
return;
}
self.current_context = line.into_boxed_str();
self.tokens = unsafe { std::mem::transmute::<_, &'static str>(&*self.current_context) }
.split_whitespace()
.peekable();
}
}
}
impl<R: BufRead> Source<R> for LineSource<R> {
fn next_token(&mut self) -> Option<&str> {
self.prepare();
self.tokens.next()
}
fn is_empty(&mut self) -> bool {
self.prepare();
self.tokens.peek().is_none()
}
}
use std::io::BufReader;
impl<'a> From<&'a str> for LineSource<BufReader<&'a [u8]>> {
fn from(s: &'a str) -> LineSource<BufReader<&'a [u8]>> {
LineSource::new(BufReader::new(s.as_bytes()))
}
}