added -A and -U
[tridge/junkcode.git] / utf8.c
1 #include <stdio.h>
2 #include <iconv.h>
3
4 typedef unsigned short smb_ucs2_t;
5
6 #define CVAL(buf,pos) (((unsigned char *)(buf))[pos])
7
8 static int utf8_encode(unsigned char c[3], smb_ucs2_t uc)
9 {
10         unsigned char uc1, uc2;
11         uc1 = CVAL(&uc, 0);
12         uc2 = CVAL(&uc, 1);
13
14         if ((uc2 & 0xf8) == 0xd8) {
15                 c[0] = 0xed;
16                 c[1] = 0x9f;
17                 c[2] = 0xbf;
18                 return 3;
19         }
20
21         if (uc2 & 0xf8) {
22                 c[0] = 0xe0 | (uc2>>4);
23                 c[1] = 0x80 | ((uc2&0xF)<<2) | (uc1>>6);
24                 c[2] = 0x80 | (uc1&0x3f);
25                 return 3;
26         }
27
28         if (uc2 | (uc1 & 0x80)) {
29                 c[0] = 0xc0 | (uc2<<2) | (uc1>>6);
30                 c[1] = 0x80 | (uc1&0x3f);
31                 return 2;
32         } 
33
34         c[0] = uc1;
35         return 1;
36 }
37
38 static int utf8_decode(unsigned char c[3], smb_ucs2_t *uc)
39 {
40         *uc = 0;
41
42         if ((c[0] & 0xf0) == 0xe0) {
43                 CVAL(uc, 1) = ((c[0]&0xF)<<4) | ((c[1]>>2)&0xF);
44                 CVAL(uc, 0) = (c[1]<<6) | (c[2]&0x3f);
45                 return 3;
46         }
47
48         if ((c[0] & 0xe0) == 0xc0) {
49                 CVAL(uc, 1) = (c[0]>>2) & 0x7;
50                 CVAL(uc, 0) = (c[0]<<6) | (c[1]&0x3f);
51                 return 2;
52         }
53
54         CVAL(uc, 0) = c[0];
55         return 1;
56 }
57
58
59 int main(int argc, char *argv[])
60 {
61         unsigned short s[2];
62         int i, j;
63         unsigned char utf8[10];
64         unsigned char foo[10];
65         int len, len2;
66         iconv_t cd;
67
68         s[1] = 0;
69
70         cd = iconv_open(argv[1], "UCS2");
71         
72         for (i=1;i<0x10000;i++) {
73                 int inlen, outlen;
74                 char *p;
75                 char *q;
76
77                 p = s;
78                 q = utf8;
79                 s[0] = i;
80                 inlen = 4;
81                 outlen = 10;
82                 iconv(cd, &p, &inlen, &q, &outlen);
83                 len = strlen(utf8);
84                 len2 = utf8_encode(foo, i);
85
86                 if (1 || len != len2 || strncmp(foo, utf8, len) != 0) {
87                         printf("%02x: ", i);
88                         for (j=0;j<len;j++) {
89                                 printf("%02x ", utf8[j]);
90                         }
91                         printf("\n");
92                         
93                         printf("%02x: ", i);
94                         for (j=0;j<len2;j++) {
95                                 printf("%02x ", foo[j]);
96                         }
97                         printf("\n");
98                 }
99         }
100 }