Skip to content

Commit

Permalink
Support compile-time format string compilation (module)
Browse files Browse the repository at this point in the history
  • Loading branch information
DanielaE committed Jun 10, 2021
1 parent d8cdb02 commit 8f45f23
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 10 deletions.
20 changes: 10 additions & 10 deletions include/fmt/compile.h
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -137,11 +142,8 @@ class truncating_iterator<OutputIt, std::true_type>
truncating_iterator& operator*() { return *this; }
};

// A compile-time string which is compiled into fast formatting code.
class compiled_string {};

template <typename S>
struct is_compiled_string : std::is_base_of<compiled_string, S> {};
struct is_compiled_string : std::is_base_of<fmt::compiled_string, S> {};

/**
\rst
Expand All @@ -157,15 +159,14 @@ struct is_compiled_string : std::is_base_of<compiled_string, S> {};
\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 <typename Char, size_t N, fmt::ct::str<Char, N> Str>
struct udl_compiled_string : compiled_string {
struct udl_compiled_string : fmt::compiled_string {
using char_type = Char;
constexpr operator basic_string_view<char_type>() const {
return {Str.data, N - 1};
Expand Down Expand Up @@ -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

Expand Down
8 changes: 8 additions & 0 deletions test/module-test.cc
Original file line number Diff line number Diff line change
Expand Up @@ -555,3 +555,11 @@ TEST(module_test, has_formatter) {
TEST(module_test, is_formattable) {
EXPECT_FALSE(fmt::is_formattable<disabled_formatter>::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"));
}

0 comments on commit 8f45f23

Please sign in to comment.