mirror of
https://github.com/theryangeary/choose
synced 2024-11-10 05:24:13 +00:00
Add custom BufReader to cut down on allocation time
This commit is contained in:
parent
dfc95865d4
commit
c81efcf42f
2 changed files with 29 additions and 5 deletions
11
src/main.rs
11
src/main.rs
|
@ -1,9 +1,10 @@
|
|||
use std::fs::File;
|
||||
use std::io::{self, BufRead, BufReader, Read, Write};
|
||||
use std::io::{self, Read, Write};
|
||||
use structopt::StructOpt;
|
||||
|
||||
mod choice;
|
||||
mod config;
|
||||
mod reader;
|
||||
use config::Config;
|
||||
|
||||
fn main() {
|
||||
|
@ -15,14 +16,14 @@ fn main() {
|
|||
None => Box::new(io::stdin()) as Box<dyn Read>,
|
||||
};
|
||||
|
||||
let buf = BufReader::new(read);
|
||||
let mut reader = reader::BufReader::new(read);
|
||||
let mut buffer = String::new();
|
||||
|
||||
let stdout = io::stdout();
|
||||
let lock = stdout.lock();
|
||||
let mut handle = io::BufWriter::new(lock);
|
||||
|
||||
let lines = buf.lines();
|
||||
for line in lines {
|
||||
while let Some(line) = reader.read_line(&mut buffer) {
|
||||
match line {
|
||||
Ok(l) => {
|
||||
for choice in &config.opt.choice {
|
||||
|
@ -30,7 +31,7 @@ fn main() {
|
|||
}
|
||||
match handle.write(b"\n") {
|
||||
Ok(_) => (),
|
||||
Err(e) => eprintln!("Failed to write to output: {}", e)
|
||||
Err(e) => eprintln!("Failed to write to output: {}", e),
|
||||
}
|
||||
}
|
||||
Err(e) => println!("Failed to read line: {}", e),
|
||||
|
|
23
src/reader.rs
Normal file
23
src/reader.rs
Normal file
|
@ -0,0 +1,23 @@
|
|||
use std::io::{self, prelude::*};
|
||||
|
||||
pub struct BufReader<R> {
|
||||
reader: io::BufReader<R>,
|
||||
}
|
||||
|
||||
impl<R: Read> BufReader<R> {
|
||||
pub fn new(f: R) -> Self {
|
||||
Self { reader: io::BufReader::new(f) }
|
||||
}
|
||||
|
||||
pub fn read_line<'buf>(
|
||||
&mut self,
|
||||
buffer: &'buf mut String,
|
||||
) -> Option<io::Result<&'buf mut String>> {
|
||||
buffer.clear();
|
||||
|
||||
self.reader
|
||||
.read_line(buffer)
|
||||
.map(|u| if u == 0 { None } else { Some(buffer) })
|
||||
.transpose()
|
||||
}
|
||||
}
|
Loading…
Reference in a new issue