Skip to main content

lindera_dictionary/loader/
prefix_dictionary.rs

1use std::path::Path;
2
3use crate::LinderaResult;
4use crate::dictionary::prefix_dictionary::{DaTrust, PrefixDictionary};
5#[cfg(feature = "mmap")]
6use crate::util::mmap_file;
7use crate::util::read_file;
8
9/// Loader for prefix dictionary data from disk files.
10pub struct PrefixDictionaryLoader {}
11
12impl PrefixDictionaryLoader {
13    /// Load prefix dictionary from files in the specified directory.
14    ///
15    /// Reads dict.da, dict.vals, dict.wordsidx, and dict.words files
16    /// and constructs a PrefixDictionary.
17    ///
18    /// # Arguments
19    ///
20    /// * `input_dir` - Path to the directory containing dictionary files.
21    ///
22    /// # Returns
23    ///
24    /// A `PrefixDictionary` loaded from the files.
25    pub fn load(input_dir: &Path) -> LinderaResult<PrefixDictionary> {
26        let da_data = read_file(input_dir.join("dict.da").as_path())?;
27        let vals_data = read_file(input_dir.join("dict.vals").as_path())?;
28        let words_idx_data = read_file(input_dir.join("dict.wordsidx").as_path())?;
29        let words_data = read_file(input_dir.join("dict.words").as_path())?;
30
31        PrefixDictionary::load(
32            da_data,
33            vals_data,
34            words_idx_data,
35            words_data,
36            true,
37            DaTrust::Untrusted,
38        )
39    }
40
41    /// Load prefix dictionary using memory-mapped files.
42    ///
43    /// Note: only `vals_data`/`words_idx_data`/`words_data` end up genuinely
44    /// mmap-backed (read lazily at lookup time via `Data::Map`). `da_data` is
45    /// still eagerly copied into an owned `DoubleArrayAhoCorasick` by
46    /// [`PrefixDictionary::load`] — daachorse has no zero-copy deserialization
47    /// API — so mmap only avoids the initial file-read syscall/allocation for
48    /// that component, not runtime lazy paging. mmap'd bytes are passed with
49    /// [`DaTrust::Untrusted`], the same as a plain read: they can be
50    /// corrupted or tampered with just as easily as a regular file.
51    ///
52    /// # Arguments
53    ///
54    /// * `input_dir` - Path to the directory containing dictionary files.
55    ///
56    /// # Returns
57    ///
58    /// A `PrefixDictionary` loaded via memory mapping.
59    #[cfg(feature = "mmap")]
60    pub fn load_mmap(input_dir: &Path) -> LinderaResult<PrefixDictionary> {
61        let da_data = mmap_file(input_dir.join("dict.da").as_path())?;
62        let vals_data = mmap_file(input_dir.join("dict.vals").as_path())?;
63        let words_idx_data = mmap_file(input_dir.join("dict.wordsidx").as_path())?;
64        let words_data = mmap_file(input_dir.join("dict.words").as_path())?;
65
66        PrefixDictionary::load(
67            da_data,
68            vals_data,
69            words_idx_data,
70            words_data,
71            true,
72            DaTrust::Untrusted,
73        )
74    }
75}