]> git.proxmox.com Git - ceph.git/blob - ceph/src/seastar/fmt/doc/api.rst
update sources to ceph Nautilus 14.2.1
[ceph.git] / ceph / src / seastar / fmt / doc / api.rst
1 .. _string-formatting-api:
2
3 *************
4 API Reference
5 *************
6
7 The {fmt} library API consists of the following parts:
8
9 * :ref:`fmt/core.h <core-api>`: the core API providing argument handling
10 facilities and a lightweight subset of formatting functions
11 * :ref:`fmt/format.h <format-api>`: the full format API providing compile-time
12 format string checks, output iterator and user-defined type support
13 * :ref:`fmt/time.h <time-api>`: date and time formatting
14 * :ref:`fmt/ostream.h <ostream-api>`: ``std::ostream`` support
15 * :ref:`fmt/printf.h <printf-api>`: ``printf`` formatting
16
17 All functions and types provided by the library reside in namespace ``fmt`` and
18 macros have prefix ``FMT_`` or ``fmt``.
19
20 .. _core-api:
21
22 Core API
23 ========
24
25 ``fmt/core.h`` defines the core API which provides argument handling facilities
26 and a lightweight subset of formatting functions.
27
28 The following functions use :ref:`format string syntax <syntax>`
29 imilar to that of Python's `str.format
30 <http://docs.python.org/3/library/stdtypes.html#str.format>`_.
31 They take *format_str* and *args* as arguments.
32
33 *format_str* is a format string that contains literal text and replacement
34 fields surrounded by braces ``{}``. The fields are replaced with formatted
35 arguments in the resulting string.
36
37 *args* is an argument list representing objects to be formatted.
38
39 .. _format:
40
41 .. doxygenfunction:: format(const String&, const Args&...)
42 .. doxygenfunction:: vformat(const String&, basic_format_args<typename buffer_context<Char>::type>)
43
44 .. _print:
45
46 .. doxygenfunction:: print(string_view, const Args&...)
47 .. doxygenfunction:: vprint(string_view, format_args)
48
49 .. doxygenfunction:: print(std::FILE *, string_view, const Args&...)
50 .. doxygenfunction:: vprint(std::FILE *, string_view, format_args)
51
52 .. doxygenfunction:: print(std::FILE *, wstring_view, const Args&...)
53 .. doxygenfunction:: vprint(std::FILE *, wstring_view, wformat_args)
54
55 Named arguments
56 ---------------
57
58 .. doxygenfunction:: fmt::arg(string_view, const T&)
59
60 Argument lists
61 --------------
62
63 .. doxygenfunction:: fmt::make_format_args(const Args&...)
64
65 .. doxygenclass:: fmt::format_arg_store
66 :members:
67
68 .. doxygenclass:: fmt::basic_format_args
69 :members:
70
71 .. doxygenstruct:: fmt::format_args
72
73 .. doxygenclass:: fmt::basic_format_arg
74 :members:
75
76 Compatibility
77 -------------
78
79 .. doxygenclass:: fmt::basic_string_view
80 :members:
81
82 .. doxygentypedef:: fmt::string_view
83 .. doxygentypedef:: fmt::wstring_view
84
85 .. _format-api:
86
87 Format API
88 ==========
89
90 ``fmt/format.h`` defines the full format API providing compile-time format
91 string checks, output iterator and user-defined type support.
92
93 Compile-time format string checks
94 ---------------------------------
95
96 .. doxygendefine:: fmt
97
98 Formatting user-defined types
99 -----------------------------
100
101 To make a user-defined type formattable, specialize the ``formatter<T>`` struct
102 template and implement ``parse`` and ``format`` methods::
103
104 #include <fmt/format.h>
105
106 struct point { double x, y; };
107
108 namespace fmt {
109 template <>
110 struct formatter<point> {
111 template <typename ParseContext>
112 constexpr auto parse(ParseContext &ctx) { return ctx.begin(); }
113
114 template <typename FormatContext>
115 auto format(const point &p, FormatContext &ctx) {
116 return format_to(ctx.begin(), "({:.1f}, {:.1f})", p.x, p.y);
117 }
118 };
119 }
120
121 Then you can pass objects of type ``point`` to any formatting function::
122
123 point p = {1, 2};
124 std::string s = fmt::format("{}", p);
125 // s == "(1.0, 2.0)"
126
127 In the example above the ``formatter<point>::parse`` function ignores the
128 contents of the format string referred to by ``ctx.begin()`` so the object will
129 always be formatted in the same way. See ``formatter<tm>::parse`` in
130 :file:`fmt/time.h` for an advanced example of how to parse the format string and
131 customize the formatted output.
132
133 You can also reuse existing formatters, for example::
134
135 enum class color {red, green, blue};
136
137 template <>
138 struct fmt::formatter<color>: formatter<string_view> {
139 // parse is inherited from formatter<string_view>.
140 template <typename FormatContext>
141 auto format(color c, FormatContext &ctx) {
142 string_view name = "unknown";
143 switch (c) {
144 case color::red: name = "red"; break;
145 case color::green: name = "green"; break;
146 case color::blue: name = "blue"; break;
147 }
148 return formatter<string_view>::format(name, ctx);
149 }
150 };
151
152 This section shows how to define a custom format function for a user-defined
153 type. The next section describes how to get ``fmt`` to use a conventional stream
154 output ``operator<<`` when one is defined for a user-defined type.
155
156 Output iterator support
157 -----------------------
158
159 .. doxygenfunction:: fmt::format_to(OutputIt, string_view, const Args&...)
160 .. doxygenfunction:: fmt::format_to_n(OutputIt, std::size_t, string_view, const Args&...)
161 .. doxygenstruct:: fmt::format_to_n_result
162 :members:
163
164 Literal-based API
165 -----------------
166
167 The following user-defined literals are defined in ``fmt/format.h``.
168
169 .. doxygenfunction:: operator""_format(const char *, std::size_t)
170
171 .. doxygenfunction:: operator""_a(const char *, std::size_t)
172
173 Utilities
174 ---------
175
176 .. doxygenfunction:: fmt::formatted_size(string_view, const Args&...)
177
178 .. doxygenfunction:: fmt::to_string(const T&)
179
180 .. doxygenfunction:: fmt::to_wstring(const T&)
181
182 .. doxygenclass:: fmt::basic_memory_buffer
183 :protected-members:
184 :members:
185
186 System errors
187 -------------
188
189 fmt does not use ``errno`` to communicate errors to the user, but it may call
190 system functions which set ``errno``. Users should not make any assumptions about
191 the value of ``errno`` being preserved by library functions.
192
193 .. doxygenclass:: fmt::system_error
194 :members:
195
196 .. doxygenfunction:: fmt::format_system_error
197
198 .. doxygenclass:: fmt::windows_error
199 :members:
200
201 .. _formatstrings:
202
203 Custom allocators
204 -----------------
205
206 The {fmt} library supports custom dynamic memory allocators.
207 A custom allocator class can be specified as a template argument to
208 :class:`fmt::basic_memory_buffer`::
209
210 using custom_memory_buffer =
211 fmt::basic_memory_buffer<char, fmt::inline_buffer_size, custom_allocator>;
212
213 It is also possible to write a formatting function that uses a custom
214 allocator::
215
216 using custom_string =
217 std::basic_string<char, std::char_traits<char>, custom_allocator>;
218
219 custom_string vformat(custom_allocator alloc, fmt::string_view format_str,
220 fmt::format_args args) {
221 custom_memory_buffer buf(alloc);
222 fmt::vformat_to(buf, format_str, args);
223 return custom_string(buf.data(), buf.size(), alloc);
224 }
225
226 template <typename ...Args>
227 inline custom_string format(custom_allocator alloc,
228 fmt::string_view format_str,
229 const Args & ... args) {
230 return vformat(alloc, format_str, fmt::make_format_args(args...));
231 }
232
233 The allocator will be used for the output container only. If you are using named
234 arguments, the container that stores pointers to them will be allocated using
235 the default allocator. Also floating-point formatting falls back on ``sprintf``
236 which may do allocations.
237
238 Custom formatting of built-in types
239 -----------------------------------
240
241 It is possible to change the way arguments are formatted by providing a
242 custom argument formatter class::
243
244 using arg_formatter =
245 fmt::arg_formatter<fmt::back_insert_range<fmt::internal::buffer>>;
246
247 // A custom argument formatter that formats negative integers as unsigned
248 // with the ``x`` format specifier.
249 class custom_arg_formatter : public arg_formatter {
250 public:
251 custom_arg_formatter(fmt::format_context &ctx, fmt::format_specs &spec)
252 : arg_formatter(ctx, spec) {}
253
254 using arg_formatter::operator();
255
256 auto operator()(int value) {
257 if (spec().type() == 'x')
258 return (*this)(static_cast<unsigned>(value)); // convert to unsigned and format
259 return arg_formatter::operator()(value);
260 }
261 };
262
263 std::string custom_vformat(fmt::string_view format_str, fmt::format_args args) {
264 fmt::memory_buffer buffer;
265 // Pass custom argument formatter as a template arg to vformat_to.
266 fmt::vformat_to<custom_arg_formatter>(buffer, format_str, args);
267 return fmt::to_string(buffer);
268 }
269
270 template <typename ...Args>
271 inline std::string custom_format(
272 fmt::string_view format_str, const Args &... args) {
273 return custom_vformat(format_str, fmt::make_format_args(args...));
274 }
275
276 std::string s = custom_format("{:x}", -42); // s == "ffffffd6"
277
278 .. doxygenclass:: fmt::arg_formatter
279 :members:
280
281 .. _time-api:
282
283 Date and time formatting
284 ========================
285
286 The library supports `strftime
287 <http://en.cppreference.com/w/cpp/chrono/c/strftime>`_-like date and time
288 formatting::
289
290 #include <fmt/time.h>
291
292 std::time_t t = std::time(nullptr);
293 // Prints "The date is 2016-04-29." (with the current date)
294 fmt::print("The date is {:%Y-%m-%d}.", *std::localtime(&t));
295
296 The format string syntax is described in the documentation of
297 `strftime <http://en.cppreference.com/w/cpp/chrono/c/strftime>`_.
298
299 .. _ostream-api:
300
301 ``std::ostream`` support
302 ========================
303
304 ``fmt/ostream.h`` provides ``std::ostream`` support including formatting of
305 user-defined types that have overloaded ``operator<<``::
306
307 #include <fmt/ostream.h>
308
309 class date {
310 int year_, month_, day_;
311 public:
312 date(int year, int month, int day): year_(year), month_(month), day_(day) {}
313
314 friend std::ostream &operator<<(std::ostream &os, const date &d) {
315 return os << d.year_ << '-' << d.month_ << '-' << d.day_;
316 }
317 };
318
319 std::string s = fmt::format("The date is {}", date(2012, 12, 9));
320 // s == "The date is 2012-12-9"
321
322 .. doxygenfunction:: print(std::ostream&, string_view, const Args&...)
323
324 .. _printf-api:
325
326 ``printf`` formatting
327 =====================
328
329 The header ``fmt/printf.h`` provides ``printf``-like formatting functionality.
330 The following functions use `printf format string syntax
331 <http://pubs.opengroup.org/onlinepubs/009695399/functions/fprintf.html>`_ with
332 the POSIX extension for positional arguments. Unlike their standard
333 counterparts, the ``fmt`` functions are type-safe and throw an exception if an
334 argument type doesn't match its format specification.
335
336 .. doxygenfunction:: printf(string_view, const Args&...)
337
338 .. doxygenfunction:: fprintf(std::FILE *, string_view, const Args&...)
339
340 .. doxygenfunction:: fprintf(std::ostream&, string_view, const Args&...)
341
342 .. doxygenfunction:: sprintf(string_view, const Args&...)