21 #import <Foundation/Foundation.h>
23 #include <winpr/config.h>
24 #include <winpr/assert.h>
29 #include <winpr/crt.h>
30 #include <winpr/error.h>
31 #include <winpr/print.h>
36 #define MIN(a, b) (a) < (b) ? (a) : (b)
40 #define TAG WINPR_TAG("unicode")
42 int int_MultiByteToWideChar(UINT CodePage, DWORD dwFlags, LPCSTR lpMultiByteStr,
int cbMultiByte,
43 LPWSTR lpWideCharStr,
int cchWideChar)
45 const BOOL isNullTerminated = cbMultiByte < 0;
48 if ((cbMultiByte == 0) || (cbMultiByte < -1))
54 size_t len = strnlen(lpMultiByteStr, INT32_MAX);
57 cbMultiByte = (int)len + 1;
60 NSString *utf = [[NSString alloc] initWithBytes:lpMultiByteStr
62 encoding:NSUTF8StringEncoding];
65 WLog_WARN(TAG,
"[NSString alloc] NSUTF8StringEncoding failed [%d] '%s'", cbMultiByte,
71 (
const WCHAR *)[utf cStringUsingEncoding:NSUTF16LittleEndianStringEncoding];
72 const size_t utf16ByteLen = [utf lengthOfBytesUsingEncoding:NSUTF16LittleEndianStringEncoding];
73 const size_t utf16CharLen = utf16ByteLen /
sizeof(WCHAR);
76 WLog_WARN(TAG,
"[utf cStringUsingEncoding:NSUTF16LittleEndianStringEncoding] failed");
82 else if (cchWideChar < utf16CharLen)
84 SetLastError(ERROR_INSUFFICIENT_BUFFER);
89 const size_t mlen = MIN((
size_t)utf16CharLen, cchWideChar);
90 const size_t len = _wcsnlen(utf16, mlen);
91 memcpy(lpWideCharStr, utf16, len *
sizeof(WCHAR));
92 if ((len < (
size_t)cchWideChar) && (len > 0) && (lpWideCharStr[len - 1] !=
'\0'))
93 lpWideCharStr[len] =
'\0';
98 int int_WideCharToMultiByte(UINT CodePage, DWORD dwFlags, LPCWSTR lpWideCharStr,
int cchWideChar,
99 LPSTR lpMultiByteStr,
int cbMultiByte, LPCSTR lpDefaultChar,
100 LPBOOL lpUsedDefaultChar)
102 const BOOL isNullTerminated = cchWideChar < 0;
105 if ((cchWideChar == 0) || (cchWideChar < -1))
109 if (isNullTerminated)
111 size_t len = _wcslen(lpWideCharStr);
112 if (len >= INT32_MAX)
114 cchWideChar = (int)len + 1;
117 NSString *utf = [[NSString alloc] initWithCharacters:lpWideCharStr length:cchWideChar];
120 WLog_WARN(TAG,
"[NSString alloc] initWithCharacters failed [%d] 'XXX'", cchWideChar);
124 const char *utf8 = [utf cStringUsingEncoding:NSUTF8StringEncoding];
125 const size_t utf8Len = [utf lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
128 WLog_WARN(TAG,
"[utf cStringUsingEncoding:NSUTF8StringEncoding] failed");
132 if (cbMultiByte == 0)
134 else if (cbMultiByte < utf8Len)
136 SetLastError(ERROR_INSUFFICIENT_BUFFER);
141 const size_t mlen = MIN((
size_t)cbMultiByte, utf8Len);
142 const size_t len = strnlen(utf8, mlen);
143 memcpy(lpMultiByteStr, utf8, len *
sizeof(
char));
144 if ((len < (
size_t)cbMultiByte) && (len > 0) && (lpMultiByteStr[len - 1] !=
'\0'))
145 lpMultiByteStr[len] =
'\0';