Debian Codegraph @

src/Conversion.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 "Conversion.hpp"
20 #include "PrefixMatch.hpp"
21 #include "Segments.hpp"
22 #include "UTF8Util.hpp"
23
24 using namespace opencc;
25
26 Conversion::Conversion(DictPtr _dict)
27 : dict(_dict), prefixMatch(new PrefixMatch(_dict)) {}
28
29 void Conversion::AppendConverted(std::string_view phrase,
30 std::string* output) const {
31 if (phrase.empty()) {
32 return;
33 }
34 const size_t phraseLength = phrase.size();
35 output->reserve(output->size() + phraseLength + phraseLength / 5);
36
37 const char* phraseData = phrase.data();
38 const char* phraseEnd = phraseData + phraseLength;
39 for (const char* pstr = phraseData; pstr < phraseEnd;) {
40 size_t remainingLength = phraseEnd - pstr;
41 const PrefixMatchView matched =
42 prefixMatch->MatchPrefixView(pstr, remainingLength);
43 size_t matchedLength;
44 if (!matched.matched) {
45 matchedLength =
46 UTF8Util::NextIdeographicDescriptionSequenceLength(pstr,
47 remainingLength);
48 if (matchedLength == 0) {
49 matchedLength = UTF8Util::NextCharLength(pstr);
50 }
51 if (matchedLength > remainingLength) {
52 matchedLength = remainingLength;
53 }
54 output->append(pstr, matchedLength);
55 } else {
56 matchedLength = matched.keyLength;
57 if (matchedLength > remainingLength) {
58 matchedLength = remainingLength;
59 }
60 output->append(matched.value.data(), matched.value.size());
61 }
62 pstr += matchedLength;
63 }
64 }
65
66 std::string Conversion::Convert(std::string_view phrase) const {
67 if (phrase.empty()) {
68 return std::string();
69 }
70 std::string buffer;
71 AppendConverted(phrase, &buffer);
72 return buffer;
73 }
74
75 std::string Conversion::Convert(const char* phrase) const {
76 return Convert(std::string_view(phrase));
77 }
78
79 void Conversion::AppendConverted(const char* phrase, std::string* output) const {
80 AppendConverted(std::string_view(phrase), output);
81 }
82
83 SegmentsPtr Conversion::Convert(const SegmentsPtr& input) const {
84 SegmentsPtr output(new Segments);
85 for (const char* segment : *input) {
86 output->AddSegment(Convert(segment));
87 }
88 return output;
89 }