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