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
| 3315 | // and contains invalid UTF-16 surrogate pairs, values in those pairs |
| 3316 | // will be encoded as individual Unicode characters from Basic Normal Plane. |
| 3317 | std::string WideStringToUtf8(const wchar_t* str, int num_chars) { |
| 3318 | if (num_chars == -1) |
| 3319 | num_chars = static_cast<int>(wcslen(str)); |
| 3320 | |
| 3321 | ::std::stringstream stream; |
| 3322 | for (int i = 0; i < num_chars; ++i) { |
| 3323 | UInt32 unicode_code_point; |
| 3324 | |
| 3325 | if (str[i] == L'\0') { |
| 3326 | break; |
| 3327 | } else if (i + 1 < num_chars && IsUtf16SurrogatePair(str[i], str[i + 1])) { |
| 3328 | unicode_code_point = CreateCodePointFromUtf16SurrogatePair(str[i], |
| 3329 | str[i + 1]); |
| 3330 | i++; |
| 3331 | } else { |
| 3332 | unicode_code_point = static_cast<UInt32>(str[i]); |
| 3333 | } |
| 3334 | |
| 3335 | stream << CodePointToUtf8(unicode_code_point); |
| 3336 | } |
| 3337 | return StringStreamToString(&stream); |
| 3338 | } |
| 3339 | |
| 3340 | // Converts a wide C string to an std::string using the UTF-8 encoding. |
| 3341 | // NULL will be converted to "(null)". |
no test coverage detected