#include <sys/types.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#if defined(_WIN32) && !defined(__MINGW32__)
#include "config-msvc.h"
#else
#include "config.h"
#endif
#if OMIT_ICONV == 0
#if defined(__MINGW32__) || defined(_WIN32)
#define LIBICONV_STATIC
#include <iconv.h>
#define LIBCHARSET_STATIC
#ifdef _MSC_VER
extern const char *locale_charset (void);
#else
#include <localcharset.h>
#endif
#else
#if defined(__APPLE__) || defined(__ANDROID__)
#include <iconv.h>
#include <localcharset.h>
#else
#include <iconv.h>
#include <langinfo.h>
#endif
#endif
#include <spatialite/sqlite.h>
#include <spatialite/gaiaaux.h>
GAIAAUX_DECLARE const char *
gaiaGetLocaleCharset ()
{
#if defined(__MINGW32__) || defined(_WIN32)
return locale_charset ();
#else
#if defined(__APPLE__) || defined(__ANDROID__)
return locale_charset ();
#else
return nl_langinfo (CODESET);
#endif
#endif
}
GAIAAUX_DECLARE int
gaiaConvertCharset (char **buf, const char *fromCs, const char *toCs)
{
char utf8buf[65536];
#if !defined(__MINGW32__) && defined(_WIN32)
const char *pBuf;
#else
char *pBuf;
#endif
size_t len;
size_t utf8len;
char *pUtf8buf;
iconv_t cvt = iconv_open (toCs, fromCs);
if (cvt == (iconv_t) (-1))
goto unsupported;
len = strlen (*buf);
utf8len = 65536;
pBuf = *buf;
pUtf8buf = utf8buf;
if (iconv (cvt, &pBuf, &len, &pUtf8buf, &utf8len) == (size_t) (-1))
goto error;
utf8buf[65536 - utf8len] = '\0';
memcpy (*buf, utf8buf, (65536 - utf8len) + 1);
iconv_close (cvt);
return 1;
error:
iconv_close (cvt);
unsupported:
return 0;
}
GAIAAUX_DECLARE void *
gaiaCreateUTF8Converter (const char *fromCS)
{
iconv_t cvt = iconv_open ("UTF-8", fromCS);
if (cvt == (iconv_t) (-1))
return NULL;
return cvt;
}
GAIAAUX_DECLARE void
gaiaFreeUTF8Converter (void *cvtCS)
{
if (cvtCS)
iconv_close (cvtCS);
}
GAIAAUX_DECLARE char *
gaiaConvertToUTF8 (void *cvtCS, const char *buf, int buflen, int *err)
{
char *utf8buf = 0;
#if !defined(__MINGW32__) && defined(_WIN32)
const char *pBuf;
#else
char *pBuf;
#endif
size_t len;
size_t utf8len;
int maxlen = buflen * 4;
char *pUtf8buf;
*err = 0;
if (!cvtCS)
{
*err = 1;
return NULL;
}
utf8buf = malloc (maxlen);
len = buflen;
utf8len = maxlen;
pBuf = (char *) buf;
pUtf8buf = utf8buf;
if (iconv (cvtCS, &pBuf, &len, &pUtf8buf, &utf8len) == (size_t) (-1))
{
free (utf8buf);
*err = 1;
return NULL;
}
utf8buf[maxlen - utf8len] = '\0';
return utf8buf;
}
#endif