Set conv_fails on total conversion failure too.
[gedcom-parse.git] / utf8 / utf8-locale.c
index de40ded6db26c46c02d893a9b8605107e8546033..9d58b625db3c47eae95f13604e682502c26dcd71 100644 (file)
 
 #include <stdlib.h>
 #include <iconv.h>
-#include <langinfo.h>
 #include <assert.h>
 #include <errno.h>
+#include <string.h>
+#include "config.h"
+#include "libcharset.h"
 #include "utf8-locale.h"
 
 #define INITIAL_OUTSIZE 256
@@ -42,11 +44,11 @@ int open_conversion_contexts()
 {
   assert(utf8_to_locale == (iconv_t) -1);
   assert(locale_to_utf8 == (iconv_t) -1);
-  utf8_to_locale = iconv_open(nl_langinfo(CODESET), "UTF-8");
+  utf8_to_locale = iconv_open(locale_charset(), "UTF-8");
   if (utf8_to_locale == (iconv_t) -1)
     return -1;
   else {
-    locale_to_utf8 = iconv_open("UTF-8", nl_langinfo(CODESET));
+    locale_to_utf8 = iconv_open("UTF-8", locale_charset());
     if (locale_to_utf8 == (iconv_t) -1) {
       close_conversion_contexts();
       return -1;
@@ -60,16 +62,18 @@ int open_conversion_contexts()
   }
 }
 
-char* convert_utf8_to_locale(char* input, int *conv_fails)
+char* convert_utf8_to_locale(const char* input, int *conv_fails)
 {
   size_t insize  = strlen(input);
   size_t outsize;
-  char   *inptr  = input;
+  ICONV_CONST char *inptr  = (ICONV_CONST char*) input;
   char   *outptr;
   size_t nconv;
 
-  if (utf8_to_locale == (iconv_t) -1 && (open_conversion_contexts() == -1))
+  if (utf8_to_locale == (iconv_t) -1 && (open_conversion_contexts() == -1)) {
+    if (conv_fails != NULL) *conv_fails = insize;
     return NULL;
+  }
   assert(utf8_to_locale != (iconv_t) -1);
   /* make sure we start from an empty state */
   iconv(utf8_to_locale, NULL, NULL, NULL, NULL);
@@ -111,6 +115,7 @@ char* convert_utf8_to_locale(char* input, int *conv_fails)
     else {
       /* EINVAL should not happen, since we convert entire strings */
       /* EBADF is an error which should be captured by the assert above */
+      if (conv_fails != NULL) *conv_fails += insize;
       return NULL;
     }
     nconv = iconv(utf8_to_locale, &inptr, &insize, &outptr, &outsize);
@@ -118,11 +123,11 @@ char* convert_utf8_to_locale(char* input, int *conv_fails)
   return outbuffer;
 }
 
-char* convert_locale_to_utf8(char* input)
+char* convert_locale_to_utf8(const char* input)
 {
   size_t insize  = strlen(input);
   size_t outsize;
-  char   *inptr  = input;
+  ICONV_CONST char *inptr  = (ICONV_CONST char*) input;
   char   *outptr;
   size_t nconv;