1 |
/* wptUTF8.cpp - UTF8 conversation |
/* wptUTF8.cpp - UTF8 conversation |
2 |
* Copyright (C) 2002, 2004, 2005, 2006 Timo Schulz |
* Copyright (C) 2002, 2004, 2005, 2006, 2009 Timo Schulz |
3 |
* |
* |
4 |
* This file is part of WinPT. |
* This file is part of WinPT. |
5 |
* |
* |
27 |
#include "wptErrors.h" |
#include "wptErrors.h" |
28 |
|
|
29 |
|
|
30 |
|
/** |
31 |
|
* Converts the given intput string, which is encoded with the locale |
32 |
|
* setting, into UTF-8 representation. |
33 |
|
*/ |
34 |
char* |
char* |
35 |
native_to_utf8 (const char *string) |
native_to_utf8 (const char *string) |
36 |
{ |
{ |
67 |
} |
} |
68 |
|
|
69 |
free_if_alloc (result); |
free_if_alloc (result); |
70 |
|
//native[n] = '\0'; |
71 |
return native; |
return native; |
72 |
} |
} |
73 |
|
|
74 |
|
|
75 |
/* Convert utf8 string @str to native CP. */ |
/** |
76 |
|
* Converts the given string, which is encoded in UTF-8, |
77 |
|
* into the locale setting. |
78 |
|
*/ |
79 |
char* |
char* |
80 |
utf8_to_native (const char *string) |
utf8_to_native (const char *string) |
81 |
{ |
{ |
87 |
if (n < 0) |
if (n < 0) |
88 |
return NULL; |
return NULL; |
89 |
|
|
90 |
result = (wchar_t*)malloc ((n+1) * sizeof *result); |
result = new wchar_t[n+1]; |
91 |
if (!result) |
if (!result) |
92 |
BUG (0); |
BUG (0); |
93 |
|
|
94 |
n = MultiByteToWideChar (CP_UTF8, 0, string, -1, result, n); |
n = MultiByteToWideChar (CP_UTF8, 0, string, -1, result, n); |
95 |
if (n < 0) { |
if (n < 0) { |
96 |
free (result); |
free_if_alloc (result); |
97 |
return NULL; |
return NULL; |
98 |
} |
} |
99 |
|
|
101 |
if (n < 0) |
if (n < 0) |
102 |
return NULL; |
return NULL; |
103 |
|
|
104 |
native = (char*)malloc (n+1); |
native = new char[n+1]; |
105 |
if (!native) |
if (!native) |
106 |
BUG (0); |
BUG (0); |
107 |
|
|
108 |
n = WideCharToMultiByte (GetACP (), 0, result, -1, native, n, NULL, NULL); |
n = WideCharToMultiByte (GetACP (), 0, result, -1, native, n, NULL, NULL); |
109 |
if (n < 0) { |
if (n < 0) { |
110 |
free (result); |
free_if_alloc (result); |
111 |
return NULL; |
return NULL; |
112 |
} |
} |
113 |
|
|
114 |
free (result); |
free_if_alloc (result); |
115 |
|
//native[n] = '\0'; |
116 |
return native; |
return native; |
117 |
} |
} |
118 |
|
|
119 |
|
|
120 |
/* Return -1 if the string contains any 8-bit characters. */ |
/** |
121 |
|
* Returns -1 if the given string contains any 8-bit characters. |
122 |
|
* This is a helper to decide when to use UTF8 encoding. |
123 |
|
*/ |
124 |
int |
int |
125 |
is_8bit_string (const char *str) |
is_8bit_string (const char *str) |
126 |
{ |
{ |
127 |
size_t i; |
for (size_t i = 0; i < strlen (str); i++) { |
|
|
|
|
for (i = 0; i < strlen (str); i++) { |
|
128 |
if (str[i] & 0x80) |
if (str[i] & 0x80) |
129 |
return -1; |
return -1; |
130 |
} |
} |