Debian Codegraph @

src/Converter.cpp

raw symbols SCIP
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 "Converter.hpp"
20 #include "UTF8Util.hpp"
21
22 using namespace opencc;
23
24 std::string ConverterStream::ConvertChunk(std::string_view input) {
25 if (!input.empty()) {
26 pending.append(input);
27 }
28 if (pending.empty()) {
29 return std::string();
30 }
31
32 const char* bufferBegin = pending.data();
33 const char* bufferEnd = bufferBegin + pending.size();
34 const char* completeEnd = bufferBegin;
35 while (completeEnd < bufferEnd) {
36 const size_t nextCharLen = UTF8Util::NextCharLength(completeEnd);
37 if (completeEnd + nextCharLen > bufferEnd) {
38 break;
39 }
40 completeEnd += nextCharLen;
41 }
42
43 const char* keepStart = completeEnd;
44 size_t charsKept = 0;
45 while (keepStart > bufferBegin && charsKept < maxKeepChars) {
46 const size_t prevCharLen = UTF8Util::PrevCharLength(keepStart);
47 keepStart -= prevCharLen;
48 charsKept++;
49 }
50
51 const char* idsKeepStart = completeEnd;
52 const char* idsCandidate = completeEnd;
53 size_t idsCharsScanned = 0;
54 const size_t kMaxIDSCodePoints = 64;
55 while (idsCandidate > bufferBegin && idsCharsScanned < kMaxIDSCodePoints) {
56 idsCandidate -= UTF8Util::PrevCharLength(idsCandidate);
57 idsCharsScanned++;
58 if (UTF8Util::IsIncompleteIdeographicDescriptionSequencePrefix(
59 idsCandidate, completeEnd - idsCandidate)) {
60 idsKeepStart = idsCandidate;
61 }
62 }
63 if (idsKeepStart < keepStart) {
64 keepStart = idsKeepStart;
65 }
66
67 if (keepStart == bufferBegin) {
68 return std::string();
69 }
70
71 const std::string output = converter->Convert(std::string_view(
72 bufferBegin, static_cast<size_t>(keepStart - bufferBegin)));
73 pending.erase(0, static_cast<size_t>(keepStart - bufferBegin));
74 return output;
75 }
76
77 std::string ConverterStream::Finish(std::string_view input) {
78 if (!input.empty()) {
79 pending.append(input);
80 }
81 return Finish();
82 }
83
84 std::string ConverterStream::Finish() {
85 const std::string output =
86 pending.empty() ? std::string()
87 : converter->Convert(std::string_view(pending));
88 pending.clear();
89 return output;
90 }
91