| 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 |
// 4 bytes 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 |
const bool highBytesZero = |
| 80 |
data[4] == 0 && data[5] == 0 && data[6] == 0 && data[7] == 0; |
| 81 |
if (highBytesZero && size != 3 * sizeof(uint32_t)) { |
| 82 |
return sizeof(uint64_t); |
| 83 |
} |
| 84 |
return sizeof(uint32_t); |
| 85 |
} |
| 86 |
|
| 87 |
} // namespace |
| 88 |
|
| 89 |
void BinaryDict::SerializeToFile(FILE* fp) const { |
| 90 |
std::string keyBuf, valueBuf; |
| 91 |
std::vector<size_t> keyOffsets, valueOffsets; |
| 92 |
size_t keyTotalLength = 0, valueTotalLength = 0; |
| 93 |
ConstructBuffer(keyBuf, keyOffsets, keyTotalLength, valueBuf, valueOffsets, |
| 94 |
valueTotalLength); |
| 95 |
// Number of items |
| 96 |
size_t numItems = lexicon->Length(); |
| 97 |
WriteField(fp, numItems); |
| 98 |
|
| 99 |
// Data |
| 100 |
WriteField(fp, keyTotalLength); |
| 101 |
fwrite(keyBuf.c_str(), sizeof(char), keyTotalLength, fp); |
| 102 |
WriteField(fp, valueTotalLength); |
| 103 |
fwrite(valueBuf.c_str(), sizeof(char), valueTotalLength, fp); |
| 104 |
|
| 105 |
size_t keyCursor = 0, valueCursor = 0; |
| 106 |
for (const std::unique_ptr<DictEntry>& entry : *lexicon) { |
| 107 |
// Number of values |
| 108 |
size_t numValues = entry->NumValues(); |
| 109 |
WriteField(fp, numValues); |
| 110 |
// Key offset |
| 111 |
size_t keyOffset = keyOffsets[keyCursor++]; |
| 112 |
WriteField(fp, keyOffset); |
| 113 |
// Values offset |
| 114 |
for (size_t i = 0; i < numValues; i++) { |
| 115 |
size_t valueOffset = valueOffsets[valueCursor++]; |
| 116 |
WriteField(fp, valueOffset); |
| 117 |
} |
| 118 |
} |
| 119 |
assert(keyCursor == numItems); |
| 120 |
} |
| 121 |
|
| 122 |
BinaryDictPtr BinaryDict::NewFromFile(FILE* fp) { |
| 123 |
long savedOffset = ftell(fp); |
| 124 |
fseek(fp, 0L, SEEK_END); |
| 125 |
long remainingSizeLong = ftell(fp) - savedOffset; |
| 126 |
fseek(fp, savedOffset, SEEK_SET); |
| 127 |
assert(remainingSizeLong >= 0); |
| 128 |
size_t remainingSize = static_cast<size_t>(remainingSizeLong); |
| 129 |
|
| 130 |
std::string buffer; |
| 131 |
buffer.resize(remainingSize); |
| 132 |
size_t bytesRead = fread(const_cast<char*>(buffer.c_str()), sizeof(char), |
| 133 |
remainingSize, fp); |
| 134 |
if (bytesRead != remainingSize) { |
| 135 |
throw InvalidFormat("Invalid OpenCC binary dictionary (truncated)"); |
| 136 |
} |
| 137 |
return NewFromBuffer(buffer.data(), buffer.size()); |
| 138 |
} |
| 139 |
|
| 140 |
BinaryDictPtr BinaryDict::NewFromBuffer(const char* data, size_t size) { |
| 141 |
BinaryDictPtr dict(new BinaryDict(LexiconPtr(new Lexicon))); |
| 142 |
size_t offset = 0; |
| 143 |
const size_t fieldWidth = DetectFieldWidth(data, size); |
| 144 |
|
| 145 |
auto readField = [&]() -> size_t { |
| 146 |
uint64_t value = ReadField(data, size, &offset, fieldWidth); |
| 147 |
if (value > size) { |
| 148 |
// Every field is a count, length or offset bounded by the data size; |
| 149 |
// this also guarantees the value fits in size_t on 32-bit platforms. |
| 150 |
throw InvalidFormat("Invalid OpenCC binary dictionary (field too large)"); |
| 151 |
} |
| 152 |
return static_cast<size_t>(value); |
| 153 |
}; |
| 154 |
|
| 155 |
size_t numItems = readField(); |
| 156 |
|
| 157 |
size_t keyTotalLength = readField(); |
| 158 |
if (keyTotalLength > size - offset) { |
| 159 |
throw InvalidFormat( |
| 160 |
"Invalid OpenCC binary dictionary (keyTotalLength exceeds data size)"); |
| 161 |
} |
| 162 |
dict->keyBuffer.assign(data + offset, keyTotalLength); |
| 163 |
offset += keyTotalLength; |
| 164 |
|
| 165 |
size_t valueTotalLength = readField(); |
| 166 |
if (valueTotalLength > size - offset) { |
| 167 |
throw InvalidFormat( |
| 168 |
"Invalid OpenCC binary dictionary (valueTotalLength exceeds data size)"); |
| 169 |
} |
| 170 |
dict->valueBuffer.assign(data + offset, valueTotalLength); |
| 171 |
offset += valueTotalLength; |
| 172 |
|
| 173 |
for (size_t i = 0; i < numItems; i++) { |
| 174 |
size_t numValues = readField(); |
| 175 |
size_t keyOffset = readField(); |
| 176 |
if (keyOffset >= keyTotalLength) { |
| 177 |
throw InvalidFormat("Invalid OpenCC binary dictionary (keyOffset)"); |
| 178 |
} |
| 179 |
const char* keyStart = dict->keyBuffer.c_str() + keyOffset; |
| 180 |
if (memchr(keyStart, '\0', keyTotalLength - keyOffset) == nullptr) { |
| 181 |
throw InvalidFormat( |
| 182 |
"Invalid OpenCC binary dictionary (key not null-terminated)"); |
| 183 |
} |
| 184 |
std::string key = keyStart; |
| 185 |
std::vector<std::string> values; |
| 186 |
for (size_t j = 0; j < numValues; j++) { |
| 187 |
size_t valueOffset = readField(); |
| 188 |
if (valueOffset >= valueTotalLength) { |
| 189 |
throw InvalidFormat("Invalid OpenCC binary dictionary (valueOffset)"); |
| 190 |
} |
| 191 |
const char* valueStart = dict->valueBuffer.c_str() + valueOffset; |
| 192 |
if (memchr(valueStart, '\0', valueTotalLength - valueOffset) == nullptr) { |
| 193 |
throw InvalidFormat( |
| 194 |
"Invalid OpenCC binary dictionary (value not null-terminated)"); |
| 195 |
} |
| 196 |
values.push_back(valueStart); |
| 197 |
} |
| 198 |
DictEntry* entry = DictEntryFactory::New(key, values); |
| 199 |
dict->lexicon->Add(entry); |
| 200 |
} |
| 201 |
return dict; |
| 202 |
} |
| 203 |
|
| 204 |
void BinaryDict::ConstructBuffer(std::string& keyBuf, |
| 205 |
std::vector<size_t>& keyOffset, |
| 206 |
size_t& keyTotalLength, std::string& valueBuf, |
| 207 |
std::vector<size_t>& valueOffset, |
| 208 |
size_t& valueTotalLength) const { |
| 209 |
keyTotalLength = 0; |
| 210 |
valueTotalLength = 0; |
| 211 |
// Calculate total length |
| 212 |
for (const std::unique_ptr<DictEntry>& entry : *lexicon) { |
| 213 |
keyTotalLength += entry->KeyLength() + 1; |
| 214 |
assert(entry->NumValues() != 0); |
| 215 |
if (entry->NumValues() == 1) { |
| 216 |
const auto* svEntry = |
| 217 |
static_cast<const SingleValueDictEntry*>(entry.get()); |
| 218 |
valueTotalLength += svEntry->Value().length() + 1; |
| 219 |
} else { |
| 220 |
const auto* mvEntry = |
| 221 |
static_cast<const MultiValueDictEntry*>(entry.get()); |
| 222 |
for (const auto& value : mvEntry->Values()) { |
| 223 |
valueTotalLength += value.length() + 1; |
| 224 |
} |
| 225 |
} |
| 226 |
} |
| 227 |
// Write keys and values to buffers |
| 228 |
keyBuf.resize(keyTotalLength, '\0'); |
| 229 |
valueBuf.resize(valueTotalLength, '\0'); |
| 230 |
char* pKeyBuffer = keyBuf.data(); |
| 231 |
char* pValueBuffer = valueBuf.data(); |
| 232 |
for (const std::unique_ptr<DictEntry>& entry : *lexicon) { |
| 233 |
const std::string& key = entry->Key(); |
| 234 |
strcpy(pKeyBuffer, key.c_str()); |
| 235 |
keyOffset.push_back(pKeyBuffer - keyBuf.data()); |
| 236 |
pKeyBuffer += key.length() + 1; |
| 237 |
if (entry->NumValues() == 1) { |
| 238 |
const auto* svEntry = |
| 239 |
static_cast<const SingleValueDictEntry*>(entry.get()); |
| 240 |
const std::string& val = svEntry->Value(); |
| 241 |
strcpy(pValueBuffer, val.c_str()); |
| 242 |
valueOffset.push_back(pValueBuffer - valueBuf.data()); |
| 243 |
pValueBuffer += val.length() + 1; |
| 244 |
} else { |
| 245 |
const auto* mvEntry = |
| 246 |
static_cast<const MultiValueDictEntry*>(entry.get()); |
| 247 |
for (const auto& value : mvEntry->Values()) { |
| 248 |
strcpy(pValueBuffer, value.c_str()); |
| 249 |
valueOffset.push_back(pValueBuffer - valueBuf.data()); |
| 250 |
pValueBuffer += value.length() + 1; |
| 251 |
} |
| 252 |
} |
| 253 |
} |
| 254 |
assert(keyBuf.data() + keyTotalLength == pKeyBuffer); |
| 255 |
assert(valueBuf.data() + valueTotalLength == pValueBuffer); |
| 256 |
} |