| 1 |
use std::ops::DerefMut; |
| 2 |
|
| 3 |
use nucleo::pattern::{Atom, AtomKind, CaseMatching, Normalization}; |
| 4 |
use nucleo::Config; |
| 5 |
use parking_lot::Mutex; |
| 6 |
|
| 7 |
pub struct LazyMutex<T> { |
| 8 |
inner: Mutex<Option<T>>, |
| 9 |
init: fn() -> T, |
| 10 |
} |
| 11 |
|
| 12 |
impl<T> LazyMutex<T> { |
| 13 |
pub const fn new(init: fn() -> T) -> Self { |
| 14 |
Self { |
| 15 |
inner: Mutex::new(None), |
| 16 |
init, |
| 17 |
} |
| 18 |
} |
| 19 |
|
| 20 |
pub fn lock(&self) -> impl DerefMut<Target = T> + '_ { |
| 21 |
parking_lot::MutexGuard::map(self.inner.lock(), |val| val.get_or_insert_with(self.init)) |
| 22 |
} |
| 23 |
} |
| 24 |
|
| 25 |
pub static MATCHER: LazyMutex<nucleo::Matcher> = LazyMutex::new(nucleo::Matcher::default); |
| 26 |
|
| 27 |
|
| 28 |
|
| 29 |
|
| 30 |
|
| 31 |
pub fn fuzzy_match<T: AsRef<str>>( |
| 32 |
pattern: &str, |
| 33 |
items: impl IntoIterator<Item = T>, |
| 34 |
path: bool, |
| 35 |
) -> Vec<(T, u16)> { |
| 36 |
let mut matcher = MATCHER.lock(); |
| 37 |
matcher.config = Config::DEFAULT; |
| 38 |
if path { |
| 39 |
matcher.config.set_match_paths(); |
| 40 |
} |
| 41 |
let pattern = Atom::new( |
| 42 |
pattern, |
| 43 |
CaseMatching::Smart, |
| 44 |
Normalization::Smart, |
| 45 |
AtomKind::Fuzzy, |
| 46 |
false, |
| 47 |
); |
| 48 |
pattern.match_list(items, &mut matcher) |
| 49 |
} |