Debian Codegraph @

src/BinaryDict.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 <cassert>
21 #include <cstdint>
22 #include <cstring>
23
24 #include "BinaryDict.hpp"
25 #include "Lexicon.hpp"
26
27 using namespace opencc;
28
29 size_t BinaryDict::KeyMaxLength() const {
30 size_t maxLength = 0;
31 for (const std::unique_ptr<DictEntry>& entry : *lexicon) {
32 maxLength = (std::max)(maxLength, entry->KeyLength());
33 }
34 return maxLength;
35 }
36
37 namespace {
38
39 // All integer fields are serialized as fixed-width uint32_t so that the file
40 // is identical regardless of the word size of the platform that built it.
41 // Files written by old 64-bit builds used native 8-byte size_t fields; the
42 // deserializers below detect and accept both layouts.
43 void WriteField(FILE* fp, size_t value) {
44 if (value > UINT32_MAX) {
45 throw InvalidFormat("OpenCC binary dictionary field exceeds uint32 range");
46 }
47 uint32_t field = static_cast<uint32_t>(value);
48 fwrite(&field, sizeof(field), 1, fp);
49 }
50
51 uint64_t ReadField(const char* data, size_t size, size_t* offset,
52 size_t fieldWidth) {
53 if (fieldWidth > size || *offset > size - fieldWidth) {
54 throw InvalidFormat("Invalid OpenCC binary dictionary (truncated)");
55 }
56 uint64_t value;
57 if (fieldWidth == sizeof(uint32_t)) {
58 uint32_t field;
59 memcpy(&field, data + *offset, sizeof(field));
60 value = field;
61 } else {
62 memcpy(&value, data + *offset, sizeof(value));
63 }
64 *offset += fieldWidth;
65 return value;
66 }
67
68 // Detects the integer field width of a serialized BinaryDict.
69 // - Fixed-width layout (current builds and old 32-bit builds): the first 8
70 // bytes are numItems followed by keyTotalLength; keyTotalLength is
71 // non-zero whenever the dictionary has entries, and an empty dictionary
72 // is exactly 12 bytes long.
73 // - Legacy 64-bit layout: the first field is an 8-byte numItems whose high
•74 // 32 bits are zero for any realistic dictionary.
75 size_t DetectFieldWidth(const char* data, size_t size) {
76 if (size < 8) {
77 return sizeof(uint32_t);
78 }
•79 if (LooksLikeLegacy64Field(data) && size != 3 * sizeof(uint32_t)) {
80 return sizeof(uint64_t);
81 }
82 return sizeof(uint32_t);
83 }
84
85 } // namespace
86
87 void BinaryDict::SerializeToFile(FILE* fp) const {
88 std::string keyBuf, valueBuf;
89 std::vector<size_t> keyOffsets, valueOffsets;
90 size_t keyTotalLength = 0, valueTotalLength = 0;
91 ConstructBuffer(keyBuf, keyOffsets, keyTotalLength, valueBuf, valueOffsets,
92 valueTotalLength);
93 // Number of items
94 size_t numItems = lexicon->Length();
95 WriteField(fp, numItems);
96
97 // Data
98 WriteField(fp, keyTotalLength);
99 fwrite(keyBuf.c_str(), sizeof(char), keyTotalLength, fp);
100 WriteField(fp, valueTotalLength);
101 fwrite(valueBuf.c_str(), sizeof(char), valueTotalLength, fp);
102
103 size_t keyCursor = 0, valueCursor = 0;
104 for (const std::unique_ptr<DictEntry>& entry : *lexicon) {
105 // Number of values
106 size_t numValues = entry->NumValues();
107 WriteField(fp, numValues);
108 // Key offset
109 size_t keyOffset = keyOffsets[keyCursor++];
110 WriteField(fp, keyOffset);
111 // Values offset
112 for (size_t i = 0; i < numValues; i++) {
113 size_t valueOffset = valueOffsets[valueCursor++];
114 WriteField(fp, valueOffset);
115 }
116 }
117 assert(keyCursor == numItems);
118 }
119
120 BinaryDictPtr BinaryDict::NewFromFile(FILE* fp) {
121 long savedOffset = ftell(fp);
122 fseek(fp, 0L, SEEK_END);
123 long remainingSizeLong = ftell(fp) - savedOffset;
124 fseek(fp, savedOffset, SEEK_SET);
125 assert(remainingSizeLong >= 0);
126 size_t remainingSize = static_cast<size_t>(remainingSizeLong);
127
128 std::string buffer;
129 buffer.resize(remainingSize);
130 size_t bytesRead = fread(const_cast<char*>(buffer.c_str()), sizeof(char),
131 remainingSize, fp);
132 if (bytesRead != remainingSize) {
133 throw InvalidFormat("Invalid OpenCC binary dictionary (truncated)");
134 }
135 return NewFromBuffer(buffer.data(), buffer.size());
136 }
137
138 BinaryDictPtr BinaryDict::NewFromBuffer(const char* data, size_t size) {
139 BinaryDictPtr dict(new BinaryDict(LexiconPtr(new Lexicon)));
140 size_t offset = 0;
141 const size_t fieldWidth = DetectFieldWidth(data, size);
142
143 auto readField = [&]() -> size_t {
144 uint64_t value = ReadField(data, size, &offset, fieldWidth);
145 if (value > size) {
146 // Every field is a count, length or offset bounded by the data size;
147 // this also guarantees the value fits in size_t on 32-bit platforms.
148 throw InvalidFormat("Invalid OpenCC binary dictionary (field too large)");
149 }
150 return static_cast<size_t>(value);
151 };
152
153 size_t numItems = readField();
154
155 size_t keyTotalLength = readField();
156 if (keyTotalLength > size - offset) {
157 throw InvalidFormat(
158 "Invalid OpenCC binary dictionary (keyTotalLength exceeds data size)");
159 }
160 dict->keyBuffer.assign(data + offset, keyTotalLength);
161 offset += keyTotalLength;
162
163 size_t valueTotalLength = readField();
164 if (valueTotalLength > size - offset) {
165 throw InvalidFormat(
166 "Invalid OpenCC binary dictionary (valueTotalLength exceeds data size)");
167 }
168 dict->valueBuffer.assign(data + offset, valueTotalLength);
169 offset += valueTotalLength;
170
171 for (size_t i = 0; i < numItems; i++) {
172 size_t numValues = readField();
173 size_t keyOffset = readField();
174 if (keyOffset >= keyTotalLength) {
175 throw InvalidFormat("Invalid OpenCC binary dictionary (keyOffset)");
176 }
177 const char* keyStart = dict->keyBuffer.c_str() + keyOffset;
178 if (memchr(keyStart, '\0', keyTotalLength - keyOffset) == nullptr) {
179 throw InvalidFormat(
180 "Invalid OpenCC binary dictionary (key not null-terminated)");
181 }
182 std::string key = keyStart;
183 std::vector<std::string> values;
184 for (size_t j = 0; j < numValues; j++) {
185 size_t valueOffset = readField();
186 if (valueOffset >= valueTotalLength) {
187 throw InvalidFormat("Invalid OpenCC binary dictionary (valueOffset)");
188 }
189 const char* valueStart = dict->valueBuffer.c_str() + valueOffset;
190 if (memchr(valueStart, '\0', valueTotalLength - valueOffset) == nullptr) {
191 throw InvalidFormat(
192 "Invalid OpenCC binary dictionary (value not null-terminated)");
193 }
194 values.push_back(valueStart);
195 }
196 DictEntry* entry = DictEntryFactory::New(key, values);
197 dict->lexicon->Add(entry);
198 }
199 return dict;
200 }
201
202 void BinaryDict::ConstructBuffer(std::string& keyBuf,
203 std::vector<size_t>& keyOffset,
204 size_t& keyTotalLength, std::string& valueBuf,
205 std::vector<size_t>& valueOffset,
206 size_t& valueTotalLength) const {
207 keyTotalLength = 0;
208 valueTotalLength = 0;
209 // Calculate total length
210 for (const std::unique_ptr<DictEntry>& entry : *lexicon) {
211 keyTotalLength += entry->KeyLength() + 1;
212 assert(entry->NumValues() != 0);
213 if (entry->NumValues() == 1) {
214 const auto* svEntry =
215 static_cast<const SingleValueDictEntry*>(entry.get());
216 valueTotalLength += svEntry->Value().length() + 1;
217 } else {
218 const auto* mvEntry =
219 static_cast<const MultiValueDictEntry*>(entry.get());
220 for (const auto& value : mvEntry->Values()) {
221 valueTotalLength += value.length() + 1;
222 }
223 }
224 }
225 // Write keys and values to buffers
226 keyBuf.resize(keyTotalLength, '\0');
227 valueBuf.resize(valueTotalLength, '\0');
228 char* pKeyBuffer = keyBuf.data();
229 char* pValueBuffer = valueBuf.data();
230 for (const std::unique_ptr<DictEntry>& entry : *lexicon) {
231 const std::string& key = entry->Key();
232 strcpy(pKeyBuffer, key.c_str());
233 keyOffset.push_back(pKeyBuffer - keyBuf.data());
234 pKeyBuffer += key.length() + 1;
235 if (entry->NumValues() == 1) {
236 const auto* svEntry =
237 static_cast<const SingleValueDictEntry*>(entry.get());
238 const std::string& val = svEntry->Value();
239 strcpy(pValueBuffer, val.c_str());
240 valueOffset.push_back(pValueBuffer - valueBuf.data());
241 pValueBuffer += val.length() + 1;
242 } else {
243 const auto* mvEntry =
244 static_cast<const MultiValueDictEntry*>(entry.get());
245 for (const auto& value : mvEntry->Values()) {
246 strcpy(pValueBuffer, value.c_str());
247 valueOffset.push_back(pValueBuffer - valueBuf.data());
248 pValueBuffer += value.length() + 1;
249 }
250 }
251 }
252 assert(keyBuf.data() + keyTotalLength == pKeyBuffer);
253 assert(valueBuf.data() + valueTotalLength == pValueBuffer);
254 }