]> git.sur5r.net Git - i3/i3/blob - i3-input/ucs2_to_utf8.c
dcd0619702607c5cdbe16069f4fec6758a4a75e1
[i3/i3] / i3-input / ucs2_to_utf8.c
1 /*
2  * vim:ts=8:expandtab
3  *
4  * i3 - an improved dynamic tiling window manager
5  *
6  * © 2009 Michael Stapelberg and contributors
7  *
8  * See file LICENSE for license information.
9  *
10  */
11 #include <stdlib.h>
12 #include <stdio.h>
13 #include <err.h>
14 #include <iconv.h>
15
16 static iconv_t conversion_descriptor = 0;
17
18 /*
19  * Returns the input string, but converted from UCS-2 to UTF-8. Memory will be
20  * allocated, thus the caller has to free the output.
21  *
22  */
23 char *convert_ucs_to_utf8(char *input) {
24         size_t input_size = 2;
25         /* UTF-8 may consume up to 4 byte */
26         int buffer_size = 8;
27
28         char *buffer = calloc(buffer_size, 1);
29         if (buffer == NULL)
30                 err(EXIT_FAILURE, "malloc() failed\n");
31         size_t output_size = buffer_size;
32         /* We need to use an additional pointer, because iconv() modifies it */
33         char *output = buffer;
34
35         /* We convert the input into UCS-2 big endian */
36         if (conversion_descriptor == 0) {
37                 conversion_descriptor = iconv_open("UTF-8", "UCS-2BE");
38                 if (conversion_descriptor == 0) {
39                         fprintf(stderr, "error opening the conversion context\n");
40                         exit(1);
41                 }
42         }
43
44         /* Get the conversion descriptor back to original state */
45         iconv(conversion_descriptor, NULL, NULL, NULL, NULL);
46
47         /* Convert our text */
48         int rc = iconv(conversion_descriptor, (void*)&input, &input_size, &output, &output_size);
49         if (rc == (size_t)-1) {
50                 perror("Converting to UCS-2 failed");
51                 return NULL;
52         }
53
54         return buffer;
55 }