1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
//! Optimized Guard-based Levenshtein NFA implementation.
//!
//! Similar to mrab-regex's fuzzy guards - uses bit-packed state encoding
//! for efficient fuzzy matching with early termination.
#![allow(
clippy::too_many_lines,
clippy::float_cmp,
clippy::allow_attributes,
let_underscore_drop
)]
use crate::engine::damlev::{DamLevMatch, EditLimits};
/// Guard-based NFA for fast fuzzy matching.
#[derive(Debug)]
pub struct GuardNfa {
pattern: Vec<char>,
pattern_len: usize,
edit_limits: EditLimits,
case_insensitive: bool,
first_char: char,
}
impl GuardNfa {
/// Create a new guard-based NFA.
#[must_use]
pub fn new(pattern: &str, edit_limits: EditLimits, case_insensitive: bool) -> Self {
let pattern: Vec<char> = if case_insensitive {
pattern.to_lowercase().chars().collect()
} else {
pattern.chars().collect()
};
let pattern_len = pattern.len();
let first_char = pattern.first().copied().unwrap_or('\0');
GuardNfa {
pattern,
pattern_len,
edit_limits,
case_insensitive,
first_char,
}
}
/// Find the first match in text with early termination.
#[inline]
#[must_use]
pub fn find_first(&self, text: &str, threshold: f32) -> Option<DamLevMatch> {
let max_edits = self.edit_limits.max_edits as usize;
if self.pattern_len == 0 {
return Some(DamLevMatch {
start: 0,
end: 0,
insertions: 0,
deletions: 0,
substitutions: 0,
swaps: 0,
similarity: 1.0,
});
}
let text_chars: Vec<char> = if self.case_insensitive {
text.chars()
.map(|c| c.to_lowercase().next().unwrap_or(c))
.collect()
} else {
text.chars().collect()
};
let text_len = text_chars.len();
let mut char_to_byte: Vec<usize> = vec![0; text_len + 1];
let mut byte_pos = 0;
for (i, c) in text.char_indices() {
char_to_byte[i] = byte_pos;
byte_pos += c.len_utf8();
}
char_to_byte[text_len] = byte_pos;
if text_len == 0 {
if self.pattern_len <= max_edits {
let edits = self.pattern_len;
let sim = 1.0 - (edits as f32 / (self.pattern_len + max_edits) as f32);
return Some(DamLevMatch {
start: 0,
end: 0,
insertions: 0,
deletions: edits as u8,
substitutions: 0,
swaps: 0,
similarity: sim,
});
}
return None;
}
let m = self.pattern_len;
// Vec-based states but with bit-packed seen for O(1) deduplication
let mut active: Vec<(usize, usize, usize, u8, u8, u8, usize)> = Vec::with_capacity(32);
let mut next_active: Vec<(usize, usize, usize, u8, u8, u8, usize)> = Vec::with_capacity(32);
// Bit-packed seen: 12 bits (6 for pat_pos + 6 for edits)
let encode_key =
|pat_pos: usize, edits: usize| -> u128 { ((pat_pos as u128) << 6) | (edits as u128) };
let mut pos = 0;
while pos < text_len {
let text_char = text_chars[pos];
let mut new_seen: u128 = 0;
// Start new match at this position
active.clear();
active.push((0, 0, pos, 0, 0, 0, pos));
next_active.clear();
// Process all active states
for &(pat_pos, edits, start_pos, ins, del, sub, last_consumed) in &active {
if pat_pos >= m || edits > max_edits {
continue;
}
let pat_char = self.pattern[pat_pos];
// Exact match
if text_char == pat_char {
let key = encode_key(pat_pos + 1, edits);
if new_seen & (1u128 << key) == 0 {
new_seen |= 1u128 << key;
next_active.push((pat_pos + 1, edits, start_pos, ins, del, sub, pos));
}
}
// Substitution
if edits < max_edits && text_char != pat_char {
let key = encode_key(pat_pos + 1, edits + 1);
if new_seen & (1u128 << key) == 0 {
new_seen |= 1u128 << key;
next_active.push((
pat_pos + 1,
edits + 1,
start_pos,
ins,
del,
sub + 1,
pos,
));
}
}
// Insertion
if edits < max_edits {
let key = encode_key(pat_pos, edits + 1);
if new_seen & (1u128 << key) == 0 {
new_seen |= 1u128 << key;
next_active.push((
pat_pos,
edits + 1,
start_pos,
ins + 1,
del,
sub,
last_consumed,
));
}
}
// Deletion
if pat_pos + 1 < m && edits < max_edits {
let key = encode_key(pat_pos + 1, edits + 1);
if new_seen & (1u128 << key) == 0 {
new_seen |= 1u128 << key;
next_active.push((
pat_pos + 1,
edits + 1,
start_pos,
ins,
del + 1,
sub,
last_consumed,
));
}
}
}
// Check for matches - return immediately on first match
for &(pat_pos, edits, start_pos, ins, del, sub, last_consumed) in &next_active {
if pat_pos >= m && edits <= max_edits {
let sim = 1.0 - (edits as f32 / (m + max_edits) as f32);
if sim >= threshold {
let match_end = last_consumed + 1;
let byte_start = char_to_byte[start_pos];
let byte_end = char_to_byte[match_end];
return Some(DamLevMatch {
start: byte_start,
end: byte_end,
insertions: ins,
deletions: del,
substitutions: sub,
swaps: 0,
similarity: sim,
});
}
}
}
std::mem::swap(&mut active, &mut next_active);
// Guard pruning - skip to first character if no active states
if active.is_empty() {
pos += 1;
while pos < text_len && text_chars[pos] != self.first_char {
pos += 1;
}
} else {
pos += 1;
}
}
// Handle trailing deletions
for &(pat_pos, edits, start_pos, ins, del, sub, _last_consumed) in &active {
if pat_pos >= m && edits <= max_edits {
let sim = 1.0 - (edits as f32 / (m + max_edits) as f32);
if sim >= threshold {
let byte_start = char_to_byte[start_pos];
let byte_end = char_to_byte[text_len];
return Some(DamLevMatch {
start: byte_start,
end: byte_end,
insertions: ins,
deletions: del,
substitutions: sub,
swaps: 0,
similarity: sim,
});
}
}
let remaining = m - pat_pos;
let new_edits = edits + remaining;
if new_edits <= max_edits {
let new_del = del + remaining as u8;
let sim = 1.0 - (new_edits as f32 / (m + max_edits) as f32);
if sim >= threshold {
let byte_start = char_to_byte[start_pos];
let byte_end = char_to_byte[text_len];
return Some(DamLevMatch {
start: byte_start,
end: byte_end,
insertions: ins,
deletions: new_del,
substitutions: sub,
swaps: 0,
similarity: sim,
});
}
}
}
None
}
}