From ffd8e9b12d9e12a51c5858259d1fd07a29568620 Mon Sep 17 00:00:00 2001 From: graelo Date: Sat, 13 Mar 2021 18:51:31 +0100 Subject: [PATCH] refactor: follow clippy suggestions --- src/alphabets.rs | 4 ++-- src/bridge.rs | 51 ++++++++++++------------------------------------ src/main.rs | 4 ++-- src/model.rs | 20 +++++++++---------- src/process.rs | 2 +- src/regexes.rs | 4 ++-- src/ui.rs | 22 +++++++++------------ 7 files changed, 38 insertions(+), 69 deletions(-) diff --git a/src/alphabets.rs b/src/alphabets.rs index e1e7aaa..aa2d6ad 100644 --- a/src/alphabets.rs +++ b/src/alphabets.rs @@ -6,7 +6,7 @@ use crate::error; /// /// Keep in mind letters 'n' and 'y' are systematically removed at runtime to /// prevent conflict with navigation and yank/copy keys. -const ALPHABETS: [(&'static str, &'static str); 21] = [ +const ALPHABETS: [(&str, &str); 21] = [ // ("abcd", "abcd"), ("qwerty", "asdfqwerzxcvjklmiuopghtybn"), ("qwerty-homerow", "asdfjklgh"), @@ -47,7 +47,7 @@ pub fn parse_alphabet(src: &str) -> Result { match alphabet_pair { Some((_name, letters)) => { let letters = letters.replace(&['n', 'N', 'y', 'Y'][..], ""); - Ok(Alphabet(letters.to_string())) + Ok(Alphabet(letters)) } None => Err(error::ParseError::UnknownAlphabet), } diff --git a/src/bridge.rs b/src/bridge.rs index 45e4304..4cbd500 100644 --- a/src/bridge.rs +++ b/src/bridge.rs @@ -44,11 +44,8 @@ impl BridgeOpt { options: &HashMap, ) -> Result<(), error::ParseError> { for (name, value) in options { - match name.as_ref() { - "@copyrat-capture" => { - self.capture_region = tmux::CaptureRegion::from_str(&value)?; - } - _ => (), + if let "@copyrat-capture" = name.as_ref() { + self.capture_region = tmux::CaptureRegion::from_str(&value)?; } } @@ -94,41 +91,17 @@ fn main() -> Result<(), error::ParseError> { // buffer if it was uppercased. // TODO: consider getting rid of multi-selection mode. - // Execute a command on each group of selections (normal and uppercased). - let (normal_selections, uppercased_selections): (Vec<(String, bool)>, Vec<(String, bool)>) = - selections - .into_iter() - .partition(|(_text, uppercased)| !*uppercased); + match selections { + None => return Ok(()), + Some((text, uppercased)) => { + let args = vec!["set-buffer", &text]; + process::execute("tmux", &args)?; - let buffer_selections: String = normal_selections - .into_iter() - .map(|(text, _)| text) - .collect::>() - .join("\n"); - - if buffer_selections.len() > 0 { - let args = vec!["set-buffer", &buffer_selections]; - // Simply execute the command as is, and let the program crash on - // potential errors because it is not our responsibility. - process::execute("tmux", &args).unwrap(); - } - - let buffer_selections: String = uppercased_selections - .into_iter() - .map(|(text, _)| text) - .collect::>() - .join("\n"); - - if buffer_selections.len() > 0 { - let args = vec!["set-buffer", &buffer_selections]; - // Simply execute the command as is, and let the program crash on - // potential errors because it is not our responsibility. - process::execute("tmux", &args).unwrap(); - - let args = vec!["paste-buffer", "-t", active_pane.id.as_str()]; - // Simply execute the command as is, and let the program crash on - // potential errors because it is not our responsibility. - process::execute("tmux", &args).unwrap(); + if uppercased { + let args = vec!["paste-buffer", "-t", active_pane.id.as_str()]; + process::execute("tmux", &args)?; + } + } } Ok(()) diff --git a/src/main.rs b/src/main.rs index 2cee8da..ad08248 100644 --- a/src/main.rs +++ b/src/main.rs @@ -16,7 +16,7 @@ fn main() { handle.read_to_string(&mut buffer).unwrap(); // Execute copyrat over the buffer (will take control over stdout). - // This returns the selected matches. + // This returns the selected matche. let selection: Option<(String, bool)> = run(buffer, &opt); // Early exit, signaling no selections were found. @@ -37,7 +37,7 @@ fn main() { .open(target) .expect("Unable to open the target file"); - file.write(text.as_bytes()).unwrap(); + file.write_all(text.as_bytes()).unwrap(); } } } diff --git a/src/model.rs b/src/model.rs index 8d4d283..8338370 100644 --- a/src/model.rs +++ b/src/model.rs @@ -12,8 +12,8 @@ pub struct Model<'a> { pub lines: Vec<&'a str>, alphabet: &'a Alphabet, use_all_patterns: bool, - named_patterns: &'a Vec, - custom_patterns: &'a Vec, + named_patterns: &'a [NamedPattern], + custom_patterns: &'a [String], pub reverse: bool, } @@ -22,8 +22,8 @@ impl<'a> Model<'a> { buffer: &'a str, alphabet: &'a Alphabet, use_all_patterns: bool, - named_patterns: &'a Vec, - custom_patterns: &'a Vec, + named_patterns: &'a [NamedPattern], + custom_patterns: &'a [String], reverse: bool, ) -> Model<'a> { let lines = buffer.split('\n').collect(); @@ -112,7 +112,7 @@ impl<'a> Model<'a> { loop { let chunk_matches = all_regexes .iter() - .filter_map(|(&ref name, regex)| match regex.find_iter(chunk).nth(0) { + .filter_map(|(&ref name, regex)| match regex.find_iter(chunk).next() { Some(m) => Some((name, regex, m)), None => None, }) @@ -164,7 +164,7 @@ impl<'a> Model<'a> { /// If `unique` is `true`, all duplicate matches will have the same hint. /// For copying matched text, this seems easier and more natural. /// If `unique` is `false`, duplicate matches will have their own hint. - fn associate_hints(&self, raw_matches: &Vec>, unique: bool) -> Vec> { + fn associate_hints(&self, raw_matches: &[RawMatch<'a>], unique: bool) -> Vec> { let hints = self.alphabet.make_hints(raw_matches.len()); let mut hints_iter = hints.iter(); @@ -175,11 +175,11 @@ impl<'a> Model<'a> { let mut known: collections::HashMap<&str, &str> = collections::HashMap::new(); for raw_mat in raw_matches { - let hint: &str = known.entry(raw_mat.text).or_insert( + let hint: &str = known.entry(raw_mat.text).or_insert_with(|| { hints_iter .next() - .expect("We should have as many hints as necessary, even invisible ones."), - ); + .expect("We should have as many hints as necessary, even invisible ones.") + }); result.push(Match { x: raw_mat.x, @@ -211,7 +211,7 @@ impl<'a> Model<'a> { /// Builds a `SequenceTrie` that helps determine if a sequence of keys /// entered by the user corresponds to a match. This kind of lookup /// directly returns a reference to the corresponding `Match` if any. - pub fn build_lookup_trie(matches: &'a Vec>) -> SequenceTrie { + pub fn build_lookup_trie(matches: &'a [Match<'a>]) -> SequenceTrie { let mut trie = SequenceTrie::new(); for (index, mat) in matches.iter().enumerate() { diff --git a/src/process.rs b/src/process.rs index af6a5f1..5ef5825 100644 --- a/src/process.rs +++ b/src/process.rs @@ -4,7 +4,7 @@ use crate::error::ParseError; /// Execute an arbitrary Unix command and return the stdout as a `String` if /// successful. -pub fn execute(command: &str, args: &Vec<&str>) -> Result { +pub fn execute(command: &str, args: &[&str]) -> Result { let output = Command::new(command).args(args).output()?; if !output.status.success() { diff --git a/src/regexes.rs b/src/regexes.rs index 89001b0..4c0fd4d 100644 --- a/src/regexes.rs +++ b/src/regexes.rs @@ -1,13 +1,13 @@ use crate::error; -pub const EXCLUDE_PATTERNS: [(&'static str, &'static str); 1] = +pub const EXCLUDE_PATTERNS: [(&str, &str); 1] = [("ansi_colors", r"[[:cntrl:]]\[([0-9]{1,2};)?([0-9]{1,2})?m")]; /// Holds all the regex patterns that are currently supported. /// /// The email address was obtained at https://www.regular-expressions.info/email.html. /// Others were obtained from Ferran Basora. -pub const PATTERNS: [(&'static str, &'static str); 15] = [ +pub const PATTERNS: [(&str, &str); 15] = [ ("markdown-url", r"\[[^]]*\]\(([^)]+)\)"), ( "url", diff --git a/src/ui.rs b/src/ui.rs index dc402a9..06d3db1 100644 --- a/src/ui.rs +++ b/src/ui.rs @@ -82,10 +82,8 @@ impl<'a> Ui<'a> { } else { self.focus_index -= 1; } - } else { - if self.focus_index > 0 { - self.focus_index -= 1; - } + } else if self.focus_index > 0 { + self.focus_index -= 1; } let new_index = self.focus_index; (old_index, new_index) @@ -101,10 +99,8 @@ impl<'a> Ui<'a> { } else { self.focus_index += 1; } - } else { - if self.focus_index < self.matches.len() - 1 { - self.focus_index += 1; - } + } else if self.focus_index < self.matches.len() - 1 { + self.focus_index += 1; } let new_index = self.focus_index; (old_index, new_index) @@ -137,10 +133,10 @@ impl<'a> Ui<'a> { /// - This writes directly on the writer, avoiding extra allocation. fn render_base_text( stdout: &mut dyn io::Write, - lines: &Vec<&str>, - line_offsets: &Vec, + lines: &[&str], + line_offsets: &[usize], colors: &UiColors, - ) -> () { + ) { write!( stdout, "{bg_color}{fg_color}", @@ -361,7 +357,7 @@ impl<'a> Ui<'a> { /// # Note /// Multibyte characters are taken into account, so that the Match's `text` /// and `hint` are rendered in their proper position. - fn full_render(&self, stdout: &mut dyn io::Write) -> () { + fn full_render(&self, stdout: &mut dyn io::Write) { // 1. Trim all lines and render non-empty ones. Ui::render_base_text( stdout, @@ -557,7 +553,7 @@ impl<'a> Ui<'a> { /// Compute each line's actual y offset if displayed in a terminal of width /// `term_width`. -fn get_line_offsets(lines: &Vec<&str>, term_width: u16) -> Vec { +fn get_line_offsets(lines: &[&str], term_width: u16) -> Vec { lines .iter() .scan(0, |offset, &line| {