much love
[mu.git] / tools / termbox / utf8.c
blob26c0c27b50fe977ff3e5bd14d3466f01aaad1438
1 #include "termbox.h"
3 static const unsigned char utf8_length[256] = {
4 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
5 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
6 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
7 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
8 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
9 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
10 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,
11 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,4,4,4,4,4,4,4,4,5,5,5,5,6,6,1,1
14 static const unsigned char utf8_mask[6] = {
15 0x7F,
16 0x1F,
17 0x0F,
18 0x07,
19 0x03,
20 0x01
23 int tb_utf8_char_length(char c)
25 return utf8_length[(unsigned char)c];
28 int tb_utf8_char_to_unicode(uint32_t *out, const char *c)
30 if (*c == 0)
31 return TB_EOF;
33 int i;
34 unsigned char len = tb_utf8_char_length(*c);
35 unsigned char mask = utf8_mask[len-1];
36 uint32_t result = c[0] & mask;
37 for (i = 1; i < len; ++i) {
38 result <<= 6;
39 result |= c[i] & 0x3f;
42 *out = result;
43 return (int)len;
46 int tb_utf8_unicode_to_char(char *out, uint32_t c)
48 int len = 0;
49 int first;
50 int i;
52 if (c < 0x80) {
53 first = 0;
54 len = 1;
55 } else if (c < 0x800) {
56 first = 0xc0;
57 len = 2;
58 } else if (c < 0x10000) {
59 first = 0xe0;
60 len = 3;
61 } else if (c < 0x200000) {
62 first = 0xf0;
63 len = 4;
64 } else if (c < 0x4000000) {
65 first = 0xf8;
66 len = 5;
67 } else {
68 first = 0xfc;
69 len = 6;
72 for (i = len - 1; i > 0; --i) {
73 out[i] = (c & 0x3f) | 0x80;
74 c >>= 6;
76 out[0] = c | first;
78 return len;