载入中...
搜索中...
未找到
utf8.cpp
浏览该文件的文档.
1#include "utf8.h"
2
3namespace eve
4{
5
6namespace {
7
8size_t utf8_step(unsigned char c)
9{
10 if ((c & 0x80) == 0)
11 return 1;
12 if ((c & 0xE0) == 0xC0)
13 return 2;
14 if ((c & 0xF0) == 0xE0)
15 return 3;
16 if ((c & 0xF8) == 0xF0)
17 return 4;
18 return 1;
19}
20
21} // namespace
22
23size_t utf8_codepoint_count(const std::string &s)
24{
25 size_t n = 0;
26 for (size_t i = 0; i < s.size();)
27 {
28 const size_t step = utf8_step(static_cast<unsigned char>(s[i]));
29 if (i + step > s.size())
30 break;
31 i += step;
32 ++n;
33 }
34 return n;
35}
36
37size_t utf8_byte_offset_for_codepoints(const std::string &s, size_t codepoints)
38{
39 size_t n = 0;
40 size_t i = 0;
41 while (i < s.size() && n < codepoints)
42 {
43 const size_t step = utf8_step(static_cast<unsigned char>(s[i]));
44 if (i + step > s.size())
45 break;
46 i += step;
47 ++n;
48 }
49 return i;
50}
51
52#ifdef EVENGINE_WINDOWS
53
54std::string to_utf8(LPCWSTR wstr)
55{
56 size_t wide_len = wcslen(wstr)+1;
57
58 // Get size in UTF-8.
59 int utf8_size = WideCharToMultiByte(CP_UTF8, 0, wstr, wide_len, 0, 0, 0, 0);
60
61 char *utf8_str = new char[utf8_size];
62
63 // Convert to UTF-8.
64 int ok = WideCharToMultiByte(CP_UTF8, 0, wstr, wide_len, utf8_str, utf8_size, 0, 0);
65
66 std::string ret;
67 if (ok)
68 ret = utf8_str;
69
70 delete[] utf8_str;
71 return ret;
72}
73
74std::wstring to_widestr(const std::string &str)
75{
76 if (str.empty())
77 return std::wstring();
78
79 int wide_size = MultiByteToWideChar(CP_UTF8, 0, str.c_str(), (int) str.length(), nullptr, 0);
80
81 if (wide_size == 0)
82 return std::wstring();
83
84 std::wstring widestr;
85 widestr.resize(wide_size);
86
87 int ok = MultiByteToWideChar(CP_UTF8, 0, str.c_str(), (int) str.length(), &widestr[0], widestr.length());
88
89 if (!ok)
90 return std::wstring();
91
92 return widestr;
93}
94
95void replace_char(std::string &str, char find, char replace)
96{
97 int length = str.length();
98
99 for (int i = 0; i<length; i++)
100 {
101 if (str[i] == find)
102 str[i] = replace;
103 }
104}
105
106#endif // EVENGINE_WINDOWS
107
108} // eve
glm::vec3 n
Definition Grass.cpp:64
uint32_t c
float step
Definition TreeMesh.cpp:196
uint32_t s
Definition Weather.cpp:28
Definition Build.cpp:11
size_t utf8_codepoint_count(const std::string &s)
Count UTF-8 code points in a string. Invalid / truncated sequences stop the scan.
Definition utf8.cpp:23
size_t utf8_byte_offset_for_codepoints(const std::string &s, size_t codepoints)
Byte offset of the N-th UTF-8 code point (0-based count of code points). Returns s....
Definition utf8.cpp:37