Converts a wide string to a narrow string in UTF-8 encoding. The wide string is assumed to have the following encoding: UTF-16 if sizeof(wchar_t) == 2 (on Windows, Cygwin) UTF-32 if sizeof(wchar_t) == 4 (on Linux) Parameter str points to a null-terminated wide string. Parameter num_chars may additionally limit the number of wchar_t characters processed. -1 is used when the entire string should be
| 2036 | // and contains invalid UTF-16 surrogate pairs, values in those pairs |
| 2037 | // will be encoded as individual Unicode characters from Basic Normal Plane. |
| 2038 | std::string WideStringToUtf8(const wchar_t* str, int num_chars) { |
| 2039 | if (num_chars == -1) num_chars = static_cast<int>(wcslen(str)); |
| 2040 | |
| 2041 | ::std::stringstream stream; |
| 2042 | for (int i = 0; i < num_chars; ++i) { |
| 2043 | uint32_t unicode_code_point; |
| 2044 | |
| 2045 | if (str[i] == L'\0') { |
| 2046 | break; |
| 2047 | } else if (i + 1 < num_chars && IsUtf16SurrogatePair(str[i], str[i + 1])) { |
| 2048 | unicode_code_point = |
| 2049 | CreateCodePointFromUtf16SurrogatePair(str[i], str[i + 1]); |
| 2050 | i++; |
| 2051 | } else { |
| 2052 | unicode_code_point = static_cast<uint32_t>(str[i]); |
| 2053 | } |
| 2054 | |
| 2055 | stream << CodePointToUtf8(unicode_code_point); |
| 2056 | } |
| 2057 | return StringStreamToString(&stream); |
| 2058 | } |
| 2059 | |
| 2060 | // Converts a wide C string to an std::string using the UTF-8 encoding. |
| 2061 | // NULL will be converted to "(null)". |
no test coverage detected