From acbfcecb7f6e3e8811b0ca07bdaed2ed058f8ac2 Mon Sep 17 00:00:00 2001 From: Charles Milette Date: Sun, 16 Oct 2022 21:11:20 -0400 Subject: [PATCH] Efficient way to format directly to hstring --- strings/base_string.h | 28 ++++++++++++++++++++++++++++ test/test_cpp20/format.cpp | 7 +++++++ 2 files changed, 35 insertions(+) diff --git a/strings/base_string.h b/strings/base_string.h index c23e981c3..dbe022857 100644 --- a/strings/base_string.h +++ b/strings/base_string.h @@ -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(end - buffer)} }; } + +#if __cpp_lib_format >= 202207L + template + inline hstring base_format(Args&&... args) + { + auto const size = std::formatted_size(args...); + WINRT_ASSERT(size < UINT_MAX); + auto const size32 = static_cast(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 + inline hstring format(std::wformat_string const fmt, Args&&... args) + { + return impl::base_format(fmt, args...); + } + + template + inline hstring format(std::locale const& loc, std::wformat_string 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) diff --git a/test/test_cpp20/format.cpp b/test/test_cpp20/format.cpp index b3119a77e..a77c2afbe 100644 --- a/test/test_cpp20/format.cpp +++ b/test/test_cpp20/format.cpp @@ -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 }