Debian Codegraph @

terps/alan3/converter.c

raw symbols SCIP
1 #include "converter.h"
2
3 #include <errno.h>
4
5 #include "options.h"
6 #include "syserr.h"
7 #include "msg.h"
8
9 #ifndef HAVE_GARGLK
10
11 /* Cross-building sets iconv args to const using WINICONV_CONST, so
12 * nullify that to remove warnings... */
13 #define WINICONV_CONST
14 #include <iconv.h>
15
16 /* Outgoing - will always return an alloc'd string that needs to be freed */
17 char *ensureExternalEncoding(char input[]) {
18 if (encodingOption == ENCODING_UTF) {
19 iconv_t cd = iconv_open("UTF-8", "ISO_8859-1");
20 if (cd == (iconv_t) -1)
21 syserr("iconv_open() failed!");
22
23 /* UTF-8 might be longer than ISO8859-1 encoding so double */
24 char *in_p = input;
25 size_t in_left = strlen(input);
26 size_t out_left = strlen(input)*2;
27 char *converted = (char *)malloc(out_left+1);
28 char *out_p = converted;
29
30 if (iconv(cd, &in_p, &in_left, &out_p, &out_left) == (size_t) -1) {
31 /* Internal code (ISO8859-1) to UTF should never fail */
32 syserr("Conversion of command output to UTF-8 failed");
33 }
34 *out_p = '\0';
35
36 iconv_close(cd);
37 return converted;
38 } else
39 return strdup(input);
40 }
41
42
43 /* Incoming -- will always return an alloc'd string that needs to be freed */
44 char *ensureInternalEncoding(char input[]) {
45 if (encodingOption == ENCODING_UTF) {
46 iconv_t cd = iconv_open("ISO_8859-1", "UTF-8");
47 if (cd == (iconv_t) -1)
48 syserr("iconv_open() failed!");
49
50 /* ISO8859-1 encoding is always shorter than UTF-8, so this is enough */
51 char *in_p = input;
52 size_t in_left = strlen(input);
53 size_t out_left = in_left;
54 char *converted = (char *)malloc(strlen(input)+1);
55 char *out_p = converted;
56
57 if (iconv(cd, &in_p, &in_left, &out_p, &out_left) == (size_t) -1) {
58 /* TODO: We need a message for illegal characters in input */
59 printf("Conversion of command input from UTF-8 failed, are you sure about the input encoding? ('%s')\n", strerror(errno));
60 error(M_WHAT);
61 }
62 *out_p = '\0';
63
64 iconv_close(cd);
65 return converted;
66 } else
67 return strdup(input);
68 }
69
70 #else
71
72 /* For Gargoyle/GARGLK we just return the original string to avoid extra dependency on iconv */
73
74 char *ensureExternalEncoding(char input[]) {
75 return strdup(input);
76 }
77
78 char *ensureInternalEncoding(char input[]) {
79 return strdup(input);
80 }
81
82 #endif