fuzzy_search_lite 0.1.0

Fast fuzzy string scoring and top-k search with optional Rayon parallelism.
Documentation
  • Coverage
  • 100%
    13 out of 13 items documented5 out of 5 items with examples
  • Size
  • Source code size: 76.2 kB This is the summed size of all the files inside the crates.io package for this release.
  • Documentation size: 268.9 kB This is the summed size of all files generated by rustdoc for all configured targets
  • Ø build duration
  • this release: 5s Average build duration of successful builds.
  • all releases: 5s Average build duration of successful builds in releases after 2024-10-23.
  • Links
  • axelfechner/fuzzy_search_lite
    0 0 0
  • crates.io
  • Dependencies
  • Versions
  • Owners
  • axelfechner

FuzzySearch

Fast fuzzy string scoring and top-k search for Rust.

FuzzySearch is useful when you have a list of candidate strings and want the best matches for a short query, such as command palettes, file pickers, autocomplete lists, log filters, searchable menus, or lightweight CLI search.

The crate provides:

  • single-term scoring with fuzzy_score
  • allocation-light top-k search with fuzzy_matches
  • optional Rayon parallelism for large input slices
  • strict Unicode case folding without normalization or transliteration

Quick Start

Add the crate:

cargo add fuzzy_search_lite

Score one candidate:

use fuzzy_search_lite::fuzzy_score::fuzzy_score;

let result = fuzzy_score("Workshop", "wo");
assert_eq!(result.score, 4);

Search a list and borrow matches from the original data:

use fuzzy_search_lite::fuzzy_score::fuzzy_matches;

let items = ["Workshop", "Room", "Apache Software Foundation"];
let matches = fuzzy_matches(&items, "wo", 5);

assert_eq!(matches[0].term, "Workshop");
assert_eq!(matches[0].index, 0);
assert_eq!(matches[0].score, 4);

Choosing an API

Function Use when Result type
fuzzy_score You want to score one term against one query. FuzzyScore
fuzzy_matches You want top-k results borrowed from the original input. Vec<ScoredMatch>

Use fuzzy_matches for list search. It avoids cloning returned terms and includes the original input index so you can map results back to your own data.

Library Usage

Borrowed Top-K Results

fuzzy_matches accepts any slice whose items implement AsRef<str> + Sync. That includes arrays of &str, Vec<String>, Vec<&str>, and custom string-like types.

use fuzzy_search_lite::fuzzy_score::fuzzy_matches;

let commands = [
    "Open File",
    "Open Folder",
    "Close Window",
    "Toggle Terminal",
];

let matches = fuzzy_matches(&commands, "of", 3);

for item in matches {
    println!(
        "matched '{}' at index {} with score {}",
        item.term, item.index, item.score
    );
}

Single-Term Scoring

Use fuzzy_score when you want to rank or compare terms yourself.

use fuzzy_search_lite::fuzzy_score::fuzzy_score;

let compact = fuzzy_score("abc", "abc");
let interrupted = fuzzy_score("a_b_c", "abc");

assert!(compact.score > interrupted.score);

Working with Custom Types

The list APIs work with custom types by implementing AsRef<str>.

use fuzzy_search_lite::fuzzy_score::fuzzy_matches;

struct Command {
    label: String,
    id: u32,
}

impl AsRef<str> for Command {
    fn as_ref(&self) -> &str {
        &self.label
    }
}

let commands = vec![
    Command { label: "Open File".into(), id: 1 },
    Command { label: "Close Window".into(), id: 2 },
];

let matches = fuzzy_matches(&commands, "of", 1);
let command = &commands[matches[0].index];

assert_eq!(command.id, 1);

Result Types

ScoredMatch

Returned by fuzzy_matches.

pub struct ScoredMatch<'data, 'query> {
    pub term: &'data str,
    pub query: &'query str,
    pub score: u16,
    pub index: usize,
}

This result borrows term from the original input slice. Keep the input data alive for as long as you use the matches.

FuzzyScore

Returned by fuzzy_score.

pub struct FuzzyScore<'query> {
    pub term: String,
    pub query: &'query str,
    pub score: u16,
}

This result owns the matched term. It is convenient when returned values must outlive the input data.

Both result types implement Debug, Clone, Eq, and ordering traits where applicable.

Scoring Model

The query is matched from left to right against the candidate term.

Scoring rules:

  • first matching character: +1
  • matching character immediately after the previous match: +3
  • non-match: resets the next match back to +1
  • empty query: score 0

Examples:

Term Query Score Why
Workshop w 1 first character match
Workshop wo 4 w gives 1, consecutive o gives 3
Workshop ws 2 w and s match, but not consecutively
a_b ab 2 interrupted match, no consecutive bonus
abc abc 7 1 + 3 + 3

fuzzy_matches omits candidates with score 0. fuzzy_score returns a result even when the score is 0.

Sorting and Top-K Behavior

List results are returned in descending score order. If scores are equal, the current ranking is deterministic and preserves the stable top-k behavior tested by the crate.

top_k is a maximum, not a guarantee:

  • top_k = 0 returns an empty result.
  • an empty query returns an empty result.
  • candidates with score 0 are not returned.
  • if fewer than top_k candidates match, only matching candidates are returned.

Unicode Behavior

Unicode handling is intentionally strict.

What the crate does:

  • ASCII matching is case-insensitive.
  • Non-ASCII queries use Unicode lowercasing.
  • UTF-8 terms are iterated by character, not by raw byte.

What the crate does not do:

  • no Unicode normalization
  • no accent removal
  • no transliteration
  • no locale-specific matching

For example, an accented character is not treated as its ASCII base letter.

use fuzzy_search_lite::fuzzy_score::fuzzy_score;

assert_eq!(fuzzy_score("\u{dc}ber", "\u{fc}b").score, 4);
assert_eq!(fuzzy_score("\u{dc}ber", "ub").score, 0);

If your application needs accent-insensitive search, normalize or transliterate your data before passing it to this crate.

Feature Flags

Default features:

fuzzy_search_lite = "0.1"

By default, the parallel feature is enabled. Large inputs use Rayon for parallel scoring, while small inputs remain sequential to avoid scheduling overhead.

Disable default features for a dependency-minimal build:

fuzzy_search_lite = { version = "0.1", default-features = false }

Build locally without Rayon:

cargo build --release --no-default-features

CLI Usage

The package also includes a small CLI.

cargo build --release

./target/release/fuzzy_search_lite <file> <query> [count]

Example:

./target/release/fuzzy_search_lite words.txt "wrkshp" 5

Arguments:

  • file: path to a newline-delimited text file
  • query: fuzzy query to search for
  • count: optional maximum number of results, defaults to 5

The CLI reads the file line by line and keeps only top-k results in memory per chunk, making it suitable for large files.

Performance

Benchmarks on generated ASCII-heavy test data, query "ap", top 10 results:

Metric Time
1,000 elements ~18.5 us
10,000 elements ~128 us
100,000 elements ~524 us
500,000 elements ~1.59 ms

Throughput: ~314 million elements/sec at 500k dataset size.

Run benchmarks locally:

cargo bench

Benchmarks cover:

  • single score performance with different term/query combinations
  • data size scaling from 1k to 500k elements
  • query pattern variations
  • top-k value impact
  • memory efficiency

Testing

Run the full local test matrix before changing scoring, ranking, feature handling, or CLI behavior:

cargo fmt --check
cargo test
cargo test --no-default-features
cargo test --all-features
cargo clippy --all-targets --all-features
cargo doc --no-deps

The test suite covers:

  • score rules and edge cases for ASCII and UTF-8 paths
  • fuzzy_matches list behavior
  • empty input, empty query, top_k = 0, no-match, ranking, and invariants
  • sequential and Rayon-backed parallel paths
  • CLI argument parsing
  • file search, empty input, zero-count behavior, and chunk merging
  • binary-level smoke tests through Cargo's CARGO_BIN_EXE_fuzzy_search_lite
  • doc examples

Coverage

Coverage is optional for normal development, but recommended when making broad refactors.

Suggested tool:

cargo install cargo-llvm-cov
cargo llvm-cov --all-features
cargo llvm-cov --all-features --html

Coverage goals:

  • src/fuzzy_score.rs: at least 85 percent line coverage
  • extracted and testable CLI/search logic in src/main.rs: at least 70 percent line coverage
  • branches to watch explicitly: empty query, top_k = 0, ASCII path, mixed UTF-8 path, full Unicode path, and the parallel threshold

Generated reports should stay out of version control. The default target/ ignore covers the usual cargo-llvm-cov HTML output.

Troubleshooting

Why did I get no matches?

Check these common cases:

  • the query is empty
  • top_k is 0
  • the query characters do not appear in order in the candidate
  • you expected accent-insensitive or transliterated matching, which this crate does not perform

Why is fuzzy_matches returning borrowed data?

That is intentional. It avoids cloning result terms and lets you map matches back to your original data through index.

Does the crate allocate?

Single-term scoring allocates only for the owned FuzzyScore.term result. fuzzy_matches avoids cloning matched terms. Internally, list scoring keeps a bounded heap of top-k scored indices instead of sorting all candidates.

Should I use the CLI or the library?

Use the CLI for quick line-based file search. Use the library when integrating fuzzy matching into an application, service, editor tool, or UI.

Architecture

The engine uses a three-tier hybrid approach:

  1. ASCII fast path - Both query and term are ASCII: byte-level matching with eq_ignore_ascii_case.
  2. Mixed path - ASCII query, UTF-8 term: char-level iteration with case folding.
  3. Full Unicode path - Non-ASCII query: full char-level matching with Unicode case folding.

For small lists, results are collected sequentially to avoid Rayon scheduling overhead. With the default parallel feature enabled, larger lists use Rayon and collect results in per-thread BinaryHeaps with Reverse ordering, then merge only the top-k scores in the reduce step.

License

MIT