Remove repeated Regex compilation

This commit is contained in:
Ryan Geary 2019-10-09 18:23:02 -04:00
parent 09ddbb4f65
commit f722cbcbbb
2 changed files with 16 additions and 13 deletions

View file

@ -219,22 +219,13 @@ impl Choice {
&self, &self,
line: &String, line: &String,
opt: &Opt, opt: &Opt,
re: &Regex,
handle: &mut BufWriter<std::io::StdoutLock>, handle: &mut BufWriter<std::io::StdoutLock>,
) { ) {
write!(handle, "{}", self.get_choice_slice(line, opt).join(" ")); write!(handle, "{}", self.get_choice_slice(line, opt, re).join(" "));
} }
fn get_choice_slice<'a>(&self, line: &'a String, opt: &Opt) -> Vec<&'a str> { fn get_choice_slice<'a>(&self, line: &'a String, opt: &Opt, re: &Regex) -> Vec<&'a str> {
let re = Regex::new(match &opt.field_separator {
Some(s) => s,
None => "[[:space:]]",
})
.unwrap_or_else(|e| {
eprintln!("Failed to compile regular expression: {}", e);
// Exit code of 1 means failed to compile field_separator regex
process::exit(1);
});
let words = re let words = re
.split(line) .split(line)
.into_iter() .into_iter()

View file

@ -1,5 +1,7 @@
use regex::Regex;
use std::fs::File; use std::fs::File;
use std::io::{self, BufRead, BufReader, Read, Write}; use std::io::{self, BufRead, BufReader, Read, Write};
use std::process;
use structopt::StructOpt; use structopt::StructOpt;
mod choice; mod choice;
@ -18,12 +20,22 @@ fn main() {
let lock = stdout.lock(); let lock = stdout.lock();
let mut handle = io::BufWriter::new(lock); let mut handle = io::BufWriter::new(lock);
let re = Regex::new(match &opt.field_separator {
Some(s) => s,
None => "[[:space:]]",
})
.unwrap_or_else(|e| {
eprintln!("Failed to compile regular expression: {}", e);
// Exit code of 1 means failed to compile field_separator regex
process::exit(1);
});
let lines = buf.lines(); let lines = buf.lines();
for line in lines { for line in lines {
match line { match line {
Ok(l) => { Ok(l) => {
for choice in &opt.choice { for choice in &opt.choice {
choice.print_choice(&l, &opt, &mut handle); choice.print_choice(&l, &opt, &re, &mut handle);
} }
writeln!(handle, ""); writeln!(handle, "");
} }