1 /* 2 Custom argument formatter tests 3 4 Copyright (c) 2016, Victor Zverovich 5 All rights reserved. 6 7 For the license information refer to format.h. 8 */ 9 10 #include "fmt/printf.h" 11 #include "gtest-extra.h" 12 13 using fmt::BasicPrintfArgFormatter; 14 15 // A custom argument formatter that doesn't print `-` for floating-point values 16 // rounded to 0. 17 class CustomArgFormatter 18 : public fmt::BasicArgFormatter<CustomArgFormatter, char> { 19 public: 20 CustomArgFormatter(fmt::BasicFormatter<char, CustomArgFormatter> &f, 21 fmt::FormatSpec &s, const char *fmt) 22 : fmt::BasicArgFormatter<CustomArgFormatter, char>(f, s, fmt) {} 23 24 void visit_double(double value) { 25 if (round(value * pow(10, spec().precision())) == 0) 26 value = 0; 27 fmt::BasicArgFormatter<CustomArgFormatter, char>::visit_double(value); 28 } 29 }; 30 31 // A custom argument formatter that doesn't print `-` for floating-point values 32 // rounded to 0. 33 class CustomPrintfArgFormatter : 34 public BasicPrintfArgFormatter<CustomPrintfArgFormatter, char> { 35 public: 36 typedef BasicPrintfArgFormatter<CustomPrintfArgFormatter, char> Base; 37 38 CustomPrintfArgFormatter(fmt::BasicWriter<char> &w, fmt::FormatSpec &spec) 39 : Base(w, spec) {} 40 41 void visit_double(double value) { 42 if (round(value * pow(10, spec().precision())) == 0) 43 value = 0; 44 Base::visit_double(value); 45 } 46 }; 47 48 std::string custom_format(const char *format_str, fmt::ArgList args) { 49 fmt::MemoryWriter writer; 50 // Pass custom argument formatter as a template arg to BasicFormatter. 51 fmt::BasicFormatter<char, CustomArgFormatter> formatter(args, writer); 52 formatter.format(format_str); 53 return writer.str(); 54 } 55 FMT_VARIADIC(std::string, custom_format, const char *) 56 57 std::string custom_sprintf(const char* format_str, fmt::ArgList args){ 58 fmt::MemoryWriter writer; 59 fmt::PrintfFormatter<char, CustomPrintfArgFormatter> formatter(args, writer); 60 formatter.format(format_str); 61 return writer.str(); 62 } 63 FMT_VARIADIC(std::string, custom_sprintf, const char*); 64 65 TEST(CustomFormatterTest, Format) { 66 EXPECT_EQ("0.00", custom_format("{:.2f}", -.00001)); 67 EXPECT_EQ("0.00", custom_sprintf("%.2f", -.00001)); 68 } 69