Jeff Sharkey | 5b78a3a | 2013-02-19 17:28:10 -0800 | [diff] [blame] | 1 | /* The following functions copied and adapted from libtermkey |
| 2 | * |
| 3 | * http://www.leonerd.org.uk/code/libtermkey/ |
| 4 | */ |
| 5 | static inline unsigned int utf8_seqlen(long codepoint) |
| 6 | { |
| 7 | if(codepoint < 0x0000080) return 1; |
| 8 | if(codepoint < 0x0000800) return 2; |
| 9 | if(codepoint < 0x0010000) return 3; |
| 10 | if(codepoint < 0x0200000) return 4; |
| 11 | if(codepoint < 0x4000000) return 5; |
| 12 | return 6; |
| 13 | } |
| 14 | |
| 15 | static int fill_utf8(long codepoint, char *str) |
| 16 | { |
| 17 | int nbytes = utf8_seqlen(codepoint); |
| 18 | |
| 19 | str[nbytes] = 0; |
| 20 | |
| 21 | // This is easier done backwards |
| 22 | int b = nbytes; |
| 23 | while(b > 1) { |
| 24 | b--; |
| 25 | str[b] = 0x80 | (codepoint & 0x3f); |
| 26 | codepoint >>= 6; |
| 27 | } |
| 28 | |
| 29 | switch(nbytes) { |
| 30 | case 1: str[0] = (codepoint & 0x7f); break; |
| 31 | case 2: str[0] = 0xc0 | (codepoint & 0x1f); break; |
| 32 | case 3: str[0] = 0xe0 | (codepoint & 0x0f); break; |
| 33 | case 4: str[0] = 0xf0 | (codepoint & 0x07); break; |
| 34 | case 5: str[0] = 0xf8 | (codepoint & 0x03); break; |
| 35 | case 6: str[0] = 0xfc | (codepoint & 0x01); break; |
| 36 | } |
| 37 | |
| 38 | return nbytes; |
| 39 | } |
| 40 | /* end copy */ |