Debian Codegraph @

src/MarisaDict.cpp

raw symbols SCIP
1 /*
2 * Open Chinese Convert
3 *
4 * Copyright 2020-2026 Carbo Kuo and contributors
5 *
6 * Licensed under the Apache License, Version 2.0 (the "License");
7 * you may not use this file except in compliance with the License.
8 * You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing, software
13 * distributed under the License is distributed on an "AS IS" BASIS,
14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 * See the License for the specific language governing permissions and
16 * limitations under the License.
17 */
18
19 #include <algorithm>
20 #include <cstring>
21 #include <stdexcept>
22 #include <unordered_map>
23
24 #include "marisa.h"
25
26 #include "Lexicon.hpp"
27 #include "MarisaDict.hpp"
28 #include "SerializedValues.hpp"
29
30 using namespace opencc;
31
32 namespace {
33 static const char* OCD2_HEADER = "OPENCC_MARISA_0.2.5";
34 }
35
36 class MarisaDict::MarisaInternal {
37 public:
38 std::unique_ptr<marisa::Trie> marisa;
39 std::string mappedBuffer;
40
41 MarisaInternal() : marisa(new marisa::Trie()) {}
42 };
43
44 MarisaDict::MarisaDict()
45 : maxLength(128), lexiconReconstructed(false), internal(new MarisaInternal()) {}
46
47 MarisaDict::~MarisaDict() {}
48
49 size_t MarisaDict::KeyMaxLength() const {
50 ReconstructLexicon();
51 return maxLength;
52 }
53
54 Optional<const DictEntry*> MarisaDict::Match(const char* word,
55 size_t len) const {
56 ReconstructLexicon();
57 if (len > maxLength) {
58 return Optional<const DictEntry*>::Null();
59 }
60 const marisa::Trie& trie = *internal->marisa;
61 marisa::Agent agent;
62 agent.set_query(word, len);
63 if (trie.lookup(agent)) {
64 return Optional<const DictEntry*>(lexicon->At(agent.key().id()));
65 } else {
66 return Optional<const DictEntry*>::Null();
67 }
68 }
69
70 Optional<const DictEntry*> MarisaDict::MatchPrefix(const char* word,
71 size_t len) const {
72 ReconstructLexicon();
73 const marisa::Trie& trie = *internal->marisa;
74 marisa::Agent agent;
75 agent.set_query(word, (std::min)(maxLength, len));
76 const DictEntry* match = nullptr;
77 while (trie.common_prefix_search(agent)) {
78 match = lexicon->At(agent.key().id());
79 }
80 if (match == nullptr) {
81 return Optional<const DictEntry*>::Null();
82 } else {
83 return Optional<const DictEntry*>(match);
84 }
85 }
86
87 std::vector<const DictEntry*> MarisaDict::MatchAllPrefixes(const char* word,
88 size_t len) const {
89 ReconstructLexicon();
90 const marisa::Trie& trie = *internal->marisa;
91 marisa::Agent agent;
92 agent.set_query(word, (std::min)(maxLength, len));
93 std::vector<const DictEntry*> matches;
94 while (trie.common_prefix_search(agent)) {
95 matches.push_back(lexicon->At(agent.key().id()));
96 }
97 std::reverse(matches.begin(), matches.end());
98 return matches;
99 }
100
101 LexiconPtr MarisaDict::GetLexicon() const {
102 ReconstructLexicon();
103 return lexicon;
104 }
105
106 void MarisaDict::ReconstructLexicon() const {
107 if (lexiconReconstructed.load(std::memory_order_acquire)) {
108 return;
109 }
110 std::lock_guard<std::mutex> lock(lexiconMutex);
111 if (lexiconReconstructed.load(std::memory_order_relaxed)) {
112 return;
113 }
114 if (!valuesLexicon) {
115 lexiconReconstructed.store(true, std::memory_order_release);
116 return;
117 }
118 marisa::Agent agent;
119 agent.set_query("");
120 std::vector<std::unique_ptr<DictEntry>> entries;
121 entries.resize(valuesLexicon->Length());
122 size_t maxLen = 0;
123 try {
124 while (internal->marisa->predictive_search(agent)) {
125 const std::string key(agent.key().ptr(), agent.key().length());
126 size_t id = agent.key().id();
127 if (id >= entries.size()) {
128 throw InvalidFormat(
129 "Invalid OpenCC Marisa dictionary (key id out of bounds)");
130 }
131 maxLen = (std::max)(key.length(), maxLen);
132 std::unique_ptr<DictEntry> entry(
133 DictEntryFactory::New(key, valuesLexicon->At(id)->Values()));
134 entries[id] = std::move(entry);
135 }
136 } catch (const std::exception& e) {
137 throw InvalidFormat(std::string("Invalid OpenCC Marisa dictionary: ") +
138 e.what());
139 }
140 lexicon.reset(new Lexicon(std::move(entries)));
141 maxLength = maxLen;
142 lexiconReconstructed.store(true, std::memory_order_release);
143 }
144
145 MarisaDictPtr MarisaDict::NewFromFile(FILE* fp) {
146 // Verify file header
147 size_t headerLen = strlen(OCD2_HEADER);
148 void* buffer = malloc(sizeof(char) * headerLen);
149 size_t bytesRead = fread(buffer, sizeof(char), headerLen, fp);
150 if (bytesRead != headerLen || memcmp(buffer, OCD2_HEADER, headerLen) != 0) {
151 throw InvalidFormat("Invalid OpenCC dictionary header");
152 }
153 free(buffer);
154 long trieOffset = ftell(fp);
155 fseek(fp, 0L, SEEK_END);
156 long fileEnd = ftell(fp);
157 fseek(fp, trieOffset, SEEK_SET);
158 size_t remainingSize =
159 (fileEnd > trieOffset) ? static_cast<size_t>(fileEnd - trieOffset) : 0;
160
161 MarisaDictPtr dict(new MarisaDict());
162 if (remainingSize > 0) {
163 dict->internal->mappedBuffer.resize(remainingSize);
164 bytesRead = fread(&dict->internal->mappedBuffer[0],
165 sizeof(char), remainingSize, fp);
166 if (bytesRead != remainingSize) {
167 throw InvalidFormat("Invalid OpenCC Marisa dictionary.");
168 }
169 }
170
171 dict->LoadFromMappedBuffer();
172 return dict;
173 }
174
175 MarisaDictPtr MarisaDict::NewFromBuffer(const char* data, size_t size) {
176 // Verify file header
177 size_t headerLen = strlen(OCD2_HEADER);
178 if (size < headerLen || memcmp(data, OCD2_HEADER, headerLen) != 0) {
179 throw InvalidFormat("Invalid OpenCC dictionary header");
180 }
181
182 size_t remainingSize = size - headerLen;
183 MarisaDictPtr dict(new MarisaDict());
184 dict->internal->mappedBuffer.assign(data + headerLen, remainingSize);
185
186 dict->LoadFromMappedBuffer();
187 return dict;
188 }
189
190 void MarisaDict::LoadFromMappedBuffer() {
191 try {
192 internal->marisa->map(internal->mappedBuffer.data(),
193 internal->mappedBuffer.size());
194 } catch (const std::exception& e) {
195 throw InvalidFormat(std::string("Invalid OpenCC Marisa dictionary: ") +
196 e.what());
197 }
198
199 const size_t trieSize = internal->marisa->io_size();
200 if (trieSize > internal->mappedBuffer.size()) {
201 throw InvalidFormat(
202 "Invalid OpenCC Marisa dictionary (trie exceeds file size)");
203 }
204
205 size_t valuesBytesRead = 0;
206 std::shared_ptr<SerializedValues> serialized_values =
207 SerializedValues::NewFromBuffer(
208 internal->mappedBuffer.data() + trieSize,
209 internal->mappedBuffer.size() - trieSize, &valuesBytesRead);
210 valuesLexicon = serialized_values->GetLexicon();
211 // Validate key count consistency
212 size_t numKeys = internal->marisa->num_keys();
213 if (numKeys != valuesLexicon->Length()) {
214 throw InvalidFormat(
215 "Invalid OpenCC Marisa dictionary (key count mismatch)");
216 }
217 maxLength = 128;
218 lexiconReconstructed.store(false, std::memory_order_release);
219 }
220
221
222 MarisaDictPtr MarisaDict::NewFromDict(const Dict& thatDict) {
223 // Extract lexicon into marisa::Keyset and a map.
224 const LexiconPtr& thatLexicon = thatDict.GetLexicon();
225 size_t maxLength = 0;
226 marisa::Keyset keyset;
227 std::unordered_map<std::string, std::unique_ptr<DictEntry>> key_value_map;
228 for (size_t i = 0; i < thatLexicon->Length(); i++) {
229 const DictEntry* entry = thatLexicon->At(i);
230 keyset.push_back(entry->Key().c_str());
231 key_value_map[entry->Key()].reset(DictEntryFactory::New(entry));
232 maxLength = (std::max)(entry->KeyLength(), maxLength);
233 }
234 // Build Marisa Trie
235 MarisaDictPtr dict(new MarisaDict());
236 dict->internal->marisa->build(keyset);
237 // Extract lexicon from built Marisa Trie, in order to get the order of keys.
238 marisa::Agent agent;
239 agent.set_query("");
240 std::vector<std::unique_ptr<DictEntry>> entries;
241 entries.resize(thatLexicon->Length());
242 while (dict->internal->marisa->predictive_search(agent)) {
243 std::string key(agent.key().ptr(), agent.key().length());
244 std::unique_ptr<DictEntry> entry = std::move(key_value_map[key]);
245 entries[agent.key().id()] = std::move(entry);
246 }
247 // Set lexicon with entries ordered by Marisa Trie key id.
248 dict->lexicon.reset(new Lexicon(std::move(entries)));
249 dict->maxLength = maxLength;
250 dict->lexiconReconstructed.store(true, std::memory_order_release);
251 return dict;
252 }
253
254 void MarisaDict::SerializeToFile(FILE* fp) const {
255 fwrite(OCD2_HEADER, sizeof(char), strlen(OCD2_HEADER), fp);
256 marisa::fwrite(fp, *internal->marisa);
257 std::unique_ptr<SerializedValues> serialized_values(
258 new SerializedValues(GetLexicon()));
259 serialized_values->SerializeToFile(fp);
260 }
261 PrefixMatchView MarisaDict::MatchPrefixValue(const char* word,
262 size_t len) const {
263 const marisa::Trie* trie = internal->marisa.get();
264 if (trie == nullptr) {
265 return PrefixMatchView{};
266 }
267 static thread_local marisa::Agent agent;
268 agent.set_query(word, len);
269 bool matched = false;
270 size_t matchedId = 0;
271 size_t matchedLength = 0;
272 while (trie->common_prefix_search(agent)) {
273 const size_t currentLength = agent.key().length();
274 if (!matched || currentLength > matchedLength) {
275 matched = true;
276 matchedId = agent.key().id();
277 matchedLength = currentLength;
278 }
279 }
280 if (!matched) {
281 return PrefixMatchView{};
282 }
283 // value view points directly into the DictEntry's owned string storage,
284 // valid for the lifetime of this dictionary.
285 if (valuesLexicon != nullptr) {
286 if (matchedId < valuesLexicon->Length()) {
287 return PrefixMatchView{true, matchedLength,
288 std::string_view(word, matchedLength),
289 valuesLexicon->At(matchedId)->GetDefaultView()};
290 }
291 return PrefixMatchView{};
292 }
293 LexiconPtr lex = GetLexicon();
294 if (lex != nullptr && matchedId < lex->Length()) {
295 return PrefixMatchView{true, matchedLength,
296 std::string_view(word, matchedLength),
297 lex->At(matchedId)->GetDefaultView()};
298 }
299 return PrefixMatchView{};
300 }