• Home
  • History
  • Annotate
Name Date Size #Lines LOC

..03-May-2022-

.github/H22-Oct-2021-71

doc/H03-May-2022-9,9858,161

include/fmt/H22-Oct-2021-10,8568,160

src/H22-Oct-2021-494380

support/H22-Oct-2021-3,6533,165

test/H03-May-2022-55,90237,505

.clang-formatH A D22-Oct-2021231 98

.gitignoreH A D22-Oct-2021366 3633

.travis.ymlH A D22-Oct-20212.5 KiB10294

CONTRIBUTING.mdH A D22-Oct-2021589 1813

ChangeLog.rstH A D22-Oct-2021110.8 KiB2,8952,163

LICENSE.rstH A D22-Oct-20211.4 KiB2822

README.rstH A D22-Oct-202118.9 KiB502369

README.rst

1{fmt}
2=====
3
4.. image:: https://travis-ci.org/fmtlib/fmt.png?branch=master
5   :target: https://travis-ci.org/fmtlib/fmt
6
7.. image:: https://ci.appveyor.com/api/projects/status/ehjkiefde6gucy1v
8   :target: https://ci.appveyor.com/project/vitaut/fmt
9
10.. image:: https://oss-fuzz-build-logs.storage.googleapis.com/badges/libfmt.svg
11   :alt: fmt is continuously fuzzed att oss-fuzz
12   :target: https://bugs.chromium.org/p/oss-fuzz/issues/list?colspec=ID%20Type%20Component%20Status%20Proj%20Reported%20Owner%20Summary&q=proj%3Dlibfmt&can=1
13
14.. image:: https://img.shields.io/badge/stackoverflow-fmt-blue.svg
15   :alt: Ask questions at StackOverflow with the tag fmt
16   :target: https://stackoverflow.com/questions/tagged/fmt
17
18**{fmt}** is an open-source formatting library for C++.
19It can be used as a safe and fast alternative to (s)printf and iostreams.
20
21`Documentation <https://fmt.dev/latest/>`__
22
23Q&A: ask questions on `StackOverflow with the tag fmt <https://stackoverflow.com/questions/tagged/fmt>`_.
24
25Features
26--------
27
28* Replacement-based `format API <https://fmt.dev/dev/api.html>`_ with
29  positional arguments for localization.
30* `Format string syntax <https://fmt.dev/dev/syntax.html>`_ similar to the one
31  of `str.format <https://docs.python.org/3/library/stdtypes.html#str.format>`_
32  in Python.
33* Safe `printf implementation
34  <https://fmt.dev/latest/api.html#printf-formatting>`_ including
35  the POSIX extension for positional arguments.
36* Implementation of `C++20 std::format <https://en.cppreference.com/w/cpp/utility/format>`__.
37* Support for user-defined types.
38* High performance: faster than common standard library implementations of
39  `printf <https://en.cppreference.com/w/cpp/io/c/fprintf>`_ and
40  iostreams. See `Speed tests`_ and `Fast integer to string conversion in C++
41  <http://zverovich.net/2013/09/07/integer-to-string-conversion-in-cplusplus.html>`_.
42* Small code size both in terms of source code (the minimum configuration
43  consists of just three header files, ``core.h``, ``format.h`` and
44  ``format-inl.h``) and compiled code. See `Compile time and code bloat`_.
45* Reliability: the library has an extensive set of `unit tests
46  <https://github.com/fmtlib/fmt/tree/master/test>`_ and is continuously fuzzed.
47* Safety: the library is fully type safe, errors in format strings can be
48  reported at compile time, automatic memory management prevents buffer overflow
49  errors.
50* Ease of use: small self-contained code base, no external dependencies,
51  permissive MIT `license
52  <https://github.com/fmtlib/fmt/blob/master/LICENSE.rst>`_
53* `Portability <https://fmt.dev/latest/index.html#portability>`_ with
54  consistent output across platforms and support for older compilers.
55* Clean warning-free codebase even on high warning levels
56  (``-Wall -Wextra -pedantic``).
57* Support for wide strings.
58* Optional header-only configuration enabled with the ``FMT_HEADER_ONLY`` macro.
59
60See the `documentation <https://fmt.dev/latest/>`_ for more details.
61
62Examples
63--------
64
65Print ``Hello, world!`` to ``stdout``:
66
67.. code:: c++
68
69    fmt::print("Hello, {}!", "world");  // Python-like format string syntax
70    fmt::printf("Hello, %s!", "world"); // printf format string syntax
71
72Format a string and use positional arguments:
73
74.. code:: c++
75
76    std::string s = fmt::format("I'd rather be {1} than {0}.", "right", "happy");
77    // s == "I'd rather be happy than right."
78
79Check a format string at compile time:
80
81.. code:: c++
82
83    // test.cc
84    #include <fmt/format.h>
85    std::string s = format(FMT_STRING("{2}"), 42);
86
87.. code::
88
89    $ c++ -Iinclude -std=c++14 test.cc
90    ...
91    test.cc:4:17: note: in instantiation of function template specialization 'fmt::v5::format<S, int>' requested here
92    std::string s = format(FMT_STRING("{2}"), 42);
93                    ^
94    include/fmt/core.h:778:19: note: non-constexpr function 'on_error' cannot be used in a constant expression
95        ErrorHandler::on_error(message);
96                      ^
97    include/fmt/format.h:2226:16: note: in call to '&checker.context_->on_error(&"argument index out of range"[0])'
98          context_.on_error("argument index out of range");
99                   ^
100
101Use {fmt} as a safe portable replacement for ``itoa``
102(`godbolt <https://godbolt.org/g/NXmpU4>`_):
103
104.. code:: c++
105
106    fmt::memory_buffer buf;
107    format_to(buf, "{}", 42);    // replaces itoa(42, buffer, 10)
108    format_to(buf, "{:x}", 42);  // replaces itoa(42, buffer, 16)
109    // access the string with to_string(buf) or buf.data()
110
111Format objects of user-defined types via a simple `extension API
112<https://fmt.dev/latest/api.html#formatting-user-defined-types>`_:
113
114.. code:: c++
115
116    #include "fmt/format.h"
117
118    struct date {
119      int year, month, day;
120    };
121
122    template <>
123    struct fmt::formatter<date> {
124      constexpr auto parse(format_parse_context& ctx) { return ctx.begin(); }
125
126      template <typename FormatContext>
127      auto format(const date& d, FormatContext& ctx) {
128        return format_to(ctx.out(), "{}-{}-{}", d.year, d.month, d.day);
129      }
130    };
131
132    std::string s = fmt::format("The date is {}", date{2012, 12, 9});
133    // s == "The date is 2012-12-9"
134
135Create your own functions similar to `format
136<https://fmt.dev/latest/api.html#format>`_ and
137`print <https://fmt.dev/latest/api.html#print>`_
138which take arbitrary arguments (`godbolt <https://godbolt.org/g/MHjHVf>`_):
139
140.. code:: c++
141
142    // Prints formatted error message.
143    void vreport_error(const char* format, fmt::format_args args) {
144      fmt::print("Error: ");
145      fmt::vprint(format, args);
146    }
147    template <typename... Args>
148    void report_error(const char* format, const Args & ... args) {
149      vreport_error(format, fmt::make_format_args(args...));
150    }
151
152    report_error("file not found: {}", path);
153
154Note that ``vreport_error`` is not parameterized on argument types which can
155improve compile times and reduce code size compared to a fully parameterized
156version.
157
158Benchmarks
159----------
160
161Speed tests
162~~~~~~~~~~~
163
164================= ============= ===========
165Library           Method        Run Time, s
166================= ============= ===========
167libc              printf          1.04
168libc++            std::ostream    3.05
169{fmt} 6.1.1       fmt::print      0.75
170Boost Format 1.67 boost::format   7.24
171Folly Format      folly::format   2.23
172================= ============= ===========
173
174{fmt} is the fastest of the benchmarked methods, ~35% faster than ``printf``.
175
176The above results were generated by building ``tinyformat_test.cpp`` on macOS
17710.14.6 with ``clang++ -O3 -DSPEED_TEST -DHAVE_FORMAT``, and taking the best of
178three runs. In the test, the format string ``"%0.10f:%04d:%+g:%s:%p:%c:%%\n"``
179or equivalent is filled 2,000,000 times with output sent to ``/dev/null``; for
180further details refer to the `source
181<https://github.com/fmtlib/format-benchmark/blob/master/tinyformat_test.cpp>`_.
182
183{fmt} is 10x faster than ``std::ostringstream`` and ``sprintf`` on floating-point
184formatting (`dtoa-benchmark <https://github.com/fmtlib/dtoa-benchmark>`_)
185and as fast as `double-conversion <https://github.com/google/double-conversion>`_:
186
187.. image:: https://user-images.githubusercontent.com/576385/69767160-cdaca400-112f-11ea-9fc5-347c9f83caad.png
188   :target: https://fmt.dev/unknown_mac64_clang10.0.html
189
190Compile time and code bloat
191~~~~~~~~~~~~~~~~~~~~~~~~~~~
192
193The script `bloat-test.py
194<https://github.com/fmtlib/format-benchmark/blob/master/bloat-test.py>`_
195from `format-benchmark <https://github.com/fmtlib/format-benchmark>`_
196tests compile time and code bloat for nontrivial projects.
197It generates 100 translation units and uses ``printf()`` or its alternative
198five times in each to simulate a medium sized project.  The resulting
199executable size and compile time (Apple LLVM version 8.1.0 (clang-802.0.42),
200macOS Sierra, best of three) is shown in the following tables.
201
202**Optimized build (-O3)**
203
204============= =============== ==================== ==================
205Method        Compile Time, s Executable size, KiB Stripped size, KiB
206============= =============== ==================== ==================
207printf                    2.6                   29                 26
208printf+string            16.4                   29                 26
209iostreams                31.1                   59                 55
210{fmt}                    19.0                   37                 34
211Boost Format             91.9                  226                203
212Folly Format            115.7                  101                 88
213============= =============== ==================== ==================
214
215As you can see, {fmt} has 60% less overhead in terms of resulting binary code
216size compared to iostreams and comes pretty close to ``printf``. Boost Format
217and Folly Format have the largest overheads.
218
219``printf+string`` is the same as ``printf`` but with extra ``<string>``
220include to measure the overhead of the latter.
221
222**Non-optimized build**
223
224============= =============== ==================== ==================
225Method        Compile Time, s Executable size, KiB Stripped size, KiB
226============= =============== ==================== ==================
227printf                    2.2                   33                 30
228printf+string            16.0                   33                 30
229iostreams                28.3                   56                 52
230{fmt}                    18.2                   59                 50
231Boost Format             54.1                  365                303
232Folly Format             79.9                  445                430
233============= =============== ==================== ==================
234
235``libc``, ``lib(std)c++`` and ``libfmt`` are all linked as shared libraries to
236compare formatting function overhead only. Boost Format is a
237header-only library so it doesn't provide any linkage options.
238
239Running the tests
240~~~~~~~~~~~~~~~~~
241
242Please refer to `Building the library`__ for the instructions on how to build
243the library and run the unit tests.
244
245__ https://fmt.dev/latest/usage.html#building-the-library
246
247Benchmarks reside in a separate repository,
248`format-benchmarks <https://github.com/fmtlib/format-benchmark>`_,
249so to run the benchmarks you first need to clone this repository and
250generate Makefiles with CMake::
251
252    $ git clone --recursive https://github.com/fmtlib/format-benchmark.git
253    $ cd format-benchmark
254    $ cmake .
255
256Then you can run the speed test::
257
258    $ make speed-test
259
260or the bloat test::
261
262    $ make bloat-test
263
264Projects using this library
265---------------------------
266
267* `0 A.D. <https://play0ad.com/>`_: A free, open-source, cross-platform real-time
268  strategy game
269
270* `AMPL/MP <https://github.com/ampl/mp>`_:
271  An open-source library for mathematical programming
272
273* `AvioBook <https://www.aviobook.aero/en>`_: A comprehensive aircraft
274  operations suite
275
276* `Celestia <https://celestia.space/>`_: Real-time 3D visualization of space
277
278* `Ceph <https://ceph.com/>`_: A scalable distributed storage system
279
280* `ccache <https://ccache.dev/>`_: A compiler cache
281
282* `CUAUV <http://cuauv.org/>`_: Cornell University's autonomous underwater
283  vehicle
284
285* `HarpyWar/pvpgn <https://github.com/pvpgn/pvpgn-server>`_:
286  Player vs Player Gaming Network with tweaks
287
288* `KBEngine <https://kbengine.org/>`_: An open-source MMOG server engine
289
290* `Keypirinha <https://keypirinha.com/>`_: A semantic launcher for Windows
291
292* `Kodi <https://kodi.tv/>`_ (formerly xbmc): Home theater software
293
294* `Lifeline <https://github.com/peter-clark/lifeline>`_: A 2D game
295
296* `Drake <https://drake.mit.edu/>`_: A planning, control, and analysis toolbox
297  for nonlinear dynamical systems (MIT)
298
299* `Envoy <https://lyft.github.io/envoy/>`_: C++ L7 proxy and communication bus
300  (Lyft)
301
302* `FiveM <https://fivem.net/>`_: a modification framework for GTA V
303
304* `MongoDB <https://mongodb.com/>`_: Distributed document database
305
306* `MongoDB Smasher <https://github.com/duckie/mongo_smasher>`_: A small tool to
307  generate randomized datasets
308
309* `OpenSpace <https://openspaceproject.com/>`_: An open-source astrovisualization
310  framework
311
312* `PenUltima Online (POL) <https://www.polserver.com/>`_:
313  An MMO server, compatible with most Ultima Online clients
314
315* `quasardb <https://www.quasardb.net/>`_: A distributed, high-performance,
316  associative database
317
318* `readpe <https://bitbucket.org/sys_dev/readpe>`_: Read Portable Executable
319
320* `redis-cerberus <https://github.com/HunanTV/redis-cerberus>`_: A Redis cluster
321  proxy
322
323* `rpclib <http://rpclib.net/>`_: A modern C++ msgpack-RPC server and client
324  library
325
326* `Saddy <https://github.com/mamontov-cpp/saddy-graphics-engine-2d>`_:
327  Small crossplatform 2D graphic engine
328
329* `Salesforce Analytics Cloud <https://www.salesforce.com/analytics-cloud/overview/>`_:
330  Business intelligence software
331
332* `Scylla <https://www.scylladb.com/>`_: A Cassandra-compatible NoSQL data store
333  that can handle 1 million transactions per second on a single server
334
335* `Seastar <http://www.seastar-project.org/>`_: An advanced, open-source C++
336  framework for high-performance server applications on modern hardware
337
338* `spdlog <https://github.com/gabime/spdlog>`_: Super fast C++ logging library
339
340* `Stellar <https://www.stellar.org/>`_: Financial platform
341
342* `Touch Surgery <https://www.touchsurgery.com/>`_: Surgery simulator
343
344* `TrinityCore <https://github.com/TrinityCore/TrinityCore>`_: Open-source
345  MMORPG framework
346
347`More... <https://github.com/search?q=fmtlib&type=Code>`_
348
349If you are aware of other projects using this library, please let me know
350by `email <mailto:victor.zverovich@gmail.com>`_ or by submitting an
351`issue <https://github.com/fmtlib/fmt/issues>`_.
352
353Motivation
354----------
355
356So why yet another formatting library?
357
358There are plenty of methods for doing this task, from standard ones like
359the printf family of function and iostreams to Boost Format and FastFormat
360libraries. The reason for creating a new library is that every existing
361solution that I found either had serious issues or didn't provide
362all the features I needed.
363
364printf
365~~~~~~
366
367The good thing about ``printf`` is that it is pretty fast and readily available
368being a part of the C standard library. The main drawback is that it
369doesn't support user-defined types. ``printf`` also has safety issues although
370they are somewhat mitigated with `__attribute__ ((format (printf, ...))
371<https://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html>`_ in GCC.
372There is a POSIX extension that adds positional arguments required for
373`i18n <https://en.wikipedia.org/wiki/Internationalization_and_localization>`_
374to ``printf`` but it is not a part of C99 and may not be available on some
375platforms.
376
377iostreams
378~~~~~~~~~
379
380The main issue with iostreams is best illustrated with an example:
381
382.. code:: c++
383
384    std::cout << std::setprecision(2) << std::fixed << 1.23456 << "\n";
385
386which is a lot of typing compared to printf:
387
388.. code:: c++
389
390    printf("%.2f\n", 1.23456);
391
392Matthew Wilson, the author of FastFormat, called this "chevron hell". iostreams
393don't support positional arguments by design.
394
395The good part is that iostreams support user-defined types and are safe although
396error handling is awkward.
397
398Boost Format
399~~~~~~~~~~~~
400
401This is a very powerful library which supports both ``printf``-like format
402strings and positional arguments. Its main drawback is performance. According to
403various benchmarks it is much slower than other methods considered here. Boost
404Format also has excessive build times and severe code bloat issues (see
405`Benchmarks`_).
406
407FastFormat
408~~~~~~~~~~
409
410This is an interesting library which is fast, safe and has positional
411arguments. However it has significant limitations, citing its author:
412
413    Three features that have no hope of being accommodated within the
414    current design are:
415
416    * Leading zeros (or any other non-space padding)
417    * Octal/hexadecimal encoding
418    * Runtime width/alignment specification
419
420It is also quite big and has a heavy dependency, STLSoft, which might be
421too restrictive for using it in some projects.
422
423Boost Spirit.Karma
424~~~~~~~~~~~~~~~~~~
425
426This is not really a formatting library but I decided to include it here for
427completeness. As iostreams, it suffers from the problem of mixing verbatim text
428with arguments. The library is pretty fast, but slower on integer formatting
429than ``fmt::format_int`` on Karma's own benchmark,
430see `Fast integer to string conversion in C++
431<http://zverovich.net/2013/09/07/integer-to-string-conversion-in-cplusplus.html>`_.
432
433FAQ
434---
435
436Q: how can I capture formatting arguments and format them later?
437
438A: use ``std::tuple``:
439
440.. code:: c++
441
442   template <typename... Args>
443   auto capture(const Args&... args) {
444     return std::make_tuple(args...);
445   }
446
447   auto print_message = [](const auto&... args) {
448     fmt::print(args...);
449   };
450
451   // Capture and store arguments:
452   auto args = capture("{} {}", 42, "foo");
453   // Do formatting:
454   std::apply(print_message, args);
455
456License
457-------
458
459{fmt} is distributed under the MIT `license
460<https://github.com/fmtlib/fmt/blob/master/LICENSE.rst>`_.
461
462The `Format String Syntax
463<https://fmt.dev/latest/syntax.html>`_
464section in the documentation is based on the one from Python `string module
465documentation <https://docs.python.org/3/library/string.html#module-string>`_
466adapted for the current library. For this reason the documentation is
467distributed under the Python Software Foundation license available in
468`doc/python-license.txt
469<https://raw.github.com/fmtlib/fmt/master/doc/python-license.txt>`_.
470It only applies if you distribute the documentation of fmt.
471
472Acknowledgments
473---------------
474
475The {fmt} library is maintained by Victor Zverovich (`vitaut
476<https://github.com/vitaut>`_) and Jonathan Müller (`foonathan
477<https://github.com/foonathan>`_) with contributions from many other people.
478See `Contributors <https://github.com/fmtlib/fmt/graphs/contributors>`_ and
479`Releases <https://github.com/fmtlib/fmt/releases>`_ for some of the names.
480Let us know if your contribution is not listed or mentioned incorrectly and
481we'll make it right.
482
483The benchmark section of this readme file and the performance tests are taken
484from the excellent `tinyformat <https://github.com/c42f/tinyformat>`_ library
485written by Chris Foster.  Boost Format library is acknowledged transitively
486since it had some influence on tinyformat.
487Some ideas used in the implementation are borrowed from `Loki
488<http://loki-lib.sourceforge.net/>`_ SafeFormat and `Diagnostic API
489<https://clang.llvm.org/doxygen/classclang_1_1Diagnostic.html>`_ in
490`Clang <https://clang.llvm.org/>`_.
491Format string syntax and the documentation are based on Python's `str.format
492<https://docs.python.org/3/library/stdtypes.html#str.format>`_.
493Thanks `Doug Turnbull <https://github.com/softwaredoug>`_ for his valuable
494comments and contribution to the design of the type-safe API and
495`Gregory Czajkowski <https://github.com/gcflymoto>`_ for implementing binary
496formatting. Thanks `Ruslan Baratov <https://github.com/ruslo>`_ for comprehensive
497`comparison of integer formatting algorithms <https://github.com/ruslo/int-dec-format-tests>`_
498and useful comments regarding performance, `Boris Kaul <https://github.com/localvoid>`_ for
499`C++ counting digits benchmark <https://github.com/localvoid/cxx-benchmark-count-digits>`_.
500Thanks to `CarterLi <https://github.com/CarterLi>`_ for contributing various
501improvements to the code.
502