Converts a Unicode code point to a narrow string in UTF-8 encoding. code_point parameter is of type UInt32 because wchar_t may not be wide enough to contain a code point. If the code_point is not a valid Unicode code point (i.e. outside of Unicode range U+0 to U+10FFFF) it will be converted to "(Invalid Unicode 0xXXXXXXXX)".
| 3229 | // (i.e. outside of Unicode range U+0 to U+10FFFF) it will be converted |
| 3230 | // to "(Invalid Unicode 0xXXXXXXXX)". |
| 3231 | std::string CodePointToUtf8(UInt32 code_point) { |
| 3232 | if (code_point > kMaxCodePoint4) { |
| 3233 | return "(Invalid Unicode 0x" + String::FormatHexInt(code_point) + ")"; |
| 3234 | } |
| 3235 | |
| 3236 | char str[5]; // Big enough for the largest valid code point. |
| 3237 | if (code_point <= kMaxCodePoint1) { |
| 3238 | str[1] = '\0'; |
| 3239 | str[0] = static_cast<char>(code_point); // 0xxxxxxx |
| 3240 | } else if (code_point <= kMaxCodePoint2) { |
| 3241 | str[2] = '\0'; |
| 3242 | str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx |
| 3243 | str[0] = static_cast<char>(0xC0 | code_point); // 110xxxxx |
| 3244 | } else if (code_point <= kMaxCodePoint3) { |
| 3245 | str[3] = '\0'; |
| 3246 | str[2] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx |
| 3247 | str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx |
| 3248 | str[0] = static_cast<char>(0xE0 | code_point); // 1110xxxx |
| 3249 | } else { // code_point <= kMaxCodePoint4 |
| 3250 | str[4] = '\0'; |
| 3251 | str[3] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx |
| 3252 | str[2] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx |
| 3253 | str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx |
| 3254 | str[0] = static_cast<char>(0xF0 | code_point); // 11110xxx |
| 3255 | } |
| 3256 | return str; |
| 3257 | } |
| 3258 | |
| 3259 | // The following two functions only make sense if the the system |
| 3260 | // uses UTF-16 for wide string encoding. All supported systems |
no test coverage detected