Skip to main content

sudachi/dic/build/
index.rs

1/*
2 *  Copyright (c) 2021-2026 Works Applications Co., Ltd.
3 *
4 *  Licensed under the Apache License, Version 2.0 (the "License");
5 *  you may not use this file except in compliance with the License.
6 *  You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 *   Unless required by applicable law or agreed to in writing, software
11 *  distributed under the License is distributed on an "AS IS" BASIS,
12 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 *  See the License for the specific language governing permissions and
14 *  limitations under the License.
15 */
16
17use crate::dic::build::error::{BuildFailure, DicBuildError};
18use crate::dic::word_id::WordId;
19use crate::error::{SudachiError, SudachiResult};
20use crate::util::fxhash::FxBuildHasher;
21use indexmap::map::IndexMap;
22
23pub struct IndexEntry {
24    ids: Vec<WordId>,
25    offset: usize,
26}
27
28impl Default for IndexEntry {
29    fn default() -> Self {
30        Self {
31            ids: Vec::new(),
32            offset: usize::MAX,
33        }
34    }
35}
36
37pub struct IndexBuilder<'a> {
38    // Insertion order matters for the built dictionary,
39    // so using IndexMap here instead of a simple HashMap
40    data: IndexMap<&'a str, IndexEntry, FxBuildHasher>,
41}
42
43impl<'a> IndexBuilder<'a> {
44    pub fn new() -> Self {
45        Self {
46            data: IndexMap::default(),
47        }
48    }
49
50    pub fn add(&mut self, key: &'a str, id: WordId) {
51        self.data.entry(key).or_default().ids.push(id)
52    }
53
54    pub fn build_word_id_table(&mut self, non_indexed: &[WordId]) -> SudachiResult<Vec<u8>> {
55        // by default assume that there will be 3 entries on average
56        let mut result =
57            Vec::with_capacity((self.data.len() + usize::from(!non_indexed.is_empty())) * 13);
58        for (k, entry) in self.data.iter_mut() {
59            entry.offset = result.len();
60            // clear stored ids memory after use
61            let ids = std::mem::take(&mut entry.ids);
62            write_delta_varint_word_ids(&mut result, &ids).map_err(|e| {
63                SudachiError::DictionaryCompilationError(DicBuildError {
64                    cause: e,
65                    line: 0,
66                    file: format!("<word id table for `{}` has too much entries>", k),
67                })
68            })?;
69        }
70        if !non_indexed.is_empty() {
71            write_delta_varint_word_ids(&mut result, non_indexed).map_err(|e| {
72                SudachiError::DictionaryCompilationError(DicBuildError {
73                    cause: e,
74                    line: 0,
75                    file: "<word id table for non-indexed entries has too much entries>".to_owned(),
76                })
77            })?;
78        }
79        Ok(result)
80    }
81
82    pub fn build_trie(&mut self) -> SudachiResult<Vec<u8>> {
83        let mut trie_entries: Vec<(&str, u32)> = Vec::new();
84        for (k, v) in self.data.drain(..) {
85            if v.offset > u32::MAX as _ {
86                return Err(DicBuildError {
87                    file: format!("entry {}", k),
88                    line: 0,
89                    cause: BuildFailure::WordIdTableNotBuilt,
90                }
91                .into());
92            }
93            trie_entries.push((k, v.offset as u32));
94        }
95        self.data.shrink_to_fit();
96        trie_entries.sort_by(|(a, _), (b, _)| a.cmp(b));
97
98        let trie = yada::builder::DoubleArrayBuilder::build(&trie_entries);
99        match trie {
100            Some(t) => Ok(t),
101            None => Err(DicBuildError {
102                file: "<trie>".to_owned(),
103                line: 0,
104                cause: BuildFailure::TrieBuildFailure,
105            }
106            .into()),
107        }
108    }
109}
110
111fn write_delta_varint_word_ids(dst: &mut Vec<u8>, ids: &[WordId]) -> Result<(), BuildFailure> {
112    write_varint32(dst, ids.len() as u32);
113    let mut prev = 0u32;
114    for wid in ids {
115        let current = wid.entry().as_raw();
116        let delta = current.saturating_sub(prev);
117        write_varint32(dst, delta);
118        prev = current;
119    }
120    Ok(())
121}
122
123fn write_varint32(dst: &mut Vec<u8>, mut value: u32) {
124    loop {
125        if (value & !0x7f) == 0 {
126            dst.push(value as u8);
127            return;
128        }
129        dst.push((value as u8 & 0x7f) | 0x80);
130        value >>= 7;
131    }
132}
133
134#[cfg(test)]
135mod test {
136    use super::*;
137    use crate::dic::lexicon::trie::{Trie, TrieEntry};
138    use crate::dic::lexicon::word_id_table::WordIdTable;
139    use crate::dic::word_id::EntryId;
140    use std::convert::TryInto;
141
142    fn make_trie(data: Vec<u8>) -> Trie<'static> {
143        let mut elems: Vec<u32> = Vec::with_capacity(data.len() / 4);
144        for i in (0..data.len()).step_by(4) {
145            let arr: [u8; 4] = data[i..i + 4].try_into().unwrap();
146            elems.push(u32::from_le_bytes(arr))
147        }
148        Trie::new_owned(elems)
149    }
150
151    #[test]
152    fn build_index_1() {
153        let mut bldr = IndexBuilder::new();
154        bldr.add("test", WordId::new(0, 0));
155        let _ = bldr.build_word_id_table(&[]).unwrap();
156
157        let trie = make_trie(bldr.build_trie().unwrap());
158        let mut iter = trie.common_prefix_iterator(b"test", 0);
159        assert_eq!(iter.next(), Some(TrieEntry { value: 0, end: 4 }));
160        assert_eq!(iter.next(), None);
161    }
162
163    #[test]
164    fn build_index_2() {
165        let mut bldr = IndexBuilder::new();
166        bldr.add("test", WordId::new(0, 0));
167        bldr.add("tes", WordId::new(0, 1));
168        let _ = bldr.build_word_id_table(&[]).unwrap();
169
170        let trie = make_trie(bldr.build_trie().unwrap());
171        let mut iter = trie.common_prefix_iterator(b"test", 0);
172        assert_eq!(iter.next(), Some(TrieEntry { value: 2, end: 3 }));
173        assert_eq!(iter.next(), Some(TrieEntry { value: 0, end: 4 }));
174        assert_eq!(iter.next(), None);
175    }
176
177    #[test]
178    fn word_id_table_includes_non_indexed_entries() {
179        let mut bldr = IndexBuilder::new();
180        bldr.add("a", WordId::new(0, 4));
181        bldr.add("b", WordId::new(0, 8));
182
183        let table = bldr
184            .build_word_id_table(&[WordId::new(0, 12), WordId::new(0, 16)])
185            .unwrap();
186
187        let all: Vec<_> = WordIdTable::from_bytes(&table).all_entries().collect();
188        assert_eq!(
189            all,
190            vec![
191                EntryId::new(4),
192                EntryId::new(8),
193                EntryId::new(12),
194                EntryId::new(16),
195            ]
196        );
197    }
198}