fmt/doc/api.rst

277 lines
8.1 KiB
ReStructuredText
Raw Normal View History

2014-10-10 15:40:35 +00:00
.. _string-formatting-api:
*************
API Reference
*************
All functions and classes provided by the {fmt} library reside in namespace
``fmt`` and macros have prefix ``FMT_``.
2014-10-10 15:40:35 +00:00
2015-12-18 15:16:40 +00:00
Format API
==========
2014-10-10 15:40:35 +00:00
2018-02-11 21:43:16 +00:00
The following functions defined in ``fmt/core.h`` use :ref:`format string
2018-03-04 06:12:23 +00:00
syntax <syntax>` similar to that of Python's `str.format
<http://docs.python.org/3/library/stdtypes.html#str.format>`_.
2014-10-10 15:40:35 +00:00
They take *format_str* and *args* as arguments.
*format_str* is a format string that contains literal text and replacement
fields surrounded by braces ``{}``. The fields are replaced with formatted
arguments in the resulting string.
2018-02-11 17:43:54 +00:00
*args* is an argument list representing objects to be formatted.
2014-10-10 15:40:35 +00:00
The `performance of the formating functions
2016-05-10 14:29:31 +00:00
<https://github.com/fmtlib/fmt/blob/master/README.rst#speed-tests>`_ is close
to that of glibc's ``printf`` and better than the performance of IOStreams.
2014-10-10 15:40:35 +00:00
.. _format:
2018-02-11 17:43:54 +00:00
.. doxygenfunction:: format(string_view, const Args&...)
2014-10-10 15:40:35 +00:00
.. doxygenfunction:: operator""_format(const char *, std::size_t)
2014-10-10 15:40:35 +00:00
.. _print:
2018-02-11 17:43:54 +00:00
.. doxygenfunction:: print(string_view, const Args&...)
2014-10-10 15:40:35 +00:00
2018-02-11 17:43:54 +00:00
.. doxygenfunction:: print(std::FILE *, string_view, const Args&...)
2015-12-18 15:16:40 +00:00
Date and time formatting
------------------------
2016-07-20 15:17:33 +00:00
The library supports `strftime
<http://en.cppreference.com/w/cpp/chrono/c/strftime>`_-like date and time
formatting::
#include "fmt/time.h"
std::time_t t = std::time(nullptr);
// Prints "The date is 2016-04-29." (with the current date)
fmt::print("The date is {:%Y-%m-%d}.", *std::localtime(&t));
The format string syntax is described in the documentation of
2016-04-29 14:02:37 +00:00
`strftime <http://en.cppreference.com/w/cpp/chrono/c/strftime>`_.
Formatting user-defined types
-----------------------------
To make a user-defined type formattable, specialize the ``formatter<T>`` struct
template and implement ``parse`` and ``format`` methods::
struct point { double x, y; };
namespace fmt {
template <>
struct formatter<point> {
template <typename ParseContext>
2018-03-04 17:16:51 +00:00
constexpr auto parse(ParseContext &ctx) { return ctx.begin(); }
template <typename FormatContext>
auto format(const point &p, FormatContext &ctx) {
return format_to(ctx.begin(), "({:.1f}, {:.1f})", p.x, p.y);
}
};
}
Then you can pass objects of type ``point`` to any formatting function::
point p = {1, 2};
std::string s = fmt::format("{}", p);
// s == "(1.0, 2.0)"
In the example above the ``formatter<point>::parse`` function ignores the
contents of the format string referred to by ``ctx.begin()`` so the object will
2018-02-11 21:43:16 +00:00
always be formatted in the same way. See ``formatter<tm>::parse`` in
:file:`fmt/time.h` for an advanced example of how to parse the format string and
customize the formatted output.
This section shows how to define a custom format function for a user-defined
type. The next section describes how to get ``fmt`` to use a conventional stream
output ``operator<<`` when one is defined for a user-defined type.
2016-05-07 16:09:33 +00:00
``std::ostream`` support
------------------------
The header ``fmt/ostream.h`` provides ``std::ostream`` support including
formatting of user-defined types that have overloaded ``operator<<``::
#include "fmt/ostream.h"
2018-03-04 17:16:51 +00:00
class date {
2016-05-07 16:09:33 +00:00
int year_, month_, day_;
public:
2018-03-04 17:16:51 +00:00
date(int year, int month, int day): year_(year), month_(month), day_(day) {}
2016-05-07 16:09:33 +00:00
2018-03-04 17:16:51 +00:00
friend std::ostream &operator<<(std::ostream &os, const date &d) {
2016-05-07 16:09:33 +00:00
return os << d.year_ << '-' << d.month_ << '-' << d.day_;
}
};
2018-03-04 17:16:51 +00:00
std::string s = fmt::format("The date is {}", date(2012, 12, 9));
2016-05-07 16:09:33 +00:00
// s == "The date is 2012-12-9"
2018-02-11 21:43:16 +00:00
.. doxygenfunction:: print(std::ostream&, string_view, const Args&...)
2016-05-07 16:09:33 +00:00
2016-04-20 14:16:52 +00:00
Argument formatters
-------------------
It is possible to change the way arguments are formatted by providing a
custom argument formatter class::
2018-03-04 06:12:23 +00:00
using arg_formatter =
fmt::arg_formatter<fmt::back_insert_range<fmt::internal::buffer>>;
// A custom argument formatter that formats negative integers as unsigned
// with the ``x`` format specifier.
2018-03-04 06:12:23 +00:00
class custom_arg_formatter : public arg_formatter {
2016-10-07 10:22:14 +00:00
public:
custom_arg_formatter(fmt::context &ctx, fmt::format_specs &spec)
2018-03-04 06:12:23 +00:00
: arg_formatter(ctx, spec) {}
using arg_formatter::operator();
2018-03-04 06:12:23 +00:00
void operator()(int value) {
if (spec().type() == 'x')
2018-03-04 06:12:23 +00:00
(*this)(static_cast<unsigned>(value)); // convert to unsigned and format
else
2018-03-04 06:12:23 +00:00
arg_formatter::operator()(value);
}
};
2018-03-04 06:12:23 +00:00
std::string custom_vformat(fmt::string_view format_str, fmt::format_args args) {
fmt::memory_buffer buffer;
// Pass custom argument formatter as a template arg to vformat_to.
fmt::vformat_to<custom_arg_formatter>(buffer, format_str, args);
2018-03-04 06:12:23 +00:00
return fmt::to_string(buffer);
}
template <typename ...Args>
inline std::string custom_format(
fmt::string_view format_str, const Args &... args) {
return custom_vformat(format_str, fmt::make_args(args...));
}
std::string s = custom_format("{:x}", -42); // s == "ffffffd6"
.. doxygenclass:: fmt::ArgVisitor
:members:
2018-03-04 06:12:23 +00:00
.. doxygenclass:: fmt::arg_formatter_base
2016-04-20 14:16:52 +00:00
:members:
2018-03-04 06:12:23 +00:00
.. doxygenclass:: fmt::arg_formatter
2016-04-20 14:16:52 +00:00
:members:
Printf formatting
-----------------
2014-10-10 15:40:35 +00:00
The header ``fmt/printf.h`` provides ``printf``-like formatting functionality.
2014-10-10 15:40:35 +00:00
The following functions use `printf format string syntax
<http://pubs.opengroup.org/onlinepubs/009695399/functions/fprintf.html>`_ with
the POSIX extension for positional arguments. Unlike their standard
counterparts, the ``fmt`` functions are type-safe and throw an exception if an
argument type doesn't match its format specification.
2014-10-10 15:40:35 +00:00
2018-02-11 21:43:16 +00:00
.. doxygenfunction:: printf(string_view, const Args&...)
2014-10-10 15:40:35 +00:00
2018-02-11 21:43:16 +00:00
.. doxygenfunction:: fprintf(std::FILE *, string_view, const Args&...)
2018-02-11 21:43:16 +00:00
.. doxygenfunction:: fprintf(std::ostream&, string_view, const Args&...)
2016-08-03 15:52:05 +00:00
2018-02-11 21:43:16 +00:00
.. doxygenfunction:: sprintf(string_view, const Args&...)
2014-10-10 15:40:35 +00:00
Write API
=========
2016-05-10 14:29:31 +00:00
The write API provides classes for writing formatted data into character
streams. It is usually faster than the `format API`_ but, as IOStreams,
may result in larger compiled code size. The main writer class is
2018-03-04 17:55:17 +00:00
`~fmt::basic_memory_writer` which stores its output in a memory buffer and
2016-07-20 15:17:33 +00:00
provides direct access to it. It is possible to create custom writers that
2016-05-10 14:29:31 +00:00
store output elsewhere by subclassing `~fmt::BasicWriter`.
2014-10-10 15:40:35 +00:00
.. doxygenclass:: fmt::BasicWriter
:members:
2018-03-04 17:55:17 +00:00
.. doxygenclass:: fmt::basic_memory_writer
2014-10-10 15:40:35 +00:00
:members:
2015-03-02 02:10:09 +00:00
.. doxygenclass:: fmt::BasicArrayWriter
:members:
2016-07-14 14:41:00 +00:00
.. doxygenclass:: fmt::BasicStringWriter
:members:
2016-04-11 13:32:24 +00:00
.. doxygenfunction:: bin(int)
2014-10-10 15:40:35 +00:00
2016-04-11 13:32:24 +00:00
.. doxygenfunction:: oct(int)
2014-10-10 15:40:35 +00:00
2016-04-11 13:32:24 +00:00
.. doxygenfunction:: hex(int)
2014-10-10 15:40:35 +00:00
2016-04-11 13:32:24 +00:00
.. doxygenfunction:: hexu(int)
2014-10-10 15:40:35 +00:00
2015-05-20 01:04:32 +00:00
.. doxygenfunction:: pad(int, unsigned, Char)
2014-10-10 15:40:35 +00:00
Utilities
=========
2018-03-04 06:12:23 +00:00
.. doxygenfunction:: fmt::arg(string_view, const T&)
2015-06-10 01:32:59 +00:00
.. doxygenfunction:: operator""_a(const char *, std::size_t)
2018-03-04 06:12:23 +00:00
.. doxygenclass:: fmt::basic_format_args
2014-10-10 15:40:35 +00:00
:members:
2016-05-19 02:54:52 +00:00
.. doxygenfunction:: fmt::to_string(const T&)
2018-03-04 06:12:23 +00:00
.. doxygenclass:: fmt::basic_string_view
2015-06-26 16:09:23 +00:00
:members:
2018-03-04 17:55:17 +00:00
.. doxygenclass:: fmt::basic_memory_buffer
2015-03-20 13:46:39 +00:00
:protected-members:
2015-03-20 13:42:55 +00:00
:members:
2016-04-20 14:44:37 +00:00
System errors
2014-10-10 15:40:35 +00:00
=============
2018-02-11 21:43:16 +00:00
.. doxygenclass:: fmt::system_error
2014-10-10 15:40:35 +00:00
:members:
.. doxygenfunction:: fmt::format_system_error
2018-02-11 21:43:16 +00:00
.. doxygenclass:: fmt::windows_error
2014-10-10 15:40:35 +00:00
:members:
.. _formatstrings:
Custom allocators
=================
2018-03-04 17:55:17 +00:00
The {fmt} library supports custom dynamic memory allocators.
2014-10-10 15:40:35 +00:00
A custom allocator class can be specified as a template argument to
2018-03-04 17:55:17 +00:00
:class:`fmt::basic_memory_buffer`::
2014-10-10 15:40:35 +00:00
2018-03-04 17:55:17 +00:00
using custom_memory_buffer =
fmt::basic_memory_buffer<char, fmt::inline_buffer_size, custom_allocator>;
2014-10-10 15:40:35 +00:00
It is also possible to write a formatting function that uses a custom
allocator::
2018-03-04 17:55:17 +00:00
using custom_string =
std::basic_string<char, std::char_traits<char>, custom_allocator>;
custom_string vformat(custom_allocator alloc, fmt::string_view format_str,
fmt::format_args args) {
2018-03-04 17:55:17 +00:00
custom_memory_buffer buf(alloc);
fmt::vformat_to(buf, format_str, args);
return custom_string(buf.data(), buf.size(), alloc);
}
2014-10-10 15:40:35 +00:00
2018-03-04 17:55:17 +00:00
template <typename ...Args>
inline custom_string format(custom_allocator alloc,
fmt::string_view format_str,
const Args & ... args) {
return vformat(alloc, format_str, fmt::make_args(args...));
2014-10-10 15:40:35 +00:00
}