Skip to main content

goldenfuzz_core/
lib.rs

1//! Vendored string-similarity primitives — GoldenMatch's OWN implementations of
2//! the four metrics the scorer surface needs, replacing the `rapidfuzz` crate on
3//! the shipped path so the "one authoritative semantic owner per capability"
4//! invariant holds for the scoring math itself (not a black box).
5//!
6//! Slice 1 of the rapidfuzz-ownership epic. These are faithful, byte-identical
7//! ports of rapidfuzz-rs 0.5.0's scalar `normalized_similarity` / `distance`:
8//!
9//!   * [`jaro_winkler`]  == `jaro_winkler::normalized_similarity` (prefix_weight 0.1)
10//!   * [`levenshtein_normalized_similarity`] == `levenshtein::normalized_similarity`
11//!   * [`indel_ratio`]   == `fuzz::ratio` (Indel normalized_similarity, [0,1])
12//!   * [`damerau_levenshtein_distance`] == `damerau_levenshtein::distance` (true DL)
13//!
14//! rapidfuzz's bit-parallel machinery (Myers/Hyyrö, SIMD batch) is an
15//! *optimization*: the integer distances / LCS / Jaro match+transposition counts
16//! it produces are exact and identical to a correct naive computation, so
17//! byte-identical output only requires (a) the same final float arithmetic and
18//! (b) rapidfuzz's Jaro match order (iterate the text string, greedily bind the
19//! lowest unflagged pattern position in the window). Both are replicated below.
20//!
21//! Byte-identical output is PROVEN, not assumed: the `parity` test module (built
22//! only with the `rapidfuzz` dev-dependency) asserts `f64::to_bits` equality
23//! against the crate over a large randomized + adversarial corpus.
24
25use std::collections::BTreeSet;
26use std::collections::HashMap;
27use std::collections::HashSet;
28use std::hash::Hash;
29
30// ---------------------------------------------------------------------------
31// Multiword bit-parallel primitives (little-endian u64 limbs)
32// ---------------------------------------------------------------------------
33//
34// The LCS (Allison-Dix), Levenshtein (Myers 1999) and Jaro (rapidfuzz
35// FlaggedChars) kernels below all pack the PATTERN's positions into one bit per
36// position and advance a DP row/column with a handful of word ops per text
37// char. rapidfuzz uses the identical machinery; the INTEGER counts (LCS length,
38// edit distance, Jaro match/transposition) are exact, so byte-identical output
39// is preserved (proven vs the rapidfuzz crate + a naive-oracle fuzz across the
40// 64/128/192-bit limb boundaries in the test module). A pattern longer than 64
41// codepoints spans multiple limbs, so every op carries/borrows across limbs.
42
43#[inline]
44fn nwords(m: usize) -> usize {
45    m.div_ceil(64)
46}
47
48/// Mask of the valid bits in the TOP limb of an `m`-bit vector.
49#[inline]
50fn top_mask(m: usize) -> u64 {
51    let r = m % 64;
52    if r == 0 {
53        u64::MAX
54    } else {
55        (1u64 << r) - 1
56    }
57}
58
59/// `out = a + b` (equal length); the carry out of the top limb is discarded
60/// (callers mask the top limb to the pattern width where it matters).
61fn bv_add(a: &[u64], b: &[u64], out: &mut [u64]) {
62    let mut carry: u128 = 0;
63    for i in 0..a.len() {
64        let s = a[i] as u128 + b[i] as u128 + carry;
65        out[i] = s as u64;
66        carry = s >> 64;
67    }
68}
69
70/// `out = a - b`, assuming `a >= b` (the callers only ever subtract a subset),
71/// so the final borrow is always zero.
72fn bv_sub(a: &[u64], b: &[u64], out: &mut [u64]) {
73    let mut borrow: i128 = 0;
74    for i in 0..a.len() {
75        let d = a[i] as i128 - b[i] as i128 - borrow;
76        if d < 0 {
77            out[i] = (d + (1i128 << 64)) as u64;
78            borrow = 1;
79        } else {
80            out[i] = d as u64;
81            borrow = 0;
82        }
83    }
84}
85
86fn bv_popcount(a: &[u64]) -> usize {
87    a.iter().map(|w| w.count_ones() as usize).sum()
88}
89
90/// In-place left shift by one across limbs; sets bit 0 if `carry_in`, then masks
91/// the top limb to `tmask`.
92fn bv_shl1(v: &mut [u64], tmask: u64, carry_in: bool) {
93    let mut carry: u64 = u64::from(carry_in);
94    for w in v.iter_mut() {
95        let next = *w >> 63;
96        *w = (*w << 1) | carry;
97        carry = next;
98    }
99    let last = v.len() - 1;
100    v[last] &= tmask;
101}
102
103fn bv_clear_below(v: &mut [u64], lo: usize) {
104    let w = lo / 64;
105    for x in v.iter_mut().take(w) {
106        *x = 0;
107    }
108    if w < v.len() {
109        let r = lo % 64;
110        if r > 0 {
111            v[w] &= !((1u64 << r) - 1);
112        }
113    }
114}
115
116fn bv_clear_above(v: &mut [u64], hi: usize) {
117    let w = hi / 64;
118    let r = hi % 64;
119    let keep = if r == 63 {
120        u64::MAX
121    } else {
122        (1u64 << (r + 1)) - 1
123    };
124    if w < v.len() {
125        v[w] &= keep;
126    }
127    for x in v.iter_mut().skip(w + 1) {
128        *x = 0;
129    }
130}
131
132fn bv_lowest_set(v: &[u64]) -> Option<usize> {
133    for (i, &w) in v.iter().enumerate() {
134        if w != 0 {
135            return Some(i * 64 + w.trailing_zeros() as usize);
136        }
137    }
138    None
139}
140
141/// Multiword position bitmap: `get(c)` is a length-`nw` limb slice with a bit set
142/// at each position where `c` occurs in the pattern. A Latin-1 pattern uses a flat
143/// stack-of-limbs array indexed by codepoint -- no hashing, no per-char alloc; a
144/// non-Latin-1 pattern (CJK / emoji) falls back to a HashMap. The flat path is
145/// what makes long-string scoring competitive: the HashMap peq for a 600-char
146/// pattern is ~16us (600 char-hashes + ~27 small Vec allocs) vs ~3us flat, and
147/// that build dominated our per-pair document cost. Byte-identical either way.
148enum MwPeq {
149    Flat { masks: Vec<u64>, nw: usize },
150    Hash(HashMap<char, Vec<u64>>),
151}
152
153impl MwPeq {
154    #[inline]
155    fn get<'a>(&'a self, c: char, empty: &'a [u64]) -> &'a [u64] {
156        match self {
157            MwPeq::Flat { masks, nw } => {
158                let ci = c as usize;
159                if ci < 256 {
160                    &masks[ci * nw..ci * nw + nw]
161                } else {
162                    empty
163                }
164            }
165            MwPeq::Hash(map) => map.get(&c).map(Vec::as_slice).unwrap_or(empty),
166        }
167    }
168}
169
170fn peq_multiword(pattern: &[char]) -> MwPeq {
171    let nw = nwords(pattern.len()).max(1);
172    if pattern.iter().all(|&c| (c as u32) < 256) {
173        let mut masks = vec![0u64; 256 * nw];
174        for (i, &c) in pattern.iter().enumerate() {
175            masks[(c as usize) * nw + i / 64] |= 1u64 << (i % 64);
176        }
177        MwPeq::Flat { masks, nw }
178    } else {
179        let mut map: HashMap<char, Vec<u64>> = HashMap::new();
180        for (i, &c) in pattern.iter().enumerate() {
181            map.entry(c).or_insert_with(|| vec![0u64; nw])[i / 64] |= 1u64 << (i % 64);
182        }
183        MwPeq::Hash(map)
184    }
185}
186
187// ---------------------------------------------------------------------------
188// Jaro / Jaro-Winkler
189// ---------------------------------------------------------------------------
190
191/// rapidfuzz `jaro::calculate_similarity`: `transposition/=2` then
192/// `(m/p_len + m/t_len + (m-t)/m) / 3` — exact operation order preserved.
193#[inline]
194fn jaro_calculate_similarity(
195    p_len: usize,
196    t_len: usize,
197    common: usize,
198    mut transposition: usize,
199) -> f64 {
200    transposition /= 2;
201    let mut sim: f64 = 0.0;
202    sim += common as f64 / p_len as f64;
203    sim += common as f64 / t_len as f64;
204    sim += (common as f64 - transposition as f64) / common as f64;
205    sim / 3.0
206}
207
208// ---------------------------------------------------------------------------
209// Single-word fast path (patterns <= 64 codepoints, Latin-1)
210// ---------------------------------------------------------------------------
211//
212// The multiword path heap-allocates a HashMap peq + limb vectors PER CALL, which
213// dominates on short fields (names / addresses / dates): ~20x the actual
214// bit-parallel work, and measurably SLOWER than the naive two-row DP it replaced
215// on that regime. Almost every ER field is <= 64 codepoints and Latin-1, so a
216// stack `[u64; 256]` position bitmap + a single u64 DP register cover it with
217// ZERO heap -- the scalar scorer then beats rapidfuzz on the common case. Longer
218// or non-Latin-1 (CJK / emoji) patterns fall through to the multiword path.
219// Byte-identical to it (fuzzed vs the multiword + rapidfuzz oracle to the exact
220// 64-codepoint boundary).
221
222const SW_MAX: usize = 64;
223
224/// Stack position-bitmap for a pattern of <= 64 Latin-1 codepoints. `None` when
225/// the pattern is too long or holds a codepoint >= 256 (multiword handles those).
226#[inline]
227fn sw_peq(pat: &[char]) -> Option<[u64; 256]> {
228    if pat.len() > SW_MAX {
229        return None;
230    }
231    let mut peq = [0u64; 256];
232    for (i, &c) in pat.iter().enumerate() {
233        let ci = c as u32;
234        if ci >= 256 {
235            return None;
236        }
237        peq[ci as usize] |= 1u64 << i;
238    }
239    Some(peq)
240}
241
242#[inline]
243fn sw_get(peq: &[u64; 256], c: char) -> u64 {
244    let ci = c as u32;
245    if ci < 256 {
246        peq[ci as usize]
247    } else {
248        0
249    }
250}
251
252#[inline]
253fn sw_mask(m: usize) -> u64 {
254    if m >= 64 {
255        u64::MAX
256    } else {
257        (1u64 << m) - 1
258    }
259}
260
261/// ASCII position bitmap (`[u64; 128]`, half the `char` tier's 2 KiB, and no
262/// `Vec<char>` at the call site). Caller guarantees `pat` is ASCII and
263/// `pat.len() <= 64`; the `& 0x7f` keeps the index in range defensively.
264#[inline]
265fn byte_peq(pat: &[u8]) -> [u64; 128] {
266    let mut peq = [0u64; 128];
267    for (i, &c) in pat.iter().enumerate() {
268        peq[(c & 0x7f) as usize] |= 1u64 << i;
269    }
270    peq
271}
272
273/// Single-word Allison-Dix LCS. Caller guarantees `s1.len() <= 64`. Generic over
274/// the symbol type so both the `char` (Latin-1, `[u64; 256]` peq) and the `u8`
275/// (ASCII, `[u64; 128]` peq) tiers share one monomorphised body; `get` is the
276/// position-bitmap lookup, inlined to a single bounds-checked array index.
277fn lcs_length_sw<T: Copy>(s1: &[T], s2: &[T], get: impl Fn(T) -> u64) -> usize {
278    let m = s1.len();
279    let mask = sw_mask(m);
280    let mut v = mask;
281    for &c in s2 {
282        let p = get(c);
283        let u = v & p;
284        v = (v.wrapping_add(u) & mask) | (v - u);
285    }
286    m - (v & mask).count_ones() as usize
287}
288
289/// Single-word Myers Levenshtein. Caller guarantees `1 <= s1.len() <= 64`.
290fn levenshtein_distance_sw<T: Copy>(s1: &[T], s2: &[T], get: impl Fn(T) -> u64) -> usize {
291    let m = s1.len();
292    let mask = sw_mask(m);
293    let top = 1u64 << (m - 1);
294    let mut pv = mask;
295    let mut mv = 0u64;
296    let mut score = m;
297    for &c in s2 {
298        let eq = get(c);
299        let xv = eq | mv;
300        let xh = ((((eq & pv).wrapping_add(pv)) ^ pv) | eq) & mask;
301        let ph = (mv | !(xh | pv)) & mask;
302        let mh = pv & xh;
303        if ph & top != 0 {
304            score += 1;
305        } else if mh & top != 0 {
306            score -= 1;
307        }
308        let ph = ((ph << 1) | 1) & mask;
309        let mh = (mh << 1) & mask;
310        pv = (mh | !(xv | ph)) & mask;
311        mv = ph & xv;
312    }
313    score
314}
315
316/// Single-word FlaggedChars Jaro. Caller guarantees `s1.len() <= 64` (and, via
317/// the `len1 == 1 && len2 == 1` short-circuit in the dispatcher, `len2 >= 2` when
318/// `len1 == 1`). Same match/transposition order as the multiword path.
319fn jaro_similarity_sw<T: Copy + PartialEq>(s1: &[T], s2: &[T], get: impl Fn(T) -> u64) -> f64 {
320    let len1 = s1.len();
321    let len2 = s2.len();
322    let bound = std::cmp::max(len1, len2) / 2 - 1;
323    let mut p_flag = 0u64;
324    // Matched TEXT positions in ascending j order. The TEXT (s2) may be longer
325    // than 64, so a u64 position bitmask would overflow; there are at most
326    // `common <= len1 <= 64` matches, so a fixed stack array holds them.
327    let mut t_pos = [0usize; SW_MAX];
328    let mut nt = 0usize;
329    let hi_max = len1 - 1;
330    for (j, &cj) in s2.iter().enumerate() {
331        let lo = j.saturating_sub(bound);
332        let hi = std::cmp::min(j + bound, hi_max);
333        if lo > hi {
334            continue;
335        }
336        let window = (((1u128 << (hi + 1)) - 1) ^ ((1u128 << lo) - 1)) as u64;
337        let cand = get(cj) & window & !p_flag;
338        if cand != 0 {
339            p_flag |= cand & cand.wrapping_neg(); // blsi: lowest set bit
340            t_pos[nt] = j;
341            nt += 1;
342        }
343    }
344    let common = p_flag.count_ones() as usize;
345    if common == 0 {
346        return 0.0;
347    }
348    // Pair the k-th flagged pattern char (ascending) with the k-th matched text
349    // char (ascending j order); count positional disagreements.
350    let mut transposition = 0usize;
351    let mut pf = p_flag;
352    let mut k = 0usize;
353    while pf != 0 {
354        let i = pf.trailing_zeros() as usize;
355        if s1[i] != s2[t_pos[k]] {
356            transposition += 1;
357        }
358        pf &= pf - 1;
359        k += 1;
360    }
361    jaro_calculate_similarity(len1, len2, common, transposition)
362}
363
364/// Jaro similarity on `[0, 1]`, matching `rapidfuzz::distance::jaro` at
365/// `score_cutoff = 0.0`. `s1`/`s2` are codepoint slices.
366fn jaro_similarity(s1: &[char], s2: &[char]) -> f64 {
367    let len1 = s1.len();
368    let len2 = s2.len();
369
370    if len1 == 0 && len2 == 0 {
371        return 1.0;
372    }
373    // length_filter: either side empty -> 0.0 (never passes at any cutoff).
374    if len1 == 0 || len2 == 0 {
375        return 0.0;
376    }
377    if len1 == 1 && len2 == 1 {
378        return if s1[0] == s2[0] { 1.0 } else { 0.0 };
379    }
380
381    // Single-word fast path for a <= 64-codepoint Latin-1 pattern (accented
382    // names etc.; pure ASCII already took the byte tier in jaro_winkler).
383    // Byte-identical to the multiword path below.
384    if let Some(peq) = sw_peq(s1) {
385        return jaro_similarity_sw(s1, s2, |c: char| sw_get(&peq, c));
386    }
387
388    jaro_similarity_mw(s1, s2, &peq_multiword(s1))
389}
390
391/// Multiword Jaro body over a PREPARED peq, so the one-vs-many batch API can
392/// build the query's peq ONCE and reuse it across choices. Caller guarantees
393/// `len1 >= 1`, `len2 >= 1`, and not (`len1 == 1 && len2 == 1`) — the edge cases
394/// `jaro_similarity` handles before dispatching here. Byte-identical to the
395/// inline path it replaced.
396fn jaro_similarity_mw(s1: &[char], s2: &[char], peq: &MwPeq) -> f64 {
397    let len1 = s1.len();
398    let len2 = s2.len();
399    // rapidfuzz bound = max(len1, len2) / 2 - 1 (both >= 1 here, so >= 0).
400    let bound = std::cmp::max(len1, len2) / 2 - 1;
401
402    // Bit-parallel FlaggedChars: bind each TEXT (s2) position to the LOWEST
403    // unflagged PATTERN (s1) position within [j-bound, j+bound].
404    let nw = nwords(len1);
405    let empty = vec![0u64; nw];
406    let mut p_flag = vec![0u64; nw]; // matched pattern positions
407    let mut t_flag_pos: Vec<usize> = Vec::new(); // matched text positions, ascending
408    let mut cand = vec![0u64; nw];
409    let hi_max = len1 - 1;
410    for (j, &cj) in s2.iter().enumerate() {
411        let lo = j.saturating_sub(bound);
412        let hi = std::cmp::min(j + bound, hi_max);
413        if lo > hi {
414            continue;
415        }
416        let pm = peq.get(cj, &empty);
417        for i in 0..nw {
418            cand[i] = pm[i] & !p_flag[i];
419        }
420        bv_clear_below(&mut cand, lo);
421        bv_clear_above(&mut cand, hi);
422        if let Some(bit) = bv_lowest_set(&cand) {
423            p_flag[bit / 64] |= 1u64 << (bit % 64);
424            t_flag_pos.push(j);
425        }
426    }
427
428    // common_char_filter: no common chars -> 0.0.
429    let common = bv_popcount(&p_flag);
430    if common == 0 {
431        return 0.0;
432    }
433
434    // Transpositions: pair the k-th flagged pattern char with the k-th flagged
435    // text char (both ascending); count positional disagreements.
436    let mut transposition = 0usize;
437    let mut tmp = p_flag.clone();
438    let mut k = 0usize;
439    while let Some(bit) = bv_lowest_set(&tmp) {
440        if s1[bit] != s2[t_flag_pos[k]] {
441            transposition += 1;
442        }
443        tmp[bit / 64] &= !(1u64 << (bit % 64));
444        k += 1;
445    }
446
447    jaro_calculate_similarity(len1, len2, common, transposition)
448}
449
450/// Jaro-Winkler normalized similarity on `[0, 1]`, matching
451/// `rapidfuzz::distance::jaro_winkler::normalized_similarity` with the default
452/// `prefix_weight = 0.1`. Operates on Unicode codepoints.
453pub fn jaro_winkler(a: &str, b: &str) -> f64 {
454    // ASCII single-word fast path (the common ER field): work on the byte slices
455    // directly -- no `Vec<char>`, a 1 KiB stack peq -- so this beats rapidfuzz on
456    // short names/addresses. len 0/1 (and the `1,1` jaro edge) route to the char
457    // path, which owns the edge cases; a >= 2 keeps the jaro `bound` non-negative.
458    if a.is_ascii() && b.is_ascii() && (2..=SW_MAX).contains(&a.len()) {
459        let ab = a.as_bytes();
460        let bb = b.as_bytes();
461        let peq = byte_peq(ab);
462        let jaro = jaro_similarity_sw(ab, bb, |x: u8| peq[(x & 0x7f) as usize]);
463        return jaro_winkler_combine(ab, bb, jaro);
464    }
465    let s1: Vec<char> = a.chars().collect();
466    let s2: Vec<char> = b.chars().collect();
467    jaro_winkler_chars(&s1, &s2)
468}
469
470/// Jaro-Winkler prefix boost + `Metricf64` round-trip, shared by the char and
471/// byte tiers. `jaro` is the raw Jaro similarity of the same two slices.
472#[inline]
473fn jaro_winkler_combine<T: PartialEq>(s1: &[T], s2: &[T], jaro: f64) -> f64 {
474    const PREFIX_WEIGHT: f64 = 0.1;
475    // Common prefix, capped at 4 (rapidfuzz `.take(4).take_while(eq)`).
476    let mut prefix = 0usize;
477    for (c1, c2) in s1.iter().zip(s2.iter()).take(4) {
478        if c1 == c2 {
479            prefix += 1;
480        } else {
481            break;
482        }
483    }
484    let mut sim = jaro;
485    if sim > 0.7 {
486        sim += prefix as f64 * PREFIX_WEIGHT * (1.0 - sim);
487    }
488    // jaro_winkler is a `Metricf64` similarity metric with `maximum == 1.0`, so
489    // the normalized round-trip is `1.0 - (1.0 - sim)` (see the parity note).
490    1.0 - (1.0 - sim)
491}
492
493/// Slice form (lets `score_one`/callers avoid re-collecting when they already
494/// hold `Vec<char>`). `prefix_weight` fixed at rapidfuzz's default 0.1.
495pub fn jaro_winkler_chars(s1: &[char], s2: &[char]) -> f64 {
496    // score_cutoff = 0.0 on the normalized_similarity path, so the jaro cutoff
497    // adjustment (only fires when cutoff > 0.7) is a no-op and omitted. The
498    // prefix boost + Metricf64 round-trip are shared with the byte tier.
499    jaro_winkler_combine(s1, s2, jaro_similarity(s1, s2))
500}
501
502// ---------------------------------------------------------------------------
503// Levenshtein
504// ---------------------------------------------------------------------------
505
506/// Uniform-weight Levenshtein edit distance, bit-parallel (Myers 1999). The
507/// PATTERN `a` is packed one bit per position; each text char advances the
508/// vertical-delta vectors `pv`/`mv` with a fixed set of word ops. Integer result
509/// identical to the naive Wagner-Fischer DP and to rapidfuzz (proven in tests).
510pub fn levenshtein_distance(a: &[char], b: &[char]) -> usize {
511    if a.is_empty() {
512        return b.len();
513    }
514    if b.is_empty() {
515        return a.len();
516    }
517    levenshtein_distance_mw(a, b, &peq_multiword(a))
518}
519
520/// Multiword Myers body over a PREPARED peq (one-vs-many amortisation). Caller
521/// guarantees `a` and `b` non-empty.
522fn levenshtein_distance_mw(a: &[char], b: &[char], peq: &MwPeq) -> usize {
523    let m = a.len();
524    let nw = nwords(m);
525    let tmask = top_mask(m);
526    let empty = vec![0u64; nw];
527    let top_word = (m - 1) / 64;
528    let top_bit = 1u64 << ((m - 1) % 64);
529
530    let mut pv = vec![u64::MAX; nw];
531    pv[nw - 1] &= tmask;
532    let mut mv = vec![0u64; nw];
533    let mut score = m;
534
535    let mut xv = vec![0u64; nw];
536    let mut xh = vec![0u64; nw];
537    let mut ph = vec![0u64; nw];
538    let mut mh = vec![0u64; nw];
539    let mut t = vec![0u64; nw];
540    let mut t2 = vec![0u64; nw];
541
542    for &cb in b {
543        let eq = peq.get(cb, &empty);
544        for i in 0..nw {
545            xv[i] = eq[i] | mv[i];
546            t[i] = eq[i] & pv[i];
547        }
548        // xh = (((eq & pv) + pv) ^ pv) | eq
549        bv_add(&t, &pv, &mut t2);
550        for i in 0..nw {
551            let m_all = if i == nw - 1 { tmask } else { u64::MAX };
552            xh[i] = ((t2[i] ^ pv[i]) | eq[i]) & m_all;
553            ph[i] = (mv[i] | !(xh[i] | pv[i])) & m_all;
554            mh[i] = pv[i] & xh[i];
555        }
556        if ph[top_word] & top_bit != 0 {
557            score += 1;
558        } else if mh[top_word] & top_bit != 0 {
559            score -= 1;
560        }
561        bv_shl1(&mut ph, tmask, true);
562        bv_shl1(&mut mh, tmask, false);
563        for i in 0..nw {
564            let m_all = if i == nw - 1 { tmask } else { u64::MAX };
565            pv[i] = (mh[i] | !(xv[i] | ph[i])) & m_all;
566            mv[i] = ph[i] & xv[i];
567        }
568    }
569    score
570}
571
572/// `rapidfuzz::distance::levenshtein::normalized_similarity`:
573/// `1.0 - dist / max(len1, len2)` (`maximum == 0 -> 0` distance -> 1.0 sim).
574pub fn levenshtein_normalized_similarity(a: &str, b: &str) -> f64 {
575    // ASCII single-word fast path (no Vec<char>, 1 KiB stack peq).
576    if a.is_ascii() && b.is_ascii() && (1..=SW_MAX).contains(&a.len()) {
577        let ab = a.as_bytes();
578        let bb = b.as_bytes();
579        let maximum = std::cmp::max(ab.len(), bb.len());
580        let peq = byte_peq(ab);
581        let dist = levenshtein_distance_sw(ab, bb, |x: u8| peq[(x & 0x7f) as usize]);
582        return 1.0 - (dist as f64 / maximum as f64);
583    }
584    let s1: Vec<char> = a.chars().collect();
585    let s2: Vec<char> = b.chars().collect();
586    let maximum = std::cmp::max(s1.len(), s2.len());
587    if maximum == 0 {
588        return 1.0;
589    }
590    // Latin-1 char tier for accented short patterns; else multiword.
591    let dist = match sw_peq(&s1) {
592        Some(peq) if !s1.is_empty() => levenshtein_distance_sw(&s1, &s2, |c: char| sw_get(&peq, c)),
593        _ => levenshtein_distance(&s1, &s2),
594    };
595    1.0 - (dist as f64 / maximum as f64)
596}
597
598// ---------------------------------------------------------------------------
599// Indel / fuzz::ratio  (LCS-based, substitution-free edit distance)
600// ---------------------------------------------------------------------------
601
602/// Longest common subsequence length, bit-parallel (Allison-Dix). The PATTERN
603/// `a` is packed one bit per position; each text char advances the LCS row with
604/// `V = (V + (V & Peq[c])) | (V - (V & Peq[c]))`, and the LCS length is the count
605/// of ZERO bits left in `V`. Integer result identical to the naive DP and to
606/// rapidfuzz's LCS kernel (proven in tests, incl. the multiword boundaries).
607fn lcs_length(a: &[char], b: &[char]) -> usize {
608    if a.is_empty() || b.is_empty() {
609        return 0;
610    }
611    lcs_length_mw(a, b, &peq_multiword(a))
612}
613
614/// Multiword Allison-Dix body over a PREPARED peq (one-vs-many amortisation).
615/// Caller guarantees `a` and `b` non-empty.
616fn lcs_length_mw(a: &[char], b: &[char], peq: &MwPeq) -> usize {
617    let m = a.len();
618    let nw = nwords(m);
619    let tmask = top_mask(m);
620    let empty = vec![0u64; nw];
621
622    let mut v = vec![u64::MAX; nw];
623    v[nw - 1] &= tmask;
624    let mut u = vec![0u64; nw];
625    let mut add = vec![0u64; nw];
626    let mut sub = vec![0u64; nw];
627    for &cb in b {
628        let p = peq.get(cb, &empty);
629        for i in 0..nw {
630            u[i] = v[i] & p[i];
631        }
632        bv_add(&v, &u, &mut add);
633        add[nw - 1] &= tmask;
634        bv_sub(&v, &u, &mut sub);
635        for i in 0..nw {
636            v[i] = add[i] | sub[i];
637        }
638    }
639    v[nw - 1] &= tmask;
640    m - bv_popcount(&v)
641}
642
643/// `rapidfuzz::fuzz::ratio` == Indel `normalized_similarity` on `[0, 1]`:
644/// indel distance `= len1 + len2 - 2*lcs`, maximum `= len1 + len2`,
645/// `sim = 1.0 - dist / maximum` (`maximum == 0 -> 1.0`).
646pub fn indel_ratio(a: &str, b: &str) -> f64 {
647    // ASCII single-word fast path (no Vec<char>, 1 KiB stack peq). lcs_length_sw
648    // is safe for an empty side (returns 0), so `a.len()` may be 0..=64 here.
649    if a.is_ascii() && b.is_ascii() && a.len() <= SW_MAX {
650        let ab = a.as_bytes();
651        let bb = b.as_bytes();
652        let maximum = ab.len() + bb.len();
653        if maximum == 0 {
654            return 1.0;
655        }
656        let peq = byte_peq(ab);
657        let lcs = lcs_length_sw(ab, bb, |x: u8| peq[(x & 0x7f) as usize]);
658        return 1.0 - ((maximum - 2 * lcs) as f64 / maximum as f64);
659    }
660    let s1: Vec<char> = a.chars().collect();
661    let s2: Vec<char> = b.chars().collect();
662    let maximum = s1.len() + s2.len();
663    if maximum == 0 {
664        return 1.0;
665    }
666    // Latin-1 char tier for accented short patterns; else multiword.
667    let lcs = match sw_peq(&s1) {
668        Some(peq) => lcs_length_sw(&s1, &s2, |c: char| sw_get(&peq, c)),
669        None => lcs_length(&s1, &s2),
670    };
671    let dist = maximum - 2 * lcs;
672    1.0 - (dist as f64 / maximum as f64)
673}
674
675// ---------------------------------------------------------------------------
676// One-vs-many: BatchComparator / extract / cdist (amortised query peq)
677// ---------------------------------------------------------------------------
678//
679// The dominant per-pair cost is building the query's position bitmap (~16us for
680// a 600-char HashMap peq, ~3us flat). In a one-vs-many workload (a query vs many
681// choices -- fuzzy dedup, record linkage, autocomplete) that build is pure
682// repeated work. `BatchComparator` builds it ONCE and reuses it across every
683// choice, exactly like rapidfuzz's `process.cdist` / `BatchComparator`. Results
684// are byte-identical to the per-pair scorers (proven in tests).
685
686/// Which normalized-similarity scorer the batch API uses (all on `[0, 1]`).
687#[derive(Clone, Copy, Debug, PartialEq, Eq)]
688pub enum Scorer {
689    /// `jaro_winkler` normalized similarity.
690    JaroWinkler,
691    /// `levenshtein` normalized similarity.
692    Levenshtein,
693    /// `indel` normalized similarity (== `fuzz::ratio`).
694    Indel,
695}
696
697/// How a prepared query scores its choices.
698///
699/// For a `<= 64`-codepoint query the peq build is cheap (~80ns) and the per-pair
700/// path already has a zero-alloc byte tier that beats rapidfuzz, so we just reuse
701/// it (no `Vec<char>` collect per choice). Amortising only pays off for the
702/// EXPENSIVE multiword peq (a long / non-Latin-1 query, ~16us HashMap / ~3us
703/// flat), which we build once and reuse.
704enum Prepared {
705    PerPair(String),
706    Mw { q: Vec<char>, peq: MwPeq },
707}
708
709/// A query prepared for one-vs-many scoring (rapidfuzz's `BatchComparator` /
710/// `cdist`). Byte-identical to the per-pair scorers.
711pub struct BatchComparator {
712    prep: Prepared,
713}
714
715impl BatchComparator {
716    pub fn new(query: &str) -> Self {
717        let qc: Vec<char> = query.chars().collect();
718        let prep = if qc.len() <= SW_MAX {
719            Prepared::PerPair(query.to_string())
720        } else {
721            let peq = peq_multiword(&qc);
722            Prepared::Mw { q: qc, peq }
723        };
724        BatchComparator { prep }
725    }
726
727    pub fn jaro_winkler(&self, choice: &str) -> f64 {
728        match &self.prep {
729            Prepared::PerPair(qs) => jaro_winkler(qs, choice),
730            Prepared::Mw { q, peq } => {
731                let c: Vec<char> = choice.chars().collect();
732                // q.len() > 64, so only the empty-choice edge can fire here.
733                let raw = if c.is_empty() {
734                    0.0
735                } else {
736                    jaro_similarity_mw(q, &c, peq)
737                };
738                jaro_winkler_combine(q, &c, raw)
739            }
740        }
741    }
742
743    pub fn levenshtein(&self, choice: &str) -> f64 {
744        match &self.prep {
745            Prepared::PerPair(qs) => levenshtein_normalized_similarity(qs, choice),
746            Prepared::Mw { q, peq } => {
747                let c: Vec<char> = choice.chars().collect();
748                let maximum = std::cmp::max(q.len(), c.len());
749                let dist = if c.is_empty() {
750                    q.len()
751                } else {
752                    levenshtein_distance_mw(q, &c, peq)
753                };
754                1.0 - (dist as f64 / maximum as f64)
755            }
756        }
757    }
758
759    pub fn indel(&self, choice: &str) -> f64 {
760        match &self.prep {
761            Prepared::PerPair(qs) => indel_ratio(qs, choice),
762            Prepared::Mw { q, peq } => {
763                let c: Vec<char> = choice.chars().collect();
764                let maximum = q.len() + c.len();
765                let lcs = if c.is_empty() {
766                    0
767                } else {
768                    lcs_length_mw(q, &c, peq)
769                };
770                1.0 - ((maximum - 2 * lcs) as f64 / maximum as f64)
771            }
772        }
773    }
774
775    #[inline]
776    pub fn score(&self, choice: &str, scorer: Scorer) -> f64 {
777        match scorer {
778            Scorer::JaroWinkler => self.jaro_winkler(choice),
779            Scorer::Levenshtein => self.levenshtein(choice),
780            Scorer::Indel => self.indel(choice),
781        }
782    }
783}
784
785/// One-vs-many top-k. Scores `query` against each choice with `scorer` (the
786/// query peq is built once), keeps scores `>= score_cutoff`, and returns up to
787/// `limit` `(choice_index, score)` pairs, highest score first (ties broken by
788/// lower index). `limit == 0` means no limit.
789pub fn extract(
790    query: &str,
791    choices: &[&str],
792    scorer: Scorer,
793    score_cutoff: f64,
794    limit: usize,
795) -> Vec<(usize, f64)> {
796    let bc = BatchComparator::new(query);
797    let mut scored: Vec<(usize, f64)> = choices
798        .iter()
799        .enumerate()
800        .map(|(i, &c)| (i, bc.score(c, scorer)))
801        .filter(|&(_, s)| s >= score_cutoff)
802        .collect();
803    scored.sort_by(|a, b| {
804        b.1.partial_cmp(&a.1)
805            .unwrap_or(std::cmp::Ordering::Equal)
806            .then(a.0.cmp(&b.0))
807    });
808    if limit != 0 && scored.len() > limit {
809        scored.truncate(limit);
810    }
811    scored
812}
813
814/// Full one-vs-many score matrix: `out[i][j]` = `scorer(queries[i], choices[j])`.
815/// Each query's peq is built once and reused across all choices.
816pub fn cdist(queries: &[&str], choices: &[&str], scorer: Scorer) -> Vec<Vec<f64>> {
817    queries
818        .iter()
819        .map(|&q| {
820            let bc = BatchComparator::new(q);
821            choices.iter().map(|&c| bc.score(c, scorer)).collect()
822        })
823        .collect()
824}
825
826// ---------------------------------------------------------------------------
827// Damerau-Levenshtein (true / unrestricted, Lowrance-Wagner)
828// ---------------------------------------------------------------------------
829
830/// True Damerau-Levenshtein edit distance (adjacent transposition = 1 edit,
831/// unrestricted), matching `rapidfuzz::distance::damerau_levenshtein::distance`.
832/// Integer result; used by the date comparator over 8 packed digits.
833pub fn damerau_levenshtein_distance<T: Eq + Hash + Copy>(a: &[T], b: &[T]) -> usize {
834    let la = a.len();
835    let lb = b.len();
836    if la == 0 {
837        return lb;
838    }
839    if lb == 0 {
840        return la;
841    }
842    let inf = la + lb;
843    // (la+2) x (lb+2) matrix, offset by 1 so row/col 0 hold the INF sentinels.
844    let w = lb + 2;
845    let mut d = vec![0usize; (la + 2) * w];
846    let at = |i: usize, j: usize| i * w + j;
847    d[at(0, 0)] = inf;
848    for i in 0..=la {
849        d[at(i + 1, 0)] = inf;
850        d[at(i + 1, 1)] = i;
851    }
852    for j in 0..=lb {
853        d[at(0, j + 1)] = inf;
854        d[at(1, j + 1)] = j;
855    }
856    let mut last: HashMap<T, usize> = HashMap::new();
857    for i in 1..=la {
858        let mut db = 0usize; // last column in row i where a[i-1] matched b
859        for j in 1..=lb {
860            let k = last.get(&b[j - 1]).copied().unwrap_or(0); // last row with b[j-1]
861            let l = db;
862            let cost = if a[i - 1] == b[j - 1] {
863                db = j;
864                0
865            } else {
866                1
867            };
868            let sub = d[at(i, j)] + cost;
869            let ins = d[at(i + 1, j)] + 1;
870            let del = d[at(i, j + 1)] + 1;
871            let trans = d[at(k, l)] + (i - k - 1) + 1 + (j - l - 1);
872            d[at(i + 1, j + 1)] = sub.min(ins).min(del).min(trans);
873        }
874        last.insert(a[i - 1], i);
875    }
876    d[at(la + 1, lb + 1)]
877}
878
879// ---------------------------------------------------------------------------
880// fuzz::* composite scorers  (rapidfuzz `fuzz` module, byte-identical)
881// ---------------------------------------------------------------------------
882//
883// Faithful ports of rapidfuzz's PURE-PYTHON reference (`rapidfuzz/fuzz_py.py`
884// + `distance/Indel_py.py`), all returning a float in [0, 100]. The rapidfuzz
885// Rust crate 0.5.0 only exposes `fuzz::ratio`, so these are proven byte-for-byte
886// against the Python `rapidfuzz.fuzz.*` oracle (the `emit_fuzz_corpus` test dumps
887// a large deterministic corpus that `scripts/check_fuzz_parity.py` cross-checks).
888//
889// The internal `*_cut` variants thread rapidfuzz's `score_cutoff` EXACTLY as the
890// reference does (WRatio bumps `score_cutoff = max(sc, end_ratio) / SCALE` before
891// each sub-call, which can early-return 0 and change the final `max`). The public
892// entry points pass `score_cutoff = 0.0`, which is behaviorally identical to the
893// reference's `None` (a threshold of 0 never zeroes a non-negative score).
894
895/// rapidfuzz's tokenizer whitespace test, matching the SHIPPED `rapidfuzz.fuzz`
896/// (its C++ `common::is_space<CharT>`). This is WIDTH-DEPENDENT and does NOT
897/// match Python `str.split()`: rapidfuzz picks the smallest integer element type
898/// holding a string's max codepoint (uint8 for all-Latin1, uint16/uint32
899/// otherwise), and `is_space` for the 8-bit type EXCLUDES `0x85` (NEL) and `0xA0`
900/// (NBSP) even though they fit in a byte. So an all-Latin1 string does NOT split
901/// on NEL/NBSP, while any string containing a codepoint > 0xFF does (matching the
902/// pure-Python `str.split()` there). This is DECISIVE per-string (a narrow s1
903/// keeps its NBSP regardless of a wide s2 — verified against the C++ default).
904/// `0x1C..=0x1F` (info separators) split in both widths. All other cases verified
905/// char-by-char over the Python whitespace set + `0x180E`/`0x200B`/`0xFEFF`.
906#[inline]
907fn is_rf_whitespace(c: char, wide: bool) -> bool {
908    let cp = c as u32;
909    if matches!(cp, 0x09..=0x0D | 0x1C..=0x1F | 0x20) {
910        return true;
911    }
912    // NEL/NBSP + the Unicode space separators: only for a "wide" (any codepoint
913    // > 0xFF) string. (The 0x1680.. separators are themselves > 0xFF, so they can
914    // only appear in a wide string anyway; the load-bearing gate is NEL/NBSP.)
915    wide && matches!(
916        cp,
917        0x85 | 0xA0 | 0x1680 | 0x2000..=0x200A | 0x2028 | 0x2029 | 0x202F | 0x205F | 0x3000
918    )
919}
920
921/// rapidfuzz's `_split_sequence` on a string (its C++ tokenizer): split on runs
922/// of whitespace (see `is_rf_whitespace`), drop empty tokens. Preserves order
923/// and duplicates (the `token_sort` / list path). The whitespace set is chosen
924/// per string from its own max codepoint (uint8 vs wider).
925fn split_tokens(s: &str) -> Vec<String> {
926    let wide = s.chars().any(|c| c as u32 > 0xFF);
927    let mut out: Vec<String> = Vec::new();
928    let mut cur = String::new();
929    for c in s.chars() {
930        if is_rf_whitespace(c, wide) {
931            if !cur.is_empty() {
932                out.push(std::mem::take(&mut cur));
933            }
934        } else {
935            cur.push(c);
936        }
937    }
938    if !cur.is_empty() {
939        out.push(cur);
940    }
941    out
942}
943
944/// `_join_splitted_sequence`: single-space join (`" ".join(tokens)`); empty -> "".
945#[inline]
946fn join_tokens(tokens: &[String]) -> String {
947    tokens.join(" ")
948}
949
950/// Codepoint length of `" ".join(tokens)` without building the string
951/// (`len(_join_splitted_sequence(intersect))`, order-independent).
952#[inline]
953fn joined_len_refs(v: &[&String]) -> usize {
954    if v.is_empty() {
955        0
956    } else {
957        v.iter().map(|s| s.chars().count()).sum::<usize>() + v.len() - 1
958    }
959}
960
961/// Indel normalized similarity on `[0, 1]` for codepoint slices (== `fuzz.ratio`
962/// / 100). `maximum == 0 -> 1.0` (both empty). Byte-identical to `indel_ratio`.
963#[inline]
964fn indel_sim01_chars(a: &[char], b: &[char]) -> f64 {
965    let maximum = a.len() + b.len();
966    if maximum == 0 {
967        return 1.0;
968    }
969    let lcs = lcs_length(a, b);
970    let dist = maximum - 2 * lcs;
971    1.0 - (dist as f64 / maximum as f64)
972}
973
974/// Indel edit distance `len1 + len2 - 2*lcs` for codepoint slices.
975#[inline]
976fn indel_distance_chars(a: &[char], b: &[char]) -> usize {
977    let lcs = lcs_length(a, b);
978    a.len() + b.len() - 2 * lcs
979}
980
981/// `_norm_distance(dist, lensum, score_cutoff)`: `100 - 100*dist/lensum`
982/// (`lensum == 0 -> 100`), zeroed below `score_cutoff`. Operation order matches
983/// the reference (`100 - 100 * dist / lensum`, left-associative).
984#[inline]
985fn norm_distance(dist: usize, lensum: usize, score_cutoff: f64) -> f64 {
986    let score = if lensum != 0 {
987        100.0 - 100.0 * (dist as f64) / (lensum as f64)
988    } else {
989        100.0
990    };
991    if score >= score_cutoff {
992        score
993    } else {
994        0.0
995    }
996}
997
998/// `ratio` on codepoint slices with a `score_cutoff` in `[0, 100]`. The reference
999/// divides the cutoff by 100 and gates `norm_sim >= score_cutoff/100` before the
1000/// `* 100` scale-up.
1001#[inline]
1002fn ratio_cut(a: &[char], b: &[char], score_cutoff: f64) -> f64 {
1003    let sim01 = indel_sim01_chars(a, b);
1004    if sim01 >= score_cutoff / 100.0 {
1005        sim01 * 100.0
1006    } else {
1007        0.0
1008    }
1009}
1010
1011/// `_partial_ratio_impl` (short-needle path): slides `s1` (the shorter string)
1012/// across `s2` and returns the best `fuzz.ratio` in `[0, 100]`. Assumes
1013/// `s1.len() <= s2.len()`. Replicates the three window loops, the
1014/// `s2[...] in set(s1)` guards, the running `score_cutoff`, and the exact-match
1015/// early return EXACTLY.
1016fn partial_ratio_impl(s1: &[char], s2: &[char], mut cutoff_frac: f64) -> f64 {
1017    let len1 = s1.len();
1018    let len2 = s2.len();
1019    // Empty needle: every window guard fails (set(s1) is empty) -> 0.0. (Also
1020    // sidesteps the reference's Python-negative-index `s2[i+len1-1]` when len1==0.)
1021    if len1 == 0 {
1022        return 0.0;
1023    }
1024    let s1_set: HashSet<char> = s1.iter().copied().collect();
1025    let mut best = 0.0_f64; // best sim01 seen (fraction)
1026
1027    // Returns true on an exact-match early exit (score forced to 100).
1028    macro_rules! consider {
1029        ($window:expr) => {{
1030            let sim = indel_sim01_chars(s1, $window);
1031            let ls = if sim >= cutoff_frac { sim } else { 0.0 };
1032            if ls > best {
1033                best = ls;
1034                cutoff_frac = ls;
1035                if ls == 1.0 {
1036                    return 100.0;
1037                }
1038            }
1039        }};
1040    }
1041
1042    // loop 1: windows s2[0..i], i in 1..len1  (guard: s2[i-1] in set(s1))
1043    for i in 1..len1 {
1044        if !s1_set.contains(&s2[i - 1]) {
1045            continue;
1046        }
1047        consider!(&s2[0..i]);
1048    }
1049    // loop 2: windows s2[i..i+len1], i in 0..len2-len1  (guard: s2[i+len1-1])
1050    for i in 0..(len2 - len1) {
1051        if !s1_set.contains(&s2[i + len1 - 1]) {
1052            continue;
1053        }
1054        consider!(&s2[i..i + len1]);
1055    }
1056    // loop 3: windows s2[i..len2], i in len2-len1..len2  (guard: s2[i])
1057    for i in (len2 - len1)..len2 {
1058        if !s1_set.contains(&s2[i]) {
1059            continue;
1060        }
1061        consider!(&s2[i..len2]);
1062    }
1063    best * 100.0
1064}
1065
1066/// `partial_ratio` / `partial_ratio_alignment` score on codepoint slices, in
1067/// `[0, 100]`. Runs `_partial_ratio_impl` on the shorter-in-longer, adds the
1068/// `len1 == len2` swapped re-run, and applies the outer `score < score_cutoff ->
1069/// None (0)` gate.
1070fn partial_ratio_cut(s1: &[char], s2: &[char], score_cutoff: f64) -> f64 {
1071    // Both empty -> ScoreAlignment(100.0), returned before the cutoff gate.
1072    if s1.is_empty() && s2.is_empty() {
1073        return 100.0;
1074    }
1075    let len1 = s1.len();
1076    let len2 = s2.len();
1077    let (shorter, longer) = if len1 <= len2 { (s1, s2) } else { (s2, s1) };
1078
1079    let mut res_score = partial_ratio_impl(shorter, longer, score_cutoff / 100.0);
1080    if res_score != 100.0 && len1 == len2 {
1081        let sc2 = f64::max(score_cutoff, res_score);
1082        let res2 = partial_ratio_impl(longer, shorter, sc2 / 100.0);
1083        if res2 > res_score {
1084            res_score = res2;
1085        }
1086    }
1087    if res_score < score_cutoff {
1088        return 0.0;
1089    }
1090    res_score
1091}
1092
1093/// `token_sort_ratio`: sort the token LIST (dups kept), join, `ratio`.
1094fn token_sort_ratio_cut(s1: &str, s2: &str, score_cutoff: f64) -> f64 {
1095    let mut t1 = split_tokens(s1);
1096    t1.sort();
1097    let mut t2 = split_tokens(s2);
1098    t2.sort();
1099    let j1: Vec<char> = join_tokens(&t1).chars().collect();
1100    let j2: Vec<char> = join_tokens(&t2).chars().collect();
1101    ratio_cut(&j1, &j2, score_cutoff)
1102}
1103
1104/// `token_set_ratio`: the intersect/diff formula, EXACTLY as `fuzz_py.py`.
1105fn token_set_ratio_cut(s1: &str, s2: &str, score_cutoff: f64) -> f64 {
1106    let a: BTreeSet<String> = split_tokens(s1).into_iter().collect();
1107    let b: BTreeSet<String> = split_tokens(s2).into_iter().collect();
1108    if a.is_empty() || b.is_empty() {
1109        return 0.0;
1110    }
1111    let inter: Vec<&String> = a.intersection(&b).collect();
1112    let diff_ab: Vec<String> = a.difference(&b).cloned().collect(); // BTreeSet -> sorted
1113    let diff_ba: Vec<String> = b.difference(&a).cloned().collect();
1114    // one sentence is part of the other one
1115    if !inter.is_empty() && (diff_ab.is_empty() || diff_ba.is_empty()) {
1116        return 100.0;
1117    }
1118
1119    let diff_ab_joined = join_tokens(&diff_ab);
1120    let diff_ba_joined = join_tokens(&diff_ba);
1121    let ab_len = diff_ab_joined.chars().count();
1122    let ba_len = diff_ba_joined.chars().count();
1123    let sect_len = joined_len_refs(&inter);
1124    let sect_flag = usize::from(sect_len != 0);
1125
1126    let sect_ab_len = sect_len + sect_flag + ab_len;
1127    let sect_ba_len = sect_len + sect_flag + ba_len;
1128    let lensum = sect_ab_len + sect_ba_len;
1129
1130    let mut result = 0.0_f64;
1131    let cutoff_distance = (lensum as f64 * (1.0 - score_cutoff / 100.0)).ceil();
1132    let dab: Vec<char> = diff_ab_joined.chars().collect();
1133    let dba: Vec<char> = diff_ba_joined.chars().collect();
1134    let dist = indel_distance_chars(&dab, &dba);
1135    if (dist as f64) <= cutoff_distance {
1136        result = norm_distance(dist, lensum, score_cutoff);
1137    }
1138
1139    // exit early since the other ratios are 0
1140    if sect_len == 0 {
1141        return result;
1142    }
1143
1144    let sect_ab_dist = sect_flag + ab_len;
1145    let sect_ab_ratio = norm_distance(sect_ab_dist, sect_len + sect_ab_len, score_cutoff);
1146    let sect_ba_dist = sect_flag + ba_len;
1147    let sect_ba_ratio = norm_distance(sect_ba_dist, sect_len + sect_ba_len, score_cutoff);
1148
1149    result.max(sect_ab_ratio).max(sect_ba_ratio)
1150}
1151
1152/// `token_ratio` = `max(token_set_ratio, token_sort_ratio)`.
1153fn token_ratio_cut(s1: &str, s2: &str, score_cutoff: f64) -> f64 {
1154    f64::max(
1155        token_set_ratio_cut(s1, s2, score_cutoff),
1156        token_sort_ratio_cut(s1, s2, score_cutoff),
1157    )
1158}
1159
1160/// `partial_token_sort_ratio`: sort the token LIST, join, `partial_ratio`.
1161fn partial_token_sort_ratio_cut(s1: &str, s2: &str, score_cutoff: f64) -> f64 {
1162    let mut t1 = split_tokens(s1);
1163    t1.sort();
1164    let mut t2 = split_tokens(s2);
1165    t2.sort();
1166    let j1: Vec<char> = join_tokens(&t1).chars().collect();
1167    let j2: Vec<char> = join_tokens(&t2).chars().collect();
1168    partial_ratio_cut(&j1, &j2, score_cutoff)
1169}
1170
1171/// `partial_token_set_ratio`: common-word early-100, else `partial_ratio` of the
1172/// sorted-unique diffs.
1173fn partial_token_set_ratio_cut(s1: &str, s2: &str, score_cutoff: f64) -> f64 {
1174    let a: BTreeSet<String> = split_tokens(s1).into_iter().collect();
1175    let b: BTreeSet<String> = split_tokens(s2).into_iter().collect();
1176    if a.is_empty() || b.is_empty() {
1177        return 0.0;
1178    }
1179    if a.intersection(&b).next().is_some() {
1180        return 100.0;
1181    }
1182    let diff_ab: Vec<String> = a.difference(&b).cloned().collect();
1183    let diff_ba: Vec<String> = b.difference(&a).cloned().collect();
1184    let j1: Vec<char> = join_tokens(&diff_ab).chars().collect();
1185    let j2: Vec<char> = join_tokens(&diff_ba).chars().collect();
1186    partial_ratio_cut(&j1, &j2, score_cutoff)
1187}
1188
1189/// `partial_token_ratio` = max of the sorted-list partial ratio and (unless the
1190/// diffs equal the whole token lists) the sorted-diff partial ratio, threading
1191/// `score_cutoff = max(cutoff, result)` between the two.
1192fn partial_token_ratio_cut(s1: &str, s2: &str, score_cutoff: f64) -> f64 {
1193    let list_a = split_tokens(s1);
1194    let list_b = split_tokens(s2);
1195    let a: BTreeSet<String> = list_a.iter().cloned().collect();
1196    let b: BTreeSet<String> = list_b.iter().cloned().collect();
1197    if a.intersection(&b).next().is_some() {
1198        return 100.0;
1199    }
1200    let diff_ab: Vec<String> = a.difference(&b).cloned().collect();
1201    let diff_ba: Vec<String> = b.difference(&a).cloned().collect();
1202
1203    let mut sorted_a = list_a.clone();
1204    sorted_a.sort();
1205    let mut sorted_b = list_b.clone();
1206    sorted_b.sort();
1207    let ja: Vec<char> = join_tokens(&sorted_a).chars().collect();
1208    let jb: Vec<char> = join_tokens(&sorted_b).chars().collect();
1209    let result = partial_ratio_cut(&ja, &jb, score_cutoff);
1210
1211    // do not calculate the same partial_ratio twice
1212    if list_a.len() == diff_ab.len() && list_b.len() == diff_ba.len() {
1213        return result;
1214    }
1215    let cutoff2 = f64::max(score_cutoff, result);
1216    let jda: Vec<char> = join_tokens(&diff_ab).chars().collect();
1217    let jdb: Vec<char> = join_tokens(&diff_ba).chars().collect();
1218    result.max(partial_ratio_cut(&jda, &jdb, cutoff2))
1219}
1220
1221// ---- Public fuzz entry points (score_cutoff = 0, == reference `None`) --------
1222
1223/// `fuzz.ratio` in `[0, 100]` (Indel normalized similarity * 100).
1224pub fn ratio(a: &str, b: &str) -> f64 {
1225    indel_ratio(a, b) * 100.0
1226}
1227
1228/// `fuzz.partial_ratio` in `[0, 100]`.
1229pub fn partial_ratio(a: &str, b: &str) -> f64 {
1230    let s1: Vec<char> = a.chars().collect();
1231    let s2: Vec<char> = b.chars().collect();
1232    partial_ratio_cut(&s1, &s2, 0.0)
1233}
1234
1235/// `fuzz.token_sort_ratio` in `[0, 100]`.
1236pub fn token_sort_ratio(a: &str, b: &str) -> f64 {
1237    token_sort_ratio_cut(a, b, 0.0)
1238}
1239
1240/// `fuzz.token_set_ratio` in `[0, 100]`.
1241pub fn token_set_ratio(a: &str, b: &str) -> f64 {
1242    token_set_ratio_cut(a, b, 0.0)
1243}
1244
1245/// `fuzz.token_ratio` = `max(token_set_ratio, token_sort_ratio)`.
1246pub fn token_ratio(a: &str, b: &str) -> f64 {
1247    token_ratio_cut(a, b, 0.0)
1248}
1249
1250/// `fuzz.partial_token_sort_ratio` in `[0, 100]`.
1251pub fn partial_token_sort_ratio(a: &str, b: &str) -> f64 {
1252    partial_token_sort_ratio_cut(a, b, 0.0)
1253}
1254
1255/// `fuzz.partial_token_set_ratio` in `[0, 100]`.
1256pub fn partial_token_set_ratio(a: &str, b: &str) -> f64 {
1257    partial_token_set_ratio_cut(a, b, 0.0)
1258}
1259
1260/// `fuzz.partial_token_ratio` in `[0, 100]`.
1261pub fn partial_token_ratio(a: &str, b: &str) -> f64 {
1262    partial_token_ratio_cut(a, b, 0.0)
1263}
1264
1265/// `fuzz.WRatio` — the composite weighted ratio in `[0, 100]`. Empty input -> 0.
1266pub fn w_ratio(a: &str, b: &str) -> f64 {
1267    // in FuzzyWuzzy this returns 0 -- keep parity (rapidfuzz issue #110).
1268    if a.is_empty() || b.is_empty() {
1269        return 0.0;
1270    }
1271    const UNBASE_SCALE: f64 = 0.95;
1272    let s1: Vec<char> = a.chars().collect();
1273    let s2: Vec<char> = b.chars().collect();
1274    let len1 = s1.len();
1275    let len2 = s2.len();
1276    let len_ratio = if len1 > len2 {
1277        len1 as f64 / len2 as f64
1278    } else {
1279        len2 as f64 / len1 as f64
1280    };
1281
1282    let mut score_cutoff = 0.0_f64;
1283    let end_ratio = ratio_cut(&s1, &s2, score_cutoff);
1284    if len_ratio < 1.5 {
1285        score_cutoff = f64::max(score_cutoff, end_ratio) / UNBASE_SCALE;
1286        return f64::max(
1287            end_ratio,
1288            token_ratio_cut(a, b, score_cutoff) * UNBASE_SCALE,
1289        );
1290    }
1291
1292    let partial_scale = if len_ratio <= 8.0 { 0.9 } else { 0.6 };
1293    score_cutoff = f64::max(score_cutoff, end_ratio) / partial_scale;
1294    let end_ratio = f64::max(
1295        end_ratio,
1296        partial_ratio_cut(&s1, &s2, score_cutoff) * partial_scale,
1297    );
1298
1299    score_cutoff = f64::max(score_cutoff, end_ratio) / UNBASE_SCALE;
1300    f64::max(
1301        end_ratio,
1302        partial_token_ratio_cut(a, b, score_cutoff) * UNBASE_SCALE * partial_scale,
1303    )
1304}
1305
1306/// `fuzz.QRatio` = `ratio`, except two empty (or one-empty) strings return 0.
1307pub fn q_ratio(a: &str, b: &str) -> f64 {
1308    if a.is_empty() || b.is_empty() {
1309        return 0.0;
1310    }
1311    indel_ratio(a, b) * 100.0
1312}
1313
1314#[cfg(test)]
1315mod tests {
1316    use super::*;
1317
1318    #[test]
1319    fn basic_identities() {
1320        assert_eq!(jaro_winkler("", ""), 1.0);
1321        assert_eq!(jaro_winkler("abc", ""), 0.0);
1322        assert_eq!(jaro_winkler("abc", "abc"), 1.0);
1323        assert_eq!(levenshtein_normalized_similarity("", ""), 1.0);
1324        assert_eq!(levenshtein_normalized_similarity("abc", "abc"), 1.0);
1325        assert_eq!(indel_ratio("", ""), 1.0);
1326        assert_eq!(indel_ratio("abc", "abc"), 1.0);
1327        assert_eq!(damerau_levenshtein_distance(b"abcd", b"acbd"), 1); // one transposition
1328        assert_eq!(damerau_levenshtein_distance(b"ca", b"abc"), 2);
1329    }
1330
1331    // ---- Byte-identical parity vs the rapidfuzz crate (the proof gate) ----
1332    // rapidfuzz is a dev-dependency ONLY; the shipped path uses the vendored
1333    // fns above. This module proves they are bit-for-bit identical so the swap
1334    // is a pure sovereignty change with zero output drift.
1335    use rapidfuzz::distance::{damerau_levenshtein as rf_dl, levenshtein as rf_lev};
1336    use rapidfuzz::{distance::jaro_winkler as rf_jw, fuzz as rf_fuzz};
1337
1338    // Deterministic SplitMix64 corpus generator (no rand dep, stable).
1339    fn next(state: &mut u64) -> u64 {
1340        *state = state.wrapping_add(0x9E37_79B9_7F4A_7C15);
1341        let mut z = *state;
1342        z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
1343        z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
1344        z ^ (z >> 31)
1345    }
1346
1347    // Small alphabet forces frequent matches/transpositions/repeats — the exact
1348    // regime where Jaro transposition order and DL transposition edges bite.
1349    const ALPHABET: &[char] = &['a', 'b', 'c', 'd', 'e', 'é', '1', '2', ' '];
1350
1351    fn gen(rng: &mut u64, max_len: usize) -> String {
1352        let len = (next(rng) as usize) % (max_len + 1);
1353        (0..len)
1354            .map(|_| ALPHABET[(next(rng) as usize) % ALPHABET.len()])
1355            .collect()
1356    }
1357
1358    fn assert_bits(name: &str, a: &str, b: &str, mine: f64, theirs: f64) {
1359        assert_eq!(
1360            mine.to_bits(),
1361            theirs.to_bits(),
1362            "{name} drift on ({a:?},{b:?}): mine={mine} theirs={theirs}"
1363        );
1364    }
1365
1366    #[test]
1367    fn parity_vs_rapidfuzz_crate() {
1368        let mut rng: u64 = 0xF00D_CAFE_1234_5678;
1369        // Directed edge cases first.
1370        let edge = [
1371            ("", ""),
1372            ("a", ""),
1373            ("", "a"),
1374            ("a", "a"),
1375            ("a", "b"),
1376            ("ab", "ba"),
1377            ("abc", "acb"),
1378            ("martha", "marhta"),
1379            ("dwayne", "duane"),
1380            ("dixon", "dicksonx"),
1381            ("aabbcc", "abcabc"),
1382            ("2026-07-26", "2026-07-25"),
1383            ("caaba", "aabac"),
1384        ];
1385        for (a, b) in edge {
1386            check_pair(a, b);
1387        }
1388        // 40k randomized pairs across length regimes (0..1..2..long).
1389        for _ in 0..40_000 {
1390            let ml = [1usize, 2, 3, 6, 12, 24][(next(&mut rng) as usize) % 6];
1391            let a = gen(&mut rng, ml);
1392            let b = gen(&mut rng, ml);
1393            check_pair(&a, &b);
1394        }
1395        // 20k pairs in the MULTIWORD regime (patterns > 64 codepoints), so the
1396        // bit-parallel kernels' carry/borrow across u64 limbs is proven vs
1397        // rapidfuzz, not just the single-limb path.
1398        for _ in 0..20_000 {
1399            let ml = [40usize, 64, 65, 100, 128, 130, 200][(next(&mut rng) as usize) % 7];
1400            let a = gen(&mut rng, ml);
1401            let b = gen(&mut rng, ml);
1402            check_pair(&a, &b);
1403        }
1404    }
1405
1406    #[test]
1407    fn fast_path_short_pattern_long_text_and_fallback() {
1408        // The single-word fast path gates on the PATTERN (<=64), but the TEXT can
1409        // be arbitrarily long -> exercise short-pattern / long-text pairs (the
1410        // regime the equal-length corpus never hits), plus non-Latin-1 codepoints
1411        // that must fall through to the multiword path. All vs the rapidfuzz oracle.
1412        let mut rng: u64 = 0x5EED_F00D_1234;
1413        for _ in 0..20_000 {
1414            let a = gen(&mut rng, 64); // pattern: 0..=64 (single-word regime)
1415            let b = gen(&mut rng, 300); // text: 0..=300 (spills far past 64)
1416            check_pair(&a, &b);
1417        }
1418        // Non-Latin-1 (codepoint >= 256) forces sw_peq -> None -> multiword.
1419        let uni = [
1420            "日本語abc",
1421            "Ωμέγα x",
1422            "naïve 日",
1423            "abc日def",
1424            "Ω",
1425            "café日",
1426        ];
1427        for a in uni {
1428            for b in uni {
1429                check_pair(a, b);
1430                assert!(sw_peq(&a.chars().collect::<Vec<_>>()).is_none() || a.is_ascii());
1431            }
1432        }
1433    }
1434
1435    #[test]
1436    fn byte_tier_ascii_parity() {
1437        // Pure-ASCII inputs take the byte tier (u8 core, [u64;128], no Vec<char>).
1438        // Cover the guard edges (0/1/2/64/65 pattern lengths, empty text) plus a
1439        // large asymmetric fuzz (short pattern, long text), all vs rapidfuzz.
1440        const AB: &[char] = &['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', ' ', '1', '2'];
1441        let mk = |len: usize, off: usize| -> String {
1442            (0..len).map(|i| AB[(i + off) % AB.len()]).collect()
1443        };
1444        for &(la, lb) in &[
1445            (0usize, 0usize),
1446            (0, 5),
1447            (5, 0),
1448            (1, 1),
1449            (1, 9),
1450            (9, 1),
1451            (2, 2),
1452            (2, 200),
1453            (64, 64),
1454            (64, 200),
1455            (65, 3),
1456            (66, 66),
1457        ] {
1458            check_pair(&mk(la, 0), &mk(lb, 3));
1459        }
1460        let mut rng: u64 = 0xA5C110FF1CE;
1461        for _ in 0..30_000 {
1462            let la = (next(&mut rng) as usize) % 65; // 0..=64: pattern in byte-tier range
1463            let lb = (next(&mut rng) as usize) % 200; // text may spill past 64
1464            let a: String = (0..la)
1465                .map(|_| AB[(next(&mut rng) as usize) % AB.len()])
1466                .collect();
1467            let b: String = (0..lb)
1468                .map(|_| AB[(next(&mut rng) as usize) % AB.len()])
1469                .collect();
1470            assert!(a.is_ascii() && b.is_ascii());
1471            check_pair(&a, &b);
1472        }
1473    }
1474
1475    #[test]
1476    fn parity_vs_rapidfuzz_at_limb_boundaries() {
1477        // Exact pattern lengths straddling the 64-bit limb edges, where the
1478        // multiword shift/add/borrow is most likely to be off by a bit.
1479        for &n in &[63usize, 64, 65, 127, 128, 129, 191, 192, 193, 256] {
1480            let a: String = (0..n).map(|i| ALPHABET[i % ALPHABET.len()]).collect();
1481            let mut cb: Vec<char> = a.chars().collect();
1482            // Perturb a few interior/edge positions to exercise mismatches.
1483            for &p in &[0usize, 1, n / 2, n - 1] {
1484                cb[p] = ALPHABET[(p + 3) % ALPHABET.len()];
1485            }
1486            let b: String = cb.into_iter().collect();
1487            check_pair(&a, &b);
1488            check_pair(&b, &a); // asymmetric pattern/text roles
1489        }
1490    }
1491
1492    #[test]
1493    fn batch_matches_per_pair() {
1494        // BatchComparator / extract / cdist just amortise the query peq, so every
1495        // result must be bit-for-bit identical to the per-pair scorers.
1496        let mut rng: u64 = 0xBA7C40FF1CE;
1497        for _ in 0..20_000 {
1498            let ml = [1usize, 3, 13, 40, 64, 100, 200][(next(&mut rng) as usize) % 7];
1499            let q = gen(&mut rng, ml);
1500            let c = gen(&mut rng, ml);
1501            let bc = BatchComparator::new(&q);
1502            assert_eq!(
1503                bc.jaro_winkler(&c).to_bits(),
1504                jaro_winkler(&q, &c).to_bits()
1505            );
1506            assert_eq!(
1507                bc.levenshtein(&c).to_bits(),
1508                levenshtein_normalized_similarity(&q, &c).to_bits()
1509            );
1510            assert_eq!(bc.indel(&c).to_bits(), indel_ratio(&q, &c).to_bits());
1511        }
1512        // extract: cutoff + top-k + descending order + exact match ranks first.
1513        let choices = [
1514            "johnathan smith",
1515            "jonathan smith",
1516            "jon smith",
1517            "jane doe",
1518            "j smith",
1519        ];
1520        let got = extract("jonathan smith", &choices, Scorer::JaroWinkler, 0.5, 3);
1521        assert!(got.len() <= 3 && !got.is_empty());
1522        assert_eq!(got[0].0, 1); // the exact match
1523        for w in got.windows(2) {
1524            assert!(w[0].1 >= w[1].1);
1525        }
1526        for &(_, s) in &got {
1527            assert!(s >= 0.5);
1528        }
1529        // cdist == per-pair over the full matrix.
1530        let qs = ["abc", "café", ""];
1531        let mat = cdist(&qs, &choices, Scorer::Indel);
1532        for (i, &q) in qs.iter().enumerate() {
1533            for (j, &c) in choices.iter().enumerate() {
1534                assert_eq!(mat[i][j].to_bits(), indel_ratio(q, c).to_bits());
1535            }
1536        }
1537    }
1538
1539    // ---- fuzz::* composite scorers: directed + emitted-corpus parity ----------
1540    //
1541    // The rapidfuzz Rust crate 0.5.0 exposes only `fuzz::ratio`, so the composite
1542    // family (WRatio / token_* / partial_*) is proven against the Python
1543    // `rapidfuzz.fuzz.*` oracle: `emit_fuzz_corpus` writes a large deterministic
1544    // corpus + our results to `target/goldenfuzz_fuzz_corpus.jsonl`, which
1545    // `scripts/check_fuzz_parity.py` cross-checks (equality within 1e-9).
1546
1547    #[test]
1548    fn ratio_matches_crate_fuzz_scaled() {
1549        // `fuzz::ratio` IS in the crate -> a cheap in-Rust oracle for the *100 scale.
1550        let mut rng: u64 = 0x1234_ABCD_9876;
1551        for _ in 0..5_000 {
1552            let ml = [1usize, 3, 8, 20][(next(&mut rng) as usize) % 4];
1553            let a = gen(&mut rng, ml);
1554            let b = gen(&mut rng, ml);
1555            let mine = ratio(&a, &b);
1556            // The rapidfuzz CRATE's `fuzz::ratio` is [0,1]; Python's is *100.
1557            let theirs = rf_fuzz::ratio(a.chars(), b.chars()) * 100.0;
1558            assert_bits("ratio*100", &a, &b, mine, theirs);
1559            // QRatio == ratio for non-empty, 0 for empty.
1560            let q = q_ratio(&a, &b);
1561            if a.is_empty() || b.is_empty() {
1562                assert_eq!(q, 0.0);
1563            } else {
1564                assert_eq!(q.to_bits(), mine.to_bits());
1565            }
1566        }
1567    }
1568
1569    #[test]
1570    fn fuzz_directed_identities() {
1571        // Exact-match / subset identities are float-exact (100.0) in the reference.
1572        assert_eq!(
1573            token_sort_ratio("fuzzy wuzzy was a bear", "wuzzy fuzzy was a bear"),
1574            100.0
1575        );
1576        assert_eq!(
1577            token_set_ratio("fuzzy was a bear", "fuzzy fuzzy was a bear"),
1578            100.0
1579        );
1580        assert_eq!(
1581            token_set_ratio("fuzzy was a bear but not a dog", "fuzzy was a bear"),
1582            100.0
1583        );
1584        assert_eq!(token_ratio("a b c", "c b a"), 100.0);
1585        // ratio identities
1586        assert_eq!(ratio("", ""), 100.0);
1587        assert_eq!(q_ratio("", ""), 0.0);
1588        assert_eq!(q_ratio("abc", ""), 0.0);
1589        assert_eq!(ratio("abc", "abc"), 100.0);
1590        assert_eq!(w_ratio("", "abc"), 0.0);
1591        assert_eq!(w_ratio("abc", "abc"), 100.0);
1592        assert_eq!(partial_ratio("", ""), 100.0);
1593        assert_eq!(partial_ratio("abc", "abc"), 100.0);
1594        // rapidfuzz splits 0x1c..0x1f (info separators) in both widths.
1595        assert_eq!(split_tokens("a\u{1c}b\tc  d"), vec!["a", "b", "c", "d"]);
1596        assert_eq!(token_sort_ratio("b a", "a\u{1c}b"), 100.0);
1597        // WIDTH-DEPENDENT NBSP: an all-Latin1 string does NOT split on NBSP
1598        // (matches C++ `is_space<uint8>`), so "a\u{a0}b" stays one token; a
1599        // string with a codepoint > 0xFF DOES split on NBSP.
1600        assert_eq!(split_tokens("a\u{a0}b"), vec!["a\u{a0}b"]);
1601        assert_eq!(split_tokens("\u{4e00}\u{a0}b"), vec!["\u{4e00}", "b"]);
1602        assert_eq!(split_tokens("a\u{85}b"), vec!["a\u{85}b"]);
1603    }
1604
1605    // Deterministic corpus spanning every required category. Returns >5000 pairs.
1606    fn fuzz_corpus() -> Vec<(String, String)> {
1607        const TOKS: &[&str] = &[
1608            "john",
1609            "jon",
1610            "jonathan",
1611            "smith",
1612            "smyth",
1613            "acme",
1614            "corp",
1615            "corporation",
1616            "inc",
1617            "ltd",
1618            "the",
1619            "of",
1620            "and",
1621            "a",
1622            "bear",
1623            "fuzzy",
1624            "wuzzy",
1625            "was",
1626            "dog",
1627            "cat",
1628            "not",
1629            "but",
1630            "café",
1631            "naïve",
1632            "日本",
1633            "東京",
1634            "Ωμέγα",
1635            "müller",
1636            "strasse",
1637            "o'brien",
1638            "mary",
1639            "anne",
1640            "van",
1641            "der",
1642            "berg",
1643            "123",
1644            "2026",
1645            "x",
1646            "ab",
1647            "abc",
1648            "abcd",
1649            "z",
1650        ];
1651        const WS: &[&str] = &[" ", "  ", "\t", " \u{1c} ", "\n", "   ", " \u{a0}"];
1652        let mut rng: u64 = 0x00C0_FFEE_1234_5678;
1653        let mut out: Vec<(String, String)> = Vec::new();
1654        let tok = |rng: &mut u64| TOKS[(next(rng) as usize) % TOKS.len()];
1655        let ws = |rng: &mut u64| WS[(next(rng) as usize) % WS.len()];
1656        let phrase = |rng: &mut u64, k: usize| -> Vec<String> {
1657            (0..k).map(|_| tok(rng).to_string()).collect()
1658        };
1659        let join = |rng: &mut u64, ts: &[String]| -> String {
1660            let mut s = String::new();
1661            for (i, t) in ts.iter().enumerate() {
1662                if i > 0 {
1663                    s.push_str(ws(rng));
1664                }
1665                s.push_str(t);
1666            }
1667            s
1668        };
1669
1670        // Directed edge cases.
1671        for &(a, b) in &[
1672            ("", ""),
1673            ("a", ""),
1674            ("", "a"),
1675            ("a", "a"),
1676            ("abc", "abc"),
1677            ("this is a test", "this is a test!"),
1678            ("fuzzy wuzzy was a bear", "wuzzy fuzzy was a bear"),
1679            ("fuzzy was a bear", "fuzzy fuzzy was a bear"),
1680            (
1681                "fuzzy was a bear but not a dog",
1682                "fuzzy was a bear but not a cat",
1683            ),
1684            ("fuzzy was a bear but not a dog", "fuzzy was a bear"),
1685            ("a certain string", "cetain"),
1686            ("jonathan smith", "jon smith"),
1687            ("dixon", "dicksonx"),
1688            ("   ", "       "),
1689            ("a\u{1c}b c", "c b a"),
1690            ("café", "cafe"),
1691            ("Ωμέγα 日本", "日本 Ωμέγα"),
1692            ("mary anne smith", "smith mary anne"),
1693        ] {
1694            out.push((a.to_string(), b.to_string()));
1695        }
1696
1697        for _ in 0..6500 {
1698            let cat = (next(&mut rng) as usize) % 12;
1699            let (s1, s2) = match cat {
1700                0 => {
1701                    // single tokens
1702                    (tok(&mut rng).to_string(), tok(&mut rng).to_string())
1703                }
1704                1 => {
1705                    // multi-token phrases (2..6 tokens each)
1706                    let k1 = 2 + (next(&mut rng) as usize) % 5;
1707                    let k2 = 2 + (next(&mut rng) as usize) % 5;
1708                    let p1 = phrase(&mut rng, k1);
1709                    let p2 = phrase(&mut rng, k2);
1710                    (join(&mut rng, &p1), join(&mut rng, &p2))
1711                }
1712                2 => {
1713                    // identical
1714                    let k = 1 + (next(&mut rng) as usize) % 5;
1715                    let p = phrase(&mut rng, k);
1716                    let s = join(&mut rng, &p);
1717                    (s.clone(), s)
1718                }
1719                3 => {
1720                    // shuffled tokens (same set, reordered) -> token_sort/set 100
1721                    let k = 2 + (next(&mut rng) as usize) % 5;
1722                    let mut p = phrase(&mut rng, k);
1723                    let s1 = join(&mut rng, &p);
1724                    // rotate
1725                    p.rotate_left(1 + (next(&mut rng) as usize) % k);
1726                    (s1, join(&mut rng, &p))
1727                }
1728                4 => {
1729                    // subset: s2 is a subset of s1's tokens
1730                    let k = 3 + (next(&mut rng) as usize) % 4;
1731                    let p = phrase(&mut rng, k);
1732                    let take = 1 + (next(&mut rng) as usize) % k;
1733                    let sub: Vec<String> = p.iter().take(take).cloned().collect();
1734                    (join(&mut rng, &p), join(&mut rng, &sub))
1735                }
1736                5 => {
1737                    // length ratio > 8: token repeated many times
1738                    let t = tok(&mut rng).to_string();
1739                    let n = 10 + (next(&mut rng) as usize) % 8;
1740                    let big: Vec<String> = std::iter::repeat_n(t.clone(), n).collect();
1741                    (t, join(&mut rng, &big))
1742                }
1743                6 => {
1744                    // length ratio 1.5..8
1745                    let k = 1 + (next(&mut rng) as usize) % 2;
1746                    let p = phrase(&mut rng, k);
1747                    let s1 = join(&mut rng, &p);
1748                    let reps = 2 + (next(&mut rng) as usize) % 3;
1749                    let mut big = Vec::new();
1750                    for _ in 0..reps {
1751                        big.extend(p.iter().cloned());
1752                    }
1753                    (s1, join(&mut rng, &big))
1754                }
1755                7 => {
1756                    // length ratio < 1.5 (tiny edit)
1757                    let k = 1 + (next(&mut rng) as usize) % 4;
1758                    let p = phrase(&mut rng, k);
1759                    let s1 = join(&mut rng, &p);
1760                    let mut s2 = s1.clone();
1761                    if (next(&mut rng) & 1) == 0 {
1762                        s2.push('x');
1763                    } else if !s2.is_empty() {
1764                        s2.pop();
1765                    }
1766                    (s1, s2)
1767                }
1768                8 => {
1769                    // repeated tokens within a phrase
1770                    let t = tok(&mut rng).to_string();
1771                    let u = tok(&mut rng).to_string();
1772                    let p1 = vec![t.clone(), t.clone(), u.clone()];
1773                    let p2 = vec![t.clone(), u.clone(), u.clone()];
1774                    (join(&mut rng, &p1), join(&mut rng, &p2))
1775                }
1776                9 => {
1777                    // unicode-heavy
1778                    let uni = ["café", "naïve", "日本", "東京", "Ωμέγα", "müller"];
1779                    let a = uni[(next(&mut rng) as usize) % uni.len()];
1780                    let b = uni[(next(&mut rng) as usize) % uni.len()];
1781                    let w1 = ws(&mut rng);
1782                    let t1 = tok(&mut rng);
1783                    let t2 = tok(&mut rng);
1784                    let w2 = ws(&mut rng);
1785                    (format!("{a}{w1}{t1}"), format!("{t2}{w2}{b}"))
1786                }
1787                10 => {
1788                    // one empty
1789                    let p = phrase(&mut rng, 3);
1790                    let s = join(&mut rng, &p);
1791                    if (next(&mut rng) & 1) == 0 {
1792                        (String::new(), s)
1793                    } else {
1794                        (s, String::new())
1795                    }
1796                }
1797                _ => {
1798                    // char-level edits on a single token
1799                    let t = tok(&mut rng);
1800                    let mut cs: Vec<char> = t.chars().collect();
1801                    if !cs.is_empty() {
1802                        let i = (next(&mut rng) as usize) % cs.len();
1803                        cs[i] = TOKS[(next(&mut rng) as usize) % 8].chars().next().unwrap();
1804                    }
1805                    (t.to_string(), cs.into_iter().collect())
1806                }
1807            };
1808            out.push((s1, s2));
1809        }
1810        out
1811    }
1812
1813    fn json_escape(s: &str) -> String {
1814        let mut out = String::from("\"");
1815        for c in s.chars() {
1816            match c {
1817                '"' => out.push_str("\\\""),
1818                '\\' => out.push_str("\\\\"),
1819                '\n' => out.push_str("\\n"),
1820                '\r' => out.push_str("\\r"),
1821                '\t' => out.push_str("\\t"),
1822                c if (c as u32) < 0x20 => out.push_str(&format!("\\u{:04x}", c as u32)),
1823                c => out.push(c),
1824            }
1825        }
1826        out.push('"');
1827        out
1828    }
1829
1830    #[test]
1831    fn emit_fuzz_corpus() {
1832        // Dump the corpus + our fuzz.* results as JSONL for the Python oracle
1833        // cross-check (scripts/check_fuzz_parity.py). Full-precision floats via
1834        // Display (shortest round-trippable) so Python recovers exact bits.
1835        let corpus = fuzz_corpus();
1836        let mut buf = String::new();
1837        for (a, b) in &corpus {
1838            let scores = [
1839                ratio(a, b),
1840                partial_ratio(a, b),
1841                token_sort_ratio(a, b),
1842                token_set_ratio(a, b),
1843                token_ratio(a, b),
1844                partial_token_sort_ratio(a, b),
1845                partial_token_set_ratio(a, b),
1846                partial_token_ratio(a, b),
1847                w_ratio(a, b),
1848                q_ratio(a, b),
1849            ];
1850            // sanity: all in [0, 100]
1851            for s in scores {
1852                assert!(
1853                    (0.0..=100.0).contains(&s),
1854                    "out of range {s} for ({a:?},{b:?})"
1855                );
1856            }
1857            buf.push_str(&format!(
1858                "{{\"s1\":{},\"s2\":{},\"ratio\":{},\"partial_ratio\":{},\"token_sort_ratio\":{},\"token_set_ratio\":{},\"token_ratio\":{},\"partial_token_sort_ratio\":{},\"partial_token_set_ratio\":{},\"partial_token_ratio\":{},\"WRatio\":{},\"QRatio\":{}}}\n",
1859                json_escape(a), json_escape(b),
1860                scores[0], scores[1], scores[2], scores[3], scores[4],
1861                scores[5], scores[6], scores[7], scores[8], scores[9],
1862            ));
1863        }
1864        let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("target");
1865        std::fs::create_dir_all(&dir).unwrap();
1866        let path = dir.join("goldenfuzz_fuzz_corpus.jsonl");
1867        std::fs::write(&path, buf).unwrap();
1868        assert!(corpus.len() >= 5000, "corpus too small: {}", corpus.len());
1869        eprintln!("emitted {} pairs to {}", corpus.len(), path.display());
1870    }
1871
1872    fn check_pair(a: &str, b: &str) {
1873        // Jaro-Winkler
1874        let mine = jaro_winkler(a, b);
1875        let theirs = rf_jw::normalized_similarity(a.chars(), b.chars());
1876        assert_bits("jaro_winkler", a, b, mine, theirs);
1877
1878        // Levenshtein normalized similarity
1879        let mine = levenshtein_normalized_similarity(a, b);
1880        let theirs = rf_lev::normalized_similarity(a.chars(), b.chars());
1881        assert_bits("levenshtein", a, b, mine, theirs);
1882
1883        // fuzz::ratio (Indel normalized similarity)
1884        let mine = indel_ratio(a, b);
1885        let theirs = rf_fuzz::ratio(a.chars(), b.chars());
1886        assert_bits("indel_ratio", a, b, mine, theirs);
1887
1888        // Damerau-Levenshtein distance over the codepoints
1889        let ca: Vec<char> = a.chars().collect();
1890        let cb: Vec<char> = b.chars().collect();
1891        let mine = damerau_levenshtein_distance(&ca, &cb);
1892        let theirs = rf_dl::distance(a.chars(), b.chars());
1893        assert_eq!(mine, theirs, "damerau_levenshtein drift on ({a:?},{b:?})");
1894    }
1895}