From 2a4cd6d05e09c6c4a862695aebe2b765ddcc6194 Mon Sep 17 00:00:00 2001 From: Marek Kurdej Date: Mon, 9 Jul 2018 15:49:44 +0200 Subject: [PATCH] Fix the returned value of `format_to_n` with user-defined types having operator<<. --- include/fmt/ostream.h | 3 +-- test/ostream-test.cc | 22 ++++++++++++++++++++++ 2 files changed, 23 insertions(+), 2 deletions(-) diff --git a/include/fmt/ostream.h b/include/fmt/ostream.h index 94f18834..6673ef81 100644 --- a/include/fmt/ostream.h +++ b/include/fmt/ostream.h @@ -124,8 +124,7 @@ struct formatter buffer; internal::format_value(buffer, value); basic_string_view str(buffer.data(), buffer.size()); - formatter, Char>::format(str, ctx); - return ctx.out(); + return formatter, Char>::format(str, ctx); } }; diff --git a/test/ostream-test.cc b/test/ostream-test.cc index 4d8303d3..3623d7ea 100644 --- a/test/ostream-test.cc +++ b/test/ostream-test.cc @@ -169,3 +169,25 @@ TEST(OStreamTest, ConstexprString) { EXPECT_EQ("42", format(fmt("{}"), std::string("42"))); } #endif + +namespace fmt_test { +struct ABC {}; + +template Output &operator<<(Output &out, ABC) { + out << "ABC"; + return out; +} +} // namespace fmt_test + +TEST(FormatTest, FormatToN) { + char buffer[4]; + buffer[3] = 'x'; + auto result = fmt::format_to_n(buffer, 3, "{}", fmt_test::ABC()); + EXPECT_EQ(3u, result.size); + EXPECT_EQ(buffer + 3, result.out); + EXPECT_EQ("ABCx", fmt::string_view(buffer, 4)); + result = fmt::format_to_n(buffer, 3, "x{}y", fmt_test::ABC()); + EXPECT_EQ(5u, result.size); + EXPECT_EQ(buffer + 3, result.out); + EXPECT_EQ("xABx", fmt::string_view(buffer, 4)); +}