opendict-rs 0.1.0

Unified Rust reader for StarDict and MDict 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
use std::io::BufRead;
use std::{fs, io, path};

use crate::error::Error;

#[derive(Debug, Clone)]
pub struct Ifo {
    pub author: String,
    pub version: String,
    pub name: String,
    pub date: String,
    pub description: String,
    pub email: String,
    pub web_site: String,
    pub same_type_sequence: String,
    pub idx_file_size: u64,
    pub word_count: usize,
    pub syn_word_count: usize,
    pub idx_offset_bits: u32,
}

impl Ifo {
    pub fn open(file: &path::Path) -> crate::Result<Ifo> {
        let mut it = Ifo {
            author: String::new(),
            version: String::new(),
            name: String::new(),
            date: String::new(),
            description: String::new(),
            email: String::new(),
            web_site: String::new(),
            same_type_sequence: String::new(),
            idx_file_size: 0,
            word_count: 0,
            syn_word_count: 0,
            idx_offset_bits: 32,
        };

        let mut has_name = false;
        let mut has_word_count = false;
        let mut has_idx_file_size = false;
        let mut magic_checked = false;

        for line in io::BufReader::new(fs::File::open(file)?).lines() {
            let line = line?;
            let trimmed = line.trim();
            if trimmed.is_empty() {
                continue;
            }

            if !magic_checked {
                if trimmed != "StarDict's dict ifo file" {
                    return Err(Error::InvalidFormat(format!(
                        "invalid magic line: {}", trimmed
                    )));
                }
                magic_checked = true;
                continue;
            }

            if let Some(id) = trimmed.find('=') {
                let key = trimmed[..id].trim();
                let val = trimmed[id + 1..].trim().to_string();
                match key {
                    "author" => it.author = val,
                    "bookname" => {
                        it.name = val;
                        has_name = true;
                    }
                    "version" => {
                        match val.as_str() {
                            "2.4.2" | "3.0.0" => it.version = val,
                            v => return Err(Error::Unsupported(format!(
                                "unsupported ifo version: {}", v
                            ))),
                        }
                    }
                    "description" => it.description = val,
                    "date" => it.date = val,
                    "idxfilesize" => {
                        it.idx_file_size = val.parse().map_err(|e| {
                            Error::InvalidFormat(format!("invalid idxfilesize: {}", e))
                        })?;
                        has_idx_file_size = true;
                    }
                    "wordcount" => {
                        it.word_count = val.parse().map_err(|e| {
                            Error::InvalidFormat(format!("invalid wordcount: {}", e))
                        })?;
                        has_word_count = true;
                    }
                    "website" => it.web_site = val,
                    "email" => it.email = val,
                    "sametypesequence" => it.same_type_sequence = val,
                    "synwordcount" => {
                        it.syn_word_count = val.parse().map_err(|e| {
                            Error::InvalidFormat(format!("invalid synwordcount: {}", e))
                        })?;
                    }
                    "idxoffsetbits" => {
                        it.idx_offset_bits = val.parse().map_err(|e| {
                            Error::InvalidFormat(format!("invalid idxoffsetbits: {}", e))
                        })?;
                    }
                    _ => {}
                };
            }
        }

        if !has_name {
            return Err(Error::InvalidFormat(
                "missing required field: bookname".into(),
            ));
        }
        if !has_word_count {
            return Err(Error::InvalidFormat(
                "missing required field: wordcount".into(),
            ));
        }
        if !has_idx_file_size {
            return Err(Error::InvalidFormat(
                "missing required field: idxfilesize".into(),
            ));
        }

        Ok(it)
    }
}

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

    fn fixture(name: &str) -> PathBuf {
        PathBuf::from(env!("CARGO_MANIFEST_DIR"))
            .join("tests")
            .join("fixtures")
            .join(name)
    }

    #[test]
    fn rejects_wrong_magic_line() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("bad.ifo");
        std::fs::write(
            &path,
            "Wrong magic line\nversion=3.0.0\nbookname=Test\nwordcount=1\nidxfilesize=10\n",
        )
        .unwrap();
        let result = Ifo::open(&path);
        assert!(result.is_err(), "Should reject wrong magic line");
    }

    #[test]
    fn accepts_correct_magic_line() {
        let result = Ifo::open(&fixture("testdict.ifo"));
        assert!(result.is_ok(), "Should accept correct magic line");
    }

    #[test]
    fn parses_v300() {
        let ifo = Ifo::open(&fixture("testdict.ifo")).unwrap();
        assert_eq!(ifo.version, "3.0.0");
    }

    #[test]
    fn parses_v242() {
        let ifo = Ifo::open(&fixture("v242.ifo")).unwrap();
        assert_eq!(ifo.version, "2.4.2");
    }

    #[test]
    fn rejects_unknown_version() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("bad_ver.ifo");
        std::fs::write(
            &path,
            "StarDict's dict ifo file\nversion=1.0.0\nbookname=Test\nwordcount=1\nidxfilesize=10\n",
        )
        .unwrap();
        let result = Ifo::open(&path);
        assert!(result.is_err(), "Should reject unknown version");
    }

    #[test]
    fn parses_bookname() {
        let ifo = Ifo::open(&fixture("testdict.ifo")).unwrap();
        assert_eq!(ifo.name, "A foo-bar dictionary");
    }

    #[test]
    fn parses_wordcount() {
        let ifo = Ifo::open(&fixture("testdict.ifo")).unwrap();
        assert_eq!(ifo.word_count, 4);
    }

    #[test]
    fn parses_idxfilesize() {
        let ifo = Ifo::open(&fixture("testdict.ifo")).unwrap();
        assert_eq!(ifo.idx_file_size, 60);
    }

    #[test]
    fn parses_sametypesequence() {
        let ifo = Ifo::open(&fixture("testdict.ifo")).unwrap();
        assert_eq!(ifo.same_type_sequence, "m");
    }

    #[test]
    fn parses_description_empty() {
        let ifo = Ifo::open(&fixture("testdict.ifo")).unwrap();
        assert_eq!(ifo.description, "");
    }

    #[test]
    fn parses_v242_bookname() {
        let ifo = Ifo::open(&fixture("v242.ifo")).unwrap();
        assert_eq!(ifo.name, "Test Dict v242");
    }

    #[test]
    fn parses_v242_wordcount() {
        let ifo = Ifo::open(&fixture("v242.ifo")).unwrap();
        assert_eq!(ifo.word_count, 2);
    }

    #[test]
    fn parses_v242_idxfilesize() {
        let ifo = Ifo::open(&fixture("v242.ifo")).unwrap();
        assert_eq!(ifo.idx_file_size, 24);
    }

    #[test]
    fn optional_author_defaults_empty() {
        let ifo = Ifo::open(&fixture("testdict.ifo")).unwrap();
        assert_eq!(ifo.author, "");
    }

    #[test]
    fn optional_email_defaults_empty() {
        let ifo = Ifo::open(&fixture("testdict.ifo")).unwrap();
        assert_eq!(ifo.email, "");
    }

    #[test]
    fn optional_website_defaults_empty() {
        let ifo = Ifo::open(&fixture("testdict.ifo")).unwrap();
        assert_eq!(ifo.web_site, "");
    }

    #[test]
    fn idxoffsetbits_defaults_to_32() {
        let ifo = Ifo::open(&fixture("testdict.ifo")).unwrap();
        assert_eq!(ifo.idx_offset_bits, 32);
    }

    #[test]
    fn parses_idxoffsetbits_when_present() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("bits64.ifo");
        std::fs::write(
            &path,
            "StarDict's dict ifo file\nversion=3.0.0\nbookname=Test\nwordcount=1\nidxfilesize=10\nidxoffsetbits=64\n",
        )
        .unwrap();
        let ifo = Ifo::open(&path).unwrap();
        assert_eq!(ifo.idx_offset_bits, 64);
    }

    #[test]
    fn synwordcount_defaults_to_zero() {
        let ifo = Ifo::open(&fixture("v242.ifo")).unwrap();
        assert_eq!(ifo.syn_word_count, 0);
    }

    #[test]
    fn trims_whitespace_around_equals() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("spaces.ifo");
        std::fs::write(
            &path,
            "StarDict's dict ifo file\nversion=3.0.0\nbookname = Spaced Name \nwordcount = 4 \nidxfilesize = 60 \n",
        )
        .unwrap();
        let ifo = Ifo::open(&path).unwrap();
        assert_eq!(ifo.name, "Spaced Name");
        assert_eq!(ifo.word_count, 4);
        assert_eq!(ifo.idx_file_size, 60);
    }

    #[test]
    fn blank_lines_ignored() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("blanks.ifo");
        std::fs::write(
            &path,
            "StarDict's dict ifo file\n\nversion=3.0.0\n\nbookname=Blanky\n\nwordcount=1\nidxfilesize=10\n\n",
        )
        .unwrap();
        let ifo = Ifo::open(&path).unwrap();
        assert_eq!(ifo.name, "Blanky");
    }

    #[test]
    fn missing_bookname_is_error() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("no_name.ifo");
        std::fs::write(
            &path,
            "StarDict's dict ifo file\nversion=3.0.0\nwordcount=1\nidxfilesize=10\n",
        )
        .unwrap();
        let result = Ifo::open(&path);
        assert!(result.is_err(), "Should error on missing bookname");
    }

    #[test]
    fn missing_wordcount_is_error() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("no_wc.ifo");
        std::fs::write(
            &path,
            "StarDict's dict ifo file\nversion=3.0.0\nbookname=Test\nidxfilesize=10\n",
        )
        .unwrap();
        let result = Ifo::open(&path);
        assert!(result.is_err(), "Should error on missing wordcount");
    }

    #[test]
    fn missing_idxfilesize_is_error() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("no_idx.ifo");
        std::fs::write(
            &path,
            "StarDict's dict ifo file\nversion=3.0.0\nbookname=Test\nwordcount=1\n",
        )
        .unwrap();
        let result = Ifo::open(&path);
        assert!(result.is_err(), "Should error on missing idxfilesize");
    }

    #[test]
    fn wordcount_handles_large_values() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("large.ifo");
        std::fs::write(
            &path,
            "StarDict's dict ifo file\nversion=3.0.0\nbookname=Big\nwordcount=3000000000\nidxfilesize=99999999\n",
        )
        .unwrap();
        let ifo = Ifo::open(&path).unwrap();
        assert_eq!(ifo.word_count, 3_000_000_000);
    }

    #[test]
    fn nonexistent_file_is_io_error() {
        let result = Ifo::open(path::Path::new("/nonexistent/path.ifo"));
        assert!(matches!(result, Err(crate::error::Error::Io(_))));
    }

    #[test]
    fn wrong_magic_is_invalid_format() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("bad.ifo");
        std::fs::write(&path, "Wrong magic\nversion=3.0.0\nbookname=X\nwordcount=1\nidxfilesize=10\n").unwrap();
        let result = Ifo::open(&path);
        assert!(matches!(result, Err(crate::error::Error::InvalidFormat(_))));
    }

    #[test]
    fn unsupported_version_is_unsupported() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("bad_ver.ifo");
        std::fs::write(&path, "StarDict's dict ifo file\nversion=1.0.0\nbookname=X\nwordcount=1\nidxfilesize=10\n").unwrap();
        let result = Ifo::open(&path);
        assert!(matches!(result, Err(crate::error::Error::Unsupported(_))));
    }

    #[test]
    fn missing_bookname_is_invalid_format() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("no_name.ifo");
        std::fs::write(&path, "StarDict's dict ifo file\nversion=3.0.0\nwordcount=1\nidxfilesize=10\n").unwrap();
        let result = Ifo::open(&path);
        assert!(matches!(result, Err(crate::error::Error::InvalidFormat(_))));
    }

    #[test]
    fn invalid_wordcount_is_invalid_format() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("bad_wc.ifo");
        std::fs::write(&path, "StarDict's dict ifo file\nversion=3.0.0\nbookname=X\nwordcount=abc\nidxfilesize=10\n").unwrap();
        let result = Ifo::open(&path);
        assert!(matches!(result, Err(crate::error::Error::InvalidFormat(_))));
    }

    #[test]
    fn parses_all_optional_fields() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("full.ifo");
        std::fs::write(
            &path,
            "StarDict's dict ifo file\n\
             version=3.0.0\n\
             bookname=Full Dict\n\
             wordcount=100\n\
             idxfilesize=5000\n\
             author=Jane Doe\n\
             email=jane@example.com\n\
             website=https://example.com\n\
             description=A test dictionary\n\
             date=2024.01.01\n\
             sametypesequence=m\n\
             synwordcount=10\n\
             idxoffsetbits=64\n",
        )
        .unwrap();
        let ifo = Ifo::open(&path).unwrap();
        assert_eq!(ifo.author, "Jane Doe");
        assert_eq!(ifo.email, "jane@example.com");
        assert_eq!(ifo.web_site, "https://example.com");
        assert_eq!(ifo.description, "A test dictionary");
        assert_eq!(ifo.date, "2024.01.01");
        assert_eq!(ifo.same_type_sequence, "m");
        assert_eq!(ifo.syn_word_count, 10);
        assert_eq!(ifo.idx_offset_bits, 64);
    }
}