]>
git.proxmox.com Git - ceph.git/blob - ceph/src/fmt/test/custom-formatter-test.cc
1 // Formatting library for C++ - custom argument formatter tests
3 // Copyright (c) 2012 - present, Victor Zverovich
4 // All rights reserved.
6 // For the license information refer to format.h.
8 #ifndef _CRT_SECURE_NO_WARNINGS
9 #define _CRT_SECURE_NO_WARNINGS
12 #include "fmt/format.h"
13 #include "gtest-extra.h"
15 // MSVC 2013 is known to be broken.
16 #if !FMT_MSC_VER || FMT_MSC_VER > 1800
18 // A custom argument formatter that doesn't print `-` for floating-point values
20 class custom_arg_formatter
21 : public fmt::arg_formatter
<fmt::buffer_range
<char>> {
23 using range
= fmt::buffer_range
<char>;
24 typedef fmt::arg_formatter
<range
> base
;
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
) {}
31 using base::operator();
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
);
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());
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
);
53 TEST(CustomFormatterTest
, Format
) {
54 EXPECT_EQ("0.00", custom_format("{:.2f}", -.00001));