-
Notifications
You must be signed in to change notification settings - Fork 4
/
decode.c
139 lines (109 loc) · 2.24 KB
/
decode.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
/**
* libutf8 - `decode.c'
*
* (c) 2013 joseph werle <joseph.werle@gmail.com>
*/
#define _BSD_SOURCE 1
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <math.h>
#include <errno.h>
#include "utf8.h"
char *
utf8_decode (const char *str) {
// decoded char buffer
unsigned char buf[UTF8_MAX_BUFFER_LENGTH];
// byte pointer
unsigned char bp = 0;
// utf8 code point
unsigned char cp = 0;
// boundaries
unsigned char lower = 0x80;
unsigned char upper = 0xBF;
// byte pointer value
unsigned int b = 0;
// stream index
int i = 0;
// buffer index
int n = 0;
// byte meta
int seen = 0;
int needed = 0;
while ('\0' != (bp = str[i++])) {
if (errno > 0) {
return NULL;
}
b = (unsigned int) bp;
if (b == EOF) {
if (0 != needed) {
needed = 0;
errno = UTF8E_EOF_BYTES_NEEDED;
}
buf[n++] = EOF;
continue;
}
if (0 == needed) {
// 1 byte
if (UTF8_IN_URANGE(b, 0x00, 0x7F)) {
buf[n++] = b;
continue;
}
if (0 == UTF8_IN_URANGE(b, 0xC2, 0xF4)) {
errno = UTF8E_BYTE_RANGE;
continue;
}
// 2 byte
if (UTF8_IN_URANGE(b, 0xC2, 0xDF)) {
needed = 1;
cp = b - 0xC0;
}
// 3 byte
if (UTF8_IN_URANGE(b, 0xE0, 0xEF)) {
if (b == 0xE0) {
lower = 0xA0;
} else if (b == 0xED) {
upper = 0x9F;
}
needed = 2;
cp = b - 0xE0;
}
// 4 byte
if (UTF8_IN_URANGE(b, 0xF0, 0xF4)) {
if (b == 0xF0) {
lower = 0x90;
} else if (b == 0xF4) {
upper = 0x8F;
}
needed = 3;
cp = b - 0xF0;
}
cp = cp * pow(64, needed);
continue;
}
if (0 == UTF8_IN_URANGE(b, lower, upper)) {
cp = 0;
needed = 0;
seen = 0;
bp = str[--i];
lower = 0x80;
upper = 0xBF;
errno = UTF8E_BYTE_BOUNDARY_RANGE;
continue;
}
lower = 0x80;
upper = 0xBF;
seen++;
cp += (b - 0x80) * pow(64, needed - seen);
if (seen != needed) {
continue;
}
buf[n++] = cp;
cp = 0;
needed = 0;
seen = 0;
}
buf[n] = '\0';
return strdup((char *) buf);
}