MCPcopy Create free account
hub / github.com/OpenPTrack/open_ptrack_v2 / CodePointToUtf8

Function CodePointToUtf8

rtpose_wrapper/src/gtest/gtest-all.cpp:2738–2769  ·  view source on GitHub ↗

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. The output buffer str must containt at least 32 characters. The function returns the address of the output buffer. 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 out

Source from the content-addressed store, hash-verified

2736// (i.e. outside of Unicode range U+0 to U+10FFFF) it will be output
2737// as '(Invalid Unicode 0xXXXXXXXX)'.
2738char* CodePointToUtf8(UInt32 code_point, char* str) {
2739 if (code_point <= kMaxCodePoint1) {
2740 str[1] = '\0';
2741 str[0] = static_cast<char>(code_point); // 0xxxxxxx
2742 } else if (code_point <= kMaxCodePoint2) {
2743 str[2] = '\0';
2744 str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
2745 str[0] = static_cast<char>(0xC0 | code_point); // 110xxxxx
2746 } else if (code_point <= kMaxCodePoint3) {
2747 str[3] = '\0';
2748 str[2] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
2749 str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
2750 str[0] = static_cast<char>(0xE0 | code_point); // 1110xxxx
2751 } else if (code_point <= kMaxCodePoint4) {
2752 str[4] = '\0';
2753 str[3] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
2754 str[2] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
2755 str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
2756 str[0] = static_cast<char>(0xF0 | code_point); // 11110xxx
2757 } else {
2758 // The longest string String::Format can produce when invoked
2759 // with these parameters is 28 character long (not including
2760 // the terminating nul character). We are asking for 32 character
2761 // buffer just in case. This is also enough for strncpy to
2762 // null-terminate the destination string.
2763 posix::StrNCpy(
2764 str, String::Format("(Invalid Unicode 0x%X)", code_point).c_str(), 32);
2765 str[31] = '\0'; // Makes sure no change in the format to strncpy leaves
2766 // the result unterminated.
2767 }
2768 return str;
2769}
2770
2771// The following two functions only make sense if the the system
2772// uses UTF-16 for wide string encoding. All supported systems

Callers 1

WideStringToUtf8Function · 0.85

Calls 3

ChopLowBitsFunction · 0.85
StrNCpyFunction · 0.85
FormatClass · 0.85

Tested by

no test coverage detected