diff options
author | Ryan Geary <rtgnj42@gmail.com> | 2019-10-09 18:23:02 -0400 |
---|---|---|
committer | Ryan Geary <rtgnj42@gmail.com> | 2019-10-09 18:23:02 -0400 |
commit | f722cbcbbb61ba46c5d6e63d543a834c65a51751 (patch) | |
tree | 86e0fb28d058cd36f9f8d960ac6ee810eae9b7bc | |
parent | 09ddbb4f659076e08b2e85fb65fea97623178eb7 (diff) |
Remove repeated Regex compilation
-rw-r--r-- | src/choice.rs | 15 | ||||
-rw-r--r-- | src/main.rs | 14 |
2 files changed, 16 insertions, 13 deletions
diff --git a/src/choice.rs b/src/choice.rs index eb20dc4..65e1acd 100644 --- a/src/choice.rs +++ b/src/choice.rs @@ -219,22 +219,13 @@ impl Choice { &self, line: &String, opt: &Opt, + re: &Regex, 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> { - 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); - }); - + fn get_choice_slice<'a>(&self, line: &'a String, opt: &Opt, re: &Regex) -> Vec<&'a str> { let words = re .split(line) .into_iter() diff --git a/src/main.rs b/src/main.rs index b3bdc29..d6c7c50 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,5 +1,7 @@ +use regex::Regex; use std::fs::File; use std::io::{self, BufRead, BufReader, Read, Write}; +use std::process; use structopt::StructOpt; mod choice; @@ -18,12 +20,22 @@ fn main() { let lock = stdout.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(); for line in lines { match line { Ok(l) => { for choice in &opt.choice { - choice.print_choice(&l, &opt, &mut handle); + choice.print_choice(&l, &opt, &re, &mut handle); } writeln!(handle, ""); } |