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
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
|
#define UNICODE
#define Unknown win_Unknown
#include <windows.h>
#include <winbase.h>
#undef Unknown
#undef Sleep
#include "dat.h"
#include "fns.h"
#include "error.h"
#include "r16.h"
#define Bit(i) (7-(i))
/* N 0's preceded by i 1's, T(Bit(2)) is 1100 0000 */
#define T(i) (((1 << (Bit(i)+1))-1) ^ 0xFF)
/* 0000 0000 0000 0111 1111 1111 */
#define RuneX(i) ((1 << (Bit(i) + ((i)-1)*Bitx))-1)
enum
{
Bitx = Bit(1),
Tx = T(1), /* 1000 0000 */
Rune1 = (1<<(Bit(0)+0*Bitx))-1, /* 0000 0000 0000 0000 0111 1111 */
Maskx = (1<<Bitx)-1, /* 0011 1111 */
Testx = Maskx ^ 0xFF, /* 1100 0000 */
SurrogateMin = 0xD800,
SurrogateMax = 0xDFFF,
Bad = Runeerror,
};
Rune16*
runes16dup(Rune16 *r)
{
int n;
Rune16 *s;
n = runes16len(r) + 1;
s = malloc(n * sizeof(Rune16));
if(s == nil)
error(Enomem);
memmove(s, r, n * sizeof(Rune16));
return s;
}
int
runes16len(Rune16 *r)
{
int n;
n = 0;
while(*r++ != 0)
n++;
return n;
}
char*
runes16toutf(char *p, Rune16 *r, int nc)
{
char *op, *ep;
int n, c;
Rune rc;
op = p;
ep = p + nc;
while(c = *r++) {
n = 1;
if(c >= Runeself)
n = runelen(c);
if(p + n >= ep)
break;
rc = c;
if(c < Runeself)
*p++ = c;
else
p += runetochar(p, &rc);
}
*p = '\0';
return op;
}
int
rune16nlen(Rune16 *r, int nrune)
{
int nb, i;
Rune c;
nb = 0;
while(nrune--) {
c = *r++;
if(c <= Rune1){
nb++;
} else {
for(i = 2; i < UTFmax + 1; i++)
if(c <= RuneX(i) || i == UTFmax){
nb += i;
break;
}
}
}
return nb;
}
Rune16*
utftorunes16(Rune16 *r, char *p, int nc)
{
Rune16 *or, *er;
Rune rc;
or = r;
er = r + nc;
while(*p != '\0' && r + 1 < er){
p += chartorune(&rc, p);
*r++ = rc; /* we'll ignore surrogate pairs */
}
*r = '\0';
return or;
}
int
runes16cmp(Rune16 *s1, Rune16 *s2)
{
Rune16 r1, r2;
for(;;) {
r1 = *s1++;
r2 = *s2++;
if(r1 != r2) {
if(r1 > r2)
return 1;
return -1;
}
if(r1 == 0)
return 0;
}
}
wchar_t *
widen(char *s)
{
int n;
wchar_t *ws;
n = utflen(s) + 1;
ws = smalloc(n*sizeof(wchar_t));
utftorunes16(ws, s, n);
return ws;
}
char *
narrowen(wchar_t *ws)
{
char *s;
int n;
n = widebytes(ws);
s = smalloc(n);
runes16toutf(s, ws, n);
return s;
}
int
widebytes(wchar_t *ws)
{
int n = 0;
while (*ws)
n += runelen(*ws++);
return n+1;
}
|