Skip empty strings in ToUtf(8|16).

We've observed a crash on Windows when the strings are empty, skipping the conversion seems reasonable in that case.

Bug: None
Change-Id: I3acf3060a88741fb750d7a0cc02e9422713c59cd
Reviewed-on: https://webrtc-review.googlesource.com/c/src/+/147380
Commit-Queue: Noah Richards <noahric@chromium.org>
Reviewed-by: Stefan Holmer <stefan@webrtc.org>
Cr-Commit-Position: refs/heads/master@{#28709}
This commit is contained in:
Noah Richards 2019-07-30 11:56:08 -07:00 committed by Commit Bot
parent fe431e482e
commit 4ed5b087f5
2 changed files with 15 additions and 0 deletions

View file

@ -47,6 +47,8 @@ size_t strcpyn(char* buffer,
#if defined(WEBRTC_WIN)
inline std::wstring ToUtf16(const char* utf8, size_t len) {
if (len == 0)
return std::wstring();
int len16 = ::MultiByteToWideChar(CP_UTF8, 0, utf8, static_cast<int>(len),
nullptr, 0);
std::wstring ws(len16, 0);
@ -60,6 +62,8 @@ inline std::wstring ToUtf16(const std::string& str) {
}
inline std::string ToUtf8(const wchar_t* wide, size_t len) {
if (len == 0)
return std::string();
int len8 = ::WideCharToMultiByte(CP_UTF8, 0, wide, static_cast<int>(len),
nullptr, 0, nullptr, nullptr);
std::string ns(len8, 0);

View file

@ -28,4 +28,15 @@ TEST(string_toHexTest, ToHex) {
EXPECT_EQ(ToHex(-20), "ffffffec");
}
#if defined(WEBRTC_WIN)
TEST(string_toutf, Empty) {
char empty_string[] = "";
EXPECT_TRUE(ToUtf16(empty_string, 0u).empty());
wchar_t empty_wchar[] = L"";
EXPECT_TRUE(ToUtf8(empty_wchar, 0u).empty());
}
#endif // WEBRTC_WIN
} // namespace rtc