xref: /vim-8.2.3635/src/libvterm/src/utf8.h (revision 591cec83)
1 /* The following functions copied and adapted from libtermkey
2  *
3  * http://www.leonerd.org.uk/code/libtermkey/
4  */
5 unsigned int utf8_seqlen(long codepoint);
6 
7 #if defined(DEFINE_INLINES) || USE_INLINE
utf8_seqlen(long codepoint)8 INLINE unsigned int utf8_seqlen(long codepoint)
9 {
10   if(codepoint < 0x0000080) return 1;
11   if(codepoint < 0x0000800) return 2;
12   if(codepoint < 0x0010000) return 3;
13   if(codepoint < 0x0200000) return 4;
14   if(codepoint < 0x4000000) return 5;
15   return 6;
16 }
17 #endif
18 
19 /* Does NOT NUL-terminate the buffer */
20 int fill_utf8(long codepoint, char *str);
21 
22 #if defined(DEFINE_INLINES) || USE_INLINE
fill_utf8(long codepoint,char * str)23 INLINE int fill_utf8(long codepoint, char *str)
24 {
25   int nbytes = utf8_seqlen(codepoint);
26 
27   // This is easier done backwards
28   int b = nbytes;
29   while(b > 1) {
30     b--;
31     str[b] = 0x80 | (codepoint & 0x3f);
32     codepoint >>= 6;
33   }
34 
35   switch(nbytes) {
36     case 1: str[0] =        (codepoint & 0x7f); break;
37     case 2: str[0] = 0xc0 | (codepoint & 0x1f); break;
38     case 3: str[0] = 0xe0 | (codepoint & 0x0f); break;
39     case 4: str[0] = 0xf0 | (codepoint & 0x07); break;
40     case 5: str[0] = 0xf8 | (codepoint & 0x03); break;
41     case 6: str[0] = 0xfc | (codepoint & 0x01); break;
42   }
43 
44   return nbytes;
45 }
46 #endif
47 /* end copy */
48