]> git.proxmox.com Git - ceph.git/blame - ceph/src/fmt/test/custom-formatter-test.cc
buildsys: switch source download to quincy
[ceph.git] / ceph / src / fmt / test / custom-formatter-test.cc
CommitLineData
11fdf7f2
TL
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
f67539c2
TL
8#ifndef _CRT_SECURE_NO_WARNINGS
9#define _CRT_SECURE_NO_WARNINGS
10#endif
11
11fdf7f2
TL
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.
9f95a23c 20class custom_arg_formatter
f67539c2 21 : public fmt::arg_formatter<fmt::buffer_range<char>> {
11fdf7f2 22 public:
f67539c2 23 using range = fmt::buffer_range<char>;
11fdf7f2
TL
24 typedef fmt::arg_formatter<range> base;
25
9f95a23c
TL
26 custom_arg_formatter(fmt::format_context& ctx,
27 fmt::format_parse_context* parse_ctx,
f67539c2 28 fmt::format_specs* s = nullptr)
9f95a23c 29 : base(ctx, parse_ctx, s) {}
11fdf7f2
TL
30
31 using base::operator();
32
33 iterator operator()(double value) {
eafe8130 34 // Comparing a float to 0.0 is safe.
f67539c2 35 if (round(value * pow(10, specs()->precision)) == 0.0) value = 0;
11fdf7f2
TL
36 return base::operator()(value);
37 }
38};
39
40std::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
47template <typename... Args>
9f95a23c 48std::string custom_format(const char* format_str, const Args&... args) {
11fdf7f2
TL
49 auto va = fmt::make_format_args(args...);
50 return custom_vformat(format_str, va);
51}
52
53TEST(CustomFormatterTest, Format) {
54 EXPECT_EQ("0.00", custom_format("{:.2f}", -.00001));
55}
56#endif