Skip to content

Commit 9df7978

Browse files
committed
refactor: lossy_reader
1 parent 5a79bdb commit 9df7978

File tree

2 files changed

+20
-27
lines changed

2 files changed

+20
-27
lines changed

src/bin/code-minimap/main.rs

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
mod cli;
22
use std::{
3+
fs::File,
34
io::{self, BufRead},
45
process,
56
};
@@ -28,8 +29,8 @@ fn try_main() -> anyhow::Result<()> {
2829
None => {
2930
let stdin = io::stdin();
3031
let reader: Box<dyn BufRead> = match &opt.file {
31-
Some(path) => Box::new(LossyReader::open(path)?),
32-
None => Box::new(stdin.lock()),
32+
Some(path) => Box::new(LossyReader::new(File::open(path)?)),
33+
None => Box::new(LossyReader::new(stdin)),
3334
};
3435
code_minimap::print(reader, opt.hscale, opt.vscale, opt.padding)?;
3536
}

src/lossy_reader.rs

Lines changed: 17 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -1,44 +1,36 @@
1-
use std::{
2-
fs::File,
3-
io::{self, BufRead, BufReader, Read},
4-
path::Path,
5-
};
1+
use std::io::{self, BufRead, BufReader, Read};
62

7-
pub struct LossyReader {
8-
reader: BufReader<File>,
3+
pub struct LossyReader<R> {
4+
inner: BufReader<R>,
95
}
106

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+
}
1712
}
1813
}
1914

20-
impl Read for LossyReader {
15+
impl<R: Read> Read for LossyReader<R> {
2116
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
22-
self.reader.read(buf)
17+
self.inner.read(buf)
2318
}
2419
}
2520

26-
impl BufRead for LossyReader {
21+
impl<R: Read> BufRead for LossyReader<R> {
2722
fn fill_buf(&mut self) -> io::Result<&[u8]> {
28-
self.reader.fill_buf()
23+
self.inner.fill_buf()
2924
}
3025

3126
fn consume(&mut self, amt: usize) {
32-
self.reader.consume(amt)
27+
self.inner.consume(amt)
3328
}
3429

3530
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)
4335
}
4436
}

0 commit comments

Comments
 (0)