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
//! Optimized LRU implementation demonstrating all optimization techniques.
//!
//! This module shows performance optimizations using feature flags:
//! - `eviction-parking-lot`: Use parking_lot::RwLock instead of std::sync::RwLock
//! - `eviction-dashmap`: Use DashMap for lock-free concurrent access
//! - `eviction-arc-str`: Use Arc<str> instead of String for keys
//! - `eviction-compact-metadata`: Compact metadata representation
//! - `eviction-coarse-timestamps`: Coarse-grained timestamps (reduce syscalls)

use libdictenstein::{
    Dictionary, DictionaryNode, DictionaryValue, MappedDictionary, MappedDictionaryNode,
    SyncStrategy,
};
use std::sync::Arc;

// Conditional imports based on feature flags
#[cfg(all(feature = "eviction-parking-lot", not(feature = "eviction-dashmap")))]
use crate::sync_compat::RwLock;
#[cfg(all(
    not(feature = "eviction-parking-lot"),
    not(feature = "eviction-dashmap")
))]
use std::sync::RwLock;

#[cfg(feature = "eviction-dashmap")]
use dashmap::DashMap;
#[cfg(not(feature = "eviction-dashmap"))]
use std::collections::HashMap;

#[cfg(feature = "eviction-coarse-timestamps")]
use std::sync::atomic::{AtomicU64, Ordering};
#[cfg(not(feature = "eviction-coarse-timestamps"))]
use std::time::Instant;

// Coarse timestamp management
#[cfg(feature = "eviction-coarse-timestamps")]
static COARSE_TIMESTAMP_MS: AtomicU64 = AtomicU64::new(0);

#[cfg(feature = "eviction-coarse-timestamps")]
pub(crate) fn init_coarse_timestamp_thread() {
    use std::thread;
    use std::time::{Duration, SystemTime, UNIX_EPOCH};

    thread::spawn(|| loop {
        let now_ms = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .expect("system clock predates UNIX epoch")
            .as_millis() as u64;
        COARSE_TIMESTAMP_MS.store(now_ms, Ordering::Relaxed);
        thread::sleep(Duration::from_millis(100));
    });
}

// Metadata representation
#[cfg(not(feature = "eviction-compact-metadata"))]
#[derive(Debug, Clone)]
struct EntryMetadata {
    #[cfg(not(feature = "eviction-coarse-timestamps"))]
    last_accessed: Instant,
    #[cfg(feature = "eviction-coarse-timestamps")]
    last_accessed_ms: u64,
}

#[cfg(feature = "eviction-compact-metadata")]
#[derive(Debug, Clone)]
#[repr(C)]
struct EntryMetadata {
    last_accessed_ms: u64,
}

impl EntryMetadata {
    fn new() -> Self {
        #[cfg(all(
            not(feature = "eviction-compact-metadata"),
            not(feature = "eviction-coarse-timestamps")
        ))]
        {
            Self {
                last_accessed: Instant::now(),
            }
        }

        #[cfg(all(
            not(feature = "eviction-compact-metadata"),
            feature = "eviction-coarse-timestamps"
        ))]
        {
            Self {
                last_accessed_ms: COARSE_TIMESTAMP_MS.load(Ordering::Relaxed),
            }
        }

        #[cfg(all(
            feature = "eviction-compact-metadata",
            not(feature = "eviction-coarse-timestamps")
        ))]
        {
            Self {
                last_accessed_ms: get_timestamp_ms(),
            }
        }

        #[cfg(all(
            feature = "eviction-compact-metadata",
            feature = "eviction-coarse-timestamps"
        ))]
        {
            Self {
                last_accessed_ms: COARSE_TIMESTAMP_MS.load(Ordering::Relaxed),
            }
        }
    }

    fn update_access(&mut self) {
        #[cfg(all(
            not(feature = "eviction-compact-metadata"),
            not(feature = "eviction-coarse-timestamps")
        ))]
        {
            self.last_accessed = Instant::now();
        }

        #[cfg(feature = "eviction-coarse-timestamps")]
        {
            self.last_accessed_ms = COARSE_TIMESTAMP_MS.load(Ordering::Relaxed);
        }

        #[cfg(all(
            feature = "eviction-compact-metadata",
            not(feature = "eviction-coarse-timestamps")
        ))]
        {
            self.last_accessed_ms = get_timestamp_ms();
        }
    }

    fn recency_score(&self) -> u64 {
        #[cfg(all(
            not(feature = "eviction-compact-metadata"),
            not(feature = "eviction-coarse-timestamps")
        ))]
        {
            self.last_accessed.elapsed().as_millis() as u64
        }

        #[cfg(feature = "eviction-coarse-timestamps")]
        {
            let now = COARSE_TIMESTAMP_MS.load(Ordering::Relaxed);
            now.saturating_sub(self.last_accessed_ms)
        }

        #[cfg(all(
            feature = "eviction-compact-metadata",
            not(feature = "eviction-coarse-timestamps")
        ))]
        {
            let now = get_timestamp_ms();
            now.saturating_sub(self.last_accessed_ms)
        }
    }
}

#[cfg(all(
    feature = "eviction-compact-metadata",
    not(feature = "eviction-coarse-timestamps")
))]
fn get_timestamp_ms() -> u64 {
    use std::time::{SystemTime, UNIX_EPOCH};
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .expect("system clock predates UNIX epoch")
        .as_millis() as u64
}

// Key type
#[cfg(feature = "eviction-arc-str")]
type MetadataKey = Arc<str>;
#[cfg(not(feature = "eviction-arc-str"))]
type MetadataKey = String;

#[cfg(feature = "eviction-arc-str")]
fn make_key(term: &str) -> MetadataKey {
    Arc::from(term)
}
#[cfg(not(feature = "eviction-arc-str"))]
fn make_key(term: &str) -> MetadataKey {
    term.to_string()
}

// Storage type
#[cfg(feature = "eviction-dashmap")]
type MetadataStorage = Arc<DashMap<MetadataKey, EntryMetadata>>;
#[cfg(not(feature = "eviction-dashmap"))]
type MetadataStorage = Arc<RwLock<HashMap<MetadataKey, EntryMetadata>>>;

/// Optimized LRU wrapper with conditional optimizations.
#[derive(Clone)]
pub struct LruOptimized<D> {
    inner: D,
    metadata: MetadataStorage,
}

impl<D> LruOptimized<D> {
    /// Creates a new LRU-optimized wrapper around the given dictionary.
    ///
    /// # Arguments
    ///
    /// * `dict` - The dictionary to wrap with LRU tracking
    ///
    /// # Returns
    ///
    /// A new `LruOptimized` instance
    pub fn new(dict: D) -> Self {
        #[cfg(feature = "eviction-coarse-timestamps")]
        {
            static TIMESTAMP_THREAD_INIT: std::sync::Once = std::sync::Once::new();
            TIMESTAMP_THREAD_INIT.call_once(|| {
                init_coarse_timestamp_thread();
            });
        }

        Self {
            inner: dict,
            #[cfg(feature = "eviction-dashmap")]
            metadata: Arc::new(DashMap::new()),
            #[cfg(not(feature = "eviction-dashmap"))]
            metadata: Arc::new(RwLock::new(HashMap::new())),
        }
    }

    /// Consumes the wrapper and returns the inner dictionary.
    ///
    /// # Returns
    ///
    /// The wrapped dictionary
    #[inline]
    pub fn into_inner(self) -> D {
        self.inner
    }

    /// Returns a reference to the inner dictionary.
    ///
    /// # Returns
    ///
    /// Reference to the wrapped dictionary
    #[inline]
    pub fn inner(&self) -> &D {
        &self.inner
    }

    fn record_access(&self, term: &str) {
        #[cfg(feature = "eviction-dashmap")]
        {
            self.metadata
                .entry(make_key(term))
                .and_modify(|m| m.update_access())
                .or_insert_with(EntryMetadata::new);
        }

        #[cfg(not(feature = "eviction-dashmap"))]
        {
            #[cfg(feature = "eviction-parking-lot")]
            let mut metadata = self.metadata.write();
            #[cfg(not(feature = "eviction-parking-lot"))]
            let mut metadata = self
                .metadata
                .write()
                .expect("poisoned RwLock; only fatal if writer panicked");

            metadata
                .entry(make_key(term))
                .and_modify(|m| m.update_access())
                .or_insert_with(EntryMetadata::new);
        }
    }

    /// Gets the recency score for a term (lower is more recent).
    ///
    /// # Arguments
    ///
    /// * `term` - The term to query
    ///
    /// # Returns
    ///
    /// The recency score if the term exists, `None` otherwise
    pub fn recency(&self, term: &str) -> Option<u64> {
        #[cfg(feature = "eviction-dashmap")]
        {
            self.metadata.get(term).map(|m| m.recency_score())
        }

        #[cfg(not(feature = "eviction-dashmap"))]
        {
            #[cfg(feature = "eviction-parking-lot")]
            let metadata = self.metadata.read();
            #[cfg(not(feature = "eviction-parking-lot"))]
            let metadata = self
                .metadata
                .read()
                .expect("poisoned RwLock; only fatal if writer panicked");

            metadata.get(term).map(|m| m.recency_score())
        }
    }

    /// Finds the least recently used term from a list of candidates.
    ///
    /// # Arguments
    ///
    /// * `terms` - Slice of term candidates to check
    ///
    /// # Returns
    ///
    /// The LRU term if any have metadata, `None` if none are tracked
    pub fn find_lru(&self, terms: &[&str]) -> Option<String> {
        #[cfg(feature = "eviction-dashmap")]
        {
            terms
                .iter()
                .filter_map(|&term| self.metadata.get(term).map(|m| (term, m.recency_score())))
                .max_by_key(|(_, recency)| *recency)
                .map(|(term, _)| term.to_string())
        }

        #[cfg(not(feature = "eviction-dashmap"))]
        {
            #[cfg(feature = "eviction-parking-lot")]
            let metadata = self.metadata.read();
            #[cfg(not(feature = "eviction-parking-lot"))]
            let metadata = self
                .metadata
                .read()
                .expect("poisoned RwLock; only fatal if writer panicked");

            terms
                .iter()
                .filter_map(|&term| metadata.get(term).map(|m| (term, m.recency_score())))
                .max_by_key(|(_, recency)| *recency)
                .map(|(term, _)| term.to_string())
        }
    }

    /// Evicts the least recently used term from a list of candidates.
    ///
    /// Removes the LRU term's metadata from tracking.
    ///
    /// # Arguments
    ///
    /// * `terms` - Slice of term candidates to check
    ///
    /// # Returns
    ///
    /// The evicted term if any were tracked, `None` otherwise
    pub fn evict_lru(&self, terms: &[&str]) -> Option<String> {
        if let Some(lru_term) = self.find_lru(terms) {
            #[cfg(feature = "eviction-dashmap")]
            {
                self.metadata.remove(&*lru_term);
            }

            #[cfg(not(feature = "eviction-dashmap"))]
            {
                #[cfg(feature = "eviction-parking-lot")]
                let mut metadata = self.metadata.write();
                #[cfg(not(feature = "eviction-parking-lot"))]
                let mut metadata = self
                    .metadata
                    .write()
                    .expect("poisoned RwLock; only fatal if writer panicked");

                metadata.remove(lru_term.as_str());
            }

            Some(lru_term)
        } else {
            None
        }
    }

    /// Clears all LRU metadata, resetting tracking state.
    ///
    /// This removes all recency information for all terms.
    pub fn clear_metadata(&self) {
        #[cfg(feature = "eviction-dashmap")]
        {
            self.metadata.clear();
        }

        #[cfg(not(feature = "eviction-dashmap"))]
        {
            #[cfg(feature = "eviction-parking-lot")]
            let mut metadata = self.metadata.write();
            #[cfg(not(feature = "eviction-parking-lot"))]
            let mut metadata = self
                .metadata
                .write()
                .expect("poisoned RwLock; only fatal if writer panicked");

            metadata.clear();
        }
    }
}

impl<D> Dictionary for LruOptimized<D>
where
    D: Dictionary,
{
    type Node = LruOptimizedNode<D::Node>;

    #[inline]
    fn root(&self) -> Self::Node {
        LruOptimizedNode::new(self.inner.root(), Arc::clone(&self.metadata))
    }

    #[inline]
    fn len(&self) -> Option<usize> {
        self.inner.len()
    }

    #[inline]
    fn contains(&self, term: &str) -> bool {
        self.inner.contains(term)
    }

    #[inline]
    fn sync_strategy(&self) -> SyncStrategy {
        self.inner.sync_strategy()
    }
}

impl<D, V> MappedDictionary for LruOptimized<D>
where
    D: MappedDictionary<Value = V>,
    V: DictionaryValue,
{
    type Value = V;

    #[inline]
    fn get_value(&self, term: &str) -> Option<Self::Value> {
        self.record_access(term);
        self.inner.get_value(term)
    }

    #[inline]
    fn contains_with_value<F>(&self, term: &str, predicate: F) -> bool
    where
        F: Fn(&Self::Value) -> bool,
    {
        self.inner.contains_with_value(term, predicate)
    }
}

/// Dictionary node wrapper that tracks LRU metadata.
///
/// Wraps a dictionary node and maintains shared access to LRU tracking metadata.
#[derive(Clone)]
pub struct LruOptimizedNode<N> {
    inner: N,
    metadata: MetadataStorage,
}

impl<N> LruOptimizedNode<N> {
    fn new(inner: N, metadata: MetadataStorage) -> Self {
        Self { inner, metadata }
    }
}

impl<N> DictionaryNode for LruOptimizedNode<N>
where
    N: DictionaryNode,
{
    type Unit = N::Unit;

    #[inline]
    fn is_final(&self) -> bool {
        self.inner.is_final()
    }

    #[inline]
    fn transition(&self, label: Self::Unit) -> Option<Self> {
        self.inner
            .transition(label)
            .map(|node| LruOptimizedNode::new(node, Arc::clone(&self.metadata)))
    }

    #[inline]
    fn edges(&self) -> Box<dyn Iterator<Item = (Self::Unit, Self)> + '_> {
        let metadata = Arc::clone(&self.metadata);
        Box::new(
            self.inner.edges().map(move |(label, node)| {
                (label, LruOptimizedNode::new(node, Arc::clone(&metadata)))
            }),
        )
    }

    #[inline]
    fn edge_count(&self) -> Option<usize> {
        self.inner.edge_count()
    }
}

impl<N, V> MappedDictionaryNode for LruOptimizedNode<N>
where
    N: MappedDictionaryNode<Value = V>,
    V: DictionaryValue,
{
    type Value = V;

    #[inline]
    fn value(&self) -> Option<Self::Value> {
        self.inner.value()
    }
}