UNPKG

wio-fmt

Version:

32 lines 22.8 kB
{ "name": "wio-fmt", "description": "", "keywords": [ "wio", "pkg", "fmt", "c++" ], "readme": "{fmt}\n=====\n\n[![image](https://travis-ci.org/fmtlib/fmt.png?branch=master)](https://travis-ci.org/fmtlib/fmt)\n\n[![image](https://ci.appveyor.com/api/projects/status/ehjkiefde6gucy1v)](https://ci.appveyor.com/project/vitaut/fmt)\n\n[![Join the chat at https://gitter.im/fmtlib/fmt](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/fmtlib/fmt)\n\n**{fmt}** is an open-source formatting library for C++. It can be used\nas a safe and fast alternative to (s)printf and IOStreams.\n\n[Documentation](http://fmtlib.net/latest/)\n\nFeatures\n--------\n\n- Replacement-based [format API](http://fmtlib.net/dev/api.html) with\n positional arguments for localization.\n- [Format string syntax](http://fmtlib.net/dev/syntax.html) similar to\n the one of\n [str.format](https://docs.python.org/2/library/stdtypes.html#str.format)\n in Python.\n- Safe [printf\n implementation](http://fmtlib.net/latest/api.html#printf-formatting)\n including the POSIX extension for positional arguments.\n- Implementation of the ISO C++ standards proposal [P0645 Text\n Formatting](http://fmtlib.net/Text%20Formatting.html).\n- Support for user-defined types.\n- High speed: performance of the format API is close to that of\n glibc\\'s [printf](http://en.cppreference.com/w/cpp/io/c/fprintf) and\n better than the performance of IOStreams. See [Speed\n tests](#speed-tests) and [Fast integer to string conversion in\n C++](http://zverovich.net/2013/09/07/integer-to-string-conversion-in-cplusplus.html).\n- Small code size both in terms of source code (the minimum\n configuration consists of just three header files, `core.h`,\n `format.h` and `format-inl.h`) and compiled code. See [Compile time\n and code bloat](#compile-time-and-code-bloat).\n- Reliability: the library has an extensive set of [unit\n tests](https://github.com/fmtlib/fmt/tree/master/test).\n- Safety: the library is fully type safe, errors in format strings can\n be reported at compile time, automatic memory management prevents\n buffer overflow errors.\n- Ease of use: small self-contained code base, no external\n dependencies, permissive BSD\n [license](https://github.com/fmtlib/fmt/blob/master/LICENSE.rst)\n- [Portability](http://fmtlib.net/latest/index.html#portability) with\n consistent output across platforms and support for older compilers.\n- Clean warning-free codebase even on high warning levels\n (`-Wall -Wextra -pedantic`).\n- Support for wide strings.\n- Optional header-only configuration enabled with the\n `FMT_HEADER_ONLY` macro.\n\nSee the [documentation](http://fmtlib.net/latest/) for more details.\n\nExamples\n--------\n\nThis prints `Hello, world!` to stdout:\n\n``` {.sourceCode .c++}\nfmt::print(\"Hello, {}!\", \"world\"); // uses Python-like format string syntax\nfmt::printf(\"Hello, %s!\", \"world\"); // uses printf format string syntax\n```\n\nArguments can be accessed by position and arguments\\' indices can be\nrepeated:\n\n``` {.sourceCode .c++}\nstd::string s = fmt::format(\"{0}{1}{0}\", \"abra\", \"cad\");\n// s == \"abracadabra\"\n```\n\nFormat strings can be checked at compile time:\n\n``` {.sourceCode .c++}\n// test.cc\n#define FMT_STRING_ALIAS 1\n#include \u003cfmt/format.h\u003e\nstd::string s = format(fmt(\"{2}\"), 42);\n```\n\n``` {.sourceCode .}\n$ c++ -Iinclude -std=c++14 test.cc\n...\ntest.cc:4:17: note: in instantiation of function template specialization 'fmt::v5::format\u003cS, int\u003e' requested here\nstd::string s = format(fmt(\"{2}\"), 42);\n ^\ninclude/fmt/core.h:778:19: note: non-constexpr function 'on_error' cannot be used in a constant expression\n ErrorHandler::on_error(message);\n ^\ninclude/fmt/format.h:2226:16: note: in call to '\u0026checker.context_-\u003eon_error(\u0026\"argument index out of range\"[0])'\n context_.on_error(\"argument index out of range\");\n ^\n```\n\n{fmt} can be used as a safe portable replacement for `itoa`\n([godbolt](https://godbolt.org/g/NXmpU4)):\n\n``` {.sourceCode .c++}\nfmt::memory_buffer buf;\nformat_to(buf, \"{}\", 42); // replaces itoa(42, buffer, 10)\nformat_to(buf, \"{:x}\", 42); // replaces itoa(42, buffer, 16)\n// access the string using to_string(buf) or buf.data()\n```\n\nFormatting of user-defined types is supported via a simple [extension\nAPI](http://fmtlib.net/latest/api.html#formatting-user-defined-types):\n\n``` {.sourceCode .c++}\n#include \"fmt/format.h\"\n\nstruct date {\n int year, month, day;\n};\n\ntemplate \u003c\u003e\nstruct fmt::formatter\u003cdate\u003e {\n template \u003ctypename ParseContext\u003e\n constexpr auto parse(ParseContext \u0026ctx) { return ctx.begin(); }\n\n template \u003ctypename FormatContext\u003e\n auto format(const date \u0026d, FormatContext \u0026ctx) {\n return format_to(ctx.out(), \"{}-{}-{}\", d.year, d.month, d.day);\n }\n};\n\nstd::string s = fmt::format(\"The date is {}\", date{2012, 12, 9});\n// s == \"The date is 2012-12-9\"\n```\n\nYou can create your own functions similar to\n[format](http://fmtlib.net/latest/api.html#format) and\n[print](http://fmtlib.net/latest/api.html#print) which take arbitrary\narguments ([godbolt](https://godbolt.org/g/MHjHVf)):\n\n``` {.sourceCode .c++}\n// Prints formatted error message.\nvoid vreport_error(const char *format, fmt::format_args args) {\n fmt::print(\"Error: \");\n fmt::vprint(format, args);\n}\ntemplate \u003ctypename... Args\u003e\nvoid report_error(const char *format, const Args \u0026 ... args) {\n vreport_error(format, fmt::make_format_args(args...));\n}\n\nreport_error(\"file not found: {}\", path);\n```\n\nNote that `vreport_error` is not parameterized on argument types which\ncan improve compile times and reduce code size compared to fully\nparameterized version.\n\nProjects using this library\n---------------------------\n\n- [0 A.D.](http://play0ad.com/): A free, open-source, cross-platform\n real-time strategy game\n- [AMPL/MP](https://github.com/ampl/mp): An open-source library for\n mathematical programming\n- [AvioBook](https://www.aviobook.aero/en): A comprehensive aircraft\n operations suite\n- [Celestia](https://celestia.space/): Real-time 3D visualization of\n space\n- [Ceph](https://ceph.com/): A scalable distributed storage system\n- [CUAUV](http://cuauv.org/): Cornell University\\'s autonomous\n underwater vehicle\n- [HarpyWar/pvpgn](https://github.com/pvpgn/pvpgn-server): Player vs\n Player Gaming Network with tweaks\n- [KBEngine](http://kbengine.org/): An open-source MMOG server engine\n- [Keypirinha](http://keypirinha.com/): A semantic launcher for\n Windows\n- [Kodi](https://kodi.tv/) (formerly xbmc): Home theater software\n- [Lifeline](https://github.com/peter-clark/lifeline): A 2D game\n- [Drake](http://drake.mit.edu/): A planning, control, and analysis\n toolbox for nonlinear dynamical systems (MIT)\n- [Envoy](https://lyft.github.io/envoy/): C++ L7 proxy and\n communication bus (Lyft)\n- [FiveM](https://fivem.net/): a modification framework for GTA V\n- [MongoDB Smasher](https://github.com/duckie/mongo_smasher): A small\n tool to generate randomized datasets\n- [OpenSpace](http://openspaceproject.com/): An open-source\n astrovisualization framework\n- [PenUltima Online (POL)](http://www.polserver.com/): An MMO server,\n compatible with most Ultima Online clients\n- [quasardb](https://www.quasardb.net/): A distributed,\n high-performance, associative database\n- [readpe](https://bitbucket.org/sys_dev/readpe): Read Portable\n Executable\n- [redis-cerberus](https://github.com/HunanTV/redis-cerberus): A Redis\n cluster proxy\n- [rpclib](http://rpclib.net/): A modern C++ msgpack-RPC server and\n client library\n- [Saddy](https://github.com/mamontov-cpp/saddy-graphics-engine-2d):\n Small crossplatform 2D graphic engine\n- [Salesforce Analytics\n Cloud](http://www.salesforce.com/analytics-cloud/overview/):\n Business intelligence software\n- [Scylla](http://www.scylladb.com/): A Cassandra-compatible NoSQL\n data store that can handle 1 million transactions per second on a\n single server\n- [Seastar](http://www.seastar-project.org/): An advanced, open-source\n C++ framework for high-performance server applications on modern\n hardware\n- [spdlog](https://github.com/gabime/spdlog): Super fast C++ logging\n library\n- [Stellar](https://www.stellar.org/): Financial platform\n- [Touch Surgery](https://www.touchsurgery.com/): Surgery simulator\n- [TrinityCore](https://github.com/TrinityCore/TrinityCore):\n Open-source MMORPG framework\n\n[More\\...](https://github.com/search?q=cppformat\u0026type=Code)\n\nIf you are aware of other projects using this library, please let me\nknow by [email](mailto:victor.zverovich@gmail.com) or by submitting an\n[issue](https://github.com/fmtlib/fmt/issues).\n\nMotivation\n----------\n\nSo why yet another formatting library?\n\nThere are plenty of methods for doing this task, from standard ones like\nthe printf family of function and IOStreams to Boost Format library and\nFastFormat. The reason for creating a new library is that every existing\nsolution that I found either had serious issues or didn\\'t provide all\nthe features I needed.\n\n### Printf\n\nThe good thing about printf is that it is pretty fast and readily\navailable being a part of the C standard library. The main drawback is\nthat it doesn\\'t support user-defined types. Printf also has safety\nissues although they are mostly solved with\n[\\_\\_[attribute](http://fmtlib.net/latest/usage.html#building-the-library)\n((format (printf,\n\\...))](http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html) in\nGCC. There is a POSIX extension that adds positional arguments required\nfor\n[i18n](https://en.wikipedia.org/wiki/Internationalization_and_localization)\nto printf but it is not a part of C99 and may not be available on some\nplatforms.\n\n### IOStreams\n\nThe main issue with IOStreams is best illustrated with an example:\n\n``` {.sourceCode .c++}\nstd::cout \u003c\u003c std::setprecision(2) \u003c\u003c std::fixed \u003c\u003c 1.23456 \u003c\u003c \"\\n\";\n```\n\nwhich is a lot of typing compared to printf:\n\n``` {.sourceCode .c++}\nprintf(\"%.2f\\n\", 1.23456);\n```\n\nMatthew Wilson, the author of FastFormat, referred to this situation\nwith IOStreams as \\\"chevron hell\\\". IOStreams doesn\\'t support\npositional arguments by design.\n\nThe good part is that IOStreams supports user-defined types and is safe\nalthough error reporting is awkward.\n\n### Boost Format library\n\nThis is a very powerful library which supports both printf-like format\nstrings and positional arguments. Its main drawback is performance.\nAccording to various benchmarks it is much slower than other methods\nconsidered here. Boost Format also has excessive build times and severe\ncode bloat issues (see [Benchmarks](#benchmarks)).\n\n### FastFormat\n\nThis is an interesting library which is fast, safe and has positional\narguments. However it has significant limitations, citing its author:\n\n\u003e Three features that have no hope of being accommodated within the\n\u003e current design are:\n\u003e\n\u003e - Leading zeros (or any other non-space padding)\n\u003e - Octal/hexadecimal encoding\n\u003e - Runtime width/alignment specification\n\nIt is also quite big and has a heavy dependency, STLSoft, which might be\ntoo restrictive for using it in some projects.\n\n### Loki SafeFormat\n\nSafeFormat is a formatting library which uses printf-like format strings\nand is type safe. It doesn\\'t support user-defined types or positional\narguments. It makes unconventional use of `operator()` for passing\nformat arguments.\n\n### Tinyformat\n\nThis library supports printf-like format strings and is very small and\nfast. Unfortunately it doesn\\'t support positional arguments and\nwrapping it in C++98 is somewhat difficult. Also its performance and\ncode compactness are limited by IOStreams.\n\n### Boost Spirit.Karma\n\nThis is not really a formatting library but I decided to include it here\nfor completeness. As IOStreams it suffers from the problem of mixing\nverbatim text with arguments. The library is pretty fast, but slower on\ninteger formatting than `fmt::Writer` on Karma\\'s own benchmark, see\n[Fast integer to string conversion in\nC++](http://zverovich.net/2013/09/07/integer-to-string-conversion-in-cplusplus.html).\n\nBenchmarks\n----------\n\n### Speed tests\n\nThe following speed tests results were generated by building\n`tinyformat_test.cpp` on Ubuntu GNU/Linux 14.04.1 with\n`g++-4.8.2 -O3 -DSPEED_TEST -DHAVE_FORMAT`, and taking the best of three\nruns. In the test, the format string `\"%0.10f:%04d:%+g:%s:%p:%c:%%\\n\"`\nor equivalent is filled 2000000 times with output sent to `/dev/null`;\nfor further details see the\n[source](https://github.com/fmtlib/format-benchmark/blob/master/tinyformat_test.cpp).\n\n+-------------------+---------------+-------------+\n| Library | Method | Run Time, s |\n+===================+===============+=============+\n| libc | printf | \u003e 1.35 |\n+-------------------+---------------+-------------+\n| libc++ | std::ostream | \u003e 3.42 |\n+-------------------+---------------+-------------+\n| fmt 534bff7 | fmt::print | \u003e 1.56 |\n+-------------------+---------------+-------------+\n| tinyformat 2.0.1 | tfm::printf | \u003e 3.73 |\n+-------------------+---------------+-------------+\n| Boost Format 1.54 | boost::format | \u003e 8.44 |\n+-------------------+---------------+-------------+\n| Folly Format | folly::format | \u003e 2.54 |\n+-------------------+---------------+-------------+\n\nAs you can see `boost::format` is much slower than the alternative\nmethods; this is confirmed by [other\ntests](http://accu.org/index.php/journals/1539). Tinyformat is quite\ngood coming close to IOStreams. Unfortunately tinyformat cannot be\nfaster than the IOStreams because it uses them internally. Performance\nof fmt is close to that of printf, being [faster than printf on integer\nformatting](http://zverovich.net/2013/09/07/integer-to-string-conversion-in-cplusplus.html),\nbut slower on floating-point formatting which dominates this benchmark.\n\n### Compile time and code bloat\n\nThe script\n[bloat-test.py](https://github.com/fmtlib/format-benchmark/blob/master/bloat-test.py)\nfrom [format-benchmark](https://github.com/fmtlib/format-benchmark)\ntests compile time and code bloat for nontrivial projects. It generates\n100 translation units and uses `printf()` or its alternative five times\nin each to simulate a medium sized project. The resulting executable\nsize and compile time (Apple LLVM version 8.1.0 (clang-802.0.42), macOS\nSierra, best of three) is shown in the following tables.\n\n**Optimized build (-O3)**\n\n+---------------+-----------------+----------------------+--------------------+\n| Method | Compile Time, s | Executable size, KiB | Stripped size, KiB |\n+===============+=================+======================+====================+\n| printf | \u003e 2.6 | \u003e 29 | \u003e 26 |\n+---------------+-----------------+----------------------+--------------------+\n| printf+string | \u003e 16.4 | \u003e 29 | \u003e 26 |\n+---------------+-----------------+----------------------+--------------------+\n| IOStreams | \u003e 31.1 | \u003e 59 | \u003e 55 |\n+---------------+-----------------+----------------------+--------------------+\n| fmt | \u003e 19.0 | \u003e 37 | \u003e 34 |\n+---------------+-----------------+----------------------+--------------------+\n| tinyformat | \u003e 44.0 | \u003e 103 | \u003e 97 |\n+---------------+-----------------+----------------------+--------------------+\n| Boost Format | \u003e 91.9 | \u003e 226 | \u003e 203 |\n+---------------+-----------------+----------------------+--------------------+\n| Folly Format | \u003e 115.7 | \u003e 101 | \u003e 88 |\n+---------------+-----------------+----------------------+--------------------+\n\nAs you can see, fmt has 60% less overhead in terms of resulting binary\ncode size compared to IOStreams and comes pretty close to `printf`.\nBoost Format and Folly Format have the largest overheads.\n\n`printf+string` is the same as `printf` but with extra `\u003cstring\u003e`\ninclude to measure the overhead of the latter.\n\n**Non-optimized build**\n\n+---------------+-----------------+----------------------+--------------------+\n| Method | Compile Time, s | Executable size, KiB | Stripped size, KiB |\n+===============+=================+======================+====================+\n| printf | \u003e 2.2 | \u003e 33 | \u003e 30 |\n+---------------+-----------------+----------------------+--------------------+\n| printf+string | \u003e 16.0 | \u003e 33 | \u003e 30 |\n+---------------+-----------------+----------------------+--------------------+\n| IOStreams | \u003e 28.3 | \u003e 56 | \u003e 52 |\n+---------------+-----------------+----------------------+--------------------+\n| fmt | \u003e 18.2 | \u003e 59 | \u003e 50 |\n+---------------+-----------------+----------------------+--------------------+\n| tinyformat | \u003e 32.6 | \u003e 88 | \u003e 82 |\n+---------------+-----------------+----------------------+--------------------+\n| Boost Format | \u003e 54.1 | \u003e 365 | \u003e 303 |\n+---------------+-----------------+----------------------+--------------------+\n| Folly Format | \u003e 79.9 | \u003e 445 | \u003e 430 |\n+---------------+-----------------+----------------------+--------------------+\n\n`libc`, `lib(std)c++` and `libfmt` are all linked as shared libraries to\ncompare formatting function overhead only. Boost Format and tinyformat\nare header-only libraries so they don\\'t provide any linkage options.\n\n### Running the tests\n\nPlease refer to Building the library\\_\\_ for the instructions on how to\nbuild the library and run the unit tests.\n\nBenchmarks reside in a separate repository,\n[format-benchmarks](https://github.com/fmtlib/format-benchmark), so to\nrun the benchmarks you first need to clone this repository and generate\nMakefiles with CMake:\n\n $ git clone --recursive https://github.com/fmtlib/format-benchmark.git\n $ cd format-benchmark\n $ cmake .\n\nThen you can run the speed test:\n\n $ make speed-test\n\nor the bloat test:\n\n $ make bloat-test\n\nFAQ\n---\n\nQ: how can I capture formatting arguments and format them later?\n\nA: use `std::tuple`:\n\n``` {.sourceCode .c++}\ntemplate \u003ctypename... Args\u003e\nauto capture(const Args\u0026... args) {\n return std::make_tuple(args...);\n}\n\nauto print_message = [](const auto\u0026... args) {\n fmt::print(args...);\n};\n\n// Capture and store arguments:\nauto args = capture(\"{} {}\", 42, \"foo\");\n// Do formatting:\nstd::apply(print_message, args);\n```\n\nLicense\n-------\n\nfmt is distributed under the BSD\n[license](https://github.com/fmtlib/fmt/blob/master/LICENSE.rst).\n\nThe [Format String Syntax](http://fmtlib.net/latest/syntax.html) section\nin the documentation is based on the one from Python [string module\ndocumentation](https://docs.python.org/3/library/string.html#module-string)\nadapted for the current library. For this reason the documentation is\ndistributed under the Python Software Foundation license available in\n[doc/python-license.txt](https://raw.github.com/fmtlib/fmt/master/doc/python-license.txt).\nIt only applies if you distribute the documentation of fmt.\n\nAcknowledgments\n---------------\n\nThe fmt library is maintained by Victor Zverovich\n([vitaut](https://github.com/vitaut)) and Jonathan Müller\n([foonathan](https://github.com/foonathan)) with contributions from many\nother people. See\n[Contributors](https://github.com/fmtlib/fmt/graphs/contributors) and\n[Releases](https://github.com/fmtlib/fmt/releases) for some of the\nnames. Let us know if your contribution is not listed or mentioned\nincorrectly and we\\'ll make it right.\n\nThe benchmark section of this readme file and the performance tests are\ntaken from the excellent\n[tinyformat](https://github.com/c42f/tinyformat) library written by\nChris Foster. Boost Format library is acknowledged transitively since it\nhad some influence on tinyformat. Some ideas used in the implementation\nare borrowed from [Loki](http://loki-lib.sourceforge.net/) SafeFormat\nand [Diagnostic\nAPI](http://clang.llvm.org/doxygen/classclang_1_1Diagnostic.html) in\n[Clang](http://clang.llvm.org/). Format string syntax and the\ndocumentation are based on Python\\'s\n[str.format](http://docs.python.org/2/library/stdtypes.html#str.format).\nThanks [Doug Turnbull](https://github.com/softwaredoug) for his valuable\ncomments and contribution to the design of the type-safe API and\n[Gregory Czajkowski](https://github.com/gcflymoto) for implementing\nbinary formatting. Thanks [Ruslan Baratov](https://github.com/ruslo) for\ncomprehensive [comparison of integer formatting\nalgorithms](https://github.com/ruslo/int-dec-format-tests) and useful\ncomments regarding performance, [Boris\nKaul](https://github.com/localvoid) for [C++ counting digits\nbenchmark](https://github.com/localvoid/cxx-benchmark-count-digits).\nThanks to [CarterLi](https://github.com/CarterLi) for contributing\nvarious improvements to the code.\n", "readmeFile": "README.md", "version": "5.3.1", "main": ".wio.js", "dist": { "integrity": "", "shasum": "", "tarball": "", "fileCount": 0, "unpackedSize": 0, "npm-signature": "" }, "scripts": null, "dependencies": {}, "maintainers": null, "contributors": null, "bugs": "", "author": "fmtlib", "license": "BSD-2-Clause", "homepage": "", "repository": "https://github.com/fmtlib/fmt", "ignore-files": null }