libdictenstein 4.0.0-rc.3

High-performance dictionary data structures (trie, DAWG, double-array trie, suffix automaton, lock-free durable persistent ART) behind one trait API; pairs with liblevenshtein for fuzzy matching
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
//! Dictionary factory for creating different backend implementations.
//!
//! This module provides a unified interface for creating dictionary instances
//! across all in-memory backends in the crate. Persistent backends
//! (`PersistentARTrie`, `PersistentARTrieChar`, `PersistentVocabARTrie`)
//! require a file path and a different construction protocol, so they live
//! outside the factory.
//!
//! # Example
//!
//! ```rust,no_run
//! use libdictenstein::factory::{DictionaryFactory, DictionaryBackend};
//!
//! // Create a DoubleArrayTrie dictionary
//! let dict = DictionaryFactory::create(
//!     DictionaryBackend::DoubleArrayTrie,
//!     vec!["test", "testing", "tested"],
//! );
//!
//! // Create a DynamicDawgChar (Unicode) dictionary
//! let dict = DictionaryFactory::create(
//!     DictionaryBackend::DynamicDawgChar,
//!     vec!["café", "naïve"],
//! );
//! ```

use super::double_array_trie::char::DoubleArrayTrieChar;
use super::double_array_trie::DoubleArrayTrie;
use super::dynamic_dawg::char::DynamicDawgChar;
use super::dynamic_dawg::u64::DynamicDawgU64;
use super::dynamic_dawg::DynamicDawg;
#[cfg(feature = "pathmap-backend")]
use super::pathmap::char::PathMapDictionaryChar;
#[cfg(feature = "pathmap-backend")]
use super::pathmap::PathMapDictionary;
use super::scdawg::char::ScdawgChar;
use super::scdawg::Scdawg;
use super::suffix_automaton::char::SuffixAutomatonChar;
use super::suffix_automaton::SuffixAutomaton;
use super::{Dictionary, SyncStrategy};

/// Dictionary backend types.
///
/// Covers all in-memory backends. Persistent ARTrie variants
/// (`PersistentARTrie{,Char}`, `PersistentVocabARTrie`) are not included
/// here because they require file paths and richer configuration than the
/// factory exposes — construct them directly.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DictionaryBackend {
    /// PathMap-based trie dictionary (fastest for queries, highest memory).
    #[cfg(feature = "pathmap-backend")]
    PathMap,
    /// PathMap-based trie, character (Unicode) variant.
    #[cfg(feature = "pathmap-backend")]
    PathMapChar,
    /// Double-Array Trie (O(1) transitions, excellent cache, byte-keyed).
    DoubleArrayTrie,
    /// Double-Array Trie, character (Unicode) variant.
    DoubleArrayTrieChar,
    /// Dynamic DAWG dictionary (space-efficient, byte-keyed, supports modifications).
    DynamicDawg,
    /// Dynamic DAWG, character (Unicode) variant.
    DynamicDawgChar,
    /// Dynamic DAWG keyed on `u64` sequences (token sequences, time series).
    DynamicDawgU64,
    /// Suffix automaton dictionary (substring matching, byte-keyed, dynamic).
    SuffixAutomaton,
    /// Suffix automaton, character (Unicode) variant.
    SuffixAutomatonChar,
    /// Compact Suffix DAWG (substring matching, byte-keyed, batch-build).
    Scdawg,
    /// Compact Suffix DAWG, character (Unicode) variant.
    ScdawgChar,
}

/// Edge-label unit used by a backend.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BackendKeyUnit {
    /// Raw UTF-8 bytes (`u8`).
    Byte,
    /// Unicode scalar values (`char`).
    Char,
    /// Native 64-bit labels.
    U64,
}

/// Query semantics exposed by a backend.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BackendQuerySemantics {
    /// Terms are matched from the root as complete dictionary entries.
    ExactTerm,
    /// Indexed text can be matched from suffix states as substrings.
    Substring,
}

/// In-place update support exposed by the constructed backend.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BackendUpdateMode {
    /// The built dictionary is immutable; rebuild to change terms.
    Immutable,
    /// Terms can be inserted but not removed through the public backend API.
    InsertOnly,
    /// Terms can be inserted and removed.
    InsertRemove,
}

/// Machine-readable backend characteristics for selection and benchmarking.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct BackendCapabilities {
    /// Edge-label unit used by traversal.
    pub key_unit: BackendKeyUnit,
    /// Exact-term or substring semantics.
    pub query: BackendQuerySemantics,
    /// In-place update support.
    pub updates: BackendUpdateMode,
    /// Synchronization strategy advertised by the backend family.
    pub sync_strategy: SyncStrategy,
    /// Reads do not block on process-local locks.
    pub lock_free_reads: bool,
    /// Mutations do not block on process-local locks.
    pub lock_free_writes: bool,
}

impl BackendCapabilities {
    /// Returns true for Unicode scalar-value backends.
    pub fn is_unicode(self) -> bool {
        self.key_unit == BackendKeyUnit::Char
    }

    /// Returns true when the backend supports substring search semantics.
    pub fn supports_substring_search(self) -> bool {
        self.query == BackendQuerySemantics::Substring
    }

    /// Returns true when the backend supports removal through its public API.
    pub fn supports_removal(self) -> bool {
        self.updates == BackendUpdateMode::InsertRemove
    }

    /// Returns true when reads and supported writes are both lock-free.
    pub fn is_fully_lock_free_for_supported_operations(self) -> bool {
        self.lock_free_reads
            && (self.updates == BackendUpdateMode::Immutable || self.lock_free_writes)
    }
}

impl DictionaryBackend {
    /// Machine-readable backend characteristics.
    pub fn capabilities(self) -> BackendCapabilities {
        match self {
            #[cfg(feature = "pathmap-backend")]
            DictionaryBackend::PathMap => BackendCapabilities {
                key_unit: BackendKeyUnit::Byte,
                query: BackendQuerySemantics::ExactTerm,
                updates: BackendUpdateMode::InsertRemove,
                sync_strategy: SyncStrategy::InternalSync,
                lock_free_reads: true,
                lock_free_writes: true,
            },
            #[cfg(feature = "pathmap-backend")]
            DictionaryBackend::PathMapChar => BackendCapabilities {
                key_unit: BackendKeyUnit::Char,
                query: BackendQuerySemantics::ExactTerm,
                updates: BackendUpdateMode::InsertRemove,
                sync_strategy: SyncStrategy::InternalSync,
                lock_free_reads: true,
                lock_free_writes: true,
            },
            DictionaryBackend::DoubleArrayTrie => BackendCapabilities {
                key_unit: BackendKeyUnit::Byte,
                query: BackendQuerySemantics::ExactTerm,
                updates: BackendUpdateMode::Immutable,
                sync_strategy: SyncStrategy::Persistent,
                lock_free_reads: true,
                lock_free_writes: false,
            },
            DictionaryBackend::DoubleArrayTrieChar => BackendCapabilities {
                key_unit: BackendKeyUnit::Char,
                query: BackendQuerySemantics::ExactTerm,
                updates: BackendUpdateMode::Immutable,
                sync_strategy: SyncStrategy::Persistent,
                lock_free_reads: true,
                lock_free_writes: false,
            },
            DictionaryBackend::DynamicDawg => BackendCapabilities {
                key_unit: BackendKeyUnit::Byte,
                query: BackendQuerySemantics::ExactTerm,
                updates: BackendUpdateMode::InsertRemove,
                sync_strategy: SyncStrategy::InternalSync,
                lock_free_reads: true,
                lock_free_writes: true,
            },
            DictionaryBackend::DynamicDawgChar => BackendCapabilities {
                key_unit: BackendKeyUnit::Char,
                query: BackendQuerySemantics::ExactTerm,
                updates: BackendUpdateMode::InsertRemove,
                sync_strategy: SyncStrategy::InternalSync,
                lock_free_reads: true,
                lock_free_writes: true,
            },
            DictionaryBackend::DynamicDawgU64 => BackendCapabilities {
                key_unit: BackendKeyUnit::U64,
                query: BackendQuerySemantics::ExactTerm,
                updates: BackendUpdateMode::InsertRemove,
                sync_strategy: SyncStrategy::InternalSync,
                lock_free_reads: true,
                lock_free_writes: true,
            },
            DictionaryBackend::SuffixAutomaton => BackendCapabilities {
                key_unit: BackendKeyUnit::Byte,
                query: BackendQuerySemantics::Substring,
                updates: BackendUpdateMode::InsertRemove,
                sync_strategy: SyncStrategy::InternalSync,
                lock_free_reads: true,
                lock_free_writes: true,
            },
            DictionaryBackend::SuffixAutomatonChar => BackendCapabilities {
                key_unit: BackendKeyUnit::Char,
                query: BackendQuerySemantics::Substring,
                updates: BackendUpdateMode::InsertRemove,
                sync_strategy: SyncStrategy::InternalSync,
                lock_free_reads: true,
                lock_free_writes: true,
            },
            DictionaryBackend::Scdawg => BackendCapabilities {
                key_unit: BackendKeyUnit::Byte,
                query: BackendQuerySemantics::Substring,
                updates: BackendUpdateMode::InsertOnly,
                sync_strategy: SyncStrategy::InternalSync,
                lock_free_reads: true,
                lock_free_writes: true,
            },
            DictionaryBackend::ScdawgChar => BackendCapabilities {
                key_unit: BackendKeyUnit::Char,
                query: BackendQuerySemantics::Substring,
                updates: BackendUpdateMode::InsertOnly,
                sync_strategy: SyncStrategy::InternalSync,
                lock_free_reads: true,
                lock_free_writes: true,
            },
        }
    }
}

impl std::fmt::Display for DictionaryBackend {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            #[cfg(feature = "pathmap-backend")]
            DictionaryBackend::PathMap => write!(f, "PathMap"),
            #[cfg(feature = "pathmap-backend")]
            DictionaryBackend::PathMapChar => write!(f, "PathMapChar"),
            DictionaryBackend::DoubleArrayTrie => write!(f, "DoubleArrayTrie"),
            DictionaryBackend::DoubleArrayTrieChar => write!(f, "DoubleArrayTrieChar"),
            DictionaryBackend::DynamicDawg => write!(f, "DynamicDAWG"),
            DictionaryBackend::DynamicDawgChar => write!(f, "DynamicDAWGChar"),
            DictionaryBackend::DynamicDawgU64 => write!(f, "DynamicDAWGU64"),
            DictionaryBackend::SuffixAutomaton => write!(f, "SuffixAutomaton"),
            DictionaryBackend::SuffixAutomatonChar => write!(f, "SuffixAutomatonChar"),
            DictionaryBackend::Scdawg => write!(f, "Scdawg"),
            DictionaryBackend::ScdawgChar => write!(f, "ScdawgChar"),
        }
    }
}

/// Unified dictionary container that can hold any backend type.
///
/// Carries only `()`-valued (set-like) dictionaries — for value-bearing
/// dictionaries (`DynamicDawg<V>`, etc.) construct the backend directly.
#[derive(Debug)]
pub enum DictionaryContainer {
    #[cfg(feature = "pathmap-backend")]
    PathMap(PathMapDictionary),
    #[cfg(feature = "pathmap-backend")]
    PathMapChar(PathMapDictionaryChar),
    DoubleArrayTrie(DoubleArrayTrie),
    DoubleArrayTrieChar(DoubleArrayTrieChar),
    DynamicDawg(DynamicDawg),
    DynamicDawgChar(DynamicDawgChar),
    DynamicDawgU64(DynamicDawgU64),
    SuffixAutomaton(SuffixAutomaton),
    SuffixAutomatonChar(SuffixAutomatonChar),
    Scdawg(Scdawg),
    ScdawgChar(ScdawgChar),
}

impl DictionaryContainer {
    /// Get the backend type of this container.
    pub fn backend(&self) -> DictionaryBackend {
        match self {
            #[cfg(feature = "pathmap-backend")]
            DictionaryContainer::PathMap(_) => DictionaryBackend::PathMap,
            #[cfg(feature = "pathmap-backend")]
            DictionaryContainer::PathMapChar(_) => DictionaryBackend::PathMapChar,
            DictionaryContainer::DoubleArrayTrie(_) => DictionaryBackend::DoubleArrayTrie,
            DictionaryContainer::DoubleArrayTrieChar(_) => DictionaryBackend::DoubleArrayTrieChar,
            DictionaryContainer::DynamicDawg(_) => DictionaryBackend::DynamicDawg,
            DictionaryContainer::DynamicDawgChar(_) => DictionaryBackend::DynamicDawgChar,
            DictionaryContainer::DynamicDawgU64(_) => DictionaryBackend::DynamicDawgU64,
            DictionaryContainer::SuffixAutomaton(_) => DictionaryBackend::SuffixAutomaton,
            DictionaryContainer::SuffixAutomatonChar(_) => DictionaryBackend::SuffixAutomatonChar,
            DictionaryContainer::Scdawg(_) => DictionaryBackend::Scdawg,
            DictionaryContainer::ScdawgChar(_) => DictionaryBackend::ScdawgChar,
        }
    }

    /// Get the number of terms in the dictionary.
    pub fn len(&self) -> Option<usize> {
        match self {
            #[cfg(feature = "pathmap-backend")]
            DictionaryContainer::PathMap(d) => d.len(),
            #[cfg(feature = "pathmap-backend")]
            DictionaryContainer::PathMapChar(d) => d.len(),
            DictionaryContainer::DoubleArrayTrie(d) => d.len(),
            DictionaryContainer::DoubleArrayTrieChar(d) => d.len(),
            DictionaryContainer::DynamicDawg(d) => d.len(),
            DictionaryContainer::DynamicDawgChar(d) => d.len(),
            DictionaryContainer::DynamicDawgU64(d) => d.len(),
            DictionaryContainer::SuffixAutomaton(d) => d.len(),
            DictionaryContainer::SuffixAutomatonChar(d) => d.len(),
            DictionaryContainer::Scdawg(d) => d.len(),
            DictionaryContainer::ScdawgChar(d) => d.len(),
        }
    }

    /// Check if the dictionary is empty.
    pub fn is_empty(&self) -> bool {
        self.len() == Some(0)
    }

    /// Check if a term exists in the dictionary.
    pub fn contains(&self, term: &str) -> bool {
        match self {
            #[cfg(feature = "pathmap-backend")]
            DictionaryContainer::PathMap(d) => d.contains(term),
            #[cfg(feature = "pathmap-backend")]
            DictionaryContainer::PathMapChar(d) => d.contains(term),
            DictionaryContainer::DoubleArrayTrie(d) => d.contains(term),
            DictionaryContainer::DoubleArrayTrieChar(d) => d.contains(term),
            DictionaryContainer::DynamicDawg(d) => d.contains(term),
            DictionaryContainer::DynamicDawgChar(d) => d.contains(term),
            DictionaryContainer::DynamicDawgU64(d) => d.contains(term),
            DictionaryContainer::SuffixAutomaton(d) => d.contains(term),
            DictionaryContainer::SuffixAutomatonChar(d) => d.contains(term),
            DictionaryContainer::Scdawg(d) => d.contains(term),
            DictionaryContainer::ScdawgChar(d) => d.contains(term),
        }
    }
}

/// Factory for creating dictionaries with different backends.
pub struct DictionaryFactory;

impl DictionaryFactory {
    /// Create a dictionary with the specified backend.
    ///
    /// # Arguments
    ///
    /// * `backend` - The backend implementation to use
    /// * `terms` - Iterator of terms to insert
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use libdictenstein::factory::{DictionaryFactory, DictionaryBackend};
    ///
    /// let dict = DictionaryFactory::create(
    ///     DictionaryBackend::DynamicDawg,
    ///     vec!["hello", "world"],
    /// );
    /// assert!(dict.contains("hello"));
    /// ```
    pub fn create<I, S>(backend: DictionaryBackend, terms: I) -> DictionaryContainer
    where
        I: IntoIterator<Item = S>,
        S: AsRef<str>,
    {
        match backend {
            #[cfg(feature = "pathmap-backend")]
            DictionaryBackend::PathMap => {
                DictionaryContainer::PathMap(PathMapDictionary::from_terms(terms))
            }
            #[cfg(feature = "pathmap-backend")]
            DictionaryBackend::PathMapChar => {
                DictionaryContainer::PathMapChar(PathMapDictionaryChar::from_terms(terms))
            }
            DictionaryBackend::DoubleArrayTrie => {
                DictionaryContainer::DoubleArrayTrie(DoubleArrayTrie::from_terms(terms))
            }
            DictionaryBackend::DoubleArrayTrieChar => {
                DictionaryContainer::DoubleArrayTrieChar(DoubleArrayTrieChar::from_terms(terms))
            }
            DictionaryBackend::DynamicDawg => {
                DictionaryContainer::DynamicDawg(DynamicDawg::from_terms(terms))
            }
            DictionaryBackend::DynamicDawgChar => {
                DictionaryContainer::DynamicDawgChar(DynamicDawgChar::from_terms(terms))
            }
            DictionaryBackend::DynamicDawgU64 => {
                DictionaryContainer::DynamicDawgU64(DynamicDawgU64::from_terms(terms))
            }
            DictionaryBackend::SuffixAutomaton => {
                DictionaryContainer::SuffixAutomaton(SuffixAutomaton::from_texts(terms))
            }
            DictionaryBackend::SuffixAutomatonChar => {
                DictionaryContainer::SuffixAutomatonChar(SuffixAutomatonChar::from_texts(terms))
            }
            DictionaryBackend::Scdawg => DictionaryContainer::Scdawg(Scdawg::from_terms(terms)),
            DictionaryBackend::ScdawgChar => {
                DictionaryContainer::ScdawgChar(ScdawgChar::from_terms(terms))
            }
        }
    }

    /// Create an empty dictionary with the specified backend.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use libdictenstein::factory::{DictionaryFactory, DictionaryBackend};
    ///
    /// let dict = DictionaryFactory::empty(DictionaryBackend::DynamicDawg);
    /// assert_eq!(dict.len(), Some(0));
    /// ```
    pub fn empty(backend: DictionaryBackend) -> DictionaryContainer {
        match backend {
            #[cfg(feature = "pathmap-backend")]
            DictionaryBackend::PathMap => DictionaryContainer::PathMap(PathMapDictionary::new()),
            #[cfg(feature = "pathmap-backend")]
            DictionaryBackend::PathMapChar => {
                DictionaryContainer::PathMapChar(PathMapDictionaryChar::new())
            }
            DictionaryBackend::DoubleArrayTrie => {
                DictionaryContainer::DoubleArrayTrie(DoubleArrayTrie::new())
            }
            DictionaryBackend::DoubleArrayTrieChar => {
                // DoubleArrayTrieChar uses `empty()` instead of `new()`.
                DictionaryContainer::DoubleArrayTrieChar(DoubleArrayTrieChar::empty())
            }
            DictionaryBackend::DynamicDawg => DictionaryContainer::DynamicDawg(DynamicDawg::new()),
            DictionaryBackend::DynamicDawgChar => {
                DictionaryContainer::DynamicDawgChar(DynamicDawgChar::new())
            }
            DictionaryBackend::DynamicDawgU64 => {
                DictionaryContainer::DynamicDawgU64(DynamicDawgU64::new())
            }
            DictionaryBackend::SuffixAutomaton => {
                DictionaryContainer::SuffixAutomaton(SuffixAutomaton::new())
            }
            DictionaryBackend::SuffixAutomatonChar => {
                DictionaryContainer::SuffixAutomatonChar(SuffixAutomatonChar::new())
            }
            DictionaryBackend::Scdawg => DictionaryContainer::Scdawg(Scdawg::new()),
            DictionaryBackend::ScdawgChar => DictionaryContainer::ScdawgChar(ScdawgChar::new()),
        }
    }

    /// List of all available backends.
    pub fn available_backends() -> Vec<DictionaryBackend> {
        vec![
            #[cfg(feature = "pathmap-backend")]
            DictionaryBackend::PathMap,
            #[cfg(feature = "pathmap-backend")]
            DictionaryBackend::PathMapChar,
            DictionaryBackend::DoubleArrayTrie,
            DictionaryBackend::DoubleArrayTrieChar,
            DictionaryBackend::DynamicDawg,
            DictionaryBackend::DynamicDawgChar,
            DictionaryBackend::DynamicDawgU64,
            DictionaryBackend::SuffixAutomaton,
            DictionaryBackend::SuffixAutomatonChar,
            DictionaryBackend::Scdawg,
            DictionaryBackend::ScdawgChar,
        ]
    }

    /// Machine-readable characteristics for a backend.
    pub fn backend_capabilities(backend: DictionaryBackend) -> BackendCapabilities {
        backend.capabilities()
    }

    /// Description of a backend's characteristics.
    pub fn backend_description(backend: DictionaryBackend) -> &'static str {
        match backend {
            #[cfg(feature = "pathmap-backend")]
            DictionaryBackend::PathMap => {
                "PathMap-based byte trie. Fast queries, higher memory; in-memory only."
            }
            #[cfg(feature = "pathmap-backend")]
            DictionaryBackend::PathMapChar => {
                "PathMap-based character trie. Unicode-aware variant of PathMap."
            }
            DictionaryBackend::DoubleArrayTrie => {
                "Byte-keyed double-array trie. O(1) transitions, excellent cache locality, \
                 read-mostly. Best for static dictionaries."
            }
            DictionaryBackend::DoubleArrayTrieChar => {
                "Character-keyed double-array trie. Unicode-aware variant of DoubleArrayTrie."
            }
            DictionaryBackend::DynamicDawg => {
                "Byte-keyed dynamic DAWG. Space-efficient with full dynamic modification \
                 support. Best for evolving dictionaries."
            }
            DictionaryBackend::DynamicDawgChar => {
                "Character-keyed dynamic DAWG. Unicode-aware variant of DynamicDawg."
            }
            DictionaryBackend::DynamicDawgU64 => {
                "u64-keyed dynamic DAWG. For token-sequence dictionaries, time series, \
                 or any application keying on 64-bit symbols."
            }
            DictionaryBackend::SuffixAutomaton => {
                "Byte-keyed suffix automaton. Substring matching anywhere in indexed text. \
                 Best for full-text and code search."
            }
            DictionaryBackend::SuffixAutomatonChar => {
                "Character-keyed suffix automaton. Unicode-aware variant of SuffixAutomaton."
            }
            DictionaryBackend::Scdawg => {
                "Byte-keyed compact suffix DAWG (Blumer et al. 1987). Substring matching \
                 with smaller memory footprint than SuffixAutomaton for static inputs."
            }
            DictionaryBackend::ScdawgChar => {
                "Character-keyed compact suffix DAWG. Unicode-aware variant of Scdawg."
            }
        }
    }
}

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

    #[test]
    #[cfg(feature = "pathmap-backend")]
    fn test_factory_pathmap() {
        let dict = DictionaryFactory::create(
            DictionaryBackend::PathMap,
            vec!["test", "testing", "tested"],
        );

        assert_eq!(dict.backend(), DictionaryBackend::PathMap);
        assert_eq!(dict.len(), Some(3));
        assert!(dict.contains("test"));
        assert!(dict.contains("testing"));
        assert!(dict.contains("tested"));
        assert!(!dict.contains("tester"));
    }

    #[test]
    fn test_factory_dynamic_dawg() {
        let dict =
            DictionaryFactory::create(DictionaryBackend::DynamicDawg, vec!["foo", "bar", "baz"]);

        assert_eq!(dict.backend(), DictionaryBackend::DynamicDawg);
        assert_eq!(dict.len(), Some(3));
        assert!(dict.contains("foo"));
        assert!(dict.contains("bar"));
        assert!(dict.contains("baz"));
        assert!(!dict.contains("qux"));
    }

    #[test]
    fn test_factory_unicode_backends() {
        let unicode_terms = vec!["café", "naïve", "日本語"];

        for backend in [
            DictionaryBackend::DoubleArrayTrieChar,
            DictionaryBackend::DynamicDawgChar,
            DictionaryBackend::SuffixAutomatonChar,
            DictionaryBackend::ScdawgChar,
        ] {
            let dict = DictionaryFactory::create(backend, unicode_terms.clone());
            assert!(dict.contains("café"), "{backend} should contain 'café'");
            assert!(dict.contains("naïve"), "{backend} should contain 'naïve'");
            assert!(dict.contains("日本語"), "{backend} should contain '日本語'");
        }
    }

    #[test]
    fn test_factory_empty() {
        for backend in DictionaryFactory::available_backends() {
            let dict = DictionaryFactory::empty(backend);
            assert_eq!(dict.len(), Some(0), "{backend}");
            assert!(dict.is_empty(), "{backend}");
        }
    }

    #[test]
    fn test_backend_display() {
        #[cfg(feature = "pathmap-backend")]
        assert_eq!(DictionaryBackend::PathMap.to_string(), "PathMap");
        assert_eq!(DictionaryBackend::DynamicDawg.to_string(), "DynamicDAWG");
        assert_eq!(
            DictionaryBackend::DoubleArrayTrieChar.to_string(),
            "DoubleArrayTrieChar"
        );
        assert_eq!(DictionaryBackend::Scdawg.to_string(), "Scdawg");
    }

    #[test]
    fn test_available_backends() {
        let backends = DictionaryFactory::available_backends();
        // 11 backends total: 4 byte + 4 char + DynamicDawgU64 + 2 scdawg.
        // PathMap and PathMapChar gated behind feature.
        #[cfg(feature = "pathmap-backend")]
        assert_eq!(backends.len(), 11);
        #[cfg(not(feature = "pathmap-backend"))]
        assert_eq!(backends.len(), 9);
        assert!(backends.contains(&DictionaryBackend::DoubleArrayTrie));
        assert!(backends.contains(&DictionaryBackend::DynamicDawg));
        assert!(backends.contains(&DictionaryBackend::DynamicDawgChar));
        assert!(backends.contains(&DictionaryBackend::SuffixAutomaton));
        assert!(backends.contains(&DictionaryBackend::Scdawg));
    }

    #[test]
    fn test_backend_descriptions() {
        for backend in DictionaryFactory::available_backends() {
            let desc = DictionaryFactory::backend_description(backend);
            assert!(!desc.is_empty(), "{backend} has empty description");
        }
    }

    #[test]
    fn test_backend_capabilities_cover_selection_axes() {
        for backend in DictionaryFactory::available_backends() {
            let caps = DictionaryFactory::backend_capabilities(backend);
            assert_eq!(caps, backend.capabilities(), "{backend}");
            assert!(
                caps.is_fully_lock_free_for_supported_operations(),
                "{backend} should be lock-free for advertised operations"
            );

            match backend {
                DictionaryBackend::DoubleArrayTrie | DictionaryBackend::DoubleArrayTrieChar => {
                    assert_eq!(caps.updates, BackendUpdateMode::Immutable, "{backend}");
                    assert_eq!(caps.sync_strategy, SyncStrategy::Persistent, "{backend}");
                }
                DictionaryBackend::SuffixAutomaton
                | DictionaryBackend::SuffixAutomatonChar
                | DictionaryBackend::Scdawg
                | DictionaryBackend::ScdawgChar => {
                    assert!(
                        caps.supports_substring_search(),
                        "{backend} should advertise substring semantics"
                    );
                }
                _ => {
                    assert!(
                        !caps.supports_substring_search(),
                        "{backend} should advertise exact-term semantics"
                    );
                }
            }
        }
    }

    #[test]
    fn test_backend_capability_key_units() {
        assert_eq!(
            DictionaryBackend::DynamicDawg.capabilities().key_unit,
            BackendKeyUnit::Byte
        );
        assert_eq!(
            DictionaryBackend::DynamicDawgChar.capabilities().key_unit,
            BackendKeyUnit::Char
        );
        assert!(DictionaryBackend::DynamicDawgChar
            .capabilities()
            .is_unicode());
        assert_eq!(
            DictionaryBackend::DynamicDawgU64.capabilities().key_unit,
            BackendKeyUnit::U64
        );
    }

    #[test]
    fn test_all_backends_work() {
        let terms = vec!["apple", "banana", "cherry"];

        for backend in DictionaryFactory::available_backends() {
            let dict = DictionaryFactory::create(backend, terms.clone());
            assert!(dict.contains("apple"), "{backend} should contain 'apple'");
            assert!(dict.contains("banana"), "{backend} should contain 'banana'");
            assert!(dict.contains("cherry"), "{backend} should contain 'cherry'");
        }
    }
}