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
use crate::{irc::IrcMessage, IntoOwned, MessageError};
use std::{
future::Future,
io::Read,
pin::Pin,
task::{Context, Poll},
};
use futures_lite::{io::BufReader as AsyncBufReader, AsyncBufReadExt, AsyncRead, Stream};
#[derive(Debug)]
pub enum DecodeError {
Io(std::io::Error),
InvalidUtf8(std::str::Utf8Error),
ParseError(MessageError),
Eof,
}
impl std::fmt::Display for DecodeError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Io(err) => write!(f, "io error: {}", err),
Self::InvalidUtf8(err) => write!(f, "invalid utf8: {}", err),
Self::ParseError(err) => write!(f, "parse error: {}", err),
Self::Eof => f.write_str("end of file reached"),
}
}
}
impl std::error::Error for DecodeError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
Self::Io(err) => Some(err),
Self::InvalidUtf8(err) => Some(err),
Self::ParseError(err) => Some(err),
_ => None,
}
}
}
pub struct Decoder<R> {
reader: std::io::BufReader<R>,
buf: Vec<u8>,
}
impl<R> std::fmt::Debug for Decoder<R> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Decoder").finish()
}
}
impl<R: Read> Decoder<R> {
pub fn new(reader: R) -> Self {
Self {
reader: std::io::BufReader::new(reader),
buf: Vec::with_capacity(1024),
}
}
pub fn read_message(&mut self) -> Result<IrcMessage<'_>, DecodeError> {
use std::io::BufRead;
self.buf.clear();
let n = self
.reader
.read_until(b'\n', &mut self.buf)
.map_err(DecodeError::Io)?;
if n == 0 {
return Err(DecodeError::Eof);
}
let str = std::str::from_utf8(&self.buf[..n]).map_err(DecodeError::InvalidUtf8)?;
crate::irc::parse_one(str)
.map_err(DecodeError::ParseError)
.map(|(_, msg)| msg)
}
pub fn iter(&mut self) -> &mut Self {
self
}
pub fn into_inner(self) -> R {
self.reader.into_inner()
}
}
impl<R: Read> Iterator for Decoder<R> {
type Item = Result<IrcMessage<'static>, DecodeError>;
fn next(&mut self) -> Option<Self::Item> {
match self.read_message() {
Err(DecodeError::Eof) => None,
Ok(msg) => Some(Ok(msg.into_owned())),
Err(err) => Some(Err(err)),
}
}
}
pub struct AsyncDecoder<R> {
reader: AsyncBufReader<R>,
buf: Vec<u8>,
}
impl<R> std::fmt::Debug for AsyncDecoder<R> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("AsyncDecoder").finish()
}
}
impl<R: AsyncRead + Send + Sync + Unpin> AsyncDecoder<R> {
pub fn new(reader: R) -> Self {
Self {
reader: AsyncBufReader::new(reader),
buf: Vec::with_capacity(1024),
}
}
pub async fn read_message(&mut self) -> Result<IrcMessage<'_>, DecodeError> {
self.buf.clear();
let n = self
.reader
.read_until(b'\n', &mut self.buf)
.await
.map_err(DecodeError::Io)?;
if n == 0 {
return Err(DecodeError::Eof);
}
let str = std::str::from_utf8(&self.buf[..n]).map_err(DecodeError::InvalidUtf8)?;
log::trace!("< {}", str.escape_debug());
crate::irc::parse_one(str)
.map_err(DecodeError::ParseError)
.map(|(_, msg)| msg)
}
pub fn into_inner(self) -> R {
self.reader.into_inner()
}
}
impl<R> Stream for AsyncDecoder<R>
where
R: AsyncRead + Send + Sync + Unpin,
{
type Item = Result<IrcMessage<'static>, DecodeError>;
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
let mut this = self.as_mut();
let fut = this.read_message();
futures_lite::pin!(fut);
match futures_lite::ready!(fut.poll(cx)) {
Err(DecodeError::Eof) => Poll::Ready(None),
Ok(msg) => Poll::Ready(Some(Ok(msg.into_owned()))),
Err(err) => Poll::Ready(Some(Err(err))),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn read_sync() {
let data = b"hello\r\nworld\r\ntesting this\r\nand another thing\r\n".to_vec();
let mut reader = std::io::Cursor::new(data);
let v = Decoder::new(&mut reader)
.iter()
.collect::<Result<Vec<_>, _>>()
.unwrap();
assert_eq!(v.len(), 4);
reader.set_position(0);
let mut dec = Decoder::new(reader);
for _ in 0..4 {
dec.read_message().unwrap();
}
assert!(matches!(dec.read_message().unwrap_err(), DecodeError::Eof))
}
#[test]
fn read_async() {
use futures_lite::stream::StreamExt as _;
let fut = async move {
let data = b"hello\r\nworld\r\ntesting this\r\nand another thing\r\n".to_vec();
let mut reader = futures_lite::io::Cursor::new(data);
let out = AsyncDecoder::new(&mut reader).collect::<Vec<_>>().await;
let out = out
.into_iter()
.collect::<Result<Vec<_>, DecodeError>>()
.unwrap();
assert_eq!(out.len(), 4);
reader.set_position(0);
let mut dec = AsyncDecoder::new(reader);
for _ in 0..4 {
dec.read_message().await.unwrap();
}
assert!(matches!(
dec.read_message().await.unwrap_err(),
DecodeError::Eof
))
};
futures_lite::future::block_on(fut);
}
}