From 9a4cc88426831595a29147cc32539c8141752267 Mon Sep 17 00:00:00 2001 From: Victor Zverovich Date: Sat, 20 Jun 2020 08:50:02 -0700 Subject: [PATCH] Add FMT_COMPILE support to format_to --- include/fmt/compile.h | 14 ++++++++++++-- test/compile-test.cc | 7 +++++++ 2 files changed, 19 insertions(+), 2 deletions(-) diff --git a/include/fmt/compile.h b/include/fmt/compile.h index c85bf7c3..f5f08602 100644 --- a/include/fmt/compile.h +++ b/include/fmt/compile.h @@ -24,7 +24,9 @@ struct is_compiled_string : std::is_base_of {}; #define FMT_COMPILE(s) FMT_STRING_IMPL(s, fmt::detail::compiled_string) template -const T& first(const T& value, const Tail&...) { return value; } +const T& first(const T& value, const Tail&...) { + return value; +} // Part of a compiled format string. It can be either literal text or a // replacement field. @@ -556,7 +558,8 @@ std::basic_string format(const CompiledFormat& cf, const Args&... args) { template ::value)> -FMT_INLINE std::basic_string format(S, Args&&... args) { +FMT_INLINE std::basic_string format(const S&, + Args&&... args) { constexpr basic_string_view str = S(); if (str.size() == 2 && str[0] == '{' && str[1] == '}') return fmt::to_string(detail::first(args...)); @@ -575,6 +578,13 @@ OutputIt format_to(OutputIt out, const CompiledFormat& cf, make_format_args(args...)); } +template ::value)> +OutputIt format_to(OutputIt out, const S&, const Args&... args) { + constexpr auto compiled = compile(S()); + return format_to(out, compiled, args...); +} + template < typename OutputIt, typename CompiledFormat, typename... Args, FMT_ENABLE_IF(detail::is_output_iterator::value&& std::is_base_of< diff --git a/test/compile-test.cc b/test/compile-test.cc index 83f8327c..a3f7322d 100644 --- a/test/compile-test.cc +++ b/test/compile-test.cc @@ -156,6 +156,13 @@ TEST(CompileTest, FormatDefault) { EXPECT_EQ("foo", fmt::format(FMT_COMPILE("{}"), std::string("foo"))); } +TEST(CompileTest, FormatTo) { + char buf[8]; + auto end = fmt::format_to(buf, FMT_COMPILE("{}"), 42); + *end = '\0'; + EXPECT_STREQ("42", buf); +} + TEST(CompileTest, TextAndArg) { EXPECT_EQ(">>>42<<<", fmt::format(FMT_COMPILE(">>>{}<<<"), 42)); }