mkfs_ext2: fix bad comment. no code changes
[oweals/busybox.git] / libbb / unicode.c
1 /* vi: set sw=4 ts=4: */
2 /*
3  * Unicode support routines.
4  *
5  * Copyright (C) 2009 Denys Vlasenko
6  *
7  * Licensed under GPL version 2, see file LICENSE in this tarball for details.
8  */
9 #include "libbb.h"
10 #include "unicode.h"
11
12 /* If it's not #defined as a constant in unicode.h... */
13 #ifndef unicode_status
14 uint8_t unicode_status;
15 #endif
16
17 /* This file is compiled only if FEATURE_ASSUME_UNICODE is on.
18  * We check other options and decide whether to use libc support
19  * via locale, or use our own logic:
20  */
21
22 #if ENABLE_LOCALE_SUPPORT
23
24 /* Unicode support using libc locale support. */
25
26 void FAST_FUNC init_unicode(void)
27 {
28         /* In unicode, this is a one character string */
29         static const char unicode_0x394[] = { 0xce, 0x94, 0 };
30
31         if (unicode_status != UNICODE_UNKNOWN)
32                 return;
33
34         unicode_status = unicode_strlen(unicode_0x394) == 1 ? UNICODE_ON : UNICODE_OFF;
35 }
36
37 #else
38
39 /* Homegrown Unicode support. It knows only C and Unicode locales. */
40
41 # if ENABLE_FEATURE_CHECK_UNICODE_IN_ENV
42 void FAST_FUNC init_unicode(void)
43 {
44         char *lang;
45
46         if (unicode_status != UNICODE_UNKNOWN)
47                 return;
48
49         unicode_status = UNICODE_OFF;
50         lang = getenv("LANG");
51         if (!lang || !(strstr(lang, ".utf") || strstr(lang, ".UTF")))
52                 return;
53         unicode_status = UNICODE_ON;
54 }
55 # endif
56
57 static size_t wcrtomb_internal(char *s, wchar_t wc)
58 {
59         int n, i;
60         uint32_t v = wc;
61
62         if (v <= 0x7f) {
63                 *s = v;
64                 return 1;
65         }
66
67         /* RFC 3629 says that Unicode ends at 10FFFF,
68          * but we cover entire 32 bits */
69
70         /* 4000000-FFFFFFFF -> 111111tt 10tttttt 10zzzzzz 10zzyyyy 10yyyyxx 10xxxxxx */
71         /* 200000-3FFFFFF -> 111110tt 10zzzzzz 10zzyyyy 10yyyyxx 10xxxxxx */
72         /* 10000-1FFFFF -> 11110zzz 10zzyyyy 10yyyyxx 10xxxxxx */
73         /* 800-FFFF -> 1110yyyy 10yyyyxx 10xxxxxx */
74         /* 80-7FF -> 110yyyxx 10xxxxxx */
75
76         /* How many bytes do we need? */
77         n = 2;
78         /* (0x80000000+ would result in n = 7, limiting n to 6) */
79         while (v >= 0x800 && n < 6) {
80                 v >>= 5;
81                 n++;
82         }
83         /* Fill bytes n-1..1 */
84         i = n;
85         while (--i) {
86                 s[i] = (wc & 0x3f) | 0x80;
87                 wc >>= 6;
88         }
89         /* Fill byte 0 */
90         s[0] = wc | (uint8_t)(0x3f00 >> n);
91         return n;
92 }
93 size_t FAST_FUNC wcrtomb(char *s, wchar_t wc, mbstate_t *ps UNUSED_PARAM)
94 {
95         if (unicode_status != UNICODE_ON) {
96                 *s = wc;
97                 return 1;
98         }
99
100         return wcrtomb_internal(s, wc);
101 }
102 size_t FAST_FUNC wcstombs(char *dest, const wchar_t *src, size_t n)
103 {
104         size_t org_n = n;
105
106         if (unicode_status != UNICODE_ON) {
107                 while (n) {
108                         wchar_t c = *src++;
109                         *dest++ = c;
110                         if (c == 0)
111                                 break;
112                         n--;
113                 }
114                 return org_n - n;
115         }
116
117         while (n >= MB_CUR_MAX) {
118                 wchar_t wc = *src++;
119                 size_t len = wcrtomb_internal(dest, wc);
120
121                 if (wc == L'\0')
122                         return org_n - n;
123                 dest += len;
124                 n -= len;
125         }
126         while (n) {
127                 char tbuf[MB_CUR_MAX];
128                 wchar_t wc = *src++;
129                 size_t len = wcrtomb_internal(tbuf, wc);
130
131                 if (len > n)
132                         len = n;
133                 memcpy(dest, tbuf, len);
134                 if (wc == L'\0')
135                         return org_n - n;
136                 dest += len;
137                 n -= len;
138         }
139         return org_n - n;
140 }
141
142 #define ERROR_WCHAR (~(wchar_t)0)
143
144 static const char *mbstowc_internal(wchar_t *res, const char *src)
145 {
146         int bytes;
147         unsigned c = (unsigned char) *src++;
148
149         if (c <= 0x7f) {
150                 *res = c;
151                 return src;
152         }
153
154         /* 80-7FF -> 110yyyxx 10xxxxxx */
155         /* 800-FFFF -> 1110yyyy 10yyyyxx 10xxxxxx */
156         /* 10000-1FFFFF -> 11110zzz 10zzyyyy 10yyyyxx 10xxxxxx */
157         /* 200000-3FFFFFF -> 111110tt 10zzzzzz 10zzyyyy 10yyyyxx 10xxxxxx */
158         /* 4000000-FFFFFFFF -> 111111tt 10tttttt 10zzzzzz 10zzyyyy 10yyyyxx 10xxxxxx */
159         bytes = 0;
160         do {
161                 c <<= 1;
162                 bytes++;
163         } while ((c & 0x80) && bytes < 6);
164         if (bytes == 1) {
165                 /* A bare "continuation" byte. Say, 80 */
166                 *res = ERROR_WCHAR;
167                 return src;
168         }
169         c = (uint8_t)(c) >> bytes;
170
171         while (--bytes) {
172                 unsigned ch = (unsigned char) *src;
173                 if ((ch & 0xc0) != 0x80) {
174                         /* Missing "continuation" byte. Example: e0 80 */
175                         *res = ERROR_WCHAR;
176                         return src;
177                 }
178                 c = (c << 6) + (ch & 0x3f);
179                 src++;
180         }
181
182         /* TODO */
183         /* Need to check that c isn't produced by overlong encoding */
184         /* Example: 11000000 10000000 converts to NUL */
185         /* 11110000 10000000 10000100 10000000 converts to 0x100 */
186         /* correct encoding: 11000100 10000000 */
187         if (c <= 0x7f) { /* crude check */
188                 *res = ERROR_WCHAR;
189                 return src;
190         }
191
192         *res = c;
193         return src;
194 }
195 size_t FAST_FUNC mbstowcs(wchar_t *dest, const char *src, size_t n)
196 {
197         size_t org_n = n;
198
199         if (unicode_status != UNICODE_ON) {
200                 while (n) {
201                         unsigned char c = *src++;
202
203                         if (dest)
204                                 *dest++ = c;
205                         if (c == 0)
206                                 break;
207                         n--;
208                 }
209                 return org_n - n;
210         }
211
212         while (n) {
213                 wchar_t wc;
214                 src = mbstowc_internal(&wc, src);
215                 if (wc == ERROR_WCHAR) /* error */
216                         return (size_t) -1L;
217                 if (dest)
218                         *dest++ = wc;
219                 if (wc == 0) /* end-of-string */
220                         break;
221                 n--;
222         }
223
224         return org_n - n;
225 }
226
227 int FAST_FUNC iswspace(wint_t wc)
228 {
229         return (unsigned)wc <= 0x7f && isspace(wc);
230 }
231
232 int FAST_FUNC iswalnum(wint_t wc)
233 {
234         return (unsigned)wc <= 0x7f && isalnum(wc);
235 }
236
237 int FAST_FUNC iswpunct(wint_t wc)
238 {
239         return (unsigned)wc <= 0x7f && ispunct(wc);
240 }
241
242 #include "unicode_wcwidth.c"
243
244 #endif /* Homegrown Unicode support */
245
246
247 /* The rest is mostly same for libc and for "homegrown" support */
248
249 size_t FAST_FUNC unicode_strlen(const char *string)
250 {
251         size_t width = mbstowcs(NULL, string, INT_MAX);
252         if (width == (size_t)-1L)
253                 return strlen(string);
254         return width;
255 }
256
257 static char* FAST_FUNC unicode_conv_to_printable2(uni_stat_t *stats, const char *src, unsigned width, int flags)
258 {
259         char *dst;
260         unsigned dst_len;
261         unsigned uni_count;
262         unsigned uni_width;
263
264         if (unicode_status != UNICODE_ON) {
265                 char *d;
266                 if (flags & UNI_FLAG_PAD) {
267                         d = dst = xmalloc(width + 1);
268                         while ((int)--width >= 0) {
269                                 unsigned char c = *src;
270                                 if (c == '\0') {
271                                         do
272                                                 *d++ = ' ';
273                                         while ((int)--width >= 0);
274                                         break;
275                                 }
276                                 *d++ = (c >= ' ' && c < 0x7f) ? c : '?';
277                                 src++;
278                         }
279                         *d = '\0';
280                 } else {
281                         d = dst = xstrndup(src, width);
282                         while (*d) {
283                                 unsigned char c = *d;
284                                 if (c < ' ' || c >= 0x7f)
285                                         *d = '?';
286                                 d++;
287                         }
288                 }
289                 if (stats)
290                         stats->byte_count = stats->unicode_count = (d - dst);
291                 return dst;
292         }
293
294         dst = NULL;
295         uni_count = uni_width = 0;
296         dst_len = 0;
297         while (1) {
298                 int w;
299                 wchar_t wc;
300
301 #if ENABLE_LOCALE_SUPPORT
302                 {
303                         mbstate_t mbst = { 0 };
304                         ssize_t rc = mbsrtowcs(&wc, &src, 1, &mbst);
305                         /* If invalid sequence is seen: -1 is returned,
306                          * src points to the invalid sequence, errno = EILSEQ.
307                          * Else number of wchars (excluding terminating L'\0')
308                          * written to dest is returned.
309                          * If len (here: 1) non-L'\0' wchars stored at dest,
310                          * src points to the next char to be converted.
311                          * If string is completely converted: src = NULL.
312                          */
313                         if (rc == 0) /* end-of-string */
314                                 break;
315                         if (rc < 0) { /* error */
316                                 src++;
317                                 goto subst;
318                         }
319                         if (!iswprint(wc))
320                                 goto subst;
321                 }
322 #else
323                 src = mbstowc_internal(&wc, src);
324                 /* src is advanced to next mb char
325                  * wc == ERROR_WCHAR: invalid sequence is seen
326                  * else: wc is set
327                  */
328                 if (wc == ERROR_WCHAR) /* error */
329                         goto subst;
330                 if (wc == 0) /* end-of-string */
331                         break;
332 #endif
333                 if (CONFIG_LAST_SUPPORTED_WCHAR && wc > CONFIG_LAST_SUPPORTED_WCHAR)
334                         goto subst;
335                 w = wcwidth(wc);
336                 if ((ENABLE_UNICODE_COMBINING_WCHARS && w < 0) /* non-printable wchar */
337                  || (!ENABLE_UNICODE_COMBINING_WCHARS && w <= 0)
338                  || (!ENABLE_UNICODE_WIDE_WCHARS && w > 1)
339                 ) {
340  subst:
341                         wc = CONFIG_SUBST_WCHAR;
342                         w = 1;
343                 }
344                 width -= w;
345                 /* Note: if width == 0, we still may add more chars,
346                  * they may be zero-width or combining ones */
347                 if ((int)width < 0) {
348                         /* can't add this wc, string would become longer than width */
349                         width += w;
350                         break;
351                 }
352
353                 uni_count++;
354                 uni_width += w;
355                 dst = xrealloc(dst, dst_len + MB_CUR_MAX);
356 #if ENABLE_LOCALE_SUPPORT
357                 {
358                         mbstate_t mbst = { 0 };
359                         dst_len += wcrtomb(&dst[dst_len], wc, &mbst);
360                 }
361 #else
362                 dst_len += wcrtomb_internal(&dst[dst_len], wc);
363 #endif
364         }
365
366         /* Pad to remaining width */
367         if (flags & UNI_FLAG_PAD) {
368                 dst = xrealloc(dst, dst_len + width + 1);
369                 uni_count += width;
370                 uni_width += width;
371                 while ((int)--width >= 0) {
372                         dst[dst_len++] = ' ';
373                 }
374         }
375         dst[dst_len] = '\0';
376         if (stats) {
377                 stats->byte_count = dst_len;
378                 stats->unicode_count = uni_count;
379                 stats->unicode_width = uni_width;
380         }
381
382         return dst;
383 }
384 char* FAST_FUNC unicode_conv_to_printable(uni_stat_t *stats, const char *src)
385 {
386         return unicode_conv_to_printable2(stats, src, INT_MAX, 0);
387 }
388 char* FAST_FUNC unicode_conv_to_printable_maxwidth(uni_stat_t *stats, const char *src, unsigned maxwidth)
389 {
390         return unicode_conv_to_printable2(stats, src, maxwidth, 0);
391 }
392 char* FAST_FUNC unicode_conv_to_printable_fixedwidth(uni_stat_t *stats, const char *src, unsigned width)
393 {
394         return unicode_conv_to_printable2(stats, src, width, UNI_FLAG_PAD);
395 }
396
397 #ifdef UNUSED
398 unsigned FAST_FUNC unicode_padding_to_width(unsigned width, const char *src)
399 {
400         if (unicode_status != UNICODE_ON) {
401                 return width - strnlen(src, width);
402         }
403
404         while (1) {
405                 int w;
406                 wchar_t wc;
407
408 #if ENABLE_LOCALE_SUPPORT
409                 {
410                         mbstate_t mbst = { 0 };
411                         ssize_t rc = mbsrtowcs(&wc, &src, 1, &mbst);
412                         if (rc <= 0) /* error, or end-of-string */
413                                 return width;
414                 }
415 #else
416                 src = mbstowc_internal(&wc, src);
417                 if (wc == ERROR_WCHAR || wc == 0) /* error, or end-of-string */
418                         return width;
419 #endif
420                 w = wcwidth(wc);
421                 if (w < 0) /* non-printable wchar */
422                         return width;
423                 width -= w;
424                 if ((int)width <= 0) /* string is longer than width */
425                         return 0;
426         }
427 }
428 #endif