Skip to content
Open
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 11 additions & 8 deletions strings/base_string.h
Original file line number Diff line number Diff line change
Expand Up @@ -674,14 +674,7 @@ WINRT_EXPORT namespace winrt
template <typename T, std::enable_if_t<std::is_same_v<T, bool>, int> = 0>
hstring to_hstring(T const value)
{
if (value)
{
return hstring{ L"true" };
}
else
{
return hstring{ L"false" };
}
return hstring{ value ? L"true" : L"false" };
}

inline hstring to_hstring(guid const& value)
Expand Down Expand Up @@ -719,8 +712,18 @@ WINRT_EXPORT namespace winrt
return{};
}

#if defined(__cpp_lib_string_resize_and_overwrite) && __cpp_lib_string_resize_and_overwrite >= 202110L
std::string result;
result.resize_and_overwrite(size, [&](char* buffer, std::size_t) -> std::size_t

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: Feels slightly dirty to capture size instead of using the lambda's param. Perhaps this is simplified if we are selective about our lambda captures and capture only &value.

{
auto bytes_written = WINRT_IMPL_WideCharToMultiByte(65001 /*CP_UTF8*/, 0, value.data(), static_cast<std::int32_t>(value.size()), buffer, size, nullptr, nullptr);
WINRT_VERIFY_(size, bytes_written);
return bytes_written == size ? size : 0;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: This slightly changes the specified behavior from the original. Now we truncate to zero if written differs from size, whereas before we would simply accept the result.

In practice, assuming WideCharToMultiByte behaves sanely, written should always equal the value of size (obtained from the first call to WCTMB). I think we are committing to assuming this sane behavior, so let's keep the defensive guardrails consistent, and go ahead and return bytes_written directly. The WINRT_VERIFY_ sanity check is fine to keep as is to warn if something weird happened.

});
Comment thread
YexuanXiao marked this conversation as resolved.
#else
std::string result(size, '?');
WINRT_VERIFY_(size, WINRT_IMPL_WideCharToMultiByte(65001 /*CP_UTF8*/, 0, value.data(), static_cast<std::int32_t>(value.size()), result.data(), size, nullptr, nullptr));
#endif
return result;
}
}