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
use std::io;
use unicode_reader::CodePoints;
use crate::error::{Error, Result};
use crate::json::Json;
pub struct Jsons<R>
where
R: io::Read,
{
codes: CodePoints<io::Bytes<R>>,
quant: String,
}
impl<R> From<R> for Jsons<R>
where
R: io::Read,
{
fn from(input: R) -> Jsons<R> {
Jsons {
codes: input.into(),
quant: String::with_capacity(1024),
}
}
}
impl<R> Iterator for Jsons<R>
where
R: io::Read,
{
type Item = Result<Json>;
fn next(&mut self) -> Option<Self::Item> {
let mut markers = String::new();
let mut ok_ch = self.read_whitespace()?;
loop {
let ch = match ok_ch {
Ok(ch) => {
self.quant.push(ch);
match ch {
'{' => markers.push('}'),
'[' => markers.push(']'),
'}' | ']' => loop {
if let Some(m) = markers.pop() {
if m == ch {
break;
}
} else if markers.is_empty() {
break;
}
},
'"' => match Jsons::read_string(self)? {
Ok(_) => (),
Err(err) => break Some(Err(err)),
},
_ => (),
}
ch
}
Err(err) => break Some(Err(err)),
};
let eov = ch.is_whitespace() || ch == '}' || ch == ']' || ch == '"';
if markers.is_empty() && eov {
let res = match self.quant.parse() {
Ok(json) => Some(Ok(json)),
Err(s) => Some(Ok(Json::__Error(s))),
};
self.quant.truncate(0);
break res;
}
let res = self.codes.next();
if res.is_none() && !self.quant.is_empty() {
let res = match self.quant.parse() {
Ok(json) => Some(Ok(json)),
Err(s) => Some(Ok(Json::__Error(s))),
};
self.quant.truncate(0);
break res;
} else if res.is_none() {
break None;
}
ok_ch = match res.unwrap() {
Ok(x) => Ok(x),
Err(err) => Err(Error::IoError(err.to_string())),
}
}
}
}
impl<R> Jsons<R>
where
R: io::Read,
{
fn read_string(&mut self) -> Option<Result<()>> {
let mut escape = false;
loop {
match self.codes.next() {
Some(Ok(ch)) if escape => {
self.quant.push(ch);
escape = false;
}
Some(Ok('\\')) => {
self.quant.push('\\');
escape = true;
}
Some(Ok('"')) => {
self.quant.push('"');
break Some(Ok(()));
}
Some(Ok(ch)) => self.quant.push(ch),
Some(Err(err)) => break Some(Err(Error::IoError(err.to_string()))),
None => break Some(Ok(())),
}
}
}
fn read_whitespace(&mut self) -> Option<Result<char>> {
loop {
match self.codes.next()? {
Ok(ch) if !ch.is_whitespace() => break Some(Ok(ch)),
Ok(_) => (),
Err(err) => break Some(Err(Error::IoError(err.to_string()))),
}
}
}
}
#[cfg(test)]
#[path = "jsons_test.rs"]
mod jsons_test;