Open Chinese Convert: UTF8Util.hpp Source File

Open Chinese Convert 1.3.1+g1a12f2dc6.dirty A project for conversion between Traditional and Simplified Chinese

Loading...
Searching...
No Matches
UTF8Util.hpp
1/*
2 * Open Chinese Convert
3 *
4 * Copyright 2013 Carbo Kuo <byvoid@byvoid.com>
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#pragma once
20
21#ifdef _MSC_VER
22#ifndef NOMINMAX
23#define NOMINMAX
24#endif
25#include <Windows.h>
26#endif // _MSC_VER
27
28#include <cstring>
29
30#include "Common.hpp"
31#include "Exception.hpp"
32
33namespace opencc {
38 class OPENCC_EXPORT UTF8Util {
39public:
43 static void SkipUtf8Bom(FILE* fp);
44
49 static size_t NextCharLengthNoException(const char* str) {
50 const unsigned char ch = static_cast<unsigned char>(*str);
51 if ((ch & 0xF0) == 0xE0) {
52 return 3;
53 } else if ((ch & 0x80) == 0x00) {
54 return 1;
55 } else if ((ch & 0xE0) == 0xC0) {
56 return 2;
57 } else if ((ch & 0xF8) == 0xF0) {
58 return 4;
59 } else if ((ch & 0xFC) == 0xF8) {
60 return 5;
61 } else if ((ch & 0xFE) == 0xFC) {
62 return 6;
63 }
64 return 0;
65 }
66
70 static size_t NextCharLength(const char* str) {
71 size_t length = NextCharLengthNoException(str);
72 if (length == 0) {
73 throw InvalidUTF8(str);
74 }
75 return length;
76 }
77
81 static size_t PrevCharLength(const char* str) {
82 const char* candidate = str - 1;
83 size_t distance = 1;
84 while (distance < 6) {
85 const unsigned char ch = static_cast<unsigned char>(*candidate);
86 if ((ch & 0xC0) != 0x80) {
87 break;
88 }
89 candidate--;
90 distance++;
91 }
92
93 const size_t length = NextCharLengthNoException(candidate);
94 if (length == distance) {
95 return length;
96 }
97 throw InvalidUTF8(str);
98 }
99
103 static const char* NextChar(const char* str) {
104 return str + NextCharLength(str);
105 }
106
110 static const char* PrevChar(const char* str) {
111 return str - PrevCharLength(str);
112 }
113
120 static size_t Length(const char* str) {
121 size_t length = 0;
122 while (*str != '\0') {
123 const size_t charLen = NextCharLengthNoException(str);
124 if (charLen == 0) {
125 throw InvalidUTF8(str);
126 }
127 // Verify all continuation bytes are present before the null terminator.
128 // Use a while loop (not a for-with-return) to avoid complex control flow
129 // that triggers MSVC LTCG code-generator bugs.
130 size_t i = 1;
131 while (i < charLen && str[i] != '\0') {
132 ++i;
133 }
134 if (i < charLen) {
135 throw InvalidUTF8(str); // Truncated sequence: throw, don't silently skip
136 }
137 str += charLen;
138 ++length;
139 }
140 return length;
141 }
142
149 static const char* FindNextInline(const char* str, const char ch) {
150 while (!IsLineEndingOrFileEnding(*str) && *str != ch) {
151 str = NextChar(str);
152 }
153 return str;
154 }
155
159 static bool IsLineEndingOrFileEnding(const char ch) {
160 return ch == '\0' || ch == '\n' || ch == '\r';
161 }
162
166 static std::string FromSubstr(const char* str, size_t length) {
167 std::string newStr;
168 newStr.resize(length);
169 strncpy(newStr.data(), str, length);
170 return newStr;
171 }
172
177 static bool NotShorterThan(const char* str, size_t byteLength) {
178 while (byteLength > 0) {
179 if (*str == '\0') {
180 return false;
181 }
182 byteLength--;
183 str++;
184 }
185 return true;
186 }
187
192 static std::string TruncateUTF8(const char* str, size_t maxByteLength) {
193 std::string wordTrunc;
194 if (NotShorterThan(str, maxByteLength)) {
195 size_t len = 0;
196 const char* pStr = str;
197 for (;;) {
198 const size_t charLength = NextCharLength(pStr);
199 if (len + charLength > maxByteLength) {
200 break;
201 }
202 pStr += charLength;
203 len += charLength;
204 }
205 wordTrunc = FromSubstr(str, len);
206 } else {
207 wordTrunc = str;
208 }
209 return wordTrunc;
210 }
211
215 static void ReplaceAll(std::string& str, const char* from, const char* to) {
216 std::string::size_type pos = 0;
217 std::string::size_type fromLen = strlen(from);
218 std::string::size_type toLen = strlen(to);
219 while ((pos = str.find(from, pos)) != std::string::npos) {
220 str.replace(pos, fromLen, to);
221 pos += toLen;
222 }
223 }
224
228 static std::string Join(const std::vector<std::string>& strings,
229 const std::string& separator) {
230 std::ostringstream buffer;
231 bool first = true;
232 for (const auto& str : strings) {
233 if (!first) {
234 buffer << separator;
235 }
236 buffer << str;
237 first = false;
238 }
239 return buffer.str();
240 }
241
245 static std::string Join(const std::vector<std::string>& strings) {
246 std::ostringstream buffer;
247 for (const auto& str : strings) {
248 buffer << str;
249 }
250 return buffer.str();
251 }
252
253 static void GetByteMap(const char* str, const size_t utf8Length,
254 std::vector<size_t>* byteMap) {
255 if (byteMap->size() < utf8Length) {
256 byteMap->resize(utf8Length);
257 }
258 const char* pstr = str;
259 for (size_t i = 0; i < utf8Length; i++) {
260 (*byteMap)[i] = pstr - str;
261 pstr = NextChar(pstr);
262 }
263 }
264
265#ifdef _MSC_VER
266 static std::wstring GetPlatformString(const std::string& str) {
267 return U8ToU16(str);
268 }
269#else
270 static std::string GetPlatformString(const std::string& str) { return str; }
271#endif // _MSC_VER
272
273#ifdef _MSC_VER
274 static std::string U16ToU8(const std::wstring& wstr) {
275 std::string ret;
276 int length = static_cast<int>(wstr.length());
277 int convcnt = WideCharToMultiByte(CP_UTF8, 0, wstr.c_str(), length, NULL, 0,
278 NULL, NULL);
279 if (convcnt > 0) {
280 ret.resize(convcnt);
281 WideCharToMultiByte(CP_UTF8, 0, wstr.c_str(), length, &ret[0], convcnt,
282 NULL, NULL);
283 }
284 return ret;
285 }
286
287 static std::wstring U8ToU16(const std::string& str) {
288 std::wstring ret;
289 int length = static_cast<int>(str.length());
290 int convcnt = MultiByteToWideChar(CP_UTF8, 0, str.c_str(), length, NULL, 0);
291 if (convcnt > 0) {
292 ret.resize(convcnt);
293 MultiByteToWideChar(CP_UTF8, 0, str.c_str(), length, &ret[0], convcnt);
294 }
295 return ret;
296 }
297#endif // _MSC_VER
298};
299} // namespace opencc
opencc::InvalidUTF8
Definition Exception.hpp:77
opencc::UTF8Util
UTF8 std::string utilities.
Definition UTF8Util.hpp:38
opencc::UTF8Util::IsLineEndingOrFileEnding
static bool IsLineEndingOrFileEnding(const char ch)
Returns true if the character is a line ending or end of file.
Definition UTF8Util.hpp:159
opencc::UTF8Util::PrevCharLength
static size_t PrevCharLength(const char *str)
Returns the length in byte for the previous UTF8 character.
Definition UTF8Util.hpp:81
opencc::UTF8Util::FromSubstr
static std::string FromSubstr(const char *str, size_t length)
Copies a substring with given length to a new string.
Definition UTF8Util.hpp:166
opencc::UTF8Util::ReplaceAll
static void ReplaceAll(std::string &str, const char *from, const char *to)
Replaces all patterns in a std::string in place.
Definition UTF8Util.hpp:215
opencc::UTF8Util::SkipUtf8Bom
static void SkipUtf8Bom(FILE *fp)
Detect UTF8 BOM and skip it.
Definition UTF8Util.cpp:23
opencc::UTF8Util::NextCharLengthNoException
static size_t NextCharLengthNoException(const char *str)
Returns the length in byte for the next UTF8 character.
Definition UTF8Util.hpp:49
opencc::UTF8Util::NotShorterThan
static bool NotShorterThan(const char *str, size_t byteLength)
Returns true if the given std::string is longer or as long as the given length.
Definition UTF8Util.hpp:177
opencc::UTF8Util::Join
static std::string Join(const std::vector< std::string > &strings)
Joins a std::string vector in to a std::string.
Definition UTF8Util.hpp:245
opencc::UTF8Util::TruncateUTF8
static std::string TruncateUTF8(const char *str, size_t maxByteLength)
Truncates a std::string with a maximal length in byte.
Definition UTF8Util.hpp:192
opencc::UTF8Util::Length
static size_t Length(const char *str)
Returns the UTF8 length of a null-terminated string.
Definition UTF8Util.hpp:120
opencc::UTF8Util::FindNextInline
static const char * FindNextInline(const char *str, const char ch)
Finds a character in the same line.
Definition UTF8Util.hpp:149
opencc::UTF8Util::NextCharLength
static size_t NextCharLength(const char *str)
Returns the length in byte for the next UTF8 character.
Definition UTF8Util.hpp:70
opencc::UTF8Util::Join
static std::string Join(const std::vector< std::string > &strings, const std::string &separator)
Joins a std::string vector in to a std::string with a separator.
Definition UTF8Util.hpp:228
opencc::UTF8Util::PrevChar
static const char * PrevChar(const char *str)
Move the char* pointer before the previous UTF8 character.
Definition UTF8Util.hpp:110
opencc::UTF8Util::NextChar
static const char * NextChar(const char *str)
Returns the char* pointer over the next UTF8 character.
Definition UTF8Util.hpp:103