dictutils 0.1.2

Dictionary utilities for Mdict and other formats
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
# DictUtils


A high-performance Rust library for fast dictionary operations with support for multiple dictionary formats (MDict, StarDict, ZIM) and advanced indexing capabilities.

## โš ๏ธ Experimental Status


DictUtils is currently experimental and not suitable for production use. Many format parsers rely on placeholder logic that does not validate real dictionary files, index sidecars are not compatible with production dictionaries, and compression/IO helpers are best-effort prototypes. Use this crate only for prototyping or research experiments. Contributions are welcome to replace the mock parsing layers with real format support.



[![Crates.io](https://img.shields.io/crates/v/dictutils.svg)](https://crates.io/crates/dictutils)
[![Documentation](https://docs.rs/dictutils/badge.svg)](https://docs.rs/dictutils)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)

## โœจ Features


- **๐Ÿš€ High Performance**: B-TREE indexing and memory-mapped files for optimal speed
- **๐Ÿ“š Multi-Format Support**: MDict, StarDict, and ZIM dictionary formats
- **๐Ÿ” Advanced Search**: Prefix, fuzzy, and full-text search capabilities
- **โšก Concurrent Access**: Thread-safe operations with parallel processing
- **๐Ÿ’พ Memory Efficient**: LRU caching and lazy loading
- **๐Ÿ› ๏ธ Flexible Configuration**: Customizable cache sizes, indexing options, and more

## ๐Ÿš€ Quick Start


Add DictUtils to your `Cargo.toml`:

```toml
[dependencies]
dictutils = "0.1.0"
```

Or with optional features:

```toml
[dependencies]
dictutils = { version = "0.1.0", features = ["criterion", "rayon", "cli", "encoding-support"] }
```

Basic usage example:

```rust
use dictutils::prelude::*;

fn main() -> dictutils::Result<()> {
    // Load dictionary with auto-detection
    let loader = DictLoader::new();
    let mut dict = loader.load("path/to/dictionary.mdict")?;
    
    // Basic lookup
    let entry = dict.get(&"hello".to_string())?;
    println!("Found: {}", String::from_utf8_lossy(&entry));
    
    // Prefix search
    let results = dict.search_prefix("hel", Some(10))?;
    for result in results {
        println!("Found: {}", result.word);
    }
    
    Ok(())
}
```

## ๐Ÿ“– Documentation


### Core Concepts


#### Dictionary Loading


```rust
// Auto-detection of dictionary format
let mut dict = DictLoader::new().load("dictionary.mdict")?;

// With custom configuration
let config = DictConfig {
    load_btree: true,        // Enable B-TREE indexing
    load_fts: true,          // Enable full-text search
    use_mmap: true,          // Memory mapping for large files
    cache_size: 1000,        // Entry cache size
    batch_size: 100,         // Batch operation size
    ..Default::default()
};

let loader = DictLoader::with_config(config);
let mut dict = loader.load("large_dictionary.zim")?;
```

#### Search Operations


```rust
use dictutils::traits::*;

// Prefix search - find words starting with "comp"
let prefix_results = dict.search_prefix("comp", Some(20))?;

// Fuzzy search - find words similar to "programing"
let fuzzy_results = dict.search_fuzzy("programing", Some(2))?;

// Full-text search - search within content
let fts_iterator = dict.search_fulltext("programming language")?;
let fts_results: Vec<_> = fts_iterator.collect()?;

// Range queries
let range_results = dict.get_range(100..200)?;

// Batch lookups
let keys = vec!["hello".to_string(), "world".to_string(), "rust".to_string()];
let batch_results = dict.get_batch(&keys, Some(50))?;
```

#### Performance Optimization


```rust
// Build indexes for better performance
dict.build_indexes()?;

// Configure for memory efficiency
let efficient_config = DictConfig {
    use_mmap: true,      // Better for large files
    cache_size: 500,     // Smaller cache for memory-constrained environments
    load_btree: true,    // Fast lookups
    load_fts: false,     // Disable if not needed
    ..Default::default()
};

// Monitor performance statistics
let stats = dict.stats();
println!("Memory usage: {} bytes", stats.memory_usage);
println!("Cache hit rate: {:.2}%", stats.cache_hit_rate * 100.0);
for (index_name, size) in &stats.index_sizes {
    println!("{} index: {} bytes", index_name, size);
}
```

## ๐Ÿ—๏ธ Architecture


### Core Components


```
dictutils/
โ”œโ”€โ”€ traits.rs          # Core trait definitions
โ”œโ”€โ”€ dict/              # Dictionary format implementations
โ”‚   โ”œโ”€โ”€ mdict.rs      # Monkey's Dictionary format
โ”‚   โ”œโ”€โ”€ stardict.rs   # StarDict format
โ”‚   โ””โ”€โ”€ zimdict.rs    # ZIM format
โ”œโ”€โ”€ index/             # High-performance indexing
โ”‚   โ”œโ”€โ”€ btree.rs      # B-TREE index for fast lookups
โ”‚   โ””โ”€โ”€ fts.rs        # Full-text search index
โ”œโ”€โ”€ util/              # Utility modules
โ”‚   โ”œโ”€โ”€ compression.rs # Compression algorithms
โ”‚   โ”œโ”€โ”€ encoding.rs    # Text encoding conversion
โ”‚   โ””โ”€โ”€ buffer.rs      # Binary buffer utilities
โ””โ”€โ”€ lib.rs            # Main library module
```

### Design Principles


1. **Performance First**: Optimized for speed with efficient data structures
2. **Memory Efficiency**: Lazy loading, caching, and memory mapping
3. **Thread Safety**: All operations are thread-safe by default
4. **Format Agnostic**: Unified interface across different dictionary formats
5. **Extensible**: Easy to add new dictionary formats and features

## ๐Ÿ“Š Performance Guide


### Dictionary Size Recommendations


| Dictionary Size | Configuration | Memory Mapping | Indexes |
|----------------|---------------|----------------|---------|
| < 10MB         | Basic config  | Optional       | Optional |
| 10MB - 100MB   | Standard      | Recommended    | B-TREE |
| 100MB - 1GB    | Optimized     | Recommended    | B-TREE + FTS |
| > 1GB          | Enterprise    | Required       | B-TREE + FTS |

### Performance Tips


#### 1. Index Optimization


```rust
// Build B-TREE index for fast exact lookups
dict.build_indexes()?;

// Enable memory mapping for better I/O performance
let config = DictConfig {
    use_mmap: true,
    ..Default::default()
};

// Cache frequently accessed entries
let config = DictConfig {
    cache_size: 2000,  // Increase cache size
    ..Default::default()
};
```

#### 2. Search Optimization


```rust
// Use batch operations for multiple lookups
let keys = vec!["word1".to_string(), "word2".to_string(), /* ... */];
let results = dict.get_batch(&keys, Some(100))?;

// Cache search results
let mut cache = HashMap::new();

// Prefix search with limits
let results = dict.search_prefix("prefix", Some(100))?;

// Use appropriate search type
if query.len() <= 3 {
    dict.search_prefix(query, limit);  // Fast for short prefixes
} else if query.contains(" ") {
    dict.search_fulltext(query)?;     // For phrases
} else {
    dict.search_fuzzy(query, Some(2))?; // For typo tolerance
}
```

#### 3. Memory Optimization


```rust
// Use memory mapping for large files
let config = DictConfig {
    use_mmap: true,
    ..Default::default()
};

// Clear cache periodically
dict.clear_cache();

// Monitor memory usage
let stats = dict.stats();
println!("Memory usage: {} bytes", stats.memory_usage);
```

### Benchmarking


Run performance benchmarks:

```bash
# Run all benchmarks

cargo bench --all-features

# Run specific benchmark category

cargo bench --features criterion -- dict_lookup

# Profile memory usage

cargo run --features criterion --example performance_profiling
```

Expected performance characteristics:

- **Dictionary Loading**: 10-100ms for dictionaries < 100MB
- **Exact Lookup**: < 1ms with B-TREE index
- **Prefix Search**: < 10ms for 1000 results
- **Fuzzy Search**: < 100ms for 100 results
- **Full-Text Search**: < 50ms for 100 results

## ๐Ÿ”ง Advanced Usage


### Concurrent Access


```rust
use std::sync::{Arc, Mutex};
use std::thread;

// Share dictionary across threads
let dict = Arc::new(dict);

// Thread 1: Reading operations
let dict1 = Arc::clone(&dict);
let handle1 = thread::spawn(move || {
    let entry = dict1.get(&"hello".to_string())?;
    println!("Found: {}", String::from_utf8_lossy(&entry));
    Ok::<(), dictutils::DictError>(())
});

// Thread 2: Search operations
let dict2 = Arc::clone(&dict);
let handle2 = thread::spawn(move || {
    let results = dict2.search_prefix("test", Some(10))?;
    println!("Found {} results", results.len());
    Ok::<(), dictutils::DictError>(())
});

handle1.join().unwrap().unwrap();
handle2.join().unwrap().unwrap();
```

### Custom Dictionary Processing


```rust
// Process large dictionaries efficiently
fn process_large_dictionary(dict_path: &str) -> dictutils::Result<()> {
    let loader = DictLoader::new();
    let mut dict = loader.load(dict_path)?;
    
    // Build indexes for better performance
    dict.build_indexes()?;
    
    // Process entries in batches
    let iterator = dict.iter()?;
    let mut batch = Vec::new();
    let batch_size = 1000;
    
    for entry_result in iterator {
        match entry_result {
            Ok((key, value)) => {
                batch.push((key, value));
                
                if batch.len() >= batch_size {
                    process_batch(&batch)?;
                    batch.clear();
                }
            }
            Err(e) => {
                println!("Error processing entry: {}", e);
            }
        }
    }
    
    // Process remaining entries
    if !batch.is_empty() {
        process_batch(&batch)?;
    }
    
    Ok(())
}
```

### Format Conversion


```rust
// Convert between dictionary formats
use dictutils::dict::{BatchOperations, DictFormat};

fn convert_dictionary(source: &str, destination: &str, target_format: &str) -> dictutils::Result<()> {
    let loader = DictLoader::new();
    let mut source_dict = loader.load(source)?;
    
    // Extract all entries
    let entries: Vec<(String, Vec<u8>)> = source_dict.iter()
        .collect::<Result<Vec<_>, _>>()?;
    
    // Create new dictionary in target format
    // Note: This would require a DictBuilder implementation
    // For now, create the new dictionary manually
    
    match target_format {
        "mdict" => {
            // Create MDict file with extracted entries
            println!("Converting to MDict format with {} entries", entries.len());
        }
        "stardict" => {
            // Create StarDict file with extracted entries  
            println!("Converting to StarDict format with {} entries", entries.len());
        }
        _ => {
            return Err(DictError::UnsupportedOperation(
                format!("Target format '{}' not supported", target_format)
            ));
        }
    }
    
    Ok(())
}
```

## ๐Ÿ” Dictionary Formats


### MDict (Monkey's Dictionary)


High-performance binary format with:
- B-TREE indexing for fast lookups
- Memory-mapped file access
- Compression support (GZIP, LZ4, Zstandard)
- Custom metadata fields

**Best for**: Large dictionaries, performance-critical applications

### StarDict

 
Classic format with:
- Binary search support
- Synonym and mnemonic files
- Cross-platform compatibility
- Simple text-based format
- Enhanced DICTZIP handling: random-access via RA tables or deterministic sequential inflation when RA is missing

**Best for**: General purpose dictionaries, simple implementations

### ZIM


Wikipedia offline format with:
- Article-based storage
- Built-in compression
- Rich metadata support
- Efficient for encyclopedia content

**Best for**: Offline wikis, reference materials

### Babylon (BGL)


Babylon format with:
- Sidecar index support
- Memory-mapped file access
- Requires external indexing tools

**Important**: The BGL implementation does NOT parse raw `.bgl` binaries directly. It requires externally built sidecar index files (`.btree` and `.fts`) that must be provided by an external tool like GoldenDict's indexer. The BGL parser only consumes these pre-built indexes and does not implement raw BGL binary parsing.

**Best for**: Babylon dictionaries with pre-built indexes

## ๐Ÿšจ Error Handling


All operations return `Result<T, DictError>`:

```rust
use dictutils::traits::{DictError, Result};

fn robust_dict_operation() -> Result<()> {
    let loader = DictLoader::new();
    
    match loader.load("dictionary.mdict") {
        Ok(mut dict) => {
            match dict.get(&"example".to_string()) {
                Ok(entry) => {
                    println!("Found: {}", String::from_utf8_lossy(&entry));
                }
                Err(DictError::IndexError(msg)) => {
                    println!("Word not found: {}", msg);
                }
                Err(e) => {
                    println!("Lookup error: {}", e);
                }
            }
        }
        Err(DictError::FileNotFound(path)) => {
            println!("Dictionary file not found: {}", path);
        }
        Err(DictError::InvalidFormat(msg)) => {
            println!("Invalid dictionary format: {}", msg);
        }
        Err(DictError::IoError(msg)) => {
            println!("I/O error: {}", msg);
        }
        Err(e) => {
            println!("Other error: {}", e);
        }
    }
    
    Ok(())
}
```

## ๐Ÿงช Testing


### Running Tests


```bash
# Run all tests

cargo test

# Run specific test categories

cargo test unit_tests
cargo test integration_tests
cargo test error_tests
cargo test concurrent_tests

# Run with coverage

cargo test --lib -- --test-threads=1

# Run benchmarks (requires criterion feature)

cargo test --features criterion
```

### Performance Testing


```bash
# Run performance tests

cargo test --features criterion performance_tests

# Run memory leak detection

cargo test --features debug_leak_detector

# Run concurrent stress tests

cargo test concurrent_tests -- --nocapture
```

## ๐Ÿ“ฆ Optional Features


Enable additional functionality with Cargo features:

```toml
[dependencies.dictutils]
version = "0.1.0"
features = [
    "criterion",          # Performance benchmarks
    "rayon",              # Parallel processing
    "cli",                # Command-line tools
    "serde",              # Serialization support
    "debug_leaks"         # Memory leak detection
]
```

## ๐Ÿค Contributing


We welcome contributions! Please see our [Contributing Guide](CONTRIBUTING.md) for details.

### Development Setup


```bash
# Clone repository

git clone https://github.com/your-username/dictutils.git
cd dictutils

# Install development dependencies

cargo install cargo-watch
cargo install cargo-audit

# Run tests

cargo test

# Run linting

cargo fmt --check
cargo clippy --all-targets --all-features

# Run benchmarks

cargo bench --all-features
```

### Adding New Dictionary Formats


To add support for a new dictionary format:

1. Implement the `DictFormat` trait
2. Implement the `Dict` trait for your format
3. Add format detection logic to `DictLoader`
4. Add comprehensive tests

Example template:

```rust
use dictutils::traits::*;

pub struct NewDict {
    // Your implementation
}

impl DictFormat<String> for NewDict {
    const FORMAT_NAME: &'static str = "newdict";
    
    fn is_valid_format(path: &Path) -> Result<bool> {
        // Implement format validation
        Ok(false) // Placeholder
    }
    
    fn load(path: &Path, config: DictConfig) -> Result<Box<dyn Dict<String>>> {
        // Implement format loading
        Err(DictError::UnsupportedOperation("Not implemented".to_string()))
    }
}

impl Dict<String> for NewDict {
    // Implement all required methods
    // ...
}
```

## ๐Ÿ“„ License


This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.

## ๐Ÿ™ Acknowledgments


- [MDict format specification]https://github.com/zhansf129/MDict
- [StarDict documentation]http://stardict.sourceforge.net/
- [ZIM format documentation]https://wiki.openzim.org/wiki/ZIM_file_format
- Rust ecosystem crates that made this possible

## ๐Ÿ“Š Benchmarks


Performance results on typical hardware (Intel i7, 16GB RAM):

| Operation | Small Dict (<1MB) | Medium Dict (10MB) | Large Dict (100MB) |
|-----------|-------------------|--------------------|-------------------|
| Load Time | < 10ms | < 100ms | < 500ms |
| Exact Lookup | < 0.1ms | < 0.1ms | < 0.1ms |
| Prefix Search | < 1ms | < 5ms | < 20ms |
| Fuzzy Search | < 10ms | < 50ms | < 200ms |
| Full-Text Search | < 20ms | < 100ms | < 500ms |

## ๐Ÿ†˜ Support


- **Documentation**: [docs.rs/dictutils]https://docs.rs/dictutils
- **Issues**: [GitHub Issues]https://github.com/your-username/dictutils/issues
- **Discussions**: [GitHub Discussions]https://github.com/your-username/dictutils/discussions
- **Discord**: [Join our Discord server]https://discord.gg/your-invite

---

Made with โค๏ธ by the DictUtils team