Debian Codegraph @

src/levenshtein.rs

raw symbols SCIP
1 //! This module provides many Levenshtein distance routines.
2 //!
3 //! These distance functions share the same efficient underlying SIMD-accelerated implementation:
4 //! * `levenshtein_exp` for low number of edits, otherwise `levenshtein`
5 //! * `rdamerau_exp` for low number of edits, otherwise `rdamerau`
6 //! * `levenshtein_simd_k`
7 //! * `levenshtein_simd_k_with_opts`
8 //!
9 //! These search functions share the same efficient underlying SIMD-accelerated implementation:
10 //! * `levenshtein_search`
11 //! * `levenshtein_search_simd`
12 //! * `levenshtein_search_simd_with_opts`
13
14 use std::*;
15 use super::*;
16 use super::jewel::*;
17
18 /// A struct holding the edit costs for mismatches, gaps, and possibly transpositions.
19 ///
20 /// This should be used as a parameter for Levenshtein distance or search routines.
21 #[derive(Copy, Clone, Debug)]
22 pub struct EditCosts {
23 mismatch_cost: u8,
24 gap_cost: u8,
25 start_gap_cost: u8,
26 transpose_cost: Option<u8>
27 }
28
29 impl EditCosts {
30 /// Create a new `EditCosts` struct, checking for whether the specified costs are valid.
31 ///
32 /// # Arguments
33 /// * `mismatch_cost` - cost of a mismatch edit, which must be positive
34 /// * `gap_cost` - cost of a gap, which must be positive
35 /// * `start_gap_cost` - additional cost of starting a gap, for affine gap costs; this can
36 /// be zero for linear gap costs
37 /// * `transpose_cost` - cost of a transpose, which must be cheaper than doing the equivalent
38 /// operation with mismatches and gaps
39 pub fn new(mismatch_cost: u8, gap_cost: u8, start_gap_cost: u8, transpose_cost: Option<u8>) -> Self {
40 assert!(mismatch_cost > 0);
41 assert!(gap_cost > 0);
42
43 if let Some(cost) = transpose_cost {
44 assert!(cost > 0);
45 // transpose cost must be cheaper than doing the equivalent with other edits
46 assert!((cost >> 1) < mismatch_cost);
47 assert!((cost >> 1) < gap_cost);
48 }
49
50 Self{
51 mismatch_cost: mismatch_cost,
52 gap_cost: gap_cost,
53 start_gap_cost: start_gap_cost,
54 transpose_cost: transpose_cost
55 }
56 }
57
58 /// For Levenshtein searches, the cost of transpositions must be less than or equal to cost of
59 /// gaps.
60 ///
61 /// This is important for free gaps at the beginning of the needle to be unable to take priority
62 /// over transpositions, as it is possible to emulate a transposition with two gaps.
63 fn check_search(&self) {
64 if let Some(cost) = self.transpose_cost {
65 assert!(cost <= self.start_gap_cost + self.gap_cost);
66 }
67 }
68 }
69
70 /// Costs for Levenshtein distance, where mismatches and gaps both have a cost of 1, and
71 /// transpositions are not allowed.
72 pub const LEVENSHTEIN_COSTS: EditCosts = EditCosts{mismatch_cost: 1, gap_cost: 1, start_gap_cost: 0, transpose_cost: None};
73 /// Costs for restricted Damerau-Levenshtein distance, where mismatches, gaps, and transpositions
74 /// all have a cost of 1.
75 pub const RDAMERAU_COSTS: EditCosts = EditCosts{mismatch_cost: 1, gap_cost: 1, start_gap_cost: 0, transpose_cost: Some(1)};
76
77 /// Returns the Levenshtein distance between two strings using the naive scalar algorithm.
78 ///
79 /// # Arguments
80 /// * `a` - first string (slice)
81 /// * `b` - second string (slice)
82 ///
83 /// # Example
84 /// ```
85 /// # use triple_accel::*;
86 /// # use triple_accel::levenshtein::*;
87 /// let dist = levenshtein_naive(b"abc", b"ab");
88 ///
89 /// assert!(dist == 1);
90 /// ```
91 pub fn levenshtein_naive<T: PartialEq>(a: &[T], b: &[T]) -> u32 {
92 levenshtein_naive_with_opts(a, b, false, LEVENSHTEIN_COSTS).0
93 }
94
95 /// Returns the Levenshtein distance between two strings using the naive scalar algorithm.
96 ///
97 /// # Arguments
98 /// * `a` - first string (&str)
99 /// * `b` - second string (&str)
100 ///
101 /// # Example
102 /// ```
103 /// # use triple_accel::*;
104 /// # use triple_accel::levenshtein::*;
105 /// let dist = levenstein_naive_str("abc", "ab");
106 ///
107 /// assert!(dist == 1);
108 /// ```
109 pub fn levenstein_naive_str(a: &str, b: &str) -> u32 {
110 let a: Vec<char> = a.chars().collect();
111 let b: Vec<char> = b.chars().collect();
112 levenshtein_naive(&a, &b)
113 }
114
115 /// Returns the Levenshtein distance between two strings and optionally, the edit traceback,
116 /// using the naive scalar algorithm, with extra options.
117 ///
118 /// # Arguments
119 /// * `a` - first string (slice)
120 /// * `b` - second string (slice)
121 /// * `trace_on` - whether to return the traceback, the sequence of edits between `a` and `b`
122 /// * `costs` - `EditCosts` struct for the cost of each edit operation
123 ///
124 /// # Example
125 /// ```
126 /// # use triple_accel::*;
127 /// # use triple_accel::levenshtein::*;
128 /// let dist = levenshtein_naive_with_opts(b"abc", b"ab", true, LEVENSHTEIN_COSTS);
129 ///
130 /// assert!(dist == (1, Some(vec![Edit{edit: EditType::Match, count: 2},
131 /// Edit{edit: EditType::BGap, count: 1}])));
132 /// ```
133 #[inline]
134 pub fn levenshtein_naive_with_opts<T>(a: &[T], b: &[T], trace_on: bool, costs: EditCosts) -> (u32, Option<Vec<Edit>>)
135 where T: PartialEq
136 {
137 let swap = a.len() > b.len(); // swap so that a len <= b len
138 let a_new = if swap {b} else {a};
139 let a_new_len = a_new.len();
140 let b_new = if swap {a} else {b};
141 let b_new_len = b_new.len();
142 let mismatch_cost = costs.mismatch_cost as u32;
143 let gap_cost = costs.gap_cost as u32;
144 let start_gap_cost = costs.start_gap_cost as u32;
145 let transpose_cost = match costs.transpose_cost {
146 Some(cost) => cost as u32,
147 None => 0
148 };
149 let allow_transpose = costs.transpose_cost.is_some();
150
151 let len = a_new_len + 1;
152 let mut dp0 = vec![0u32; len];
153 let mut dp1 = vec![0u32; len]; // in each iteration, dp0 and dp1 are already calculated
154 let mut dp2 = vec![0u32; len]; // dp2 the currently calculated column
155 let mut a_gap_dp = vec![u32::MAX; len];
156 let mut b_gap_dp = vec![u32::MAX; len];
157 let mut traceback = if trace_on {vec![0u8; (b_new_len + 1) * len]} else {vec![]};
158
159 for i in 0..len {
160 dp1[i] = (i as u32) * gap_cost + if i == 0 {0} else {start_gap_cost};
161
162 if trace_on {
163 traceback[0 * len + i] = 2u8;
164 }
165 }
166
167 for i in 1..(b_new_len + 1) {
168 a_gap_dp[0] = (i as u32) * gap_cost + start_gap_cost;
169 dp2[0] = (i as u32) * gap_cost + start_gap_cost;
170
171 if trace_on {
172 traceback[i * len + 0] = 1u8;
173 }
174
175 for j in 1..len {
176 let sub = dp1[j - 1] + ((a_new[j - 1] != b_new[i - 1]) as u32) * mismatch_cost;
177 a_gap_dp[j] = cmp::min(dp1[j] + start_gap_cost + gap_cost, a_gap_dp[j].saturating_add(gap_cost));
178 b_gap_dp[j] = cmp::min(dp2[j - 1] + start_gap_cost + gap_cost, b_gap_dp[j - 1].saturating_add(gap_cost));
179 let traceback_idx = i * len + j;
180
181 dp2[j] = a_gap_dp[j];
182
183 if trace_on {
184 traceback[traceback_idx] = 1u8;
185 }
186
187 if b_gap_dp[j] < dp2[j] {
188 dp2[j] = b_gap_dp[j];
189
190 if trace_on {
191 traceback[traceback_idx] = 2u8;
192 }
193 }
194
195 if sub <= dp2[j] {
196 dp2[j] = sub;
197
198 if trace_on {
199 traceback[traceback_idx] = 0u8;
200 }
201 }
202
203 if allow_transpose && i > 1 && j > 1
204 && a_new[j - 1] == b_new[i - 2] && a_new[j - 2] == b_new[i - 1] {
205 let transpose = dp0[j - 2] + transpose_cost;
206
207 if transpose <= dp2[j] {
208 dp2[j] = transpose;
209
210 if trace_on {
211 traceback[traceback_idx] = 3u8;
212 }
213 }
214 }
215 }
216
217 mem::swap(&mut dp0, &mut dp1);
218 mem::swap(&mut dp1, &mut dp2);
219 }
220
221 if trace_on {
222 // estimate an upper bound for the number of Edits
223 let mut upper_bound_edits = dp1[a_new_len] / cmp::min(mismatch_cost, gap_cost);
224
225 if allow_transpose {
226 upper_bound_edits = cmp::max(upper_bound_edits, (dp1[a_new_len] >> 1) / transpose_cost + 1);
227 }
228
229 let mut res: Vec<Edit> = Vec::with_capacity(((upper_bound_edits << 1) + 1) as usize);
230 let mut i = b_new_len;
231 let mut j = a_new_len;
232
233 while i > 0 || j > 0 {
234 let edit = traceback[i * len + j];
235
236 let e = match edit {
237 0 => {
238 i -= 1;
239 j -= 1;
240 if a_new[j] == b_new[i] {EditType::Match} else {EditType::Mismatch}
241 },
242 1 => {
243 i -= 1;
244 if swap {EditType::BGap} else {EditType::AGap}
245 },
246 2 => {
247 j -= 1;
248 if swap {EditType::AGap} else {EditType::BGap}
249 },
250 3 => {
251 i -= 2;
252 j -= 2;
253 EditType::Transpose
254 },
255 _ => unreachable!()
256 };
257
258 if res.len() > 0 && res.last().unwrap().edit == e {
259 res.last_mut().unwrap().count += 1;
260 }else{
261 res.push(Edit{edit: e, count: 1});
262 }
263 }
264
265 res.reverse();
266 (dp1[a_new_len], Some(res))
267 }else{
268 (dp1[a_new_len], None)
269 }
270 }
271
272 /// Returns the Levenshtein distance, bounded by a cost threshold `k`, between two strings, using the
273 /// naive scalar algorithm.
274 ///
275 /// This will return `None` if the Levenshtein distance between `a` and `b` is greater than the
276 /// threshold `k`.
277 /// This should be much faster than `levenshtein_naive` if `k` is small compared to the lengths of
278 /// `a` and `b`.
279 ///
280 /// # Arguments
281 /// * `a` - first string (slice)
282 /// * `b` - second string (slice)
283 /// * `k` - maximum number of edits allowed between `a` and `b`
284 ///
285 /// # Example
286 /// ```
287 /// # use triple_accel::*;
288 /// # use triple_accel::levenshtein::*;
289 /// let dist = levenshtein_naive_k(b"abc", b"ab", 1);
290 ///
291 /// assert!(dist.unwrap() == 1);
292 /// ```
293 pub fn levenshtein_naive_k(a: &[u8], b: &[u8], k: u32) -> Option<u32> {
294 let res = levenshtein_naive_k_with_opts(a, b, k, false, LEVENSHTEIN_COSTS);
295
296 match res {
297 Some((edits, _)) => Some(edits),
298 None => None
299 }
300 }
301
302 /// Returns the Levenshtein distance, bounded by a cost threshold `k`, between two strings and optionally,
303 /// the edit traceback, using the naive scalar algorithm, with extra options.
304 ///
305 /// This will return `None` if the Levenshtein distance between `a` and `b` is greater than the
306 /// threshold `k`.
307 /// This should be much faster than `levenshtein_naive_with_opts` if `k` is small compared to the lengths of
308 /// `a` and `b`.
309 ///
310 /// # Arguments
311 /// * `a` - first string (slice)
312 /// * `b` - second string (slice)
313 /// * `k` - maximum number of cost allowed between `a` and `b`
314 /// * `trace_on` - whether to return the traceback, the sequence of edits between `a` and `b`
315 /// * `costs` - `EditCosts` struct for the cost of each edit operation
316 ///
317 /// # Example
318 /// ```
319 /// # use triple_accel::*;
320 /// # use triple_accel::levenshtein::*;
321 /// let dist = levenshtein_naive_k_with_opts(b"abc", b"ab", 1, true, LEVENSHTEIN_COSTS);
322 ///
323 /// assert!(dist.unwrap() == (1, Some(vec![Edit{edit: EditType::Match, count: 2},
324 /// Edit{edit: EditType::BGap, count: 1}])));
325 /// ```
326 #[inline]
327 pub fn levenshtein_naive_k_with_opts<T>(a: &[T], b: &[T], k: u32, trace_on: bool, costs: EditCosts) -> Option<(u32, Option<Vec<Edit>>)>
328 where T: PartialEq
329 {
330 let swap = a.len() > b.len(); // swap so that a len <= b len
331 let a_new = if swap {b} else {a};
332 let a_new_len = a_new.len();
333 let b_new = if swap {a} else {b};
334 let b_new_len = b_new.len();
335 let mismatch_cost = costs.mismatch_cost as u32;
336 let gap_cost = costs.gap_cost as u32;
337 let start_gap_cost = costs.start_gap_cost as u32;
338 let transpose_cost = match costs.transpose_cost {
339 Some(cost) => cost as u32,
340 None => 0
341 };
342 let allow_transpose = costs.transpose_cost.is_some();
343 // upper bound on the number of edits, in case k is too large
344 let max_k = cmp::min((a_new_len as u32) * mismatch_cost,
345 ((a_new_len as u32) << 1) * gap_cost
346 + if a_new_len == 0 {0} else {start_gap_cost
347 + if b_new_len == a_new_len {start_gap_cost} else {0}});
348 let max_k = cmp::min(k,
349 max_k + ((b_new_len - a_new_len) as u32) * gap_cost
350 + if b_new_len == a_new_len {0} else {start_gap_cost});
351 // farthest we can stray from the main diagonal
352 // have to start at least one gap
353 let unit_k = (max_k.saturating_sub(start_gap_cost) / gap_cost) as usize;
354
355 if b_new_len - a_new_len > unit_k {
356 return None;
357 }
358
359 let len = a_new_len + 1;
360 let mut lo = 0usize;
361 let mut hi = cmp::min(unit_k + 1, b_new_len + 1);
362 let mut prev_lo0;
363 let mut prev_lo1 = 0; // unused value
364 let mut prev_hi;
365 let k_len = cmp::min((unit_k << 1) + 1, b_new_len + 1);
366 let mut dp0 = vec![0u32; k_len];
367 let mut dp1 = vec![0u32; k_len]; // in each iteration, dp0 and dp1 are already calculated
368 let mut dp2 = vec![0u32; k_len]; // dp2 the currently calculated row
369 let mut a_gap_dp = vec![u32::MAX; k_len];
370 let mut b_gap_dp = vec![u32::MAX; k_len];
371 let mut traceback = if trace_on {vec![0u8; len * k_len]} else {vec![]};
372
373 for i in 0..(hi - lo) {
374 dp1[i] = (i as u32) * gap_cost + if i == 0 {0} else {start_gap_cost};
375
376 if trace_on {
377 traceback[0 * k_len + i] = 1u8;
378 }
379 }
380
381 for i in 1..len {
382 // keep track of prev_lo for the offset of previous rows
383 prev_lo0 = prev_lo1;
384 prev_lo1 = lo;
385 prev_hi = hi;
386 hi = cmp::min(hi + 1, b_new_len + 1);
387
388 if i > unit_k {
389 lo += 1;
390 }
391
392 for j in 0..(hi - lo) {
393 let idx = lo + j;
394 let sub = if idx == 0 {
395 u32::MAX
396 }else{
397 dp1[idx - 1 - prev_lo1] + ((a_new[i - 1] != b_new[idx - 1]) as u32) * mismatch_cost
398 };
399 a_gap_dp[j] = if j == 0 {
400 u32::MAX
401 }else{
402 cmp::min(dp2[j - 1] + start_gap_cost + gap_cost, a_gap_dp[j - 1].saturating_add(gap_cost))
403 };
404 b_gap_dp[j] = if idx >= prev_hi {
405 u32::MAX
406 }else{
407 cmp::min(dp1[idx - prev_lo1] + start_gap_cost + gap_cost, b_gap_dp[idx - prev_lo1].saturating_add(gap_cost))
408 };
409
410 dp2[j] = sub;
411
412 let traceback_idx = i * k_len + j;
413
414 if trace_on {
415 traceback[traceback_idx] = 0u8;
416 }
417
418 if a_gap_dp[j] < dp2[j] {
419 dp2[j] = a_gap_dp[j];
420
421 if trace_on {
422 traceback[traceback_idx] = 1u8;
423 }
424 }
425
426 if b_gap_dp[j] < dp2[j] {
427 dp2[j] = b_gap_dp[j];
428
429 if trace_on {
430 traceback[traceback_idx] = 2u8;
431 }
432 }
433
434 if allow_transpose && i > 1 && idx > 1
435 && a_new[i - 1] == b_new[idx - 2] && a_new[i - 2] == b_new[idx - 1] {
436 let transpose = dp0[idx - prev_lo0 - 2] + transpose_cost;
437
438 if transpose <= dp2[j] {
439 dp2[j] = transpose;
440
441 if trace_on {
442 traceback[traceback_idx] = 3u8;
443 }
444 }
445 }
446 }
447
448 mem::swap(&mut dp0, &mut dp1);
449 mem::swap(&mut dp1, &mut dp2);
450 }
451
452 if dp1[hi - lo - 1] > max_k {
453 return None;
454 }
455
456 if !trace_on {
457 return Some((dp1[hi - lo - 1], None));
458 }
459
460 // estimate an upper bound for the number of Edits
461 let mut upper_bound_edits = dp1[hi - lo - 1] / cmp::min(mismatch_cost, gap_cost);
462
463 if allow_transpose {
464 upper_bound_edits = cmp::max(upper_bound_edits, (dp1[hi - lo - 1] >> 1) / transpose_cost + 1);
465 }
466
467 let mut res: Vec<Edit> = Vec::with_capacity(((upper_bound_edits << 1) + 1) as usize);
468 let mut i = a_new_len;
469 let mut j = b_new_len;
470
471 while i > 0 || j > 0 {
472 let edit = traceback[i * k_len + (j - (if i > unit_k {i - unit_k} else {0}))];
473
474 let e = match edit {
475 0 => {
476 i -= 1;
477 j -= 1;
478 if a_new[i] == b_new[j] {EditType::Match} else {EditType::Mismatch}
479 },
480 1 => {
481 j -= 1;
482 if swap {EditType::BGap} else {EditType::AGap}
483 },
484 2 => {
485 i -= 1;
486 if swap {EditType::AGap} else {EditType::BGap}
487 },
488 3 => {
489 i -= 2;
490 j -= 2;
491 EditType::Transpose
492 },
493 _ => unreachable!()
494 };
495
496 if res.len() > 0 && res.last().unwrap().edit == e {
497 res.last_mut().unwrap().count += 1;
498 }else{
499 res.push(Edit{edit: e, count: 1});
500 }
501 }
502
503 res.reverse();
504 Some((dp1[hi - lo - 1], Some(res)))
505 }
506
507 fn translate_str(chars: &mut Vec<char>, s: &str) -> Option<Vec<u8>> {
508 s.chars().map(|c| match chars.iter().position(|&d| c == d) {
509 Some(i) => Some(i as u8),
510 None => {
511 let idx = chars.len();
512 if idx < 256 {
513 chars.push(c);
514 Some(idx as u8)
515 } else {
516 None
517 }
518 }
519 }).collect()
520 }
521
522 /// Returns the Levenshtein distance, bounded by a cost threshold `k`, between two utf8 encoded strings, using
523 /// SIMD acceleration.
524 /// # Arguments
525 /// * `a` - first string (&str)
526 /// * `b` - second string (&str)
527 /// * `k` - maximum number of edits allowed between `a` and `b`
528 ///
529 /// # Example
530 /// ```
531 /// # use triple_accel::*;
532 /// # use triple_accel::levenshtein::*;
533 /// let dist = levenshtein_simd_k_str("abc", "ab", 1);
534 ///
535 /// assert!(dist.unwrap() == 1);
536 /// ```
537 pub fn levenshtein_simd_k_str(a: &str, b: &str, k: u32) -> Option<u32> {
538 if a.is_ascii() && b.is_ascii() {
539 levenshtein_simd_k(a.as_bytes(), b.as_bytes(), k)
540 } else {
541 let mut chars = Vec::with_capacity(256);
542
543 let a = translate_str(&mut chars, a)?;
544 let b = translate_str(&mut chars, b)?;
545 levenshtein_simd_k(&a, &b, k)
546 }
547 }
548
549 /// Returns the Levenshtein distance, bounded by a cost threshold `k`, between two strings, using
550 /// SIMD acceleration.
551 ///
552 /// This will return `None` if the Levenshtein distance between `a` and `b` is greater than the
553 /// threshold `k`.
554 /// This should be much faster than `levenshtein_naive` and `levenshtein_naive_k`.
555 /// Internally, this will automatically use AVX or SSE vectors with 8-bit, 16-bit, or 32-bit elements
556 /// to represent anti-diagonals in the dynamic programming matrix for calculating Levenshtein distance.
557 /// If AVX2 or SSE4.1 is not supported, then this will automatically fall back to
558 /// `levenshtein_naive_k_with_opts`.
559 ///
560 /// # Arguments
561 /// * `a` - first string (slice)
562 /// * `b` - second string (slice)
563 /// * `k` - maximum number of edits allowed between `a` and `b`
564 ///
565 /// # Example
566 /// ```
567 /// # use triple_accel::*;
568 /// # use triple_accel::levenshtein::*;
569 /// let dist = levenshtein_simd_k(b"abc", b"ab", 1);
570 ///
571 /// assert!(dist.unwrap() == 1);
572 /// ```
573 pub fn levenshtein_simd_k(a: &[u8], b: &[u8], k: u32) -> Option<u32> {
574 let res = levenshtein_simd_k_with_opts(a, b, k, false, LEVENSHTEIN_COSTS);
575
576 match res {
577 Some((edits, _)) => Some(edits),
578 None => None
579 }
580 }
581
582 /// Returns the Levenshtein distance, bounded by a cost threshold `k`, between two strings and optionally,
583 /// the edit traceback, using SIMD acceleration, with extra options.
584 ///
585 /// This will return `None` if the Levenshtein distance between `a` and `b` is greater than the
586 /// threshold `k`.
587 /// This should be much faster than `levenshtein_naive_with_opts` and
588 /// `levenshtein_naive_k_with_opts`.
589 /// Internally, this will automatically use AVX or SSE vectors with 8-bit, 16-bit, or 32-bit elements
590 /// to represent anti-diagonals in the dynamic programming matrix for calculating Levenshtein distance.
591 /// If AVX2 or SSE4.1 is not supported, then this will automatically fall back to
592 /// `levenshtein_naive_k_with_opts`.
593 ///
594 /// # Arguments
595 /// * `a` - first string (slice)
596 /// * `b` - second string (slice)
597 /// * `k` - maximum number of cost allowed between `a` and `b`
598 /// * `trace_on` - whether to return the traceback, the sequence of edits between `a` and `b`
599 /// * `costs` - `EditCosts` struct for the cost of each edit operation
600 ///
601 /// # Example
602 /// ```
603 /// # use triple_accel::*;
604 /// # use triple_accel::levenshtein::*;
605 /// let dist = levenshtein_simd_k_with_opts(b"abc", b"ab", 1, true, LEVENSHTEIN_COSTS);
606 ///
607 /// assert!(dist.unwrap() == (1, Some(vec![Edit{edit: EditType::Match, count: 2},
608 /// Edit{edit: EditType::BGap, count: 1}])));
609 /// ```
610 pub fn levenshtein_simd_k_with_opts(a: &[u8], b: &[u8], k: u32, trace_on: bool, costs: EditCosts) -> Option<(u32, Option<Vec<Edit>>)> {
611 if a.len() == 0 && b.len() == 0 {
612 return if trace_on {Some((0u32, Some(vec![])))} else {Some((0u32, None))};
613 }
614
615 #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
616 {
617 let min_len = cmp::min(a.len(), b.len()) as u32;
618 let max_len = cmp::max(a.len(), b.len()) as u32;
619 // upper bound on the number of edits, in case k is too large
620 let max_k = cmp::min(min_len * (costs.mismatch_cost as u32),
621 (min_len << 1) * (costs.gap_cost as u32)
622 + if min_len == 0 {0} else {costs.start_gap_cost as u32
623 + if max_len == min_len {costs.start_gap_cost as u32} else {0}});
624 let max_k = cmp::min(k,
625 max_k + (max_len - min_len) * (costs.gap_cost as u32)
626 + if max_len == min_len {0} else {costs.start_gap_cost as u32});
627 // farthest we can stray from the main diagonal
628 // have to start at least one gap
629 let unit_k = cmp::min(max_k.saturating_sub(costs.start_gap_cost as u32) / (costs.gap_cost as u32), max_len);
630
631 // note: do not use the MAX value, because it indicates overflow/inaccuracy
632 if cfg!(feature = "jewel-avx") && is_x86_feature_detected!("avx2") {
633 if cfg!(feature = "jewel-8bit") && unit_k <= (Avx1x32x8::static_upper_bound() as u32 - 2) && max_k <= ((u8::MAX - 1) as u32) {
634 return unsafe {levenshtein_simd_core_avx_1x32x8(a, b, max_k, trace_on, costs)};
635 }else if cfg!(feature = "jewel-8bit") && unit_k <= (Avx2x32x8::static_upper_bound() as u32 - 2) && max_k <= ((u8::MAX - 1) as u32) {
636 return unsafe {levenshtein_simd_core_avx_2x32x8(a, b, max_k, trace_on, costs)};
637 }else if cfg!(feature = "jewel-8bit") && unit_k <= (Avx4x32x8::static_upper_bound() as u32 - 2) && max_k <= ((u8::MAX - 1) as u32) {
638 return unsafe {levenshtein_simd_core_avx_4x32x8(a, b, max_k, trace_on, costs)};
639 }else if cfg!(feature = "jewel-8bit") && unit_k <= (Avx8x32x8::static_upper_bound() as u32 - 2) && max_k <= ((u8::MAX - 1) as u32) {
640 return unsafe {levenshtein_simd_core_avx_8x32x8(a, b, max_k, trace_on, costs)};
641 }else if cfg!(feature = "jewel-16bit") && max_k <= ((u16::MAX - 1) as u32) {
642 return unsafe {levenshtein_simd_core_avx_nx16x16(a, b, max_k, trace_on, costs)};
643 }else if cfg!(feature = "jewel-32bit") {
644 return unsafe {levenshtein_simd_core_avx_nx8x32(a, b, max_k, trace_on, costs)};
645 }
646 }else if cfg!(feature = "jewel-sse") && is_x86_feature_detected!("sse4.1") {
647 if cfg!(feature = "jewel-8bit") && unit_k <= (Sse1x16x8::static_upper_bound() as u32 - 2) && max_k <= ((u8::MAX - 1) as u32) {
648 return unsafe {levenshtein_simd_core_sse_1x16x8(a, b, max_k, trace_on, costs)};
649 }else if cfg!(feature = "jewel-8bit") && unit_k <= (Sse2x16x8::static_upper_bound() as u32 - 2) && max_k <= ((u8::MAX - 1) as u32) {
650 return unsafe {levenshtein_simd_core_sse_2x16x8(a, b, max_k, trace_on, costs)};
651 }else if cfg!(feature = "jewel-8bit") && unit_k <= (Sse4x16x8::static_upper_bound() as u32 - 2) && max_k <= ((u8::MAX - 1) as u32) {
652 return unsafe {levenshtein_simd_core_sse_4x16x8(a, b, max_k, trace_on, costs)};
653 }else if cfg!(feature = "jewel-8bit") && unit_k <= (Sse8x16x8::static_upper_bound() as u32 - 2) && max_k <= ((u8::MAX - 1) as u32) {
654 return unsafe {levenshtein_simd_core_sse_8x16x8(a, b, max_k, trace_on, costs)};
655 }else if cfg!(feature = "jewel-8bit") && unit_k <= (Sse16x16x8::static_upper_bound() as u32 - 2) && max_k <= ((u8::MAX - 1) as u32) {
656 return unsafe {levenshtein_simd_core_sse_16x16x8(a, b, max_k, trace_on, costs)};
657 }else if cfg!(feature = "jewel-16bit") && max_k <= ((u16::MAX - 1) as u32) {
658 return unsafe {levenshtein_simd_core_sse_nx8x16(a, b, max_k, trace_on, costs)};
659 }else if cfg!(feature = "jewel-32bit") {
660 return unsafe {levenshtein_simd_core_sse_nx4x32(a, b, max_k, trace_on, costs)};
661 }
662 }
663 }
664
665 levenshtein_naive_k_with_opts(a, b, k, trace_on, costs)
666 }
667
668 macro_rules! create_levenshtein_simd_core {
669 ($name:ident, $traceback_name:ident, $jewel:ty, $target:literal) => {
670 #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
671 #[target_feature(enable = $target)]
672 unsafe fn $name(a_old: &[u8], b_old: &[u8], k: u32, trace_on: bool, costs: EditCosts) -> Option<(u32, Option<Vec<Edit>>)> {
673 #[cfg(feature = "debug")]
674 {
675 println!("Debug: Levenshtein Jewel vector type {} for target {}.", stringify!($jewel), stringify!($target));
676 }
677
678 // swap a and b so that a is shorter than b, if applicable
679 // makes operations later on slightly easier, since length of a <= length of b
680 let swap = a_old.len() > b_old.len();
681 let a = if swap {b_old} else {a_old};
682 let a_len = a.len();
683 let b = if swap {a_old} else {b_old};
684 let b_len = b.len();
685 let unit_k = cmp::min((k.saturating_sub(costs.start_gap_cost as u32) / (costs.gap_cost as u32)) as usize, b_len);
686
687 if b_len - a_len > unit_k {
688 return None;
689 }
690
691 // initialized with max values
692 // must use saturated additions afterwards to not overflow
693 let mut dp1 = <$jewel>::repeating_max((unit_k + 2) as usize);
694 let max_len = dp1.upper_bound();
695 let mut dp2 = <$jewel>::repeating_max(max_len);
696 let mut dp0 = <$jewel>::repeating_max(max_len);
697 let mut dp_temp = <$jewel>::repeating_max(max_len);
698 // dp0 -> dp_temp -> dp1 -> dp2 -> current diagonal
699
700 // dp for whether to extend gap or start new gap
701 let mut a_gap_dp = <$jewel>::repeating_max(max_len);
702 let mut b_gap_dp = <$jewel>::repeating_max(max_len);
703
704 // lengths of the (anti) diagonals
705 // assumes max_len is even
706 let k1 = max_len - 1;
707 let k1_div2 = k1 >> 1;
708 let k2 = max_len - 2;
709 let k2_div2 = k2 >> 1;
710
711 // set dp[0][0] = 0
712 dp1.slow_insert(k1_div2, 0);
713 // set dp[0][1] = start_gap_cost + gap_cost and dp[1][0] = start_gap_cost + gap_cost
714 dp2.slow_insert(k2_div2 - 1, costs.start_gap_cost as u32 + costs.gap_cost as u32);
715 dp2.slow_insert(k2_div2, costs.start_gap_cost as u32 + costs.gap_cost as u32);
716 b_gap_dp.slow_insert(k2_div2 - 1, costs.start_gap_cost as u32 + costs.gap_cost as u32);
717 a_gap_dp.slow_insert(k2_div2, costs.start_gap_cost as u32 + costs.gap_cost as u32);
718
719 // a_k1_window and a_k2_window represent reversed portions of the string a
720 // copy in half of k1/k2 number of characters
721 // these characters are placed in the second half of b windows
722 // since a windows are reversed, the characters are placed in reverse in the first half of b windows
723 let mut a_k1_window = <$jewel>::repeating(0, max_len);
724 a_k1_window.slow_loadu(k1_div2 - 1, a.as_ptr(), cmp::min(k1_div2, a_len), true);
725
726 let mut b_k1_window = <$jewel>::repeating(0, max_len);
727 b_k1_window.slow_loadu(k1_div2 + 1, b.as_ptr(), cmp::min(k1_div2, b_len), false);
728
729 let mut a_k2_window = <$jewel>::repeating(0, max_len);
730 a_k2_window.slow_loadu(k2_div2 - 1, a.as_ptr(), cmp::min(k2_div2, a_len), true);
731
732 let mut b_k2_window = <$jewel>::repeating(0, max_len);
733 b_k2_window.slow_loadu(k2_div2, b.as_ptr(), cmp::min(k2_div2, b_len), false);
734
735 // used to keep track of the next characters to place in the windows
736 let mut k1_idx = k1_div2 - 1;
737 let mut k2_idx = k2_div2 - 1;
738
739 let len_diff = b_len - a_len;
740 let len = a_len + b_len + 1;
741 let len_div2 = (len >> 1) + (len & 1);
742 let ends_with_k2 = len & 1 == 0;
743 // every diff between the length of a and b results in a shift from the main diagonal
744 let final_idx = {
745 if ends_with_k2 { // divisible by 2, ends with k2
746 k2_div2 + ((len_diff - 1) >> 1)
747 }else{ // not divisible by 2, ends with k1
748 k1_div2 + (len_diff >> 1)
749 }
750 };
751
752 // 0 = match/mismatch, 1 = a gap, 2 = b gap, 3 = transpose
753 let mut traceback_arr = if trace_on {Vec::with_capacity(len + (len & 1))} else {vec![]};
754
755 if trace_on {
756 traceback_arr.push(<$jewel>::repeating(0, max_len));
757 traceback_arr.push(<$jewel>::repeating(0, max_len));
758 traceback_arr.get_unchecked_mut(1).slow_insert(k2_div2 - 1, 2);
759 traceback_arr.get_unchecked_mut(1).slow_insert(k2_div2, 1);
760 }
761
762 // reusable constant
763 let threes = <$jewel>::repeating(3, max_len);
764
765 // used in calculations
766 let mut sub = <$jewel>::repeating(0, max_len);
767 let mut match_mask0 = <$jewel>::repeating(0, max_len);
768 let mut match_mask1 = <$jewel>::repeating(0, max_len);
769 let mut a_gap = <$jewel>::repeating(0, max_len);
770 let mut b_gap = <$jewel>::repeating(0, max_len);
771 let mut transpose = <$jewel>::repeating(0, max_len);
772
773 let mismatch_cost = <$jewel>::repeating(costs.mismatch_cost as u32, max_len);
774 let gap_cost = <$jewel>::repeating(costs.gap_cost as u32, max_len);
775 let start_gap_cost = <$jewel>::repeating(costs.start_gap_cost as u32 + costs.gap_cost as u32, max_len);
776 let transpose_cost = match costs.transpose_cost {
777 Some(cost) => <$jewel>::repeating(cost as u32, max_len),
778 None => <$jewel>::repeating(0, max_len) // value does not matter
779 };
780 let allow_transpose = costs.transpose_cost.is_some();
781
782 // example: allow k = 2 edits for two strings of length 3
783 // -b--
784 // | xx */*
785 // a x /*/*
786 // | */*/ x
787 // | */* xx
788 //
789 // each (anti) diagonal is represented with '*' or '/'
790 // '/', use k2 = 2
791 // '*', use k1 = 3
792 // 'x' represents cells not in the "traditional" dp array
793 // these out of bounds dp cells are shown because they represent
794 // a horizontal sliding window of length 5 (2 * k + 1)
795 //
796 // dp2 is one diagonal before current
797 // dp1 is two diagonals before current
798 // dp0 is four diagonals before current
799 // dp0 is useful for transpositions
800 // we are trying to calculate the "current" diagonal
801 // note that a k1 '*' dp diagonal has its center cell on the main diagonal
802 // in general, the diagonals are centered on the main diagonal
803 // each diagonal is represented using a Jewel vector
804 // each vector goes from bottom-left to top-right
805 //
806 // the a windows and b windows are queues of a fixed length
807 // a is reversed, so that elementwise comparison can be done between a and b
808 // this operation obtains the comparison of characters along the (anti) diagonal
809 // if transpositions are allowed, then previous match_masks must be saved to calculate
810 // a[i - 1] == b[j] and a[i] == b[j - 1]
811 // for speed, transpositions are done by directly blending using the mask, without calculating
812 // the minimum cost compared to the other edit operations
813 //
814 // example of moving the windows:
815 // a windows: [5 4 3 2 1] -> [6 5 4 3 2] (right shift + insert)
816 // b windows: [1 2 3 4 5] -> [2 3 4 5 6] (left shift + insert)
817 //
818 // initially:
819 // a windows: [2 1 0 0 0]
820 // b windows: [0 0 0 1 2]
821 //
822 // note that there will be left over cells not filled in the Jewel vector
823 // this is because k1 and k2 are not long enough
824 // all of these empty cells should be at the end of the SIMD vectors
825 //
826 // each iteration of the loop below results in processing both a k1 diagonal and a k2 diagonal
827 // this could be done with an alternating state flag but it is unrolled for less branching
828 //
829 // note: in traditional dp array
830 // dp[i][j] -> dp[i + 1][j] is a gap in string b
831 // dp[i][j] -> dp[i][j + 1] is a gap in string a
832
833 for _ in 1..len_div2 {
834 // move indexes in strings forward
835 k1_idx += 1;
836 k2_idx += 1;
837
838 // move windows for the strings a and b
839 a_k1_window.shift_right_1_mut();
840
841 if k1_idx < a_len {
842 a_k1_window.insert_first(*a.get_unchecked(k1_idx) as u32);
843 }
844
845 b_k1_window.shift_left_1_mut();
846
847 if k1_idx < b_len {
848 b_k1_window.insert_last_1(*b.get_unchecked(k1_idx) as u32); // k1 - 1
849 }
850
851 a_k2_window.shift_right_1_mut();
852
853 if k2_idx < a_len {
854 a_k2_window.insert_first(*a.get_unchecked(k2_idx) as u32);
855 }
856
857 b_k2_window.shift_left_1_mut();
858
859 if k2_idx < b_len {
860 b_k2_window.insert_last_2(*b.get_unchecked(k2_idx) as u32); // k2 - 1
861 }
862
863 // (anti) diagonal that matches in the a and b windows
864 <$jewel>::cmpeq(&a_k1_window, &b_k1_window, &mut match_mask1);
865 <$jewel>::andnot(&match_mask1, &mismatch_cost, &mut sub);
866 sub.adds_mut(&dp1);
867 // cost of gaps in a
868 // start new gap
869 <$jewel>::adds(&dp2, &start_gap_cost, &mut a_gap);
870 // continue gap
871 a_gap_dp.adds_mut(&gap_cost);
872 a_gap_dp.min_mut(&a_gap);
873 a_gap_dp.shift_right_1_mut();
874 a_gap_dp.insert_first_max();
875 // cost of gaps in b
876 // start new gap
877 <$jewel>::adds(&dp2, &start_gap_cost, &mut b_gap);
878 // continue gap
879 b_gap_dp.adds_mut(&gap_cost);
880 b_gap_dp.min_mut(&b_gap);
881
882 if allow_transpose {
883 <$jewel>::shift_right_1(&match_mask0, &mut transpose); // reuse transpose, zeros shifted in
884 transpose.and_mut(&match_mask0);
885 // make sure that current matching locations are excluded
886 <$jewel>::andnot(&match_mask1, &transpose, &mut match_mask0); // reuse match_mask0 to represent transpose mask
887 <$jewel>::adds(&dp0, &transpose_cost, &mut transpose);
888 }
889
890 // min of the cost of all three edit operations
891 if trace_on {
892 let mut args = <$jewel>::triple_argmin(&sub, &a_gap_dp, &b_gap_dp, &mut dp0);
893
894 if allow_transpose {
895 // blend using transpose mask
896 dp0.blendv_mut(&transpose, &match_mask0);
897 args.blendv_mut(&threes, &match_mask0);
898 mem::swap(&mut match_mask0, &mut match_mask1);
899 }
900
901 traceback_arr.push(args);
902 }else{
903 <$jewel>::min(&a_gap_dp, &b_gap_dp, &mut dp0);
904 dp0.min_mut(&sub);
905
906 if allow_transpose {
907 // blend using transpose mask
908 dp0.blendv_mut(&transpose, &match_mask0);
909 mem::swap(&mut match_mask0, &mut match_mask1);
910 }
911 }
912
913 mem::swap(&mut dp0, &mut dp_temp);
914 mem::swap(&mut dp_temp, &mut dp1);
915 mem::swap(&mut dp1, &mut dp2);
916
917 // (anti) diagonal that matches in the a and b windows
918 <$jewel>::cmpeq(&a_k2_window, &b_k2_window, &mut match_mask1);
919 <$jewel>::andnot(&match_mask1, &mismatch_cost, &mut sub);
920 sub.adds_mut(&dp1);
921 // cost of gaps in b
922 // start new gap
923 <$jewel>::adds(&dp2, &start_gap_cost, &mut b_gap);
924 // continue gap
925 b_gap_dp.adds_mut(&gap_cost);
926 b_gap_dp.min_mut(&b_gap);
927 b_gap_dp.shift_left_1_mut();
928 b_gap_dp.insert_last_max(); // k1, shift in max value
929 // cost of gaps in a
930 // start new gap
931 <$jewel>::adds(&dp2, &start_gap_cost, &mut a_gap);
932 a_gap_dp.adds_mut(&gap_cost);
933 // continue gap
934 a_gap_dp.min_mut(&a_gap);
935
936 if allow_transpose {
937 <$jewel>::shift_left_1(&match_mask0, &mut transpose); // reuse transpose, zeros shifted in
938 transpose.and_mut(&match_mask0);
939 // make sure that current matching locations are excluded
940 <$jewel>::andnot(&match_mask1, &transpose, &mut match_mask0); // reuse match_mask0 to represent transpose mask
941 <$jewel>::adds(&dp0, &transpose_cost, &mut transpose);
942 }
943
944 // min of the cost of all three edit operations
945 if trace_on {
946 let mut args = <$jewel>::triple_argmin(&sub, &a_gap_dp, &b_gap_dp, &mut dp0);
947
948 if allow_transpose {
949 // blend using transpose mask
950 dp0.blendv_mut(&transpose, &match_mask0);
951 args.blendv_mut(&threes, &match_mask0);
952 mem::swap(&mut match_mask0, &mut match_mask1);
953 }
954
955 traceback_arr.push(args);
956 }else{
957 <$jewel>::min(&a_gap_dp, &b_gap_dp, &mut dp0);
958 dp0.min_mut(&sub);
959
960 if allow_transpose {
961 // blend using transpose mask
962 dp0.blendv_mut(&transpose, &match_mask0);
963 mem::swap(&mut match_mask0, &mut match_mask1);
964 }
965 }
966
967 mem::swap(&mut dp0, &mut dp_temp);
968 mem::swap(&mut dp_temp, &mut dp1);
969 mem::swap(&mut dp1, &mut dp2);
970 }
971
972 let final_res = if ends_with_k2 {
973 dp2.slow_extract(final_idx)
974 }else{
975 dp1.slow_extract(final_idx)
976 };
977
978 if final_res > k {
979 return None;
980 }
981
982 if !trace_on {
983 return Some((final_res, None));
984 }
985
986 // upper bound the number of edit operations, to reduce memory allocations for saving the traceback
987 let mut upper_bound_edits = final_res / (cmp::min(costs.mismatch_cost, costs.gap_cost) as u32);
988
989 if let Some(cost) = costs.transpose_cost {
990 upper_bound_edits = cmp::max(upper_bound_edits, (final_res >> 1) / (cost as u32) + 1);
991 }
992
993 Some((final_res, Some($traceback_name(&traceback_arr, upper_bound_edits as usize, final_idx, a, b, swap, ends_with_k2))))
994 }
995
996 unsafe fn $traceback_name(arr: &[$jewel], k: usize, mut idx: usize, a: &[u8], b: &[u8], swap: bool, mut is_k2: bool) -> Vec<Edit> {
997 // keep track of position in traditional dp array and strings
998 let mut i = a.len(); // index in a
999 let mut j = b.len(); // index in b
1000
1001 // last diagonal may overshoot, so ignore it
1002 let mut arr_idx = arr.len() - 1 - (if is_k2 {0} else {1});
1003 let mut res: Vec<Edit> = Vec::with_capacity((k << 1) + 1);
1004
1005 while arr_idx > 0 {
1006 // each Jewel vector in arr is only visited once, so extract (which is costly) is fine
1007 let edit = arr.get_unchecked(arr_idx).slow_extract(idx);
1008
1009 let e = match edit {
1010 0 => { // match/mismatch
1011 arr_idx -= 2;
1012 i -= 1;
1013 j -= 1;
1014 if *a.get_unchecked(i) == *b.get_unchecked(j) {EditType::Match} else {EditType::Mismatch}
1015 },
1016 1 => { // a gap
1017 arr_idx -= 1;
1018
1019 if !is_k2 {
1020 idx -= 1;
1021 }
1022
1023 j -= 1;
1024 is_k2 = !is_k2; // must account for alternating k1/k2 diagonals
1025 if swap {EditType::BGap} else {EditType::AGap} // account for the swap in the beginning
1026 },
1027 2 => { // b gap
1028 arr_idx -= 1;
1029
1030 if is_k2 {
1031 idx += 1;
1032 }
1033
1034 i -= 1;
1035 is_k2 = !is_k2;
1036 if swap {EditType::AGap} else {EditType::BGap}
1037 },
1038 3 => { // transpose
1039 arr_idx -= 4;
1040 i -= 2;
1041 j -= 2;
1042 EditType::Transpose
1043 },
1044 _ => unreachable!()
1045 };
1046
1047 if res.len() > 0 && res.last().unwrap().edit == e {
1048 res.last_mut().unwrap().count += 1;
1049 }else{
1050 res.push(Edit{edit: e, count: 1});
1051 }
1052 }
1053
1054 res.reverse();
1055 res
1056 }
1057 };
1058 }
1059
1060 // create a version of the functions for each Jewel vector
1061 #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
1062 create_levenshtein_simd_core!(levenshtein_simd_core_avx_1x32x8, traceback_avx_1x32x8, Avx1x32x8, "avx2");
1063 #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
1064 create_levenshtein_simd_core!(levenshtein_simd_core_avx_2x32x8, traceback_avx_2x32x8, Avx2x32x8, "avx2");
1065 #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
1066 create_levenshtein_simd_core!(levenshtein_simd_core_avx_4x32x8, traceback_avx_4x32x8, Avx4x32x8, "avx2");
1067 #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
1068 create_levenshtein_simd_core!(levenshtein_simd_core_avx_8x32x8, traceback_avx_8x32x8, Avx8x32x8, "avx2");
1069 #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
1070 create_levenshtein_simd_core!(levenshtein_simd_core_avx_nx16x16, traceback_avx_nx16x16, AvxNx16x16, "avx2");
1071 #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
1072 create_levenshtein_simd_core!(levenshtein_simd_core_avx_nx8x32, traceback_avx_nx8x32, AvxNx8x32, "avx2");
1073
1074 #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
1075 create_levenshtein_simd_core!(levenshtein_simd_core_sse_1x16x8, traceback_sse_1x16x8, Sse1x16x8, "sse4.1");
1076 #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
1077 create_levenshtein_simd_core!(levenshtein_simd_core_sse_2x16x8, traceback_sse_2x16x8, Sse2x16x8, "sse4.1");
1078 #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
1079 create_levenshtein_simd_core!(levenshtein_simd_core_sse_4x16x8, traceback_sse_4x16x8, Sse4x16x8, "sse4.1");
1080 #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
1081 create_levenshtein_simd_core!(levenshtein_simd_core_sse_8x16x8, traceback_sse_8x16x8, Sse8x16x8, "sse4.1");
1082 #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
1083 create_levenshtein_simd_core!(levenshtein_simd_core_sse_16x16x8, traceback_sse_16x16x8, Sse16x16x8, "sse4.1");
1084 #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
1085 create_levenshtein_simd_core!(levenshtein_simd_core_sse_nx8x16, traceback_sse_nx8x16, SseNx8x16, "sse4.1");
1086 #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
1087 create_levenshtein_simd_core!(levenshtein_simd_core_sse_nx4x32, traceback_sse_nx4x32, SseNx4x32, "sse4.1");
1088
1089 /// Returns the Levenshtein distance between two strings using SIMD acceleration.
1090 ///
1091 /// Note that `levenshtein_exp` may be much faster if the number of edits between the two strings
1092 /// is expected to be small.
1093 /// Internally, this will call `levenshtein_simd_k`.
1094 /// If AVX2 or SSE4.1 is not supported, then this will automatically fall back to a scalar alternative.
1095 ///
1096 /// # Arguments
1097 /// * `a` - first string (slice)
1098 /// * `b` - second string (slice)
1099 ///
1100 /// # Example
1101 /// ```
1102 /// # use triple_accel::*;
1103 /// let dist = levenshtein(b"abc", b"ab");
1104 ///
1105 /// assert!(dist == 1);
1106 /// ```
1107 pub fn levenshtein(a: &[u8], b: &[u8]) -> u32 {
1108 levenshtein_simd_k(a, b, u32::MAX).unwrap()
1109 }
1110
1111 /// Returns the restricted Damerau-Levenshtein distance between two strings using SIMD acceleration.
1112 ///
1113 /// Note that `rdamerau_exp` may be much faster if the number of edits between the two strings
1114 /// is expected to be small.
1115 /// Internally, this will call `levenshtein_simd_k_with_opts`.
1116 /// If AVX2 or SSE4.1 is not supported, then this will automatically fall back to a scalar alternative.
1117 ///
1118 /// # Arguments
1119 /// * `a` - first string (slice)
1120 /// * `b` - second string (slice)
1121 ///
1122 /// # Example
1123 /// ```
1124 /// # use triple_accel::*;
1125 /// let dist = rdamerau(b"abc", b"acb");
1126 ///
1127 /// assert!(dist == 1);
1128 /// ```
1129 pub fn rdamerau(a: &[u8], b: &[u8]) -> u32 {
1130 levenshtein_simd_k_with_opts(a, b, u32::MAX, false, RDAMERAU_COSTS).unwrap().0
1131 }
1132
1133 /// Returns the Levenshtein distance between two strings using exponential search and SIMD
1134 /// acceleration.
1135 ///
1136 /// This may be much more efficient than `levenshtein` if the number of edits between `a` and `b`
1137 /// is expected to be small.
1138 /// Internally, this will call `levenshtein_simd_k` with values of `k` determined through
1139 /// exponential search.
1140 /// If AVX2 or SSE4.1 is not supported, then this will automatically fall back to a scalar alternative.
1141 ///
1142 /// # Arguments
1143 /// * `a` - first string (slice)
1144 /// * `b` - second string (slice)
1145 ///
1146 /// # Example
1147 /// ```
1148 /// # use triple_accel::*;
1149 /// let dist = levenshtein_exp(b"abc", b"ab");
1150 ///
1151 /// assert!(dist == 1);
1152 /// ```
1153 pub fn levenshtein_exp(a: &[u8], b: &[u8]) -> u32 {
1154 let mut k = 30;
1155 let mut res = levenshtein_simd_k(a, b, k);
1156
1157 // exponential search
1158 while res.is_none() {
1159 k <<= 1;
1160 res = levenshtein_simd_k(a, b, k);
1161 }
1162
1163 // should not panic
1164 res.unwrap()
1165 }
1166
1167 /// Returns the restricted Damerau-Levenshtein distance between two strings using exponential
1168 /// search and SIMD acceleration.
1169 ///
1170 /// This may be much more efficient than `rdamerau` if the number of edits between `a` and `b`
1171 /// is expected to be small.
1172 /// Internally, this will call `levenshtein_simd_k_with_opts` with values of `k` determined through
1173 /// exponential search.
1174 /// If AVX2 or SSE4.1 is not supported, then this will automatically fall back to a scalar alternative.
1175 ///
1176 /// # Arguments
1177 /// * `a` - first string (slice)
1178 /// * `b` - second string (slice)
1179 ///
1180 /// # Example
1181 /// ```
1182 /// # use triple_accel::*;
1183 /// let dist = rdamerau_exp(b"abc", b"acb");
1184 ///
1185 /// assert!(dist == 1);
1186 /// ```
1187 pub fn rdamerau_exp(a: &[u8], b: &[u8]) -> u32 {
1188 let mut k = 30;
1189 let mut res = levenshtein_simd_k_with_opts(a, b, k, false, RDAMERAU_COSTS);
1190
1191 // exponential search
1192 while res.is_none() {
1193 k <<= 1;
1194 res = levenshtein_simd_k_with_opts(a, b, k, false, RDAMERAU_COSTS);
1195 }
1196
1197 // should not panic
1198 res.unwrap().0
1199 }
1200
1201 /// Returns an iterator over the best `Match`s by searching through the text `haystack` for the
1202 /// pattern `needle` using the naive algorithm.
1203 ///
1204 /// The best matches are the matches with the lowest Levenshtein distance.
1205 /// If multiple best matches end at the same position or fully overlap, then the longest match is chosen.
1206 /// If `needle` is empty, then no `Match`es are returned.
1207 /// Each returned `Match` requires at least half or more bytes of the `needle` to match
1208 /// somewhere in the `haystack`.
1209 ///
1210 /// # Arguments
1211 /// * `needle` - pattern string (slice)
1212 /// * `haystack` - text string (slice)
1213 ///
1214 /// # Example
1215 /// ```
1216 /// # use triple_accel::*;
1217 /// # use triple_accel::levenshtein::*;
1218 /// let matches: Vec<Match> = levenshtein_search_naive(b"abc", b" abd").collect();
1219 ///
1220 /// assert!(matches == vec![Match{start: 2, end: 5, k: 1}]);
1221 /// ```
1222 pub fn levenshtein_search_naive<'a>(needle: &'a [u8], haystack: &'a [u8]) -> Box<dyn Iterator<Item = Match> + 'a> {
1223 levenshtein_search_naive_with_opts(needle, haystack, ((needle.len() as u32) >> 1) + ((needle.len() as u32) & 1), SearchType::Best, LEVENSHTEIN_COSTS, false)
1224 }
1225
1226 /// Returns an iterator over `Match`s by searching through the text `haystack` for the
1227 /// pattern `needle` using the naive algorithm, with extra options.
1228 ///
1229 /// Note that overlapping matches may be returned.
1230 /// If multiple matches end at the same position, then the longest match is chosen.
1231 /// If `needle` is empty and `anchored` is false, then no `Match`es are returned.
1232 ///
1233 /// # Arguments
1234 /// * `needle` - pattern string (slice)
1235 /// * `haystack` - text string (slice)
1236 /// * `k` - maximum cost threshold for a match to be returned
1237 /// * `search_type` - indicates whether to return all matches (within a cost of `k`), or the best matches with
1238 /// the lowest cost (additionally, only the longest matches are retained for matches that fully overlap)
1239 /// * `costs` - `EditCosts` struct for the cost of each edit operation
1240 /// * `anchored` - whether the `needle` should be anchored to the start of the `haystack` string,
1241 /// causing any shifts to cost gap edits
1242 ///
1243 /// # Example
1244 /// ```
1245 /// # use triple_accel::*;
1246 /// # use triple_accel::levenshtein::*;
1247 /// let matches: Vec<Match> = levenshtein_search_naive_with_opts(b"abc", b" acb", 1, SearchType::All, RDAMERAU_COSTS, false).collect();
1248 ///
1249 /// // note: it is possible to end the match at two different positions
1250 /// assert!(matches == vec![Match{start: 2, end: 4, k: 1}, Match{start: 2, end: 5, k: 1}]);
1251 /// ```
1252 pub fn levenshtein_search_naive_with_opts<'a>(needle: &'a [u8], haystack: &'a [u8], k: u32, search_type: SearchType, costs: EditCosts, anchored: bool) -> Box<dyn Iterator<Item = Match> + 'a> {
1253 let needle_len = needle.len();
1254 let haystack_len = haystack.len();
1255
1256 if needle_len == 0 {
1257 // special case when anchored is true: return possible matches
1258 if anchored {
1259 return match search_type {
1260 SearchType::All => {
1261 let mut i = 0;
1262 let mut cost = costs.start_gap_cost as u32;
1263 let mut start = true;
1264
1265 Box::new(iter::from_fn(move || {
1266 if start {
1267 start = false;
1268 return Some(Match{start: 0, end: 0, k: 0});
1269 }
1270
1271 if i < haystack_len {
1272 i += 1;
1273 cost += costs.gap_cost as u32;
1274
1275 if cost <= k {
1276 return Some(Match{start: 0, end: i, k: cost});
1277 }
1278 }
1279
1280 None
1281 }))
1282 },
1283 SearchType::Best => Box::new(iter::once(Match{start: 0, end: 0, k: 0}))
1284 };
1285 }else{
1286 return Box::new(iter::empty());
1287 }
1288 }
1289
1290 // enforce another constraint on the costs
1291 costs.check_search();
1292
1293 let len = needle_len + 1;
1294 let iter_len = if anchored {
1295 // start_gap_cost must be incurred at least once
1296 cmp::min(haystack_len, needle_len.saturating_add(
1297 (k.saturating_sub(costs.start_gap_cost as u32) as usize) / (costs.gap_cost as usize)))
1298 }else{
1299 haystack_len
1300 };
1301
1302 let mut dp0 = vec![0u32; len];
1303 let mut dp1 = vec![0u32; len];
1304 let mut dp2 = vec![0u32; len];
1305 let mut needle_gap_dp = vec![u32::MAX; len];
1306 let mut haystack_gap_dp = vec![u32::MAX; len];
1307 let mut length0 = vec![0usize; len];
1308 let mut length1 = vec![0usize; len];
1309 let mut length2 = vec![0usize; len];
1310 let mut needle_gap_length = vec![0usize; len];
1311 let mut haystack_gap_length = vec![0usize; len];
1312 let mut curr_k = k;
1313 let mismatch_cost = costs.mismatch_cost as u32;
1314 let gap_cost = costs.gap_cost as u32;
1315 let start_gap_cost = costs.start_gap_cost as u32;
1316 let transpose_cost = match costs.transpose_cost {
1317 Some(cost) => cost as u32,
1318 None => 0
1319 };
1320 let allow_transpose = costs.transpose_cost.is_some();
1321 let mut first = true;
1322 let mut i = 0;
1323
1324 let res = iter::from_fn(move || {
1325 if first {
1326 first = false;
1327
1328 for j in 0..len {
1329 dp1[j] = (j as u32) * gap_cost + if j == 0 {0} else {start_gap_cost};
1330 }
1331
1332 if dp1[len - 1] <= curr_k {
1333 if search_type == SearchType::Best {
1334 curr_k = dp1[len - 1];
1335 }
1336
1337 return Some((Match{start: 0, end: 0, k: dp1[len - 1]}, curr_k));
1338 }
1339 }
1340
1341 while i < iter_len {
1342 needle_gap_dp[0] = if anchored {(i as u32 + 1) * gap_cost + start_gap_cost} else {0};
1343 dp2[0] = if anchored {(i as u32 + 1) * gap_cost + start_gap_cost} else {0};
1344 needle_gap_length[0] = 0;
1345 length2[0] = 0;
1346
1347 for j in 1..len {
1348 let sub = dp1[j - 1] + ((needle[j - 1] != haystack[i]) as u32) * mismatch_cost;
1349
1350 let new_gap = dp1[j] + start_gap_cost + gap_cost;
1351 let cont_gap = needle_gap_dp[j].saturating_add(gap_cost);
1352 if new_gap < cont_gap {
1353 needle_gap_dp[j] = new_gap;
1354 needle_gap_length[j] = length1[j] + 1;
1355 }else if new_gap > cont_gap {
1356 needle_gap_dp[j] = cont_gap;
1357 needle_gap_length[j] += 1;
1358 }else{
1359 needle_gap_dp[j] = cont_gap;
1360 needle_gap_length[j] = cmp::max(length1[j], needle_gap_length[j]) + 1;
1361 }
1362
1363 let new_gap = dp2[j - 1] + start_gap_cost + gap_cost;
1364 let cont_gap = haystack_gap_dp[j - 1].saturating_add(gap_cost);
1365 if new_gap < cont_gap {
1366 haystack_gap_dp[j] = new_gap;
1367 haystack_gap_length[j] = length2[j - 1];
1368 }else if new_gap > cont_gap {
1369 haystack_gap_dp[j] = cont_gap;
1370 haystack_gap_length[j] = haystack_gap_length[j - 1];
1371 }else{
1372 haystack_gap_dp[j] = cont_gap;
1373 haystack_gap_length[j] = cmp::max(length2[j - 1], haystack_gap_length[j - 1]);
1374 }
1375
1376 dp2[j] = needle_gap_dp[j];
1377 length2[j] = needle_gap_length[j];
1378
1379 if (haystack_gap_dp[j] < dp2[j]) || (haystack_gap_dp[j] == dp2[j] && length2[j - 1] > length2[j]) {
1380 dp2[j] = haystack_gap_dp[j];
1381 length2[j] = haystack_gap_length[j];
1382 }
1383
1384 if (sub < dp2[j]) || (sub == dp2[j] && (length1[j - 1] + 1) > length2[j]) {
1385 dp2[j] = sub;
1386 length2[j] = length1[j - 1] + 1;
1387 }
1388
1389 if allow_transpose && i > 0 && j > 1
1390 && needle[j - 1] == haystack[i - 1] && needle[j - 2] == haystack[i] {
1391 let transpose = dp0[j - 2] + transpose_cost;
1392
1393 if transpose <= dp2[j] {
1394 dp2[j] = transpose;
1395 length2[j] = length0[j - 2] + 2;
1396 }
1397 }
1398 }
1399
1400 let final_res = dp2[len - 1];
1401 let final_length = length2[len - 1];
1402
1403 mem::swap(&mut dp0, &mut dp1);
1404 mem::swap(&mut dp1, &mut dp2);
1405 mem::swap(&mut length0, &mut length1);
1406 mem::swap(&mut length1, &mut length2);
1407
1408 i += 1;
1409
1410 if final_res <= curr_k {
1411 match search_type {
1412 SearchType::Best => curr_k = final_res,
1413 _ => ()
1414 }
1415
1416 return Some((Match{start: i - final_length, end: i, k: final_res}, curr_k));
1417 }
1418 }
1419
1420 None
1421 });
1422
1423 if search_type == SearchType::Best {
1424 // estimate the number of Matches
1425 let mut res_vec = Vec::with_capacity(iter_len / needle_len);
1426
1427 for m in res {
1428 match res_vec.len() {
1429 0 => res_vec.push(m.0),
1430 _ => {
1431 let last = res_vec.last_mut().unwrap();
1432
1433 // replace previous if fully overlapping
1434 if m.0.start <= last.start {
1435 *last = m.0;
1436 }else{
1437 res_vec.push(m.0);
1438 }
1439 }
1440 }
1441
1442 curr_k = m.1;
1443 }
1444
1445 return Box::new(res_vec.into_iter().filter(move |m| m.k == curr_k));
1446 }
1447
1448 Box::new(res.map(|m| m.0))
1449 }
1450
1451 /// Returns an iterator over the best `Match`s by searching through the text `haystack` for the
1452 /// pattern `needle` using SIMD acceleration.
1453 ///
1454 /// The best matches are the matches with the lowest Levenshtein distance.
1455 /// If multiple best matches end at the same position or fully overlap, then the longest match is chosen.
1456 /// If `needle` is empty, then no `Match`es are returned.
1457 /// Each returned `Match` requires at least half or more bytes of the `needle` to match
1458 /// somewhere in the `haystack`.
1459 /// This should be much faster than `levenshtein_search_naive`.
1460 /// Internally, this will automatically use AVX or SSE vectors with 8-bit, 16-bit, or 32-bit elements
1461 /// to represent anti-diagonals in the dynamic programming matrix for calculating Levenshtein distance.
1462 /// If AVX2 or SSE4.1 is not supported, then this will automatically fall back to
1463 /// `levenshtein_search_naive_with_opts`.
1464 ///
1465 /// # Arguments
1466 /// * `needle` - pattern string (slice)
1467 /// * `haystack` - text string (slice)
1468 ///
1469 /// # Example
1470 /// ```
1471 /// # use triple_accel::*;
1472 /// # use triple_accel::levenshtein::*;
1473 /// let matches: Vec<Match> = levenshtein_search_simd(b"abc", b" abd").collect();
1474 ///
1475 /// assert!(matches == vec![Match{start: 2, end: 5, k: 1}]);
1476 /// ```
1477 pub fn levenshtein_search_simd<'a>(needle: &'a [u8], haystack: &'a [u8]) -> Box<dyn Iterator<Item = Match> + 'a> {
1478 levenshtein_search_simd_with_opts(needle, haystack, ((needle.len() >> 1) as u32) + ((needle.len() as u32) & 1), SearchType::Best, LEVENSHTEIN_COSTS, false)
1479 }
1480
1481 /// Returns an iterator over `Match`s by searching through the text `haystack` for the
1482 /// pattern `needle` using SIMD acceleration, with extra options.
1483 ///
1484 /// Note that overlapping matches may be returned.
1485 /// If multiple matches end at the same position, then the longest match is chosen.
1486 /// If `needle` is empty and `anchored` is false, then no `Match`es are returned.
1487 /// This should be much faster than `levenshtein_search_naive_with_opts`.
1488 /// Internally, this will automatically use AVX or SSE vectors with 8-bit, 16-bit, or 32-bit elements
1489 /// to represent anti-diagonals in the dynamic programming matrix for calculating Levenshtein distance.
1490 /// If AVX2 or SSE4.1 is not supported, then this will automatically fall back to
1491 /// `levenshtein_search_naive_with_opts`.
1492 ///
1493 /// # Arguments
1494 /// * `needle` - pattern string (slice)
1495 /// * `haystack` - text string (slice)
1496 /// * `k` - maximum cost threshold for a match to be returned
1497 /// * `search_type` - indicates whether to return all matches (within a cost of `k`), or the best matches with
1498 /// the lowest cost (additionally, only the longest matches are retained for matches that fully overlap)
1499 /// * `costs` - `EditCosts` struct for the cost of each edit operation
1500 /// * `anchored` - whether the `needle` should be anchored to the start of the `haystack` string,
1501 /// causing any shifts to cost gap edits
1502 ///
1503 /// # Example
1504 /// ```
1505 /// # use triple_accel::*;
1506 /// # use triple_accel::levenshtein::*;
1507 /// let matches: Vec<Match> = levenshtein_search_simd_with_opts(b"abc", b" acb", 1, SearchType::All, RDAMERAU_COSTS, false).collect();
1508 ///
1509 /// // note: it is possible to end the match at two different positions
1510 /// assert!(matches == vec![Match{start: 2, end: 4, k: 1}, Match{start: 2, end: 5, k: 1}]);
1511 /// ```
1512 pub fn levenshtein_search_simd_with_opts<'a>(needle: &'a [u8], haystack: &'a [u8], k: u32, search_type: SearchType, costs: EditCosts, anchored: bool) -> Box<dyn Iterator<Item = Match> + 'a> {
1513 if needle.len() == 0 {
1514 // special case when anchored is true: return possible matches
1515 if anchored {
1516 return match search_type {
1517 SearchType::All => {
1518 let mut i = 0;
1519 let mut cost = costs.start_gap_cost as u32;
1520 let mut start = true;
1521
1522 Box::new(iter::from_fn(move || {
1523 if start {
1524 start = false;
1525 return Some(Match{start: 0, end: 0, k: 0});
1526 }
1527
1528 if i < haystack.len() {
1529 i += 1;
1530 cost += costs.gap_cost as u32;
1531
1532 if cost <= k {
1533 return Some(Match{start: 0, end: i, k: cost});
1534 }
1535 }
1536
1537 None
1538 }))
1539 },
1540 SearchType::Best => Box::new(iter::once(Match{start: 0, end: 0, k: 0}))
1541 };
1542 }else{
1543 return Box::new(iter::empty());
1544 }
1545 }
1546
1547 costs.check_search();
1548
1549 #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
1550 {
1551 let unit_k = k.saturating_sub(costs.start_gap_cost as u32) / (costs.gap_cost as u32);
1552 // either the length of the match or the number of edits may exceed the maximum
1553 // available int size; additionally, MAX value is used to indicate overflow
1554 let upper_bound = cmp::max((needle.len() as u32).saturating_add(unit_k), k.saturating_add(1));
1555
1556 if cfg!(feature = "jewel-avx") && is_x86_feature_detected!("avx2") {
1557 if cfg!(feature = "jewel-8bit") && needle.len() <= Avx1x32x8::static_upper_bound() && upper_bound <= u8::MAX as u32 {
1558 return unsafe {levenshtein_search_simd_core_avx_1x32x8(needle, haystack, k, search_type, costs, anchored)};
1559 }else if cfg!(feature = "jewel-8bit") && needle.len() <= Avx2x32x8::static_upper_bound() && upper_bound <= u8::MAX as u32 {
1560 return unsafe {levenshtein_search_simd_core_avx_2x32x8(needle, haystack, k, search_type, costs, anchored)};
1561 }else if cfg!(feature = "jewel-8bit") && needle.len() <= Avx4x32x8::static_upper_bound() && upper_bound <= u8::MAX as u32 {
1562 return unsafe {levenshtein_search_simd_core_avx_4x32x8(needle, haystack, k, search_type, costs, anchored)};
1563 }else if cfg!(feature = "jewel-8bit") && needle.len() <= Avx8x32x8::static_upper_bound() && upper_bound <= u8::MAX as u32 {
1564 return unsafe {levenshtein_search_simd_core_avx_8x32x8(needle, haystack, k, search_type, costs, anchored)};
1565 }else if cfg!(feature = "jewel-16bit") && upper_bound <= u16::MAX as u32 {
1566 return unsafe {levenshtein_search_simd_core_avx_nx16x16(needle, haystack, k, search_type, costs, anchored)};
1567 }else if cfg!(feature = "jewel-32bit") {
1568 return unsafe {levenshtein_search_simd_core_avx_nx8x32(needle, haystack, k, search_type, costs, anchored)};
1569 }
1570 }else if cfg!(feature = "jewel-sse") && is_x86_feature_detected!("sse4.1") {
1571 if cfg!(feature = "jewel-8bit") && needle.len() <= Sse1x16x8::static_upper_bound() && upper_bound <= u8::MAX as u32 {
1572 return unsafe {levenshtein_search_simd_core_sse_1x16x8(needle, haystack, k, search_type, costs, anchored)};
1573 }else if cfg!(feature = "jewel-8bit") && needle.len() <= Sse2x16x8::static_upper_bound() && upper_bound <= u8::MAX as u32 {
1574 return unsafe {levenshtein_search_simd_core_sse_2x16x8(needle, haystack, k, search_type, costs, anchored)};
1575 }else if cfg!(feature = "jewel-8bit") && needle.len() <= Sse4x16x8::static_upper_bound() && upper_bound <= u8::MAX as u32 {
1576 return unsafe {levenshtein_search_simd_core_sse_4x16x8(needle, haystack, k, search_type, costs, anchored)};
1577 }else if cfg!(feature = "jewel-8bit") && needle.len() <= Sse8x16x8::static_upper_bound() && upper_bound <= u8::MAX as u32 {
1578 return unsafe {levenshtein_search_simd_core_sse_8x16x8(needle, haystack, k, search_type, costs, anchored)};
1579 }else if cfg!(feature = "jewel-8bit") && needle.len() <= Sse16x16x8::static_upper_bound() && upper_bound <= u8::MAX as u32 {
1580 return unsafe {levenshtein_search_simd_core_sse_16x16x8(needle, haystack, k, search_type, costs, anchored)};
1581 }else if cfg!(feature = "jewel-16bit") && upper_bound <= u16::MAX as u32 {
1582 return unsafe {levenshtein_search_simd_core_sse_nx8x16(needle, haystack, k, search_type, costs, anchored)};
1583 }else if cfg!(feature = "jewel-32bit") {
1584 return unsafe {levenshtein_search_simd_core_sse_nx4x32(needle, haystack, k, search_type, costs, anchored)};
1585 }
1586 }
1587 }
1588
1589 levenshtein_search_naive_with_opts(needle, haystack, k, search_type, costs, anchored)
1590 }
1591
1592 macro_rules! create_levenshtein_search_simd_core {
1593 ($name:ident, $jewel:ty, $target:literal) => {
1594 #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
1595 #[target_feature(enable = $target)]
1596 unsafe fn $name<'a>(needle: &'a [u8], haystack: &'a [u8], k: u32, search_type: SearchType, costs: EditCosts, anchored: bool) -> Box<dyn Iterator<Item = Match> + 'a> {
1597 #[cfg(feature = "debug")]
1598 {
1599 println!("Debug: Levenshtein search Jewel vector type {} for target {}.", stringify!($jewel), stringify!($target));
1600 }
1601
1602 let needle_len = needle.len();
1603 let haystack_len = haystack.len();
1604 let mut dp0 = <$jewel>::repeating_max(needle_len);
1605 let mut dp_temp = <$jewel>::repeating_max(needle_len);
1606 let mut dp1 = <$jewel>::repeating_max(needle_len);
1607 let mut dp2 = <$jewel>::repeating_max(needle_len);
1608 let mut needle_gap_dp = <$jewel>::repeating_max(needle_len);
1609 let mut haystack_gap_dp = <$jewel>::repeating_max(needle_len);
1610 dp2.slow_insert(dp2.upper_bound() - 1, costs.start_gap_cost as u32 + costs.gap_cost as u32); // last cell
1611 haystack_gap_dp.slow_insert(dp2.upper_bound() - 1, costs.start_gap_cost as u32 + costs.gap_cost as u32);
1612
1613 // save length instead of start idx due to int size constraints
1614 let mut length0 = <$jewel>::repeating(0, needle_len);
1615 let mut length_temp = <$jewel>::repeating(0, needle_len);
1616 let mut length1 = <$jewel>::repeating(0, needle_len);
1617 let mut length2 = <$jewel>::repeating(0, needle_len);
1618 let mut needle_gap_length = <$jewel>::repeating(0, needle_len);
1619 let mut haystack_gap_length = <$jewel>::repeating(0, needle_len);
1620
1621 let ones = <$jewel>::repeating(1, needle_len);
1622 let twos = <$jewel>::repeating(2, needle_len);
1623
1624 // the suffix of haystack can be ignored if needle must be anchored
1625 let len = if anchored {
1626 needle_len + cmp::min(haystack_len, needle_len.saturating_add(
1627 (k.saturating_sub(costs.start_gap_cost as u32) as usize) / (costs.gap_cost as usize)))
1628 }else{
1629 needle_len + haystack_len
1630 };
1631
1632 let final_idx = dp1.upper_bound() - needle_len;
1633
1634 // load needle characters into needle_window in reversed order
1635 let mut needle_window = <$jewel>::repeating(0, needle_len);
1636 needle_window.slow_loadu(needle_window.upper_bound() - 1, needle.as_ptr(), needle_len, true);
1637
1638 let mut haystack_window = <$jewel>::repeating(0, needle_len);
1639 let mut haystack_idx = 0usize;
1640 let mut curr_k = k;
1641
1642 // used in calculations
1643 let mut match_mask0 = <$jewel>::repeating(0, needle_len);
1644 let mut match_mask1 = <$jewel>::repeating(0, needle_len);
1645 let mut match_mask_cost = <$jewel>::repeating(0, needle_len);
1646 let mut sub = <$jewel>::repeating(0, needle_len);
1647 let mut sub_length = <$jewel>::repeating(0, needle_len);
1648 let mut needle_gap = <$jewel>::repeating(0, needle_len);
1649 let mut haystack_gap = <$jewel>::repeating(0, needle_len);
1650 let mut transpose = <$jewel>::repeating(0, needle_len);
1651 let mut transpose_length = <$jewel>::repeating(0, needle_len);
1652
1653 let mismatch_cost = <$jewel>::repeating(costs.mismatch_cost as u32, needle_len);
1654 let gap_cost = <$jewel>::repeating(costs.gap_cost as u32, needle_len);
1655 let start_gap_cost = <$jewel>::repeating(costs.start_gap_cost as u32, needle_len);
1656 let transpose_cost = match costs.transpose_cost {
1657 Some(cost) => <$jewel>::repeating(cost as u32, needle_len),
1658 None => <$jewel>::repeating(0, needle_len)
1659 };
1660 let allow_transpose = costs.transpose_cost.is_some();
1661
1662 // ..i...
1663 // --h---
1664 // | //////xxxx
1665 // | x//////xxx
1666 // n xx//////xx
1667 // | xxx//////x
1668 // | xxxx//////
1669 //
1670 // 'n' = needle, 'h' = haystack
1671 // each (anti) diagonal is denoted using '/' and 'x'
1672 // 'x' marks cells that are not in the traditional dp array
1673 // every (anti) diagonal is calculated simultaneously using Jewel vectors
1674 // note: each vector goes from bottom-left to top-right, ending at the first row in the
1675 // DP matrix
1676 // similar to levenshtein_simd_k, but without alternating anti-diagonals
1677 // note that the first row, which should be all zeros for searching, is not saved in the
1678 // Jewel vectors, for space concerns
1679 // therefore, starting at i = 1 does not include the first diagonal that only contains
1680 // a zero from the initial row of zeros
1681 // when left shift are required, then zeros must be shifted in
1682 // if anchored = true, then the number of gaps times the gap cost plus the starting gap
1683 // cost must be shifted in
1684 // for speed, transpositions are done by directly blending using the mask, without calculating
1685 // the minimum cost compared to the other edit operations
1686
1687 let mut i = 1;
1688
1689 let res = iter::from_fn(move || {
1690 while i < len {
1691 // shift the haystack window
1692 haystack_window.shift_left_1_mut();
1693
1694 if haystack_idx < haystack_len {
1695 haystack_window.insert_last_0(*haystack.get_unchecked(haystack_idx) as u32);
1696 haystack_idx += 1;
1697 }
1698
1699 <$jewel>::cmpeq(&needle_window, &haystack_window, &mut match_mask1);
1700 <$jewel>::andnot(&match_mask1, &mismatch_cost, &mut match_mask_cost);
1701
1702 // match/mismatch
1703 <$jewel>::shift_left_1(&dp1, &mut sub);
1704
1705 if anchored && i > 1 {
1706 // dp1 is 2 diagonals behind the current i
1707 // must be capped at k to prevent overflow when inserting
1708 sub.insert_last_0(cmp::min((i as u32 - 1) * (costs.gap_cost as u32) + costs.start_gap_cost as u32, k + 1));
1709 }
1710
1711 sub.adds_mut(&match_mask_cost);
1712
1713 <$jewel>::shift_left_1(&length1, &mut sub_length); // zeros are shifted in
1714 sub_length.add_mut(&ones);
1715
1716 // gap in needle
1717 <$jewel>::adds(&dp2, &start_gap_cost, &mut needle_gap);
1718 <$jewel>::double_min_length(&needle_gap, &mut needle_gap_dp, &length2, &mut needle_gap_length);
1719 needle_gap_dp.adds_mut(&gap_cost);
1720 needle_gap_length.add_mut(&ones);
1721
1722 // gap in haystack
1723 <$jewel>::adds(&dp2, &start_gap_cost, &mut haystack_gap);
1724 <$jewel>::double_min_length(&haystack_gap, &mut haystack_gap_dp, &length2, &mut haystack_gap_length);
1725 haystack_gap_dp.shift_left_1_mut(); // zeros are shifted in
1726
1727 if anchored {
1728 // dp2 is one diagonal behind the current i
1729 haystack_gap_dp.insert_last_0(cmp::min((i as u32) * (costs.gap_cost as u32) + costs.start_gap_cost as u32, k + 1));
1730 }else{
1731 haystack_gap_dp.insert_last_0(costs.start_gap_cost as u32);
1732 }
1733
1734 haystack_gap_dp.adds_mut(&gap_cost);
1735 haystack_gap_length.shift_left_1_mut(); // zeros are shifted in
1736
1737 if allow_transpose {
1738 <$jewel>::shift_left_1(&match_mask0, &mut transpose); // reuse transpose, shift in zeros
1739 transpose.and_mut(&match_mask0);
1740 // ensure that current matches are excluded
1741 <$jewel>::andnot(&match_mask1, &transpose, &mut match_mask0); // reuse match_mask0 to represent transpose mask
1742 dp0.shift_left_2_mut();
1743
1744 if anchored && i > 3 {
1745 // dp0 is four diagonals behind the current i
1746 dp0.insert_last_1(cmp::min((i as u32 - 3) * (costs.gap_cost as u32) + costs.start_gap_cost as u32, k + 1));
1747 }
1748
1749 length0.shift_left_2_mut();
1750 <$jewel>::adds(&dp0, &transpose_cost, &mut transpose);
1751 <$jewel>::add(&length0, &twos, &mut transpose_length);
1752 }
1753
1754 <$jewel>::triple_min_length(&sub, &needle_gap_dp, &haystack_gap_dp, &sub_length,
1755 &needle_gap_length, &haystack_gap_length, &mut dp0, &mut length0);
1756
1757 if allow_transpose {
1758 // blend using transpose mask
1759 dp0.blendv_mut(&transpose, &match_mask0);
1760 length0.blendv_mut(&transpose_length, &match_mask0);
1761 mem::swap(&mut match_mask0, &mut match_mask1);
1762 }
1763
1764 mem::swap(&mut dp0, &mut dp_temp);
1765 mem::swap(&mut dp_temp, &mut dp1);
1766 mem::swap(&mut dp1, &mut dp2);
1767 mem::swap(&mut length0, &mut length_temp);
1768 mem::swap(&mut length_temp, &mut length1);
1769 mem::swap(&mut length1, &mut length2);
1770
1771 i += 1;
1772
1773 if i >= needle_len {
1774 let final_res = dp2.slow_extract(final_idx);
1775 let final_length = length2.slow_extract(final_idx) as usize;
1776
1777 if final_res <= curr_k {
1778 let end_idx = i - needle_len;
1779
1780 match search_type {
1781 // if we want the best, then we can shrink the k threshold
1782 SearchType::Best => curr_k = final_res,
1783 _ => ()
1784 }
1785
1786 return Some((Match{start: end_idx - final_length, end: end_idx, k: final_res}, curr_k));
1787 }
1788 }
1789 }
1790
1791 None
1792 });
1793
1794 if search_type == SearchType::Best {
1795 // estimate the number of Matches
1796 let mut res_vec = Vec::with_capacity((len - needle_len) / needle_len);
1797
1798 for m in res {
1799 match res_vec.len() {
1800 0 => res_vec.push(m.0),
1801 _ => {
1802 let last = res_vec.last_mut().unwrap();
1803
1804 // replace previous if fully overlapping
1805 if m.0.start <= last.start {
1806 *last = m.0;
1807 }else{
1808 res_vec.push(m.0);
1809 }
1810 }
1811 }
1812
1813 curr_k = m.1;
1814 }
1815
1816 // only retain matches with the lowest k
1817 return Box::new(res_vec.into_iter().filter(move |m| m.k == curr_k));
1818 }
1819
1820 Box::new(res.map(|m| m.0))
1821 }
1822 };
1823 }
1824
1825 // duplicate functions for each Jewel vector type
1826 #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
1827 create_levenshtein_search_simd_core!(levenshtein_search_simd_core_avx_1x32x8, Avx1x32x8, "avx2");
1828 #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
1829 create_levenshtein_search_simd_core!(levenshtein_search_simd_core_avx_2x32x8, Avx2x32x8, "avx2");
1830 #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
1831 create_levenshtein_search_simd_core!(levenshtein_search_simd_core_avx_4x32x8, Avx4x32x8, "avx2");
1832 #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
1833 create_levenshtein_search_simd_core!(levenshtein_search_simd_core_avx_8x32x8, Avx8x32x8, "avx2");
1834 #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
1835 create_levenshtein_search_simd_core!(levenshtein_search_simd_core_avx_nx16x16, AvxNx16x16, "avx2");
1836 #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
1837 create_levenshtein_search_simd_core!(levenshtein_search_simd_core_avx_nx8x32, AvxNx8x32, "avx2");
1838
1839 #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
1840 create_levenshtein_search_simd_core!(levenshtein_search_simd_core_sse_1x16x8, Sse1x16x8, "sse4.1");
1841 #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
1842 create_levenshtein_search_simd_core!(levenshtein_search_simd_core_sse_2x16x8, Sse2x16x8, "sse4.1");
1843 #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
1844 create_levenshtein_search_simd_core!(levenshtein_search_simd_core_sse_4x16x8, Sse4x16x8, "sse4.1");
1845 #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
1846 create_levenshtein_search_simd_core!(levenshtein_search_simd_core_sse_8x16x8, Sse8x16x8, "sse4.1");
1847 #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
1848 create_levenshtein_search_simd_core!(levenshtein_search_simd_core_sse_16x16x8, Sse16x16x8, "sse4.1");
1849 #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
1850 create_levenshtein_search_simd_core!(levenshtein_search_simd_core_sse_nx8x16, SseNx8x16, "sse4.1");
1851 #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
1852 create_levenshtein_search_simd_core!(levenshtein_search_simd_core_sse_nx4x32, SseNx4x32, "sse4.1");
1853
1854 /// Returns an iterator over best `Match`s by searching through the text `haystack` for the
1855 /// pattern `needle` using SIMD acceleration.
1856 ///
1857 /// The best matches are the matches with the lowest Levenshtein distance.
1858 /// If multiple best matches end at the same position or fully overlap, then the longest match is chosen.
1859 /// If `needle` is empty, then no `Match`es are returned.
1860 /// Each returned `Match` requires at least half or more bytes of the `needle` to match
1861 /// somewhere in the `haystack`.
1862 /// Internally, this will call `levenshtein_search_simd`.
1863 /// If AVX2 or SSE4.1 is not supported, then this will automatically fall back to a scalar alternative.
1864 ///
1865 /// # Arguments
1866 /// * `needle` - pattern string (slice)
1867 /// * `haystack` - text string (slice)
1868 ///
1869 /// # Example
1870 /// ```
1871 /// # use triple_accel::*;
1872 /// let matches: Vec<Match> = levenshtein_search(b"abc", b" abd").collect();
1873 ///
1874 /// assert!(matches == vec![Match{start: 2, end: 5, k: 1}]);
1875 /// ```
1876 pub fn levenshtein_search<'a>(needle: &'a [u8], haystack: &'a [u8]) -> Box<dyn Iterator<Item = Match> + 'a> {
1877 levenshtein_search_simd(needle, haystack)
1878 }
1879