3 int utf8_encode(int codepoint, char *buffer, int *size)
7 else if(codepoint < 0x80)
9 buffer[0] = (char)codepoint;
12 else if(codepoint < 0x800)
14 buffer[0] = 0xC0 + ((codepoint & 0x7C0) >> 6);
15 buffer[1] = 0x80 + ((codepoint & 0x03F));
18 else if(codepoint < 0x10000)
20 buffer[0] = 0xE0 + ((codepoint & 0xF000) >> 12);
21 buffer[1] = 0x80 + ((codepoint & 0x0FC0) >> 6);
22 buffer[2] = 0x80 + ((codepoint & 0x003F));
25 else if(codepoint <= 0x10FFFF)
27 buffer[0] = 0xF0 + ((codepoint & 0x1C0000) >> 18);
28 buffer[1] = 0x80 + ((codepoint & 0x03F000) >> 12);
29 buffer[2] = 0x80 + ((codepoint & 0x000FC0) >> 6);
30 buffer[3] = 0x80 + ((codepoint & 0x00003F));
39 int utf8_check_first(char byte)
41 unsigned char u = (unsigned char)byte;
46 if(0x80 <= u && u <= 0xBF) {
47 /* second, third or fourth byte of a multi-byte
48 sequence, i.e. a "continuation byte" */
51 else if(u == 0xC0 || u == 0xC1) {
52 /* overlong encoding of an ASCII byte */
55 else if(0xC2 <= u && u <= 0xDF) {
60 else if(0xE0 <= u && u <= 0xEF) {
64 else if(0xF0 <= u && u <= 0xF4) {
68 else { /* u >= 0xF5 */
69 /* Restricted (start of 4-, 5- or 6-byte sequence) or invalid
75 int utf8_check_full(const char *buffer, int size)
78 unsigned char u = (unsigned char)buffer[0];
95 for(i = 1; i < size; i++)
97 u = (unsigned char)buffer[i];
99 if(u < 0x80 || u > 0xBF) {
100 /* not a continuation byte */
104 value = (value << 6) + (u & 0x3F);
107 if(value > 0x10FFFF) {
108 /* not in Unicode range */
112 else if(0xD800 <= value && value <= 0xDFFF) {
113 /* invalid code point (UTF-16 surrogate halves) */
117 else if((size == 2 && value < 0x80) ||
118 (size == 3 && value < 0x800) ||
119 (size == 4 && value < 0x10000)) {
120 /* overlong encoding */
127 int utf8_check_string(const char *string, int length)
132 length = strlen(string);
134 for(i = 0; i < length; i++)
136 int count = utf8_check_first(string[i]);
141 if(i + count > length)
144 if(!utf8_check_full(&string[i], count))