Debian Codegraph @

src/DartsDict.cpp

raw symbols ◀ ▶ SCIP
1 Debian patch touch this file
1 /*
2 * Open Chinese Convert
3 *
4 * Copyright 2010-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 <cstdint>
21 #include <cstring>
22 #include <memory>
23
24 #include "BinaryDict.hpp"
25 #include "DartsDict.hpp"
26 #include "Dict.hpp"
27 #include "Lexicon.hpp"
28 #include "darts.h"
29
30 using namespace opencc;
31
32 static const char* OCDHEADER = "OPENCCDARTS1";
33
34 // Minimal reader for legacy OPENCCDARTS1 files built on 64-bit platforms,
35 // where id_type was size_t (8 bytes). The bit layout of each unit is the
36 // same as the 32-bit case; old files simply zero-extend every unit to 64 bits.
37 namespace {
38
39 struct LegacyUnit64 {
40 uint64_t unit;
41 bool has_leaf() const { return ((unit >> 8) & 1) == 1; }
42 int value() const {
43 return static_cast<int>(unit & ((1U << 31) - 1));
44 }
45 uint64_t label() const { return unit & ((1U << 31) | 0xFF); }
46 uint64_t offset() const {
47 return (unit >> 10) << ((unit & (1U << 9)) >> 6);
48 }
49 };
50
51 int Legacy64ExactMatch(const LegacyUnit64* arr, const char* key, size_t len) {
52 size_t pos = 0;
53 for (size_t i = 0; i < len; ++i) {
54 uint64_t c = static_cast<unsigned char>(key[i]);
55 pos ^= static_cast<size_t>(arr[pos].offset() ^ c);
56 if (arr[pos].label() != c) return -1;
57 }
58 if (!arr[pos].has_leaf()) return -1;
59 return arr[pos ^ static_cast<size_t>(arr[pos].offset())].value();
60 }
61
62 // Returns number of matches found; fills results[] with values (shortest to
63 // longest). Mirror of Darts::DoubleArray::commonPrefixSearch value-only form.
64 size_t Legacy64PrefixSearch(const LegacyUnit64* arr, const char* key,
65 size_t maxLen, int* results, size_t maxResults) {
66 size_t count = 0;
67 size_t pos = 0;
68 for (size_t i = 0; i < maxLen; ++i) {
69 uint64_t c = static_cast<unsigned char>(key[i]);
70 pos ^= static_cast<size_t>(arr[pos].offset() ^ c);
71 if (arr[pos].label() != c) break;
72 if (arr[pos].has_leaf()) {
73 if (count < maxResults) {
74 results[count] = arr[pos ^ static_cast<size_t>(arr[pos].offset())].value();
75 }
76 ++count;
77 }
78 }
79 return count;
80 }
81
82 // Mirror of Darts::DoubleArray::validate(); checks root sanity, offset bounds,
83 // and leaf value bounds to catch malformed legacy files before any traversal.
84 bool ValidateLegacy64(const LegacyUnit64* arr, size_t numUnits, int maxValueLimit) {
85 if (numUnits == 0) return false;
86 if (arr[0].label() != 0 || arr[0].has_leaf() || arr[0].offset() == 0) return false;
87 if (((static_cast<size_t>(arr[0].offset())) | 0xFFu) >= numUnits) return false;
88 for (size_t i = 1; i < numUnits; ++i) {
89 uint64_t lbl = arr[i].label();
90 if (lbl <= 0xFF) {
91 if (((i ^ static_cast<size_t>(arr[i].offset())) | 0xFFu) >= numUnits) return false;
92 } else if (maxValueLimit >= 0) {
93 if (arr[i].value() >= maxValueLimit) return false;
94 }
95 }
96 return true;
97 }
98
99 } // namespace
100
101 class DartsDict::DartsInternal {
102 public:
103 BinaryDictPtr binary;
104 void* buffer;
105 Darts::DoubleArray* doubleArray; // 32-bit files (new, or old 32-bit platform)
106 const LegacyUnit64* legacyArray64; // old 64-bit files; points into buffer
107
108 DartsInternal()
109 : binary(nullptr), buffer(nullptr), doubleArray(nullptr),
110 legacyArray64(nullptr) {}
111
112 ~DartsInternal() {
113 if (buffer != nullptr) {
114 free(buffer);
115 }
116 delete doubleArray;
117 // legacyArray64 aliases buffer — no separate free
118 }
119 };
120
121 DartsDict::DartsDict() { internal = new DartsInternal; }
122
123 DartsDict::~DartsDict() { delete internal; }
124
125 size_t DartsDict::KeyMaxLength() const { return maxLength; }
126
127 Optional<const DictEntry*> DartsDict::Match(const char* word,
128 size_t len) const {
129 if (len > maxLength) {
130 return Optional<const DictEntry*>::Null();
131 }
132 if (internal->legacyArray64 != nullptr) {
133 int val = Legacy64ExactMatch(internal->legacyArray64, word, len);
134 if (val != -1) {
135 return Optional<const DictEntry*>(lexicon->At(static_cast<size_t>(val)));
136 }
137 return Optional<const DictEntry*>::Null();
138 }
139 Darts::DoubleArray& dict = *internal->doubleArray;
140 Darts::DoubleArray::result_pair_type result;
141 dict.exactMatchSearch(word, result, len);
142 if (result.value != -1) {
143 return Optional<const DictEntry*>(
144 lexicon->At(static_cast<size_t>(result.value)));
145 }
146 return Optional<const DictEntry*>::Null();
147 }
148
149 Optional<const DictEntry*> DartsDict::MatchPrefix(const char* word,
150 size_t len) const {
151 const size_t DEFAULT_NUM_ENTRIES = 64;
152 size_t searchLen = (std::min)(maxLength, len);
153
154 if (internal->legacyArray64 != nullptr) {
155 int results[DEFAULT_NUM_ENTRIES];
156 size_t numMatched = Legacy64PrefixSearch(
157 internal->legacyArray64, word, searchLen, results, DEFAULT_NUM_ENTRIES);
158 if (numMatched == 0) {
159 return Optional<const DictEntry*>::Null();
160 }
161 int maxVal;
162 if (numMatched < DEFAULT_NUM_ENTRIES) {
163 maxVal = results[numMatched - 1];
164 } else {
165 std::vector<int> rematchedResults(numMatched);
166 numMatched = Legacy64PrefixSearch(internal->legacyArray64, word,
167 searchLen, rematchedResults.data(),
168 rematchedResults.size());
169 maxVal = rematchedResults[numMatched - 1];
170 }
171 if (maxVal >= 0) {
172 return Optional<const DictEntry*>(
173 lexicon->At(static_cast<size_t>(maxVal)));
174 }
175 return Optional<const DictEntry*>::Null();
176 }
177
178 Darts::DoubleArray& dict = *internal->doubleArray;
179 Darts::DoubleArray::value_type results[DEFAULT_NUM_ENTRIES];
180 Darts::DoubleArray::value_type maxMatchedResult;
181 size_t numMatched =
182 dict.commonPrefixSearch(word, results, DEFAULT_NUM_ENTRIES, searchLen);
183 if (numMatched == 0) {
184 return Optional<const DictEntry*>::Null();
185 } else if (numMatched < DEFAULT_NUM_ENTRIES) {
186 maxMatchedResult = results[numMatched - 1];
187 } else {
188 Darts::DoubleArray::value_type* rematchedResults =
189 new Darts::DoubleArray::value_type[numMatched];
190 numMatched = dict.commonPrefixSearch(word, rematchedResults, numMatched,
191 searchLen);
192 maxMatchedResult = rematchedResults[numMatched - 1];
193 delete[] rematchedResults;
194 }
195 if (maxMatchedResult >= 0) {
196 return Optional<const DictEntry*>(
197 lexicon->At(static_cast<size_t>(maxMatchedResult)));
198 }
199 return Optional<const DictEntry*>::Null();
200 }
201
202 LexiconPtr DartsDict::GetLexicon() const { return lexicon; }
203
204 PrefixMatchView DartsDict::MatchPrefixValue(const char* word,
205 size_t len) const {
206 Optional<const DictEntry*> matched = MatchPrefix(word, len);
207 if (matched.IsNull()) {
208 return PrefixMatchView{};
209 }
210 const DictEntry* entry = matched.Get();
211 const size_t keyLen = entry->KeyLength();
212 return PrefixMatchView{true, keyLen, std::string_view(word, keyLen),
213 entry->GetDefaultView()};
214 }
215
216 DartsDictPtr DartsDict::NewFromFile(FILE* fp) {
217 DartsDictPtr dict(new DartsDict());
218 auto internal = dict->internal;
219
220 size_t headerLen = strlen(OCDHEADER);
221 std::vector<char> headerBuffer(headerLen);
222 size_t bytesRead = fread(headerBuffer.data(), sizeof(char), headerLen, fp);
223 if (bytesRead != headerLen || memcmp(headerBuffer.data(), OCDHEADER, headerLen) != 0) {
224 throw InvalidFormat("Invalid OpenCC dictionary header");
225 }
226
227 // Measure remaining bytes for bounds checking
228 long currentOffset = ftell(fp);
229 fseek(fp, 0L, SEEK_END);
230 long fileEnd = ftell(fp);
231 fseek(fp, currentOffset, SEEK_SET);
232 size_t remainingSize =
233 (fileEnd > currentOffset)
234 ? static_cast<size_t>(fileEnd - currentOffset)
235 : 0;
236
•237 // Detect the dartsSize field width by reading 8 bytes.
238 // - Old 64-bit build: dartsSize field is uint64_t (8 bytes); high 32 bits
•239 // are zero for any realistic file size.
240 // - Current build (any word size) or old 32-bit build: dartsSize field is
•241 // uint32_t (4 bytes); the other half of the probe is either the first
242 // 4 bytes of the darts array (non-zero for any valid array whose root
243 // unit has a non-zero offset) or dartsSize itself, so the native
244 // uint64_t load has non-zero high bits.
245 uint8_t probe[8];
246 if (fread(probe, 1, 8, fp) != 8) {
247 throw InvalidFormat("Invalid OpenCC dictionary header (dartsSize)");
248 }
•249 bool is64bit = LooksLikeLegacy64Field(probe);
250
251 if (is64bit) {
252 uint64_t dartsSize64;
253 memcpy(&dartsSize64, probe, 8);
254 size_t dartsSize = static_cast<size_t>(dartsSize64);
255 if (dartsSize > remainingSize) {
256 throw InvalidFormat(
257 "Invalid OpenCC dictionary (dartsSize exceeds file size)");
258 }
259 if (dartsSize % sizeof(LegacyUnit64) != 0) {
260 throw InvalidFormat("Invalid legacy OCD dictionary unit alignment");
261 }
262 std::unique_ptr<void, decltype(&free)> buffer(malloc(dartsSize), free);
263 if (!buffer) {
264 throw std::bad_alloc();
265 }
266 bytesRead = fread(buffer.get(), 1, dartsSize, fp);
267 if (bytesRead != dartsSize) {
268 throw InvalidFormat("Invalid legacy OCD dictionary size mismatch");
269 }
270
271 BinaryDictPtr binary = BinaryDict::NewFromFile(fp);
272
273 internal->buffer = buffer.release();
274 internal->binary = std::move(binary);
275 internal->legacyArray64 = static_cast<const LegacyUnit64*>(internal->buffer);
276
277 dict->lexicon = internal->binary->GetLexicon();
278 dict->maxLength = internal->binary->KeyMaxLength();
279 size_t numUnits = dartsSize / sizeof(LegacyUnit64);
280 if (!ValidateLegacy64(internal->legacyArray64, numUnits,
281 static_cast<int>(dict->lexicon->Length()))) {
282 throw InvalidFormat("Invalid legacy OCD dictionary darts data");
283 }
284 return dict;
285 }
286
287 // Fixed-width layout: dartsSize is the first 4 bytes of probe; remaining 4
288 // bytes belong to the array, so seek back.
289 fseek(fp, -4, SEEK_CUR);
290 uint32_t dartsSize32;
291 memcpy(&dartsSize32, probe, 4);
292 size_t dartsSize = dartsSize32;
293 if (dartsSize > remainingSize) {
294 throw InvalidFormat(
295 "Invalid OpenCC dictionary (dartsSize exceeds file size)");
296 }
297 std::unique_ptr<Darts::DoubleArray> doubleArray(new Darts::DoubleArray());
298 if (dartsSize % doubleArray->unit_size() != 0) {
299 throw InvalidFormat("Invalid OpenCC dictionary size of darts alignment");
300 }
301 std::unique_ptr<void, decltype(&free)> buffer(malloc(dartsSize), free);
302 if (!buffer) {
303 throw std::bad_alloc();
304 }
305 bytesRead = fread(buffer.get(), 1, dartsSize, fp);
306 if (bytesRead != dartsSize) {
307 throw InvalidFormat("Invalid OpenCC dictionary size of darts mismatch");
308 }
309 doubleArray->set_array(buffer.get(), dartsSize / doubleArray->unit_size());
310
311 BinaryDictPtr binary = BinaryDict::NewFromFile(fp);
312
313 internal->buffer = buffer.release();
314 internal->doubleArray = doubleArray.release();
315 internal->binary = std::move(binary);
316
317 dict->lexicon = internal->binary->GetLexicon();
318 dict->maxLength = internal->binary->KeyMaxLength();
319 if (!internal->doubleArray->validate(static_cast<Darts::DoubleArray::value_type>(
320 dict->lexicon->Length()))) {
321 throw InvalidFormat("Invalid OpenCC dictionary darts data");
322 }
323 return dict;
324 }
325
326 DartsDictPtr DartsDict::NewFromBuffer(const char* data, size_t size) {
327 DartsDictPtr dict(new DartsDict());
328 auto internal = dict->internal;
329
330 size_t headerLen = strlen(OCDHEADER);
331 if (size < headerLen || memcmp(data, OCDHEADER, headerLen) != 0) {
332 throw InvalidFormat("Invalid OpenCC dictionary header");
333 }
334 size_t offset = headerLen;
335
336 if (size - offset < 8) {
337 throw InvalidFormat("Invalid OpenCC dictionary header (dartsSize)");
338 }
339 uint8_t probe[8];
340 memcpy(probe, data + offset, 8);
341 offset += 8;
•342 bool is64bit = LooksLikeLegacy64Field(probe);
343
344 if (is64bit) {
345 uint64_t dartsSize64;
346 memcpy(&dartsSize64, probe, 8);
347 size_t dartsSize = static_cast<size_t>(dartsSize64);
348 if (dartsSize > size - offset) {
349 throw InvalidFormat(
350 "Invalid OpenCC dictionary (dartsSize exceeds file size)");
351 }
352 if (dartsSize % sizeof(LegacyUnit64) != 0) {
353 throw InvalidFormat("Invalid legacy OCD dictionary unit alignment");
354 }
355 std::unique_ptr<void, decltype(&free)> buffer(malloc(dartsSize), free);
356 if (!buffer) {
357 throw std::bad_alloc();
358 }
359 memcpy(buffer.get(), data + offset, dartsSize);
360 offset += dartsSize;
361
362 BinaryDictPtr binary = BinaryDict::NewFromBuffer(data + offset, size - offset);
363
364 internal->buffer = buffer.release();
365 internal->binary = std::move(binary);
366 internal->legacyArray64 = static_cast<const LegacyUnit64*>(internal->buffer);
367
368 dict->lexicon = internal->binary->GetLexicon();
369 dict->maxLength = internal->binary->KeyMaxLength();
370 size_t numUnits = dartsSize / sizeof(LegacyUnit64);
371 if (!ValidateLegacy64(internal->legacyArray64, numUnits,
372 static_cast<int>(dict->lexicon->Length()))) {
373 throw InvalidFormat("Invalid legacy OCD dictionary darts data");
374 }
375 return dict;
376 }
377
378 // Fixed-width layout: dartsSize is the first 4 bytes of probe; probe[4..7]
379 // belong to the darts array, so rewind 4 bytes before reading the array.
380 uint32_t dartsSize32;
381 memcpy(&dartsSize32, probe, 4);
382 size_t dartsSize = dartsSize32;
383 offset -= 4;
384 if (dartsSize > size - offset) {
385 throw InvalidFormat(
386 "Invalid OpenCC dictionary (dartsSize exceeds file size)");
387 }
388 std::unique_ptr<Darts::DoubleArray> doubleArray(new Darts::DoubleArray());
389 if (dartsSize % doubleArray->unit_size() != 0) {
390 throw InvalidFormat("Invalid OpenCC dictionary size of darts alignment");
391 }
392 std::unique_ptr<void, decltype(&free)> buffer(malloc(dartsSize), free);
393 if (!buffer) {
394 throw std::bad_alloc();
395 }
396 memcpy(buffer.get(), data + offset, dartsSize);
397 offset += dartsSize;
398 doubleArray->set_array(buffer.get(), dartsSize / doubleArray->unit_size());
399
400 BinaryDictPtr binary = BinaryDict::NewFromBuffer(data + offset, size - offset);
401
402 internal->buffer = buffer.release();
403 internal->doubleArray = doubleArray.release();
404 internal->binary = std::move(binary);
405
406 dict->lexicon = internal->binary->GetLexicon();
407 dict->maxLength = internal->binary->KeyMaxLength();
408 if (!internal->doubleArray->validate(static_cast<Darts::DoubleArray::value_type>(
409 dict->lexicon->Length()))) {
410 throw InvalidFormat("Invalid OpenCC dictionary darts data");
411 }
412 return dict;
413 }
414
415 DartsDictPtr DartsDict::NewFromDict(const Dict& thatDict) {
416 DartsDictPtr dict(new DartsDict());
417 auto internal = dict->internal;
418
419 std::unique_ptr<Darts::DoubleArray> doubleArray(new Darts::DoubleArray());
420 std::vector<std::string> keys;
421 std::vector<const char*> keys_cstr;
422 size_t maxLength = 0;
423 const LexiconPtr& lexicon = thatDict.GetLexicon();
424 size_t lexiconCount = lexicon->Length();
425 keys.resize(lexiconCount);
426 keys_cstr.resize(lexiconCount);
427 for (size_t i = 0; i < lexiconCount; i++) {
428 const DictEntry* entry = lexicon->At(i);
429 keys[i] = entry->Key();
430 keys_cstr[i] = keys[i].c_str();
431 maxLength = (std::max)(entry->KeyLength(), maxLength);
432 }
433 doubleArray->build(lexicon->Length(), &keys_cstr[0]);
434 dict->lexicon = lexicon;
435 dict->maxLength = maxLength;
436 internal->doubleArray = doubleArray.release();
437 return dict;
438 }
439
440 void DartsDict::SerializeToFile(FILE* fp) const {
441 if (internal->doubleArray == nullptr) {
442 throw InvalidFormat(
443 "Cannot serialize a legacy 64-bit OCD dictionary; "
444 "rebuild via NewFromDict first");
445 }
446 Darts::DoubleArray& dict = *internal->doubleArray;
447
448 fwrite(OCDHEADER, sizeof(char), strlen(OCDHEADER), fp);
449
450 // Write dartsSize as uint32_t so the file is platform-independent.
451 // id_type is fixed at uint32_t, so total_size() always fits in 32 bits.
452 uint32_t dartsSize = static_cast<uint32_t>(dict.total_size());
453 fwrite(&dartsSize, sizeof(uint32_t), 1, fp);
454 fwrite(dict.array(), sizeof(char), dartsSize, fp);
455
456 internal->binary.reset(new BinaryDict(lexicon));
457 internal->binary->SerializeToFile(fp);
458 }