Correction by Marian ??urkovi??
[infodrom/newmail] / charset.c
1 /*
2     Copyright (c) 2006,8  Joey Schulze <joey@infodrom.org>
3
4     This program is free software; you can redistribute it and/or modify
5     it under the terms of the GNU General Public License as published by
6     the Free Software Foundation; either version 2 of the License, or
7     (at your option) any later version.
8
9     This program is distributed in the hope that it will be useful,
10     but WITHOUT ANY WARRANTY; without even the implied warranty of
11     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12     GNU General Public License for more details.
13
14     You should have received a copy of the GNU General Public License
15     along with this program; if not, write to the Free Software
16     Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
17  */
18
19 #include <locale.h>
20 #include <langinfo.h>
21 #include <string.h>
22 #include <iconv.h>
23 #include <errno.h>
24
25 char *charset = NULL;
26
27 /*
28  * Determine the output character set
29  */
30 void set_charset()
31 {
32   setlocale (LC_CTYPE, "");
33
34   charset = strdup (nl_langinfo(CODESET));
35 }
36
37 /*
38  * Convert a word from an arbitrary charset into the output character set
39  *
40  * No conversion is performed when both charsets are equal
41  */
42 char *convert_word(const char *encoding, char *inbuf, char *outbuf, size_t outbytesleft)
43 {
44   iconv_t cd;
45   char *inptr, *outptr;
46   size_t inbytesleft;
47   size_t nconv;
48   size_t outsize;
49
50   if (!charset || !strcasecmp (encoding, charset)) {
51     memmove (outbuf, inbuf, strlen(inbuf)<outbytesleft?strlen(inbuf)+1:outbytesleft);
52     outbuf[outbytesleft-1] = '\0';
53     return outbuf;
54   }
55
56   outsize = outbytesleft;
57
58   cd = iconv_open (charset, encoding);
59
60   inbytesleft = strlen (inbuf)+1;
61   inptr = inbuf;
62   outptr = outbuf;
63
64   while (1) {
65     nconv = iconv (cd, &inptr, &inbytesleft, &outptr, &outbytesleft);
66
67     if (nconv != -1)
68       break;
69
70     if (errno == EILSEQ && outsize-outbytesleft >= 0 && outbytesleft > 1) {
71       outbuf[outsize-outbytesleft] = '?';
72       outbuf[outsize-outbytesleft+1] = '\0';
73       outbytesleft--;
74       inbytesleft--;
75       outptr++;
76       inptr++;
77     } else
78       break;
79   }
80
81   iconv_close(cd);
82
83   if (nconv == -1 && outsize-outbytesleft >= 0)
84     outbuf[outsize-outbytesleft] = '\0';
85
86   return outbuf;
87 }
88
89
90 /*
91  * Needs to be called with LANG=de_DE.ISO-8859-1
92
93 void test_charset()
94 {
95   char outbuf[100];
96   size_t size = 99;
97
98   memset (outbuf, 0, sizeof (outbuf));
99   printf ("%s\n", convert_word ("UTF-8", "für ein", outbuf, size));
100   printf ("%s\n", outbuf);
101   if (!strcmp(outbuf, "für ein"))
102     printf ("charset.c: test passed\n");
103   else
104     printf ("charset.c: test failed\n");
105 }
106
107 */