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
/*
 * Open Chinese Convert
 *
 * Copyright 2013 Carbo Kuo <byvoid@byvoid.com>
 *
 * 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.
 */

#pragma once

#ifdef _MSC_VER
#ifndef NOMINMAX
#define NOMINMAX
#endif
#include <windows.h>
#endif // _MSC_VER

#include <cstdint>
#include <cstring>

#include "Common.hpp"
#include "Exception.hpp"

namespace opencc {
/**
 * UTF8 std::string utilities
 * @ingroup opencc_cpp_api
 */
class OPENCC_EXPORT UTF8Util {
public:
  /**
   * Detect UTF8 BOM and skip it.
   */
  static void SkipUtf8Bom(FILE* fp);

  /**
   * Returns the length in byte for the next UTF8 character.
   * On error returns 0.
   */
  static size_t NextCharLengthNoException(const char* str) {
    const unsigned char ch = static_cast<unsigned char>(*str);
    if ((ch & 0xF0) == 0xE0) {
      return 3;
    } else if ((ch & 0x80) == 0x00) {
      return 1;
    } else if ((ch & 0xE0) == 0xC0) {
      return 2;
    } else if ((ch & 0xF8) == 0xF0) {
      return 4;
    } else if ((ch & 0xFC) == 0xF8) {
      return 5;
    } else if ((ch & 0xFE) == 0xFC) {
      return 6;
    }
    return 0;
  }

  /**
   * Returns the length in byte for the next UTF8 character.
   */
  static size_t NextCharLength(const char* str) {
    size_t length = NextCharLengthNoException(str);
    if (length == 0) {
      throw InvalidUTF8(str);
    }
    return length;
  }

  /**
   * Returns the length in byte for the previous UTF8 character.
   */
  static size_t PrevCharLength(const char* str) {
    const char* candidate = str - 1;
    size_t distance = 1;
    while (distance < 6) {
      const unsigned char ch = static_cast<unsigned char>(*candidate);
      if ((ch & 0xC0) != 0x80) {
        break;
      }
      candidate--;
      distance++;
    }

    const size_t length = NextCharLengthNoException(candidate);
    if (length == distance) {
      return length;
    }
    throw InvalidUTF8(str);
  }

  /**
   * Returns the char* pointer over the next UTF8 character.
   */
  static const char* NextChar(const char* str) {
    return str + NextCharLength(str);
  }

  /**
   * Move the char* pointer before the previous UTF8 character.
   */
  static const char* PrevChar(const char* str) {
    return str - PrevCharLength(str);
  }

  static size_t IdeographicDescriptionOperatorArity(uint32_t codePoint) {
    switch (codePoint) {
    case 0x2FF2:
    case 0x2FF3:
      return 3;
    case 0x2FFE:
    case 0x2FFF:
      return 1;
    case 0x2FF0:
    case 0x2FF1:
    case 0x2FF4:
    case 0x2FF5:
    case 0x2FF6:
    case 0x2FF7:
    case 0x2FF8:
    case 0x2FF9:
    case 0x2FFA:
    case 0x2FFB:
    case 0x2FFC:
    case 0x2FFD:
      return 2;
    default:
      return 0;
    }
  }

  static size_t NextIdeographicDescriptionSequenceLength(const char* str,
                                                         size_t len) {
    const size_t kMaxIDSDepth = 16;
    const size_t kMaxIDSCodePoints = 64;
    if (len == 0) {
      return 0;
    }
    const size_t charLen = NextCharLengthNoException(str);
    if (charLen == 0 || charLen > len) {
      return 0;
    }
    const uint32_t codePoint = CodePointNoException(str, charLen);
    if (IdeographicDescriptionOperatorArity(codePoint) == 0) {
      return 0;
    }

    size_t consumed = 0;
    size_t codePoints = 0;
    if (ConsumeIdeographicDescriptionSequence(
            str, len, kMaxIDSDepth, kMaxIDSCodePoints, &consumed,
            &codePoints) == IDSParseStatus::Complete) {
      return consumed;
    }
    return 0;
  }

  static bool IsIncompleteIdeographicDescriptionSequencePrefix(const char* str,
                                                               size_t len) {
    const size_t kMaxIDSDepth = 16;
    const size_t kMaxIDSCodePoints = 64;
    if (len == 0) {
      return false;
    }
    const size_t charLen = NextCharLengthNoException(str);
    if (charLen == 0 || charLen > len) {
      return false;
    }
    const uint32_t codePoint = CodePointNoException(str, charLen);
    if (IdeographicDescriptionOperatorArity(codePoint) == 0) {
      return false;
    }

    size_t consumed = 0;
    size_t codePoints = 0;
    return ConsumeIdeographicDescriptionSequence(
               str, len, kMaxIDSDepth, kMaxIDSCodePoints, &consumed,
               &codePoints) == IDSParseStatus::Incomplete;
  }

  static bool IsVariationSelector(uint32_t codePoint) {
    return (codePoint >= 0xFE00 && codePoint <= 0xFE0F) ||
           (codePoint >= 0xE0100 && codePoint <= 0xE01EF);
  }

  static bool ContainsVariationSelector(const char* str, size_t len) {
    const char* pStr = str;
    const char* strEnd = str + len;
    while (pStr < strEnd) {
      const size_t remainingLength = strEnd - pStr;
      const size_t charLen = NextCharLengthNoException(pStr);
      if (charLen == 0) {
        ++pStr;
        continue;
      }
      if (charLen > remainingLength) {
        return false;
      }
      if (IsVariationSelector(CodePointNoException(pStr, charLen))) {
        return true;
      }
      pStr += charLen;
    }
    return false;
  }

  /**
   * Returns the UTF8 length of a null-terminated string.
   * Throws InvalidUTF8 for invalid or truncated byte sequences.
   * The truncated-sequence check reads only up to the null terminator, so it
   * does not read out of bounds (issue #799 fix).
   */
  static size_t Length(const char* str) {
    size_t length = 0;
    while (*str != '\0') {
      const size_t charLen = NextCharLengthNoException(str);
      if (charLen == 0) {
        throw InvalidUTF8(str);
      }
      // Verify all continuation bytes are present before the null terminator.
      // Use a while loop (not a for-with-return) to avoid complex control flow
      // that triggers MSVC LTCG code-generator bugs.
      size_t i = 1;
      while (i < charLen && str[i] != '\0') {
        ++i;
      }
      if (i < charLen) {
        throw InvalidUTF8(str); // Truncated sequence: throw, don't silently skip
      }
      str += charLen;
      ++length;
    }
    return length;
  }

  /**
   * Finds a character in the same line.
   * @param str The text to be searched in.
   * @param ch  The character to find.
   * @return    The pointer that points to the found chacter in str or EOL/EOF.
   */
  static const char* FindNextInline(const char* str, const char ch) {
    while (!IsLineEndingOrFileEnding(*str) && *str != ch) {
      str = NextChar(str);
    }
    return str;
  }

  /**
   * Returns true if the character is a line ending or end of file.
   */
  static bool IsLineEndingOrFileEnding(const char ch) {
    return ch == '\0' || ch == '\n' || ch == '\r';
  }

  /**
   * Copies a substring with given length to a new string.
   */
  static std::string FromSubstr(const char* str, size_t length) {
    std::string newStr;
    newStr.resize(length);
    memcpy(newStr.data(), str, length);
    return newStr;
  }

  /**
   * Returns true if the given std::string is longer or as long as the given
   * length.
   */
  static bool NotShorterThan(const char* str, size_t byteLength) {
    while (byteLength > 0) {
      if (*str == '\0') {
        return false;
      }
      byteLength--;
      str++;
    }
    return true;
  }

  /**
   * Truncates a std::string with a maximal length in byte.
   * No UTF8 character will be broken.
   */
  static std::string TruncateUTF8(const char* str, size_t maxByteLength) {
    std::string wordTrunc;
    if (NotShorterThan(str, maxByteLength)) {
      size_t len = 0;
      const char* pStr = str;
      for (;;) {
        const size_t charLength = NextCharLength(pStr);
        if (len + charLength > maxByteLength) {
          break;
        }
        pStr += charLength;
        len += charLength;
      }
      wordTrunc = FromSubstr(str, len);
    } else {
      wordTrunc = str;
    }
    return wordTrunc;
  }

  /**
   * Replaces all patterns in a std::string in place.
   */
  static void ReplaceAll(std::string& str, const char* from, const char* to) {
    std::string::size_type pos = 0;
    std::string::size_type fromLen = strlen(from);
    std::string::size_type toLen = strlen(to);
    while ((pos = str.find(from, pos)) != std::string::npos) {
      str.replace(pos, fromLen, to);
      pos += toLen;
    }
  }

  /**
   * Joins a std::string vector in to a std::string with a separator.
   */
  static std::string Join(const std::vector<std::string>& strings,
                          const std::string& separator) {
    std::ostringstream buffer;
    bool first = true;
    for (const auto& str : strings) {
      if (!first) {
        buffer << separator;
      }
      buffer << str;
      first = false;
    }
    return buffer.str();
  }

  /**
   * Joins a std::string vector in to a std::string.
   */
  static std::string Join(const std::vector<std::string>& strings) {
    std::ostringstream buffer;
    for (const auto& str : strings) {
      buffer << str;
    }
    return buffer.str();
  }

  static void GetByteMap(const char* str, const size_t utf8Length,
                         std::vector<size_t>* byteMap) {
    if (byteMap->size() < utf8Length) {
      byteMap->resize(utf8Length);
    }
    const char* pstr = str;
    for (size_t i = 0; i < utf8Length; i++) {
      (*byteMap)[i] = pstr - str;
      pstr = NextChar(pstr);
    }
  }

#ifdef _MSC_VER
  static std::wstring GetPlatformString(const std::string& str) {
    return U8ToU16(str);
  }
#else
  static std::string GetPlatformString(const std::string& str) { return str; }
#endif // _MSC_VER

#ifdef _MSC_VER
  static std::string U16ToU8(const std::wstring& wstr) {
    std::string ret;
    int length = static_cast<int>(wstr.length());
    int convcnt = WideCharToMultiByte(CP_UTF8, 0, wstr.c_str(), length, NULL, 0,
                                      NULL, NULL);
    if (convcnt > 0) {
      ret.resize(convcnt);
      WideCharToMultiByte(CP_UTF8, 0, wstr.c_str(), length, &ret[0], convcnt,
                          NULL, NULL);
    }
    return ret;
  }

  static std::wstring U8ToU16(const std::string& str) {
    std::wstring ret;
    int length = static_cast<int>(str.length());
    int convcnt = MultiByteToWideChar(CP_UTF8, 0, str.c_str(), length, NULL, 0);
    if (convcnt > 0) {
      ret.resize(convcnt);
      MultiByteToWideChar(CP_UTF8, 0, str.c_str(), length, &ret[0], convcnt);
    }
    return ret;
  }
#endif // _MSC_VER

private:
  enum class IDSParseStatus {
    Complete,
    Incomplete,
    Invalid,
  };

  static uint32_t CodePointNoException(const char* str, size_t charLen) {
    const unsigned char first = static_cast<unsigned char>(str[0]);
    if (charLen == 1) {
      return first;
    }

    uint32_t codePoint = first & ((1U << (7 - charLen)) - 1);
    for (size_t i = 1; i < charLen; i++) {
      codePoint = (codePoint << 6) |
                  (static_cast<unsigned char>(str[i]) & 0x3FU);
    }
    return codePoint;
  }

  static IDSParseStatus ConsumeIdeographicDescriptionSequence(
      const char* str, size_t len, size_t depthLeft, size_t maxCodePoints,
      size_t* consumed, size_t* codePoints) {
    if (len == 0) {
      return IDSParseStatus::Incomplete;
    }
    if (depthLeft == 0 || *codePoints >= maxCodePoints) {
      return IDSParseStatus::Invalid;
    }
    const size_t charLen = NextCharLengthNoException(str);
    if (charLen == 0) {
      return IDSParseStatus::Invalid;
    }
    if (charLen > len) {
      return IDSParseStatus::Incomplete;
    }
    ++(*codePoints);

    const uint32_t codePoint = CodePointNoException(str, charLen);
    const size_t arity = IdeographicDescriptionOperatorArity(codePoint);
    if (arity == 0) {
      *consumed = charLen;
      return IDSParseStatus::Complete;
    }

    size_t offset = charLen;
    for (size_t i = 0; i < arity; i++) {
      if (offset >= len) {
        return IDSParseStatus::Incomplete;
      }
      size_t operandLength = 0;
      const IDSParseStatus operandStatus = ConsumeIdeographicDescriptionSequence(
          str + offset, len - offset, depthLeft - 1, maxCodePoints,
          &operandLength, codePoints);
      if (operandStatus != IDSParseStatus::Complete) {
        return operandStatus;
      }
      offset += operandLength;
    }
    *consumed = offset;
    return IDSParseStatus::Complete;
  }
};
} // namespace opencc