fmt/test/custom-formatter-test.cc

82 lines
2.4 KiB
C++
Raw Normal View History

/*
Custom argument formatter tests
Copyright (c) 2016, Victor Zverovich
All rights reserved.
For the license information refer to format.h.
*/
#include "fmt/printf.h"
#include "gtest-extra.h"
using fmt::PrintfArgFormatter;
// A custom argument formatter that doesn't print `-` for floating-point values
// rounded to 0.
class CustomArgFormatter
: public fmt::BasicArgFormatter<CustomArgFormatter, char> {
public:
2016-11-07 03:11:24 +03:00
CustomArgFormatter(fmt::Writer &w, fmt::basic_format_context<char> &ctx,
fmt::FormatSpec &s)
: fmt::BasicArgFormatter<CustomArgFormatter, char>(w, ctx, s) {}
void visit_double(double value) {
if (round(value * pow(10, spec().precision())) == 0)
value = 0;
fmt::BasicArgFormatter<CustomArgFormatter, char>::visit_double(value);
}
};
// A custom argument formatter that doesn't print `-` for floating-point values
// rounded to 0.
class CustomPrintfArgFormatter : public PrintfArgFormatter<char> {
public:
CustomPrintfArgFormatter(fmt::BasicWriter<char> &w, fmt::FormatSpec &spec)
: PrintfArgFormatter<char>(w, spec) {}
using PrintfArgFormatter<char>::operator();
void operator()(double value) {
if (round(value * pow(10, spec().precision())) == 0)
value = 0;
PrintfArgFormatter<char>::operator()(value);
}
};
2016-11-07 03:11:24 +03:00
std::string custom_vformat(fmt::CStringRef format_str, fmt::format_args args) {
fmt::MemoryWriter writer;
// Pass custom argument formatter as a template arg to vformat.
fmt::vformat<CustomArgFormatter>(writer, format_str, args);
return writer.str();
}
2016-08-27 03:23:13 +03:00
template <typename... Args>
std::string custom_format(const char *format_str, const Args & ... args) {
2016-11-07 06:27:14 +03:00
auto va = fmt::make_format_args(args...);
2016-08-27 17:57:48 +03:00
return custom_vformat(format_str, va);
2016-08-27 03:23:13 +03:00
}
2016-11-07 03:11:24 +03:00
typedef fmt::printf_context<char, CustomPrintfArgFormatter>
CustomPrintfFormatter;
std::string custom_vsprintf(
const char* format_str,
fmt::basic_format_args<CustomPrintfFormatter> args) {
fmt::MemoryWriter writer;
2016-11-07 03:11:24 +03:00
CustomPrintfFormatter formatter(format_str, args);
formatter.format(writer);
return writer.str();
}
2016-08-27 03:23:13 +03:00
template <typename... Args>
std::string custom_sprintf(const char *format_str, const Args & ... args) {
2016-11-07 06:27:14 +03:00
auto va = fmt::make_xformat_args<CustomPrintfFormatter>(args...);
2016-08-27 17:57:48 +03:00
return custom_vsprintf(format_str, va);
2016-08-27 03:23:13 +03:00
}
TEST(CustomFormatterTest, Format) {
EXPECT_EQ("0.00", custom_format("{:.2f}", -.00001));
EXPECT_EQ("0.00", custom_sprintf("%.2f", -.00001));
}