rwer 0.2.1

A fast Rust crate for WER, CER, and related ASR evaluation metrics
Documentation
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
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
/// Represents a single edit operation in the alignment between reference and hypothesis.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum EditOp {
    /// Reference and hypothesis tokens match at this index.
    Equal {
        /// Index into the reference (and hypothesis) token list.
        index: usize,
    },
    /// Reference token was substituted by hypothesis token.
    Substitute {
        /// Index into the reference token list.
        ref_index: usize,
        /// Index into the hypothesis token list.
        hyp_index: usize,
    },
    /// Hypothesis token was inserted (not in reference).
    Insert {
        /// Index into the hypothesis token list.
        hyp_index: usize,
    },
    /// Reference token was deleted (not in hypothesis).
    Delete {
        /// Index into the reference token list.
        ref_index: usize,
    },
}

impl EditOp {
    /// Returns `true` if this is an equal (match) operation.
    #[must_use]
    pub fn is_equal(&self) -> bool {
        matches!(self, EditOp::Equal { .. })
    }

    /// Returns `true` if this is any error operation (substitution, insertion, or deletion).
    #[must_use]
    pub fn is_error(&self) -> bool {
        !self.is_equal()
    }

    /// Returns `true` if this is a substitution operation.
    #[must_use]
    pub fn is_substitute(&self) -> bool {
        matches!(self, EditOp::Substitute { .. })
    }

    /// Returns `true` if this is an insertion operation.
    #[must_use]
    pub fn is_insert(&self) -> bool {
        matches!(self, EditOp::Insert { .. })
    }

    /// Returns `true` if this is a deletion operation.
    #[must_use]
    pub fn is_delete(&self) -> bool {
        matches!(self, EditOp::Delete { .. })
    }
}

/// Counts of each edit operation type from an alignment.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct OperationCounts {
    /// Number of matching tokens.
    pub hits: usize,
    /// Number of substitutions.
    pub substitutions: usize,
    /// Number of deletions.
    pub deletions: usize,
    /// Number of insertions.
    pub insertions: usize,
}

/// Count the occurrences of each operation type.
#[must_use]
pub fn count_operations(ops: &[EditOp]) -> OperationCounts {
    let mut counts = OperationCounts::default();
    for op in ops {
        match op {
            EditOp::Equal { .. } => counts.hits += 1,
            EditOp::Substitute { .. } => counts.substitutions += 1,
            EditOp::Insert { .. } => counts.insertions += 1,
            EditOp::Delete { .. } => counts.deletions += 1,
        }
    }
    counts
}

/// Compute the Levenshtein edit distance between two token sequences.
///
/// Uses single-row dynamic programming for O(min(M,N)) space complexity.
pub(crate) fn edit_distance<S: AsRef<str> + PartialEq>(reference: &[S], hypothesis: &[S]) -> usize {
    let m = reference.len();
    let n = hypothesis.len();

    if m == 0 {
        return n;
    }
    if n == 0 {
        return m;
    }

    let mut prev_row: Vec<usize> = (0..=n).collect();
    let mut curr_row = vec![0; n + 1];

    for i in 1..=m {
        curr_row[0] = i;
        for j in 1..=n {
            let cost = usize::from(reference[i - 1] != hypothesis[j - 1]);
            curr_row[j] = (prev_row[j] + 1)
                .min(curr_row[j - 1] + 1)
                .min(prev_row[j - 1] + cost);
        }
        std::mem::swap(&mut prev_row, &mut curr_row);
    }

    prev_row[n]
}

/// Compute Levenshtein distance between two char sequences using rapidfuzz.
///
/// Uses Myers bit-parallel algorithm for O([K/64]×M) complexity where K is
/// the edit distance and M is the shorter sequence length.
pub(crate) fn rapidfuzz_char_distance(
    s1: impl IntoIterator<Item = char>,
    s2: impl IntoIterator<Item = char>,
) -> usize {
    let v1: Vec<char> = s1.into_iter().collect();
    let v2: Vec<char> = s2.into_iter().collect();
    rapidfuzz::distance::levenshtein::distance(v1.iter().copied(), v2.iter().copied())
}

/// Compute the Levenshtein alignment between two token sequences.
///
/// Uses a two-phase approach for performance:
/// 1. Compute total edit distance using single-row DP
/// 2. Run banded Wagner-Fischer (diagonal ± distance band) for traceback
///
/// The band width is derived from the precomputed distance, making this
/// much faster than full O(M×N) Wagner-Fischer when the distance is small
/// relative to the sequence lengths.
///
/// # Examples
///
/// ```
/// use rwer::alignment::align;
///
/// let ref_tokens = vec!["hello", "world"];
/// let hyp_tokens = vec!["hello", "earth"];
/// let ops = align(&ref_tokens, &hyp_tokens);
/// assert_eq!(ops.len(), 2);
/// ```
#[must_use]
pub fn align<S: AsRef<str> + PartialEq>(reference: &[S], hypothesis: &[S]) -> Vec<EditOp> {
    let m = reference.len();
    let n = hypothesis.len();

    if m == 0 {
        return (0..n).map(|i| EditOp::Insert { hyp_index: i }).collect();
    }
    if n == 0 {
        return (0..m).map(|i| EditOp::Delete { ref_index: i }).collect();
    }

    let dist = edit_distance(reference, hypothesis);

    if dist == 0 {
        return (0..m).map(|i| EditOp::Equal { index: i }).collect();
    }

    align_banded(reference, hypothesis, dist)
}

/// Banded Wagner-Fischer alignment.
///
/// Only computes DP cells within a band of width `(2 * dist + 1)` centered
/// on the main diagonal. This reduces time and space from O(M×N) to O(M×D)
/// where D is the edit distance.
fn align_banded<S: AsRef<str> + PartialEq>(
    reference: &[S],
    hypothesis: &[S],
    dist: usize,
) -> Vec<EditOp> {
    let ref_len = reference.len();
    let hyp_len = hypothesis.len();

    let band = dist;
    let lo = |row: usize| row.saturating_sub(band);
    let hi = |row: usize| std::cmp::min(hyp_len, row + band);

    let rows = build_banded_dp(reference, hypothesis, ref_len, &lo, &hi);
    backtrack_banded(reference, hypothesis, ref_len, hyp_len, &rows, &lo, &hi)
}

/// Build the banded DP table for Wagner-Fischer.
fn build_banded_dp<S: AsRef<str> + PartialEq>(
    reference: &[S],
    hypothesis: &[S],
    ref_len: usize,
    lo: &dyn Fn(usize) -> usize,
    hi: &dyn Fn(usize) -> usize,
) -> Vec<Vec<usize>> {
    let mut rows: Vec<Vec<usize>> = Vec::with_capacity(ref_len + 1);

    // Row 0
    {
        let lo_val = lo(0);
        let hi_val = hi(0);
        let mut row = vec![0; hi_val - lo_val + 1];
        for (idx, val) in row.iter_mut().enumerate() {
            *val = lo_val + idx;
        }
        rows.push(row);
    }

    // Rows 1..=ref_len
    for ref_idx in 1..=ref_len {
        let lo_val = lo(ref_idx);
        let hi_val = hi(ref_idx);
        let width = hi_val - lo_val + 1;
        let mut row = vec![0; width];

        let prev_lo = lo(ref_idx - 1);
        let prev_hi = hi(ref_idx - 1);

        for hyp_idx in lo_val..=hi_val {
            let local_j = hyp_idx - lo_val;

            if hyp_idx == 0 {
                row[local_j] = ref_idx;
                continue;
            }

            // SAFETY: Diagonal neighbor is always within the band when band = dist,
            // since the band width equals the maximum possible off-diagonal
            // displacement in an optimal alignment.
            let diag = rows[ref_idx - 1][hyp_idx - 1 - prev_lo];

            let up = if hyp_idx >= prev_lo && hyp_idx <= prev_hi {
                Some(rows[ref_idx - 1][hyp_idx - prev_lo] + 1)
            } else {
                None
            };

            let left = if hyp_idx > lo_val {
                Some(row[local_j - 1] + 1)
            } else {
                None
            };

            let cost = usize::from(reference[ref_idx - 1] != hypothesis[hyp_idx - 1]);
            let diag_val = diag + cost;

            row[local_j] = up
                .into_iter()
                .chain(left)
                .chain(Some(diag_val))
                .min()
                .unwrap_or(ref_idx + hyp_idx);
        }

        rows.push(row);
    }

    rows
}

/// Backtrack through the banded DP table to reconstruct the alignment.
fn backtrack_banded<S: AsRef<str> + PartialEq>(
    reference: &[S],
    hypothesis: &[S],
    ref_len: usize,
    hyp_len: usize,
    rows: &[Vec<usize>],
    lo: &dyn Fn(usize) -> usize,
    hi: &dyn Fn(usize) -> usize,
) -> Vec<EditOp> {
    let mut ops = Vec::with_capacity(ref_len + hyp_len);
    let (mut ref_pos, mut hyp_pos) = (ref_len, hyp_len);

    while ref_pos > 0 || hyp_pos > 0 {
        let lo_val = lo(ref_pos);
        // The optimal alignment path is always within the band when band = dist,
        // so hyp_pos is guaranteed to be within [lo_val, hi(ref_pos)].
        let cv = rows[ref_pos][hyp_pos - lo_val];

        if ref_pos > 0 && hyp_pos > 0 && reference[ref_pos - 1] == hypothesis[hyp_pos - 1] {
            ops.push(EditOp::Equal { index: ref_pos - 1 });
            ref_pos -= 1;
            hyp_pos -= 1;
        } else {
            let prev_lo = lo(ref_pos.saturating_sub(1));
            let prev_hi = if ref_pos > 0 { hi(ref_pos - 1) } else { 0 };

            let diag_ok = ref_pos > 0
                && hyp_pos > 0
                && hyp_pos > prev_lo
                && hyp_pos - 1 <= prev_hi
                && cv == rows[ref_pos - 1][hyp_pos - 1 - prev_lo] + 1;
            let left_ok = hyp_pos > lo_val && cv == rows[ref_pos][hyp_pos - 1 - lo_val] + 1;

            if diag_ok {
                ops.push(EditOp::Substitute {
                    ref_index: ref_pos - 1,
                    hyp_index: hyp_pos - 1,
                });
                ref_pos -= 1;
                hyp_pos -= 1;
            } else if left_ok {
                ops.push(EditOp::Insert {
                    hyp_index: hyp_pos - 1,
                });
                hyp_pos -= 1;
            } else {
                ops.push(EditOp::Delete {
                    ref_index: ref_pos - 1,
                });
                ref_pos -= 1;
            }
        }
    }
    ops.reverse();
    ops
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn equal_operation() {
        let op = EditOp::Equal { index: 0 };
        assert!(op.is_equal());
        assert!(!op.is_error());
    }

    #[test]
    fn equal_operation_not_substitute_or_insert_or_delete() {
        let op = EditOp::Equal { index: 0 };
        assert!(!op.is_substitute());
        assert!(!op.is_insert());
        assert!(!op.is_delete());
    }

    #[test]
    fn substitute_operation() {
        let op = EditOp::Substitute {
            ref_index: 0,
            hyp_index: 0,
        };
        assert!(!op.is_equal());
        assert!(op.is_error());
        assert!(op.is_substitute());
        assert!(!op.is_insert());
        assert!(!op.is_delete());
    }

    #[test]
    fn insert_operation() {
        let op = EditOp::Insert { hyp_index: 0 };
        assert!(op.is_error());
        assert!(op.is_insert());
        assert!(!op.is_substitute());
        assert!(!op.is_delete());
    }

    #[test]
    fn delete_operation() {
        let op = EditOp::Delete { ref_index: 0 };
        assert!(op.is_error());
        assert!(op.is_delete());
        assert!(!op.is_substitute());
        assert!(!op.is_insert());
    }

    #[test]
    fn align_identical_sequences() {
        let ref_tokens = vec!["hello", "world"];
        let hyp_tokens = vec!["hello", "world"];
        let ops = align(&ref_tokens, &hyp_tokens);
        assert_eq!(ops.len(), 2);
        assert!(ops.iter().all(EditOp::is_equal));
    }

    #[test]
    fn align_empty_sequences() {
        let ops = align::<&str>(&[], &[]);
        assert!(ops.is_empty());
    }

    #[test]
    fn align_empty_reference() {
        let ref_tokens: Vec<&str> = vec![];
        let hyp_tokens = vec!["hello"];
        let ops = align(&ref_tokens, &hyp_tokens);
        assert_eq!(ops.len(), 1);
        assert!(ops[0].is_insert());
        assert_eq!(ops[0], EditOp::Insert { hyp_index: 0 });
    }

    #[test]
    fn align_empty_reference_multiple() {
        let ref_tokens: Vec<&str> = vec![];
        let hyp_tokens = vec!["hello", "world"];
        let ops = align(&ref_tokens, &hyp_tokens);
        assert_eq!(ops.len(), 2);
        assert!(ops[0].is_insert());
        assert!(ops[1].is_insert());
    }

    #[test]
    fn align_empty_hypothesis() {
        let ref_tokens = vec!["hello"];
        let hyp_tokens: Vec<&str> = vec![];
        let ops = align(&ref_tokens, &hyp_tokens);
        assert_eq!(ops.len(), 1);
        assert!(ops[0].is_delete());
        assert_eq!(ops[0], EditOp::Delete { ref_index: 0 });
    }

    #[test]
    fn align_empty_hypothesis_multiple() {
        let ref_tokens = vec!["hello", "world"];
        let hyp_tokens: Vec<&str> = vec![];
        let ops = align(&ref_tokens, &hyp_tokens);
        assert_eq!(ops.len(), 2);
        assert!(ops[0].is_delete());
        assert!(ops[1].is_delete());
    }

    #[test]
    fn align_with_substitution() {
        let ref_tokens = vec!["hello", "world"];
        let hyp_tokens = vec!["hello", "earth"];
        let ops = align(&ref_tokens, &hyp_tokens);
        assert_eq!(ops.len(), 2);
        assert!(ops[0].is_equal());
        assert!(ops[1].is_substitute());
        assert_eq!(
            ops[1],
            EditOp::Substitute {
                ref_index: 1,
                hyp_index: 1
            }
        );
    }

    #[test]
    fn align_with_deletion() {
        let ref_tokens = vec!["hello", "world", "foo"];
        let hyp_tokens = vec!["hello", "foo"];
        let ops = align(&ref_tokens, &hyp_tokens);
        assert_eq!(ops.len(), 3);
        assert!(ops[0].is_equal());
        assert!(ops[1].is_delete());
        assert!(ops[2].is_equal());
    }

    #[test]
    fn align_with_insertion() {
        let ref_tokens = vec!["hello", "foo"];
        let hyp_tokens = vec!["hello", "world", "foo"];
        let ops = align(&ref_tokens, &hyp_tokens);
        assert_eq!(ops.len(), 3);
        assert!(ops[0].is_equal());
        assert!(ops[1].is_insert());
        assert!(ops[2].is_equal());
    }

    #[test]
    fn align_complex_case() {
        let ref_tokens = vec!["the", "cat", "sat", "on", "the", "mat"];
        let hyp_tokens = vec!["the", "cat", "on", "the", "mat"];
        let ops = align(&ref_tokens, &hyp_tokens);
        let errors: Vec<_> = ops.iter().filter(|op| op.is_error()).collect();
        assert_eq!(errors.len(), 1);
        assert!(errors[0].is_delete());
    }

    #[test]
    fn align_multiple_substitutions() {
        let ref_tokens = vec!["a", "b", "c"];
        let hyp_tokens = vec!["x", "y", "z"];
        let ops = align(&ref_tokens, &hyp_tokens);
        assert_eq!(ops.len(), 3);
        assert!(ops.iter().all(EditOp::is_substitute));
    }

    #[test]
    fn align_mixed_operations() {
        let ref_tokens = vec!["a", "b", "c", "d"];
        let hyp_tokens = vec!["a", "x", "c", "d", "e"];
        let ops = align(&ref_tokens, &hyp_tokens);
        assert_eq!(ops.len(), 5);
        assert!(ops[0].is_equal());
        assert!(ops[1].is_substitute());
        assert!(ops[2].is_equal());
        assert!(ops[3].is_equal());
        assert!(ops[4].is_insert());
    }

    #[test]
    fn alignment_counts() {
        let ref_tokens = vec!["a", "b", "c"];
        let hyp_tokens = vec!["a", "x", "c", "d"];
        let ops = align(&ref_tokens, &hyp_tokens);
        let counts = count_operations(&ops);
        assert_eq!(counts.hits, 2);
        assert_eq!(counts.substitutions, 1);
        assert_eq!(counts.deletions, 0);
        assert_eq!(counts.insertions, 1);
    }

    #[test]
    fn alignment_counts_empty() {
        let ops: Vec<EditOp> = vec![];
        let counts = count_operations(&ops);
        assert_eq!(counts.hits, 0);
        assert_eq!(counts.substitutions, 0);
        assert_eq!(counts.deletions, 0);
        assert_eq!(counts.insertions, 0);
    }

    #[test]
    fn alignment_counts_all_equal() {
        let ref_tokens = vec!["a", "b", "c"];
        let hyp_tokens = vec!["a", "b", "c"];
        let ops = align(&ref_tokens, &hyp_tokens);
        let counts = count_operations(&ops);
        assert_eq!(counts.hits, 3);
        assert_eq!(counts.substitutions, 0);
        assert_eq!(counts.deletions, 0);
        assert_eq!(counts.insertions, 0);
    }

    #[test]
    fn alignment_counts_all_insertions() {
        let ref_tokens: Vec<&str> = vec![];
        let hyp_tokens = vec!["a", "b"];
        let ops = align(&ref_tokens, &hyp_tokens);
        let counts = count_operations(&ops);
        assert_eq!(counts.hits, 0);
        assert_eq!(counts.insertions, 2);
    }

    #[test]
    fn alignment_counts_all_deletions() {
        let ref_tokens = vec!["a", "b"];
        let hyp_tokens: Vec<&str> = vec![];
        let ops = align(&ref_tokens, &hyp_tokens);
        let counts = count_operations(&ops);
        assert_eq!(counts.hits, 0);
        assert_eq!(counts.deletions, 2);
    }

    #[test]
    fn alignment_counts_all_substitutions() {
        let ref_tokens = vec!["a", "b"];
        let hyp_tokens = vec!["x", "y"];
        let ops = align(&ref_tokens, &hyp_tokens);
        let counts = count_operations(&ops);
        assert_eq!(counts.hits, 0);
        assert_eq!(counts.substitutions, 2);
    }

    #[test]
    fn operation_counts_default() {
        let counts = OperationCounts::default();
        assert_eq!(counts.hits, 0);
        assert_eq!(counts.substitutions, 0);
        assert_eq!(counts.deletions, 0);
        assert_eq!(counts.insertions, 0);
    }

    #[test]
    fn edit_op_equality() {
        let op1 = EditOp::Equal { index: 5 };
        let op2 = EditOp::Equal { index: 5 };
        assert_eq!(op1, op2);
    }

    #[test]
    fn edit_op_inequality() {
        let op1 = EditOp::Equal { index: 0 };
        let op2 = EditOp::Equal { index: 1 };
        assert_ne!(op1, op2);
    }

    #[test]
    fn edit_op_clone() {
        let op = EditOp::Substitute {
            ref_index: 3,
            hyp_index: 4,
        };
        let cloned = op.clone();
        assert_eq!(op, cloned);
    }

    #[test]
    fn align_with_string_types() {
        let ref_tokens = vec![String::from("hello"), String::from("world")];
        let hyp_tokens = vec![String::from("hello"), String::from("world")];
        let ops = align(&ref_tokens, &hyp_tokens);
        assert_eq!(ops.len(), 2);
        assert!(ops.iter().all(EditOp::is_equal));
    }

    // --- New tests for banded alignment ---

    #[test]
    fn edit_distance_basic() {
        let ref_tokens = vec!["hello", "world"];
        let hyp_tokens = vec!["hello", "earth"];
        assert_eq!(edit_distance(&ref_tokens, &hyp_tokens), 1);
    }

    #[test]
    fn edit_distance_identical() {
        let ref_tokens = vec!["a", "b", "c"];
        assert_eq!(edit_distance(&ref_tokens, &ref_tokens), 0);
    }

    #[test]
    fn edit_distance_empty() {
        assert_eq!(edit_distance::<&str>(&[], &[]), 0);
        assert_eq!(edit_distance::<&str>(&[], &["a"]), 1);
        assert_eq!(edit_distance::<&str>(&["a"], &[]), 1);
    }

    #[test]
    fn align_large_banded() {
        // Test with enough tokens that banded path is taken
        let ref_tokens: Vec<String> = (0..100).map(|i| format!("word{i}")).collect();
        let mut hyp_tokens = ref_tokens.clone();
        hyp_tokens[50] = "changed".to_string();
        let ops = align(&ref_tokens, &hyp_tokens);
        let counts = count_operations(&ops);
        assert_eq!(counts.hits, 99);
        assert_eq!(counts.substitutions, 1);
    }

    #[test]
    fn align_banded_many_deletions() {
        // ref much longer than hyp — exercises deletion-heavy banded path
        // and the diag=None / cur_val=None branches at band edges
        let ref_tokens: Vec<String> = (0..50).map(|i| format!("w{i}")).collect();
        let hyp_tokens: Vec<String> = (0..25).map(|i| format!("w{i}")).collect();
        let ops = align(&ref_tokens, &hyp_tokens);
        let counts = count_operations(&ops);
        assert_eq!(counts.hits, 25);
        assert_eq!(counts.deletions, 25);
        assert_eq!(counts.insertions, 0);
        assert_eq!(counts.substitutions, 0);
    }

    #[test]
    fn align_banded_many_insertions() {
        // hyp much longer than ref — exercises insertion-heavy banded path
        let ref_tokens: Vec<String> = (0..25).map(|i| format!("w{i}")).collect();
        let hyp_tokens: Vec<String> = (0..50).map(|i| format!("w{i}")).collect();
        let ops = align(&ref_tokens, &hyp_tokens);
        let counts = count_operations(&ops);
        assert_eq!(counts.hits, 25);
        assert_eq!(counts.insertions, 25);
        assert_eq!(counts.deletions, 0);
        assert_eq!(counts.substitutions, 0);
    }

    #[test]
    fn align_banded_deletions_at_start() {
        // Deletions at the start of reference
        let ref_tokens: Vec<&str> = vec!["a", "b", "c", "d"];
        let hyp_tokens: Vec<&str> = vec!["c", "d"];
        let ops = align(&ref_tokens, &hyp_tokens);
        let counts = count_operations(&ops);
        assert_eq!(counts.hits, 2);
        assert_eq!(counts.deletions, 2);
    }

    #[test]
    fn align_banded_insertions_at_end() {
        // Insertions at the end of hypothesis
        let ref_tokens: Vec<&str> = vec!["a", "b"];
        let hyp_tokens: Vec<&str> = vec!["a", "b", "c", "d"];
        let ops = align(&ref_tokens, &hyp_tokens);
        let counts = count_operations(&ops);
        assert_eq!(counts.hits, 2);
        assert_eq!(counts.insertions, 2);
    }

    #[test]
    fn align_banded_long_with_offset_substitution() {
        // Substitution far from diagonal — exercises band boundary branches
        let ref_tokens: Vec<String> = (0..200)
            .map(|i| {
                if i == 180 {
                    "wrong".to_string()
                } else {
                    format!("w{i}")
                }
            })
            .collect();
        let hyp_tokens: Vec<String> = (0..200).map(|i| format!("w{i}")).collect();
        let ops = align(&ref_tokens, &hyp_tokens);
        let counts = count_operations(&ops);
        assert_eq!(counts.hits, 199);
        assert_eq!(counts.substitutions, 1);
    }

    #[test]
    fn align_banded_mixed_operations_long() {
        // Long sequence with mixed ops to exercise all banded branches
        let ref_tokens: Vec<String> = (0..200)
            .map(|i| {
                if i == 100 {
                    "changed".to_string()
                } else {
                    format!("w{i}")
                }
            })
            .collect();
        let mut hyp_tokens: Vec<String> = (0..200).map(|i| format!("w{i}")).collect();
        hyp_tokens.insert(150, "extra".to_string());
        let ops = align(&ref_tokens, &hyp_tokens);
        let counts = count_operations(&ops);
        assert_eq!(counts.substitutions, 1);
        assert_eq!(counts.insertions, 1);
        assert_eq!(counts.hits, 199);
    }

    #[test]
    fn edit_distance_with_mixed_operations() {
        let ref_tokens = vec!["a", "b", "c", "d", "e"];
        let hyp_tokens = vec!["a", "x", "c", "e"];
        assert_eq!(edit_distance(&ref_tokens, &hyp_tokens), 2);
    }

    #[test]
    fn rapidfuzz_char_distance_identical() {
        assert_eq!(rapidfuzz_char_distance("hello".chars(), "hello".chars()), 0);
    }

    #[test]
    fn rapidfuzz_char_distance_substitution() {
        assert_eq!(rapidfuzz_char_distance("hello".chars(), "hallo".chars()), 1);
    }

    #[test]
    fn rapidfuzz_char_distance_empty_both() {
        assert_eq!(rapidfuzz_char_distance("".chars(), "".chars()), 0);
    }

    #[test]
    fn rapidfuzz_char_distance_empty_one() {
        assert_eq!(rapidfuzz_char_distance("abc".chars(), "".chars()), 3);
        assert_eq!(rapidfuzz_char_distance("".chars(), "abc".chars()), 3);
    }

    #[test]
    fn rapidfuzz_char_distance_all_different() {
        assert_eq!(rapidfuzz_char_distance("abc".chars(), "xyz".chars()), 3);
    }

    #[test]
    fn rapidfuzz_char_distance_unicode() {
        assert_eq!(rapidfuzz_char_distance("你好".chars(), "你好".chars()), 0);
        assert_eq!(rapidfuzz_char_distance("你好".chars(), "你们".chars()), 1);
    }

    #[test]
    fn rapidfuzz_char_distance_insertion() {
        assert_eq!(rapidfuzz_char_distance("ac".chars(), "abc".chars()), 1);
    }

    #[test]
    fn rapidfuzz_char_distance_deletion() {
        assert_eq!(rapidfuzz_char_distance("abc".chars(), "ac".chars()), 1);
    }
}