Skip to content

Commit

Permalink
Efficient way to format directly to hstring (#1207)
Browse files Browse the repository at this point in the history
  • Loading branch information
sylveon authored Nov 12, 2022
1 parent 8da046a commit 104b0b9
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 0 deletions.
28 changes: 28 additions & 0 deletions strings/base_string.h
Original file line number Diff line number Diff line change
Expand Up @@ -550,10 +550,38 @@ namespace winrt::impl
auto end = std::copy(std::begin(temp), result.ptr, buffer);
return hstring{ std::wstring_view{ buffer, static_cast<std::size_t>(end - buffer)} };
}

#if __cpp_lib_format >= 202207L
template <typename... Args>
inline hstring base_format(Args&&... args)
{
auto const size = std::formatted_size(args...);
WINRT_ASSERT(size < UINT_MAX);
auto const size32 = static_cast<uint32_t>(size);

hstring_builder builder(size32);
WINRT_VERIFY_(size32, std::format_to_n(builder.data(), size32, args...).size);
return builder.to_hstring();
}
#endif
}

WINRT_EXPORT namespace winrt
{
#if __cpp_lib_format >= 202207L
template <typename... Args>
inline hstring format(std::wformat_string<Args...> const fmt, Args&&... args)
{
return impl::base_format(fmt, args...);
}

template <typename... Args>
inline hstring format(std::locale const& loc, std::wformat_string<Args...> const fmt, Args&&... args)
{
return impl::base_format(loc, fmt, args...);
}
#endif

inline bool embedded_null(hstring const& value) noexcept
{
return std::any_of(value.begin(), value.end(), [](auto item)
Expand Down
7 changes: 7 additions & 0 deletions test/test_cpp20/format.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -25,4 +25,11 @@ TEST_CASE("format")
winrt::Windows::Data::Json::JsonArray jsonArray;
REQUIRE(std::format(L"The contents of the array are: {}", jsonArray) == L"The contents of the array are: []");
}

#if __cpp_lib_format >= 202207L
{
std::wstring str = L"World";
REQUIRE(winrt::format(L"Hello {}", str) == L"Hello World");
}
#endif
}

0 comments on commit 104b0b9

Please sign in to comment.