Converts a unicode code-point to UTF-8.
| 36 | |
| 37 | /// Converts a unicode code-point to UTF-8. |
| 38 | static inline StringContainer codePointToUTF8(unsigned int cp) { |
| 39 | StringContainer result; |
| 40 | |
| 41 | // based on description from http://en.wikipedia.org/wiki/UTF-8 |
| 42 | |
| 43 | if (cp <= 0x7f) { |
| 44 | result.resize(1); |
| 45 | result[0] = static_cast<char>(cp); |
| 46 | } else if (cp <= 0x7FF) { |
| 47 | result.resize(2); |
| 48 | result[1] = static_cast<char>(0x80 | (0x3f & cp)); |
| 49 | result[0] = static_cast<char>(0xC0 | (0x1f & (cp >> 6))); |
| 50 | } else if (cp <= 0xFFFF) { |
| 51 | result.resize(3); |
| 52 | result[2] = static_cast<char>(0x80 | (0x3f & cp)); |
| 53 | result[1] = static_cast<char>(0x80 | (0x3f & (cp >> 6))); |
| 54 | result[0] = static_cast<char>(0xE0 | (0xf & (cp >> 12))); |
| 55 | } else if (cp <= 0x10FFFF) { |
| 56 | result.resize(4); |
| 57 | result[3] = static_cast<char>(0x80 | (0x3f & cp)); |
| 58 | result[2] = static_cast<char>(0x80 | (0x3f & (cp >> 6))); |
| 59 | result[1] = static_cast<char>(0x80 | (0x3f & (cp >> 12))); |
| 60 | result[0] = static_cast<char>(0xF0 | (0x7 & (cp >> 18))); |
| 61 | } |
| 62 | |
| 63 | return result; |
| 64 | } |
| 65 | |
| 66 | enum { |
| 67 | /// Constant that specify the size of the buffer that must be passed to |