ltrait_scorer_nucleo/lib.rs
1//! # Example usage
2//! ```rust
3//! # use ltrait::{color_eyre::Result, Launcher};
4//! # use std::time::Duration;
5//! #
6//! # struct DummyUI;
7//! #
8//! # impl<'a> ltrait::UI<'a> for DummyUI {
9//! # type Context = ();
10//! #
11//! # async fn run<Cushion: 'a + Send>(
12//! # &self,
13//! # _: ltrait::launcher::batcher::Batcher<'a, Cushion, Self::Context>,
14//! # ) -> Result<Option<Cushion>> {
15//! # unimplemented!()
16//! # }
17//! # }
18//! #
19//! # fn main() -> Result<()> {
20//! #
21//! use ltrait_extra::scorer::ScorerExt as _;
22//! use ltrait_scorer_nucleo::{CaseMatching, Normalization};
23//!
24//! let launcher = Launcher::default()
25//! .set_ui(DummyUI, |c| unimplemented!())
26//! .add_raw_sorter(
27//! ltrait_scorer_nucleo::NucleoMatcher::new(
28//! false,
29//! CaseMatching::Smart,
30//! Normalization::Smart,
31//! )
32//! .into_sorter()
33//! );
34//! #
35//! # Ok(()) }
36//! ```
37
38use std::sync::{Arc, Mutex};
39
40use ltrait_extra::scorer::Scorer;
41pub use nucleo_matcher::pattern::{CaseMatching, Normalization, Pattern};
42use nucleo_matcher::{Config, Matcher, Utf32Str};
43
44pub struct Context {
45 pub match_string: String,
46}
47
48pub struct NucleoMatcher {
49 matcher: Arc<Mutex<Matcher>>,
50
51 case: CaseMatching,
52 normalization: Normalization,
53}
54
55impl Scorer for NucleoMatcher {
56 type Context = Context;
57
58 fn predicate_score(&self, ctx: &Self::Context, input: &str) -> u32 {
59 let pat = Pattern::parse(input, self.case, self.normalization);
60 pat.score(
61 Utf32Str::new(&ctx.match_string, &mut Vec::new()),
62 &mut self.matcher.lock().unwrap(),
63 )
64 .unwrap_or(0)
65 }
66}
67
68impl NucleoMatcher {
69 pub fn new(match_path: bool, case: CaseMatching, normalization: Normalization) -> Self {
70 let config = if match_path {
71 Config::DEFAULT.match_paths()
72 } else {
73 Config::DEFAULT
74 };
75
76 Self {
77 case,
78 normalization,
79 matcher: Arc::new(Mutex::new(Matcher::new(config))),
80 }
81 }
82}