Converts a unicode code-point to UTF-8.
| 16 | |
| 17 | /// Converts a unicode code-point to UTF-8. |
| 18 | static inline std::string codePointToUTF8(unsigned int cp) { |
| 19 | std::string result; |
| 20 | |
| 21 | // based on description from http://en.wikipedia.org/wiki/UTF-8 |
| 22 | |
| 23 | if (cp <= 0x7f) { |
| 24 | result.resize(1); |
| 25 | result[0] = static_cast<char>(cp); |
| 26 | } else if (cp <= 0x7FF) { |
| 27 | result.resize(2); |
| 28 | result[1] = static_cast<char>(0x80 | (0x3f & cp)); |
| 29 | result[0] = static_cast<char>(0xC0 | (0x1f & (cp >> 6))); |
| 30 | } else if (cp <= 0xFFFF) { |
| 31 | result.resize(3); |
| 32 | result[2] = static_cast<char>(0x80 | (0x3f & cp)); |
| 33 | result[1] = static_cast<char>(0x80 | (0x3f & (cp >> 6))); |
| 34 | result[0] = static_cast<char>(0xE0 | (0xf & (cp >> 12))); |
| 35 | } else if (cp <= 0x10FFFF) { |
| 36 | result.resize(4); |
| 37 | result[3] = static_cast<char>(0x80 | (0x3f & cp)); |
| 38 | result[2] = static_cast<char>(0x80 | (0x3f & (cp >> 6))); |
| 39 | result[1] = static_cast<char>(0x80 | (0x3f & (cp >> 12))); |
| 40 | result[0] = static_cast<char>(0xF0 | (0x7 & (cp >> 18))); |
| 41 | } |
| 42 | |
| 43 | return result; |
| 44 | } |
| 45 | |
| 46 | /// Returns true if ch is a control character (in range [1,31]). |
| 47 | static inline bool isControlCharacter(char ch) { return ch > 0 && ch <= 0x1F; } |