From 8f45f23be0c97624e72a5713458a0dfe704fb46b Mon Sep 17 00:00:00 2001 From: Daniela Engert Date: Fri, 4 Jun 2021 17:29:22 +0200 Subject: [PATCH] Support compile-time format string compilation (module) --- include/fmt/compile.h | 20 ++++++++++---------- test/module-test.cc | 8 ++++++++ 2 files changed, 18 insertions(+), 10 deletions(-) diff --git a/include/fmt/compile.h b/include/fmt/compile.h index 003be9e78414b..0be0b7720cf55 100644 --- a/include/fmt/compile.h +++ b/include/fmt/compile.h @@ -11,7 +11,12 @@ #include "format.h" FMT_BEGIN_NAMESPACE -namespace detail { +FMT_MODULE_EXPORT_BEGIN + +// A compile-time string which is compiled into fast formatting code. +class compiled_string {}; + +FMT_BEGIN_DETAIL_NAMESPACE // An output iterator that counts the number of objects written to it and // discards them. @@ -137,11 +142,8 @@ class truncating_iterator truncating_iterator& operator*() { return *this; } }; -// A compile-time string which is compiled into fast formatting code. -class compiled_string {}; - template -struct is_compiled_string : std::is_base_of {}; +struct is_compiled_string : std::is_base_of {}; /** \rst @@ -157,15 +159,14 @@ struct is_compiled_string : std::is_base_of {}; \endrst */ #ifdef __cpp_if_constexpr -# define FMT_COMPILE(s) \ - FMT_STRING_IMPL(s, fmt::detail::compiled_string, explicit) +# define FMT_COMPILE(s) FMT_STRING_IMPL(s, fmt::compiled_string, explicit) #else # define FMT_COMPILE(s) FMT_STRING(s) #endif #if FMT_USE_NONTYPE_TEMPLATE_PARAMETERS template Str> -struct udl_compiled_string : compiled_string { +struct udl_compiled_string : fmt::compiled_string { using char_type = Char; constexpr operator basic_string_view() const { return {Str.data, N - 1}; @@ -527,9 +528,8 @@ constexpr auto compile(S format_str) { } } #endif // __cpp_if_constexpr -} // namespace detail -FMT_MODULE_EXPORT_BEGIN +FMT_END_DETAIL_NAMESPACE #ifdef __cpp_if_constexpr diff --git a/test/module-test.cc b/test/module-test.cc index fee0e12eeae49..69b6099a7b97f 100644 --- a/test/module-test.cc +++ b/test/module-test.cc @@ -555,3 +555,11 @@ TEST(module_test, has_formatter) { TEST(module_test, is_formattable) { EXPECT_FALSE(fmt::is_formattable::value); } + +TEST(module_test, compile_format_string) { + using namespace fmt::literals; + EXPECT_EQ("42", fmt::format("{0:x}"_cf, 0x42)); + EXPECT_EQ(L"42", fmt::format(L"{:}"_cf, 42)); + EXPECT_EQ("4.2", fmt::format("{arg:3.1f}"_cf, "arg"_a = 4.2)); + EXPECT_EQ(L" 42", fmt::format(L"{arg:>3}"_cf, L"arg"_a = L"42")); +}