README.rst 20 KB

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