From 5cf3b6dc7d3b682abd8a16793b2692cc5f6764d1 Mon Sep 17 00:00:00 2001 From: Victor Zverovich Date: Tue, 6 May 2014 08:05:51 -0700 Subject: [PATCH] Add a Print overload that writes to a file. --- format.h | 17 +++++++++++++++-- test/format-test.cc | 19 +++++++++++++++++-- 2 files changed, 32 insertions(+), 4 deletions(-) diff --git a/format.h b/format.h index 1dec4935..41e8f012 100644 --- a/format.h +++ b/format.h @@ -1062,7 +1062,6 @@ class BasicWriter { */ BasicFormatter Format(StringRef format); - // TODO: ArgInfo should be made public for this to be usable inline void VFormat(BasicStringRef format, std::size_t num_args, const ArgInfo *args) { FormatParser().Format(*this, format, num_args, args); @@ -1619,12 +1618,19 @@ class FileSink { // Formats a string and prints it to stdout. // Example: // Print("Elapsed time: {0:.2f} seconds") << 1.23; -// TODO: wchar overload inline Formatter Print(StringRef format) { Formatter f(format, FileSink(stdout)); return f; } +// Formats a string and prints it to a file. +// Example: +// Print(stderr, "Don't {}!") << "panic"; +inline Formatter Print(std::FILE *file, StringRef format) { + Formatter f(format, FileSink(file)); + return f; +} + enum Color { BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE }; /** @@ -1680,6 +1686,13 @@ void Print(StringRef format, const Args & ... args) { std::fwrite(w.data(), 1, w.size(), stdout); } +template +void Print(std::FILE *f, StringRef format, const Args & ... args) { + Writer w; + w.Format(format, args...); + std::fwrite(w.data(), 1, w.size(), f); +} + #endif // FMT_USE_VARIADIC_TEMPLATES && FMT_USE_RVALUE_REFERENCES /** diff --git a/test/format-test.cc b/test/format-test.cc index e6483246..3c4e6c8b 100644 --- a/test/format-test.cc +++ b/test/format-test.cc @@ -1833,6 +1833,20 @@ TEST(FormatIntTest, FormatDec) { #if FMT_USE_FILE_DESCRIPTORS +TEST(FormatTest, Print) { + EXPECT_WRITE(stdout, fmt::Print("Don't {}!") << "panic", "Don't panic!"); + EXPECT_WRITE(stderr, + fmt::Print(stderr, "Don't {}!") << "panic", "Don't panic!"); +} + +#if FMT_USE_VARIADIC_TEMPLATES && FMT_USE_RVALUE_REFERENCES +TEST(FormatTest, PrintVariadic) { + EXPECT_WRITE(stdout, fmt::Print("Don't {}!", "panic"), "Don't panic!"); + EXPECT_WRITE(stderr, + fmt::Print(stderr, "Don't {}!", "panic"), "Don't panic!"); +} +#endif // FMT_USE_VARIADIC_TEMPLATES + TEST(FormatTest, PrintColored) { EXPECT_WRITE(stdout, fmt::PrintColored(fmt::RED, "Hello, {}!\n") << "world", "\x1b[31mHello, world!\n\x1b[0m"); @@ -1842,8 +1856,9 @@ TEST(FormatTest, PrintColored) { #if FMT_USE_VARIADIC_TEMPLATES && FMT_USE_RVALUE_REFERENCES TEST(FormatTest, Variadic) { - EXPECT_EQ("Hello, world!1", str(Format("Hello, {}!{}", "world", 1))); - EXPECT_EQ(L"Hello, world!1", str(Format(L"Hello, {}!{}", L"world", 1))); + EXPECT_EQ("abc1", str(Format("{}c{}", "ab", 1))); + EXPECT_EQ(L"abc1", str(Format(L"{}c{}", L"ab", 1))); + EXPECT_WRITE(stdout, fmt::Print("So {}!", "variadic"), "So variadic!"); } #endif // FMT_USE_VARIADIC_TEMPLATES