Converts a unicode code-point to UTF-8.
| 102 | |
| 103 | /// Converts a unicode code-point to UTF-8. |
| 104 | static inline std::string codePointToUTF8(unsigned int cp) { |
| 105 | std::string result; |
| 106 | |
| 107 | // based on description from http://en.wikipedia.org/wiki/UTF-8 |
| 108 | |
| 109 | if (cp <= 0x7f) { |
| 110 | result.resize(1); |
| 111 | result[0] = static_cast<char>(cp); |
| 112 | } else if (cp <= 0x7FF) { |
| 113 | result.resize(2); |
| 114 | result[1] = static_cast<char>(0x80 | (0x3f & cp)); |
| 115 | result[0] = static_cast<char>(0xC0 | (0x1f & (cp >> 6))); |
| 116 | } else if (cp <= 0xFFFF) { |
| 117 | result.resize(3); |
| 118 | result[2] = static_cast<char>(0x80 | (0x3f & cp)); |
| 119 | result[1] = static_cast<char>(0x80 | (0x3f & (cp >> 6))); |
| 120 | result[0] = static_cast<char>(0xE0 | (0xf & (cp >> 12))); |
| 121 | } else if (cp <= 0x10FFFF) { |
| 122 | result.resize(4); |
| 123 | result[3] = static_cast<char>(0x80 | (0x3f & cp)); |
| 124 | result[2] = static_cast<char>(0x80 | (0x3f & (cp >> 6))); |
| 125 | result[1] = static_cast<char>(0x80 | (0x3f & (cp >> 12))); |
| 126 | result[0] = static_cast<char>(0xF0 | (0x7 & (cp >> 18))); |
| 127 | } |
| 128 | |
| 129 | return result; |
| 130 | } |
| 131 | |
| 132 | /// Returns true if ch is a control character (in range [1,31]). |
| 133 | static inline bool isControlCharacter(char ch) { return ch > 0 && ch <= 0x1F; } |