From 6a9016ea600738ded2b90666d62b8f9bd241c00b Mon Sep 17 00:00:00 2001 From: Alexey Ochapov Date: Sun, 7 Mar 2021 17:44:36 +0300 Subject: [PATCH] fix `formatted_size` with "compiled format" as argument (#2161) --- include/fmt/compile.h | 5 ++++- include/fmt/core.h | 6 +++--- test/compile-test.cc | 5 +++++ 3 files changed, 12 insertions(+), 4 deletions(-) diff --git a/include/fmt/compile.h b/include/fmt/compile.h index fa8eaeca2028..819d4abd9cac 100644 --- a/include/fmt/compile.h +++ b/include/fmt/compile.h @@ -928,7 +928,10 @@ format_to_n_result format_to_n(OutputIt out, size_t n, const S&, return {it.base(), it.count()}; } -template +template ::value || + detail::is_compiled_string::value)> size_t formatted_size(const CompiledFormat& cf, const Args&... args) { return format_to(detail::counting_iterator(), cf, args...).count(); } diff --git a/include/fmt/core.h b/include/fmt/core.h index 7b2b2a435a0c..68cc7964fdd6 100644 --- a/include/fmt/core.h +++ b/include/fmt/core.h @@ -1865,11 +1865,11 @@ inline auto format_to_n(OutputIt out, size_t n, const S& format_str, Returns the number of characters in the output of ``format(format_str, args...)``. */ -template -inline size_t formatted_size(string_view format_str, Args&&... args) { +template > +inline size_t formatted_size(const S& format_str, Args&&... args) { const auto& vargs = fmt::make_args_checked(format_str, args...); detail::counting_buffer<> buf; - detail::vformat_to(buf, format_str, vargs); + detail::vformat_to(buf, to_string_view(format_str), vargs); return buf.count(); } diff --git a/test/compile-test.cc b/test/compile-test.cc index d75166cc11af..2be2b884b7f4 100644 --- a/test/compile-test.cc +++ b/test/compile-test.cc @@ -261,6 +261,11 @@ TEST(CompileTest, FormatToNWithCompileMacro) { EXPECT_STREQ("2a", buffer); } +TEST(CompileTest, FormattedSizeWithCompileMacro) { + EXPECT_EQ(2, fmt::formatted_size(FMT_COMPILE("{0}"), 42)); + EXPECT_EQ(5, fmt::formatted_size(FMT_COMPILE("{0:<4.2f}"), 42.0)); +} + TEST(CompileTest, TextAndArg) { EXPECT_EQ(">>>42<<<", fmt::format(FMT_COMPILE(">>>{}<<<"), 42)); EXPECT_EQ("42!", fmt::format(FMT_COMPILE("{}!"), 42));