]> mj.ucw.cz Git - libucw.git/blob - lib/unicode-utf8.c
lib: added {big,page}_alloc_zero routines
[libucw.git] / lib / unicode-utf8.c
1 /*
2  *      UCW Library -- UTF-8 Functions
3  *
4  *      (c) 1997--2004 Martin Mares <mj@ucw.cz>
5  *      (c) 2003 Robert Spalek <robert@ucw.cz>
6  *
7  *      This software may be freely distributed and used according to the terms
8  *      of the GNU Lesser General Public License.
9  */
10
11 #include "lib/lib.h"
12 #include "lib/unicode.h"
13
14 uns
15 utf8_strlen(byte *str)
16 {
17   uns len = 0;
18   while (*str)
19     {
20       UTF8_SKIP(str);
21       len++;
22     }
23   return len;
24 }
25
26 uns
27 utf8_strnlen(byte *str, uns n)
28 {
29   uns len = 0;
30   byte *end = str + n;
31   while (str < end)
32     {
33       UTF8_SKIP(str);
34       len++;
35     }
36   return len;
37 }
38
39 uns
40 utf8_check(byte *s)
41 {
42 #define UTF8_CHECK_NEXT if (unlikely((*s & 0xc0) != 0x80)) goto bad; s++
43   while (*s)
44     {
45       uns u = *s++;
46       if (u < 0x80)
47         ;
48       else if (unlikely(u < 0xc0))
49         {
50 bad:
51           return 0;
52         }
53       else if (u < 0xe0)
54         {
55           UTF8_CHECK_NEXT;
56         }
57       else if (likely(u < 0xf0))
58         {
59           UTF8_CHECK_NEXT;
60           UTF8_CHECK_NEXT;
61         }
62       else
63         goto bad;
64     }
65   return 1;
66 }
67
68 #ifdef TEST
69 #include <string.h>
70 #include <stdio.h>
71 int main(int argc, char **argv)
72 {
73   byte buf[256];
74   if (argc > 1 && !strncmp(argv[1], "get", 3))
75     {
76       int f32 = !strcmp(argv[1], "get32");
77       byte *p = buf;
78       uns u;
79       while (scanf("%x", &u) == 1)
80         *p++ = u;
81       *p = 0;
82       p = buf;
83       while (*p)
84         {
85           if (p != buf)
86             putchar(' ');
87           if (f32)
88             GET_UTF8_32(p, u);
89           else
90             GET_UTF8(p, u);
91           printf("%04x", u);
92         }
93       putchar('\n');
94     }
95   else if (argc > 1 && !strncmp(argv[1], "put", 3))
96     {
97       uns u, i=0;
98       int f32 = !strcmp(argv[1], "put32");
99       while (scanf("%x", &u) == 1)
100         {
101           byte *p = buf;
102           if (f32)
103             PUT_UTF8_32(p, u);
104           else
105             PUT_UTF8(p, u);
106           *p = 0;
107           for (p=buf; *p; p++)
108             {
109               if (i++)
110                 putchar(' ');
111               printf("%02x", *p);
112             }
113         }
114       putchar('\n');
115     }
116   else
117     puts("?");
118   return 0;
119 }
120 #endif