Debian Codegraph @

src/DartsDict.cpp

raw symbols ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
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 and checking
238 // whether bytes [4..7] are all zero.
239 // - Old 64-bit build: dartsSize field is uint64_t (8 bytes); high 32 bits
240 // are zero for any realistic file size → bytes [4..7] == 0.
241 // - Current build (any word size) or old 32-bit build: dartsSize field is
242 // uint32_t (4 bytes); bytes [4..7] are the first 4 bytes of the darts
243 // array (non-zero for any valid array whose root unit has a non-zero
244 // offset).
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 =
250 (probe[4] == 0 && probe[5] == 0 && probe[6] == 0 && probe[7] == 0);
251
252 if (is64bit) {
253 uint64_t dartsSize64;
254 memcpy(&dartsSize64, probe, 8);
255 size_t dartsSize = static_cast<size_t>(dartsSize64);
256 if (dartsSize > remainingSize) {
257 throw InvalidFormat(
258 "Invalid OpenCC dictionary (dartsSize exceeds file size)");
259 }
260 if (dartsSize % sizeof(LegacyUnit64) != 0) {
261 throw InvalidFormat("Invalid legacy OCD dictionary unit alignment");
262 }
263 std::unique_ptr<void, decltype(&free)> buffer(malloc(dartsSize), free);
264 if (!buffer) {
265 throw std::bad_alloc();
266 }
267 bytesRead = fread(buffer.get(), 1, dartsSize, fp);
268 if (bytesRead != dartsSize) {
269 throw InvalidFormat("Invalid legacy OCD dictionary size mismatch");
270 }
271
272 BinaryDictPtr binary = BinaryDict::NewFromFile(fp);
273
274 internal->buffer = buffer.release();
275 internal->binary = std::move(binary);
276 internal->legacyArray64 = static_cast<const LegacyUnit64*>(internal->buffer);
277
278 dict->lexicon = internal->binary->GetLexicon();
279 dict->maxLength = internal->binary->KeyMaxLength();
280 size_t numUnits = dartsSize / sizeof(LegacyUnit64);
281 if (!ValidateLegacy64(internal->legacyArray64, numUnits,
282 static_cast<int>(dict->lexicon->Length()))) {
283 throw InvalidFormat("Invalid legacy OCD dictionary darts data");
284 }
285 return dict;
286 }
287
288 // Fixed-width layout: dartsSize is the first 4 bytes of probe; remaining 4
289 // bytes belong to the array, so seek back.
290 fseek(fp, -4, SEEK_CUR);
291 uint32_t dartsSize32;
292 memcpy(&dartsSize32, probe, 4);
293 size_t dartsSize = dartsSize32;
294 if (dartsSize > remainingSize) {
295 throw InvalidFormat(
296 "Invalid OpenCC dictionary (dartsSize exceeds file size)");
297 }
298 std::unique_ptr<Darts::DoubleArray> doubleArray(new Darts::DoubleArray());
299 if (dartsSize % doubleArray->unit_size() != 0) {
300 throw InvalidFormat("Invalid OpenCC dictionary size of darts alignment");
301 }
302 std::unique_ptr<void, decltype(&free)> buffer(malloc(dartsSize), free);
303 if (!buffer) {
304 throw std::bad_alloc();
305 }
306 bytesRead = fread(buffer.get(), 1, dartsSize, fp);
307 if (bytesRead != dartsSize) {
308 throw InvalidFormat("Invalid OpenCC dictionary size of darts mismatch");
309 }
310 doubleArray->set_array(buffer.get(), dartsSize / doubleArray->unit_size());
311
312 BinaryDictPtr binary = BinaryDict::NewFromFile(fp);
313
314 internal->buffer = buffer.release();
315 internal->doubleArray = doubleArray.release();
316 internal->binary = std::move(binary);
317
318 dict->lexicon = internal->binary->GetLexicon();
319 dict->maxLength = internal->binary->KeyMaxLength();
320 if (!internal->doubleArray->validate(static_cast<Darts::DoubleArray::value_type>(
321 dict->lexicon->Length()))) {
322 throw InvalidFormat("Invalid OpenCC dictionary darts data");
323 }
324 return dict;
325 }
326
327 DartsDictPtr DartsDict::NewFromBuffer(const char* data, size_t size) {
328 DartsDictPtr dict(new DartsDict());
329 auto internal = dict->internal;
330
331 size_t headerLen = strlen(OCDHEADER);
332 if (size < headerLen || memcmp(data, OCDHEADER, headerLen) != 0) {
333 throw InvalidFormat("Invalid OpenCC dictionary header");
334 }
335 size_t offset = headerLen;
336
337 if (size - offset < 8) {
338 throw InvalidFormat("Invalid OpenCC dictionary header (dartsSize)");
339 }
340 uint8_t probe[8];
341 memcpy(probe, data + offset, 8);
342 offset += 8;
343 bool is64bit =
344 (probe[4] == 0 && probe[5] == 0 && probe[6] == 0 && probe[7] == 0);
345
346 if (is64bit) {
347 uint64_t dartsSize64;
348 memcpy(&dartsSize64, probe, 8);
349 size_t dartsSize = static_cast<size_t>(dartsSize64);
350 if (dartsSize > size - offset) {
351 throw InvalidFormat(
352 "Invalid OpenCC dictionary (dartsSize exceeds file size)");
353 }
354 if (dartsSize % sizeof(LegacyUnit64) != 0) {
355 throw InvalidFormat("Invalid legacy OCD dictionary unit alignment");
356 }
357 std::unique_ptr<void, decltype(&free)> buffer(malloc(dartsSize), free);
358 if (!buffer) {
359 throw std::bad_alloc();
360 }
361 memcpy(buffer.get(), data + offset, dartsSize);
362 offset += dartsSize;
363
364 BinaryDictPtr binary = BinaryDict::NewFromBuffer(data + offset, size - offset);
365
366 internal->buffer = buffer.release();
367 internal->binary = std::move(binary);
368 internal->legacyArray64 = static_cast<const LegacyUnit64*>(internal->buffer);
369
370 dict->lexicon = internal->binary->GetLexicon();
371 dict->maxLength = internal->binary->KeyMaxLength();
372 size_t numUnits = dartsSize / sizeof(LegacyUnit64);
373 if (!ValidateLegacy64(internal->legacyArray64, numUnits,
374 static_cast<int>(dict->lexicon->Length()))) {
375 throw InvalidFormat("Invalid legacy OCD dictionary darts data");
376 }
377 return dict;
378 }
379
380 // Fixed-width layout: dartsSize is the first 4 bytes of probe; probe[4..7]
381 // belong to the darts array, so rewind 4 bytes before reading the array.
382 uint32_t dartsSize32;
383 memcpy(&dartsSize32, probe, 4);
384 size_t dartsSize = dartsSize32;
385 offset -= 4;
386 if (dartsSize > size - offset) {
387 throw InvalidFormat(
388 "Invalid OpenCC dictionary (dartsSize exceeds file size)");
389 }
390 std::unique_ptr<Darts::DoubleArray> doubleArray(new Darts::DoubleArray());
391 if (dartsSize % doubleArray->unit_size() != 0) {
392 throw InvalidFormat("Invalid OpenCC dictionary size of darts alignment");
393 }
394 std::unique_ptr<void, decltype(&free)> buffer(malloc(dartsSize), free);
395 if (!buffer) {
396 throw std::bad_alloc();
397 }
398 memcpy(buffer.get(), data + offset, dartsSize);
399 offset += dartsSize;
400 doubleArray->set_array(buffer.get(), dartsSize / doubleArray->unit_size());
401
402 BinaryDictPtr binary = BinaryDict::NewFromBuffer(data + offset, size - offset);
403
404 internal->buffer = buffer.release();
405 internal->doubleArray = doubleArray.release();
406 internal->binary = std::move(binary);
407
408 dict->lexicon = internal->binary->GetLexicon();
409 dict->maxLength = internal->binary->KeyMaxLength();
410 if (!internal->doubleArray->validate(static_cast<Darts::DoubleArray::value_type>(
411 dict->lexicon->Length()))) {
412 throw InvalidFormat("Invalid OpenCC dictionary darts data");
413 }
414 return dict;
415 }
416
417 DartsDictPtr DartsDict::NewFromDict(const Dict& thatDict) {
418 DartsDictPtr dict(new DartsDict());
419 auto internal = dict->internal;
420
421 std::unique_ptr<Darts::DoubleArray> doubleArray(new Darts::DoubleArray());
422 std::vector<std::string> keys;
423 std::vector<const char*> keys_cstr;
424 size_t maxLength = 0;
425 const LexiconPtr& lexicon = thatDict.GetLexicon();
426 size_t lexiconCount = lexicon->Length();
427 keys.resize(lexiconCount);
428 keys_cstr.resize(lexiconCount);
429 for (size_t i = 0; i < lexiconCount; i++) {
430 const DictEntry* entry = lexicon->At(i);
431 keys[i] = entry->Key();
432 keys_cstr[i] = keys[i].c_str();
433 maxLength = (std::max)(entry->KeyLength(), maxLength);
434 }
435 doubleArray->build(lexicon->Length(), &keys_cstr[0]);
436 dict->lexicon = lexicon;
437 dict->maxLength = maxLength;
438 internal->doubleArray = doubleArray.release();
439 return dict;
440 }
441
442 void DartsDict::SerializeToFile(FILE* fp) const {
443 if (internal->doubleArray == nullptr) {
444 throw InvalidFormat(
445 "Cannot serialize a legacy 64-bit OCD dictionary; "
446 "rebuild via NewFromDict first");
447 }
448 Darts::DoubleArray& dict = *internal->doubleArray;
449
450 fwrite(OCDHEADER, sizeof(char), strlen(OCDHEADER), fp);
451
452 // Write dartsSize as uint32_t so the file is platform-independent.
453 // id_type is fixed at uint32_t, so total_size() always fits in 32 bits.
454 uint32_t dartsSize = static_cast<uint32_t>(dict.total_size());
455 fwrite(&dartsSize, sizeof(uint32_t), 1, fp);
456 fwrite(dict.array(), sizeof(char), dartsSize, fp);
457
458 internal->binary.reset(new BinaryDict(lexicon));
459 internal->binary->SerializeToFile(fp);
460 }