]> git.proxmox.com Git - ceph.git/blame - ceph/src/fmt/doc/api.rst
import quincy beta 17.1.0
[ceph.git] / ceph / src / fmt / doc / api.rst
CommitLineData
11fdf7f2
TL
1.. _string-formatting-api:
2
3*************
4API Reference
5*************
6
7The {fmt} library API consists of the following parts:
8
20effc67
TL
9* :ref:`fmt/core.h <core-api>`: the core API providing main formatting functions
10 for ``char``/UTF-8 with compile-time checks and minimal dependencies
11* :ref:`fmt/format.h <format-api>`: the full format API providing additional
12 formatting functions and locale support
13* :ref:`fmt/ranges.h <ranges-api>`: formatting of ranges and tuples
f67539c2 14* :ref:`fmt/chrono.h <chrono-api>`: date and time formatting
20effc67
TL
15* :ref:`fmt/compile.h <compile-api>`: format string compilation
16* :ref:`fmt/color.h <color-api>`: terminal color and text style
17* :ref:`fmt/os.h <os-api>`: system APIs
11fdf7f2
TL
18* :ref:`fmt/ostream.h <ostream-api>`: ``std::ostream`` support
19* :ref:`fmt/printf.h <printf-api>`: ``printf`` formatting
20effc67 20* :ref:`fmt/xchar.h <xchar-api>`: optional ``wchar_t`` support
11fdf7f2
TL
21
22All functions and types provided by the library reside in namespace ``fmt`` and
f67539c2 23macros have prefix ``FMT_``.
11fdf7f2
TL
24
25.. _core-api:
26
27Core API
28========
29
20effc67
TL
30``fmt/core.h`` defines the core API which provides main formatting functions for
31``char``/UTF-8 with compile-time checks. It has minimal include dependencies for
32better compile times. This header is only beneficial when using {fmt} as a
33library and not in the header-only mode.
11fdf7f2
TL
34
35The following functions use :ref:`format string syntax <syntax>`
eafe8130 36similar to that of Python's `str.format
20effc67
TL
37<https://docs.python.org/3/library/stdtypes.html#str.format>`_.
38They take *fmt* and *args* as arguments.
11fdf7f2 39
20effc67 40*fmt* is a format string that contains literal text and replacement
11fdf7f2 41fields surrounded by braces ``{}``. The fields are replaced with formatted
20effc67 42arguments in the resulting string. A function taking *fmt* doesn't
eafe8130 43participate in an overload resolution if the latter is not a string.
11fdf7f2
TL
44
45*args* is an argument list representing objects to be formatted.
46
47.. _format:
48
20effc67
TL
49.. doxygenfunction:: format(format_string<T...> fmt, T&&... args) -> std::string
50.. doxygenfunction:: vformat(string_view fmt, format_args args) -> std::string
51
52.. doxygenfunction:: format_to(OutputIt out, format_string<T...> fmt, T&&... args) -> OutputIt
53.. doxygenfunction:: format_to_n(OutputIt out, size_t n, format_string<T...> fmt, const T&... args) -> format_to_n_result<OutputIt>
54.. doxygenfunction:: formatted_size(format_string<T...> fmt, T&&... args) -> size_t
55
56.. doxygenstruct:: fmt::format_to_n_result
57 :members:
11fdf7f2
TL
58
59.. _print:
60
20effc67
TL
61.. doxygenfunction:: fmt::print(format_string<T...> fmt, T&&... args)
62.. doxygenfunction:: vprint(string_view fmt, format_args args)
11fdf7f2 63
20effc67
TL
64.. doxygenfunction:: print(std::FILE *f, format_string<T...> fmt, T&&... args)
65.. doxygenfunction:: vprint(std::FILE *f, string_view fmt, format_args args)
66
67Compile-time Format String Checks
68---------------------------------
69
70Compile-time checks are enabled when using ``FMT_STRING``. They support built-in
71and string types as well as user-defined types with ``constexpr`` ``parse``
72functions in their ``formatter`` specializations.
73
74.. doxygendefine:: FMT_STRING
75
76To force the use of compile-time checks, define the preprocessor variable
77``FMT_ENFORCE_COMPILE_STRING``. When set, functions accepting ``FMT_STRING``
78will fail to compile with regular strings. Runtime-checked
79formatting is still possible using ``fmt::vformat``, ``fmt::vprint``, etc.
11fdf7f2 80
f67539c2 81Named Arguments
11fdf7f2
TL
82---------------
83
9f95a23c
TL
84.. doxygenfunction:: fmt::arg(const S&, const T&)
85
86Named arguments are not supported in compile-time checks at the moment.
11fdf7f2 87
f67539c2 88Argument Lists
11fdf7f2
TL
89--------------
90
20effc67
TL
91You can create your own formatting function with compile-time checks and small
92binary footprint, for example (https://godbolt.org/z/oba4Mc):
93
94.. code:: c++
95
96 #include <fmt/format.h>
97
98 void vlog(const char* file, int line, fmt::string_view format,
99 fmt::format_args args) {
100 fmt::print("{}: {}: ", file, line);
101 fmt::vprint(format, args);
102 }
103
104 template <typename S, typename... Args>
105 void log(const char* file, int line, const S& format, Args&&... args) {
106 vlog(file, line, format,
107 fmt::make_args_checked<Args...>(format, args...));
108 }
109
110 #define MY_LOG(format, ...) \
111 log(__FILE__, __LINE__, FMT_STRING(format), __VA_ARGS__)
112
113 MY_LOG("invalid squishiness: {}", 42);
114
115Note that ``vlog`` is not parameterized on argument types which improves compile
116times and reduces binary code size compared to a fully parameterized version.
117
118.. doxygenfunction:: fmt::make_args_checked(const S&, const remove_reference_t<Args>&...)
119
11fdf7f2
TL
120.. doxygenfunction:: fmt::make_format_args(const Args&...)
121
122.. doxygenclass:: fmt::format_arg_store
123 :members:
124
f67539c2
TL
125.. doxygenclass:: fmt::dynamic_format_arg_store
126 :members:
127
11fdf7f2
TL
128.. doxygenclass:: fmt::basic_format_args
129 :members:
130
131.. doxygenstruct:: fmt::format_args
132
133.. doxygenclass:: fmt::basic_format_arg
134 :members:
135
20effc67
TL
136.. doxygenclass:: fmt::basic_format_context
137 :members:
138
139.. doxygentypedef:: fmt::format_context
140
11fdf7f2
TL
141Compatibility
142-------------
143
144.. doxygenclass:: fmt::basic_string_view
145 :members:
146
147.. doxygentypedef:: fmt::string_view
11fdf7f2 148
f67539c2
TL
149Locale
150------
151
20effc67 152All formatting is locale-independent by default. Use the ``'L'`` format
f67539c2
TL
153specifier to insert the appropriate number separator characters from the
154locale::
155
156 #include <fmt/core.h>
157 #include <locale>
158
159 std::locale::global(std::locale("en_US.UTF-8"));
160 auto s = fmt::format("{:L}", 1000000); // s == "1,000,000"
161
11fdf7f2
TL
162.. _format-api:
163
164Format API
165==========
166
20effc67
TL
167``fmt/format.h`` defines the full format API providing additional formatting
168functions and locale support.
f67539c2 169
20effc67 170.. _udt:
11fdf7f2 171
f67539c2 172Formatting User-defined Types
11fdf7f2
TL
173-----------------------------
174
175To make a user-defined type formattable, specialize the ``formatter<T>`` struct
176template and implement ``parse`` and ``format`` methods::
177
178 #include <fmt/format.h>
179
180 struct point { double x, y; };
181
20effc67 182 template <> struct fmt::formatter<point> {
f67539c2
TL
183 // Presentation format: 'f' - fixed, 'e' - exponential.
184 char presentation = 'f';
185
186 // Parses format specifications of the form ['f' | 'e'].
20effc67 187 constexpr auto parse(format_parse_context& ctx) -> decltype(ctx.begin()) {
f67539c2
TL
188 // [ctx.begin(), ctx.end()) is a character range that contains a part of
189 // the format string starting from the format specifications to be parsed,
190 // e.g. in
191 //
192 // fmt::format("{:f} - point of interest", point{1, 2});
193 //
194 // the range will contain "f} - point of interest". The formatter should
195 // parse specifiers until '}' or the end of the range. In this example
196 // the formatter should parse the 'f' specifier and return an iterator
197 // pointing to '}'.
198
199 // Parse the presentation format and store it in the formatter:
200 auto it = ctx.begin(), end = ctx.end();
201 if (it != end && (*it == 'f' || *it == 'e')) presentation = *it++;
202
203 // Check if reached the end of the range:
204 if (it != end && *it != '}')
205 throw format_error("invalid format");
206
207 // Return an iterator past the end of the parsed range:
208 return it;
209 }
11fdf7f2 210
f67539c2
TL
211 // Formats the point p using the parsed format specification (presentation)
212 // stored in this formatter.
11fdf7f2 213 template <typename FormatContext>
20effc67 214 auto format(const point& p, FormatContext& ctx) -> decltype(ctx.out()) {
f67539c2
TL
215 // ctx.out() is an output iterator to write to.
216 return format_to(
217 ctx.out(),
218 presentation == 'f' ? "({:.1f}, {:.1f})" : "({:.1e}, {:.1e})",
219 p.x, p.y);
11fdf7f2
TL
220 }
221 };
11fdf7f2
TL
222
223Then you can pass objects of type ``point`` to any formatting function::
224
225 point p = {1, 2};
f67539c2 226 std::string s = fmt::format("{:f}", p);
11fdf7f2
TL
227 // s == "(1.0, 2.0)"
228
f67539c2
TL
229You can also reuse existing formatters via inheritance or composition, for
230example::
11fdf7f2
TL
231
232 enum class color {red, green, blue};
233
f67539c2 234 template <> struct fmt::formatter<color>: formatter<string_view> {
11fdf7f2
TL
235 // parse is inherited from formatter<string_view>.
236 template <typename FormatContext>
f67539c2 237 auto format(color c, FormatContext& ctx) {
11fdf7f2
TL
238 string_view name = "unknown";
239 switch (c) {
240 case color::red: name = "red"; break;
241 case color::green: name = "green"; break;
242 case color::blue: name = "blue"; break;
243 }
244 return formatter<string_view>::format(name, ctx);
245 }
246 };
247
f67539c2
TL
248Since ``parse`` is inherited from ``formatter<string_view>`` it will recognize
249all string format specifications, for example
250
251.. code-block:: c++
252
253 fmt::format("{:>10}", color::blue)
254
255will return ``" blue"``.
256
eafe8130
TL
257You can also write a formatter for a hierarchy of classes::
258
259 #include <type_traits>
260 #include <fmt/format.h>
261
262 struct A {
263 virtual ~A() {}
264 virtual std::string name() const { return "A"; }
265 };
266
267 struct B : A {
268 virtual std::string name() const { return "B"; }
269 };
270
271 template <typename T>
272 struct fmt::formatter<T, std::enable_if_t<std::is_base_of<A, T>::value, char>> :
273 fmt::formatter<std::string> {
274 template <typename FormatCtx>
275 auto format(const A& a, FormatCtx& ctx) {
276 return fmt::formatter<std::string>::format(a.name(), ctx);
277 }
278 };
279
280 int main() {
281 B b;
282 A& a = b;
283 fmt::print("{}", a); // prints "B"
284 }
285
20effc67
TL
286If a type provides both a ``formatter`` specialization and an implicit
287conversion to a formattable type, the specialization takes precedence over the
288conversion.
11fdf7f2 289
20effc67 290.. doxygenclass:: fmt::basic_format_parse_context
11fdf7f2
TL
291 :members:
292
293Literal-based API
294-----------------
295
296The following user-defined literals are defined in ``fmt/format.h``.
297
20effc67 298.. doxygenfunction:: operator""_format(const char *s, size_t n) -> detail::udl_formatter<char>
11fdf7f2 299
20effc67 300.. doxygenfunction:: operator""_a(const char *s, size_t) -> detail::udl_arg<char>
11fdf7f2
TL
301
302Utilities
303---------
304
20effc67
TL
305.. doxygenfunction:: fmt::ptr(T p) -> const void*
306.. doxygenfunction:: fmt::ptr(const std::unique_ptr<T> &p) -> const void*
307.. doxygenfunction:: fmt::ptr(const std::shared_ptr<T> &p) -> const void*
11fdf7f2 308
20effc67 309.. doxygenfunction:: fmt::to_string(const T &value) -> std::string
11fdf7f2 310
20effc67 311.. doxygenfunction:: fmt::to_string_view(const Char *s) -> basic_string_view<Char>
f67539c2 312
20effc67 313.. doxygenfunction:: fmt::join(Range &&range, string_view sep) -> join_view<detail::iterator_t<Range>, detail::sentinel_t<Range>>
f67539c2 314
20effc67 315.. doxygenfunction:: fmt::join(It begin, Sentinel end, string_view sep) -> join_view<It, Sentinel>
f67539c2
TL
316
317.. doxygenclass:: fmt::detail::buffer
318 :members:
9f95a23c 319
11fdf7f2
TL
320.. doxygenclass:: fmt::basic_memory_buffer
321 :protected-members:
322 :members:
323
f67539c2 324System Errors
11fdf7f2
TL
325-------------
326
20effc67
TL
327{fmt} does not use ``errno`` to communicate errors to the user, but it may call
328system functions which set ``errno``. Users should not make any assumptions
329about the value of ``errno`` being preserved by library functions.
11fdf7f2 330
20effc67 331.. doxygenfunction:: fmt::system_error
11fdf7f2
TL
332
333.. doxygenfunction:: fmt::format_system_error
334
f67539c2 335Custom Allocators
11fdf7f2
TL
336-----------------
337
338The {fmt} library supports custom dynamic memory allocators.
339A custom allocator class can be specified as a template argument to
340:class:`fmt::basic_memory_buffer`::
341
342 using custom_memory_buffer =
343 fmt::basic_memory_buffer<char, fmt::inline_buffer_size, custom_allocator>;
344
345It is also possible to write a formatting function that uses a custom
346allocator::
347
348 using custom_string =
349 std::basic_string<char, std::char_traits<char>, custom_allocator>;
350
351 custom_string vformat(custom_allocator alloc, fmt::string_view format_str,
352 fmt::format_args args) {
353 custom_memory_buffer buf(alloc);
354 fmt::vformat_to(buf, format_str, args);
355 return custom_string(buf.data(), buf.size(), alloc);
356 }
357
358 template <typename ...Args>
359 inline custom_string format(custom_allocator alloc,
360 fmt::string_view format_str,
f67539c2 361 const Args& ... args) {
11fdf7f2
TL
362 return vformat(alloc, format_str, fmt::make_format_args(args...));
363 }
364
20effc67
TL
365The allocator will be used for the output container only. Formatting functions
366normally don't do any allocations for built-in and string types except for
367non-default floating-point formatting that occasionally falls back on
368``sprintf``.
11fdf7f2 369
f67539c2
TL
370.. _ranges-api:
371
372Ranges and Tuple Formatting
373===========================
374
375The library also supports convenient formatting of ranges and tuples::
376
377 #include <fmt/ranges.h>
378
379 std::tuple<char, int, float> t{'a', 1, 2.0f};
380 // Prints "('a', 1, 2.0)"
381 fmt::print("{}", t);
382
383
384NOTE: currently, the overload of ``fmt::join`` for iterables exists in the main
385``format.h`` header, but expect this to change in the future.
386
387Using ``fmt::join``, you can separate tuple elements with a custom separator::
388
389 #include <fmt/ranges.h>
390
391 std::tuple<int, char> t = {1, 'a'};
392 // Prints "1, a"
393 fmt::print("{}", fmt::join(t, ", "));
394
395.. _chrono-api:
11fdf7f2 396
f67539c2 397Date and Time Formatting
11fdf7f2
TL
398========================
399
20effc67
TL
400``fmt/chrono.h`` provides formatters for
401
402* `std::chrono::duration <https://en.cppreference.com/w/cpp/chrono/duration>`_
403* `std::chrono::time_point
404 <https://en.cppreference.com/w/cpp/chrono/time_point>`_
405* `std::tm <https://en.cppreference.com/w/cpp/chrono/c/tm>`_
406
407The format syntax is described in :ref:`chrono-specs`.
408
409**Example**::
11fdf7f2 410
f67539c2 411 #include <fmt/chrono.h>
11fdf7f2 412
20effc67
TL
413 int main() {
414 std::time_t t = std::time(nullptr);
415
416 // Prints "The date is 2020-11-07." (with the current date):
417 fmt::print("The date is {:%Y-%m-%d}.", fmt::localtime(t));
418
419 using namespace std::literals::chrono_literals;
420
421 // Prints "Default format: 42s 100ms":
422 fmt::print("Default format: {} {}\n", 42s, 100ms);
423
424 // Prints "strftime-like format: 03:15:30":
425 fmt::print("strftime-like format: {:%H:%M:%S}\n", 3h + 15min + 30s);
426 }
427
428.. doxygenfunction:: localtime(std::time_t time)
429
430.. doxygenfunction:: gmtime(std::time_t time)
431
432.. _compile-api:
433
434Format string compilation
435=========================
436
437``fmt/compile.h`` provides format string compilation support when using
438``FMT_COMPILE``. Format strings are parsed, checked and converted into efficient
439formatting code at compile-time. This supports arguments of built-in and string
440types as well as user-defined types with ``constexpr`` ``parse`` functions in
441their ``formatter`` specializations. Format string compilation can generate more
442binary code compared to the default API and is only recommended in places where
443formatting is a performance bottleneck.
11fdf7f2 444
20effc67
TL
445.. doxygendefine:: FMT_COMPILE
446
447.. _color-api:
448
449Terminal color and text style
450=============================
451
452``fmt/color.h`` provides support for terminal color and text style output.
453
454.. doxygenfunction:: print(const text_style &ts, const S &format_str, const Args&... args)
455
456.. doxygenfunction:: fg(detail::color_type)
457
458.. doxygenfunction:: bg(detail::color_type)
459
460.. _os-api:
461
462System APIs
463===========
464
465.. doxygenclass:: fmt::ostream
466 :members:
467
468.. doxygenfunction:: fmt::windows_error
469 :members:
11fdf7f2
TL
470
471.. _ostream-api:
472
f67539c2 473``std::ostream`` Support
11fdf7f2
TL
474========================
475
476``fmt/ostream.h`` provides ``std::ostream`` support including formatting of
20effc67 477user-defined types that have an overloaded insertion operator (``operator<<``)::
11fdf7f2
TL
478
479 #include <fmt/ostream.h>
480
481 class date {
482 int year_, month_, day_;
483 public:
484 date(int year, int month, int day): year_(year), month_(month), day_(day) {}
485
f67539c2 486 friend std::ostream& operator<<(std::ostream& os, const date& d) {
11fdf7f2
TL
487 return os << d.year_ << '-' << d.month_ << '-' << d.day_;
488 }
489 };
490
491 std::string s = fmt::format("The date is {}", date(2012, 12, 9));
492 // s == "The date is 2012-12-9"
493
20effc67
TL
494{fmt} only supports insertion operators that are defined in the same namespaces
495as the types they format and can be found with the argument-dependent lookup.
496
497.. doxygenfunction:: print(std::basic_ostream<Char> &os, const S &format_str, Args&&... args)
11fdf7f2
TL
498
499.. _printf-api:
500
f67539c2 501``printf`` Formatting
11fdf7f2
TL
502=====================
503
504The header ``fmt/printf.h`` provides ``printf``-like formatting functionality.
505The following functions use `printf format string syntax
20effc67 506<https://pubs.opengroup.org/onlinepubs/009695399/functions/fprintf.html>`_ with
11fdf7f2
TL
507the POSIX extension for positional arguments. Unlike their standard
508counterparts, the ``fmt`` functions are type-safe and throw an exception if an
509argument type doesn't match its format specification.
510
20effc67
TL
511.. doxygenfunction:: printf(const S &format_str, const T&... args)
512
513.. doxygenfunction:: fprintf(std::FILE *f, const S &fmt, const T&... args) -> int
514
515.. doxygenfunction:: sprintf(const S&, const T&...)
516
517.. _xchar-api:
518
519``wchar_t`` Support
520===================
521
522The optional header ``fmt/wchar_t.h`` provides support for ``wchar_t`` and
523exotic character types.
524
525.. doxygenstruct:: fmt::is_char
526
527.. doxygentypedef:: fmt::wstring_view
528
529.. doxygentypedef:: fmt::wformat_context
530
531.. doxygenfunction:: fmt::to_wstring(const T &value)
11fdf7f2 532
20effc67
TL
533Compatibility with C++20 ``std::format``
534========================================
11fdf7f2 535
20effc67
TL
536{fmt} implements nearly all of the `C++20 formatting library
537<https://en.cppreference.com/w/cpp/utility/format>`_ with the following
538differences:
11fdf7f2 539
20effc67
TL
540* Names are defined in the ``fmt`` namespace instead of ``std`` to avoid
541 collisions with standard library implementations.
542* Width calculation doesn't use grapheme clusterization. The latter has been
543 implemented in a separate branch but hasn't been integrated yet.
544* Most C++20 chrono types are not supported yet.