]> git.proxmox.com Git - ceph.git/blob - ceph/src/seastar/fmt/test/custom-formatter-test.cc
import ceph 14.2.5
[ceph.git] / ceph / src / seastar / 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 #include "fmt/format.h"
9 #include "gtest-extra.h"
10
11 // MSVC 2013 is known to be broken.
12 #if !FMT_MSC_VER || FMT_MSC_VER > 1800
13
14 // A custom argument formatter that doesn't print `-` for floating-point values
15 // rounded to 0.
16 class custom_arg_formatter :
17 public fmt::arg_formatter<fmt::back_insert_range<fmt::internal::buffer>> {
18 public:
19 typedef fmt::back_insert_range<fmt::internal::buffer> range;
20 typedef fmt::arg_formatter<range> base;
21
22 custom_arg_formatter(
23 fmt::format_context &ctx, fmt::format_specs *s = FMT_NULL)
24 : base(ctx, s) {}
25
26 using base::operator();
27
28 iterator operator()(double value) {
29 // Comparing a float to 0.0 is safe.
30 if (round(value * pow(10, spec()->precision)) == 0.0)
31 value = 0;
32 return base::operator()(value);
33 }
34 };
35
36 std::string custom_vformat(fmt::string_view format_str, fmt::format_args args) {
37 fmt::memory_buffer buffer;
38 // Pass custom argument formatter as a template arg to vwrite.
39 fmt::vformat_to<custom_arg_formatter>(buffer, format_str, args);
40 return std::string(buffer.data(), buffer.size());
41 }
42
43 template <typename... Args>
44 std::string custom_format(const char *format_str, const Args & ... args) {
45 auto va = fmt::make_format_args(args...);
46 return custom_vformat(format_str, va);
47 }
48
49 TEST(CustomFormatterTest, Format) {
50 EXPECT_EQ("0.00", custom_format("{:.2f}", -.00001));
51 }
52 #endif