README.rst 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506
  1. {fmt}
  2. =====
  3. .. image:: https://travis-ci.org/fmtlib/fmt.png?branch=master
  4. :target: https://travis-ci.org/fmtlib/fmt
  5. .. image:: https://ci.appveyor.com/api/projects/status/ehjkiefde6gucy1v
  6. :target: https://ci.appveyor.com/project/vitaut/fmt
  7. .. image:: https://oss-fuzz-build-logs.storage.googleapis.com/badges/fmt.svg
  8. :alt: fmt is continuously fuzzed at oss-fuzz
  9. :target: https://bugs.chromium.org/p/oss-fuzz/issues/list?\
  10. colspec=ID%20Type%20Component%20Status%20Proj%20Reported%20Owner%20\
  11. Summary&q=proj%3Dfmt&can=1
  12. .. image:: https://img.shields.io/badge/stackoverflow-fmt-blue.svg
  13. :alt: Ask questions at StackOverflow with the tag fmt
  14. :target: https://stackoverflow.com/questions/tagged/fmt
  15. **{fmt}** is an open-source formatting library providing a fast and safe
  16. alternative to C stdio and C++ iostreams.
  17. If you like this project, please consider donating to BYSOL,
  18. an initiative to help victims of political repressions in Belarus:
  19. https://www.facebook.com/donate/759400044849707/108388587646909/.
  20. `Documentation <https://fmt.dev>`__
  21. Q&A: ask questions on `StackOverflow with the tag fmt
  22. <https://stackoverflow.com/questions/tagged/fmt>`_.
  23. Try {fmt} in `Compiler Explorer <https://godbolt.org/z/Eq5763>`_.
  24. Features
  25. --------
  26. * Simple `format API <https://fmt.dev/latest/api.html>`_ with positional arguments
  27. for localization
  28. * Implementation of `C++20 std::format
  29. <https://en.cppreference.com/w/cpp/utility/format>`__
  30. * `Format string syntax <https://fmt.dev/latest/syntax.html>`_ similar to Python's
  31. `format <https://docs.python.org/3/library/stdtypes.html#str.format>`_
  32. * Fast IEEE 754 floating-point formatter with correct rounding, shortness and
  33. round-trip guarantees
  34. * Safe `printf implementation
  35. <https://fmt.dev/latest/api.html#printf-formatting>`_ including the POSIX
  36. extension for positional arguments
  37. * Extensibility: `support for user-defined types
  38. <https://fmt.dev/latest/api.html#formatting-user-defined-types>`_
  39. * High performance: faster than common standard library implementations of
  40. ``(s)printf``, iostreams, ``to_string`` and ``to_chars``, see `Speed tests`_
  41. and `Converting a hundred million integers to strings per second
  42. <http://www.zverovich.net/2020/06/13/fast-int-to-string-revisited.html>`_
  43. * Small code size both in terms of source code with the minimum configuration
  44. consisting of just three files, ``core.h``, ``format.h`` and ``format-inl.h``,
  45. and compiled code; see `Compile time and code bloat`_
  46. * Reliability: the library has an extensive set of `tests
  47. <https://github.com/fmtlib/fmt/tree/master/test>`_ and is `continuously fuzzed
  48. <https://bugs.chromium.org/p/oss-fuzz/issues/list?colspec=ID%20Type%20
  49. Component%20Status%20Proj%20Reported%20Owner%20Summary&q=proj%3Dfmt&can=1>`_
  50. * Safety: the library is fully type safe, errors in format strings can be
  51. reported at compile time, automatic memory management prevents buffer overflow
  52. errors
  53. * Ease of use: small self-contained code base, no external dependencies,
  54. permissive MIT `license
  55. <https://github.com/fmtlib/fmt/blob/master/LICENSE.rst>`_
  56. * `Portability <https://fmt.dev/latest/index.html#portability>`_ with
  57. consistent output across platforms and support for older compilers
  58. * Clean warning-free codebase even on high warning levels such as
  59. ``-Wall -Wextra -pedantic``
  60. * Locale-independence by default
  61. * Optional header-only configuration enabled with the ``FMT_HEADER_ONLY`` macro
  62. See the `documentation <https://fmt.dev>`_ for more details.
  63. Examples
  64. --------
  65. **Print to stdout** (`run <https://godbolt.org/z/Tevcjh>`_)
  66. .. code:: c++
  67. #include <fmt/core.h>
  68. int main() {
  69. fmt::print("Hello, world!\n");
  70. }
  71. **Format a string** (`run <https://godbolt.org/z/oK8h33>`_)
  72. .. code:: c++
  73. std::string s = fmt::format("The answer is {}.", 42);
  74. // s == "The answer is 42."
  75. **Format a string using positional arguments** (`run <https://godbolt.org/z/Yn7Txe>`_)
  76. .. code:: c++
  77. std::string s = fmt::format("I'd rather be {1} than {0}.", "right", "happy");
  78. // s == "I'd rather be happy than right."
  79. **Print chrono durations** (`run <https://godbolt.org/z/K8s4Mc>`_)
  80. .. code:: c++
  81. #include <fmt/chrono.h>
  82. int main() {
  83. using namespace std::literals::chrono_literals;
  84. fmt::print("Default format: {} {}\n", 42s, 100ms);
  85. fmt::print("strftime-like format: {:%H:%M:%S}\n", 3h + 15min + 30s);
  86. }
  87. Output::
  88. Default format: 42s 100ms
  89. strftime-like format: 03:15:30
  90. **Print a container** (`run <https://godbolt.org/z/MjsY7c>`_)
  91. .. code:: c++
  92. #include <vector>
  93. #include <fmt/ranges.h>
  94. int main() {
  95. std::vector<int> v = {1, 2, 3};
  96. fmt::print("{}\n", v);
  97. }
  98. Output::
  99. {1, 2, 3}
  100. **Check a format string at compile time**
  101. .. code:: c++
  102. std::string s = fmt::format(FMT_STRING("{:d}"), "don't panic");
  103. This gives a compile-time error because ``d`` is an invalid format specifier for
  104. a string.
  105. **Write a file from a single thread**
  106. .. code:: c++
  107. #include <fmt/os.h>
  108. int main() {
  109. auto out = fmt::output_file("guide.txt");
  110. out.print("Don't {}", "Panic");
  111. }
  112. This can be `5 to 9 times faster than fprintf
  113. <http://www.zverovich.net/2020/08/04/optimal-file-buffer-size.html>`_.
  114. **Print with colors and text styles**
  115. .. code:: c++
  116. #include <fmt/color.h>
  117. int main() {
  118. fmt::print(fg(fmt::color::crimson) | fmt::emphasis::bold,
  119. "Hello, {}!\n", "world");
  120. fmt::print(fg(fmt::color::floral_white) | bg(fmt::color::slate_gray) |
  121. fmt::emphasis::underline, "Hello, {}!\n", "мир");
  122. fmt::print(fg(fmt::color::steel_blue) | fmt::emphasis::italic,
  123. "Hello, {}!\n", "世界");
  124. }
  125. Output on a modern terminal:
  126. .. image:: https://user-images.githubusercontent.com/
  127. 576385/88485597-d312f600-cf2b-11ea-9cbe-61f535a86e28.png
  128. Benchmarks
  129. ----------
  130. Speed tests
  131. ~~~~~~~~~~~
  132. ================= ============= ===========
  133. Library Method Run Time, s
  134. ================= ============= ===========
  135. libc printf 1.04
  136. libc++ std::ostream 3.05
  137. {fmt} 6.1.1 fmt::print 0.75
  138. Boost Format 1.67 boost::format 7.24
  139. Folly Format folly::format 2.23
  140. ================= ============= ===========
  141. {fmt} is the fastest of the benchmarked methods, ~35% faster than ``printf``.
  142. The above results were generated by building ``tinyformat_test.cpp`` on macOS
  143. 10.14.6 with ``clang++ -O3 -DNDEBUG -DSPEED_TEST -DHAVE_FORMAT``, and taking the
  144. best of three runs. In the test, the format string ``"%0.10f:%04d:%+g:%s:%p:%c:%%\n"``
  145. or equivalent is filled 2,000,000 times with output sent to ``/dev/null``; for
  146. further details refer to the `source
  147. <https://github.com/fmtlib/format-benchmark/blob/master/tinyformat_test.cpp>`_.
  148. {fmt} is up to 20-30x faster than ``std::ostringstream`` and ``sprintf`` on
  149. floating-point formatting (`dtoa-benchmark <https://github.com/fmtlib/dtoa-benchmark>`_)
  150. and faster than `double-conversion <https://github.com/google/double-conversion>`_ and
  151. `ryu <https://github.com/ulfjack/ryu>`_:
  152. .. image:: https://user-images.githubusercontent.com/576385/
  153. 95684665-11719600-0ba8-11eb-8e5b-972ff4e49428.png
  154. :target: https://fmt.dev/unknown_mac64_clang12.0.html
  155. Compile time and code bloat
  156. ~~~~~~~~~~~~~~~~~~~~~~~~~~~
  157. The script `bloat-test.py
  158. <https://github.com/fmtlib/format-benchmark/blob/master/bloat-test.py>`_
  159. from `format-benchmark <https://github.com/fmtlib/format-benchmark>`_
  160. tests compile time and code bloat for nontrivial projects.
  161. It generates 100 translation units and uses ``printf()`` or its alternative
  162. five times in each to simulate a medium sized project. The resulting
  163. executable size and compile time (Apple LLVM version 8.1.0 (clang-802.0.42),
  164. macOS Sierra, best of three) is shown in the following tables.
  165. **Optimized build (-O3)**
  166. ============= =============== ==================== ==================
  167. Method Compile Time, s Executable size, KiB Stripped size, KiB
  168. ============= =============== ==================== ==================
  169. printf 2.6 29 26
  170. printf+string 16.4 29 26
  171. iostreams 31.1 59 55
  172. {fmt} 19.0 37 34
  173. Boost Format 91.9 226 203
  174. Folly Format 115.7 101 88
  175. ============= =============== ==================== ==================
  176. As you can see, {fmt} has 60% less overhead in terms of resulting binary code
  177. size compared to iostreams and comes pretty close to ``printf``. Boost Format
  178. and Folly Format have the largest overheads.
  179. ``printf+string`` is the same as ``printf`` but with extra ``<string>``
  180. include to measure the overhead of the latter.
  181. **Non-optimized build**
  182. ============= =============== ==================== ==================
  183. Method Compile Time, s Executable size, KiB Stripped size, KiB
  184. ============= =============== ==================== ==================
  185. printf 2.2 33 30
  186. printf+string 16.0 33 30
  187. iostreams 28.3 56 52
  188. {fmt} 18.2 59 50
  189. Boost Format 54.1 365 303
  190. Folly Format 79.9 445 430
  191. ============= =============== ==================== ==================
  192. ``libc``, ``lib(std)c++`` and ``libfmt`` are all linked as shared libraries to
  193. compare formatting function overhead only. Boost Format is a
  194. header-only library so it doesn't provide any linkage options.
  195. Running the tests
  196. ~~~~~~~~~~~~~~~~~
  197. Please refer to `Building the library`__ for the instructions on how to build
  198. the library and run the unit tests.
  199. __ https://fmt.dev/latest/usage.html#building-the-library
  200. Benchmarks reside in a separate repository,
  201. `format-benchmarks <https://github.com/fmtlib/format-benchmark>`_,
  202. so to run the benchmarks you first need to clone this repository and
  203. generate Makefiles with CMake::
  204. $ git clone --recursive https://github.com/fmtlib/format-benchmark.git
  205. $ cd format-benchmark
  206. $ cmake .
  207. Then you can run the speed test::
  208. $ make speed-test
  209. or the bloat test::
  210. $ make bloat-test
  211. Projects using this library
  212. ---------------------------
  213. * `0 A.D. <https://play0ad.com/>`_: a free, open-source, cross-platform
  214. real-time strategy game
  215. * `AMPL/MP <https://github.com/ampl/mp>`_:
  216. an open-source library for mathematical programming
  217. * `Aseprite <https://github.com/aseprite/aseprite>`_:
  218. animated sprite editor & pixel art tool
  219. * `AvioBook <https://www.aviobook.aero/en>`_: a comprehensive aircraft
  220. operations suite
  221. * `Blizzard Battle.net <https://battle.net/>`_: an online gaming platform
  222. * `Celestia <https://celestia.space/>`_: real-time 3D visualization of space
  223. * `Ceph <https://ceph.com/>`_: a scalable distributed storage system
  224. * `ccache <https://ccache.dev/>`_: a compiler cache
  225. * `ClickHouse <https://github.com/ClickHouse/ClickHouse>`_: analytical database
  226. management system
  227. * `CUAUV <http://cuauv.org/>`_: Cornell University's autonomous underwater
  228. vehicle
  229. * `Drake <https://drake.mit.edu/>`_: a planning, control, and analysis toolbox
  230. for nonlinear dynamical systems (MIT)
  231. * `Envoy <https://lyft.github.io/envoy/>`_: C++ L7 proxy and communication bus
  232. (Lyft)
  233. * `FiveM <https://fivem.net/>`_: a modification framework for GTA V
  234. * `Folly <https://github.com/facebook/folly>`_: Facebook open-source library
  235. * `HarpyWar/pvpgn <https://github.com/pvpgn/pvpgn-server>`_:
  236. Player vs Player Gaming Network with tweaks
  237. * `KBEngine <https://github.com/kbengine/kbengine>`_: an open-source MMOG server
  238. engine
  239. * `Keypirinha <https://keypirinha.com/>`_: a semantic launcher for Windows
  240. * `Kodi <https://kodi.tv/>`_ (formerly xbmc): home theater software
  241. * `Knuth <https://kth.cash/>`_: high-performance Bitcoin full-node
  242. * `Microsoft Verona <https://github.com/microsoft/verona>`_:
  243. research programming language for concurrent ownership
  244. * `MongoDB <https://mongodb.com/>`_: distributed document database
  245. * `MongoDB Smasher <https://github.com/duckie/mongo_smasher>`_: a small tool to
  246. generate randomized datasets
  247. * `OpenSpace <https://openspaceproject.com/>`_: an open-source
  248. astrovisualization framework
  249. * `PenUltima Online (POL) <https://www.polserver.com/>`_:
  250. an MMO server, compatible with most Ultima Online clients
  251. * `PyTorch <https://github.com/pytorch/pytorch>`_: an open-source machine
  252. learning library
  253. * `quasardb <https://www.quasardb.net/>`_: a distributed, high-performance,
  254. associative database
  255. * `Quill <https://github.com/odygrd/quill>`_: asynchronous low-latency logging library
  256. * `QKW <https://github.com/ravijanjam/qkw>`_: generalizing aliasing to simplify
  257. navigation, and executing complex multi-line terminal command sequences
  258. * `redis-cerberus <https://github.com/HunanTV/redis-cerberus>`_: a Redis cluster
  259. proxy
  260. * `redpanda <https://vectorized.io/redpanda>`_: a 10x faster Kafka® replacement
  261. for mission critical systems written in C++
  262. * `rpclib <http://rpclib.net/>`_: a modern C++ msgpack-RPC server and client
  263. library
  264. * `Salesforce Analytics Cloud
  265. <https://www.salesforce.com/analytics-cloud/overview/>`_:
  266. business intelligence software
  267. * `Scylla <https://www.scylladb.com/>`_: a Cassandra-compatible NoSQL data store
  268. that can handle 1 million transactions per second on a single server
  269. * `Seastar <http://www.seastar-project.org/>`_: an advanced, open-source C++
  270. framework for high-performance server applications on modern hardware
  271. * `spdlog <https://github.com/gabime/spdlog>`_: super fast C++ logging library
  272. * `Stellar <https://www.stellar.org/>`_: financial platform
  273. * `Touch Surgery <https://www.touchsurgery.com/>`_: surgery simulator
  274. * `TrinityCore <https://github.com/TrinityCore/TrinityCore>`_: open-source
  275. MMORPG framework
  276. * `Windows Terminal <https://github.com/microsoft/terminal>`_: the new Windows
  277. terminal
  278. `More... <https://github.com/search?q=fmtlib&type=Code>`_
  279. If you are aware of other projects using this library, please let me know
  280. by `email <mailto:victor.zverovich@gmail.com>`_ or by submitting an
  281. `issue <https://github.com/fmtlib/fmt/issues>`_.
  282. Motivation
  283. ----------
  284. So why yet another formatting library?
  285. There are plenty of methods for doing this task, from standard ones like
  286. the printf family of function and iostreams to Boost Format and FastFormat
  287. libraries. The reason for creating a new library is that every existing
  288. solution that I found either had serious issues or didn't provide
  289. all the features I needed.
  290. printf
  291. ~~~~~~
  292. The good thing about ``printf`` is that it is pretty fast and readily available
  293. being a part of the C standard library. The main drawback is that it
  294. doesn't support user-defined types. ``printf`` also has safety issues although
  295. they are somewhat mitigated with `__attribute__ ((format (printf, ...))
  296. <https://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html>`_ in GCC.
  297. There is a POSIX extension that adds positional arguments required for
  298. `i18n <https://en.wikipedia.org/wiki/Internationalization_and_localization>`_
  299. to ``printf`` but it is not a part of C99 and may not be available on some
  300. platforms.
  301. iostreams
  302. ~~~~~~~~~
  303. The main issue with iostreams is best illustrated with an example:
  304. .. code:: c++
  305. std::cout << std::setprecision(2) << std::fixed << 1.23456 << "\n";
  306. which is a lot of typing compared to printf:
  307. .. code:: c++
  308. printf("%.2f\n", 1.23456);
  309. Matthew Wilson, the author of FastFormat, called this "chevron hell". iostreams
  310. don't support positional arguments by design.
  311. The good part is that iostreams support user-defined types and are safe although
  312. error handling is awkward.
  313. Boost Format
  314. ~~~~~~~~~~~~
  315. This is a very powerful library which supports both ``printf``-like format
  316. strings and positional arguments. Its main drawback is performance. According to
  317. various, benchmarks it is much slower than other methods considered here. Boost
  318. Format also has excessive build times and severe code bloat issues (see
  319. `Benchmarks`_).
  320. FastFormat
  321. ~~~~~~~~~~
  322. This is an interesting library which is fast, safe and has positional arguments.
  323. However, it has significant limitations, citing its author:
  324. Three features that have no hope of being accommodated within the
  325. current design are:
  326. * Leading zeros (or any other non-space padding)
  327. * Octal/hexadecimal encoding
  328. * Runtime width/alignment specification
  329. It is also quite big and has a heavy dependency, STLSoft, which might be too
  330. restrictive for using it in some projects.
  331. Boost Spirit.Karma
  332. ~~~~~~~~~~~~~~~~~~
  333. This is not really a formatting library but I decided to include it here for
  334. completeness. As iostreams, it suffers from the problem of mixing verbatim text
  335. with arguments. The library is pretty fast, but slower on integer formatting
  336. than ``fmt::format_to`` with format string compilation on Karma's own benchmark,
  337. see `Converting a hundred million integers to strings per second
  338. <http://www.zverovich.net/2020/06/13/fast-int-to-string-revisited.html>`_.
  339. License
  340. -------
  341. {fmt} is distributed under the MIT `license
  342. <https://github.com/fmtlib/fmt/blob/master/LICENSE.rst>`_.
  343. Documentation License
  344. ---------------------
  345. The `Format String Syntax <https://fmt.dev/latest/syntax.html>`_
  346. section in the documentation is based on the one from Python `string module
  347. documentation <https://docs.python.org/3/library/string.html#module-string>`_.
  348. For this reason the documentation is distributed under the Python Software
  349. Foundation license available in `doc/python-license.txt
  350. <https://raw.github.com/fmtlib/fmt/master/doc/python-license.txt>`_.
  351. It only applies if you distribute the documentation of {fmt}.
  352. Maintainers
  353. -----------
  354. The {fmt} library is maintained by Victor Zverovich (`vitaut
  355. <https://github.com/vitaut>`_) and Jonathan Müller (`foonathan
  356. <https://github.com/foonathan>`_) with contributions from many other people.
  357. See `Contributors <https://github.com/fmtlib/fmt/graphs/contributors>`_ and
  358. `Releases <https://github.com/fmtlib/fmt/releases>`_ for some of the names.
  359. Let us know if your contribution is not listed or mentioned incorrectly and
  360. we'll make it right.