use std::path::{Path, PathBuf};
use nucleo::Matcher;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Candidate {
pub path: PathBuf,
pub score: u16,
pub indices: Vec<u32>,
}
pub struct Fuzzy {
matcher: Matcher,
}
impl Default for Fuzzy {
fn default() -> Self {
Fuzzy::new()
}
}
impl Fuzzy {
pub fn new() -> Self {
Fuzzy {
matcher: Matcher::new(nucleo::Config::DEFAULT.match_paths()),
}
}
pub fn search(&mut self, paths: &[PathBuf], query: &str, limit: usize) -> Vec<Candidate> {
if query.trim().is_empty() {
return Vec::new();
}
let mut needle = Vec::new();
let needle = nucleo::Utf32Str::new(query, &mut needle);
let mut scored: Vec<Candidate> = paths
.iter()
.filter_map(|path| {
let display = path.to_str()?;
let mut buffer = Vec::new();
let haystack = nucleo::Utf32Str::new(display, &mut buffer);
let mut indices = Vec::new();
let score = self.matcher.fuzzy_indices(haystack, needle, &mut indices)?;
Some(Candidate {
path: path.clone(),
score,
indices,
})
})
.collect();
scored.sort_by(|a, b| {
b.score
.cmp(&a.score)
.then_with(|| path_len(&a.path).cmp(&path_len(&b.path)))
.then_with(|| a.path.cmp(&b.path))
});
scored.truncate(limit);
scored
}
}
fn path_len(path: &Path) -> usize {
path.to_str().map_or(usize::MAX, str::len)
}
#[cfg(test)]
mod tests {
use super::*;
fn paths() -> Vec<PathBuf> {
[
"README.md",
"docs/api/auth.md",
"docs/api/errors.md",
"docs/guides/setup.md",
"docs/guides/authentication-notes.md",
]
.iter()
.map(PathBuf::from)
.collect()
}
#[test]
fn a_query_matches_out_of_order_characters() {
let mut fuzzy = Fuzzy::new();
let found = fuzzy.search(&paths(), "dgs", 10);
assert!(found
.iter()
.any(|c| c.path == Path::new("docs/guides/setup.md")));
}
#[test]
fn the_shortest_path_wins_a_tie() {
let mut fuzzy = Fuzzy::new();
let found = fuzzy.search(&paths(), "auth", 10);
assert_eq!(found[0].path, PathBuf::from("docs/api/auth.md"));
}
#[test]
fn the_matched_characters_come_back_for_highlighting() {
let mut fuzzy = Fuzzy::new();
let found = fuzzy.search(&paths(), "auth", 10);
let candidate = &found[0];
let display = candidate.path.to_str().unwrap();
let matched: String = candidate
.indices
.iter()
.filter_map(|&at| display.chars().nth(at as usize))
.collect();
assert_eq!(matched.to_lowercase(), "auth");
}
#[test]
fn a_query_matching_nothing_returns_nothing() {
let mut fuzzy = Fuzzy::new();
assert!(fuzzy.search(&paths(), "zzzzz", 10).is_empty());
}
#[test]
fn an_empty_query_returns_nothing_rather_than_everything() {
let mut fuzzy = Fuzzy::new();
assert!(fuzzy.search(&paths(), "", 10).is_empty());
assert!(fuzzy.search(&paths(), " ", 10).is_empty());
}
#[test]
fn the_limit_is_respected() {
let mut fuzzy = Fuzzy::new();
assert_eq!(fuzzy.search(&paths(), "d", 2).len(), 2);
}
}