Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
hrydgard
GitHub Repository: hrydgard/ppsspp
Path: blob/master/Common/Data/Encoding/Utf8.cpp
3187 views
1
/*
2
Basic UTF-8 manipulation routines
3
by Jeff Bezanson
4
placed in the public domain Fall 2005
5
6
This code is designed to provide the utilities you need to manipulate
7
UTF-8 as an internal string encoding. These functions do not perform the
8
error checking normally needed when handling UTF-8 data, so if you happen
9
to be from the Unicode Consortium you will want to flay me alive.
10
I do this because error checking can be performed at the boundaries (I/O),
11
with these routines reserved for higher performance on data known to be
12
valid.
13
*/
14
15
#ifdef _WIN32
16
#define NOMINMAX
17
#include <windows.h>
18
#endif
19
20
#include <cstdlib>
21
#include <cstdio>
22
#include <cstring>
23
#include <cstdarg>
24
#include <cstdint>
25
#include <algorithm>
26
#include <string>
27
28
#include "Common/Data/Encoding/Utf8.h"
29
#include "Common/Data/Encoding/Utf16.h"
30
#include "Common/Log.h"
31
32
// is start of UTF sequence
33
inline bool isutf(char c) {
34
return (c & 0xC0) != 0x80;
35
}
36
37
static const uint32_t offsetsFromUTF8[6] = {
38
0x00000000UL, 0x00003080UL, 0x000E2080UL,
39
0x03C82080UL, 0xFA082080UL, 0x82082080UL
40
};
41
42
static const uint8_t trailingBytesForUTF8[256] = {
43
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
44
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
45
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
46
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
47
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
48
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
49
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
50
2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, 3,3,3,3,3,3,3,3,4,4,4,4,5,5,5,5,
51
};
52
53
int u8_wc_toutf8(char *dest, uint32_t ch)
54
{
55
if (ch < 0x80) {
56
dest[0] = (char)ch;
57
return 1;
58
}
59
if (ch < 0x800) {
60
dest[0] = (ch>>6) | 0xC0;
61
dest[1] = (ch & 0x3F) | 0x80;
62
return 2;
63
}
64
if (ch < 0x10000) {
65
dest[0] = (ch>>12) | 0xE0;
66
dest[1] = ((ch>>6) & 0x3F) | 0x80;
67
dest[2] = (ch & 0x3F) | 0x80;
68
return 3;
69
}
70
if (ch < 0x110000) {
71
dest[0] = (ch>>18) | 0xF0;
72
dest[1] = ((ch>>12) & 0x3F) | 0x80;
73
dest[2] = ((ch>>6) & 0x3F) | 0x80;
74
dest[3] = (ch & 0x3F) | 0x80;
75
return 4;
76
}
77
return 0;
78
}
79
80
/* charnum => byte offset */
81
int u8_offset(const char *str, int charnum)
82
{
83
int offs=0;
84
85
while (charnum > 0 && str[offs]) {
86
(void)(isutf(str[++offs]) || isutf(str[++offs]) ||
87
isutf(str[++offs]) || ++offs);
88
charnum--;
89
}
90
return offs;
91
}
92
93
/* byte offset => charnum */
94
int u8_charnum(const char *s, int offset)
95
{
96
int charnum = 0, offs=0;
97
98
while (offs < offset && s[offs]) {
99
(void)(isutf(s[++offs]) || isutf(s[++offs]) ||
100
isutf(s[++offs]) || ++offs);
101
charnum++;
102
}
103
return charnum;
104
}
105
106
/* reads the next utf-8 sequence out of a string, updating an index */
107
uint32_t u8_nextchar(const char *s, int *index, size_t size) {
108
uint32_t ch = 0;
109
_dbg_assert_(*index >= 0 && *index < 100000000);
110
int sz = 0;
111
int i = *index;
112
do {
113
ch = (ch << 6) + (unsigned char)s[i++];
114
sz++;
115
} while (i < size && s[i] && ((s[i]) & 0xC0) == 0x80);
116
*index = i;
117
return ch - offsetsFromUTF8[sz - 1];
118
}
119
120
uint32_t u8_nextchar_unsafe(const char *s, int *i) {
121
uint32_t ch = (unsigned char)s[(*i)++];
122
int sz = 1;
123
if (ch >= 0xF0) {
124
sz++;
125
ch &= ~0x10;
126
}
127
if (ch >= 0xE0) {
128
sz++;
129
ch &= ~0x20;
130
}
131
if (ch >= 0xC0) {
132
sz++;
133
ch &= ~0xC0;
134
}
135
136
// Just assume the bytes must be there. This is the logic used on the PSP.
137
for (int j = 1; j < sz; ++j) {
138
ch <<= 6;
139
ch += ((unsigned char)s[(*i)++]) & 0x3F;
140
}
141
return ch;
142
}
143
144
void u8_inc(const char *s, int *i) {
145
(void)(isutf(s[++(*i)]) || isutf(s[++(*i)]) ||
146
isutf(s[++(*i)]) || ++(*i));
147
}
148
149
void u8_dec(const char *s, int *i) {
150
(void)(isutf(s[--(*i)]) || isutf(s[--(*i)]) ||
151
isutf(s[--(*i)]) || --(*i));
152
}
153
154
bool AnyEmojiInString(std::string_view str, size_t byteCount) {
155
int i = 0;
156
while (i < byteCount) {
157
uint32_t c = u8_nextchar(str.data(), &i, str.size());
158
if (CodepointIsProbablyEmoji(c)) {
159
return true;
160
}
161
}
162
return false;
163
}
164
165
int UTF8StringNonASCIICount(std::string_view utf8string) {
166
UTF8 utf(utf8string);
167
int count = 0;
168
while (!utf.end()) {
169
int c = utf.next();
170
if (c > 127)
171
++count;
172
}
173
return count;
174
}
175
176
bool UTF8StringHasNonASCII(std::string_view utf8string) {
177
return UTF8StringNonASCIICount(utf8string) > 0;
178
}
179
180
#ifdef _WIN32
181
182
std::string ConvertWStringToUTF8(const wchar_t *wstr) {
183
int len = (int)wcslen(wstr);
184
int size = (int)WideCharToMultiByte(CP_UTF8, 0, wstr, len, 0, 0, NULL, NULL);
185
std::string s;
186
s.resize(size);
187
if (size > 0) {
188
WideCharToMultiByte(CP_UTF8, 0, wstr, len, &s[0], size, NULL, NULL);
189
}
190
return s;
191
}
192
193
std::string ConvertWStringToUTF8(const std::wstring &wstr) {
194
int len = (int)wstr.size();
195
int size = (int)WideCharToMultiByte(CP_UTF8, 0, wstr.c_str(), len, 0, 0, NULL, NULL);
196
std::string s;
197
s.resize(size);
198
if (size > 0) {
199
WideCharToMultiByte(CP_UTF8, 0, wstr.c_str(), len, &s[0], size, NULL, NULL);
200
}
201
return s;
202
}
203
204
void ConvertUTF8ToWString(wchar_t *dest, size_t destSize, std::string_view source) {
205
int len = (int)source.size();
206
destSize -= 1; // account for the \0.
207
int size = (int)MultiByteToWideChar(CP_UTF8, 0, source.data(), len, NULL, 0);
208
MultiByteToWideChar(CP_UTF8, 0, source.data(), len, dest, std::min((int)destSize, size));
209
dest[size] = 0;
210
}
211
212
std::wstring ConvertUTF8ToWString(const std::string_view source) {
213
int len = (int)source.size();
214
int size = (int)MultiByteToWideChar(CP_UTF8, 0, source.data(), len, NULL, 0);
215
std::wstring str;
216
str.resize(size);
217
if (size > 0) {
218
MultiByteToWideChar(CP_UTF8, 0, source.data(), (int)source.size(), &str[0], size);
219
}
220
return str;
221
}
222
223
#endif
224
225
std::string ConvertUCS2ToUTF8(const std::u16string &wstr) {
226
std::string s;
227
// Worst case.
228
s.resize(wstr.size() * 4);
229
230
size_t pos = 0;
231
for (wchar_t c : wstr) {
232
pos += UTF8::encode(&s[pos], c);
233
}
234
235
s.resize(pos);
236
return s;
237
}
238
239
std::string SanitizeUTF8(std::string_view utf8string) {
240
UTF8 utf(utf8string);
241
std::string s;
242
// Worst case.
243
s.resize(utf8string.size() * 4);
244
245
// This stops at invalid start bytes.
246
size_t pos = 0;
247
while (!utf.end() && !utf.invalid()) {
248
int c = utf.next_unsafe();
249
pos += UTF8::encode(&s[pos], c);
250
}
251
s.resize(pos);
252
return s;
253
}
254
255
static size_t ConvertUTF8ToUCS2Internal(char16_t *dest, size_t destSize, std::string_view source) {
256
const char16_t *const orig = dest;
257
const char16_t *const destEnd = dest + destSize;
258
259
UTF8 utf(source);
260
261
char16_t *destw = (char16_t *)dest;
262
const char16_t *const destwEnd = destw + destSize;
263
264
// Ignores characters outside the BMP.
265
while (uint32_t c = utf.next()) {
266
if (destw + UTF16LE::encodeUnitsUCS2(c) >= destwEnd) {
267
break;
268
}
269
destw += UTF16LE::encodeUCS2(destw, c);
270
}
271
272
// No ++ to not count the null-terminator in length.
273
if (destw < destEnd) {
274
*destw = 0;
275
}
276
277
return destw - orig;
278
}
279
280
std::u16string ConvertUTF8ToUCS2(std::string_view source) {
281
std::u16string dst;
282
dst.resize(source.size() + 1, 0); // multiple UTF-8 chars will be one UCS2 char. But we need to leave space for a terminating null.
283
size_t realLen = ConvertUTF8ToUCS2Internal(&dst[0], dst.size(), source);
284
dst.resize(realLen);
285
return dst;
286
}
287
288
std::string CodepointToUTF8(uint32_t codePoint) {
289
char temp[16]{};
290
UTF8::encode(temp, codePoint);
291
return std::string(temp);
292
}
293
294
// Helper function to encode a Unicode code point into UTF-8, but doesn't support 4-byte output.
295
size_t encode_utf8_modified(uint32_t code_point, unsigned char* output) {
296
if (code_point <= 0x7F) {
297
output[0] = (unsigned char)code_point;
298
return 1;
299
} else if (code_point <= 0x7FF) {
300
output[0] = (unsigned char)(0xC0 | (code_point >> 6));
301
output[1] = (unsigned char)(0x80 | (code_point & 0x3F));
302
return 2;
303
} else if (code_point <= 0xFFFF) {
304
output[0] = (unsigned char)(0xE0 | (code_point >> 12));
305
output[1] = (unsigned char)(0x80 | ((code_point >> 6) & 0x3F));
306
output[2] = (unsigned char)(0x80 | (code_point & 0x3F));
307
return 3;
308
}
309
return 0;
310
}
311
312
// A function to convert regular UTF-8 to Java Modified UTF-8. Only used on Android.
313
// Written by ChatGPT and corrected and modified.
314
void ConvertUTF8ToJavaModifiedUTF8(std::string *output, std::string_view input) {
315
output->resize(input.length() * 6); // worst case: every character is encoded as 6 bytes. shouldn't happen, though.
316
size_t out_idx = 0;
317
for (size_t i = 0; i < input.length(); ) {
318
unsigned char c = input[i];
319
if (c == 0) {
320
// Encode null character as 0xC0 0x80. TODO: We probably don't need to support this?
321
output[out_idx++] = (char)0xC0;
322
output[out_idx++] = (char)0x80;
323
i++;
324
} else if ((c & 0xF0) == 0xF0) { // 4-byte sequence (U+10000 to U+10FFFF)
325
if (i + 4 > input.length()) {
326
// Bad.
327
break;
328
}
329
// Decode the Unicode code point from the UTF-8 sequence
330
uint32_t code_point = ((input[i] & 0x07) << 18) |
331
((input[i + 1] & 0x3F) << 12) |
332
((input[i + 2] & 0x3F) << 6) |
333
(input[i + 3] & 0x3F);
334
335
// Convert to surrogate pair
336
uint16_t high_surrogate = ((code_point - 0x10000) / 0x400) + 0xD800;
337
uint16_t low_surrogate = ((code_point - 0x10000) % 0x400) + 0xDC00;
338
339
// Encode the surrogates in UTF-8. encode_utf8_modified outputs at most 3 bytes.
340
out_idx += encode_utf8_modified(high_surrogate, (unsigned char *)(output->data() + out_idx));
341
out_idx += encode_utf8_modified(low_surrogate, (unsigned char *)(output->data() + out_idx));
342
343
i += 4;
344
} else {
345
// Copy the other UTF-8 sequences (1-3 bytes)
346
size_t utf8_len = 1;
347
if ((c & 0xE0) == 0xC0) {
348
utf8_len = 2; // 2-byte sequence
349
} else if ((c & 0xF0) == 0xE0) {
350
utf8_len = 3; // 3-byte sequence
351
}
352
if (i + utf8_len > input.length()) {
353
break;
354
}
355
memcpy(output->data() + out_idx, input.data() + i, utf8_len);
356
out_idx += utf8_len;
357
i += utf8_len;
358
}
359
}
360
output->resize(out_idx);
361
_dbg_assert_(output->size() >= input.size());
362
}
363
364
#ifndef _WIN32
365
366
// Replacements for the Win32 wstring functions. Not to be used from emulation code!
367
368
std::string ConvertWStringToUTF8(const std::wstring &wstr) {
369
std::string s;
370
// Worst case.
371
s.resize(wstr.size() * 4);
372
373
size_t pos = 0;
374
for (wchar_t c : wstr) {
375
pos += UTF8::encode(&s[pos], c);
376
}
377
378
s.resize(pos);
379
return s;
380
}
381
382
static size_t ConvertUTF8ToWStringInternal(wchar_t *dest, size_t destSize, std::string_view source) {
383
const wchar_t *const orig = dest;
384
const wchar_t *const destEnd = dest + destSize;
385
386
UTF8 utf(source);
387
388
if (sizeof(wchar_t) == 2) {
389
char16_t *destw = (char16_t *)dest;
390
const char16_t *const destwEnd = destw + destSize;
391
while (char32_t c = utf.next()) {
392
if (destw + UTF16LE::encodeUnits(c) >= destwEnd) {
393
break;
394
}
395
destw += UTF16LE::encode(destw, c);
396
}
397
dest = (wchar_t *)destw;
398
} else {
399
while (char32_t c = utf.next()) {
400
if (dest + 1 >= destEnd) {
401
break;
402
}
403
*dest++ = c;
404
}
405
}
406
407
// No ++ to not count the terminal in length.
408
if (dest < destEnd) {
409
*dest = 0;
410
}
411
412
return dest - orig;
413
}
414
415
std::wstring ConvertUTF8ToWString(std::string_view source) {
416
std::wstring dst;
417
// conservative size estimate for wide characters from utf-8 bytes. Will always reserve too much space.
418
dst.resize(source.size());
419
size_t realLen = ConvertUTF8ToWStringInternal(&dst[0], source.size(), source);
420
dst.resize(realLen); // no need to write a NUL, it's done for us by resize.
421
return dst;
422
}
423
424
#endif
425
426