opencc-sys 0.5.0+1.4.0

OpenCC bindings for Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
/*
 * Open Chinese Convert
 *
 * Copyright 2010-2026 Carbo Kuo and contributors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "PrefixMatch.hpp"
#include "Dict.hpp"
#include "DictGroup.hpp"
#include "Lexicon.hpp"
#include "UTF8Util.hpp"

#include <cstdint>
#include <mutex>
#include <unordered_map>
#include <utility>
#include <vector>

using namespace opencc;

namespace {

size_t Utf8CharLength(const char* str, size_t len) {
  if (len == 0) {
    return 0;
  }
  const size_t charLen = UTF8Util::NextCharLength(str);
  return charLen <= len ? charLen : 0;
}

uint32_t Utf8CharKey(const char* str, size_t charLen) {
  uint32_t key = static_cast<uint32_t>(charLen);
  for (size_t i = 0; i < charLen; i++) {
    key = (key << 8) | static_cast<unsigned char>(str[i]);
  }
  return key;
}

} // namespace

class PrefixMatch::Tables {
public:
  class Matcher;
  std::unique_ptr<Matcher> matcher;
};

namespace {

struct CacheEntry {
  std::vector<std::weak_ptr<const Dict>> dicts;
  std::weak_ptr<const PrefixMatch::Tables> tables;
};

bool SameOwner(const std::weak_ptr<const Dict>& cached,
               const std::weak_ptr<const Dict>& current) {
  return !cached.owner_before(current) && !current.owner_before(cached);
}

bool SameDicts(const CacheEntry& cached,
               const std::vector<std::weak_ptr<const Dict>>& current) {
  if (cached.dicts.size() != current.size()) {
    return false;
  }
  for (size_t i = 0; i < current.size(); i++) {
    if (cached.dicts[i].expired() || !SameOwner(cached.dicts[i], current[i])) {
      return false;
    }
  }
  return true;
}

bool HasExpiredDict(const CacheEntry& cached) {
  if (cached.tables.expired()) {
    return true;
  }
  for (const std::weak_ptr<const Dict>& dict : cached.dicts) {
    if (dict.expired()) {
      return true;
    }
  }
  return false;
}

void PruneExpiredPrefixMatchCache(
    std::unordered_map<std::string, std::vector<CacheEntry>>* cache) {
  for (std::unordered_map<std::string, std::vector<CacheEntry>>::iterator it =
           cache->begin();
       it != cache->end();) {
    std::vector<CacheEntry>& entries = it->second;
    for (std::vector<CacheEntry>::iterator entry = entries.begin();
         entry != entries.end();) {
      if (HasExpiredDict(*entry)) {
        entry = entries.erase(entry);
      } else {
        ++entry;
      }
    }
    if (entries.empty()) {
      it = cache->erase(it);
    } else {
      ++it;
    }
  }
}

void Unreachable() {
#if defined(_MSC_VER)
  __assume(false);
#elif defined(__GNUC__) || defined(__clang__)
  __builtin_unreachable();
#endif
}

} // namespace

class PrefixMatch::Tables::Matcher {
public:
  struct Candidate {
    bool hasValue = false;
    size_t keyLength = 0;
    const std::string* key = nullptr;
    const std::string* value = nullptr;
  };

  virtual ~Matcher() {}

  virtual Candidate MatchPrefixCandidate(const char* word,
                                         size_t len) const = 0;
};

class LeafMatcher : public PrefixMatch::Tables::Matcher {
private:
  struct StoredCandidate {
    bool hasValue = false;
    size_t keyLength = 0;
    std::string key;
    std::string value;
  };

  struct Node {
    StoredCandidate candidate;
    std::unordered_map<uint32_t, std::unique_ptr<Node>> children;
  };

public:
  LeafMatcher() {}

  void AddDict(const DictPtr& dict) {
    const LexiconPtr lexicon = dict->GetLexicon();
    for (const std::unique_ptr<DictEntry>& item : *lexicon) {
      AddEntry(item->Key(), item->GetDefault());
    }
  }

  Candidate MatchPrefixCandidate(const char* word, size_t len) const override {
    const Node* node = &root;
    const StoredCandidate* matchedCandidate = nullptr;
    for (const char* pstr = word; pstr < word + len;) {
      const size_t remainingLength = word + len - pstr;
      const size_t charLength = Utf8CharLength(pstr, remainingLength);
      if (charLength == 0) {
        break;
      }
      const auto child = node->children.find(Utf8CharKey(pstr, charLength));
      if (child == node->children.end()) {
        break;
      }
      pstr += charLength;
      node = child->second.get();
      if (node->candidate.hasValue &&
          (matchedCandidate == nullptr ||
           node->candidate.keyLength > matchedCandidate->keyLength)) {
        matchedCandidate = &node->candidate;
      }
    }
    if (matchedCandidate == nullptr) {
      return Candidate{};
    }
    return Candidate{true, matchedCandidate->keyLength,
                     &matchedCandidate->key, &matchedCandidate->value};
  }

private:
  void AddEntry(const std::string& key, const std::string& value) {
    Node* node = &root;
    for (const char* pstr = key.c_str(); *pstr != '\0';) {
      const size_t remainingLength = key.c_str() + key.length() - pstr;
      const size_t charLength = Utf8CharLength(pstr, remainingLength);
      if (charLength == 0) {
        break;
      }
      std::unique_ptr<Node>& child =
          node->children[Utf8CharKey(pstr, charLength)];
      if (child == nullptr) {
        child.reset(new Node);
      }
      node = child.get();
      pstr += charLength;
    }
    if (!node->candidate.hasValue) {
      node->candidate.hasValue = true;
      node->candidate.keyLength = key.length();
      node->candidate.key = key;
      node->candidate.value = value;
    }
  }

  Node root;
};

class GroupMatcher : public PrefixMatch::Tables::Matcher {
public:
  explicit GroupMatcher(DictGroupMatchPolicy _matchPolicy)
      : matchPolicy(_matchPolicy) {}

  void AddChild(std::unique_ptr<Matcher> child) {
    children.push_back(std::move(child));
  }

  Candidate MatchPrefixCandidate(const char* word, size_t len) const override {
    switch (matchPolicy) {
    case DictGroupMatchPolicy::ShortCircuit:
      return MatchPrefixShortCircuit(word, len);
    case DictGroupMatchPolicy::Union:
      return MatchPrefixUnion(word, len);
    }
    Unreachable();
    return Candidate{};
  }

private:
  Candidate MatchPrefixShortCircuit(const char* word, size_t len) const {
    for (const std::unique_ptr<Matcher>& child : children) {
      const Candidate candidate = child->MatchPrefixCandidate(word, len);
      if (candidate.hasValue) {
        return candidate;
      }
    }
    return Candidate{};
  }

  Candidate MatchPrefixUnion(const char* word, size_t len) const {
    Candidate best;
    for (const std::unique_ptr<Matcher>& child : children) {
      const Candidate candidate = child->MatchPrefixCandidate(word, len);
      if (candidate.hasValue &&
          (!best.hasValue || candidate.keyLength > best.keyLength)) {
        best = candidate;
      }
    }
    return best;
  }

  std::vector<std::unique_ptr<Matcher>> children;
  const DictGroupMatchPolicy matchPolicy;
};

// Returns true if dict is a leaf dict, or if the entire subtree rooted at dict
// consists only of union groups and leaf dicts (no short_circuit anywhere).
// Union is associative, so such a tree is semantically equivalent to a single
// flat union of all its leaf dicts: the longest match across all leaves wins,
// which is exactly what a single LeafMatcher trie computes.
bool CanFlattenAsUnion(const DictPtr& dict) {
  const std::list<DictPtr>* items = dict->GetDictGroupItems();
  if (items == nullptr) {
    return true;
  }
  if (dict->GetMatchPolicy() != DictGroupMatchPolicy::Union) {
    return false;
  }
  for (const DictPtr& child : *items) {
    if (!CanFlattenAsUnion(child)) {
      return false;
    }
  }
  return true;
}

void CollectAllLeafDicts(const DictPtr& dict, LeafMatcher* out) {
  const std::list<DictPtr>* items = dict->GetDictGroupItems();
  if (items == nullptr) {
    out->AddDict(dict);
    return;
  }
  for (const DictPtr& child : *items) {
    CollectAllLeafDicts(child, out);
  }
}

std::unique_ptr<PrefixMatch::Tables::Matcher> BuildMatcher(
    const DictPtr& dict) {
  const std::list<DictPtr>* dictGroupItems = dict->GetDictGroupItems();
  if (dictGroupItems != nullptr) {
    // If the entire subtree is a pure union of leaf dicts, merge all entries
    // into a single LeafMatcher. One trie traversal finds the longest match
    // across all dicts, which equals union semantics, and eliminates the
    // overhead of GroupMatcher dispatch and multiple traversals.
    if (CanFlattenAsUnion(dict)) {
      std::unique_ptr<LeafMatcher> leaf(new LeafMatcher);
      CollectAllLeafDicts(dict, leaf.get());
      return std::move(leaf);
    }

    std::unique_ptr<GroupMatcher> group(
        new GroupMatcher(dict->GetMatchPolicy()));
    for (const DictPtr& child : *dictGroupItems) {
      group->AddChild(BuildMatcher(child));
    }
    return std::move(group);
  }

  std::unique_ptr<LeafMatcher> leaf(new LeafMatcher);
  leaf->AddDict(dict);
  return std::move(leaf);
}

PrefixMatch::PrefixMatch(const DictPtr& dict) {
  // Try to unwrap single dict group
  DictPtr actualDict = dict;
  while (actualDict) {
    const std::list<DictPtr>* items = actualDict->GetDictGroupItems();
    if (items != nullptr && items->size() == 1) {
      actualDict = items->front();
    } else {
      break;
    }
  }

  if (actualDict && actualDict->SupportsFastPrefixMatch()) {
    singleDict = actualDict;
    return;
  }

  static std::mutex cacheMutex;
  static std::unordered_map<std::string, std::vector<CacheEntry>> cache;

  std::string cacheKey;
  AppendCacheKey(dict, &cacheKey);
  std::vector<std::weak_ptr<const Dict>> leafDicts;
  CollectLeafDicts(dict, &leafDicts);

  {
    std::lock_guard<std::mutex> lock(cacheMutex);
    PruneExpiredPrefixMatchCache(&cache);
    const auto cached = cache.find(cacheKey);
    if (cached != cache.end()) {
      for (const CacheEntry& entry : cached->second) {
        if (SameDicts(entry, leafDicts)) {
          tables = entry.tables.lock();
          if (tables != nullptr) {
            return;
          }
        }
      }
    }
  }

  std::shared_ptr<Tables> built(new Tables);
  built->matcher = BuildMatcher(dict);

  std::lock_guard<std::mutex> lock(cacheMutex);
  PruneExpiredPrefixMatchCache(&cache);
  std::vector<CacheEntry>& entries = cache[cacheKey];
  for (std::vector<CacheEntry>::iterator it = entries.begin();
       it != entries.end();) {
    if (HasExpiredDict(*it)) {
      it = entries.erase(it);
    } else if (SameDicts(*it, leafDicts)) {
      tables = it->tables.lock();
      if (tables != nullptr) {
        return;
      }
      it = entries.erase(it);
    } else {
      ++it;
    }
  }
  tables = built;
  CacheEntry entry;
  entry.dicts = std::move(leafDicts);
  entry.tables = tables;
  entries.push_back(std::move(entry));
}

PrefixMatch::~PrefixMatch() {}

PrefixMatch::Match PrefixMatch::MatchPrefix(const char* word,
                                            size_t len) const {
  if (singleDict != nullptr) {
    struct MatchCache {
      std::string key;
      std::string value;
    };
    // key/value pointers are valid until the next MatchPrefix() call on this
    // thread.
    static thread_local MatchCache matchCache;
    const PrefixMatchView pv = singleDict->MatchPrefixValue(word, len);
    if (pv.matched) {
      matchCache.key = std::string(pv.key);
      matchCache.value = std::string(pv.value);
      return Match{true, pv.keyLength, &matchCache.key, &matchCache.value};
    }
    return Match{false, 0, nullptr, nullptr};
  }

  const Tables::Matcher::Candidate candidate =
      tables->matcher->MatchPrefixCandidate(word, len);
  if (candidate.hasValue) {
    return Match{true, candidate.keyLength, candidate.key, candidate.value};
  }
  return Match{false, 0, nullptr, nullptr};
}

PrefixMatchView PrefixMatch::MatchPrefixView(const char* word,
                                              size_t len) const {
  if (singleDict != nullptr) {
    return singleDict->MatchPrefixValue(word, len);
  }
  const Tables::Matcher::Candidate candidate =
      tables->matcher->MatchPrefixCandidate(word, len);
  if (candidate.hasValue) {
    return {true, candidate.keyLength,
            std::string_view(*candidate.key),
            std::string_view(*candidate.value)};
  }
  return {false, 0, std::string_view(), std::string_view()};
}

void PrefixMatch::AppendCacheKey(const DictPtr& dict, std::string* output) {
  const std::list<DictPtr>* dictGroupItems = dict->GetDictGroupItems();
  if (dictGroupItems != nullptr) {
    output->push_back('[');
    const DictGroupMatchPolicy matchPolicy = dict->GetMatchPolicy();
    switch (matchPolicy) {
    case DictGroupMatchPolicy::ShortCircuit:
      output->append("short_circuit:");
      break;
    case DictGroupMatchPolicy::Union:
      output->append("union:");
      break;
    }
    for (const DictPtr& child : *dictGroupItems) {
      AppendCacheKey(child, output);
    }
    output->push_back(']');
    return;
  }

  const uintptr_t dictKey = reinterpret_cast<uintptr_t>(dict.get());
  output->append(reinterpret_cast<const char*>(&dictKey), sizeof(dictKey));
  output->push_back(';');
}

void PrefixMatch::CollectLeafDicts(
    const DictPtr& dict, std::vector<std::weak_ptr<const Dict>>* output) {
  const std::list<DictPtr>* dictGroupItems = dict->GetDictGroupItems();
  if (dictGroupItems != nullptr) {
    for (const DictPtr& child : *dictGroupItems) {
      CollectLeafDicts(child, output);
    }
    return;
  }
  output->push_back(dict);
}