]> git.proxmox.com Git - ceph.git/blob - ceph/src/fmt/test/custom-formatter-test.cc
buildsys: switch source download to quincy
[ceph.git] / ceph / src / fmt / test / custom-formatter-test.cc
1 // Formatting library for C++ - custom argument formatter tests
2 //
3 // Copyright (c) 2012 - present, Victor Zverovich
4 // All rights reserved.
5 //
6 // For the license information refer to format.h.
7
8 #ifndef _CRT_SECURE_NO_WARNINGS
9 #define _CRT_SECURE_NO_WARNINGS
10 #endif
11
12 #include "fmt/format.h"
13 #include "gtest-extra.h"
14
15 // MSVC 2013 is known to be broken.
16 #if !FMT_MSC_VER || FMT_MSC_VER > 1800
17
18 // A custom argument formatter that doesn't print `-` for floating-point values
19 // rounded to 0.
20 class custom_arg_formatter
21 : public fmt::arg_formatter<fmt::buffer_range<char>> {
22 public:
23 using range = fmt::buffer_range<char>;
24 typedef fmt::arg_formatter<range> base;
25
26 custom_arg_formatter(fmt::format_context& ctx,
27 fmt::format_parse_context* parse_ctx,
28 fmt::format_specs* s = nullptr)
29 : base(ctx, parse_ctx, s) {}
30
31 using base::operator();
32
33 iterator operator()(double value) {
34 // Comparing a float to 0.0 is safe.
35 if (round(value * pow(10, specs()->precision)) == 0.0) value = 0;
36 return base::operator()(value);
37 }
38 };
39
40 std::string custom_vformat(fmt::string_view format_str, fmt::format_args args) {
41 fmt::memory_buffer buffer;
42 // Pass custom argument formatter as a template arg to vwrite.
43 fmt::vformat_to<custom_arg_formatter>(buffer, format_str, args);
44 return std::string(buffer.data(), buffer.size());
45 }
46
47 template <typename... Args>
48 std::string custom_format(const char* format_str, const Args&... args) {
49 auto va = fmt::make_format_args(args...);
50 return custom_vformat(format_str, va);
51 }
52
53 TEST(CustomFormatterTest, Format) {
54 EXPECT_EQ("0.00", custom_format("{:.2f}", -.00001));
55 }
56 #endif