comparison 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
comparison
equal deleted inserted replaced
250:1e112cf41e92 251:c596568fa45b
4 #include <stdlib.h> 4 #include <stdlib.h>
5 #include <string.h> 5 #include <string.h>
6 #include <assert.h> 6 #include <assert.h>
7 7
8 #include <polarssl/base64.h> 8 #include <polarssl/base64.h>
9
10 #ifdef WIN32
11 #include <windows.h>
12 #endif
9 13
10 /* Remarks regarding the "Flawfinder: ignore" comments in this file: 14 /* Remarks regarding the "Flawfinder: ignore" comments in this file:
11 * 15 *
12 * - strlen: 16 * - strlen:
13 * 17 *
180 *dst = NULL; 184 *dst = NULL;
181 *dst_size = 0; 185 *dst_size = 0;
182 } 186 }
183 return ret; 187 return ret;
184 } 188 }
189
190 void
191 xfree (void *p)
192 {
193 if (p)
194 free (p);
195 }
196
197 #ifdef WIN32
198 /* Adapted from GPGOL rev. e512053 */
199 char *
200 wchar_to_utf8 (const wchar_t *string, size_t len)
201 {
202 int n, ilen;
203 char *result;
204
205 ilen = (int) len;
206 if (ilen < 0)
207 return NULL;
208
209 /* Note, that CP_UTF8 is not defined in Windows versions earlier
210 than NT.*/
211 n = WideCharToMultiByte (CP_UTF8, 0, string, ilen, NULL, 0, NULL, NULL);
212 if (n < 0)
213 return NULL;
214
215 result = xmalloc ((size_t)n+1);
216 n = WideCharToMultiByte (CP_UTF8, 0, string, ilen, result, n, NULL, NULL);
217 if (n < 0)
218 {
219 xfree (result);
220 return NULL;
221 }
222 return result;
223 }
224
225 /* Adapted from GPGOL rev. e512053 */
226 wchar_t *
227 utf8_to_wchar (const char *string, size_t len)
228 {
229 int n, ilen;
230 wchar_t *result;
231
232 ilen = (int) len;
233 if (ilen < 0)
234 return NULL;
235
236 n = MultiByteToWideChar (CP_UTF8, 0, string, ilen, NULL, 0);
237 if (n < 0 || n + 1 < 0)
238 return NULL;
239
240 result = xmalloc ((size_t)(n+1) * sizeof *result);
241 n = MultiByteToWideChar (CP_UTF8, 0, string, ilen, result, n);
242 if (n < 0)
243 {
244 xfree (result);
245 return NULL;
246 }
247 result[n] = 0;
248 return result;
249 }
250 #endif

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