From 12ecdd71592eccf7bdb6214edbc7318246469c1c Mon Sep 17 00:00:00 2001 From: yzrh Date: Fri, 14 Aug 2020 22:04:26 +0000 Subject: Initial commit. --- src/iconv.c | 70 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 70 insertions(+) create mode 100644 src/iconv.c (limited to 'src/iconv.c') diff --git a/src/iconv.c b/src/iconv.c new file mode 100644 index 0000000..1bf4d94 --- /dev/null +++ b/src/iconv.c @@ -0,0 +1,70 @@ +/* + * Copyright (c) 2020, yzrh + * + * SPDX-License-Identifier: Apache-2.0 + */ + +#include +#include + +#include + +/* So, why would anyone use something other than UTF-8? */ +int +strconv(char **dst, + const char * restrict dst_code, + const char * restrict src, + const char * restrict src_code, + int *size) +{ + size_t dst_size = *size; + char *dst_conv = malloc(dst_size); + + if (dst_conv == NULL) + return 1; + + size_t src_size = strlen(src) + 1; + char *src_conv = malloc(src_size); + + if (src_conv == NULL) { + free(dst_conv); + return 1; + } + + strncpy(src_conv, src, src_size); + + char *dst_start = dst_conv; + char *src_start = src_conv; + + iconv_t conv_src_dst = iconv_open(dst_code, src_code); + + if (conv_src_dst == (iconv_t) - 1) { + free(dst_conv); + free(src_conv); + return 1; + } + + if (iconv(conv_src_dst, + &src_conv, &src_size, + &dst_conv, &dst_size) == (size_t) - 1) { + free(dst_start); + free(src_start); + return 1; + } else { + /* Not including NULL */ + *size -= dst_size + 2; + + *dst = malloc(*size); + + if (*dst != NULL) + memcpy(*dst, dst_start, *size); + + free(dst_start); + free(src_start); + } + + if (iconv_close(conv_src_dst) != 0 || *dst == NULL) + return 1; + + return 0; +} -- cgit v1.2.3