Skip to content

Commit

Permalink
Implement fuzzy matcher
Browse files Browse the repository at this point in the history
  • Loading branch information
lusingander committed Dec 13, 2024
1 parent 7c5647b commit 293889b
Show file tree
Hide file tree
Showing 3 changed files with 79 additions and 0 deletions.
26 changes: 26 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ rust-version = "1.79.0"
cargo_metadata = "0.19.1"
clap = { version = "4.5.23", features = ["derive"] }
console = "0.15.8"
fuzzy-matcher = "0.3.7"
laurier = "0.1.0"
ratatui = "0.29.0"
tui-input = "0.11.1"
52 changes: 52 additions & 0 deletions src/matcher.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
use fuzzy_matcher::{skim::SkimMatcherV2, FuzzyMatcher};

#[derive(Default)]
pub enum Matcher {
#[default]
Substring,
Fuzzy(Box<SkimMatcherV2>),
}

impl Matcher {
pub fn substring() -> Self {
Matcher::Substring
}

pub fn fuzzy() -> Self {
Matcher::Fuzzy(Box::default())
}

pub fn match_indices(&self, text: &str, pattern: &str) -> Option<Vec<usize>> {
match self {
Matcher::Substring => text
.find(pattern)
.map(|pos| (pos..pos + pattern.len()).collect()),
Matcher::Fuzzy(matcher) => matcher
.fuzzy_indices(text, pattern)
.map(|(_, indices)| indices),
}
}
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn test_matcher_substring() {
let matcher = Matcher::substring();
assert_eq!(matcher.match_indices("hello", "he"), Some(vec![0, 1]));
assert_eq!(matcher.match_indices("hello", "lo"), Some(vec![3, 4]));
assert_eq!(matcher.match_indices("hello", "ho"), None);
assert_eq!(matcher.match_indices("hello", "wr"), None);
}

#[test]
fn test_matcher_fuzzy() {
let matcher = Matcher::fuzzy();
assert_eq!(matcher.match_indices("hello", "he"), Some(vec![0, 1]));
assert_eq!(matcher.match_indices("hello", "lo"), Some(vec![3, 4]));
assert_eq!(matcher.match_indices("hello", "ho"), Some(vec![0, 4]));
assert_eq!(matcher.match_indices("hello", "wr"), None);
}
}

0 comments on commit 293889b

Please sign in to comment.