fix(ground-suite): handle failed UTF-16 conversion sizes

Reject failed UTF-16 sizing queries before allocating the UTF-8 result
and preserve terminating-NUL accounting.

Validation: nine host-stub cases with 16-bit wchar_t; native Windows
execution remains unverified.
This commit is contained in:
Onur Özkan committed 2026-11-07 18:12:11 +03:00
1 parent a78754d909
commit 4953f0a974
2 files changed
+131 -7

No files matched your search

+10 -7
View File
@@ -45,21 +45,24 @@ std::string Utf8FromUtf16(const wchar_t* utf16_string) {
if (utf16_string == nullptr) {
return std::string();
}
unsigned int target_length = ::WideCharToMultiByte(
const int target_length = ::WideCharToMultiByte(
CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string,
-1, nullptr, 0, nullptr, nullptr)
-1; // remove the trailing null character
int input_length = (int)wcslen(utf16_string);
-1, nullptr, 0, nullptr, nullptr);
if (target_length <= 0) {
return std::string();
}
std::string utf8_string;
if (target_length == 0 || target_length > utf8_string.max_size()) {
if (static_cast<size_t>(target_length) > utf8_string.max_size()) {
return utf8_string;
}
// With a terminated input, both calls include the trailing null character.
utf8_string.resize(target_length);
int converted_length = ::WideCharToMultiByte(
CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string,
input_length, utf8_string.data(), target_length, nullptr, nullptr);
if (converted_length == 0) {
-1, utf8_string.data(), target_length, nullptr, nullptr);
if (converted_length != target_length) {
return std::string();
}
utf8_string.resize(static_cast<size_t>(converted_length) - 1);
return utf8_string;
}