Util function to convert string charset.
This commit is contained in:
40
src/util.c
40
src/util.c
@ -17,6 +17,7 @@
|
||||
#include <errno.h>
|
||||
#include <ctype.h>
|
||||
#include <stdio.h>
|
||||
#include <limits.h>
|
||||
|
||||
int int_pow(int base, int power)
|
||||
{
|
||||
@ -27,6 +28,45 @@ int int_pow(int base, int power)
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
int strconv(const char *str, const char *icharset, const char *ocharset,
|
||||
char **output)
|
||||
{
|
||||
size_t inbytes;
|
||||
size_t outbytes;
|
||||
size_t n;
|
||||
iconv_t conv;
|
||||
char *out;
|
||||
char *src;
|
||||
char *ret;
|
||||
|
||||
inbytes = strlen(str);
|
||||
outbytes = (inbytes + 1) * MB_LEN_MAX;
|
||||
out = malloc(outbytes);
|
||||
if (out == NULL) {
|
||||
return ISO_MEM_ERROR;
|
||||
}
|
||||
|
||||
conv = iconv_open(ocharset, icharset);
|
||||
if (conv == (iconv_t)(-1)) {
|
||||
return ISO_CHARSET_CONV_ERROR;
|
||||
}
|
||||
src = (char *)str;
|
||||
ret = (char *)out;
|
||||
|
||||
n = iconv(conv, &src, &inbytes, &ret, &outbytes);
|
||||
if (n == -1) {
|
||||
/* error */
|
||||
iconv_close(conv);
|
||||
return ISO_CHARSET_CONV_ERROR;
|
||||
}
|
||||
iconv_close(conv);
|
||||
*ret = '\0';
|
||||
|
||||
*output = realloc(out, ret - out);
|
||||
return ISO_SUCCESS;
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert a str in a specified codeset to WCHAR_T.
|
||||
* The result must be free() when no more needed
|
||||
|
19
src/util.h
19
src/util.h
@ -32,6 +32,23 @@ extern inline int round_up(unsigned int n, unsigned int mul)
|
||||
|
||||
int int_pow(int base, int power);
|
||||
|
||||
/**
|
||||
* Convert the charset encoding of a given string.
|
||||
*
|
||||
* @param input
|
||||
* Input string
|
||||
* @param icharset
|
||||
* Input charset. Must be supported by iconv
|
||||
* @param ocharset
|
||||
* Output charset. Must be supported by iconv
|
||||
* @param output
|
||||
* Location where the pointer to the ouput string will be stored
|
||||
* @return
|
||||
* 1 on success, < 0 on error
|
||||
*/
|
||||
int strconv(const char *input, const char *icharset, const char *ocharset,
|
||||
char **output);
|
||||
|
||||
/**
|
||||
* Convert a given string from any input charset to ASCII
|
||||
*
|
||||
@ -39,7 +56,7 @@ int int_pow(int base, int power);
|
||||
* Input charset. Must be supported by iconv
|
||||
* @param input
|
||||
* Input string
|
||||
* @param ouput
|
||||
* @param output
|
||||
* Location where the pointer to the ouput string will be stored
|
||||
* @return
|
||||
* 1 on success, < 0 on error
|
||||
|
Reference in New Issue
Block a user