Skip to content

Commit

Permalink
StringToUTF16: Actually observe input and output widths correctly.
Browse files Browse the repository at this point in the history
I must have read over the "size, in wide characters" part. This becomes a problem once you only convert a part of the input string, which we haven't needed up to now.
  • Loading branch information
nmlgc committed Aug 2, 2013
1 parent 93a7bcb commit c230ad4
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 4 deletions.
15 changes: 12 additions & 3 deletions win32_utf8/src/utf.c
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,22 @@

int StringToUTF16(wchar_t *str_w, const char *str_mb, size_t str_len)
{
size_t str_w_len = str_len * sizeof(wchar_t);
int ret;
extern UINT fallback_codepage;

ret = MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, str_mb, -1, str_w, str_w_len);
if(!str_mb || !str_len) {
return 0;
}

ret = MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, str_mb, str_len, str_w, str_len);
if(!ret) {
ret = MultiByteToWideChar(fallback_codepage, MB_PRECOMPOSED, str_mb, -1, str_w, str_w_len);
if(str_mb[str_len - 1] != 0) {
// The previous conversion attempt still lingers in [str_w].
// If we don't clear it in case the original string isn't null-terminated,
// garbage may show up at the end of the converted string...
ZeroMemory(str_w, str_len * sizeof(wchar_t));
}
ret = MultiByteToWideChar(fallback_codepage, MB_PRECOMPOSED, str_mb, str_len, str_w, str_len);
}
return ret;
}
Expand Down
2 changes: 1 addition & 1 deletion win32_utf8/src/utf.h
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
// Maximum length of the largest wchar_t in UTF-8
#define UTF8_MUL 4

// Converts a "narrow" string to UTF-16.
// Converts [str_len] characters of the "narrow" string [str_mb] to UTF-16.
// Input can either be in UTF-8 or the fallback codepage specified by a call
// to w32u8_set_fallback_codepage().
int StringToUTF16(wchar_t *str_w, const char *str_mb, size_t str_len);
Expand Down

0 comments on commit c230ad4

Please sign in to comment.