/****************************************************************************
** File name    :  HTStrConvert.cpp
** Description  :  iconv lib API
** Create date  :  2018.09.01
** Auther by    :  Liuyx
** Version info :  V1.0.01
** Copyright (C) 2002-2018 xi'an huatek, Inc Co., Ltd
** Update record:  
** DATE         AUTHER   DESC 
** -------------------------------------------------------------------------               
** 2018.09.01   Liuyx    first build
****************************************************************************/
#include "HTGlobal.h"

static const char *_FILE_ = "HTStrConvert.cpp" ;

#ifdef _WIN32
//UTF-8到GB2312的转换
int utf8_to_gbk(char *inbuf, size_t inlen, char *outbuf, size_t outlen)
{
    int len = MultiByteToWideChar(CP_UTF8, 0, inbuf, inlen, NULL, 0);
    wchar_t* wstr = new wchar_t[len + 1];
    memset(wstr, 0, len + 1);

    MultiByteToWideChar(CP_UTF8, 0, inbuf, inlen, wstr, len);
    len = WideCharToMultiByte(CP_ACP, 0, wstr, -1, NULL, 0, NULL, NULL);

    memset(outbuf, 0, outlen + 1);
    WideCharToMultiByte(CP_ACP, 0, wstr, -1, outbuf, outlen, NULL, NULL);
    if (wstr) delete[] wstr;
    return 0;
}

//GB2312到UTF-8的转换
int gbk_to_utf8(char *inbuf, size_t inlen, char *outbuf, size_t outlen)
{
    int len = MultiByteToWideChar(CP_ACP, 0, inbuf, inlen, NULL, 0);
    wchar_t* wstr = new wchar_t[len + 1];
    memset(wstr, 0, len + 1);

    MultiByteToWideChar(CP_ACP, 0, inbuf, inlen, wstr, len);
    len = WideCharToMultiByte(CP_UTF8, 0, wstr, -1, NULL, 0, NULL, NULL);

    memset(outbuf, 0, outlen + 1);
    WideCharToMultiByte(CP_UTF8, 0, wstr, -1, outbuf, outlen, NULL, NULL);
    if (wstr) delete[] wstr;
    return 0;
}
#else
static int code_convert(const char *from_charset, const char *to_charset, char *inbuf, size_t inlen,
    char *outbuf, size_t outlen) 
{
    iconv_t cd;
    char **pin = &inbuf;
    char **pout = &outbuf;

    cd = iconv_open(to_charset, from_charset);
    if (cd == 0)
        return -1;
    memset(outbuf, 0, outlen);
    if (iconv(cd, pin, &inlen, pout, &outlen) == (size_t)-1)
        return -1;
    iconv_close(cd);
    *pout = '\0';

    return 0;
}
//UTF-8到GB2312的转换
int utf8_to_gbk(char *inbuf, size_t inlen, char *outbuf, size_t outlen) {
    return code_convert((const char*)"utf-8", (const char*)"gb2312", inbuf, inlen, outbuf, outlen);
}
//GB2312到UTF-8的转换
int gbk_to_utf8(char *inbuf, size_t inlen, char *outbuf, size_t outlen) {
    return code_convert((const char*)"gb2312", (const char*)"utf-8", inbuf, inlen, outbuf, outlen);
}
#endif

