#include <sys/types.h>
#include <sys/param.h>
#include <errno.h>
#include <iconv.h>
#include <libintl.h>
#include <langinfo.h>
#include <search.h>
#include <stdlib.h>
#include <string.h>
#include "libintl_local.h"
struct cache {
const char *c_origmsg;
const char *c_resultmsg;
};
static const struct cache *cache_find(const char *, struct domainbinding *);
static int cache_enter(const char *, const char *);
static int cache_cmp(const void *, const void *);
static void *cacheroot;
static const struct cache *
cache_find(const char *msg, struct domainbinding *db)
{
struct cache key;
struct cache **c;
key.c_origmsg = msg;
c = tfind(&key, &cacheroot, cache_cmp);
return c ? *c : NULL;
}
static int
cache_enter(const char *origmsg, const char *resultmsg)
{
struct cache *c;
c = malloc(sizeof(*c));
if (c == NULL)
return -1;
c->c_origmsg = origmsg;
c->c_resultmsg = resultmsg;
if (tsearch(c, &cacheroot, cache_cmp) == NULL) {
free(c);
return -1;
}
return 0;
}
static int
cache_cmp(const void *va, const void *vb)
{
const struct cache *a = va;
const struct cache *b = vb;
int result;
if (a->c_origmsg > b->c_origmsg) {
result = 1;
} else if (a->c_origmsg < b->c_origmsg) {
result = -1;
} else {
result = 0;
}
return result;
}
#define GETTEXT_ICONV_MALLOC_CHUNK (16 * 1024)
const char *
__gettext_iconv(const char *origmsg, struct domainbinding *db)
{
const char *tocode;
const char *fromcode = db->mohandle.mo.mo_charset;
const struct cache *cache;
const char *result;
iconv_t cd;
const char *src;
char *dst;
size_t origlen;
size_t srclen;
size_t dstlen;
size_t nvalid;
int savederrno = errno;
static char *buffer;
static size_t bufferlen;
if (fromcode == NULL)
return origmsg;
tocode = db->codeset;
if (tocode == NULL) {
tocode = nl_langinfo(CODESET);
}
if (!strcasecmp(tocode, fromcode))
return origmsg;
cache = cache_find(origmsg, db);
if (cache) {
result = cache->c_resultmsg;
goto out;
}
origlen = strlen(origmsg) + 1;
again:
cd = iconv_open(tocode, fromcode);
if (cd == (iconv_t)-1) {
result = origmsg;
goto out;
}
src = origmsg;
srclen = origlen;
dst = buffer;
dstlen = bufferlen;
nvalid = iconv(cd, __UNCONST(&src), &srclen, &dst, &dstlen);
iconv_close(cd);
if (nvalid == (size_t)-1) {
if (errno == E2BIG &&
bufferlen != GETTEXT_ICONV_MALLOC_CHUNK) {
buffer = malloc(GETTEXT_ICONV_MALLOC_CHUNK);
if (buffer) {
bufferlen = GETTEXT_ICONV_MALLOC_CHUNK;
goto again;
}
}
result = origmsg;
} else if (cache_enter(origmsg, buffer)) {
result = origmsg;
} else {
size_t resultlen = dst - buffer;
result = buffer;
bufferlen -= resultlen;
buffer += resultlen;
}
out:
errno = savederrno;
return result;
}