MCPcopy Create free account
hub / github.com/OpenStarbound/OpenStarbound / CodePointToUtf8

Function CodePointToUtf8

source/test/gtest/src/gtest.cc:1971–1997  ·  view source on GitHub ↗

Converts a Unicode code point to a narrow string in UTF-8 encoding. code_point parameter is of type uint32_t 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)".

Source from the content-addressed store, hash-verified

1969// (i.e. outside of Unicode range U+0 to U+10FFFF) it will be converted
1970// to "(Invalid Unicode 0xXXXXXXXX)".
1971std::string CodePointToUtf8(uint32_t code_point) {
1972 if (code_point > kMaxCodePoint4) {
1973 return "(Invalid Unicode 0x" + String::FormatHexUInt32(code_point) + ")";
1974 }
1975
1976 char str[5]; // Big enough for the largest valid code point.
1977 if (code_point <= kMaxCodePoint1) {
1978 str[1] = '\0';
1979 str[0] = static_cast<char>(code_point); // 0xxxxxxx
1980 } else if (code_point <= kMaxCodePoint2) {
1981 str[2] = '\0';
1982 str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
1983 str[0] = static_cast<char>(0xC0 | code_point); // 110xxxxx
1984 } else if (code_point <= kMaxCodePoint3) {
1985 str[3] = '\0';
1986 str[2] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
1987 str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
1988 str[0] = static_cast<char>(0xE0 | code_point); // 1110xxxx
1989 } else { // code_point <= kMaxCodePoint4
1990 str[4] = '\0';
1991 str[3] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
1992 str[2] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
1993 str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
1994 str[0] = static_cast<char>(0xF0 | code_point); // 11110xxx
1995 }
1996 return str;
1997}
1998
1999// The following two functions only make sense if the system
2000// uses UTF-16 for wide string encoding. All supported systems

Callers 1

WideStringToUtf8Function · 0.85

Calls 1

ChopLowBitsFunction · 0.85

Tested by

no test coverage detected