Commit 76bd5002 authored by Chen Bill's avatar Chen Bill

add EncodeUTF8String, DecodeUTF8String

parent fe93928a
...@@ -27,6 +27,7 @@ public: ...@@ -27,6 +27,7 @@ public:
inline static void WriteInt8(unsigned char*& p, char val) { inline static void WriteInt8(unsigned char*& p, char val) {
buffer_write<char>(p, val); buffer_write<char>(p, val);
} }
// return: string length
template<typename T1, typename T2> template<typename T1, typename T2>
inline static int CopyWStr(T1* src, T2* pstr, int bufsize) { inline static int CopyWStr(T1* src, T2* pstr, int bufsize) {
int l = 0; int l = 0;
...@@ -49,8 +50,8 @@ public: ...@@ -49,8 +50,8 @@ public:
return l; return l;
} }
// UTF-16/UTF-32 to UTF-8 // UTF-16/UTF-32 to UTF-8
template<size_t N> // return: string length
static int EncodeUTF8(const wchar_t* wsrc, char(&str)[N]) { static int EncodeUTF8String(const wchar_t* wsrc, char* str, int size) {
char* pstr = str; char* pstr = str;
while (*wsrc != 0) { while (*wsrc != 0) {
unsigned cur = *wsrc; unsigned cur = *wsrc;
...@@ -63,7 +64,7 @@ public: ...@@ -63,7 +64,7 @@ public:
codepoint_size = 3; codepoint_size = 3;
else else
codepoint_size = 4; codepoint_size = 4;
if (pstr - str + codepoint_size > N - 1) if (pstr - str + codepoint_size > size - 1)
break; break;
switch (codepoint_size) { switch (codepoint_size) {
case 1: case 1:
...@@ -101,8 +102,8 @@ public: ...@@ -101,8 +102,8 @@ public:
return pstr - str; return pstr - str;
} }
// UTF-8 to UTF-16/UTF-32 // UTF-8 to UTF-16/UTF-32
template<size_t N> // return: string length
static int DecodeUTF8(const char* src, wchar_t(&wstr)[N]) { static int DecodeUTF8String(const char* src, wchar_t* wstr, int size) {
const char* p = src; const char* p = src;
wchar_t* wp = wstr; wchar_t* wp = wstr;
while(*p != 0) { while(*p != 0) {
...@@ -116,7 +117,7 @@ public: ...@@ -116,7 +117,7 @@ public:
} }
else else
codepoint_size = 1; codepoint_size = 1;
if (wp - wstr + codepoint_size > N - 1) if (wp - wstr + codepoint_size > size - 1)
break; break;
if((cur & 0x80) == 0) { if((cur & 0x80) == 0) {
*wp = *p; *wp = *p;
...@@ -144,6 +145,14 @@ public: ...@@ -144,6 +145,14 @@ public:
*wp = 0; *wp = 0;
return wp - wstr; return wp - wstr;
} }
template<size_t N>
static int EncodeUTF8(const wchar_t* src, char(&dst)[N]) {
return EncodeUTF8String(src, dst, N);
}
template<size_t N>
static int DecodeUTF8(const char* src, wchar_t(&dst)[N]) {
return DecodeUTF8String(src, dst, N);
}
static int GetVal(const wchar_t* pstr) { static int GetVal(const wchar_t* pstr) {
unsigned int ret = 0; unsigned int ret = 0;
while(*pstr >= L'0' && *pstr <= L'9') { while(*pstr >= L'0' && *pstr <= L'9') {
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment