Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add method to Atom that preserves the index of the passed list #45

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
46 changes: 46 additions & 0 deletions matcher/src/pattern.rs
Original file line number Diff line number Diff line change
Expand Up @@ -395,6 +395,29 @@ impl Atom {
items.sort_by_key(|(_, score)| Reverse(*score));
items
}

/// Same as `match_list` expect that it returns the index appended to the tuple
/// Return tuple is (Match, score, index)
pub fn match_list_with_index<T: AsRef<str>>(
&self,
items: impl IntoIterator<Item = T>,
matcher: &mut Matcher,
) -> Vec<(T, u16, usize)> {
if self.needle.is_empty() {
return items.into_iter().map(|item| (item, 0, 0)).collect();
}
let mut buf = Vec::new();
let mut items: Vec<_> = items
.into_iter()
.enumerate()
.filter_map(|(index, item)| {
self.score(Utf32Str::new(item.as_ref(), &mut buf), matcher)
.map(|score| (item, score, index))
})
.collect();
items.sort_by_key(|(_, score, _)| Reverse(*score));
items
}
}

fn pattern_atoms(pattern: &str) -> impl Iterator<Item = &str> + '_ {
Expand Down Expand Up @@ -478,6 +501,29 @@ impl Pattern {
items
}

/// Same as `match_list` expect that it returns the index appended to the tuple
/// Return tuple is (Match, score, index)
pub fn match_list_with_index<T: AsRef<str>>(
&self,
items: impl IntoIterator<Item = T>,
matcher: &mut Matcher,
) -> Vec<(T, u32, usize)> {
if self.atoms.is_empty() {
return items.into_iter().map(|item| (item, 0, 0)).collect();
}
let mut buf = Vec::new();
let mut items: Vec<_> = items
.into_iter()
.enumerate()
.filter_map(|(index, item)| {
self.score(Utf32Str::new(item.as_ref(), &mut buf), matcher)
.map(|score| (item, score, index))
})
.collect();
items.sort_by_key(|(_, score, _)| Reverse(*score));
items
}

/// Matches this pattern against `haystack` (using the allocation and configuration
/// from `matcher`) and calculates a ranking score. See the [`Matcher`].
/// Documentation for more details.
Expand Down