diff common/strhelp.c @ 251:c596568fa45b

Add utf16 conversion functions for Windows. This also includes a null pointer checking free.
author Andre Heinecke <aheinecke@intevation.de>
date Tue, 01 Apr 2014 10:48:35 +0000
parents 4def8b263dd3
children c4a989a0d6cf
line wrap: on
line diff
--- a/common/strhelp.c	Mon Mar 31 11:41:43 2014 +0200
+++ b/common/strhelp.c	Tue Apr 01 10:48:35 2014 +0000
@@ -7,6 +7,10 @@
 
 #include <polarssl/base64.h>
 
+#ifdef WIN32
+#include <windows.h>
+#endif
+
 /* Remarks regarding the "Flawfinder: ignore" comments in this file:
  *
  * - strlen:
@@ -182,3 +186,65 @@
     }
     return ret;
 }
+
+void
+xfree (void *p)
+{
+  if (p)
+    free (p);
+}
+
+#ifdef WIN32
+/* Adapted from GPGOL rev. e512053 */
+char *
+wchar_to_utf8 (const wchar_t *string, size_t len)
+{
+  int n, ilen;
+  char *result;
+
+  ilen = (int) len;
+  if (ilen < 0)
+    return NULL;
+
+  /* Note, that CP_UTF8 is not defined in Windows versions earlier
+     than NT.*/
+  n = WideCharToMultiByte (CP_UTF8, 0, string, ilen, NULL, 0, NULL, NULL);
+  if (n < 0)
+    return NULL;
+
+  result = xmalloc ((size_t)n+1);
+  n = WideCharToMultiByte (CP_UTF8, 0, string, ilen, result, n, NULL, NULL);
+  if (n < 0)
+    {
+      xfree (result);
+      return NULL;
+    }
+  return result;
+}
+
+/* Adapted from GPGOL rev. e512053 */
+wchar_t *
+utf8_to_wchar (const char *string, size_t len)
+{
+  int n, ilen;
+  wchar_t *result;
+
+  ilen = (int) len;
+  if (ilen < 0)
+    return NULL;
+
+  n = MultiByteToWideChar (CP_UTF8, 0, string, ilen, NULL, 0);
+  if (n < 0 || n + 1 < 0)
+    return NULL;
+
+  result = xmalloc ((size_t)(n+1) * sizeof *result);
+  n = MultiByteToWideChar (CP_UTF8, 0, string, ilen, result, n);
+  if (n < 0)
+    {
+      xfree (result);
+      return NULL;
+    }
+  result[n] = 0;
+  return result;
+}
+#endif

http://wald.intevation.org/projects/trustbridge/