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 | |
Elliott Hughes | 6d78f36 | 2014-12-04 19:52:44 -0800 | [diff] [blame] | 15 | /* Does NOT NUL-terminate the buffer */ |
Jeff Sharkey | 5b78a3a | 2013-02-19 17:28:10 -0800 | [diff] [blame] | 16 | static int fill_utf8(long codepoint, char *str) |
| 17 | { |
| 18 | int nbytes = utf8_seqlen(codepoint); |
| 19 | |
Jeff Sharkey | 5b78a3a | 2013-02-19 17:28:10 -0800 | [diff] [blame] | 20 | // This is easier done backwards |
| 21 | int b = nbytes; |
| 22 | while(b > 1) { |
| 23 | b--; |
| 24 | str[b] = 0x80 | (codepoint & 0x3f); |
| 25 | codepoint >>= 6; |
| 26 | } |
| 27 | |
| 28 | switch(nbytes) { |
| 29 | case 1: str[0] = (codepoint & 0x7f); break; |
| 30 | case 2: str[0] = 0xc0 | (codepoint & 0x1f); break; |
| 31 | case 3: str[0] = 0xe0 | (codepoint & 0x0f); break; |
| 32 | case 4: str[0] = 0xf0 | (codepoint & 0x07); break; |
| 33 | case 5: str[0] = 0xf8 | (codepoint & 0x03); break; |
| 34 | case 6: str[0] = 0xfc | (codepoint & 0x01); break; |
| 35 | } |
| 36 | |
| 37 | return nbytes; |
| 38 | } |
| 39 | /* end copy */ |