Skip to content

Commit 104b0b9

Browse files
authored
Efficient way to format directly to hstring (#1207)
1 parent 8da046a commit 104b0b9

File tree

2 files changed

+35
-0
lines changed

2 files changed

+35
-0
lines changed

strings/base_string.h

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -550,10 +550,38 @@ namespace winrt::impl
550550
auto end = std::copy(std::begin(temp), result.ptr, buffer);
551551
return hstring{ std::wstring_view{ buffer, static_cast<std::size_t>(end - buffer)} };
552552
}
553+
554+
#if __cpp_lib_format >= 202207L
555+
template <typename... Args>
556+
inline hstring base_format(Args&&... args)
557+
{
558+
auto const size = std::formatted_size(args...);
559+
WINRT_ASSERT(size < UINT_MAX);
560+
auto const size32 = static_cast<uint32_t>(size);
561+
562+
hstring_builder builder(size32);
563+
WINRT_VERIFY_(size32, std::format_to_n(builder.data(), size32, args...).size);
564+
return builder.to_hstring();
565+
}
566+
#endif
553567
}
554568

555569
WINRT_EXPORT namespace winrt
556570
{
571+
#if __cpp_lib_format >= 202207L
572+
template <typename... Args>
573+
inline hstring format(std::wformat_string<Args...> const fmt, Args&&... args)
574+
{
575+
return impl::base_format(fmt, args...);
576+
}
577+
578+
template <typename... Args>
579+
inline hstring format(std::locale const& loc, std::wformat_string<Args...> const fmt, Args&&... args)
580+
{
581+
return impl::base_format(loc, fmt, args...);
582+
}
583+
#endif
584+
557585
inline bool embedded_null(hstring const& value) noexcept
558586
{
559587
return std::any_of(value.begin(), value.end(), [](auto item)

test/test_cpp20/format.cpp

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,4 +25,11 @@ TEST_CASE("format")
2525
winrt::Windows::Data::Json::JsonArray jsonArray;
2626
REQUIRE(std::format(L"The contents of the array are: {}", jsonArray) == L"The contents of the array are: []");
2727
}
28+
29+
#if __cpp_lib_format >= 202207L
30+
{
31+
std::wstring str = L"World";
32+
REQUIRE(winrt::format(L"Hello {}", str) == L"Hello World");
33+
}
34+
#endif
2835
}

0 commit comments

Comments
 (0)