-
Notifications
You must be signed in to change notification settings - Fork 0
/
iconv.c
77 lines (68 loc) · 1.62 KB
/
iconv.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
#include <errno.h>
#include <iconv.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *do_iconv(char *to, char *from, char *text, int transliterate)
{
iconv_t desc;
char *inbuf;
size_t inbytesleft;
char *outbuf;
size_t outbytesleft;
size_t insize;
int loop;
size_t res;
char *outbuf_start;
char to_with_transliteration[128];
#ifndef __APPLE__
if (transliterate) {
snprintf(to_with_transliteration, 127, "%s//TRANSLIT", to);
to_with_transliteration[127] = 0;
to = to_with_transliteration;
}
#endif
/* Open conversioon descriptor */
desc = iconv_open(to, from);
if ((long)desc == -1) {
return NULL; /* conversion not supported */
}
#ifdef __APPLE__
/* Set option */
iconvctl(desc, ICONV_SET_TRANSLITERATE, &transliterate);
#endif
/* Try conversion we reach succes of definitive error */
loop = 1;
outbuf_start = NULL;
insize = strlen(text);
while (1) {
/* update output buffers */
loop++;
free(outbuf_start);
outbuf_start = malloc(loop * insize);
if (outbuf_start == NULL) {
iconv_close(desc);
return NULL; /* out of memory error */
}
/* init conversion vars */
inbuf = text;
inbytesleft = insize;
outbuf = outbuf_start;
outbytesleft = (loop * insize) - 1; /* ensure one byte for the final \0 */
res = iconv(desc, &inbuf, &inbytesleft, &outbuf, &outbytesleft);
if (res == -1) {
if (errno == E2BIG)
/* try again with bigger buffer */
continue;
/* unrecoverable error */
iconv_close(desc);
free(outbuf_start);
return NULL;
}
break;
}
/* close converter */
iconv_close(desc);
outbuf_start[outbuf - outbuf_start] = '\0';
return outbuf_start;
}