mdictlib 0.2.8

Library-first Rust parser for MDict .mdx and .mdd dictionaries
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
//! Unpack, re-encode, and verify arbitrary `.mdx` and `.mdd` files.
//!
//! For every path given on the command line this demo:
//!
//! 1. opens the file and fully unpacks it — every entry or resource is
//!    decoded, hashed, and counted through the public read API;
//! 2. re-encodes the whole file with `reencode_mdx`/`reencode_mdd`, which
//!    decodes every block again and re-emits the file with the same
//!    structure and compression tags;
//! 3. compares the output with the original byte-for-byte.
//!
//! Uncompressed sources come back byte-identical. Sources with zlib blocks
//! may differ inside the compressed streams only — deflate output depends
//! on the compressor implementation — so when bytes differ the demo falls
//! back to a logical comparison (same keys, same payloads, same order) and
//! reports which kind of difference it found. Version 1, encrypted, and LZO
//! sources are refused with a clear message.
//!
//! With `--dump <dir>` the unpacked content is also written for debugging:
//! each `.mdx` becomes one `<stem>.txt` in the classic MDict source format
//! (`key`, `</>`, definition lines, `</>`), and each `.mdd` becomes a
//! `<stem>/` directory holding every resource under its resource path.
//!
//! Run with `cargo run --example reencode_demo -- [--dump DIR] path/to/dict.mdx
//! path/to/resources.mdd`. Without file arguments the demo builds its own
//! synthetic dictionary and resource file first, so it always has something
//! to verify.

use std::collections::hash_map::DefaultHasher;
use std::fs::{self, File};
use std::hash::{Hash, Hasher};
use std::io::{BufWriter, Write as IoWrite};
use std::path::{Path, PathBuf};
use std::process::ExitCode;

use mdictlib::{
    MddBuilder, MddFile, MdxBuilder, MdxFile, WriteCompression, WriteOptions, reencode_mdd,
    reencode_mdx,
};

struct TempGuard(Vec<PathBuf>);

impl TempGuard {
    fn push(&mut self, path: PathBuf) {
        self.0.push(path);
    }
}

impl Drop for TempGuard {
    fn drop(&mut self) {
        for path in &self.0 {
            let _ = fs::remove_file(path);
        }
    }
}

#[derive(Debug)]
struct UnpackStats {
    entries: u64,
    payload_bytes: u64,
    digest: u64,
}

fn main() -> ExitCode {
    let mut dump_root: Option<PathBuf> = None;
    let mut files: Vec<PathBuf> = Vec::new();
    let mut args = std::env::args().skip(1);
    while let Some(arg) = args.next() {
        match arg.as_str() {
            "-h" | "--help" => {
                print_usage();
                return ExitCode::SUCCESS;
            }
            "-d" | "--dump" => match args.next() {
                Some(dir) => dump_root = Some(PathBuf::from(dir)),
                None => {
                    eprintln!("[error] --dump requires a directory argument");
                    print_usage();
                    return ExitCode::FAILURE;
                }
            },
            other if other.starts_with('-') => {
                eprintln!("[error] unknown option: {other}");
                print_usage();
                return ExitCode::FAILURE;
            }
            other => files.push(PathBuf::from(other)),
        }
    }

    let mut guard = TempGuard(Vec::new());

    let targets: Vec<PathBuf> = if files.is_empty() {
        match build_synthetic_samples(&mut guard) {
            Ok(paths) => {
                println!(
                    "[selftest] no file arguments given; built {} synthetic file(s)",
                    paths.len()
                );
                paths
            }
            Err(error) => {
                eprintln!("[selftest] failed to build samples: {error}");
                return ExitCode::FAILURE;
            }
        }
    } else {
        files
    };

    let mut failures = 0usize;
    for path in &targets {
        match process(path, dump_root.as_deref()) {
            Ok(()) => {}
            Err(error) => {
                eprintln!("[error] {}: {error}", path.display());
                failures += 1;
            }
        }
    }

    if failures == 0 {
        println!(
            "[done ] {} file(s) processed, all verifications passed",
            targets.len()
        );
        ExitCode::SUCCESS
    } else {
        eprintln!("[done ] {failures} file(s) failed");
        ExitCode::FAILURE
    }
}

fn print_usage() {
    println!(
        "usage: reencode_demo [--dump DIR] <file.mdx|file.mdd> [...]

  --dump DIR, -d DIR   also write the unpacked content for debugging:
                       each .mdx becomes DIR/<stem>.txt in the MDict source
                       format (key, </>, definition, </> per entry), and each
                       .mdd becomes DIR/<stem>/ with every resource file
                       under its resource path"
    );
}

fn process(path: &Path, dump_root: Option<&Path>) -> mdictlib::Result<()> {
    let file_bytes = fs::metadata(path)?.len();
    let is_mdd = path
        .extension()
        .is_some_and(|extension| extension.eq_ignore_ascii_case("mdd"));
    println!();
    println!("[open ] {} ({} bytes)", path.display(), file_bytes);

    if is_mdd {
        let resources = MddFile::open(path)?;
        let dump_dir = dump_root.map(|root| root.join(file_stem_of(path)));
        let stats = unpack_mdd(&resources, dump_dir)?;
        println!(
            "[unpack] {} resources, {} payload bytes, hash {:016x}",
            stats.entries, stats.payload_bytes, stats.digest
        );

        let mut reencoded = Vec::new();
        let summary = reencode_mdd(&resources, &mut reencoded)?;
        finish_verification(path, &reencoded, &stats, summary.total_bytes, Kind::Mdd)
    } else {
        let dictionary = MdxFile::open(path)?;
        let dump_txt = dump_root.map(|root| root.join(format!("{}.txt", file_stem_of(path))));
        let stats = unpack_mdx(&dictionary, dump_txt)?;
        println!(
            "[unpack] {} entries, {} payload bytes, hash {:016x}",
            stats.entries, stats.payload_bytes, stats.digest
        );

        let mut reencoded = Vec::new();
        let summary = reencode_mdx(&dictionary, &mut reencoded)?;
        finish_verification(path, &reencoded, &stats, summary.total_bytes, Kind::Mdx)
    }
}

enum Kind {
    Mdx,
    Mdd,
}

fn finish_verification(
    path: &Path,
    reencoded: &[u8],
    _stats: &UnpackStats,
    total_bytes: u64,
    kind: Kind,
) -> mdictlib::Result<()> {
    let original = fs::read(path)?;
    println!(
        "[write ] re-encoded {} bytes (original {} bytes)",
        total_bytes,
        original.len()
    );

    if reencoded == original {
        println!("[verify] byte-identical: yes");
        return Ok(());
    }

    let offset = first_difference(&original, reencoded).expect("equal vectors have no difference");
    println!("[verify] byte-identical: no (first difference at byte {offset})");
    let rebuilt_path = sibling_path(path, "reencoded");
    fs::write(&rebuilt_path, reencoded)?;
    let logical = match kind {
        Kind::Mdx => logical_mdx_equal(path, &rebuilt_path)?,
        Kind::Mdd => logical_mdd_equal(path, &rebuilt_path)?,
    };
    let _ = fs::remove_file(&rebuilt_path);
    if !logical {
        return Err(mdictlib::Error::InvalidData(
            "re-encoded content diverges logically from the source".to_owned(),
        ));
    }
    // Same keys, payloads, and order: the difference is deflate's
    // compressor-specific output, which is the accepted divergence.
    println!("[verify] logical round-trip: identical keys, payloads, and order");
    println!("[verify] difference attributed to zlib re-compression");
    Ok(())
}

fn unpack_mdx(dictionary: &MdxFile, dump_txt: Option<PathBuf>) -> mdictlib::Result<UnpackStats> {
    let mut hasher = DefaultHasher::new();
    let mut payload_bytes = 0u64;
    let mut entries = 0u64;
    let mut dump_file = match &dump_txt {
        Some(target) => {
            if let Some(parent) = target.parent() {
                fs::create_dir_all(parent)?;
            }
            Some((BufWriter::new(File::create(target)?), 0u64))
        }
        None => None,
    };
    for entry in dictionary.entries() {
        let entry = entry?;
        entry.key().hash(&mut hasher);
        entry.text().hash(&mut hasher);
        payload_bytes += entry.text().len() as u64;
        entries += 1;
        if let Some((file, dumped)) = dump_file.as_mut() {
            // Classic MDict source format: key line, marker, definition
            // lines, marker.
            writeln!(file, "{}\n</>\n{}\n</>", entry.key(), entry.text())?;
            *dumped += 1;
        }
    }
    if let Some((mut file, dumped)) = dump_file {
        file.flush()?;
        println!(
            "[dump ] {dumped} entries -> {} (MDict source TXT)",
            dump_txt
                .expect("dump target exists whenever the writer does")
                .display()
        );
    }
    Ok(UnpackStats {
        entries,
        payload_bytes,
        digest: hasher.finish(),
    })
}

fn unpack_mdd(resources: &MddFile, dump_dir: Option<PathBuf>) -> mdictlib::Result<UnpackStats> {
    let mut hasher = DefaultHasher::new();
    let mut payload_bytes = 0u64;
    let mut entries = 0u64;
    let mut dumped = 0u64;
    let mut skipped_names = 0u64;
    for resource in resources.resources() {
        let resource = resource?;
        resource.key().hash(&mut hasher);
        resource.bytes().hash(&mut hasher);
        payload_bytes += resource.bytes().len() as u64;
        entries += 1;
        if let Some(root) = &dump_dir {
            match safe_resource_relative(resource.key()) {
                Some(relative) => {
                    let target = root.join(&relative);
                    if let Some(parent) = target.parent() {
                        fs::create_dir_all(parent)?;
                    }
                    fs::write(&target, resource.bytes())?;
                    dumped += 1;
                }
                None => skipped_names += 1,
            }
        }
    }
    if let Some(root) = &dump_dir {
        println!(
            "[dump ] {dumped} resources -> {} ({} unsafe name(s) skipped)",
            root.display(),
            skipped_names
        );
    }
    Ok(UnpackStats {
        entries,
        payload_bytes,
        digest: hasher.finish(),
    })
}

/// Maps one resource name to a path that stays inside the dump directory:
/// backslashes become separators, empty and `.` components are dropped, and
/// anything that could escape (`..`, drive letters, NUL) rejects the name.
fn safe_resource_relative(name: &str) -> Option<PathBuf> {
    let mut path = PathBuf::new();
    for component in name.replace('\\', "/").split('/') {
        if component.is_empty() || component == "." {
            continue;
        }
        if component == ".." || component.contains(':') || component.contains('\u{0}') {
            return None;
        }
        path.push(component);
    }
    (!path.as_os_str().is_empty()).then_some(path)
}

fn logical_mdx_equal(original: &Path, rebuilt: &Path) -> mdictlib::Result<bool> {
    let left = MdxFile::open(original)?;
    let right = MdxFile::open(rebuilt)?;
    if left.len() != right.len() {
        return Ok(false);
    }
    for (left_entry, right_entry) in left.entries().zip(right.entries()) {
        let left_entry = left_entry?;
        let right_entry = right_entry?;
        if left_entry.key() != right_entry.key() || left_entry.text() != right_entry.text() {
            return Ok(false);
        }
    }
    Ok(true)
}

fn logical_mdd_equal(original: &Path, rebuilt: &Path) -> mdictlib::Result<bool> {
    let left = MddFile::open(original)?;
    let right = MddFile::open(rebuilt)?;
    if left.len() != right.len() {
        return Ok(false);
    }
    for (left_resource, right_resource) in left.resources().zip(right.resources()) {
        let left_resource = left_resource?;
        let right_resource = right_resource?;
        if left_resource.key() != right_resource.key()
            || left_resource.bytes() != right_resource.bytes()
        {
            return Ok(false);
        }
    }
    Ok(true)
}

fn first_difference(left: &[u8], right: &[u8]) -> Option<usize> {
    if left.len() != right.len() {
        // Report the shared-prefix difference; length divergence after a
        // full shared prefix is still a byte difference.
        let shared = left.iter().zip(right.iter()).position(|(a, b)| a != b);
        return Some(shared.unwrap_or(left.len().min(right.len())));
    }
    left.iter().zip(right.iter()).position(|(a, b)| a != b)
}

fn file_stem_of(path: &Path) -> String {
    path.file_stem().map_or_else(
        || "dict".to_owned(),
        |stem| stem.to_string_lossy().into_owned(),
    )
}

fn sibling_path(path: &Path, suffix: &str) -> PathBuf {
    let mut name = file_stem_of(path);
    name.push('-');
    name.push_str(suffix);
    name.push('.');
    name.push_str(
        path.extension()
            .and_then(|extension| extension.to_str())
            .unwrap_or("mdx"),
    );
    path.with_file_name(name)
}

fn build_synthetic_samples(guard: &mut TempGuard) -> mdictlib::Result<Vec<PathBuf>> {
    let dir = std::env::temp_dir();
    let tag = std::process::id();

    let tiny = WriteOptions::new()
        .with_compression(WriteCompression::None)
        .with_key_block_target_bytes(48)
        .with_record_block_target_bytes(48);
    let mut builder = MdxBuilder::with_options(tiny);
    builder.header_attribute("Title", "reencode demo (uncompressed)")?;
    for (key, body) in [
        ("hello", "<p>used as a greeting</p>"),
        ("world", "<p>the earth</p>"),
        ("hello", "<p>a duplicate spelling</p>"),
        ("你好", "<div>中文问候</div>"),
        ("世界", "<div>中文词条</div>"),
        ("a-b", "<i>punctuation key</i>"),
        ("Apple", "<p>capitalized</p>"),
        ("zzz", "last"),
    ] {
        builder.add_entry(key, body)?;
    }
    let uncompressed = dir.join(format!("mdictlib-reencode-demo-{tag}-none.mdx"));
    let mut bytes = Vec::new();
    builder.finish(&mut bytes)?;
    fs::write(&uncompressed, &bytes)?;
    guard.push(uncompressed.clone());

    let zlib_options = WriteOptions::new();
    let mut builder = MdxBuilder::with_options(zlib_options);
    builder.header_attribute("Title", "reencode demo (zlib)")?;
    for (key, body) in [
        ("alpha", "<p>first</p>"),
        ("beta", "<p>second</p>"),
        ("gamma", "<p>third</p>"),
    ] {
        builder.add_entry(key, body)?;
    }
    let compressed = dir.join(format!("mdictlib-reencode-demo-{tag}-zlib.mdx"));
    let mut bytes = Vec::new();
    builder.finish(&mut bytes)?;
    fs::write(&compressed, &bytes)?;
    guard.push(compressed.clone());

    let mut builder =
        MddBuilder::with_options(WriteOptions::new().with_compression(WriteCompression::None));
    builder.add_resource("/style.css", b"body { font-family: serif; }")?;
    builder.add_resource(
        "/logo.png",
        &[0x89, b'P', b'N', b'G', 0x0d, 0x0a, 0x1a, 0x0a],
    )?;
    builder.add_resource("/data.bin", &[0u8; 96])?;
    let resources = dir.join(format!("mdictlib-reencode-demo-{tag}-none.mdd"));
    let mut bytes = Vec::new();
    builder.finish(&mut bytes)?;
    fs::write(&resources, &bytes)?;
    guard.push(resources.clone());

    Ok(vec![uncompressed, compressed, resources])
}