diff --git a/include/fmt/ranges.h b/include/fmt/ranges.h index 8b7c9aad27e1..7b358b710dda 100644 --- a/include/fmt/ranges.h +++ b/include/fmt/ranges.h @@ -428,6 +428,7 @@ struct formatter< detail::range_formatter_type>; formatter_type underlying_; bool custom_specs_ = false; + bool no_brackets_ = false; template FMT_CONSTEXPR auto parse(ParseContext& ctx) -> decltype(ctx.begin()) { @@ -435,8 +436,13 @@ struct formatter< auto end = ctx.end(); if (it == end || *it == '}') return it; + if (*it == 'n') { + no_brackets_ = true; + ++it; + } + if (*it != ':') - FMT_THROW(format_error("no top-level range formatters supported")); + FMT_THROW(format_error("no other top-level range formatters supported")); custom_specs_ = true; ++it; @@ -451,7 +457,7 @@ struct formatter< Char postfix = detail::is_set::value ? '}' : ']'; detail::range_mapper> mapper; auto out = ctx.out(); - *out++ = prefix; + if (!no_brackets_) *out++ = prefix; int i = 0; auto it = detail::range_begin(range); auto end = detail::range_end(range); @@ -465,7 +471,7 @@ struct formatter< } ++i; } - *out++ = postfix; + if (!no_brackets_) *out++ = postfix; return out; } }; diff --git a/test/ranges-test.cc b/test/ranges-test.cc index 0804996ffa60..0c39b3843be5 100644 --- a/test/ranges-test.cc +++ b/test/ranges-test.cc @@ -47,12 +47,14 @@ TEST(ranges_test, format_vector) { auto v = std::vector{1, 2, 3, 5, 7, 11}; EXPECT_EQ(fmt::format("{}", v), "[1, 2, 3, 5, 7, 11]"); EXPECT_EQ(fmt::format("{::#x}", v), "[0x1, 0x2, 0x3, 0x5, 0x7, 0xb]"); + EXPECT_EQ(fmt::format("{:n:#x}", v), "0x1, 0x2, 0x3, 0x5, 0x7, 0xb"); } TEST(ranges_test, format_vector2) { auto v = std::vector>{{1, 2}, {3, 5}, {7, 11}}; EXPECT_EQ(fmt::format("{}", v), "[[1, 2], [3, 5], [7, 11]]"); EXPECT_EQ(fmt::format("{:::#x}", v), "[[0x1, 0x2], [0x3, 0x5], [0x7, 0xb]]"); + EXPECT_EQ(fmt::format("{:n:n:#x}", v), "0x1, 0x2, 0x3, 0x5, 0x7, 0xb"); } TEST(ranges_test, format_map) {