factor out input-reading code from lexer.c into input.c
[cparser] / unicode.h
1 #ifndef UNICODE_H
2 #define UNICODE_H
3
4 #include <assert.h>
5
6 typedef unsigned int utf32;
7 #define UTF32_PRINTF_FORMAT "%u"
8
9 /**
10  * "parse" an utf8 character from a string.
11  * Warning: This function only works for valid utf-8 inputs. The behaviour
12  * is undefined for invalid utf-8 input.
13  *
14  * @param p    A pointer to a pointer into the string. The pointer
15  *             is incremented for each consumed char
16  */
17 static inline utf32 read_utf8_char(const char **p)
18 {
19         const unsigned char *c      = (const unsigned char *) *p;
20         utf32                result;
21
22         if ((*c & 0x80) == 0) {
23                 /* 1 character encoding: 0b0??????? */
24                 result = *c++;
25         } else if ((*c & 0xE0) == 0xC0) {
26                 /* 2 character encoding: 0b110?????, 0b10?????? */
27                 result = *c++ & 0x1F;
28                 result = (result << 6) | (*c++ & 0x3F);
29         } else if ((*c & 0xF0) == 0xE0) {
30                 /* 3 character encoding: 0b1110????, 0b10??????, 0b10?????? */
31                 result = *c++ & 0x0F;
32                 result = (result << 6) | (*c++ & 0x3F);
33                 result = (result << 6) | (*c++ & 0x3F);
34         } else {
35                 /* 4 character enc.: 0b11110???, 0b10??????, 0b10??????, 0b10?????? */
36                 assert((*c & 0xF8) == 0xF0);
37                 result = *c++ & 0x07;
38                 result = (result << 6) | (*c++ & 0x3F);
39                 result = (result << 6) | (*c++ & 0x3F);
40                 result = (result << 6) | (*c++ & 0x3F);
41         }
42
43         *p = (const char*) c;
44         return result;
45 }
46
47 #endif