liblevenshtein 0.9.1

Levenshtein/Universal Automata for approximate string matching using various dictionary backends
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
//! Memoized caching for repeated NFA/DFA queries.
//!
//! This module provides caching infrastructure for fuzzy regex queries,
//! particularly useful when querying the same patterns repeatedly with
//! similar inputs.
//!
//! # Use Cases
//!
//! - **Spell checking**: Same words queried multiple times
//! - **Autocomplete**: Prefix queries with overlapping inputs
//! - **Search**: Repeated queries in interactive sessions
//!
//! # Design
//!
//! The cache uses LRU (Least Recently Used) eviction when the cache
//! reaches its maximum size. Cache keys are (query_string, max_distance)
//! pairs, and values are the matching results.
//!
//! # Examples
//!
//! ```ignore
//! use liblevenshtein::phonetic::nfa::{MemoizedMatcherChar, ProductAutomatonChar};
//!
//! let product = ProductAutomatonChar::new(nfa, 2);
//! let mut cache = MemoizedMatcherChar::new(product, 1000);
//!
//! // First query computes result
//! let result1 = cache.accepts("phone");
//!
//! // Second query uses cached result
//! let result2 = cache.accepts("phone");
//! assert_eq!(result1, result2);
//! ```

use super::lazy_dfa::{LazyDFA, LazyDFAChar};
use super::product::{ProductAutomaton, ProductAutomatonChar};
use rustc_hash::FxHashMap;
use std::collections::VecDeque;

// ============================================================================
// Character-level Memoized Matcher
// ============================================================================

/// Cache entry for memoized results.
#[derive(Debug, Clone)]
struct CacheEntryChar {
    /// The cached result
    result: bool,
    /// Minimum distance (if computed)
    min_distance: Option<u8>,
}

/// Memoized matcher for character-level fuzzy regex.
///
/// Wraps a `ProductAutomatonChar` with a caching layer for efficient
/// repeated queries.
#[derive(Debug)]
pub struct MemoizedMatcherChar {
    /// The underlying product automaton
    product: ProductAutomatonChar,
    /// Cache: query -> result
    cache: FxHashMap<String, CacheEntryChar>,
    /// LRU order for eviction
    lru_order: VecDeque<String>,
    /// Maximum cache size
    max_cache_size: usize,
    /// Cache hit count
    hits: usize,
    /// Cache miss count
    misses: usize,
}

impl MemoizedMatcherChar {
    /// Create a new memoized matcher with the given cache size.
    pub fn new(product: ProductAutomatonChar, max_cache_size: usize) -> Self {
        Self {
            product,
            cache: FxHashMap::default(),
            lru_order: VecDeque::new(),
            max_cache_size,
            hits: 0,
            misses: 0,
        }
    }

    /// Check if input is accepted, using cache if available.
    pub fn accepts(&mut self, input: &str) -> bool {
        let key = input.to_string();

        // Check cache - get result first, then update LRU
        if let Some(entry) = self.cache.get(&key).cloned() {
            self.hits += 1;
            self.update_lru(&key);
            return entry.result;
        }

        // Cache miss - compute result
        self.misses += 1;
        let result = self.product.accepts(input);

        // Store in cache
        self.insert_cache(
            key,
            CacheEntryChar {
                result,
                min_distance: None,
            },
        );

        result
    }

    /// Get minimum distance, using cache if available.
    pub fn min_distance(&mut self, input: &str) -> Option<u8> {
        let key = input.to_string();

        // Check cache - clone to release borrow
        if let Some(entry) = self.cache.get(&key).cloned() {
            if entry.min_distance.is_some() {
                self.hits += 1;
                self.update_lru(&key);
                return entry.min_distance;
            }
        }

        // Compute min distance
        self.misses += 1;
        let min_dist = self.product.min_distance(input);
        let result = min_dist.is_some();

        // Update cache
        self.insert_cache(
            key,
            CacheEntryChar {
                result,
                min_distance: min_dist,
            },
        );

        min_dist
    }

    /// Update LRU order for a key.
    fn update_lru(&mut self, key: &str) {
        // Remove from current position and add to front
        if let Some(pos) = self.lru_order.iter().position(|k| k == key) {
            self.lru_order.remove(pos);
        }
        self.lru_order.push_front(key.to_string());
    }

    /// Insert into cache with LRU eviction.
    fn insert_cache(&mut self, key: String, entry: CacheEntryChar) {
        // Evict if at capacity
        while self.cache.len() >= self.max_cache_size && !self.lru_order.is_empty() {
            if let Some(evict_key) = self.lru_order.pop_back() {
                self.cache.remove(&evict_key);
            }
        }

        // Insert new entry
        self.cache.insert(key.clone(), entry);
        self.lru_order.push_front(key);
    }

    /// Get cache statistics.
    pub fn stats(&self) -> MemoizedStats {
        MemoizedStats {
            size: self.cache.len(),
            max_size: self.max_cache_size,
            hits: self.hits,
            misses: self.misses,
            hit_rate: if self.hits + self.misses > 0 {
                self.hits as f64 / (self.hits + self.misses) as f64
            } else {
                0.0
            },
        }
    }

    /// Clear the cache.
    pub fn clear(&mut self) {
        self.cache.clear();
        self.lru_order.clear();
        self.hits = 0;
        self.misses = 0;
    }

    /// Get the underlying product automaton.
    pub fn product(&self) -> &ProductAutomatonChar {
        &self.product
    }
}

// ============================================================================
// Byte-level Memoized Matcher
// ============================================================================

/// Cache entry for byte-level results.
#[derive(Debug, Clone)]
struct CacheEntry {
    result: bool,
    min_distance: Option<u8>,
}

/// Memoized matcher for byte-level fuzzy regex.
#[derive(Debug)]
pub struct MemoizedMatcher {
    product: ProductAutomaton,
    cache: FxHashMap<Vec<u8>, CacheEntry>,
    lru_order: VecDeque<Vec<u8>>,
    max_cache_size: usize,
    hits: usize,
    misses: usize,
}

impl MemoizedMatcher {
    /// Create a new memoized matcher.
    pub fn new(product: ProductAutomaton, max_cache_size: usize) -> Self {
        Self {
            product,
            cache: FxHashMap::default(),
            lru_order: VecDeque::new(),
            max_cache_size,
            hits: 0,
            misses: 0,
        }
    }

    /// Check if input is accepted.
    pub fn accepts(&mut self, input: &[u8]) -> bool {
        let key = input.to_vec();

        if let Some(entry) = self.cache.get(&key).cloned() {
            self.hits += 1;
            self.update_lru(&key);
            return entry.result;
        }

        self.misses += 1;
        let result = self.product.accepts(input);

        self.insert_cache(
            key,
            CacheEntry {
                result,
                min_distance: None,
            },
        );

        result
    }

    /// Get minimum distance.
    pub fn min_distance(&mut self, input: &[u8]) -> Option<u8> {
        let key = input.to_vec();

        if let Some(entry) = self.cache.get(&key).cloned() {
            if entry.min_distance.is_some() {
                self.hits += 1;
                self.update_lru(&key);
                return entry.min_distance;
            }
        }

        self.misses += 1;
        let min_dist = self.product.min_distance(input);
        let result = min_dist.is_some();

        self.insert_cache(
            key,
            CacheEntry {
                result,
                min_distance: min_dist,
            },
        );

        min_dist
    }

    fn update_lru(&mut self, key: &[u8]) {
        if let Some(pos) = self.lru_order.iter().position(|k| k == key) {
            self.lru_order.remove(pos);
        }
        self.lru_order.push_front(key.to_vec());
    }

    fn insert_cache(&mut self, key: Vec<u8>, entry: CacheEntry) {
        while self.cache.len() >= self.max_cache_size && !self.lru_order.is_empty() {
            if let Some(evict_key) = self.lru_order.pop_back() {
                self.cache.remove(&evict_key);
            }
        }

        self.cache.insert(key.clone(), entry);
        self.lru_order.push_front(key);
    }

    /// Get cache statistics.
    pub fn stats(&self) -> MemoizedStats {
        MemoizedStats {
            size: self.cache.len(),
            max_size: self.max_cache_size,
            hits: self.hits,
            misses: self.misses,
            hit_rate: if self.hits + self.misses > 0 {
                self.hits as f64 / (self.hits + self.misses) as f64
            } else {
                0.0
            },
        }
    }

    /// Clear the cache.
    pub fn clear(&mut self) {
        self.cache.clear();
        self.lru_order.clear();
        self.hits = 0;
        self.misses = 0;
    }

    /// Get the underlying product automaton.
    pub fn product(&self) -> &ProductAutomaton {
        &self.product
    }
}

// ============================================================================
// Memoized Lazy DFA
// ============================================================================

/// Memoized wrapper for character-level lazy DFA.
///
/// Caches complete accept/reject decisions for strings.
#[derive(Debug)]
pub struct MemoizedLazyDFAChar {
    dfa: LazyDFAChar,
    result_cache: FxHashMap<String, bool>,
    lru_order: VecDeque<String>,
    max_cache_size: usize,
    hits: usize,
    misses: usize,
}

impl MemoizedLazyDFAChar {
    /// Create a new memoized lazy DFA.
    pub fn new(dfa: LazyDFAChar, max_cache_size: usize) -> Self {
        Self {
            dfa,
            result_cache: FxHashMap::default(),
            lru_order: VecDeque::new(),
            max_cache_size,
            hits: 0,
            misses: 0,
        }
    }

    /// Check if input is accepted.
    pub fn accepts(&mut self, input: &str) -> bool {
        let key = input.to_string();

        if let Some(&result) = self.result_cache.get(&key) {
            self.hits += 1;
            self.update_lru(&key);
            return result;
        }

        self.misses += 1;
        let result = self.dfa.accepts(input);

        self.insert_cache(key, result);
        result
    }

    fn update_lru(&mut self, key: &str) {
        if let Some(pos) = self.lru_order.iter().position(|k| k == key) {
            self.lru_order.remove(pos);
        }
        self.lru_order.push_front(key.to_string());
    }

    fn insert_cache(&mut self, key: String, result: bool) {
        while self.result_cache.len() >= self.max_cache_size && !self.lru_order.is_empty() {
            if let Some(evict_key) = self.lru_order.pop_back() {
                self.result_cache.remove(&evict_key);
            }
        }

        self.result_cache.insert(key.clone(), result);
        self.lru_order.push_front(key);
    }

    /// Get cache statistics.
    pub fn stats(&self) -> MemoizedStats {
        MemoizedStats {
            size: self.result_cache.len(),
            max_size: self.max_cache_size,
            hits: self.hits,
            misses: self.misses,
            hit_rate: if self.hits + self.misses > 0 {
                self.hits as f64 / (self.hits + self.misses) as f64
            } else {
                0.0
            },
        }
    }

    /// Clear all caches (both result cache and DFA transition cache).
    pub fn clear(&mut self) {
        self.result_cache.clear();
        self.lru_order.clear();
        self.dfa.clear_cache();
        self.hits = 0;
        self.misses = 0;
    }

    /// Get the underlying lazy DFA.
    pub fn dfa(&self) -> &LazyDFAChar {
        &self.dfa
    }

    /// Get mutable access to the underlying lazy DFA.
    pub fn dfa_mut(&mut self) -> &mut LazyDFAChar {
        &mut self.dfa
    }
}

/// Memoized wrapper for byte-level lazy DFA.
#[derive(Debug)]
pub struct MemoizedLazyDFA {
    dfa: LazyDFA,
    result_cache: FxHashMap<Vec<u8>, bool>,
    lru_order: VecDeque<Vec<u8>>,
    max_cache_size: usize,
    hits: usize,
    misses: usize,
}

impl MemoizedLazyDFA {
    /// Create a new memoized lazy DFA.
    pub fn new(dfa: LazyDFA, max_cache_size: usize) -> Self {
        Self {
            dfa,
            result_cache: FxHashMap::default(),
            lru_order: VecDeque::new(),
            max_cache_size,
            hits: 0,
            misses: 0,
        }
    }

    /// Check if input is accepted.
    pub fn accepts(&mut self, input: &[u8]) -> bool {
        let key = input.to_vec();

        if let Some(&result) = self.result_cache.get(&key) {
            self.hits += 1;
            self.update_lru(&key);
            return result;
        }

        self.misses += 1;
        let result = self.dfa.accepts(input);

        self.insert_cache(key, result);
        result
    }

    fn update_lru(&mut self, key: &[u8]) {
        if let Some(pos) = self.lru_order.iter().position(|k| k == key) {
            self.lru_order.remove(pos);
        }
        self.lru_order.push_front(key.to_vec());
    }

    fn insert_cache(&mut self, key: Vec<u8>, result: bool) {
        while self.result_cache.len() >= self.max_cache_size && !self.lru_order.is_empty() {
            if let Some(evict_key) = self.lru_order.pop_back() {
                self.result_cache.remove(&evict_key);
            }
        }

        self.result_cache.insert(key.clone(), result);
        self.lru_order.push_front(key);
    }

    /// Get cache statistics.
    pub fn stats(&self) -> MemoizedStats {
        MemoizedStats {
            size: self.result_cache.len(),
            max_size: self.max_cache_size,
            hits: self.hits,
            misses: self.misses,
            hit_rate: if self.hits + self.misses > 0 {
                self.hits as f64 / (self.hits + self.misses) as f64
            } else {
                0.0
            },
        }
    }

    /// Clear all caches.
    pub fn clear(&mut self) {
        self.result_cache.clear();
        self.lru_order.clear();
        self.dfa.clear_cache();
        self.hits = 0;
        self.misses = 0;
    }

    /// Get the underlying lazy DFA.
    pub fn dfa(&self) -> &LazyDFA {
        &self.dfa
    }

    /// Get mutable access to the underlying lazy DFA.
    pub fn dfa_mut(&mut self) -> &mut LazyDFA {
        &mut self.dfa
    }
}

// ============================================================================
// Statistics
// ============================================================================

/// Statistics for memoized caches.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct MemoizedStats {
    /// Current cache size
    pub size: usize,
    /// Maximum cache size
    pub max_size: usize,
    /// Number of cache hits
    pub hits: usize,
    /// Number of cache misses
    pub misses: usize,
    /// Hit rate (0.0 to 1.0)
    pub hit_rate: f64,
}

// ============================================================================
// Tests
// ============================================================================

#[cfg(test)]
mod tests {
    use super::*;
    use crate::phonetic::nfa::compiler::{compile, compile_bytes};
    use crate::phonetic::regex::{parse, parse_bytes};

    #[test]
    fn test_memoized_matcher_accepts() {
        let nfa = compile(&parse("(ph|f)one").expect("test fixture: parse must be Ok"))
            .expect("test fixture: compile must be Ok");
        let product = ProductAutomatonChar::new(nfa, 1);
        let mut cache = MemoizedMatcherChar::new(product, 100);

        // First query - miss
        assert!(cache.accepts("phone"));
        let stats = cache.stats();
        assert_eq!(stats.misses, 1);
        assert_eq!(stats.hits, 0);

        // Second query - hit
        assert!(cache.accepts("phone"));
        let stats = cache.stats();
        assert_eq!(stats.misses, 1);
        assert_eq!(stats.hits, 1);
        assert!(stats.hit_rate > 0.4); // ~50%
    }

    #[test]
    fn test_memoized_matcher_min_distance() {
        let nfa = compile(&parse("phone").expect("test fixture: parse must be Ok"))
            .expect("test fixture: compile must be Ok");
        let product = ProductAutomatonChar::new(nfa, 2);
        let mut cache = MemoizedMatcherChar::new(product, 100);

        assert_eq!(cache.min_distance("phone"), Some(0));
        assert_eq!(cache.min_distance("phon"), Some(1));

        // Second query should hit
        assert_eq!(cache.min_distance("phone"), Some(0));
        let stats = cache.stats();
        assert!(stats.hits >= 1);
    }

    #[test]
    fn test_memoized_matcher_lru_eviction() {
        let nfa = compile(&parse("test").expect("test fixture: parse must be Ok"))
            .expect("test fixture: compile must be Ok");
        let product = ProductAutomatonChar::new(nfa, 1);
        let mut cache = MemoizedMatcherChar::new(product, 3);

        // Fill cache
        cache.accepts("a");
        cache.accepts("b");
        cache.accepts("c");
        assert_eq!(cache.stats().size, 3);

        // Add one more - should evict "a"
        cache.accepts("d");
        assert_eq!(cache.stats().size, 3);

        // "a" should be evicted, so this is a miss
        let hits_before = cache.stats().hits;
        cache.accepts("a");
        assert_eq!(cache.stats().hits, hits_before); // No new hit
    }

    #[test]
    fn test_memoized_matcher_clear() {
        let nfa = compile(&parse("test").expect("test fixture: parse must be Ok"))
            .expect("test fixture: compile must be Ok");
        let product = ProductAutomatonChar::new(nfa, 1);
        let mut cache = MemoizedMatcherChar::new(product, 100);

        cache.accepts("a");
        cache.accepts("b");
        assert!(cache.stats().size > 0);

        cache.clear();
        let stats = cache.stats();
        assert_eq!(stats.size, 0);
        assert_eq!(stats.hits, 0);
        assert_eq!(stats.misses, 0);
    }

    #[test]
    fn test_memoized_lazy_dfa() {
        let nfa = compile(&parse("hello").expect("test fixture: parse must be Ok"))
            .expect("test fixture: compile must be Ok");
        let dfa = LazyDFAChar::new(nfa);
        let mut cache = MemoizedLazyDFAChar::new(dfa, 100);

        // First query - miss
        assert!(cache.accepts("hello"));
        assert_eq!(cache.stats().misses, 1);

        // Second query - hit
        assert!(cache.accepts("hello"));
        assert_eq!(cache.stats().hits, 1);
    }

    #[test]
    fn test_memoized_bytes() {
        let nfa = compile_bytes(&parse_bytes(b"test").expect("test fixture: parse must be Ok"))
            .expect("test fixture: compile must be Ok");
        let product = ProductAutomaton::new(nfa, 1);
        let mut cache = MemoizedMatcher::new(product, 100);

        assert!(cache.accepts(b"test"));
        assert!(cache.accepts(b"test")); // Hit
        assert_eq!(cache.stats().hits, 1);
    }

    #[test]
    fn test_memoized_lazy_dfa_bytes() {
        let nfa = compile_bytes(&parse_bytes(b"world").expect("test fixture: parse must be Ok"))
            .expect("test fixture: compile must be Ok");
        let dfa = LazyDFA::new(nfa);
        let mut cache = MemoizedLazyDFA::new(dfa, 100);

        assert!(cache.accepts(b"world"));
        assert!(cache.accepts(b"world")); // Hit
        assert_eq!(cache.stats().hits, 1);
    }

    #[test]
    fn test_hit_rate_calculation() {
        let nfa = compile(&parse("x").expect("test fixture: parse must be Ok"))
            .expect("test fixture: compile must be Ok");
        let product = ProductAutomatonChar::new(nfa, 0);
        let mut cache = MemoizedMatcherChar::new(product, 100);

        // 1 miss
        cache.accepts("a");
        // 3 hits
        cache.accepts("a");
        cache.accepts("a");
        cache.accepts("a");

        let stats = cache.stats();
        assert_eq!(stats.hits, 3);
        assert_eq!(stats.misses, 1);
        assert!((stats.hit_rate - 0.75).abs() < 0.001);
    }
}