| 1 | /* |
| 2 | * Open Chinese Convert |
| 3 | * |
| 4 | * Copyright 2015-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 "BinaryDict.hpp" |
| 20 | #include "TextDictTestBase.hpp" |
| 21 | |
| 22 | namespace opencc { |
| 23 | |
| 24 | class BinaryDictTest : public TextDictTestBase { |
| 25 | protected: |
| 26 | BinaryDictTest() |
| 27 | : binDict(new BinaryDict(textDict->GetLexicon())), fileName("dict.bin"){}; |
| 28 | |
| 29 | // Write a crafted binary file for BinaryDict with controllable fields. |
| 30 | // FIELD selects the integer field width: uint32_t for the fixed-width |
| 31 | // layout written by current builds, uint64_t for the legacy layout written |
| 32 | // by old 64-bit builds. |
| 33 | template <typename FIELD> |
| 34 | static std::string WriteCraftedBinaryDict( |
| 35 | uint64_t numItems, uint64_t keyTotalLength, const std::string& keyBuffer, |
| 36 | uint64_t valueTotalLength, const std::string& valueBuffer, |
| 37 | const std::vector<std::tuple<uint64_t, uint64_t, std::vector<uint64_t>>>& |
| 38 | items) { |
| 39 | const std::string path = "crafted_binary_dict.bin"; |
| 40 | FILE* fp = fopen(path.c_str(), "wb"); |
| 41 | const auto writeField = [fp](uint64_t value) { |
| 42 | FIELD field = static_cast<FIELD>(value); |
| 43 | fwrite(&field, sizeof(field), 1, fp); |
| 44 | }; |
| 45 | writeField(numItems); |
| 46 | writeField(keyTotalLength); |
| 47 | fwrite(keyBuffer.data(), sizeof(char), keyBuffer.size(), fp); |
| 48 | writeField(valueTotalLength); |
| 49 | fwrite(valueBuffer.data(), sizeof(char), valueBuffer.size(), fp); |
| 50 | for (const auto& [numValues, keyOffset, valueOffsets] : items) { |
| 51 | writeField(numValues); |
| 52 | writeField(keyOffset); |
| 53 | for (uint64_t vo : valueOffsets) { |
| 54 | writeField(vo); |
| 55 | } |
| 56 | } |
| 57 | fclose(fp); |
| 58 | return path; |
| 59 | } |
| 60 | |
| 61 | const BinaryDictPtr binDict; |
| 62 | const std::string fileName; |
| 63 | }; |
| 64 | |
| 65 | TEST_F(BinaryDictTest, Serialization) { |
| 66 | binDict->opencc::SerializableDict::SerializeToFile(fileName); |
| 67 | } |
| 68 | |
| 69 | TEST_F(BinaryDictTest, Deserialization) { |
| 70 | const BinaryDictPtr& deserialized = |
| 71 | SerializableDict::NewFromFile<BinaryDict>(fileName); |
| 72 | const LexiconPtr& lex1 = binDict->GetLexicon(); |
| 73 | const LexiconPtr& lex2 = deserialized->GetLexicon(); |
| 74 | |
| 75 | // Compare every entry |
| 76 | EXPECT_EQ(lex1->Length(), lex2->Length()); |
| 77 | for (size_t i = 0; i < lex1->Length(); i++) { |
| 78 | EXPECT_EQ(lex1->At(i)->Key(), lex2->At(i)->Key()); |
| 79 | EXPECT_EQ(lex1->At(i)->NumValues(), lex2->At(i)->NumValues()); |
| 80 | } |
| 81 | |
| 82 | const TextDictPtr deserializedTextDict(new TextDict(lex2)); |
| 83 | TestDict(deserializedTextDict); |
| 84 | } |
| 85 | |
| 86 | // The serialized layout must not depend on the word size of the platform: |
| 87 | // all integer fields are fixed 4-byte, so the total file size is fully |
| 88 | // determined by the lexicon content (#1412 follow-up). |
| 89 | TEST_F(BinaryDictTest, SerializedLayoutIsWordSizeIndependent) { |
| 90 | binDict->opencc::SerializableDict::SerializeToFile(fileName); |
| 91 | |
| 92 | FILE* fp = fopen(fileName.c_str(), "rb"); |
| 93 | ASSERT_NE(fp, nullptr); |
| 94 | fseek(fp, 0L, SEEK_END); |
| 95 | const size_t fileSize = static_cast<size_t>(ftell(fp)); |
| 96 | fseek(fp, 0L, SEEK_SET); |
| 97 | uint32_t numItems; |
| 98 | ASSERT_EQ(fread(&numItems, sizeof(numItems), 1, fp), 1U); |
| 99 | fclose(fp); |
| 100 | |
| 101 | EXPECT_EQ(numItems, binDict->GetLexicon()->Length()); |
| 102 | |
| 103 | size_t expectedSize = 3 * sizeof(uint32_t); |
| 104 | for (const auto& entry : *binDict->GetLexicon()) { |
| 105 | expectedSize += entry->Key().length() + 1; // key + NUL |
| 106 | expectedSize += 2 * sizeof(uint32_t); // numValues + keyOffset |
| 107 | expectedSize += entry->NumValues() * sizeof(uint32_t); // value offsets |
| 108 | for (const std::string& value : entry->Values()) { |
| 109 | expectedSize += value.length() + 1; // value + NUL |
| 110 | } |
| 111 | } |
| 112 | EXPECT_EQ(fileSize, expectedSize); |
| 113 | } |
| 114 | |
| 115 | // An empty dictionary serializes to exactly 12 bytes and round-trips; this is |
| 116 | // the only fixed-width file whose first 8 bytes are all zero, which the |
| 117 | // legacy-layout detection must not mistake for a 64-bit file. |
| 118 | TEST_F(BinaryDictTest, EmptyDictRoundTrip) { |
| 119 | const std::string path = "empty_binary_dict.bin"; |
| 120 | const BinaryDictPtr emptyDict(new BinaryDict(LexiconPtr(new Lexicon))); |
| 121 | emptyDict->opencc::SerializableDict::SerializeToFile(path); |
| 122 | |
| 123 | FILE* fp = fopen(path.c_str(), "rb"); |
| 124 | ASSERT_NE(fp, nullptr); |
| 125 | fseek(fp, 0L, SEEK_END); |
| 126 | EXPECT_EQ(ftell(fp), static_cast<long>(3 * sizeof(uint32_t))); |
| 127 | fclose(fp); |
| 128 | |
| 129 | const auto deserialized = SerializableDict::NewFromFile<BinaryDict>(path); |
| 130 | EXPECT_EQ(deserialized->GetLexicon()->Length(), 0U); |
| 131 | std::remove(path.c_str()); |
| 132 | } |
| 133 | |
| 134 | // Test that keyTotalLength exceeding file size triggers InvalidFormat (#815). |
| 135 | TEST_F(BinaryDictTest, RejectsHugeKeyTotalLength) { |
| 136 | std::string path = WriteCraftedBinaryDict<uint64_t>( |
| 137 | 1, 0x7000000000ULL, "", 0, "", {}); |
| 138 | EXPECT_THROW(SerializableDict::NewFromFile<BinaryDict>(path), InvalidFormat); |
| 139 | std::remove(path.c_str()); |
| 140 | |
| 141 | path = WriteCraftedBinaryDict<uint32_t>(1, 0x70000000ULL, "", 0, "", {}); |
| 142 | EXPECT_THROW(SerializableDict::NewFromFile<BinaryDict>(path), InvalidFormat); |
| 143 | std::remove(path.c_str()); |
| 144 | } |
| 145 | |
| 146 | // Test that valueTotalLength exceeding file size triggers InvalidFormat (#815). |
| 147 | TEST_F(BinaryDictTest, RejectsHugeValueTotalLength) { |
| 148 | std::string keyBuf = {'k', '\0'}; |
| 149 | std::string path = WriteCraftedBinaryDict<uint64_t>( |
| 150 | 1, 2, keyBuf, 0x7000000000ULL, "", {}); |
| 151 | EXPECT_THROW(SerializableDict::NewFromFile<BinaryDict>(path), InvalidFormat); |
| 152 | std::remove(path.c_str()); |
| 153 | |
| 154 | path = WriteCraftedBinaryDict<uint32_t>(1, 2, keyBuf, 0x70000000ULL, "", {}); |
| 155 | EXPECT_THROW(SerializableDict::NewFromFile<BinaryDict>(path), InvalidFormat); |
| 156 | std::remove(path.c_str()); |
| 157 | } |
| 158 | |
| 159 | // Test that a keyOffset beyond keyTotalLength triggers InvalidFormat (#813). |
| 160 | TEST_F(BinaryDictTest, RejectsKeyOffsetOutOfBounds) { |
| 161 | std::string keyBuf = {'h', 'i', '\0'}; |
| 162 | std::string valBuf = {'v', '\0'}; |
| 163 | std::string path = WriteCraftedBinaryDict<uint32_t>( |
| 164 | 1, 3, keyBuf, 2, valBuf, {{1, 100, {0}}}); |
| 165 | EXPECT_THROW(SerializableDict::NewFromFile<BinaryDict>(path), InvalidFormat); |
| 166 | std::remove(path.c_str()); |
| 167 | } |
| 168 | |
| 169 | // Test that a valueOffset beyond valueTotalLength triggers InvalidFormat (#813). |
| 170 | TEST_F(BinaryDictTest, RejectsValueOffsetOutOfBounds) { |
| 171 | std::string keyBuf = {'h', 'i', '\0'}; |
| 172 | std::string valBuf = {'v', '\0'}; |
| 173 | std::string path = WriteCraftedBinaryDict<uint32_t>( |
| 174 | 1, 3, keyBuf, 2, valBuf, {{1, 0, {100}}}); |
| 175 | EXPECT_THROW(SerializableDict::NewFromFile<BinaryDict>(path), InvalidFormat); |
| 176 | std::remove(path.c_str()); |
| 177 | } |
| 178 | |
| 179 | // Sanity check: a well-formed fixed-width crafted file deserializes. |
| 180 | TEST_F(BinaryDictTest, AcceptsWellFormedFile) { |
| 181 | std::string keyBuf = {'h', 'i', '\0'}; |
| 182 | std::string valBuf = {'v', '\0'}; |
| 183 | std::string path = WriteCraftedBinaryDict<uint32_t>( |
| 184 | 1, 3, keyBuf, 2, valBuf, {{1, 0, {0}}}); |
| 185 | const auto deserialized = SerializableDict::NewFromFile<BinaryDict>(path); |
| 186 | EXPECT_EQ(deserialized->GetLexicon()->Length(), 1); |
| 187 | std::remove(path.c_str()); |
| 188 | } |
| 189 | |
| 190 | // Files written by old 64-bit builds use native 8-byte size_t fields and must |
| 191 | // still load. |
| 192 | TEST_F(BinaryDictTest, AcceptsLegacy64BitLayout) { |
| 193 | std::string keyBuf = {'h', 'i', '\0'}; |
| 194 | std::string valBuf = {'v', '\0'}; |
| 195 | std::string path = WriteCraftedBinaryDict<uint64_t>( |
| 196 | 1, 3, keyBuf, 2, valBuf, {{1, 0, {0}}}); |
| 197 | const auto deserialized = SerializableDict::NewFromFile<BinaryDict>(path); |
| 198 | ASSERT_EQ(deserialized->GetLexicon()->Length(), 1); |
| 199 | EXPECT_EQ(deserialized->GetLexicon()->At(0)->Key(), "hi"); |
| 200 | std::remove(path.c_str()); |
| 201 | } |
| 202 | |
| 203 | } // namespace opencc |