ncp_engine/lib.rs
1//! # Nucleo-picker-engine
2//!
3//! The `ncp-engine` crate is a fork of the [nucleo](https://docs.rs/nucleo) crate.
4//! It is not recommended for general use. This fork mainly exists to meet the specific
5//! requirements of [`nucleo-picker`](https://docs.rs/nucleo-picker).
6//!
7//! `ncp-engine` implements a high level matcher API that provides a performant
8//! parallel matcher worker threadpool. It is designed to allow integrating a `fzf`-like
9//! fuzzy matcher into a TUI application.
10//!
11//! For a fully-featured TUI implementation, see [nucleo-picker](htpps://docs.rs/nucleo-picker).
12//!
13//! Matching runs in a background threadpool while providing a snapshot of the last
14//! complete match on request. That means the matcher can update the results live while
15//! the user is typing, while never blocking the main UI thread (beyond a user provided
16//! timeout). Nucleo also supports fully concurrent streaming of input items. Insertion
17//! is lock-free and wait-free after the destination bucket has been allocated; the first
18//! insertion into a bucket may wait for another thread to finish allocating it.
19//!
20//! The [`Nucleo`] struct serves as the main API entrypoint for this crate.
21
22#![deny(missing_docs)]
23
24use std::ops::{Bound, RangeBounds};
25use std::sync::Arc;
26use std::sync::atomic::{self, AtomicBool, Ordering};
27use std::time::Duration;
28
29use parking_lot::Mutex;
30use rayon::ThreadPool;
31
32use crate::pattern::MultiPattern;
33pub use crate::worker::MatchListConfig;
34use crate::worker::{RunOutcome, Worker};
35pub use ncp_matcher::{Config, Matcher, Utf32Str, Utf32String, chars};
36
37mod boxcar;
38mod par_sort;
39pub mod pattern;
40mod worker;
41
42#[cfg(test)]
43mod tests;
44
45/// A match candidate stored in a [`Nucleo`] worker.
46pub struct Item<'a, T> {
47 /// A reference to the underlying item provided to the matcher.
48 pub data: &'a T,
49 /// The representation of the data within the matcher.
50 pub matcher_columns: &'a [Utf32String],
51}
52
53/// A detached handle to a match candidate.
54///
55/// Unlike an [`Item`], which has a lifetime tied to the [`Snapshot`] or [`Injector`] from which it was
56/// created, a [`DetachedItem`] owns a handle to the underlying data and will persist even if the original
57/// [`Nucleo`] matcher has been dropped.
58///
59/// Similarly to an [injector](Injector), holding this handle will prevent the underlying data
60/// from being dropped. This handle is internally reference counted and can be cloned cheaply.
61///
62/// This handle implements [`PartialEq`] regardless of the value `T`. Equality is tested by checking that
63/// both items originate from the same matcher and that the internal indices are the same.
64pub struct DetachedItem<T> {
65 items: Arc<boxcar::Vec<T>>,
66 // this index is guaranteed to be valid for self.items
67 idx: u32,
68}
69
70impl<T> DetachedItem<T> {
71 unsafe fn new(items: &Arc<boxcar::Vec<T>>, idx: u32) -> Self {
72 Self {
73 items: Arc::clone(items),
74 idx,
75 }
76 }
77
78 /// Get the corresponding item.
79 pub fn item(&self) -> Item<'_, T> {
80 unsafe { self.items.get_unchecked(self.idx) }
81 }
82
83 /// Get the raw underlying index.
84 ///
85 /// This index is guaranteed to be valid for the snapshot or injector from which this
86 /// [`DetachedItem`] was originally constructed.
87 pub fn idx(&self) -> u32 {
88 self.idx
89 }
90}
91
92impl<T> PartialEq for DetachedItem<T> {
93 fn eq(&self, other: &Self) -> bool {
94 self.idx == other.idx && Arc::ptr_eq(&self.items, &other.items)
95 }
96}
97
98impl<T> Clone for DetachedItem<T> {
99 fn clone(&self) -> Self {
100 Self {
101 items: Arc::clone(&self.items),
102 idx: self.idx,
103 }
104 }
105}
106
107/// A handle that allows adding new items to a [`Nucleo`] worker.
108///
109/// An `Injector` is internally reference counted and can be cheaply
110/// cloned and sent across threads.
111pub struct Injector<T> {
112 inner: Arc<InjectorInner<T>>,
113}
114
115struct InjectorInner<T> {
116 items: Arc<boxcar::Vec<T>>,
117 notify: Arc<dyn Fn() + Sync + Send>,
118}
119
120impl<T> Clone for Injector<T> {
121 fn clone(&self) -> Self {
122 Self {
123 inner: Arc::clone(&self.inner),
124 }
125 }
126}
127
128impl<T> Injector<T> {
129 /// Appends an element to the list of match candidates.
130 ///
131 /// This function is lock-free and wait-free after the destination bucket has been allocated.
132 /// The first insertion into a bucket may wait for another thread to finish allocating it. The
133 /// returned `u32` is the internal index which has been assigned to the provided value and is
134 /// guaranteed to be valid unless [`Nucleo::restart`] has been called.
135 ///
136 /// The `fill_columns` closure is called to generate the representation of the pushed value
137 /// within the matcher engine. The first argument is a reference to the provided value, and the
138 /// second argument is a slice where each entry corresponds to a column within the [`Nucleo`]
139 /// instance from which this `Injector` was created.
140 ///
141 /// ## Example
142 /// If the matcher has exactly one column and the item type `T` is a `String`, an appropriate
143 /// `fill_columns` closure might look like
144 /// ```
145 /// # use ncp_engine::Utf32String;
146 /// let fill_columns = |s: &String, cols: &mut [Utf32String]| {
147 /// cols[0] = (&**s).into();
148 /// };
149 /// ```
150 pub fn push(&self, value: T, fill_columns: impl FnOnce(&T, &mut [Utf32String])) -> u32 {
151 let idx = self.inner.items.push(value, fill_columns);
152 (self.inner.notify)();
153 idx
154 }
155
156 /// Appends multiple elements to the list of matched items. Insertion is lock-free and
157 /// wait-free after the destination buckets have been allocated. The first insertion into a
158 /// bucket may wait for another thread to finish allocating it.
159 ///
160 /// You should favor this function over `push` if at least one of the following is true:
161 /// - The number of items you're adding can be computed beforehand and is typically larger
162 /// than 1k
163 /// - You're able to batch incoming items
164 /// - You're adding items from multiple threads concurrently (this function results in less
165 /// contention)
166 pub fn extend<I>(&self, values: I, fill_columns: impl Fn(&T, &mut [Utf32String]))
167 where
168 I: IntoIterator<Item = T>,
169 {
170 self.inner.items.extend(values, fill_columns);
171 (self.inner.notify)();
172 }
173
174 /// Returns the total number of items injected in the matcher.
175 ///
176 /// This may not match the number of items in the match snapshot if the matcher
177 /// is still running.
178 pub fn injected_items(&self) -> u32 {
179 self.inner.items.count()
180 }
181
182 /// Returns a reference to the item at the given index.
183 #[inline]
184 pub fn get_item(&self, index: u32) -> Option<Item<'_, T>> {
185 self.inner.items.get(index)
186 }
187
188 /// Returns a reference to the item at the given index without checking that the index is valid.
189 ///
190 /// # Safety
191 ///
192 /// Item at `index` must be initialized. That means you must have observed
193 /// `push` returning this value or `get` returning `Some` for this value.
194 /// Just because a later index is initialized doesn't mean that this index
195 /// is initialized
196 #[inline]
197 pub unsafe fn get_item_unchecked(&self, index: u32) -> Item<'_, T> {
198 unsafe { self.inner.items.get_unchecked(index) }
199 }
200
201 /// Returns the detached item at the given index.
202 #[inline]
203 pub fn get_detached_item(&self, index: u32) -> Option<DetachedItem<T>> {
204 self.inner
205 .items
206 .is_valid(index)
207 .then(|| unsafe { DetachedItem::new(&self.inner.items, index) })
208 }
209
210 /// Returns the detached item at the given index without checking that the index is valid.
211 ///
212 /// # Safety
213 ///
214 /// Item at `index` must be initialized. That means you must have observed
215 /// `push` returning this value or `get` returning `Some` for this value.
216 /// Just because a later index is initialized doesn't mean that this index
217 /// is initialized
218 #[inline]
219 pub unsafe fn get_detached_item_unchecked(&self, index: u32) -> DetachedItem<T> {
220 unsafe { DetachedItem::new(&self.inner.items, index) }
221 }
222}
223
224/// A successful match computed by the [`Nucleo`] match.
225#[derive(PartialEq, Eq, Debug, Clone, Copy)]
226pub struct Match {
227 /// The score of the match.
228 pub score: u32,
229 /// The index of the match.
230 ///
231 /// The index is guaranteed to correspond to a valid item within the matcher and within the
232 /// same snapshot. Note that indices are invalidated if the matcher engine has been
233 /// [restarted](Nucleo::restart).
234 pub idx: u32,
235}
236
237/// The status of a [`Nucleo`] worker after a match.
238#[derive(PartialEq, Eq, Debug, Clone, Copy)]
239pub struct Status {
240 /// Whether the current snapshot has changed.
241 pub changed: bool,
242 /// Whether the matcher is still processing in the background.
243 pub running: bool,
244}
245
246/// A representation of the results of a [`Nucleo`] worker after finishing a
247/// [`tick`](Nucleo::tick).
248pub struct Snapshot<T> {
249 item_count: u32,
250 matches: Vec<Match>,
251 pattern: MultiPattern,
252 items: Arc<boxcar::Vec<T>>,
253}
254
255impl<T: Sync + Send + 'static> Snapshot<T> {
256 fn clear(&mut self, new_items: Arc<boxcar::Vec<T>>) {
257 self.item_count = 0;
258 self.matches.clear();
259 self.items = new_items;
260 }
261
262 fn update(&mut self, worker: &Worker<T>) {
263 self.item_count = worker.item_count();
264 self.pattern.clone_from(&worker.pattern);
265 self.matches.clone_from(&worker.matches);
266 if !Arc::ptr_eq(&worker.items, &self.items) {
267 self.items = worker.items.clone();
268 }
269 }
270
271 /// Returns that total number of items
272 pub fn item_count(&self) -> u32 {
273 self.item_count
274 }
275
276 /// Returns the pattern which items were matched against
277 pub fn pattern(&self) -> &MultiPattern {
278 &self.pattern
279 }
280
281 /// Returns that number of items that matched the pattern
282 pub fn matched_item_count(&self) -> u32 {
283 self.matches.len() as u32
284 }
285
286 /// Returns an iterator over the items that correspond to a subrange of
287 /// all the matches in this snapshot.
288 ///
289 /// # Panics
290 /// Panics if `range` has a range bound that is larger than
291 /// the matched item count
292 pub fn matched_items(
293 &self,
294 range: impl RangeBounds<u32>,
295 ) -> impl ExactSizeIterator<Item = Item<'_, T>> + DoubleEndedIterator + '_ {
296 // TODO: use TAIT
297 let start = match range.start_bound() {
298 Bound::Included(&start) => start as usize,
299 Bound::Excluded(&start) => start as usize + 1,
300 Bound::Unbounded => 0,
301 };
302 let end = match range.end_bound() {
303 Bound::Included(&end) => end as usize + 1,
304 Bound::Excluded(&end) => end as usize,
305 Bound::Unbounded => self.matches.len(),
306 };
307 self.matches[start..end]
308 .iter()
309 .map(|&m| unsafe { self.items.get_unchecked(m.idx) })
310 }
311
312 /// Returns a reference to the item at the given index.
313 ///
314 /// Returns `None` if the given `index` is not initialized. This function
315 /// is only guarteed to return `Some` for item indices that can be found in
316 /// the `matches` of this struct. Both smaller and larger indices may return
317 /// `None`.
318 #[inline]
319 pub fn get_item(&self, index: u32) -> Option<Item<'_, T>> {
320 self.items.get(index)
321 }
322
323 /// Returns a reference to the item at the given index.
324 ///
325 /// # Safety
326 ///
327 /// Item at `index` must be initialized. That means you must have observed a
328 /// match with the corresponding index in this exact snapshot. Observing
329 /// a higher index is not enough as item indices can be non-contigously
330 /// initialized
331 #[inline]
332 pub unsafe fn get_item_unchecked(&self, index: u32) -> Item<'_, T> {
333 unsafe { self.items.get_unchecked(index) }
334 }
335
336 /// Returns the detached item at the given index.
337 #[inline]
338 pub fn get_detached_item(&self, index: u32) -> Option<DetachedItem<T>> {
339 self.items
340 .is_valid(index)
341 .then(|| unsafe { DetachedItem::new(&self.items, index) })
342 }
343
344 /// Returns the detached item at the given index without checking that the index is valid.
345 ///
346 /// # Safety
347 ///
348 /// Item at `index` must be initialized. That means you must have observed
349 /// `push` returning this value or `get` returning `Some` for this value.
350 /// Just because a later index is initialized doesn't mean that this index
351 /// is initialized
352 #[inline]
353 pub unsafe fn get_detached_item_unchecked(&self, index: u32) -> DetachedItem<T> {
354 unsafe { DetachedItem::new(&self.items, index) }
355 }
356
357 /// Returns the matches corresponding to this snapshot.
358 #[inline]
359 pub fn matches(&self) -> &[Match] {
360 &self.matches
361 }
362
363 /// A convenience function to return the [`Item`] corresponding to the
364 /// `n`th match.
365 ///
366 /// Returns `None` if `n` is greater than or equal to the match count.
367 #[inline]
368 pub fn get_matched_item(&self, n: u32) -> Option<Item<'_, T>> {
369 // SAFETY: A match index is guaranteed to corresponding to a valid global index in this
370 // snapshot.
371 unsafe { Some(self.get_item_unchecked(self.matches.get(n as usize)?.idx)) }
372 }
373
374 /// A convenience function to return the [`DetachedItem`] corresponding to the
375 /// `n`th match.
376 ///
377 /// Returns `None` if `n` is greater than or equal to the match count.
378 #[inline]
379 pub fn get_matched_detached_item(&self, n: u32) -> Option<DetachedItem<T>> {
380 // SAFETY: A match index is guaranteed to corresponding to a valid global index in this
381 // snapshot.
382 unsafe { Some(self.get_detached_item_unchecked(self.matches.get(n as usize)?.idx)) }
383 }
384}
385
386#[repr(u8)]
387#[derive(Clone, Copy, PartialEq, Eq)]
388enum State {
389 Init,
390 /// items have been cleared but snapshot and items are still outdated
391 Cleared,
392 /// items are fresh
393 Fresh,
394}
395
396impl State {
397 fn canceled(self) -> bool {
398 self != Self::Fresh
399 }
400
401 fn cleared(self) -> bool {
402 self != Self::Fresh
403 }
404}
405
406/// A high level matcher worker that quickly computes matches in a background
407/// threadpool.
408///
409/// ## Example
410/// ```
411/// use std::sync::atomic::{AtomicBool, Ordering};
412/// use std::sync::Arc;
413/// use std::thread;
414///
415/// use ncp_engine::{Config, Nucleo};
416///
417/// static NEEDS_UPDATE: AtomicBool = AtomicBool::new(false);
418///
419/// // initialize a new matcher with default configuration and one column
420/// let matcher = Nucleo::new(
421/// Config::DEFAULT,
422/// Arc::new(|| NEEDS_UPDATE.store(true, Ordering::Relaxed)),
423/// None,
424/// 1
425/// );
426///
427/// // get a handle to add items to the matcher
428/// let injector = matcher.injector();
429///
430/// // add items to the matcher
431/// thread::spawn(move || {
432/// injector.push("Hello, world!".to_string(), |s, cols| {
433/// cols[0] = (&**s).into();
434/// });
435/// });
436/// ```
437pub struct Nucleo<T> {
438 // the way the API is build we totally don't actually need these to be Arcs
439 // but this lets us avoid some unsafe
440 canceled: Arc<AtomicBool>,
441 worker: Arc<Mutex<Worker<T>>>,
442 pool: ThreadPool,
443 state: State,
444 injector: Arc<InjectorInner<T>>,
445 snapshot: Snapshot<T>,
446 /// The pattern matched by this matcher.
447 ///
448 /// To update the match pattern, use [`MultiPattern::reparse`]. Note that
449 /// the matcher worker will only become aware of the new pattern after a
450 /// call to [`tick`](Nucleo::tick).
451 pub pattern: MultiPattern,
452}
453
454impl<T: Sync + Send + 'static> Nucleo<T> {
455 /// Constructs a new `nucleo` worker threadpool with the provided `config`.
456 ///
457 /// `notify` is called whenever new information is available and
458 /// [`tick`](Nucleo::tick) should be called. Note that `notify` is not
459 /// debounced; that should be handled by the downstream crate (for example,
460 /// debouncing to only redraw at most every 1/60 seconds).
461 ///
462 /// If `None` is passed for the number of worker threads, nucleo will use
463 /// one thread per hardware thread.
464 ///
465 /// Nucleo can match items with multiple orthogonal properties. `columns`
466 /// indicates how many matching columns each item (and the pattern) has. The
467 /// number of columns cannot be changed after construction.
468 pub fn new(
469 config: Config,
470 notify: Arc<dyn Fn() + Sync + Send>,
471 num_threads: Option<usize>,
472 columns: u32,
473 ) -> Self {
474 Self::with_match_list_config(
475 config,
476 notify,
477 num_threads,
478 columns,
479 MatchListConfig::DEFAULT,
480 )
481 }
482
483 /// Constructs a new worker threadpool with the provided configuration, with pre-defined
484 /// configuration for the match list.
485 pub fn with_match_list_config(
486 config: Config,
487 notify: Arc<dyn Fn() + Sync + Send>,
488 num_threads: Option<usize>,
489 columns: u32,
490 match_list_config: MatchListConfig,
491 ) -> Self {
492 let (pool, worker) = Worker::new(num_threads, config, columns, match_list_config);
493 let injector = Arc::new(InjectorInner {
494 items: worker.items.clone(),
495 notify,
496 });
497 Self {
498 canceled: worker.canceled.clone(),
499 pool,
500 pattern: MultiPattern::new(columns as usize),
501 snapshot: Snapshot {
502 matches: Vec::with_capacity(2 * 1024),
503 pattern: MultiPattern::new(columns as usize),
504 item_count: 0,
505 items: worker.items.clone(),
506 },
507 worker: Arc::new(Mutex::new(worker)),
508 state: State::Init,
509 injector,
510 }
511 }
512
513 /// Returns the total number of active injectors.
514 pub fn active_injectors(&self) -> usize {
515 // Nucleo owns the only non-Injector reference to the current generation.
516 Arc::strong_count(&self.injector) - 1
517 }
518
519 /// Returns a snapshot of the current matcher state.
520 ///
521 /// This method is very cheap and can be called every time a snapshot is required. The
522 /// snapshot will not change unless [`tick`](Nucleo::tick) is called.
523 pub fn snapshot(&self) -> &Snapshot<T> {
524 &self.snapshot
525 }
526
527 /// Returns an injector that can be used for adding candidates to the matcher.
528 pub fn injector(&self) -> Injector<T> {
529 Injector {
530 inner: Arc::clone(&self.injector),
531 }
532 }
533
534 /// Restart the the item stream. Removes all items and disconnects all
535 /// previously created injectors from this instance. If `clear_snapshot`
536 /// is `true` then all items and matches are removed from the [`Snapshot`]
537 /// immediately. Otherwise the snapshot will keep the current matches until
538 /// the matcher has run again.
539 ///
540 /// # Note
541 ///
542 /// The injectors will continue to function but they will not affect this
543 /// instance anymore. The old items will only be dropped when all injectors
544 /// and detached items are dropped.
545 pub fn restart(&mut self, clear_snapshot: bool) {
546 self.canceled.store(true, Ordering::Relaxed);
547 let items = Arc::new(boxcar::Vec::with_capacity(
548 1024,
549 self.injector.items.columns(),
550 ));
551 self.injector = Arc::new(InjectorInner {
552 items: Arc::clone(&items),
553 notify: Arc::clone(&self.injector.notify),
554 });
555 self.state = State::Cleared;
556 if clear_snapshot {
557 self.snapshot.clear(items);
558 }
559 }
560
561 /// Update the internal configuration.
562 pub fn update_config(&mut self, config: Config) {
563 self.worker.lock().update_config(config);
564 }
565
566 /// Set whether the matcher should sort search results by score after
567 /// matching. Defaults to true.
568 pub fn sort_results(&mut self, sort_results: bool) {
569 self.worker.lock().sort_results(sort_results);
570 }
571
572 /// Set whether the matcher should reverse the order of the input.
573 /// Defaults to false.
574 pub fn reverse_items(&mut self, reverse_items: bool) {
575 self.worker.lock().reverse_items(reverse_items);
576 }
577
578 /// Update the internal state to reflect any changes from the background worker
579 /// threads.
580 ///
581 /// This is the main way to interact with the matcher, and should be called
582 /// regularly (for example each time a frame is rendered). To avoid excessive
583 /// redraws this method will wait `timeout` milliseconds for the
584 /// worker threads to finish. It is recommend to set the timeout to 10ms.
585 pub fn tick(&mut self, timeout: u64) -> Status {
586 let status = self.pattern.status();
587 let canceled = status != pattern::Status::Unchanged || self.state.canceled();
588 let mut res = self.tick_inner(timeout, canceled, status);
589 if !canceled {
590 return res;
591 }
592 self.state = State::Fresh;
593 let status2 = self.tick_inner(timeout, false, pattern::Status::Unchanged);
594 res.changed |= status2.changed;
595 res.running = status2.running;
596 res
597 }
598
599 fn tick_inner(&mut self, timeout: u64, canceled: bool, status: pattern::Status) -> Status {
600 let mut inner = if canceled {
601 self.pattern.reset_status();
602 self.canceled.store(true, atomic::Ordering::Relaxed);
603 self.worker.lock_arc()
604 } else {
605 let Some(worker) = self.worker.try_lock_arc_for(Duration::from_millis(timeout)) else {
606 return Status {
607 changed: false,
608 running: true,
609 };
610 };
611 worker
612 };
613
614 let pending_update = inner.needs_rescore || inner.needs_sort;
615 let changed = inner.running && !pending_update;
616
617 let running =
618 canceled || pending_update || self.injector.items.count() > inner.item_count();
619 if inner.running {
620 inner.running = false;
621 if !inner.was_canceled && !self.state.canceled() && !pending_update {
622 self.snapshot.update(&inner);
623 }
624 }
625 if running {
626 let status = if inner.needs_rescore {
627 pattern::Status::Rescore
628 } else {
629 status
630 };
631 inner.needs_rescore = false;
632 inner.needs_sort = false;
633 inner.pattern.clone_from(&self.pattern);
634 self.canceled.store(false, atomic::Ordering::Relaxed);
635 let cleared = self.state.cleared();
636 if cleared {
637 inner.items = Arc::clone(&self.injector.items);
638 }
639 let notify = Arc::clone(&self.injector.notify);
640 self.pool.spawn(move || {
641 let outcome = unsafe { inner.run(status, cleared) };
642 drop(inner);
643 if outcome == RunOutcome::Completed {
644 notify();
645 }
646 });
647 }
648 Status { changed, running }
649 }
650}
651
652impl<T> Drop for Nucleo<T> {
653 fn drop(&mut self) {
654 self.canceled.store(true, atomic::Ordering::Relaxed);
655 }
656}