|
1 | | -use std::{ |
2 | | - fs::File, |
3 | | - io::{self, BufRead, BufReader, Read}, |
4 | | - path::Path, |
5 | | -}; |
| 1 | +use std::io::{self, BufRead, BufReader, Read}; |
6 | 2 |
|
7 | | -pub struct LossyReader { |
8 | | - reader: BufReader<File>, |
| 3 | +pub struct LossyReader<R> { |
| 4 | + inner: BufReader<R>, |
9 | 5 | } |
10 | 6 |
|
11 | | -impl LossyReader { |
12 | | - pub fn open(path: impl AsRef<Path>) -> io::Result<Self> { |
13 | | - let file = File::open(path)?; |
14 | | - let reader = BufReader::new(file); |
15 | | - |
16 | | - Ok(Self { reader }) |
| 7 | +impl<R: Read> LossyReader<R> { |
| 8 | + pub fn new(inner: R) -> Self { |
| 9 | + Self { |
| 10 | + inner: BufReader::new(inner), |
| 11 | + } |
17 | 12 | } |
18 | 13 | } |
19 | 14 |
|
20 | | -impl Read for LossyReader { |
| 15 | +impl<R: Read> Read for LossyReader<R> { |
21 | 16 | fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { |
22 | | - self.reader.read(buf) |
| 17 | + self.inner.read(buf) |
23 | 18 | } |
24 | 19 | } |
25 | 20 |
|
26 | | -impl BufRead for LossyReader { |
| 21 | +impl<R: Read> BufRead for LossyReader<R> { |
27 | 22 | fn fill_buf(&mut self) -> io::Result<&[u8]> { |
28 | | - self.reader.fill_buf() |
| 23 | + self.inner.fill_buf() |
29 | 24 | } |
30 | 25 |
|
31 | 26 | fn consume(&mut self, amt: usize) { |
32 | | - self.reader.consume(amt) |
| 27 | + self.inner.consume(amt) |
33 | 28 | } |
34 | 29 |
|
35 | 30 | fn read_line(&mut self, buf: &mut String) -> std::io::Result<usize> { |
36 | | - let mut append_buf = Vec::new(); |
37 | | - let res = self.read_until(0x0a, &mut append_buf); |
38 | | - if let Err(err) = res { |
39 | | - return Err(err); |
40 | | - } |
41 | | - buf.push_str(&String::from_utf8_lossy(&append_buf)); |
42 | | - Ok(buf.len()) |
| 31 | + let mut bytes = Vec::new(); |
| 32 | + let len = self.read_until(b'\n', &mut bytes)?; |
| 33 | + buf.push_str(&String::from_utf8_lossy(&bytes)); |
| 34 | + Ok(len) |
43 | 35 | } |
44 | 36 | } |
0 commit comments