diff options
author | orivej <orivej@yandex-team.ru> | 2022-02-10 16:45:01 +0300 |
---|---|---|
committer | Daniil Cherednik <dcherednik@yandex-team.ru> | 2022-02-10 16:45:01 +0300 |
commit | 2d37894b1b037cf24231090eda8589bbb44fb6fc (patch) | |
tree | be835aa92c6248212e705f25388ebafcf84bc7a1 /contrib/libs/fmt | |
parent | 718c552901d703c502ccbefdfc3c9028d608b947 (diff) | |
download | ydb-2d37894b1b037cf24231090eda8589bbb44fb6fc.tar.gz |
Restoring authorship annotation for <orivej@yandex-team.ru>. Commit 2 of 2.
Diffstat (limited to 'contrib/libs/fmt')
60 files changed, 19538 insertions, 19538 deletions
diff --git a/contrib/libs/fmt/CONTRIBUTING.md b/contrib/libs/fmt/CONTRIBUTING.md index 79acec10eb..b82f145069 100644 --- a/contrib/libs/fmt/CONTRIBUTING.md +++ b/contrib/libs/fmt/CONTRIBUTING.md @@ -1,20 +1,20 @@ -Contributing to {fmt} -===================== - -By submitting a pull request or a patch, you represent that you have the right -to license your contribution to the {fmt} project owners and the community, -agree that your contributions are licensed under the {fmt} license, and agree -to future changes to the licensing. - -All C++ code must adhere to [Google C++ Style Guide]( -https://google.github.io/styleguide/cppguide.html) with the following -exceptions: - -* Exceptions are permitted -* snake_case should be used instead of UpperCamelCase for function and type - names - +Contributing to {fmt} +===================== + +By submitting a pull request or a patch, you represent that you have the right +to license your contribution to the {fmt} project owners and the community, +agree that your contributions are licensed under the {fmt} license, and agree +to future changes to the licensing. + +All C++ code must adhere to [Google C++ Style Guide]( +https://google.github.io/styleguide/cppguide.html) with the following +exceptions: + +* Exceptions are permitted +* snake_case should be used instead of UpperCamelCase for function and type + names + All documentation must adhere to the [Google Developer Documentation Style Guide](https://developers.google.com/style). -Thanks for contributing! +Thanks for contributing! diff --git a/contrib/libs/fmt/ChangeLog.rst b/contrib/libs/fmt/ChangeLog.rst index f47746ea14..9c171af050 100644 --- a/contrib/libs/fmt/ChangeLog.rst +++ b/contrib/libs/fmt/ChangeLog.rst @@ -759,2907 +759,2907 @@ `@tohammer (Tobias Hammer) <https://github.com/tohammer>`_, `@0x8000-0000 (Florin Iucha) <https://github.com/0x8000-0000>`_. -6.2.1 - 2020-05-09 ------------------- - -* Fixed ostream support in ``sprintf`` - (`#1631 <https://github.com/fmtlib/fmt/issues/1631>`_). - -* Fixed type detection when using implicit conversion to ``string_view`` and - ostream ``operator<<`` inconsistently - (`#1662 <https://github.com/fmtlib/fmt/issues/1662>`_). - -6.2.0 - 2020-04-05 ------------------- - -* Improved error reporting when trying to format an object of a non-formattable - type: - - .. code:: c++ - - fmt::format("{}", S()); - - now gives:: - - include/fmt/core.h:1015:5: error: static_assert failed due to requirement - 'formattable' "Cannot format argument. To make type T formattable provide a - formatter<T> specialization: - https://fmt.dev/latest/api.html#formatting-user-defined-types" - static_assert( - ^ - ... - note: in instantiation of function template specialization - 'fmt::v6::format<char [3], S, char>' requested here - fmt::format("{}", S()); - ^ - - if ``S`` is not formattable. - +6.2.1 - 2020-05-09 +------------------ + +* Fixed ostream support in ``sprintf`` + (`#1631 <https://github.com/fmtlib/fmt/issues/1631>`_). + +* Fixed type detection when using implicit conversion to ``string_view`` and + ostream ``operator<<`` inconsistently + (`#1662 <https://github.com/fmtlib/fmt/issues/1662>`_). + +6.2.0 - 2020-04-05 +------------------ + +* Improved error reporting when trying to format an object of a non-formattable + type: + + .. code:: c++ + + fmt::format("{}", S()); + + now gives:: + + include/fmt/core.h:1015:5: error: static_assert failed due to requirement + 'formattable' "Cannot format argument. To make type T formattable provide a + formatter<T> specialization: + https://fmt.dev/latest/api.html#formatting-user-defined-types" + static_assert( + ^ + ... + note: in instantiation of function template specialization + 'fmt::v6::format<char [3], S, char>' requested here + fmt::format("{}", S()); + ^ + + if ``S`` is not formattable. + * Reduced the library size by ~10%. - -* Always print decimal point if ``#`` is specified - (`#1476 <https://github.com/fmtlib/fmt/issues/1476>`_, - `#1498 <https://github.com/fmtlib/fmt/issues/1498>`_): - - .. code:: c++ - - fmt::print("{:#.0f}", 42.0); - - now prints ``42.`` - -* Implemented the ``'L'`` specifier for locale-specific numeric formatting to - improve compatibility with ``std::format``. The ``'n'`` specifier is now - deprecated and will be removed in the next major release. - -* Moved OS-specific APIs such as ``windows_error`` from ``fmt/format.h`` to - ``fmt/os.h``. You can define ``FMT_DEPRECATED_INCLUDE_OS`` to automatically - include ``fmt/os.h`` from ``fmt/format.h`` for compatibility but this will be - disabled in the next major release. - -* Added precision overflow detection in floating-point formatting. - -* Implemented detection of invalid use of ``fmt::arg``. - -* Used ``type_identity`` to block unnecessary template argument deduction. - Thanks Tim Song. - -* Improved UTF-8 handling - (`#1109 <https://github.com/fmtlib/fmt/issues/1109>`_): - - .. code:: c++ - - fmt::print("┌{0:─^{2}}┐\n" - "│{1: ^{2}}│\n" - "└{0:─^{2}}┘\n", "", "Привет, мир!", 20); - - now prints:: - - ┌────────────────────┐ - │ Привет, мир! │ - └────────────────────┘ - - on systems that support Unicode. - -* Added experimental dynamic argument storage - (`#1170 <https://github.com/fmtlib/fmt/issues/1170>`_, - `#1584 <https://github.com/fmtlib/fmt/pull/1584>`_): - - .. code:: c++ - - fmt::dynamic_format_arg_store<fmt::format_context> store; - store.push_back("answer"); - store.push_back(42); - fmt::vprint("The {} is {}.\n", store); - - prints:: - - The answer is 42. - - Thanks `@vsolontsov-ll (Vladimir Solontsov) - <https://github.com/vsolontsov-ll>`_. - -* Made ``fmt::join`` accept ``initializer_list`` - (`#1591 <https://github.com/fmtlib/fmt/pull/1591>`_). - Thanks `@Rapotkinnik (Nikolay Rapotkin) <https://github.com/Rapotkinnik>`_. - -* Fixed handling of empty tuples - (`#1588 <https://github.com/fmtlib/fmt/issues/1588>`_). - -* Fixed handling of output iterators in ``format_to_n`` - (`#1506 <https://github.com/fmtlib/fmt/issues/1506>`_). - -* Fixed formatting of ``std::chrono::duration`` types to wide output - (`#1533 <https://github.com/fmtlib/fmt/pull/1533>`_). - Thanks `@zeffy (pilao) <https://github.com/zeffy>`_. - -* Added const ``begin`` and ``end`` overload to buffers - (`#1553 <https://github.com/fmtlib/fmt/pull/1553>`_). - Thanks `@dominicpoeschko <https://github.com/dominicpoeschko>`_. - -* Added the ability to disable floating-point formatting via ``FMT_USE_FLOAT``, - ``FMT_USE_DOUBLE`` and ``FMT_USE_LONG_DOUBLE`` macros for extremely - memory-constrained embedded system - (`#1590 <https://github.com/fmtlib/fmt/pull/1590>`_). - Thanks `@albaguirre (Alberto Aguirre) <https://github.com/albaguirre>`_. - -* Made ``FMT_STRING`` work with ``constexpr`` ``string_view`` - (`#1589 <https://github.com/fmtlib/fmt/pull/1589>`_). - Thanks `@scramsby (Scott Ramsby) <https://github.com/scramsby>`_. - -* Implemented a minor optimization in the format string parser - (`#1560 <https://github.com/fmtlib/fmt/pull/1560>`_). - Thanks `@IkarusDeveloper <https://github.com/IkarusDeveloper>`_. - -* Improved attribute detection - (`#1469 <https://github.com/fmtlib/fmt/pull/1469>`_, - `#1475 <https://github.com/fmtlib/fmt/pull/1475>`_, - `#1576 <https://github.com/fmtlib/fmt/pull/1576>`_). - Thanks `@federico-busato (Federico) <https://github.com/federico-busato>`_, - `@chronoxor (Ivan Shynkarenka) <https://github.com/chronoxor>`_, - `@refnum <https://github.com/refnum>`_. - -* Improved documentation - (`#1481 <https://github.com/fmtlib/fmt/pull/1481>`_, - `#1523 <https://github.com/fmtlib/fmt/pull/1523>`_). - Thanks `@JackBoosY (Jack·Boos·Yu) <https://github.com/JackBoosY>`_, - `@imba-tjd (谭九鼎) <https://github.com/imba-tjd>`_. - -* Fixed symbol visibility on Linux when compiling with ``-fvisibility=hidden`` - (`#1535 <https://github.com/fmtlib/fmt/pull/1535>`_). - Thanks `@milianw (Milian Wolff) <https://github.com/milianw>`_. - -* Implemented various build configuration fixes and improvements - (`#1264 <https://github.com/fmtlib/fmt/issues/1264>`_, - `#1460 <https://github.com/fmtlib/fmt/issues/1460>`_, - `#1534 <https://github.com/fmtlib/fmt/pull/1534>`_, - `#1536 <https://github.com/fmtlib/fmt/issues/1536>`_, - `#1545 <https://github.com/fmtlib/fmt/issues/1545>`_, - `#1546 <https://github.com/fmtlib/fmt/pull/1546>`_, - `#1566 <https://github.com/fmtlib/fmt/issues/1566>`_, - `#1582 <https://github.com/fmtlib/fmt/pull/1582>`_, - `#1597 <https://github.com/fmtlib/fmt/issues/1597>`_, - `#1598 <https://github.com/fmtlib/fmt/pull/1598>`_). - Thanks `@ambitslix (Attila M. Szilagyi) <https://github.com/ambitslix>`_, - `@jwillikers (Jordan Williams) <https://github.com/jwillikers>`_, - `@stac47 (Laurent Stacul) <https://github.com/stac47>`_. - -* Fixed various warnings and compilation issues - (`#1433 <https://github.com/fmtlib/fmt/pull/1433>`_, - `#1461 <https://github.com/fmtlib/fmt/issues/1461>`_, - `#1470 <https://github.com/fmtlib/fmt/pull/1470>`_, - `#1480 <https://github.com/fmtlib/fmt/pull/1480>`_, - `#1485 <https://github.com/fmtlib/fmt/pull/1485>`_, - `#1492 <https://github.com/fmtlib/fmt/pull/1492>`_, - `#1493 <https://github.com/fmtlib/fmt/issues/1493>`_, - `#1504 <https://github.com/fmtlib/fmt/issues/1504>`_, - `#1505 <https://github.com/fmtlib/fmt/pull/1505>`_, - `#1512 <https://github.com/fmtlib/fmt/pull/1512>`_, - `#1515 <https://github.com/fmtlib/fmt/issues/1515>`_, - `#1516 <https://github.com/fmtlib/fmt/pull/1516>`_, - `#1518 <https://github.com/fmtlib/fmt/pull/1518>`_, - `#1519 <https://github.com/fmtlib/fmt/pull/1519>`_, - `#1520 <https://github.com/fmtlib/fmt/pull/1520>`_, - `#1521 <https://github.com/fmtlib/fmt/pull/1521>`_, - `#1522 <https://github.com/fmtlib/fmt/pull/1522>`_, - `#1524 <https://github.com/fmtlib/fmt/issues/1524>`_, - `#1530 <https://github.com/fmtlib/fmt/pull/1530>`_, - `#1531 <https://github.com/fmtlib/fmt/issues/1531>`_, - `#1532 <https://github.com/fmtlib/fmt/pull/1532>`_, - `#1539 <https://github.com/fmtlib/fmt/issues/1539>`_, - `#1547 <https://github.com/fmtlib/fmt/issues/1547>`_, - `#1548 <https://github.com/fmtlib/fmt/issues/1548>`_, - `#1554 <https://github.com/fmtlib/fmt/pull/1554>`_, - `#1567 <https://github.com/fmtlib/fmt/issues/1567>`_, - `#1568 <https://github.com/fmtlib/fmt/pull/1568>`_, - `#1569 <https://github.com/fmtlib/fmt/pull/1569>`_, - `#1571 <https://github.com/fmtlib/fmt/pull/1571>`_, - `#1573 <https://github.com/fmtlib/fmt/pull/1573>`_, - `#1575 <https://github.com/fmtlib/fmt/pull/1575>`_, - `#1581 <https://github.com/fmtlib/fmt/pull/1581>`_, - `#1583 <https://github.com/fmtlib/fmt/issues/1583>`_, - `#1586 <https://github.com/fmtlib/fmt/issues/1586>`_, - `#1587 <https://github.com/fmtlib/fmt/issues/1587>`_, - `#1594 <https://github.com/fmtlib/fmt/issues/1594>`_, - `#1596 <https://github.com/fmtlib/fmt/pull/1596>`_, - `#1604 <https://github.com/fmtlib/fmt/issues/1604>`_, - `#1606 <https://github.com/fmtlib/fmt/pull/1606>`_, - `#1607 <https://github.com/fmtlib/fmt/issues/1607>`_, - `#1609 <https://github.com/fmtlib/fmt/issues/1609>`_). - Thanks `@marti4d (Chris Martin) <https://github.com/marti4d>`_, - `@iPherian <https://github.com/iPherian>`_, - `@parkertomatoes <https://github.com/parkertomatoes>`_, - `@gsjaardema (Greg Sjaardema) <https://github.com/gsjaardema>`_, - `@chronoxor (Ivan Shynkarenka) <https://github.com/chronoxor>`_, - `@DanielaE (Daniela Engert) <https://github.com/DanielaE>`_, - `@torsten48 <https://github.com/torsten48>`_, - `@tohammer (Tobias Hammer) <https://github.com/tohammer>`_, - `@lefticus (Jason Turner) <https://github.com/lefticus>`_, - `@ryusakki (Haise) <https://github.com/ryusakki>`_, - `@adnsv (Alex Denisov) <https://github.com/adnsv>`_, - `@fghzxm <https://github.com/fghzxm>`_, - `@refnum <https://github.com/refnum>`_, - `@pramodk (Pramod Kumbhar) <https://github.com/pramodk>`_, - `@Spirrwell <https://github.com/Spirrwell>`_, - `@scramsby (Scott Ramsby) <https://github.com/scramsby>`_. - -6.1.2 - 2019-12-11 ------------------- - -* Fixed ABI compatibility with ``libfmt.so.6.0.0`` - (`#1471 <https://github.com/fmtlib/fmt/issues/1471>`_). - -* Fixed handling types convertible to ``std::string_view`` - (`#1451 <https://github.com/fmtlib/fmt/pull/1451>`_). - Thanks `@denizevrenci (Deniz Evrenci) <https://github.com/denizevrenci>`_. - -* Made CUDA test an opt-in enabled via the ``FMT_CUDA_TEST`` CMake option. - -* Fixed sign conversion warnings - (`#1440 <https://github.com/fmtlib/fmt/pull/1440>`_). - Thanks `@0x8000-0000 (Florin Iucha) <https://github.com/0x8000-0000>`_. - -6.1.1 - 2019-12-04 ------------------- - -* Fixed shared library build on Windows - (`#1443 <https://github.com/fmtlib/fmt/pull/1443>`_, - `#1445 <https://github.com/fmtlib/fmt/issues/1445>`_, - `#1446 <https://github.com/fmtlib/fmt/pull/1446>`_, - `#1450 <https://github.com/fmtlib/fmt/issues/1450>`_). - Thanks `@egorpugin (Egor Pugin) <https://github.com/egorpugin>`_, - `@bbolli (Beat Bolli) <https://github.com/bbolli>`_. - -* Added a missing decimal point in exponent notation with trailing zeros. - -* Removed deprecated ``format_arg_store::TYPES``. - -6.1.0 - 2019-12-01 ------------------- - -* {fmt} now formats IEEE 754 ``float`` and ``double`` using the shortest decimal - representation with correct rounding by default: - - .. code:: c++ - - #include <cmath> - #include <fmt/core.h> - - int main() { - fmt::print("{}", M_PI); - } - - prints ``3.141592653589793``. - -* Made the fast binary to decimal floating-point formatter the default, - simplified it and improved performance. {fmt} is now 15 times faster than - libc++'s ``std::ostringstream``, 11 times faster than ``printf`` and 10% - faster than double-conversion on `dtoa-benchmark - <https://github.com/fmtlib/dtoa-benchmark>`_: - - ================== ========= ======= - Function Time (ns) Speedup - ================== ========= ======= - ostringstream 1,346.30 1.00x - ostrstream 1,195.74 1.13x - sprintf 995.08 1.35x - doubleconv 99.10 13.59x - fmt 88.34 15.24x - ================== ========= ======= - - .. image:: https://user-images.githubusercontent.com/576385/ - 69767160-cdaca400-112f-11ea-9fc5-347c9f83caad.png - -* {fmt} no longer converts ``float`` arguments to ``double``. In particular this - improves the default (shortest) representation of floats and makes - ``fmt::format`` consistent with ``std::format`` specs - (`#1336 <https://github.com/fmtlib/fmt/issues/1336>`_, - `#1353 <https://github.com/fmtlib/fmt/issues/1353>`_, - `#1360 <https://github.com/fmtlib/fmt/pull/1360>`_, - `#1361 <https://github.com/fmtlib/fmt/pull/1361>`_): - - .. code:: c++ - - fmt::print("{}", 0.1f); - - prints ``0.1`` instead of ``0.10000000149011612``. - - Thanks `@orivej (Orivej Desh) <https://github.com/orivej>`_. - -* Made floating-point formatting output consistent with ``printf``/iostreams - (`#1376 <https://github.com/fmtlib/fmt/issues/1376>`_, - `#1417 <https://github.com/fmtlib/fmt/issues/1417>`_). - -* Added support for 128-bit integers - (`#1287 <https://github.com/fmtlib/fmt/pull/1287>`_): - - .. code:: c++ - - fmt::print("{}", std::numeric_limits<__int128_t>::max()); - - prints ``170141183460469231731687303715884105727``. - - Thanks `@denizevrenci (Deniz Evrenci) <https://github.com/denizevrenci>`_. - -* The overload of ``print`` that takes ``text_style`` is now atomic, i.e. the - output from different threads doesn't interleave - (`#1351 <https://github.com/fmtlib/fmt/pull/1351>`_). - Thanks `@tankiJong (Tanki Zhang) <https://github.com/tankiJong>`_. - -* Made compile time in the header-only mode ~20% faster by reducing the number - of template instantiations. ``wchar_t`` overload of ``vprint`` was moved from - ``fmt/core.h`` to ``fmt/format.h``. - -* Added an overload of ``fmt::join`` that works with tuples - (`#1322 <https://github.com/fmtlib/fmt/issues/1322>`_, - `#1330 <https://github.com/fmtlib/fmt/pull/1330>`_): - - .. code:: c++ - - #include <tuple> - #include <fmt/ranges.h> - - int main() { - std::tuple<char, int, float> t{'a', 1, 2.0f}; - fmt::print("{}", t); - } - - prints ``('a', 1, 2.0)``. - - Thanks `@jeremyong (Jeremy Ong) <https://github.com/jeremyong>`_. - -* Changed formatting of octal zero with prefix from "00" to "0": - - .. code:: c++ - - fmt::print("{:#o}", 0); - - prints ``0``. - -* The locale is now passed to ostream insertion (``<<``) operators - (`#1406 <https://github.com/fmtlib/fmt/pull/1406>`_): - - .. code:: c++ - - #include <fmt/locale.h> - #include <fmt/ostream.h> - - struct S { - double value; - }; - - std::ostream& operator<<(std::ostream& os, S s) { - return os << s.value; - } - - int main() { - auto s = fmt::format(std::locale("fr_FR.UTF-8"), "{}", S{0.42}); - // s == "0,42" - } - - Thanks `@dlaugt (Daniel Laügt) <https://github.com/dlaugt>`_. - -* Locale-specific number formatting now uses grouping - (`#1393 <https://github.com/fmtlib/fmt/issues/1393>`_ - `#1394 <https://github.com/fmtlib/fmt/pull/1394>`_). - Thanks `@skrdaniel <https://github.com/skrdaniel>`_. - -* Fixed handling of types with deleted implicit rvalue conversion to - ``const char**`` (`#1421 <https://github.com/fmtlib/fmt/issues/1421>`_): - - .. code:: c++ - - struct mystring { - operator const char*() const&; - operator const char*() &; - operator const char*() const&& = delete; - operator const char*() && = delete; - }; - mystring str; - fmt::print("{}", str); // now compiles - -* Enums are now mapped to correct underlying types instead of ``int`` - (`#1286 <https://github.com/fmtlib/fmt/pull/1286>`_). - Thanks `@agmt (Egor Seredin) <https://github.com/agmt>`_. - -* Enum classes are no longer implicitly converted to ``int`` - (`#1424 <https://github.com/fmtlib/fmt/issues/1424>`_). - -* Added ``basic_format_parse_context`` for consistency with C++20 - ``std::format`` and deprecated ``basic_parse_context``. - -* Fixed handling of UTF-8 in precision - (`#1389 <https://github.com/fmtlib/fmt/issues/1389>`_, - `#1390 <https://github.com/fmtlib/fmt/pull/1390>`_). - Thanks `@tajtiattila (Attila Tajti) <https://github.com/tajtiattila>`_. - -* {fmt} can now be installed on Linux, macOS and Windows with - `Conda <https://docs.conda.io/en/latest/>`__ using its - `conda-forge <https://conda-forge.org>`__ - `package <https://github.com/conda-forge/fmt-feedstock>`__ - (`#1410 <https://github.com/fmtlib/fmt/pull/1410>`_):: - - conda install -c conda-forge fmt - - Thanks `@tdegeus (Tom de Geus) <https://github.com/tdegeus>`_. - -* Added a CUDA test (`#1285 <https://github.com/fmtlib/fmt/pull/1285>`_, - `#1317 <https://github.com/fmtlib/fmt/pull/1317>`_). - Thanks `@luncliff (Park DongHa) <https://github.com/luncliff>`_ and - `@risa2000 <https://github.com/risa2000>`_. - -* Improved documentation (`#1276 <https://github.com/fmtlib/fmt/pull/1276>`_, - `#1291 <https://github.com/fmtlib/fmt/issues/1291>`_, - `#1296 <https://github.com/fmtlib/fmt/issues/1296>`_, - `#1315 <https://github.com/fmtlib/fmt/pull/1315>`_, - `#1332 <https://github.com/fmtlib/fmt/pull/1332>`_, - `#1337 <https://github.com/fmtlib/fmt/pull/1337>`_, - `#1395 <https://github.com/fmtlib/fmt/issues/1395>`_ - `#1418 <https://github.com/fmtlib/fmt/pull/1418>`_). - Thanks - `@waywardmonkeys (Bruce Mitchener) <https://github.com/waywardmonkeys>`_, - `@pauldreik (Paul Dreik) <https://github.com/pauldreik>`_, - `@jackoalan (Jack Andersen) <https://github.com/jackoalan>`_. - -* Various code improvements - (`#1358 <https://github.com/fmtlib/fmt/pull/1358>`_, - `#1407 <https://github.com/fmtlib/fmt/pull/1407>`_). - Thanks `@orivej (Orivej Desh) <https://github.com/orivej>`_, - `@dpacbach (David P. Sicilia) <https://github.com/dpacbach>`_, - -* Fixed compile-time format string checks for user-defined types - (`#1292 <https://github.com/fmtlib/fmt/issues/1292>`_). - -* Worked around a false positive in ``unsigned-integer-overflow`` sanitizer - (`#1377 <https://github.com/fmtlib/fmt/issues/1377>`_). - -* Fixed various warnings and compilation issues - (`#1273 <https://github.com/fmtlib/fmt/issues/1273>`_, - `#1278 <https://github.com/fmtlib/fmt/pull/1278>`_, - `#1280 <https://github.com/fmtlib/fmt/pull/1280>`_, - `#1281 <https://github.com/fmtlib/fmt/issues/1281>`_, - `#1288 <https://github.com/fmtlib/fmt/issues/1288>`_, - `#1290 <https://github.com/fmtlib/fmt/pull/1290>`_, - `#1301 <https://github.com/fmtlib/fmt/pull/1301>`_, - `#1305 <https://github.com/fmtlib/fmt/issues/1305>`_, - `#1306 <https://github.com/fmtlib/fmt/issues/1306>`_, - `#1309 <https://github.com/fmtlib/fmt/issues/1309>`_, - `#1312 <https://github.com/fmtlib/fmt/pull/1312>`_, - `#1313 <https://github.com/fmtlib/fmt/issues/1313>`_, - `#1316 <https://github.com/fmtlib/fmt/issues/1316>`_, - `#1319 <https://github.com/fmtlib/fmt/issues/1319>`_, - `#1320 <https://github.com/fmtlib/fmt/pull/1320>`_, - `#1326 <https://github.com/fmtlib/fmt/pull/1326>`_, - `#1328 <https://github.com/fmtlib/fmt/pull/1328>`_, - `#1344 <https://github.com/fmtlib/fmt/issues/1344>`_, - `#1345 <https://github.com/fmtlib/fmt/pull/1345>`_, - `#1347 <https://github.com/fmtlib/fmt/pull/1347>`_, - `#1349 <https://github.com/fmtlib/fmt/pull/1349>`_, - `#1354 <https://github.com/fmtlib/fmt/issues/1354>`_, - `#1362 <https://github.com/fmtlib/fmt/issues/1362>`_, - `#1366 <https://github.com/fmtlib/fmt/issues/1366>`_, - `#1364 <https://github.com/fmtlib/fmt/pull/1364>`_, - `#1370 <https://github.com/fmtlib/fmt/pull/1370>`_, - `#1371 <https://github.com/fmtlib/fmt/pull/1371>`_, - `#1385 <https://github.com/fmtlib/fmt/issues/1385>`_, - `#1388 <https://github.com/fmtlib/fmt/issues/1388>`_, - `#1397 <https://github.com/fmtlib/fmt/pull/1397>`_, - `#1414 <https://github.com/fmtlib/fmt/pull/1414>`_, - `#1416 <https://github.com/fmtlib/fmt/pull/1416>`_, - `#1422 <https://github.com/fmtlib/fmt/issues/1422>`_ - `#1427 <https://github.com/fmtlib/fmt/pull/1427>`_, - `#1431 <https://github.com/fmtlib/fmt/issues/1431>`_, - `#1433 <https://github.com/fmtlib/fmt/pull/1433>`_). - Thanks `@hhb <https://github.com/hhb>`_, - `@gsjaardema (Greg Sjaardema) <https://github.com/gsjaardema>`_, - `@gabime (Gabi Melman) <https://github.com/gabime>`_, - `@neheb (Rosen Penev) <https://github.com/neheb>`_, - `@vedranmiletic (Vedran Miletić) <https://github.com/vedranmiletic>`_, - `@dkavolis (Daumantas Kavolis) <https://github.com/dkavolis>`_, - `@mwinterb <https://github.com/mwinterb>`_, - `@orivej (Orivej Desh) <https://github.com/orivej>`_, - `@denizevrenci (Deniz Evrenci) <https://github.com/denizevrenci>`_ - `@leonklingele <https://github.com/leonklingele>`_, - `@chronoxor (Ivan Shynkarenka) <https://github.com/chronoxor>`_, - `@kent-tri <https://github.com/kent-tri>`_, - `@0x8000-0000 (Florin Iucha) <https://github.com/0x8000-0000>`_, - `@marti4d (Chris Martin) <https://github.com/marti4d>`_. - -6.0.0 - 2019-08-26 ------------------- - -* Switched to the `MIT license - <https://github.com/fmtlib/fmt/blob/5a4b24613ba16cc689977c3b5bd8274a3ba1dd1f/LICENSE.rst>`_ - with an optional exception that allows distributing binary code without - attribution. - -* Floating-point formatting is now locale-independent by default: - - .. code:: c++ - - #include <locale> - #include <fmt/core.h> - - int main() { - std::locale::global(std::locale("ru_RU.UTF-8")); - fmt::print("value = {}", 4.2); - } - - prints "value = 4.2" regardless of the locale. - - For locale-specific formatting use the ``n`` specifier: - - .. code:: c++ - - std::locale::global(std::locale("ru_RU.UTF-8")); - fmt::print("value = {:n}", 4.2); - - prints "value = 4,2". - -* Added an experimental Grisu floating-point formatting algorithm - implementation (disabled by default). To enable it compile with the - ``FMT_USE_GRISU`` macro defined to 1: - - .. code:: c++ - - #define FMT_USE_GRISU 1 - #include <fmt/format.h> - - auto s = fmt::format("{}", 4.2); // formats 4.2 using Grisu - - With Grisu enabled, {fmt} is 13x faster than ``std::ostringstream`` (libc++) - and 10x faster than ``sprintf`` on `dtoa-benchmark - <https://github.com/fmtlib/dtoa-benchmark>`_ (`full results - <https://fmt.dev/unknown_mac64_clang10.0.html>`_): - - .. image:: https://user-images.githubusercontent.com/576385/ - 54883977-9fe8c000-4e28-11e9-8bde-272d122e7c52.jpg - -* Separated formatting and parsing contexts for consistency with - `C++20 std::format <http://eel.is/c++draft/format>`_, removing the - undocumented ``basic_format_context::parse_context()`` function. - -* Added `oss-fuzz <https://github.com/google/oss-fuzz>`_ support - (`#1199 <https://github.com/fmtlib/fmt/pull/1199>`_). - Thanks `@pauldreik (Paul Dreik) <https://github.com/pauldreik>`_. - -* ``formatter`` specializations now always take precedence over ``operator<<`` - (`#952 <https://github.com/fmtlib/fmt/issues/952>`_): - - .. code:: c++ - - #include <iostream> - #include <fmt/ostream.h> - - struct S {}; - - std::ostream& operator<<(std::ostream& os, S) { - return os << 1; - } - - template <> - struct fmt::formatter<S> : fmt::formatter<int> { - auto format(S, format_context& ctx) { - return formatter<int>::format(2, ctx); - } - }; - - int main() { - std::cout << S() << "\n"; // prints 1 using operator<< - fmt::print("{}\n", S()); // prints 2 using formatter - } - -* Introduced the experimental ``fmt::compile`` function that does format string - compilation (`#618 <https://github.com/fmtlib/fmt/issues/618>`_, - `#1169 <https://github.com/fmtlib/fmt/issues/1169>`_, - `#1171 <https://github.com/fmtlib/fmt/pull/1171>`_): - - .. code:: c++ - - #include <fmt/compile.h> - - auto f = fmt::compile<int>("{}"); + +* Always print decimal point if ``#`` is specified + (`#1476 <https://github.com/fmtlib/fmt/issues/1476>`_, + `#1498 <https://github.com/fmtlib/fmt/issues/1498>`_): + + .. code:: c++ + + fmt::print("{:#.0f}", 42.0); + + now prints ``42.`` + +* Implemented the ``'L'`` specifier for locale-specific numeric formatting to + improve compatibility with ``std::format``. The ``'n'`` specifier is now + deprecated and will be removed in the next major release. + +* Moved OS-specific APIs such as ``windows_error`` from ``fmt/format.h`` to + ``fmt/os.h``. You can define ``FMT_DEPRECATED_INCLUDE_OS`` to automatically + include ``fmt/os.h`` from ``fmt/format.h`` for compatibility but this will be + disabled in the next major release. + +* Added precision overflow detection in floating-point formatting. + +* Implemented detection of invalid use of ``fmt::arg``. + +* Used ``type_identity`` to block unnecessary template argument deduction. + Thanks Tim Song. + +* Improved UTF-8 handling + (`#1109 <https://github.com/fmtlib/fmt/issues/1109>`_): + + .. code:: c++ + + fmt::print("┌{0:─^{2}}┐\n" + "│{1: ^{2}}│\n" + "└{0:─^{2}}┘\n", "", "Привет, мир!", 20); + + now prints:: + + ┌────────────────────┐ + │ Привет, мир! │ + └────────────────────┘ + + on systems that support Unicode. + +* Added experimental dynamic argument storage + (`#1170 <https://github.com/fmtlib/fmt/issues/1170>`_, + `#1584 <https://github.com/fmtlib/fmt/pull/1584>`_): + + .. code:: c++ + + fmt::dynamic_format_arg_store<fmt::format_context> store; + store.push_back("answer"); + store.push_back(42); + fmt::vprint("The {} is {}.\n", store); + + prints:: + + The answer is 42. + + Thanks `@vsolontsov-ll (Vladimir Solontsov) + <https://github.com/vsolontsov-ll>`_. + +* Made ``fmt::join`` accept ``initializer_list`` + (`#1591 <https://github.com/fmtlib/fmt/pull/1591>`_). + Thanks `@Rapotkinnik (Nikolay Rapotkin) <https://github.com/Rapotkinnik>`_. + +* Fixed handling of empty tuples + (`#1588 <https://github.com/fmtlib/fmt/issues/1588>`_). + +* Fixed handling of output iterators in ``format_to_n`` + (`#1506 <https://github.com/fmtlib/fmt/issues/1506>`_). + +* Fixed formatting of ``std::chrono::duration`` types to wide output + (`#1533 <https://github.com/fmtlib/fmt/pull/1533>`_). + Thanks `@zeffy (pilao) <https://github.com/zeffy>`_. + +* Added const ``begin`` and ``end`` overload to buffers + (`#1553 <https://github.com/fmtlib/fmt/pull/1553>`_). + Thanks `@dominicpoeschko <https://github.com/dominicpoeschko>`_. + +* Added the ability to disable floating-point formatting via ``FMT_USE_FLOAT``, + ``FMT_USE_DOUBLE`` and ``FMT_USE_LONG_DOUBLE`` macros for extremely + memory-constrained embedded system + (`#1590 <https://github.com/fmtlib/fmt/pull/1590>`_). + Thanks `@albaguirre (Alberto Aguirre) <https://github.com/albaguirre>`_. + +* Made ``FMT_STRING`` work with ``constexpr`` ``string_view`` + (`#1589 <https://github.com/fmtlib/fmt/pull/1589>`_). + Thanks `@scramsby (Scott Ramsby) <https://github.com/scramsby>`_. + +* Implemented a minor optimization in the format string parser + (`#1560 <https://github.com/fmtlib/fmt/pull/1560>`_). + Thanks `@IkarusDeveloper <https://github.com/IkarusDeveloper>`_. + +* Improved attribute detection + (`#1469 <https://github.com/fmtlib/fmt/pull/1469>`_, + `#1475 <https://github.com/fmtlib/fmt/pull/1475>`_, + `#1576 <https://github.com/fmtlib/fmt/pull/1576>`_). + Thanks `@federico-busato (Federico) <https://github.com/federico-busato>`_, + `@chronoxor (Ivan Shynkarenka) <https://github.com/chronoxor>`_, + `@refnum <https://github.com/refnum>`_. + +* Improved documentation + (`#1481 <https://github.com/fmtlib/fmt/pull/1481>`_, + `#1523 <https://github.com/fmtlib/fmt/pull/1523>`_). + Thanks `@JackBoosY (Jack·Boos·Yu) <https://github.com/JackBoosY>`_, + `@imba-tjd (谭九鼎) <https://github.com/imba-tjd>`_. + +* Fixed symbol visibility on Linux when compiling with ``-fvisibility=hidden`` + (`#1535 <https://github.com/fmtlib/fmt/pull/1535>`_). + Thanks `@milianw (Milian Wolff) <https://github.com/milianw>`_. + +* Implemented various build configuration fixes and improvements + (`#1264 <https://github.com/fmtlib/fmt/issues/1264>`_, + `#1460 <https://github.com/fmtlib/fmt/issues/1460>`_, + `#1534 <https://github.com/fmtlib/fmt/pull/1534>`_, + `#1536 <https://github.com/fmtlib/fmt/issues/1536>`_, + `#1545 <https://github.com/fmtlib/fmt/issues/1545>`_, + `#1546 <https://github.com/fmtlib/fmt/pull/1546>`_, + `#1566 <https://github.com/fmtlib/fmt/issues/1566>`_, + `#1582 <https://github.com/fmtlib/fmt/pull/1582>`_, + `#1597 <https://github.com/fmtlib/fmt/issues/1597>`_, + `#1598 <https://github.com/fmtlib/fmt/pull/1598>`_). + Thanks `@ambitslix (Attila M. Szilagyi) <https://github.com/ambitslix>`_, + `@jwillikers (Jordan Williams) <https://github.com/jwillikers>`_, + `@stac47 (Laurent Stacul) <https://github.com/stac47>`_. + +* Fixed various warnings and compilation issues + (`#1433 <https://github.com/fmtlib/fmt/pull/1433>`_, + `#1461 <https://github.com/fmtlib/fmt/issues/1461>`_, + `#1470 <https://github.com/fmtlib/fmt/pull/1470>`_, + `#1480 <https://github.com/fmtlib/fmt/pull/1480>`_, + `#1485 <https://github.com/fmtlib/fmt/pull/1485>`_, + `#1492 <https://github.com/fmtlib/fmt/pull/1492>`_, + `#1493 <https://github.com/fmtlib/fmt/issues/1493>`_, + `#1504 <https://github.com/fmtlib/fmt/issues/1504>`_, + `#1505 <https://github.com/fmtlib/fmt/pull/1505>`_, + `#1512 <https://github.com/fmtlib/fmt/pull/1512>`_, + `#1515 <https://github.com/fmtlib/fmt/issues/1515>`_, + `#1516 <https://github.com/fmtlib/fmt/pull/1516>`_, + `#1518 <https://github.com/fmtlib/fmt/pull/1518>`_, + `#1519 <https://github.com/fmtlib/fmt/pull/1519>`_, + `#1520 <https://github.com/fmtlib/fmt/pull/1520>`_, + `#1521 <https://github.com/fmtlib/fmt/pull/1521>`_, + `#1522 <https://github.com/fmtlib/fmt/pull/1522>`_, + `#1524 <https://github.com/fmtlib/fmt/issues/1524>`_, + `#1530 <https://github.com/fmtlib/fmt/pull/1530>`_, + `#1531 <https://github.com/fmtlib/fmt/issues/1531>`_, + `#1532 <https://github.com/fmtlib/fmt/pull/1532>`_, + `#1539 <https://github.com/fmtlib/fmt/issues/1539>`_, + `#1547 <https://github.com/fmtlib/fmt/issues/1547>`_, + `#1548 <https://github.com/fmtlib/fmt/issues/1548>`_, + `#1554 <https://github.com/fmtlib/fmt/pull/1554>`_, + `#1567 <https://github.com/fmtlib/fmt/issues/1567>`_, + `#1568 <https://github.com/fmtlib/fmt/pull/1568>`_, + `#1569 <https://github.com/fmtlib/fmt/pull/1569>`_, + `#1571 <https://github.com/fmtlib/fmt/pull/1571>`_, + `#1573 <https://github.com/fmtlib/fmt/pull/1573>`_, + `#1575 <https://github.com/fmtlib/fmt/pull/1575>`_, + `#1581 <https://github.com/fmtlib/fmt/pull/1581>`_, + `#1583 <https://github.com/fmtlib/fmt/issues/1583>`_, + `#1586 <https://github.com/fmtlib/fmt/issues/1586>`_, + `#1587 <https://github.com/fmtlib/fmt/issues/1587>`_, + `#1594 <https://github.com/fmtlib/fmt/issues/1594>`_, + `#1596 <https://github.com/fmtlib/fmt/pull/1596>`_, + `#1604 <https://github.com/fmtlib/fmt/issues/1604>`_, + `#1606 <https://github.com/fmtlib/fmt/pull/1606>`_, + `#1607 <https://github.com/fmtlib/fmt/issues/1607>`_, + `#1609 <https://github.com/fmtlib/fmt/issues/1609>`_). + Thanks `@marti4d (Chris Martin) <https://github.com/marti4d>`_, + `@iPherian <https://github.com/iPherian>`_, + `@parkertomatoes <https://github.com/parkertomatoes>`_, + `@gsjaardema (Greg Sjaardema) <https://github.com/gsjaardema>`_, + `@chronoxor (Ivan Shynkarenka) <https://github.com/chronoxor>`_, + `@DanielaE (Daniela Engert) <https://github.com/DanielaE>`_, + `@torsten48 <https://github.com/torsten48>`_, + `@tohammer (Tobias Hammer) <https://github.com/tohammer>`_, + `@lefticus (Jason Turner) <https://github.com/lefticus>`_, + `@ryusakki (Haise) <https://github.com/ryusakki>`_, + `@adnsv (Alex Denisov) <https://github.com/adnsv>`_, + `@fghzxm <https://github.com/fghzxm>`_, + `@refnum <https://github.com/refnum>`_, + `@pramodk (Pramod Kumbhar) <https://github.com/pramodk>`_, + `@Spirrwell <https://github.com/Spirrwell>`_, + `@scramsby (Scott Ramsby) <https://github.com/scramsby>`_. + +6.1.2 - 2019-12-11 +------------------ + +* Fixed ABI compatibility with ``libfmt.so.6.0.0`` + (`#1471 <https://github.com/fmtlib/fmt/issues/1471>`_). + +* Fixed handling types convertible to ``std::string_view`` + (`#1451 <https://github.com/fmtlib/fmt/pull/1451>`_). + Thanks `@denizevrenci (Deniz Evrenci) <https://github.com/denizevrenci>`_. + +* Made CUDA test an opt-in enabled via the ``FMT_CUDA_TEST`` CMake option. + +* Fixed sign conversion warnings + (`#1440 <https://github.com/fmtlib/fmt/pull/1440>`_). + Thanks `@0x8000-0000 (Florin Iucha) <https://github.com/0x8000-0000>`_. + +6.1.1 - 2019-12-04 +------------------ + +* Fixed shared library build on Windows + (`#1443 <https://github.com/fmtlib/fmt/pull/1443>`_, + `#1445 <https://github.com/fmtlib/fmt/issues/1445>`_, + `#1446 <https://github.com/fmtlib/fmt/pull/1446>`_, + `#1450 <https://github.com/fmtlib/fmt/issues/1450>`_). + Thanks `@egorpugin (Egor Pugin) <https://github.com/egorpugin>`_, + `@bbolli (Beat Bolli) <https://github.com/bbolli>`_. + +* Added a missing decimal point in exponent notation with trailing zeros. + +* Removed deprecated ``format_arg_store::TYPES``. + +6.1.0 - 2019-12-01 +------------------ + +* {fmt} now formats IEEE 754 ``float`` and ``double`` using the shortest decimal + representation with correct rounding by default: + + .. code:: c++ + + #include <cmath> + #include <fmt/core.h> + + int main() { + fmt::print("{}", M_PI); + } + + prints ``3.141592653589793``. + +* Made the fast binary to decimal floating-point formatter the default, + simplified it and improved performance. {fmt} is now 15 times faster than + libc++'s ``std::ostringstream``, 11 times faster than ``printf`` and 10% + faster than double-conversion on `dtoa-benchmark + <https://github.com/fmtlib/dtoa-benchmark>`_: + + ================== ========= ======= + Function Time (ns) Speedup + ================== ========= ======= + ostringstream 1,346.30 1.00x + ostrstream 1,195.74 1.13x + sprintf 995.08 1.35x + doubleconv 99.10 13.59x + fmt 88.34 15.24x + ================== ========= ======= + + .. image:: https://user-images.githubusercontent.com/576385/ + 69767160-cdaca400-112f-11ea-9fc5-347c9f83caad.png + +* {fmt} no longer converts ``float`` arguments to ``double``. In particular this + improves the default (shortest) representation of floats and makes + ``fmt::format`` consistent with ``std::format`` specs + (`#1336 <https://github.com/fmtlib/fmt/issues/1336>`_, + `#1353 <https://github.com/fmtlib/fmt/issues/1353>`_, + `#1360 <https://github.com/fmtlib/fmt/pull/1360>`_, + `#1361 <https://github.com/fmtlib/fmt/pull/1361>`_): + + .. code:: c++ + + fmt::print("{}", 0.1f); + + prints ``0.1`` instead of ``0.10000000149011612``. + + Thanks `@orivej (Orivej Desh) <https://github.com/orivej>`_. + +* Made floating-point formatting output consistent with ``printf``/iostreams + (`#1376 <https://github.com/fmtlib/fmt/issues/1376>`_, + `#1417 <https://github.com/fmtlib/fmt/issues/1417>`_). + +* Added support for 128-bit integers + (`#1287 <https://github.com/fmtlib/fmt/pull/1287>`_): + + .. code:: c++ + + fmt::print("{}", std::numeric_limits<__int128_t>::max()); + + prints ``170141183460469231731687303715884105727``. + + Thanks `@denizevrenci (Deniz Evrenci) <https://github.com/denizevrenci>`_. + +* The overload of ``print`` that takes ``text_style`` is now atomic, i.e. the + output from different threads doesn't interleave + (`#1351 <https://github.com/fmtlib/fmt/pull/1351>`_). + Thanks `@tankiJong (Tanki Zhang) <https://github.com/tankiJong>`_. + +* Made compile time in the header-only mode ~20% faster by reducing the number + of template instantiations. ``wchar_t`` overload of ``vprint`` was moved from + ``fmt/core.h`` to ``fmt/format.h``. + +* Added an overload of ``fmt::join`` that works with tuples + (`#1322 <https://github.com/fmtlib/fmt/issues/1322>`_, + `#1330 <https://github.com/fmtlib/fmt/pull/1330>`_): + + .. code:: c++ + + #include <tuple> + #include <fmt/ranges.h> + + int main() { + std::tuple<char, int, float> t{'a', 1, 2.0f}; + fmt::print("{}", t); + } + + prints ``('a', 1, 2.0)``. + + Thanks `@jeremyong (Jeremy Ong) <https://github.com/jeremyong>`_. + +* Changed formatting of octal zero with prefix from "00" to "0": + + .. code:: c++ + + fmt::print("{:#o}", 0); + + prints ``0``. + +* The locale is now passed to ostream insertion (``<<``) operators + (`#1406 <https://github.com/fmtlib/fmt/pull/1406>`_): + + .. code:: c++ + + #include <fmt/locale.h> + #include <fmt/ostream.h> + + struct S { + double value; + }; + + std::ostream& operator<<(std::ostream& os, S s) { + return os << s.value; + } + + int main() { + auto s = fmt::format(std::locale("fr_FR.UTF-8"), "{}", S{0.42}); + // s == "0,42" + } + + Thanks `@dlaugt (Daniel Laügt) <https://github.com/dlaugt>`_. + +* Locale-specific number formatting now uses grouping + (`#1393 <https://github.com/fmtlib/fmt/issues/1393>`_ + `#1394 <https://github.com/fmtlib/fmt/pull/1394>`_). + Thanks `@skrdaniel <https://github.com/skrdaniel>`_. + +* Fixed handling of types with deleted implicit rvalue conversion to + ``const char**`` (`#1421 <https://github.com/fmtlib/fmt/issues/1421>`_): + + .. code:: c++ + + struct mystring { + operator const char*() const&; + operator const char*() &; + operator const char*() const&& = delete; + operator const char*() && = delete; + }; + mystring str; + fmt::print("{}", str); // now compiles + +* Enums are now mapped to correct underlying types instead of ``int`` + (`#1286 <https://github.com/fmtlib/fmt/pull/1286>`_). + Thanks `@agmt (Egor Seredin) <https://github.com/agmt>`_. + +* Enum classes are no longer implicitly converted to ``int`` + (`#1424 <https://github.com/fmtlib/fmt/issues/1424>`_). + +* Added ``basic_format_parse_context`` for consistency with C++20 + ``std::format`` and deprecated ``basic_parse_context``. + +* Fixed handling of UTF-8 in precision + (`#1389 <https://github.com/fmtlib/fmt/issues/1389>`_, + `#1390 <https://github.com/fmtlib/fmt/pull/1390>`_). + Thanks `@tajtiattila (Attila Tajti) <https://github.com/tajtiattila>`_. + +* {fmt} can now be installed on Linux, macOS and Windows with + `Conda <https://docs.conda.io/en/latest/>`__ using its + `conda-forge <https://conda-forge.org>`__ + `package <https://github.com/conda-forge/fmt-feedstock>`__ + (`#1410 <https://github.com/fmtlib/fmt/pull/1410>`_):: + + conda install -c conda-forge fmt + + Thanks `@tdegeus (Tom de Geus) <https://github.com/tdegeus>`_. + +* Added a CUDA test (`#1285 <https://github.com/fmtlib/fmt/pull/1285>`_, + `#1317 <https://github.com/fmtlib/fmt/pull/1317>`_). + Thanks `@luncliff (Park DongHa) <https://github.com/luncliff>`_ and + `@risa2000 <https://github.com/risa2000>`_. + +* Improved documentation (`#1276 <https://github.com/fmtlib/fmt/pull/1276>`_, + `#1291 <https://github.com/fmtlib/fmt/issues/1291>`_, + `#1296 <https://github.com/fmtlib/fmt/issues/1296>`_, + `#1315 <https://github.com/fmtlib/fmt/pull/1315>`_, + `#1332 <https://github.com/fmtlib/fmt/pull/1332>`_, + `#1337 <https://github.com/fmtlib/fmt/pull/1337>`_, + `#1395 <https://github.com/fmtlib/fmt/issues/1395>`_ + `#1418 <https://github.com/fmtlib/fmt/pull/1418>`_). + Thanks + `@waywardmonkeys (Bruce Mitchener) <https://github.com/waywardmonkeys>`_, + `@pauldreik (Paul Dreik) <https://github.com/pauldreik>`_, + `@jackoalan (Jack Andersen) <https://github.com/jackoalan>`_. + +* Various code improvements + (`#1358 <https://github.com/fmtlib/fmt/pull/1358>`_, + `#1407 <https://github.com/fmtlib/fmt/pull/1407>`_). + Thanks `@orivej (Orivej Desh) <https://github.com/orivej>`_, + `@dpacbach (David P. Sicilia) <https://github.com/dpacbach>`_, + +* Fixed compile-time format string checks for user-defined types + (`#1292 <https://github.com/fmtlib/fmt/issues/1292>`_). + +* Worked around a false positive in ``unsigned-integer-overflow`` sanitizer + (`#1377 <https://github.com/fmtlib/fmt/issues/1377>`_). + +* Fixed various warnings and compilation issues + (`#1273 <https://github.com/fmtlib/fmt/issues/1273>`_, + `#1278 <https://github.com/fmtlib/fmt/pull/1278>`_, + `#1280 <https://github.com/fmtlib/fmt/pull/1280>`_, + `#1281 <https://github.com/fmtlib/fmt/issues/1281>`_, + `#1288 <https://github.com/fmtlib/fmt/issues/1288>`_, + `#1290 <https://github.com/fmtlib/fmt/pull/1290>`_, + `#1301 <https://github.com/fmtlib/fmt/pull/1301>`_, + `#1305 <https://github.com/fmtlib/fmt/issues/1305>`_, + `#1306 <https://github.com/fmtlib/fmt/issues/1306>`_, + `#1309 <https://github.com/fmtlib/fmt/issues/1309>`_, + `#1312 <https://github.com/fmtlib/fmt/pull/1312>`_, + `#1313 <https://github.com/fmtlib/fmt/issues/1313>`_, + `#1316 <https://github.com/fmtlib/fmt/issues/1316>`_, + `#1319 <https://github.com/fmtlib/fmt/issues/1319>`_, + `#1320 <https://github.com/fmtlib/fmt/pull/1320>`_, + `#1326 <https://github.com/fmtlib/fmt/pull/1326>`_, + `#1328 <https://github.com/fmtlib/fmt/pull/1328>`_, + `#1344 <https://github.com/fmtlib/fmt/issues/1344>`_, + `#1345 <https://github.com/fmtlib/fmt/pull/1345>`_, + `#1347 <https://github.com/fmtlib/fmt/pull/1347>`_, + `#1349 <https://github.com/fmtlib/fmt/pull/1349>`_, + `#1354 <https://github.com/fmtlib/fmt/issues/1354>`_, + `#1362 <https://github.com/fmtlib/fmt/issues/1362>`_, + `#1366 <https://github.com/fmtlib/fmt/issues/1366>`_, + `#1364 <https://github.com/fmtlib/fmt/pull/1364>`_, + `#1370 <https://github.com/fmtlib/fmt/pull/1370>`_, + `#1371 <https://github.com/fmtlib/fmt/pull/1371>`_, + `#1385 <https://github.com/fmtlib/fmt/issues/1385>`_, + `#1388 <https://github.com/fmtlib/fmt/issues/1388>`_, + `#1397 <https://github.com/fmtlib/fmt/pull/1397>`_, + `#1414 <https://github.com/fmtlib/fmt/pull/1414>`_, + `#1416 <https://github.com/fmtlib/fmt/pull/1416>`_, + `#1422 <https://github.com/fmtlib/fmt/issues/1422>`_ + `#1427 <https://github.com/fmtlib/fmt/pull/1427>`_, + `#1431 <https://github.com/fmtlib/fmt/issues/1431>`_, + `#1433 <https://github.com/fmtlib/fmt/pull/1433>`_). + Thanks `@hhb <https://github.com/hhb>`_, + `@gsjaardema (Greg Sjaardema) <https://github.com/gsjaardema>`_, + `@gabime (Gabi Melman) <https://github.com/gabime>`_, + `@neheb (Rosen Penev) <https://github.com/neheb>`_, + `@vedranmiletic (Vedran Miletić) <https://github.com/vedranmiletic>`_, + `@dkavolis (Daumantas Kavolis) <https://github.com/dkavolis>`_, + `@mwinterb <https://github.com/mwinterb>`_, + `@orivej (Orivej Desh) <https://github.com/orivej>`_, + `@denizevrenci (Deniz Evrenci) <https://github.com/denizevrenci>`_ + `@leonklingele <https://github.com/leonklingele>`_, + `@chronoxor (Ivan Shynkarenka) <https://github.com/chronoxor>`_, + `@kent-tri <https://github.com/kent-tri>`_, + `@0x8000-0000 (Florin Iucha) <https://github.com/0x8000-0000>`_, + `@marti4d (Chris Martin) <https://github.com/marti4d>`_. + +6.0.0 - 2019-08-26 +------------------ + +* Switched to the `MIT license + <https://github.com/fmtlib/fmt/blob/5a4b24613ba16cc689977c3b5bd8274a3ba1dd1f/LICENSE.rst>`_ + with an optional exception that allows distributing binary code without + attribution. + +* Floating-point formatting is now locale-independent by default: + + .. code:: c++ + + #include <locale> + #include <fmt/core.h> + + int main() { + std::locale::global(std::locale("ru_RU.UTF-8")); + fmt::print("value = {}", 4.2); + } + + prints "value = 4.2" regardless of the locale. + + For locale-specific formatting use the ``n`` specifier: + + .. code:: c++ + + std::locale::global(std::locale("ru_RU.UTF-8")); + fmt::print("value = {:n}", 4.2); + + prints "value = 4,2". + +* Added an experimental Grisu floating-point formatting algorithm + implementation (disabled by default). To enable it compile with the + ``FMT_USE_GRISU`` macro defined to 1: + + .. code:: c++ + + #define FMT_USE_GRISU 1 + #include <fmt/format.h> + + auto s = fmt::format("{}", 4.2); // formats 4.2 using Grisu + + With Grisu enabled, {fmt} is 13x faster than ``std::ostringstream`` (libc++) + and 10x faster than ``sprintf`` on `dtoa-benchmark + <https://github.com/fmtlib/dtoa-benchmark>`_ (`full results + <https://fmt.dev/unknown_mac64_clang10.0.html>`_): + + .. image:: https://user-images.githubusercontent.com/576385/ + 54883977-9fe8c000-4e28-11e9-8bde-272d122e7c52.jpg + +* Separated formatting and parsing contexts for consistency with + `C++20 std::format <http://eel.is/c++draft/format>`_, removing the + undocumented ``basic_format_context::parse_context()`` function. + +* Added `oss-fuzz <https://github.com/google/oss-fuzz>`_ support + (`#1199 <https://github.com/fmtlib/fmt/pull/1199>`_). + Thanks `@pauldreik (Paul Dreik) <https://github.com/pauldreik>`_. + +* ``formatter`` specializations now always take precedence over ``operator<<`` + (`#952 <https://github.com/fmtlib/fmt/issues/952>`_): + + .. code:: c++ + + #include <iostream> + #include <fmt/ostream.h> + + struct S {}; + + std::ostream& operator<<(std::ostream& os, S) { + return os << 1; + } + + template <> + struct fmt::formatter<S> : fmt::formatter<int> { + auto format(S, format_context& ctx) { + return formatter<int>::format(2, ctx); + } + }; + + int main() { + std::cout << S() << "\n"; // prints 1 using operator<< + fmt::print("{}\n", S()); // prints 2 using formatter + } + +* Introduced the experimental ``fmt::compile`` function that does format string + compilation (`#618 <https://github.com/fmtlib/fmt/issues/618>`_, + `#1169 <https://github.com/fmtlib/fmt/issues/1169>`_, + `#1171 <https://github.com/fmtlib/fmt/pull/1171>`_): + + .. code:: c++ + + #include <fmt/compile.h> + + auto f = fmt::compile<int>("{}"); std::string s = fmt::format(f, 42); // can be called multiple times to // format different values - // s == "42" - - It moves the cost of parsing a format string outside of the format function - which can be beneficial when identically formatting many objects of the same - types. Thanks `@stryku (Mateusz Janek) <https://github.com/stryku>`_. - + // s == "42" + + It moves the cost of parsing a format string outside of the format function + which can be beneficial when identically formatting many objects of the same + types. Thanks `@stryku (Mateusz Janek) <https://github.com/stryku>`_. + * Added experimental ``%`` format specifier that formats floating-point values as percentages (`#1060 <https://github.com/fmtlib/fmt/pull/1060>`_, - `#1069 <https://github.com/fmtlib/fmt/pull/1069>`_, - `#1071 <https://github.com/fmtlib/fmt/pull/1071>`_): - - .. code:: c++ - - auto s = fmt::format("{:.1%}", 0.42); // s == "42.0%" - - Thanks `@gawain-bolton (Gawain Bolton) <https://github.com/gawain-bolton>`_. - -* Implemented precision for floating-point durations - (`#1004 <https://github.com/fmtlib/fmt/issues/1004>`_, - `#1012 <https://github.com/fmtlib/fmt/pull/1012>`_): - - .. code:: c++ - - auto s = fmt::format("{:.1}", std::chrono::duration<double>(1.234)); - // s == 1.2s - - Thanks `@DanielaE (Daniela Engert) <https://github.com/DanielaE>`_. - -* Implemented ``chrono`` format specifiers ``%Q`` and ``%q`` that give the value - and the unit respectively (`#1019 <https://github.com/fmtlib/fmt/pull/1019>`_): - - .. code:: c++ - - auto value = fmt::format("{:%Q}", 42s); // value == "42" - auto unit = fmt::format("{:%q}", 42s); // unit == "s" - - Thanks `@DanielaE (Daniela Engert) <https://github.com/DanielaE>`_. - -* Fixed handling of dynamic width in chrono formatter: - - .. code:: c++ - - auto s = fmt::format("{0:{1}%H:%M:%S}", std::chrono::seconds(12345), 12); - // ^ width argument index ^ width - // s == "03:25:45 " - - Thanks Howard Hinnant. - -* Removed deprecated ``fmt/time.h``. Use ``fmt/chrono.h`` instead. - -* Added ``fmt::format`` and ``fmt::vformat`` overloads that take ``text_style`` - (`#993 <https://github.com/fmtlib/fmt/issues/993>`_, - `#994 <https://github.com/fmtlib/fmt/pull/994>`_): - - .. code:: c++ - - #include <fmt/color.h> - - std::string message = fmt::format(fmt::emphasis::bold | fg(fmt::color::red), - "The answer is {}.", 42); - - Thanks `@Naios (Denis Blank) <https://github.com/Naios>`_. - -* Removed the deprecated color API (``print_colored``). Use the new API, namely - ``print`` overloads that take ``text_style`` instead. - -* Made ``std::unique_ptr`` and ``std::shared_ptr`` formattable as pointers via - ``fmt::ptr`` (`#1121 <https://github.com/fmtlib/fmt/pull/1121>`_): - - .. code:: c++ - - std::unique_ptr<int> p = ...; - fmt::print("{}", fmt::ptr(p)); // prints p as a pointer - - Thanks `@sighingnow (Tao He) <https://github.com/sighingnow>`_. - -* Made ``print`` and ``vprint`` report I/O errors - (`#1098 <https://github.com/fmtlib/fmt/issues/1098>`_, - `#1099 <https://github.com/fmtlib/fmt/pull/1099>`_). - Thanks `@BillyDonahue (Billy Donahue) <https://github.com/BillyDonahue>`_. - -* Marked deprecated APIs with the ``[[deprecated]]`` attribute and removed - internal uses of deprecated APIs - (`#1022 <https://github.com/fmtlib/fmt/pull/1022>`_). - Thanks `@eliaskosunen (Elias Kosunen) <https://github.com/eliaskosunen>`_. - -* Modernized the codebase using more C++11 features and removing workarounds. - Most importantly, ``buffer_context`` is now an alias template, so - use ``buffer_context<T>`` instead of ``buffer_context<T>::type``. - These features require GCC 4.8 or later. - -* ``formatter`` specializations now always take precedence over implicit - conversions to ``int`` and the undocumented ``convert_to_int`` trait - is now deprecated. - -* Moved the undocumented ``basic_writer``, ``writer``, and ``wwriter`` types - to the ``internal`` namespace. - -* Removed deprecated ``basic_format_context::begin()``. Use ``out()`` instead. - -* Disallowed passing the result of ``join`` as an lvalue to prevent misuse. - -* Refactored the undocumented structs that represent parsed format specifiers - to simplify the API and allow multibyte fill. - -* Moved SFINAE to template parameters to reduce symbol sizes. - -* Switched to ``fputws`` for writing wide strings so that it's no longer - required to call ``_setmode`` on Windows - (`#1229 <https://github.com/fmtlib/fmt/issues/1229>`_, - `#1243 <https://github.com/fmtlib/fmt/pull/1243>`_). - Thanks `@jackoalan (Jack Andersen) <https://github.com/jackoalan>`_. - -* Improved literal-based API - (`#1254 <https://github.com/fmtlib/fmt/pull/1254>`_). - Thanks `@sylveon (Charles Milette) <https://github.com/sylveon>`_. - -* Added support for exotic platforms without ``uintptr_t`` such as IBM i - (AS/400) which has 128-bit pointers and only 64-bit integers - (`#1059 <https://github.com/fmtlib/fmt/issues/1059>`_). - -* Added `Sublime Text syntax highlighting config - <https://github.com/fmtlib/fmt/blob/master/support/C%2B%2B.sublime-syntax>`_ - (`#1037 <https://github.com/fmtlib/fmt/issues/1037>`_). - Thanks `@Kronuz (Germán Méndez Bravo) <https://github.com/Kronuz>`_. - -* Added the ``FMT_ENFORCE_COMPILE_STRING`` macro to enforce the use of - compile-time format strings - (`#1231 <https://github.com/fmtlib/fmt/pull/1231>`_). - Thanks `@jackoalan (Jack Andersen) <https://github.com/jackoalan>`_. - -* Stopped setting ``CMAKE_BUILD_TYPE`` if {fmt} is a subproject - (`#1081 <https://github.com/fmtlib/fmt/issues/1081>`_). - -* Various build improvements - (`#1039 <https://github.com/fmtlib/fmt/pull/1039>`_, - `#1078 <https://github.com/fmtlib/fmt/pull/1078>`_, - `#1091 <https://github.com/fmtlib/fmt/pull/1091>`_, - `#1103 <https://github.com/fmtlib/fmt/pull/1103>`_, - `#1177 <https://github.com/fmtlib/fmt/pull/1177>`_). - Thanks `@luncliff (Park DongHa) <https://github.com/luncliff>`_, - `@jasonszang (Jason Shuo Zang) <https://github.com/jasonszang>`_, - `@olafhering (Olaf Hering) <https://github.com/olafhering>`_, - `@Lecetem <https://github.com/Lectem>`_, - `@pauldreik (Paul Dreik) <https://github.com/pauldreik>`_. - -* Improved documentation - (`#1049 <https://github.com/fmtlib/fmt/issues/1049>`_, - `#1051 <https://github.com/fmtlib/fmt/pull/1051>`_, - `#1083 <https://github.com/fmtlib/fmt/pull/1083>`_, - `#1113 <https://github.com/fmtlib/fmt/pull/1113>`_, - `#1114 <https://github.com/fmtlib/fmt/pull/1114>`_, - `#1146 <https://github.com/fmtlib/fmt/issues/1146>`_, - `#1180 <https://github.com/fmtlib/fmt/issues/1180>`_, - `#1250 <https://github.com/fmtlib/fmt/pull/1250>`_, - `#1252 <https://github.com/fmtlib/fmt/pull/1252>`_, - `#1265 <https://github.com/fmtlib/fmt/pull/1265>`_). - Thanks `@mikelui (Michael Lui) <https://github.com/mikelui>`_, - `@foonathan (Jonathan Müller) <https://github.com/foonathan>`_, - `@BillyDonahue (Billy Donahue) <https://github.com/BillyDonahue>`_, - `@jwakely (Jonathan Wakely) <https://github.com/jwakely>`_, - `@kaisbe (Kais Ben Salah) <https://github.com/kaisbe>`_, - `@sdebionne (Samuel Debionne) <https://github.com/sdebionne>`_. - -* Fixed ambiguous formatter specialization in ``fmt/ranges.h`` - (`#1123 <https://github.com/fmtlib/fmt/issues/1123>`_). - -* Fixed formatting of a non-empty ``std::filesystem::path`` which is an - infinitely deep range of its components - (`#1268 <https://github.com/fmtlib/fmt/issues/1268>`_). - -* Fixed handling of general output iterators when formatting characters - (`#1056 <https://github.com/fmtlib/fmt/issues/1056>`_, - `#1058 <https://github.com/fmtlib/fmt/pull/1058>`_). - Thanks `@abolz (Alexander Bolz) <https://github.com/abolz>`_. - -* Fixed handling of output iterators in ``formatter`` specialization for - ranges (`#1064 <https://github.com/fmtlib/fmt/issues/1064>`_). - -* Fixed handling of exotic character types - (`#1188 <https://github.com/fmtlib/fmt/issues/1188>`_). - -* Made chrono formatting work with exceptions disabled - (`#1062 <https://github.com/fmtlib/fmt/issues/1062>`_). - -* Fixed DLL visibility issues - (`#1134 <https://github.com/fmtlib/fmt/pull/1134>`_, - `#1147 <https://github.com/fmtlib/fmt/pull/1147>`_). - Thanks `@denchat <https://github.com/denchat>`_. - -* Disabled the use of UDL template extension on GCC 9 - (`#1148 <https://github.com/fmtlib/fmt/issues/1148>`_). - -* Removed misplaced ``format`` compile-time checks from ``printf`` - (`#1173 <https://github.com/fmtlib/fmt/issues/1173>`_). - -* Fixed issues in the experimental floating-point formatter - (`#1072 <https://github.com/fmtlib/fmt/issues/1072>`_, - `#1129 <https://github.com/fmtlib/fmt/issues/1129>`_, - `#1153 <https://github.com/fmtlib/fmt/issues/1153>`_, - `#1155 <https://github.com/fmtlib/fmt/pull/1155>`_, - `#1210 <https://github.com/fmtlib/fmt/issues/1210>`_, - `#1222 <https://github.com/fmtlib/fmt/issues/1222>`_). - Thanks `@alabuzhev (Alex Alabuzhev) <https://github.com/alabuzhev>`_. - -* Fixed bugs discovered by fuzzing or during fuzzing integration - (`#1124 <https://github.com/fmtlib/fmt/issues/1124>`_, - `#1127 <https://github.com/fmtlib/fmt/issues/1127>`_, - `#1132 <https://github.com/fmtlib/fmt/issues/1132>`_, - `#1135 <https://github.com/fmtlib/fmt/pull/1135>`_, - `#1136 <https://github.com/fmtlib/fmt/issues/1136>`_, - `#1141 <https://github.com/fmtlib/fmt/issues/1141>`_, - `#1142 <https://github.com/fmtlib/fmt/issues/1142>`_, - `#1178 <https://github.com/fmtlib/fmt/issues/1178>`_, - `#1179 <https://github.com/fmtlib/fmt/issues/1179>`_, - `#1194 <https://github.com/fmtlib/fmt/issues/1194>`_). - Thanks `@pauldreik (Paul Dreik) <https://github.com/pauldreik>`_. - -* Fixed building tests on FreeBSD and Hurd - (`#1043 <https://github.com/fmtlib/fmt/issues/1043>`_). - Thanks `@jackyf (Eugene V. Lyubimkin) <https://github.com/jackyf>`_. - -* Fixed various warnings and compilation issues - (`#998 <https://github.com/fmtlib/fmt/pull/998>`_, - `#1006 <https://github.com/fmtlib/fmt/pull/1006>`_, - `#1008 <https://github.com/fmtlib/fmt/issues/1008>`_, - `#1011 <https://github.com/fmtlib/fmt/issues/1011>`_, - `#1025 <https://github.com/fmtlib/fmt/issues/1025>`_, - `#1027 <https://github.com/fmtlib/fmt/pull/1027>`_, - `#1028 <https://github.com/fmtlib/fmt/pull/1028>`_, - `#1029 <https://github.com/fmtlib/fmt/pull/1029>`_, - `#1030 <https://github.com/fmtlib/fmt/pull/1030>`_, - `#1031 <https://github.com/fmtlib/fmt/pull/1031>`_, - `#1054 <https://github.com/fmtlib/fmt/pull/1054>`_, - `#1063 <https://github.com/fmtlib/fmt/issues/1063>`_, - `#1068 <https://github.com/fmtlib/fmt/pull/1068>`_, - `#1074 <https://github.com/fmtlib/fmt/pull/1074>`_, - `#1075 <https://github.com/fmtlib/fmt/pull/1075>`_, - `#1079 <https://github.com/fmtlib/fmt/pull/1079>`_, - `#1086 <https://github.com/fmtlib/fmt/pull/1086>`_, - `#1088 <https://github.com/fmtlib/fmt/issues/1088>`_, - `#1089 <https://github.com/fmtlib/fmt/pull/1089>`_, - `#1094 <https://github.com/fmtlib/fmt/pull/1094>`_, - `#1101 <https://github.com/fmtlib/fmt/issues/1101>`_, - `#1102 <https://github.com/fmtlib/fmt/pull/1102>`_, - `#1105 <https://github.com/fmtlib/fmt/issues/1105>`_, - `#1107 <https://github.com/fmtlib/fmt/pull/1107>`_, - `#1115 <https://github.com/fmtlib/fmt/issues/1115>`_, - `#1117 <https://github.com/fmtlib/fmt/issues/1117>`_, - `#1118 <https://github.com/fmtlib/fmt/issues/1118>`_, - `#1120 <https://github.com/fmtlib/fmt/issues/1120>`_, - `#1123 <https://github.com/fmtlib/fmt/issues/1123>`_, - `#1139 <https://github.com/fmtlib/fmt/pull/1139>`_, - `#1140 <https://github.com/fmtlib/fmt/issues/1140>`_, - `#1143 <https://github.com/fmtlib/fmt/issues/1143>`_, - `#1144 <https://github.com/fmtlib/fmt/pull/1144>`_, - `#1150 <https://github.com/fmtlib/fmt/pull/1150>`_, - `#1151 <https://github.com/fmtlib/fmt/pull/1151>`_, - `#1152 <https://github.com/fmtlib/fmt/issues/1152>`_, - `#1154 <https://github.com/fmtlib/fmt/issues/1154>`_, - `#1156 <https://github.com/fmtlib/fmt/issues/1156>`_, - `#1159 <https://github.com/fmtlib/fmt/pull/1159>`_, - `#1175 <https://github.com/fmtlib/fmt/issues/1175>`_, - `#1181 <https://github.com/fmtlib/fmt/issues/1181>`_, - `#1186 <https://github.com/fmtlib/fmt/issues/1186>`_, - `#1187 <https://github.com/fmtlib/fmt/pull/1187>`_, - `#1191 <https://github.com/fmtlib/fmt/pull/1191>`_, - `#1197 <https://github.com/fmtlib/fmt/issues/1197>`_, - `#1200 <https://github.com/fmtlib/fmt/issues/1200>`_, - `#1203 <https://github.com/fmtlib/fmt/issues/1203>`_, - `#1205 <https://github.com/fmtlib/fmt/issues/1205>`_, - `#1206 <https://github.com/fmtlib/fmt/pull/1206>`_, - `#1213 <https://github.com/fmtlib/fmt/issues/1213>`_, - `#1214 <https://github.com/fmtlib/fmt/issues/1214>`_, - `#1217 <https://github.com/fmtlib/fmt/pull/1217>`_, - `#1228 <https://github.com/fmtlib/fmt/issues/1228>`_, - `#1230 <https://github.com/fmtlib/fmt/pull/1230>`_, - `#1232 <https://github.com/fmtlib/fmt/issues/1232>`_, - `#1235 <https://github.com/fmtlib/fmt/pull/1235>`_, - `#1236 <https://github.com/fmtlib/fmt/pull/1236>`_, - `#1240 <https://github.com/fmtlib/fmt/issues/1240>`_). - Thanks `@DanielaE (Daniela Engert) <https://github.com/DanielaE>`_, - `@mwinterb <https://github.com/mwinterb>`_, - `@eliaskosunen (Elias Kosunen) <https://github.com/eliaskosunen>`_, - `@morinmorin <https://github.com/morinmorin>`_, - `@ricco19 (Brian Ricciardelli) <https://github.com/ricco19>`_, - `@waywardmonkeys (Bruce Mitchener) <https://github.com/waywardmonkeys>`_, - `@chronoxor (Ivan Shynkarenka) <https://github.com/chronoxor>`_, - `@remyabel <https://github.com/remyabel>`_, - `@pauldreik (Paul Dreik) <https://github.com/pauldreik>`_, - `@gsjaardema (Greg Sjaardema) <https://github.com/gsjaardema>`_, - `@rcane (Ronny Krüger) <https://github.com/rcane>`_, - `@mocabe <https://github.com/mocabe>`_, - `@denchat <https://github.com/denchat>`_, - `@cjdb (Christopher Di Bella) <https://github.com/cjdb>`_, - `@HazardyKnusperkeks (Björn Schäpers) <https://github.com/HazardyKnusperkeks>`_, - `@vedranmiletic (Vedran Miletić) <https://github.com/vedranmiletic>`_, - `@jackoalan (Jack Andersen) <https://github.com/jackoalan>`_, - `@DaanDeMeyer (Daan De Meyer) <https://github.com/DaanDeMeyer>`_, - `@starkmapper (Mark Stapper) <https://github.com/starkmapper>`_. - -5.3.0 - 2018-12-28 ------------------- - -* Introduced experimental chrono formatting support: - - .. code:: c++ - - #include <fmt/chrono.h> - - int main() { - using namespace std::literals::chrono_literals; - fmt::print("Default format: {} {}\n", 42s, 100ms); - fmt::print("strftime-like format: {:%H:%M:%S}\n", 3h + 15min + 30s); - } - - prints:: - - Default format: 42s 100ms - strftime-like format: 03:15:30 - -* Added experimental support for emphasis (bold, italic, underline, - strikethrough), colored output to a file stream, and improved colored - formatting API - (`#961 <https://github.com/fmtlib/fmt/pull/961>`_, - `#967 <https://github.com/fmtlib/fmt/pull/967>`_, - `#973 <https://github.com/fmtlib/fmt/pull/973>`_): - - .. code:: c++ - - #include <fmt/color.h> - - int main() { - print(fg(fmt::color::crimson) | fmt::emphasis::bold, - "Hello, {}!\n", "world"); - print(fg(fmt::color::floral_white) | bg(fmt::color::slate_gray) | - fmt::emphasis::underline, "Hello, {}!\n", "мир"); - print(fg(fmt::color::steel_blue) | fmt::emphasis::italic, - "Hello, {}!\n", "世界"); - } - - prints the following on modern terminals with RGB color support: - - .. image:: https://user-images.githubusercontent.com/576385/ - 50405788-b66e7500-076e-11e9-9592-7324d1f951d8.png - - Thanks `@Rakete1111 (Nicolas) <https://github.com/Rakete1111>`_. - -* Added support for 4-bit terminal colors - (`#968 <https://github.com/fmtlib/fmt/issues/968>`_, - `#974 <https://github.com/fmtlib/fmt/pull/974>`_) - - .. code:: c++ - - #include <fmt/color.h> - - int main() { - print(fg(fmt::terminal_color::red), "stop\n"); - } - - Note that these colors vary by terminal: - - .. image:: https://user-images.githubusercontent.com/576385/ - 50405925-dbfc7e00-0770-11e9-9b85-333fab0af9ac.png - - Thanks `@Rakete1111 (Nicolas) <https://github.com/Rakete1111>`_. - -* Parameterized formatting functions on the type of the format string - (`#880 <https://github.com/fmtlib/fmt/issues/880>`_, - `#881 <https://github.com/fmtlib/fmt/pull/881>`_, - `#883 <https://github.com/fmtlib/fmt/pull/883>`_, - `#885 <https://github.com/fmtlib/fmt/pull/885>`_, - `#897 <https://github.com/fmtlib/fmt/pull/897>`_, - `#920 <https://github.com/fmtlib/fmt/issues/920>`_). - Any object of type ``S`` that has an overloaded ``to_string_view(const S&)`` - returning ``fmt::string_view`` can be used as a format string: - - .. code:: c++ - - namespace my_ns { - inline string_view to_string_view(const my_string& s) { - return {s.data(), s.length()}; - } - } - - std::string message = fmt::format(my_string("The answer is {}."), 42); - - Thanks `@DanielaE (Daniela Engert) <https://github.com/DanielaE>`_. - -* Made ``std::string_view`` work as a format string - (`#898 <https://github.com/fmtlib/fmt/pull/898>`_): - - .. code:: c++ - - auto message = fmt::format(std::string_view("The answer is {}."), 42); - - Thanks `@DanielaE (Daniela Engert) <https://github.com/DanielaE>`_. - -* Added wide string support to compile-time format string checks - (`#924 <https://github.com/fmtlib/fmt/pull/924>`_): - - .. code:: c++ - - print(fmt(L"{:f}"), 42); // compile-time error: invalid type specifier - - Thanks `@XZiar <https://github.com/XZiar>`_. - -* Made colored print functions work with wide strings - (`#867 <https://github.com/fmtlib/fmt/pull/867>`_): - - .. code:: c++ - - #include <fmt/color.h> - - int main() { - print(fg(fmt::color::red), L"{}\n", 42); - } - - Thanks `@DanielaE (Daniela Engert) <https://github.com/DanielaE>`_. - -* Introduced experimental Unicode support - (`#628 <https://github.com/fmtlib/fmt/issues/628>`_, - `#891 <https://github.com/fmtlib/fmt/pull/891>`_): - - .. code:: c++ - - using namespace fmt::literals; - auto s = fmt::format("{:*^5}"_u, "🤡"_u); // s == "**🤡**"_u - -* Improved locale support: - - .. code:: c++ - - #include <fmt/locale.h> - - struct numpunct : std::numpunct<char> { - protected: - char do_thousands_sep() const override { return '~'; } - }; - - std::locale loc; - auto s = fmt::format(std::locale(loc, new numpunct()), "{:n}", 1234567); - // s == "1~234~567" - -* Constrained formatting functions on proper iterator types - (`#921 <https://github.com/fmtlib/fmt/pull/921>`_). - Thanks `@DanielaE (Daniela Engert) <https://github.com/DanielaE>`_. - -* Added ``make_printf_args`` and ``make_wprintf_args`` functions - (`#934 <https://github.com/fmtlib/fmt/pull/934>`_). - Thanks `@tnovotny <https://github.com/tnovotny>`_. - -* Deprecated ``fmt::visit``, ``parse_context``, and ``wparse_context``. - Use ``fmt::visit_format_arg``, ``format_parse_context``, and - ``wformat_parse_context`` instead. - -* Removed undocumented ``basic_fixed_buffer`` which has been superseded by the - iterator-based API - (`#873 <https://github.com/fmtlib/fmt/issues/873>`_, - `#902 <https://github.com/fmtlib/fmt/pull/902>`_). - Thanks `@superfunc (hollywood programmer) <https://github.com/superfunc>`_. - -* Disallowed repeated leading zeros in an argument ID: - - .. code:: c++ - - fmt::print("{000}", 42); // error - -* Reintroduced support for gcc 4.4. - -* Fixed compilation on platforms with exotic ``double`` - (`#878 <https://github.com/fmtlib/fmt/issues/878>`_). - -* Improved documentation - (`#164 <https://github.com/fmtlib/fmt/issues/164>`_, - `#877 <https://github.com/fmtlib/fmt/issues/877>`_, - `#901 <https://github.com/fmtlib/fmt/pull/901>`_, - `#906 <https://github.com/fmtlib/fmt/pull/906>`_, - `#979 <https://github.com/fmtlib/fmt/pull/979>`_). - Thanks `@kookjr (Mathew Cucuzella) <https://github.com/kookjr>`_, - `@DarkDimius (Dmitry Petrashko) <https://github.com/DarkDimius>`_, - `@HecticSerenity <https://github.com/HecticSerenity>`_. - -* Added pkgconfig support which makes it easier to consume the library from - meson and other build systems - (`#916 <https://github.com/fmtlib/fmt/pull/916>`_). - Thanks `@colemickens (Cole Mickens) <https://github.com/colemickens>`_. - -* Various build improvements - (`#909 <https://github.com/fmtlib/fmt/pull/909>`_, - `#926 <https://github.com/fmtlib/fmt/pull/926>`_, - `#937 <https://github.com/fmtlib/fmt/pull/937>`_, - `#953 <https://github.com/fmtlib/fmt/pull/953>`_, - `#959 <https://github.com/fmtlib/fmt/pull/959>`_). - Thanks `@tchaikov (Kefu Chai) <https://github.com/tchaikov>`_, - `@luncliff (Park DongHa) <https://github.com/luncliff>`_, - `@AndreasSchoenle (Andreas Schönle) <https://github.com/AndreasSchoenle>`_, - `@hotwatermorning <https://github.com/hotwatermorning>`_, - `@Zefz (JohanJansen) <https://github.com/Zefz>`_. - -* Improved ``string_view`` construction performance - (`#914 <https://github.com/fmtlib/fmt/pull/914>`_). - Thanks `@gabime (Gabi Melman) <https://github.com/gabime>`_. - -* Fixed non-matching char types - (`#895 <https://github.com/fmtlib/fmt/pull/895>`_). - Thanks `@DanielaE (Daniela Engert) <https://github.com/DanielaE>`_. - -* Fixed ``format_to_n`` with ``std::back_insert_iterator`` - (`#913 <https://github.com/fmtlib/fmt/pull/913>`_). - Thanks `@DanielaE (Daniela Engert) <https://github.com/DanielaE>`_. - -* Fixed locale-dependent formatting - (`#905 <https://github.com/fmtlib/fmt/issues/905>`_). - -* Fixed various compiler warnings and errors - (`#882 <https://github.com/fmtlib/fmt/pull/882>`_, - `#886 <https://github.com/fmtlib/fmt/pull/886>`_, - `#933 <https://github.com/fmtlib/fmt/pull/933>`_, - `#941 <https://github.com/fmtlib/fmt/pull/941>`_, - `#931 <https://github.com/fmtlib/fmt/issues/931>`_, - `#943 <https://github.com/fmtlib/fmt/pull/943>`_, - `#954 <https://github.com/fmtlib/fmt/pull/954>`_, - `#956 <https://github.com/fmtlib/fmt/pull/956>`_, - `#962 <https://github.com/fmtlib/fmt/pull/962>`_, - `#965 <https://github.com/fmtlib/fmt/issues/965>`_, - `#977 <https://github.com/fmtlib/fmt/issues/977>`_, - `#983 <https://github.com/fmtlib/fmt/pull/983>`_, - `#989 <https://github.com/fmtlib/fmt/pull/989>`_). - Thanks `@Luthaf (Guillaume Fraux) <https://github.com/Luthaf>`_, - `@stevenhoving (Steven Hoving) <https://github.com/stevenhoving>`_, - `@christinaa (Kristina Brooks) <https://github.com/christinaa>`_, - `@lgritz (Larry Gritz) <https://github.com/lgritz>`_, - `@DanielaE (Daniela Engert) <https://github.com/DanielaE>`_, - `@0x8000-0000 (Sign Bit) <https://github.com/0x8000-0000>`_, - `@liuping1997 <https://github.com/liuping1997>`_. - -5.2.1 - 2018-09-21 ------------------- - -* Fixed ``visit`` lookup issues on gcc 7 & 8 - (`#870 <https://github.com/fmtlib/fmt/pull/870>`_). - Thanks `@medithe <https://github.com/medithe>`_. - -* Fixed linkage errors on older gcc. - -* Prevented ``fmt/range.h`` from specializing ``fmt::basic_string_view`` - (`#865 <https://github.com/fmtlib/fmt/issues/865>`_, - `#868 <https://github.com/fmtlib/fmt/pull/868>`_). - Thanks `@hhggit (dual) <https://github.com/hhggit>`_. - -* Improved error message when formatting unknown types - (`#872 <https://github.com/fmtlib/fmt/pull/872>`_). - Thanks `@foonathan (Jonathan Müller) <https://github.com/foonathan>`_, - -* Disabled templated user-defined literals when compiled under nvcc - (`#875 <https://github.com/fmtlib/fmt/pull/875>`_). - Thanks `@CandyGumdrop (Candy Gumdrop) <https://github.com/CandyGumdrop>`_, - -* Fixed ``format_to`` formatting to ``wmemory_buffer`` - (`#874 <https://github.com/fmtlib/fmt/issues/874>`_). - -5.2.0 - 2018-09-13 ------------------- - -* Optimized format string parsing and argument processing which resulted in up - to 5x speed up on long format strings and significant performance boost on - various benchmarks. For example, version 5.2 is 2.22x faster than 5.1 on - decimal integer formatting with ``format_to`` (macOS, clang-902.0.39.2): - - ================== ======= ======= - Method Time, s Speedup - ================== ======= ======= - fmt::format 5.1 0.58 - fmt::format 5.2 0.35 1.66x - fmt::format_to 5.1 0.51 - fmt::format_to 5.2 0.23 2.22x - sprintf 0.71 - std::to_string 1.01 - std::stringstream 1.73 - ================== ======= ======= - -* Changed the ``fmt`` macro from opt-out to opt-in to prevent name collisions. - To enable it define the ``FMT_STRING_ALIAS`` macro to 1 before including - ``fmt/format.h``: - - .. code:: c++ - - #define FMT_STRING_ALIAS 1 - #include <fmt/format.h> - std::string answer = format(fmt("{}"), 42); - -* Added compile-time format string checks to ``format_to`` overload that takes - ``fmt::memory_buffer`` (`#783 <https://github.com/fmtlib/fmt/issues/783>`_): - - .. code:: c++ - - fmt::memory_buffer buf; - // Compile-time error: invalid type specifier. - fmt::format_to(buf, fmt("{:d}"), "foo"); - -* Moved experimental color support to ``fmt/color.h`` and enabled the - new API by default. The old API can be enabled by defining the - ``FMT_DEPRECATED_COLORS`` macro. - -* Added formatting support for types explicitly convertible to - ``fmt::string_view``: - - .. code:: c++ - - struct foo { - explicit operator fmt::string_view() const { return "foo"; } - }; - auto s = format("{}", foo()); - - In particular, this makes formatting function work with - ``folly::StringPiece``. - -* Implemented preliminary support for ``char*_t`` by replacing the ``format`` - function overloads with a single function template parameterized on the string - type. - -* Added support for dynamic argument lists - (`#814 <https://github.com/fmtlib/fmt/issues/814>`_, - `#819 <https://github.com/fmtlib/fmt/pull/819>`_). - Thanks `@MikePopoloski (Michael Popoloski) - <https://github.com/MikePopoloski>`_. - -* Reduced executable size overhead for embedded targets using newlib nano by - making locale dependency optional - (`#839 <https://github.com/fmtlib/fmt/pull/839>`_). - Thanks `@teajay-fr (Thomas Benard) <https://github.com/teajay-fr>`_. - -* Keep ``noexcept`` specifier when exceptions are disabled - (`#801 <https://github.com/fmtlib/fmt/issues/801>`_, - `#810 <https://github.com/fmtlib/fmt/pull/810>`_). - Thanks `@qis (Alexej Harm) <https://github.com/qis>`_. - -* Fixed formatting of user-defined types providing ``operator<<`` with - ``format_to_n`` - (`#806 <https://github.com/fmtlib/fmt/pull/806>`_). - Thanks `@mkurdej (Marek Kurdej) <https://github.com/mkurdej>`_. - -* Fixed dynamic linkage of new symbols - (`#808 <https://github.com/fmtlib/fmt/issues/808>`_). - -* Fixed global initialization issue - (`#807 <https://github.com/fmtlib/fmt/issues/807>`_): - - .. code:: c++ - - // This works on compilers with constexpr support. - static const std::string answer = fmt::format("{}", 42); - -* Fixed various compiler warnings and errors - (`#804 <https://github.com/fmtlib/fmt/pull/804>`_, - `#809 <https://github.com/fmtlib/fmt/issues/809>`_, - `#811 <https://github.com/fmtlib/fmt/pull/811>`_, - `#822 <https://github.com/fmtlib/fmt/issues/822>`_, - `#827 <https://github.com/fmtlib/fmt/pull/827>`_, - `#830 <https://github.com/fmtlib/fmt/issues/830>`_, - `#838 <https://github.com/fmtlib/fmt/pull/838>`_, - `#843 <https://github.com/fmtlib/fmt/issues/843>`_, - `#844 <https://github.com/fmtlib/fmt/pull/844>`_, - `#851 <https://github.com/fmtlib/fmt/issues/851>`_, - `#852 <https://github.com/fmtlib/fmt/pull/852>`_, - `#854 <https://github.com/fmtlib/fmt/pull/854>`_). - Thanks `@henryiii (Henry Schreiner) <https://github.com/henryiii>`_, - `@medithe <https://github.com/medithe>`_, and - `@eliasdaler (Elias Daler) <https://github.com/eliasdaler>`_. - -5.1.0 - 2018-07-05 ------------------- - -* Added experimental support for RGB color output enabled with - the ``FMT_EXTENDED_COLORS`` macro: - - .. code:: c++ - - #define FMT_EXTENDED_COLORS - #define FMT_HEADER_ONLY // or compile fmt with FMT_EXTENDED_COLORS defined - #include <fmt/format.h> - - fmt::print(fmt::color::steel_blue, "Some beautiful text"); - - The old API (the ``print_colored`` and ``vprint_colored`` functions and the - ``color`` enum) is now deprecated. - (`#762 <https://github.com/fmtlib/fmt/issues/762>`_ - `#767 <https://github.com/fmtlib/fmt/pull/767>`_). - thanks `@Remotion (Remo) <https://github.com/Remotion>`_. - -* Added quotes to strings in ranges and tuples - (`#766 <https://github.com/fmtlib/fmt/pull/766>`_). - Thanks `@Remotion (Remo) <https://github.com/Remotion>`_. - -* Made ``format_to`` work with ``basic_memory_buffer`` - (`#776 <https://github.com/fmtlib/fmt/issues/776>`_). - -* Added ``vformat_to_n`` and ``wchar_t`` overload of ``format_to_n`` - (`#764 <https://github.com/fmtlib/fmt/issues/764>`_, - `#769 <https://github.com/fmtlib/fmt/issues/769>`_). - -* Made ``is_range`` and ``is_tuple_like`` part of public (experimental) API - to allow specialization for user-defined types - (`#751 <https://github.com/fmtlib/fmt/issues/751>`_, - `#759 <https://github.com/fmtlib/fmt/pull/759>`_). - Thanks `@drrlvn (Dror Levin) <https://github.com/drrlvn>`_. - -* Added more compilers to continuous integration and increased ``FMT_PEDANTIC`` - warning levels - (`#736 <https://github.com/fmtlib/fmt/pull/736>`_). - Thanks `@eliaskosunen (Elias Kosunen) <https://github.com/eliaskosunen>`_. - -* Fixed compilation with MSVC 2013. - -* Fixed handling of user-defined types in ``format_to`` - (`#793 <https://github.com/fmtlib/fmt/issues/793>`_). - -* Forced linking of inline ``vformat`` functions into the library - (`#795 <https://github.com/fmtlib/fmt/issues/795>`_). - -* Fixed incorrect call to on_align in ``'{:}='`` - (`#750 <https://github.com/fmtlib/fmt/issues/750>`_). - -* Fixed floating-point formatting to a non-back_insert_iterator with sign & - numeric alignment specified - (`#756 <https://github.com/fmtlib/fmt/issues/756>`_). - -* Fixed formatting to an array with ``format_to_n`` - (`#778 <https://github.com/fmtlib/fmt/issues/778>`_). - -* Fixed formatting of more than 15 named arguments - (`#754 <https://github.com/fmtlib/fmt/issues/754>`_). - -* Fixed handling of compile-time strings when including ``fmt/ostream.h``. - (`#768 <https://github.com/fmtlib/fmt/issues/768>`_). - -* Fixed various compiler warnings and errors - (`#742 <https://github.com/fmtlib/fmt/issues/742>`_, - `#748 <https://github.com/fmtlib/fmt/issues/748>`_, - `#752 <https://github.com/fmtlib/fmt/issues/752>`_, - `#770 <https://github.com/fmtlib/fmt/issues/770>`_, - `#775 <https://github.com/fmtlib/fmt/pull/775>`_, - `#779 <https://github.com/fmtlib/fmt/issues/779>`_, - `#780 <https://github.com/fmtlib/fmt/pull/780>`_, - `#790 <https://github.com/fmtlib/fmt/pull/790>`_, - `#792 <https://github.com/fmtlib/fmt/pull/792>`_, - `#800 <https://github.com/fmtlib/fmt/pull/800>`_). - Thanks `@Remotion (Remo) <https://github.com/Remotion>`_, - `@gabime (Gabi Melman) <https://github.com/gabime>`_, - `@foonathan (Jonathan Müller) <https://github.com/foonathan>`_, - `@Dark-Passenger (Dhruv Paranjape) <https://github.com/Dark-Passenger>`_, and - `@0x8000-0000 (Sign Bit) <https://github.com/0x8000-0000>`_. - -5.0.0 - 2018-05-21 ------------------- - -* Added a requirement for partial C++11 support, most importantly variadic - templates and type traits, and dropped ``FMT_VARIADIC_*`` emulation macros. - Variadic templates are available since GCC 4.4, Clang 2.9 and MSVC 18.0 (2013). - For older compilers use {fmt} `version 4.x - <https://github.com/fmtlib/fmt/releases/tag/4.1.0>`_ which continues to be - maintained and works with C++98 compilers. - -* Renamed symbols to follow standard C++ naming conventions and proposed a subset - of the library for standardization in `P0645R2 Text Formatting - <https://wg21.link/P0645>`_. - -* Implemented ``constexpr`` parsing of format strings and `compile-time format - string checks + `#1069 <https://github.com/fmtlib/fmt/pull/1069>`_, + `#1071 <https://github.com/fmtlib/fmt/pull/1071>`_): + + .. code:: c++ + + auto s = fmt::format("{:.1%}", 0.42); // s == "42.0%" + + Thanks `@gawain-bolton (Gawain Bolton) <https://github.com/gawain-bolton>`_. + +* Implemented precision for floating-point durations + (`#1004 <https://github.com/fmtlib/fmt/issues/1004>`_, + `#1012 <https://github.com/fmtlib/fmt/pull/1012>`_): + + .. code:: c++ + + auto s = fmt::format("{:.1}", std::chrono::duration<double>(1.234)); + // s == 1.2s + + Thanks `@DanielaE (Daniela Engert) <https://github.com/DanielaE>`_. + +* Implemented ``chrono`` format specifiers ``%Q`` and ``%q`` that give the value + and the unit respectively (`#1019 <https://github.com/fmtlib/fmt/pull/1019>`_): + + .. code:: c++ + + auto value = fmt::format("{:%Q}", 42s); // value == "42" + auto unit = fmt::format("{:%q}", 42s); // unit == "s" + + Thanks `@DanielaE (Daniela Engert) <https://github.com/DanielaE>`_. + +* Fixed handling of dynamic width in chrono formatter: + + .. code:: c++ + + auto s = fmt::format("{0:{1}%H:%M:%S}", std::chrono::seconds(12345), 12); + // ^ width argument index ^ width + // s == "03:25:45 " + + Thanks Howard Hinnant. + +* Removed deprecated ``fmt/time.h``. Use ``fmt/chrono.h`` instead. + +* Added ``fmt::format`` and ``fmt::vformat`` overloads that take ``text_style`` + (`#993 <https://github.com/fmtlib/fmt/issues/993>`_, + `#994 <https://github.com/fmtlib/fmt/pull/994>`_): + + .. code:: c++ + + #include <fmt/color.h> + + std::string message = fmt::format(fmt::emphasis::bold | fg(fmt::color::red), + "The answer is {}.", 42); + + Thanks `@Naios (Denis Blank) <https://github.com/Naios>`_. + +* Removed the deprecated color API (``print_colored``). Use the new API, namely + ``print`` overloads that take ``text_style`` instead. + +* Made ``std::unique_ptr`` and ``std::shared_ptr`` formattable as pointers via + ``fmt::ptr`` (`#1121 <https://github.com/fmtlib/fmt/pull/1121>`_): + + .. code:: c++ + + std::unique_ptr<int> p = ...; + fmt::print("{}", fmt::ptr(p)); // prints p as a pointer + + Thanks `@sighingnow (Tao He) <https://github.com/sighingnow>`_. + +* Made ``print`` and ``vprint`` report I/O errors + (`#1098 <https://github.com/fmtlib/fmt/issues/1098>`_, + `#1099 <https://github.com/fmtlib/fmt/pull/1099>`_). + Thanks `@BillyDonahue (Billy Donahue) <https://github.com/BillyDonahue>`_. + +* Marked deprecated APIs with the ``[[deprecated]]`` attribute and removed + internal uses of deprecated APIs + (`#1022 <https://github.com/fmtlib/fmt/pull/1022>`_). + Thanks `@eliaskosunen (Elias Kosunen) <https://github.com/eliaskosunen>`_. + +* Modernized the codebase using more C++11 features and removing workarounds. + Most importantly, ``buffer_context`` is now an alias template, so + use ``buffer_context<T>`` instead of ``buffer_context<T>::type``. + These features require GCC 4.8 or later. + +* ``formatter`` specializations now always take precedence over implicit + conversions to ``int`` and the undocumented ``convert_to_int`` trait + is now deprecated. + +* Moved the undocumented ``basic_writer``, ``writer``, and ``wwriter`` types + to the ``internal`` namespace. + +* Removed deprecated ``basic_format_context::begin()``. Use ``out()`` instead. + +* Disallowed passing the result of ``join`` as an lvalue to prevent misuse. + +* Refactored the undocumented structs that represent parsed format specifiers + to simplify the API and allow multibyte fill. + +* Moved SFINAE to template parameters to reduce symbol sizes. + +* Switched to ``fputws`` for writing wide strings so that it's no longer + required to call ``_setmode`` on Windows + (`#1229 <https://github.com/fmtlib/fmt/issues/1229>`_, + `#1243 <https://github.com/fmtlib/fmt/pull/1243>`_). + Thanks `@jackoalan (Jack Andersen) <https://github.com/jackoalan>`_. + +* Improved literal-based API + (`#1254 <https://github.com/fmtlib/fmt/pull/1254>`_). + Thanks `@sylveon (Charles Milette) <https://github.com/sylveon>`_. + +* Added support for exotic platforms without ``uintptr_t`` such as IBM i + (AS/400) which has 128-bit pointers and only 64-bit integers + (`#1059 <https://github.com/fmtlib/fmt/issues/1059>`_). + +* Added `Sublime Text syntax highlighting config + <https://github.com/fmtlib/fmt/blob/master/support/C%2B%2B.sublime-syntax>`_ + (`#1037 <https://github.com/fmtlib/fmt/issues/1037>`_). + Thanks `@Kronuz (Germán Méndez Bravo) <https://github.com/Kronuz>`_. + +* Added the ``FMT_ENFORCE_COMPILE_STRING`` macro to enforce the use of + compile-time format strings + (`#1231 <https://github.com/fmtlib/fmt/pull/1231>`_). + Thanks `@jackoalan (Jack Andersen) <https://github.com/jackoalan>`_. + +* Stopped setting ``CMAKE_BUILD_TYPE`` if {fmt} is a subproject + (`#1081 <https://github.com/fmtlib/fmt/issues/1081>`_). + +* Various build improvements + (`#1039 <https://github.com/fmtlib/fmt/pull/1039>`_, + `#1078 <https://github.com/fmtlib/fmt/pull/1078>`_, + `#1091 <https://github.com/fmtlib/fmt/pull/1091>`_, + `#1103 <https://github.com/fmtlib/fmt/pull/1103>`_, + `#1177 <https://github.com/fmtlib/fmt/pull/1177>`_). + Thanks `@luncliff (Park DongHa) <https://github.com/luncliff>`_, + `@jasonszang (Jason Shuo Zang) <https://github.com/jasonszang>`_, + `@olafhering (Olaf Hering) <https://github.com/olafhering>`_, + `@Lecetem <https://github.com/Lectem>`_, + `@pauldreik (Paul Dreik) <https://github.com/pauldreik>`_. + +* Improved documentation + (`#1049 <https://github.com/fmtlib/fmt/issues/1049>`_, + `#1051 <https://github.com/fmtlib/fmt/pull/1051>`_, + `#1083 <https://github.com/fmtlib/fmt/pull/1083>`_, + `#1113 <https://github.com/fmtlib/fmt/pull/1113>`_, + `#1114 <https://github.com/fmtlib/fmt/pull/1114>`_, + `#1146 <https://github.com/fmtlib/fmt/issues/1146>`_, + `#1180 <https://github.com/fmtlib/fmt/issues/1180>`_, + `#1250 <https://github.com/fmtlib/fmt/pull/1250>`_, + `#1252 <https://github.com/fmtlib/fmt/pull/1252>`_, + `#1265 <https://github.com/fmtlib/fmt/pull/1265>`_). + Thanks `@mikelui (Michael Lui) <https://github.com/mikelui>`_, + `@foonathan (Jonathan Müller) <https://github.com/foonathan>`_, + `@BillyDonahue (Billy Donahue) <https://github.com/BillyDonahue>`_, + `@jwakely (Jonathan Wakely) <https://github.com/jwakely>`_, + `@kaisbe (Kais Ben Salah) <https://github.com/kaisbe>`_, + `@sdebionne (Samuel Debionne) <https://github.com/sdebionne>`_. + +* Fixed ambiguous formatter specialization in ``fmt/ranges.h`` + (`#1123 <https://github.com/fmtlib/fmt/issues/1123>`_). + +* Fixed formatting of a non-empty ``std::filesystem::path`` which is an + infinitely deep range of its components + (`#1268 <https://github.com/fmtlib/fmt/issues/1268>`_). + +* Fixed handling of general output iterators when formatting characters + (`#1056 <https://github.com/fmtlib/fmt/issues/1056>`_, + `#1058 <https://github.com/fmtlib/fmt/pull/1058>`_). + Thanks `@abolz (Alexander Bolz) <https://github.com/abolz>`_. + +* Fixed handling of output iterators in ``formatter`` specialization for + ranges (`#1064 <https://github.com/fmtlib/fmt/issues/1064>`_). + +* Fixed handling of exotic character types + (`#1188 <https://github.com/fmtlib/fmt/issues/1188>`_). + +* Made chrono formatting work with exceptions disabled + (`#1062 <https://github.com/fmtlib/fmt/issues/1062>`_). + +* Fixed DLL visibility issues + (`#1134 <https://github.com/fmtlib/fmt/pull/1134>`_, + `#1147 <https://github.com/fmtlib/fmt/pull/1147>`_). + Thanks `@denchat <https://github.com/denchat>`_. + +* Disabled the use of UDL template extension on GCC 9 + (`#1148 <https://github.com/fmtlib/fmt/issues/1148>`_). + +* Removed misplaced ``format`` compile-time checks from ``printf`` + (`#1173 <https://github.com/fmtlib/fmt/issues/1173>`_). + +* Fixed issues in the experimental floating-point formatter + (`#1072 <https://github.com/fmtlib/fmt/issues/1072>`_, + `#1129 <https://github.com/fmtlib/fmt/issues/1129>`_, + `#1153 <https://github.com/fmtlib/fmt/issues/1153>`_, + `#1155 <https://github.com/fmtlib/fmt/pull/1155>`_, + `#1210 <https://github.com/fmtlib/fmt/issues/1210>`_, + `#1222 <https://github.com/fmtlib/fmt/issues/1222>`_). + Thanks `@alabuzhev (Alex Alabuzhev) <https://github.com/alabuzhev>`_. + +* Fixed bugs discovered by fuzzing or during fuzzing integration + (`#1124 <https://github.com/fmtlib/fmt/issues/1124>`_, + `#1127 <https://github.com/fmtlib/fmt/issues/1127>`_, + `#1132 <https://github.com/fmtlib/fmt/issues/1132>`_, + `#1135 <https://github.com/fmtlib/fmt/pull/1135>`_, + `#1136 <https://github.com/fmtlib/fmt/issues/1136>`_, + `#1141 <https://github.com/fmtlib/fmt/issues/1141>`_, + `#1142 <https://github.com/fmtlib/fmt/issues/1142>`_, + `#1178 <https://github.com/fmtlib/fmt/issues/1178>`_, + `#1179 <https://github.com/fmtlib/fmt/issues/1179>`_, + `#1194 <https://github.com/fmtlib/fmt/issues/1194>`_). + Thanks `@pauldreik (Paul Dreik) <https://github.com/pauldreik>`_. + +* Fixed building tests on FreeBSD and Hurd + (`#1043 <https://github.com/fmtlib/fmt/issues/1043>`_). + Thanks `@jackyf (Eugene V. Lyubimkin) <https://github.com/jackyf>`_. + +* Fixed various warnings and compilation issues + (`#998 <https://github.com/fmtlib/fmt/pull/998>`_, + `#1006 <https://github.com/fmtlib/fmt/pull/1006>`_, + `#1008 <https://github.com/fmtlib/fmt/issues/1008>`_, + `#1011 <https://github.com/fmtlib/fmt/issues/1011>`_, + `#1025 <https://github.com/fmtlib/fmt/issues/1025>`_, + `#1027 <https://github.com/fmtlib/fmt/pull/1027>`_, + `#1028 <https://github.com/fmtlib/fmt/pull/1028>`_, + `#1029 <https://github.com/fmtlib/fmt/pull/1029>`_, + `#1030 <https://github.com/fmtlib/fmt/pull/1030>`_, + `#1031 <https://github.com/fmtlib/fmt/pull/1031>`_, + `#1054 <https://github.com/fmtlib/fmt/pull/1054>`_, + `#1063 <https://github.com/fmtlib/fmt/issues/1063>`_, + `#1068 <https://github.com/fmtlib/fmt/pull/1068>`_, + `#1074 <https://github.com/fmtlib/fmt/pull/1074>`_, + `#1075 <https://github.com/fmtlib/fmt/pull/1075>`_, + `#1079 <https://github.com/fmtlib/fmt/pull/1079>`_, + `#1086 <https://github.com/fmtlib/fmt/pull/1086>`_, + `#1088 <https://github.com/fmtlib/fmt/issues/1088>`_, + `#1089 <https://github.com/fmtlib/fmt/pull/1089>`_, + `#1094 <https://github.com/fmtlib/fmt/pull/1094>`_, + `#1101 <https://github.com/fmtlib/fmt/issues/1101>`_, + `#1102 <https://github.com/fmtlib/fmt/pull/1102>`_, + `#1105 <https://github.com/fmtlib/fmt/issues/1105>`_, + `#1107 <https://github.com/fmtlib/fmt/pull/1107>`_, + `#1115 <https://github.com/fmtlib/fmt/issues/1115>`_, + `#1117 <https://github.com/fmtlib/fmt/issues/1117>`_, + `#1118 <https://github.com/fmtlib/fmt/issues/1118>`_, + `#1120 <https://github.com/fmtlib/fmt/issues/1120>`_, + `#1123 <https://github.com/fmtlib/fmt/issues/1123>`_, + `#1139 <https://github.com/fmtlib/fmt/pull/1139>`_, + `#1140 <https://github.com/fmtlib/fmt/issues/1140>`_, + `#1143 <https://github.com/fmtlib/fmt/issues/1143>`_, + `#1144 <https://github.com/fmtlib/fmt/pull/1144>`_, + `#1150 <https://github.com/fmtlib/fmt/pull/1150>`_, + `#1151 <https://github.com/fmtlib/fmt/pull/1151>`_, + `#1152 <https://github.com/fmtlib/fmt/issues/1152>`_, + `#1154 <https://github.com/fmtlib/fmt/issues/1154>`_, + `#1156 <https://github.com/fmtlib/fmt/issues/1156>`_, + `#1159 <https://github.com/fmtlib/fmt/pull/1159>`_, + `#1175 <https://github.com/fmtlib/fmt/issues/1175>`_, + `#1181 <https://github.com/fmtlib/fmt/issues/1181>`_, + `#1186 <https://github.com/fmtlib/fmt/issues/1186>`_, + `#1187 <https://github.com/fmtlib/fmt/pull/1187>`_, + `#1191 <https://github.com/fmtlib/fmt/pull/1191>`_, + `#1197 <https://github.com/fmtlib/fmt/issues/1197>`_, + `#1200 <https://github.com/fmtlib/fmt/issues/1200>`_, + `#1203 <https://github.com/fmtlib/fmt/issues/1203>`_, + `#1205 <https://github.com/fmtlib/fmt/issues/1205>`_, + `#1206 <https://github.com/fmtlib/fmt/pull/1206>`_, + `#1213 <https://github.com/fmtlib/fmt/issues/1213>`_, + `#1214 <https://github.com/fmtlib/fmt/issues/1214>`_, + `#1217 <https://github.com/fmtlib/fmt/pull/1217>`_, + `#1228 <https://github.com/fmtlib/fmt/issues/1228>`_, + `#1230 <https://github.com/fmtlib/fmt/pull/1230>`_, + `#1232 <https://github.com/fmtlib/fmt/issues/1232>`_, + `#1235 <https://github.com/fmtlib/fmt/pull/1235>`_, + `#1236 <https://github.com/fmtlib/fmt/pull/1236>`_, + `#1240 <https://github.com/fmtlib/fmt/issues/1240>`_). + Thanks `@DanielaE (Daniela Engert) <https://github.com/DanielaE>`_, + `@mwinterb <https://github.com/mwinterb>`_, + `@eliaskosunen (Elias Kosunen) <https://github.com/eliaskosunen>`_, + `@morinmorin <https://github.com/morinmorin>`_, + `@ricco19 (Brian Ricciardelli) <https://github.com/ricco19>`_, + `@waywardmonkeys (Bruce Mitchener) <https://github.com/waywardmonkeys>`_, + `@chronoxor (Ivan Shynkarenka) <https://github.com/chronoxor>`_, + `@remyabel <https://github.com/remyabel>`_, + `@pauldreik (Paul Dreik) <https://github.com/pauldreik>`_, + `@gsjaardema (Greg Sjaardema) <https://github.com/gsjaardema>`_, + `@rcane (Ronny Krüger) <https://github.com/rcane>`_, + `@mocabe <https://github.com/mocabe>`_, + `@denchat <https://github.com/denchat>`_, + `@cjdb (Christopher Di Bella) <https://github.com/cjdb>`_, + `@HazardyKnusperkeks (Björn Schäpers) <https://github.com/HazardyKnusperkeks>`_, + `@vedranmiletic (Vedran Miletić) <https://github.com/vedranmiletic>`_, + `@jackoalan (Jack Andersen) <https://github.com/jackoalan>`_, + `@DaanDeMeyer (Daan De Meyer) <https://github.com/DaanDeMeyer>`_, + `@starkmapper (Mark Stapper) <https://github.com/starkmapper>`_. + +5.3.0 - 2018-12-28 +------------------ + +* Introduced experimental chrono formatting support: + + .. code:: c++ + + #include <fmt/chrono.h> + + int main() { + using namespace std::literals::chrono_literals; + fmt::print("Default format: {} {}\n", 42s, 100ms); + fmt::print("strftime-like format: {:%H:%M:%S}\n", 3h + 15min + 30s); + } + + prints:: + + Default format: 42s 100ms + strftime-like format: 03:15:30 + +* Added experimental support for emphasis (bold, italic, underline, + strikethrough), colored output to a file stream, and improved colored + formatting API + (`#961 <https://github.com/fmtlib/fmt/pull/961>`_, + `#967 <https://github.com/fmtlib/fmt/pull/967>`_, + `#973 <https://github.com/fmtlib/fmt/pull/973>`_): + + .. code:: c++ + + #include <fmt/color.h> + + int main() { + print(fg(fmt::color::crimson) | fmt::emphasis::bold, + "Hello, {}!\n", "world"); + print(fg(fmt::color::floral_white) | bg(fmt::color::slate_gray) | + fmt::emphasis::underline, "Hello, {}!\n", "мир"); + print(fg(fmt::color::steel_blue) | fmt::emphasis::italic, + "Hello, {}!\n", "世界"); + } + + prints the following on modern terminals with RGB color support: + + .. image:: https://user-images.githubusercontent.com/576385/ + 50405788-b66e7500-076e-11e9-9592-7324d1f951d8.png + + Thanks `@Rakete1111 (Nicolas) <https://github.com/Rakete1111>`_. + +* Added support for 4-bit terminal colors + (`#968 <https://github.com/fmtlib/fmt/issues/968>`_, + `#974 <https://github.com/fmtlib/fmt/pull/974>`_) + + .. code:: c++ + + #include <fmt/color.h> + + int main() { + print(fg(fmt::terminal_color::red), "stop\n"); + } + + Note that these colors vary by terminal: + + .. image:: https://user-images.githubusercontent.com/576385/ + 50405925-dbfc7e00-0770-11e9-9b85-333fab0af9ac.png + + Thanks `@Rakete1111 (Nicolas) <https://github.com/Rakete1111>`_. + +* Parameterized formatting functions on the type of the format string + (`#880 <https://github.com/fmtlib/fmt/issues/880>`_, + `#881 <https://github.com/fmtlib/fmt/pull/881>`_, + `#883 <https://github.com/fmtlib/fmt/pull/883>`_, + `#885 <https://github.com/fmtlib/fmt/pull/885>`_, + `#897 <https://github.com/fmtlib/fmt/pull/897>`_, + `#920 <https://github.com/fmtlib/fmt/issues/920>`_). + Any object of type ``S`` that has an overloaded ``to_string_view(const S&)`` + returning ``fmt::string_view`` can be used as a format string: + + .. code:: c++ + + namespace my_ns { + inline string_view to_string_view(const my_string& s) { + return {s.data(), s.length()}; + } + } + + std::string message = fmt::format(my_string("The answer is {}."), 42); + + Thanks `@DanielaE (Daniela Engert) <https://github.com/DanielaE>`_. + +* Made ``std::string_view`` work as a format string + (`#898 <https://github.com/fmtlib/fmt/pull/898>`_): + + .. code:: c++ + + auto message = fmt::format(std::string_view("The answer is {}."), 42); + + Thanks `@DanielaE (Daniela Engert) <https://github.com/DanielaE>`_. + +* Added wide string support to compile-time format string checks + (`#924 <https://github.com/fmtlib/fmt/pull/924>`_): + + .. code:: c++ + + print(fmt(L"{:f}"), 42); // compile-time error: invalid type specifier + + Thanks `@XZiar <https://github.com/XZiar>`_. + +* Made colored print functions work with wide strings + (`#867 <https://github.com/fmtlib/fmt/pull/867>`_): + + .. code:: c++ + + #include <fmt/color.h> + + int main() { + print(fg(fmt::color::red), L"{}\n", 42); + } + + Thanks `@DanielaE (Daniela Engert) <https://github.com/DanielaE>`_. + +* Introduced experimental Unicode support + (`#628 <https://github.com/fmtlib/fmt/issues/628>`_, + `#891 <https://github.com/fmtlib/fmt/pull/891>`_): + + .. code:: c++ + + using namespace fmt::literals; + auto s = fmt::format("{:*^5}"_u, "🤡"_u); // s == "**🤡**"_u + +* Improved locale support: + + .. code:: c++ + + #include <fmt/locale.h> + + struct numpunct : std::numpunct<char> { + protected: + char do_thousands_sep() const override { return '~'; } + }; + + std::locale loc; + auto s = fmt::format(std::locale(loc, new numpunct()), "{:n}", 1234567); + // s == "1~234~567" + +* Constrained formatting functions on proper iterator types + (`#921 <https://github.com/fmtlib/fmt/pull/921>`_). + Thanks `@DanielaE (Daniela Engert) <https://github.com/DanielaE>`_. + +* Added ``make_printf_args`` and ``make_wprintf_args`` functions + (`#934 <https://github.com/fmtlib/fmt/pull/934>`_). + Thanks `@tnovotny <https://github.com/tnovotny>`_. + +* Deprecated ``fmt::visit``, ``parse_context``, and ``wparse_context``. + Use ``fmt::visit_format_arg``, ``format_parse_context``, and + ``wformat_parse_context`` instead. + +* Removed undocumented ``basic_fixed_buffer`` which has been superseded by the + iterator-based API + (`#873 <https://github.com/fmtlib/fmt/issues/873>`_, + `#902 <https://github.com/fmtlib/fmt/pull/902>`_). + Thanks `@superfunc (hollywood programmer) <https://github.com/superfunc>`_. + +* Disallowed repeated leading zeros in an argument ID: + + .. code:: c++ + + fmt::print("{000}", 42); // error + +* Reintroduced support for gcc 4.4. + +* Fixed compilation on platforms with exotic ``double`` + (`#878 <https://github.com/fmtlib/fmt/issues/878>`_). + +* Improved documentation + (`#164 <https://github.com/fmtlib/fmt/issues/164>`_, + `#877 <https://github.com/fmtlib/fmt/issues/877>`_, + `#901 <https://github.com/fmtlib/fmt/pull/901>`_, + `#906 <https://github.com/fmtlib/fmt/pull/906>`_, + `#979 <https://github.com/fmtlib/fmt/pull/979>`_). + Thanks `@kookjr (Mathew Cucuzella) <https://github.com/kookjr>`_, + `@DarkDimius (Dmitry Petrashko) <https://github.com/DarkDimius>`_, + `@HecticSerenity <https://github.com/HecticSerenity>`_. + +* Added pkgconfig support which makes it easier to consume the library from + meson and other build systems + (`#916 <https://github.com/fmtlib/fmt/pull/916>`_). + Thanks `@colemickens (Cole Mickens) <https://github.com/colemickens>`_. + +* Various build improvements + (`#909 <https://github.com/fmtlib/fmt/pull/909>`_, + `#926 <https://github.com/fmtlib/fmt/pull/926>`_, + `#937 <https://github.com/fmtlib/fmt/pull/937>`_, + `#953 <https://github.com/fmtlib/fmt/pull/953>`_, + `#959 <https://github.com/fmtlib/fmt/pull/959>`_). + Thanks `@tchaikov (Kefu Chai) <https://github.com/tchaikov>`_, + `@luncliff (Park DongHa) <https://github.com/luncliff>`_, + `@AndreasSchoenle (Andreas Schönle) <https://github.com/AndreasSchoenle>`_, + `@hotwatermorning <https://github.com/hotwatermorning>`_, + `@Zefz (JohanJansen) <https://github.com/Zefz>`_. + +* Improved ``string_view`` construction performance + (`#914 <https://github.com/fmtlib/fmt/pull/914>`_). + Thanks `@gabime (Gabi Melman) <https://github.com/gabime>`_. + +* Fixed non-matching char types + (`#895 <https://github.com/fmtlib/fmt/pull/895>`_). + Thanks `@DanielaE (Daniela Engert) <https://github.com/DanielaE>`_. + +* Fixed ``format_to_n`` with ``std::back_insert_iterator`` + (`#913 <https://github.com/fmtlib/fmt/pull/913>`_). + Thanks `@DanielaE (Daniela Engert) <https://github.com/DanielaE>`_. + +* Fixed locale-dependent formatting + (`#905 <https://github.com/fmtlib/fmt/issues/905>`_). + +* Fixed various compiler warnings and errors + (`#882 <https://github.com/fmtlib/fmt/pull/882>`_, + `#886 <https://github.com/fmtlib/fmt/pull/886>`_, + `#933 <https://github.com/fmtlib/fmt/pull/933>`_, + `#941 <https://github.com/fmtlib/fmt/pull/941>`_, + `#931 <https://github.com/fmtlib/fmt/issues/931>`_, + `#943 <https://github.com/fmtlib/fmt/pull/943>`_, + `#954 <https://github.com/fmtlib/fmt/pull/954>`_, + `#956 <https://github.com/fmtlib/fmt/pull/956>`_, + `#962 <https://github.com/fmtlib/fmt/pull/962>`_, + `#965 <https://github.com/fmtlib/fmt/issues/965>`_, + `#977 <https://github.com/fmtlib/fmt/issues/977>`_, + `#983 <https://github.com/fmtlib/fmt/pull/983>`_, + `#989 <https://github.com/fmtlib/fmt/pull/989>`_). + Thanks `@Luthaf (Guillaume Fraux) <https://github.com/Luthaf>`_, + `@stevenhoving (Steven Hoving) <https://github.com/stevenhoving>`_, + `@christinaa (Kristina Brooks) <https://github.com/christinaa>`_, + `@lgritz (Larry Gritz) <https://github.com/lgritz>`_, + `@DanielaE (Daniela Engert) <https://github.com/DanielaE>`_, + `@0x8000-0000 (Sign Bit) <https://github.com/0x8000-0000>`_, + `@liuping1997 <https://github.com/liuping1997>`_. + +5.2.1 - 2018-09-21 +------------------ + +* Fixed ``visit`` lookup issues on gcc 7 & 8 + (`#870 <https://github.com/fmtlib/fmt/pull/870>`_). + Thanks `@medithe <https://github.com/medithe>`_. + +* Fixed linkage errors on older gcc. + +* Prevented ``fmt/range.h`` from specializing ``fmt::basic_string_view`` + (`#865 <https://github.com/fmtlib/fmt/issues/865>`_, + `#868 <https://github.com/fmtlib/fmt/pull/868>`_). + Thanks `@hhggit (dual) <https://github.com/hhggit>`_. + +* Improved error message when formatting unknown types + (`#872 <https://github.com/fmtlib/fmt/pull/872>`_). + Thanks `@foonathan (Jonathan Müller) <https://github.com/foonathan>`_, + +* Disabled templated user-defined literals when compiled under nvcc + (`#875 <https://github.com/fmtlib/fmt/pull/875>`_). + Thanks `@CandyGumdrop (Candy Gumdrop) <https://github.com/CandyGumdrop>`_, + +* Fixed ``format_to`` formatting to ``wmemory_buffer`` + (`#874 <https://github.com/fmtlib/fmt/issues/874>`_). + +5.2.0 - 2018-09-13 +------------------ + +* Optimized format string parsing and argument processing which resulted in up + to 5x speed up on long format strings and significant performance boost on + various benchmarks. For example, version 5.2 is 2.22x faster than 5.1 on + decimal integer formatting with ``format_to`` (macOS, clang-902.0.39.2): + + ================== ======= ======= + Method Time, s Speedup + ================== ======= ======= + fmt::format 5.1 0.58 + fmt::format 5.2 0.35 1.66x + fmt::format_to 5.1 0.51 + fmt::format_to 5.2 0.23 2.22x + sprintf 0.71 + std::to_string 1.01 + std::stringstream 1.73 + ================== ======= ======= + +* Changed the ``fmt`` macro from opt-out to opt-in to prevent name collisions. + To enable it define the ``FMT_STRING_ALIAS`` macro to 1 before including + ``fmt/format.h``: + + .. code:: c++ + + #define FMT_STRING_ALIAS 1 + #include <fmt/format.h> + std::string answer = format(fmt("{}"), 42); + +* Added compile-time format string checks to ``format_to`` overload that takes + ``fmt::memory_buffer`` (`#783 <https://github.com/fmtlib/fmt/issues/783>`_): + + .. code:: c++ + + fmt::memory_buffer buf; + // Compile-time error: invalid type specifier. + fmt::format_to(buf, fmt("{:d}"), "foo"); + +* Moved experimental color support to ``fmt/color.h`` and enabled the + new API by default. The old API can be enabled by defining the + ``FMT_DEPRECATED_COLORS`` macro. + +* Added formatting support for types explicitly convertible to + ``fmt::string_view``: + + .. code:: c++ + + struct foo { + explicit operator fmt::string_view() const { return "foo"; } + }; + auto s = format("{}", foo()); + + In particular, this makes formatting function work with + ``folly::StringPiece``. + +* Implemented preliminary support for ``char*_t`` by replacing the ``format`` + function overloads with a single function template parameterized on the string + type. + +* Added support for dynamic argument lists + (`#814 <https://github.com/fmtlib/fmt/issues/814>`_, + `#819 <https://github.com/fmtlib/fmt/pull/819>`_). + Thanks `@MikePopoloski (Michael Popoloski) + <https://github.com/MikePopoloski>`_. + +* Reduced executable size overhead for embedded targets using newlib nano by + making locale dependency optional + (`#839 <https://github.com/fmtlib/fmt/pull/839>`_). + Thanks `@teajay-fr (Thomas Benard) <https://github.com/teajay-fr>`_. + +* Keep ``noexcept`` specifier when exceptions are disabled + (`#801 <https://github.com/fmtlib/fmt/issues/801>`_, + `#810 <https://github.com/fmtlib/fmt/pull/810>`_). + Thanks `@qis (Alexej Harm) <https://github.com/qis>`_. + +* Fixed formatting of user-defined types providing ``operator<<`` with + ``format_to_n`` + (`#806 <https://github.com/fmtlib/fmt/pull/806>`_). + Thanks `@mkurdej (Marek Kurdej) <https://github.com/mkurdej>`_. + +* Fixed dynamic linkage of new symbols + (`#808 <https://github.com/fmtlib/fmt/issues/808>`_). + +* Fixed global initialization issue + (`#807 <https://github.com/fmtlib/fmt/issues/807>`_): + + .. code:: c++ + + // This works on compilers with constexpr support. + static const std::string answer = fmt::format("{}", 42); + +* Fixed various compiler warnings and errors + (`#804 <https://github.com/fmtlib/fmt/pull/804>`_, + `#809 <https://github.com/fmtlib/fmt/issues/809>`_, + `#811 <https://github.com/fmtlib/fmt/pull/811>`_, + `#822 <https://github.com/fmtlib/fmt/issues/822>`_, + `#827 <https://github.com/fmtlib/fmt/pull/827>`_, + `#830 <https://github.com/fmtlib/fmt/issues/830>`_, + `#838 <https://github.com/fmtlib/fmt/pull/838>`_, + `#843 <https://github.com/fmtlib/fmt/issues/843>`_, + `#844 <https://github.com/fmtlib/fmt/pull/844>`_, + `#851 <https://github.com/fmtlib/fmt/issues/851>`_, + `#852 <https://github.com/fmtlib/fmt/pull/852>`_, + `#854 <https://github.com/fmtlib/fmt/pull/854>`_). + Thanks `@henryiii (Henry Schreiner) <https://github.com/henryiii>`_, + `@medithe <https://github.com/medithe>`_, and + `@eliasdaler (Elias Daler) <https://github.com/eliasdaler>`_. + +5.1.0 - 2018-07-05 +------------------ + +* Added experimental support for RGB color output enabled with + the ``FMT_EXTENDED_COLORS`` macro: + + .. code:: c++ + + #define FMT_EXTENDED_COLORS + #define FMT_HEADER_ONLY // or compile fmt with FMT_EXTENDED_COLORS defined + #include <fmt/format.h> + + fmt::print(fmt::color::steel_blue, "Some beautiful text"); + + The old API (the ``print_colored`` and ``vprint_colored`` functions and the + ``color`` enum) is now deprecated. + (`#762 <https://github.com/fmtlib/fmt/issues/762>`_ + `#767 <https://github.com/fmtlib/fmt/pull/767>`_). + thanks `@Remotion (Remo) <https://github.com/Remotion>`_. + +* Added quotes to strings in ranges and tuples + (`#766 <https://github.com/fmtlib/fmt/pull/766>`_). + Thanks `@Remotion (Remo) <https://github.com/Remotion>`_. + +* Made ``format_to`` work with ``basic_memory_buffer`` + (`#776 <https://github.com/fmtlib/fmt/issues/776>`_). + +* Added ``vformat_to_n`` and ``wchar_t`` overload of ``format_to_n`` + (`#764 <https://github.com/fmtlib/fmt/issues/764>`_, + `#769 <https://github.com/fmtlib/fmt/issues/769>`_). + +* Made ``is_range`` and ``is_tuple_like`` part of public (experimental) API + to allow specialization for user-defined types + (`#751 <https://github.com/fmtlib/fmt/issues/751>`_, + `#759 <https://github.com/fmtlib/fmt/pull/759>`_). + Thanks `@drrlvn (Dror Levin) <https://github.com/drrlvn>`_. + +* Added more compilers to continuous integration and increased ``FMT_PEDANTIC`` + warning levels + (`#736 <https://github.com/fmtlib/fmt/pull/736>`_). + Thanks `@eliaskosunen (Elias Kosunen) <https://github.com/eliaskosunen>`_. + +* Fixed compilation with MSVC 2013. + +* Fixed handling of user-defined types in ``format_to`` + (`#793 <https://github.com/fmtlib/fmt/issues/793>`_). + +* Forced linking of inline ``vformat`` functions into the library + (`#795 <https://github.com/fmtlib/fmt/issues/795>`_). + +* Fixed incorrect call to on_align in ``'{:}='`` + (`#750 <https://github.com/fmtlib/fmt/issues/750>`_). + +* Fixed floating-point formatting to a non-back_insert_iterator with sign & + numeric alignment specified + (`#756 <https://github.com/fmtlib/fmt/issues/756>`_). + +* Fixed formatting to an array with ``format_to_n`` + (`#778 <https://github.com/fmtlib/fmt/issues/778>`_). + +* Fixed formatting of more than 15 named arguments + (`#754 <https://github.com/fmtlib/fmt/issues/754>`_). + +* Fixed handling of compile-time strings when including ``fmt/ostream.h``. + (`#768 <https://github.com/fmtlib/fmt/issues/768>`_). + +* Fixed various compiler warnings and errors + (`#742 <https://github.com/fmtlib/fmt/issues/742>`_, + `#748 <https://github.com/fmtlib/fmt/issues/748>`_, + `#752 <https://github.com/fmtlib/fmt/issues/752>`_, + `#770 <https://github.com/fmtlib/fmt/issues/770>`_, + `#775 <https://github.com/fmtlib/fmt/pull/775>`_, + `#779 <https://github.com/fmtlib/fmt/issues/779>`_, + `#780 <https://github.com/fmtlib/fmt/pull/780>`_, + `#790 <https://github.com/fmtlib/fmt/pull/790>`_, + `#792 <https://github.com/fmtlib/fmt/pull/792>`_, + `#800 <https://github.com/fmtlib/fmt/pull/800>`_). + Thanks `@Remotion (Remo) <https://github.com/Remotion>`_, + `@gabime (Gabi Melman) <https://github.com/gabime>`_, + `@foonathan (Jonathan Müller) <https://github.com/foonathan>`_, + `@Dark-Passenger (Dhruv Paranjape) <https://github.com/Dark-Passenger>`_, and + `@0x8000-0000 (Sign Bit) <https://github.com/0x8000-0000>`_. + +5.0.0 - 2018-05-21 +------------------ + +* Added a requirement for partial C++11 support, most importantly variadic + templates and type traits, and dropped ``FMT_VARIADIC_*`` emulation macros. + Variadic templates are available since GCC 4.4, Clang 2.9 and MSVC 18.0 (2013). + For older compilers use {fmt} `version 4.x + <https://github.com/fmtlib/fmt/releases/tag/4.1.0>`_ which continues to be + maintained and works with C++98 compilers. + +* Renamed symbols to follow standard C++ naming conventions and proposed a subset + of the library for standardization in `P0645R2 Text Formatting + <https://wg21.link/P0645>`_. + +* Implemented ``constexpr`` parsing of format strings and `compile-time format + string checks <https://fmt.dev/latest/api.html#compile-time-format-string-checks>`_. For - example - - .. code:: c++ - - #include <fmt/format.h> - - std::string s = format(fmt("{:d}"), "foo"); - - gives a compile-time error because ``d`` is an invalid specifier for strings - (`godbolt <https://godbolt.org/g/rnCy9Q>`__):: - - ... - <source>:4:19: note: in instantiation of function template specialization 'fmt::v5::format<S, char [4]>' requested here - std::string s = format(fmt("{:d}"), "foo"); - ^ - format.h:1337:13: note: non-constexpr function 'on_error' cannot be used in a constant expression - handler.on_error("invalid type specifier"); - - Compile-time checks require relaxed ``constexpr`` (C++14 feature) support. If - the latter is not available, checks will be performed at runtime. - -* Separated format string parsing and formatting in the extension API to enable - compile-time format string processing. For example - - .. code:: c++ - - struct Answer {}; - - namespace fmt { - template <> - struct formatter<Answer> { - constexpr auto parse(parse_context& ctx) { - auto it = ctx.begin(); - spec = *it; - if (spec != 'd' && spec != 's') - throw format_error("invalid specifier"); - return ++it; - } - - template <typename FormatContext> - auto format(Answer, FormatContext& ctx) { - return spec == 's' ? - format_to(ctx.begin(), "{}", "fourty-two") : - format_to(ctx.begin(), "{}", 42); - } - - char spec = 0; - }; - } - - std::string s = format(fmt("{:x}"), Answer()); - - gives a compile-time error due to invalid format specifier (`godbolt - <https://godbolt.org/g/2jQ1Dv>`__):: - - ... - <source>:12:45: error: expression '<throw-expression>' is not a constant expression - throw format_error("invalid specifier"); - -* Added `iterator support + example + + .. code:: c++ + + #include <fmt/format.h> + + std::string s = format(fmt("{:d}"), "foo"); + + gives a compile-time error because ``d`` is an invalid specifier for strings + (`godbolt <https://godbolt.org/g/rnCy9Q>`__):: + + ... + <source>:4:19: note: in instantiation of function template specialization 'fmt::v5::format<S, char [4]>' requested here + std::string s = format(fmt("{:d}"), "foo"); + ^ + format.h:1337:13: note: non-constexpr function 'on_error' cannot be used in a constant expression + handler.on_error("invalid type specifier"); + + Compile-time checks require relaxed ``constexpr`` (C++14 feature) support. If + the latter is not available, checks will be performed at runtime. + +* Separated format string parsing and formatting in the extension API to enable + compile-time format string processing. For example + + .. code:: c++ + + struct Answer {}; + + namespace fmt { + template <> + struct formatter<Answer> { + constexpr auto parse(parse_context& ctx) { + auto it = ctx.begin(); + spec = *it; + if (spec != 'd' && spec != 's') + throw format_error("invalid specifier"); + return ++it; + } + + template <typename FormatContext> + auto format(Answer, FormatContext& ctx) { + return spec == 's' ? + format_to(ctx.begin(), "{}", "fourty-two") : + format_to(ctx.begin(), "{}", 42); + } + + char spec = 0; + }; + } + + std::string s = format(fmt("{:x}"), Answer()); + + gives a compile-time error due to invalid format specifier (`godbolt + <https://godbolt.org/g/2jQ1Dv>`__):: + + ... + <source>:12:45: error: expression '<throw-expression>' is not a constant expression + throw format_error("invalid specifier"); + +* Added `iterator support <https://fmt.dev/latest/api.html#output-iterator-support>`_: - - .. code:: c++ - - #include <vector> - #include <fmt/format.h> - - std::vector<char> out; - fmt::format_to(std::back_inserter(out), "{}", 42); - -* Added the `format_to_n + + .. code:: c++ + + #include <vector> + #include <fmt/format.h> + + std::vector<char> out; + fmt::format_to(std::back_inserter(out), "{}", 42); + +* Added the `format_to_n <https://fmt.dev/latest/api.html#_CPPv2N3fmt11format_to_nE8OutputItNSt6size_tE11string_viewDpRK4Args>`_ - function that restricts the output to the specified number of characters - (`#298 <https://github.com/fmtlib/fmt/issues/298>`_): - - .. code:: c++ - - char out[4]; - fmt::format_to_n(out, sizeof(out), "{}", 12345); - // out == "1234" (without terminating '\0') - -* Added the `formatted_size + function that restricts the output to the specified number of characters + (`#298 <https://github.com/fmtlib/fmt/issues/298>`_): + + .. code:: c++ + + char out[4]; + fmt::format_to_n(out, sizeof(out), "{}", 12345); + // out == "1234" (without terminating '\0') + +* Added the `formatted_size <https://fmt.dev/latest/api.html#_CPPv2N3fmt14formatted_sizeE11string_viewDpRK4Args>`_ - function for computing the output size: - - .. code:: c++ - - #include <fmt/format.h> - - auto size = fmt::formatted_size("{}", 12345); // size == 5 - -* Improved compile times by reducing dependencies on standard headers and + function for computing the output size: + + .. code:: c++ + + #include <fmt/format.h> + + auto size = fmt::formatted_size("{}", 12345); // size == 5 + +* Improved compile times by reducing dependencies on standard headers and providing a lightweight `core API <https://fmt.dev/latest/api.html#core-api>`_: - - .. code:: c++ - - #include <fmt/core.h> - - fmt::print("The answer is {}.", 42); - - See `Compile time and code bloat - <https://github.com/fmtlib/fmt#compile-time-and-code-bloat>`_. - -* Added the `make_format_args + + .. code:: c++ + + #include <fmt/core.h> + + fmt::print("The answer is {}.", 42); + + See `Compile time and code bloat + <https://github.com/fmtlib/fmt#compile-time-and-code-bloat>`_. + +* Added the `make_format_args <https://fmt.dev/latest/api.html#_CPPv2N3fmt16make_format_argsEDpRK4Args>`_ - function for capturing formatting arguments: - - .. code:: c++ - - // Prints formatted error message. - void vreport_error(const char *format, fmt::format_args args) { - fmt::print("Error: "); - fmt::vprint(format, args); - } - template <typename... Args> - void report_error(const char *format, const Args & ... args) { - vreport_error(format, fmt::make_format_args(args...)); - } - -* Added the ``make_printf_args`` function for capturing ``printf`` arguments - (`#687 <https://github.com/fmtlib/fmt/issues/687>`_, - `#694 <https://github.com/fmtlib/fmt/pull/694>`_). - Thanks `@Kronuz (Germán Méndez Bravo) <https://github.com/Kronuz>`_. - -* Added prefix ``v`` to non-variadic functions taking ``format_args`` to - distinguish them from variadic ones: - - .. code:: c++ - - std::string vformat(string_view format_str, format_args args); - - template <typename... Args> - std::string format(string_view format_str, const Args & ... args); - -* Added experimental support for formatting ranges, containers and tuple-like - types in ``fmt/ranges.h`` (`#735 <https://github.com/fmtlib/fmt/pull/735>`_): - - .. code:: c++ - - #include <fmt/ranges.h> - - std::vector<int> v = {1, 2, 3}; - fmt::print("{}", v); // prints {1, 2, 3} - - Thanks `@Remotion (Remo) <https://github.com/Remotion>`_. - -* Implemented ``wchar_t`` date and time formatting - (`#712 <https://github.com/fmtlib/fmt/pull/712>`_): - - .. code:: c++ - - #include <fmt/time.h> - - std::time_t t = std::time(nullptr); - auto s = fmt::format(L"The date is {:%Y-%m-%d}.", *std::localtime(&t)); - - Thanks `@DanielaE (Daniela Engert) <https://github.com/DanielaE>`_. - -* Provided more wide string overloads - (`#724 <https://github.com/fmtlib/fmt/pull/724>`_). - Thanks `@DanielaE (Daniela Engert) <https://github.com/DanielaE>`_. - -* Switched from a custom null-terminated string view class to ``string_view`` - in the format API and provided ``fmt::string_view`` which implements a subset - of ``std::string_view`` API for pre-C++17 systems. - -* Added support for ``std::experimental::string_view`` - (`#607 <https://github.com/fmtlib/fmt/pull/607>`_): - - .. code:: c++ - - #include <fmt/core.h> - #include <experimental/string_view> - - fmt::print("{}", std::experimental::string_view("foo")); - - Thanks `@virgiliofornazin (Virgilio Alexandre Fornazin) - <https://github.com/virgiliofornazin>`__. - -* Allowed mixing named and automatic arguments: - - .. code:: c++ - - fmt::format("{} {two}", 1, fmt::arg("two", 2)); - -* Removed the write API in favor of the `format API + function for capturing formatting arguments: + + .. code:: c++ + + // Prints formatted error message. + void vreport_error(const char *format, fmt::format_args args) { + fmt::print("Error: "); + fmt::vprint(format, args); + } + template <typename... Args> + void report_error(const char *format, const Args & ... args) { + vreport_error(format, fmt::make_format_args(args...)); + } + +* Added the ``make_printf_args`` function for capturing ``printf`` arguments + (`#687 <https://github.com/fmtlib/fmt/issues/687>`_, + `#694 <https://github.com/fmtlib/fmt/pull/694>`_). + Thanks `@Kronuz (Germán Méndez Bravo) <https://github.com/Kronuz>`_. + +* Added prefix ``v`` to non-variadic functions taking ``format_args`` to + distinguish them from variadic ones: + + .. code:: c++ + + std::string vformat(string_view format_str, format_args args); + + template <typename... Args> + std::string format(string_view format_str, const Args & ... args); + +* Added experimental support for formatting ranges, containers and tuple-like + types in ``fmt/ranges.h`` (`#735 <https://github.com/fmtlib/fmt/pull/735>`_): + + .. code:: c++ + + #include <fmt/ranges.h> + + std::vector<int> v = {1, 2, 3}; + fmt::print("{}", v); // prints {1, 2, 3} + + Thanks `@Remotion (Remo) <https://github.com/Remotion>`_. + +* Implemented ``wchar_t`` date and time formatting + (`#712 <https://github.com/fmtlib/fmt/pull/712>`_): + + .. code:: c++ + + #include <fmt/time.h> + + std::time_t t = std::time(nullptr); + auto s = fmt::format(L"The date is {:%Y-%m-%d}.", *std::localtime(&t)); + + Thanks `@DanielaE (Daniela Engert) <https://github.com/DanielaE>`_. + +* Provided more wide string overloads + (`#724 <https://github.com/fmtlib/fmt/pull/724>`_). + Thanks `@DanielaE (Daniela Engert) <https://github.com/DanielaE>`_. + +* Switched from a custom null-terminated string view class to ``string_view`` + in the format API and provided ``fmt::string_view`` which implements a subset + of ``std::string_view`` API for pre-C++17 systems. + +* Added support for ``std::experimental::string_view`` + (`#607 <https://github.com/fmtlib/fmt/pull/607>`_): + + .. code:: c++ + + #include <fmt/core.h> + #include <experimental/string_view> + + fmt::print("{}", std::experimental::string_view("foo")); + + Thanks `@virgiliofornazin (Virgilio Alexandre Fornazin) + <https://github.com/virgiliofornazin>`__. + +* Allowed mixing named and automatic arguments: + + .. code:: c++ + + fmt::format("{} {two}", 1, fmt::arg("two", 2)); + +* Removed the write API in favor of the `format API <https://fmt.dev/latest/api.html#format-api>`_ with compile-time handling of - format strings. - -* Disallowed formatting of multibyte strings into a wide character target - (`#606 <https://github.com/fmtlib/fmt/pull/606>`_). - -* Improved documentation - (`#515 <https://github.com/fmtlib/fmt/pull/515>`_, - `#614 <https://github.com/fmtlib/fmt/issues/614>`_, - `#617 <https://github.com/fmtlib/fmt/pull/617>`_, - `#661 <https://github.com/fmtlib/fmt/pull/661>`_, - `#680 <https://github.com/fmtlib/fmt/pull/680>`_). - Thanks `@ibell (Ian Bell) <https://github.com/ibell>`_, - `@mihaitodor (Mihai Todor) <https://github.com/mihaitodor>`_, and - `@johnthagen <https://github.com/johnthagen>`_. - -* Implemented more efficient handling of large number of format arguments. - -* Introduced an inline namespace for symbol versioning. - -* Added debug postfix ``d`` to the ``fmt`` library name - (`#636 <https://github.com/fmtlib/fmt/issues/636>`_). - -* Removed unnecessary ``fmt/`` prefix in includes - (`#397 <https://github.com/fmtlib/fmt/pull/397>`_). - Thanks `@chronoxor (Ivan Shynkarenka) <https://github.com/chronoxor>`_. - -* Moved ``fmt/*.h`` to ``include/fmt/*.h`` to prevent irrelevant files and - directories appearing on the include search paths when fmt is used as a - subproject and moved source files to the ``src`` directory. - -* Added qmake project file ``support/fmt.pro`` - (`#641 <https://github.com/fmtlib/fmt/pull/641>`_). - Thanks `@cowo78 (Giuseppe Corbelli) <https://github.com/cowo78>`_. - -* Added Gradle build file ``support/build.gradle`` - (`#649 <https://github.com/fmtlib/fmt/pull/649>`_). - Thanks `@luncliff (Park DongHa) <https://github.com/luncliff>`_. - -* Removed ``FMT_CPPFORMAT`` CMake option. - -* Fixed a name conflict with the macro ``CHAR_WIDTH`` in glibc - (`#616 <https://github.com/fmtlib/fmt/pull/616>`_). - Thanks `@aroig (Abdó Roig-Maranges) <https://github.com/aroig>`_. - -* Fixed handling of nested braces in ``fmt::join`` - (`#638 <https://github.com/fmtlib/fmt/issues/638>`_). - -* Added ``SOURCELINK_SUFFIX`` for compatibility with Sphinx 1.5 - (`#497 <https://github.com/fmtlib/fmt/pull/497>`_). - Thanks `@ginggs (Graham Inggs) <https://github.com/ginggs>`_. - -* Added a missing ``inline`` in the header-only mode - (`#626 <https://github.com/fmtlib/fmt/pull/626>`_). - Thanks `@aroig (Abdó Roig-Maranges) <https://github.com/aroig>`_. - -* Fixed various compiler warnings - (`#640 <https://github.com/fmtlib/fmt/pull/640>`_, - `#656 <https://github.com/fmtlib/fmt/pull/656>`_, - `#679 <https://github.com/fmtlib/fmt/pull/679>`_, - `#681 <https://github.com/fmtlib/fmt/pull/681>`_, - `#705 <https://github.com/fmtlib/fmt/pull/705>`__, - `#715 <https://github.com/fmtlib/fmt/issues/715>`_, - `#717 <https://github.com/fmtlib/fmt/pull/717>`_, - `#720 <https://github.com/fmtlib/fmt/pull/720>`_, - `#723 <https://github.com/fmtlib/fmt/pull/723>`_, - `#726 <https://github.com/fmtlib/fmt/pull/726>`_, - `#730 <https://github.com/fmtlib/fmt/pull/730>`_, - `#739 <https://github.com/fmtlib/fmt/pull/739>`_). - Thanks `@peterbell10 <https://github.com/peterbell10>`_, - `@LarsGullik <https://github.com/LarsGullik>`_, - `@foonathan (Jonathan Müller) <https://github.com/foonathan>`_, - `@eliaskosunen (Elias Kosunen) <https://github.com/eliaskosunen>`_, - `@christianparpart (Christian Parpart) <https://github.com/christianparpart>`_, - `@DanielaE (Daniela Engert) <https://github.com/DanielaE>`_, - and `@mwinterb <https://github.com/mwinterb>`_. - -* Worked around an MSVC bug and fixed several warnings - (`#653 <https://github.com/fmtlib/fmt/pull/653>`_). - Thanks `@alabuzhev (Alex Alabuzhev) <https://github.com/alabuzhev>`_. - -* Worked around GCC bug 67371 - (`#682 <https://github.com/fmtlib/fmt/issues/682>`_). - -* Fixed compilation with ``-fno-exceptions`` - (`#655 <https://github.com/fmtlib/fmt/pull/655>`_). - Thanks `@chenxiaolong (Andrew Gunnerson) <https://github.com/chenxiaolong>`_. - -* Made ``constexpr remove_prefix`` gcc version check tighter - (`#648 <https://github.com/fmtlib/fmt/issues/648>`_). - -* Renamed internal type enum constants to prevent collision with poorly written - C libraries (`#644 <https://github.com/fmtlib/fmt/issues/644>`_). - -* Added detection of ``wostream operator<<`` - (`#650 <https://github.com/fmtlib/fmt/issues/650>`_). - -* Fixed compilation on OpenBSD - (`#660 <https://github.com/fmtlib/fmt/pull/660>`_). - Thanks `@hubslave <https://github.com/hubslave>`_. - -* Fixed compilation on FreeBSD 12 - (`#732 <https://github.com/fmtlib/fmt/pull/732>`_). - Thanks `@dankm <https://github.com/dankm>`_. - -* Fixed compilation when there is a mismatch between ``-std`` options between - the library and user code - (`#664 <https://github.com/fmtlib/fmt/issues/664>`_). - -* Fixed compilation with GCC 7 and ``-std=c++11`` - (`#734 <https://github.com/fmtlib/fmt/issues/734>`_). - -* Improved generated binary code on GCC 7 and older - (`#668 <https://github.com/fmtlib/fmt/issues/668>`_). - -* Fixed handling of numeric alignment with no width - (`#675 <https://github.com/fmtlib/fmt/issues/675>`_). - -* Fixed handling of empty strings in UTF8/16 converters - (`#676 <https://github.com/fmtlib/fmt/pull/676>`_). - Thanks `@vgalka-sl (Vasili Galka) <https://github.com/vgalka-sl>`_. - -* Fixed formatting of an empty ``string_view`` - (`#689 <https://github.com/fmtlib/fmt/issues/689>`_). - -* Fixed detection of ``string_view`` on libc++ - (`#686 <https://github.com/fmtlib/fmt/issues/686>`_). - -* Fixed DLL issues (`#696 <https://github.com/fmtlib/fmt/pull/696>`_). - Thanks `@sebkoenig <https://github.com/sebkoenig>`_. - -* Fixed compile checks for mixing narrow and wide strings - (`#690 <https://github.com/fmtlib/fmt/issues/690>`_). - -* Disabled unsafe implicit conversion to ``std::string`` - (`#729 <https://github.com/fmtlib/fmt/issues/729>`_). - -* Fixed handling of reused format specs (as in ``fmt::join``) for pointers - (`#725 <https://github.com/fmtlib/fmt/pull/725>`_). - Thanks `@mwinterb <https://github.com/mwinterb>`_. - -* Fixed installation of ``fmt/ranges.h`` - (`#738 <https://github.com/fmtlib/fmt/pull/738>`_). - Thanks `@sv1990 <https://github.com/sv1990>`_. - -4.1.0 - 2017-12-20 ------------------- - -* Added ``fmt::to_wstring()`` in addition to ``fmt::to_string()`` - (`#559 <https://github.com/fmtlib/fmt/pull/559>`_). - Thanks `@alabuzhev (Alex Alabuzhev) <https://github.com/alabuzhev>`_. - -* Added support for C++17 ``std::string_view`` - (`#571 <https://github.com/fmtlib/fmt/pull/571>`_ and - `#578 <https://github.com/fmtlib/fmt/pull/578>`_). - Thanks `@thelostt (Mário Feroldi) <https://github.com/thelostt>`_ and - `@mwinterb <https://github.com/mwinterb>`_. - -* Enabled stream exceptions to catch errors - (`#581 <https://github.com/fmtlib/fmt/issues/581>`_). - Thanks `@crusader-mike <https://github.com/crusader-mike>`_. - -* Allowed formatting of class hierarchies with ``fmt::format_arg()`` - (`#547 <https://github.com/fmtlib/fmt/pull/547>`_). - Thanks `@rollbear (Björn Fahller) <https://github.com/rollbear>`_. - -* Removed limitations on character types - (`#563 <https://github.com/fmtlib/fmt/pull/563>`_). - Thanks `@Yelnats321 (Elnar Dakeshov) <https://github.com/Yelnats321>`_. - -* Conditionally enabled use of ``std::allocator_traits`` - (`#583 <https://github.com/fmtlib/fmt/pull/583>`_). - Thanks `@mwinterb <https://github.com/mwinterb>`_. - -* Added support for ``const`` variadic member function emulation with - ``FMT_VARIADIC_CONST`` (`#591 <https://github.com/fmtlib/fmt/pull/591>`_). - Thanks `@ludekvodicka (Ludek Vodicka) <https://github.com/ludekvodicka>`_. - -* Various bugfixes: bad overflow check, unsupported implicit type conversion - when determining formatting function, test segfaults - (`#551 <https://github.com/fmtlib/fmt/issues/551>`_), ill-formed macros - (`#542 <https://github.com/fmtlib/fmt/pull/542>`_) and ambiguous overloads - (`#580 <https://github.com/fmtlib/fmt/issues/580>`_). - Thanks `@xylosper (Byoung-young Lee) <https://github.com/xylosper>`_. - -* Prevented warnings on MSVC (`#605 <https://github.com/fmtlib/fmt/pull/605>`_, - `#602 <https://github.com/fmtlib/fmt/pull/602>`_, and - `#545 <https://github.com/fmtlib/fmt/pull/545>`_), - clang (`#582 <https://github.com/fmtlib/fmt/pull/582>`_), - GCC (`#573 <https://github.com/fmtlib/fmt/issues/573>`_), - various conversion warnings (`#609 <https://github.com/fmtlib/fmt/pull/609>`_, - `#567 <https://github.com/fmtlib/fmt/pull/567>`_, - `#553 <https://github.com/fmtlib/fmt/pull/553>`_ and - `#553 <https://github.com/fmtlib/fmt/pull/553>`_), and added ``override`` and - ``[[noreturn]]`` (`#549 <https://github.com/fmtlib/fmt/pull/549>`_ and - `#555 <https://github.com/fmtlib/fmt/issues/555>`_). - Thanks `@alabuzhev (Alex Alabuzhev) <https://github.com/alabuzhev>`_, - `@virgiliofornazin (Virgilio Alexandre Fornazin) - <https://gihtub.com/virgiliofornazin>`_, - `@alexanderbock (Alexander Bock) <https://github.com/alexanderbock>`_, - `@yumetodo <https://github.com/yumetodo>`_, - `@VaderY (Császár Mátyás) <https://github.com/VaderY>`_, - `@jpcima (JP Cimalando) <https://github.com/jpcima>`_, - `@thelostt (Mário Feroldi) <https://github.com/thelostt>`_, and - `@Manu343726 (Manu Sánchez) <https://github.com/Manu343726>`_. - -* Improved CMake: Used ``GNUInstallDirs`` to set installation location - (`#610 <https://github.com/fmtlib/fmt/pull/610>`_) and fixed warnings - (`#536 <https://github.com/fmtlib/fmt/pull/536>`_ and - `#556 <https://github.com/fmtlib/fmt/pull/556>`_). - Thanks `@mikecrowe (Mike Crowe) <https://github.com/mikecrowe>`_, - `@evgen231 <https://github.com/evgen231>`_ and - `@henryiii (Henry Schreiner) <https://github.com/henryiii>`_. - -4.0.0 - 2017-06-27 ------------------- - -* Removed old compatibility headers ``cppformat/*.h`` and CMake options - (`#527 <https://github.com/fmtlib/fmt/pull/527>`_). - Thanks `@maddinat0r (Alex Martin) <https://github.com/maddinat0r>`_. - -* Added ``string.h`` containing ``fmt::to_string()`` as alternative to - ``std::to_string()`` as well as other string writer functionality - (`#326 <https://github.com/fmtlib/fmt/issues/326>`_ and - `#441 <https://github.com/fmtlib/fmt/pull/441>`_): - - .. code:: c++ - - #include "fmt/string.h" - - std::string answer = fmt::to_string(42); - - Thanks to `@glebov-andrey (Andrey Glebov) - <https://github.com/glebov-andrey>`_. - -* Moved ``fmt::printf()`` to new ``printf.h`` header and allowed ``%s`` as - generic specifier (`#453 <https://github.com/fmtlib/fmt/pull/453>`_), - made ``%.f`` more conformant to regular ``printf()`` - (`#490 <https://github.com/fmtlib/fmt/pull/490>`_), added custom writer - support (`#476 <https://github.com/fmtlib/fmt/issues/476>`_) and implemented - missing custom argument formatting - (`#339 <https://github.com/fmtlib/fmt/pull/339>`_ and - `#340 <https://github.com/fmtlib/fmt/pull/340>`_): - - .. code:: c++ - - #include "fmt/printf.h" + format strings. + +* Disallowed formatting of multibyte strings into a wide character target + (`#606 <https://github.com/fmtlib/fmt/pull/606>`_). + +* Improved documentation + (`#515 <https://github.com/fmtlib/fmt/pull/515>`_, + `#614 <https://github.com/fmtlib/fmt/issues/614>`_, + `#617 <https://github.com/fmtlib/fmt/pull/617>`_, + `#661 <https://github.com/fmtlib/fmt/pull/661>`_, + `#680 <https://github.com/fmtlib/fmt/pull/680>`_). + Thanks `@ibell (Ian Bell) <https://github.com/ibell>`_, + `@mihaitodor (Mihai Todor) <https://github.com/mihaitodor>`_, and + `@johnthagen <https://github.com/johnthagen>`_. + +* Implemented more efficient handling of large number of format arguments. + +* Introduced an inline namespace for symbol versioning. + +* Added debug postfix ``d`` to the ``fmt`` library name + (`#636 <https://github.com/fmtlib/fmt/issues/636>`_). + +* Removed unnecessary ``fmt/`` prefix in includes + (`#397 <https://github.com/fmtlib/fmt/pull/397>`_). + Thanks `@chronoxor (Ivan Shynkarenka) <https://github.com/chronoxor>`_. + +* Moved ``fmt/*.h`` to ``include/fmt/*.h`` to prevent irrelevant files and + directories appearing on the include search paths when fmt is used as a + subproject and moved source files to the ``src`` directory. + +* Added qmake project file ``support/fmt.pro`` + (`#641 <https://github.com/fmtlib/fmt/pull/641>`_). + Thanks `@cowo78 (Giuseppe Corbelli) <https://github.com/cowo78>`_. + +* Added Gradle build file ``support/build.gradle`` + (`#649 <https://github.com/fmtlib/fmt/pull/649>`_). + Thanks `@luncliff (Park DongHa) <https://github.com/luncliff>`_. + +* Removed ``FMT_CPPFORMAT`` CMake option. + +* Fixed a name conflict with the macro ``CHAR_WIDTH`` in glibc + (`#616 <https://github.com/fmtlib/fmt/pull/616>`_). + Thanks `@aroig (Abdó Roig-Maranges) <https://github.com/aroig>`_. + +* Fixed handling of nested braces in ``fmt::join`` + (`#638 <https://github.com/fmtlib/fmt/issues/638>`_). + +* Added ``SOURCELINK_SUFFIX`` for compatibility with Sphinx 1.5 + (`#497 <https://github.com/fmtlib/fmt/pull/497>`_). + Thanks `@ginggs (Graham Inggs) <https://github.com/ginggs>`_. + +* Added a missing ``inline`` in the header-only mode + (`#626 <https://github.com/fmtlib/fmt/pull/626>`_). + Thanks `@aroig (Abdó Roig-Maranges) <https://github.com/aroig>`_. + +* Fixed various compiler warnings + (`#640 <https://github.com/fmtlib/fmt/pull/640>`_, + `#656 <https://github.com/fmtlib/fmt/pull/656>`_, + `#679 <https://github.com/fmtlib/fmt/pull/679>`_, + `#681 <https://github.com/fmtlib/fmt/pull/681>`_, + `#705 <https://github.com/fmtlib/fmt/pull/705>`__, + `#715 <https://github.com/fmtlib/fmt/issues/715>`_, + `#717 <https://github.com/fmtlib/fmt/pull/717>`_, + `#720 <https://github.com/fmtlib/fmt/pull/720>`_, + `#723 <https://github.com/fmtlib/fmt/pull/723>`_, + `#726 <https://github.com/fmtlib/fmt/pull/726>`_, + `#730 <https://github.com/fmtlib/fmt/pull/730>`_, + `#739 <https://github.com/fmtlib/fmt/pull/739>`_). + Thanks `@peterbell10 <https://github.com/peterbell10>`_, + `@LarsGullik <https://github.com/LarsGullik>`_, + `@foonathan (Jonathan Müller) <https://github.com/foonathan>`_, + `@eliaskosunen (Elias Kosunen) <https://github.com/eliaskosunen>`_, + `@christianparpart (Christian Parpart) <https://github.com/christianparpart>`_, + `@DanielaE (Daniela Engert) <https://github.com/DanielaE>`_, + and `@mwinterb <https://github.com/mwinterb>`_. + +* Worked around an MSVC bug and fixed several warnings + (`#653 <https://github.com/fmtlib/fmt/pull/653>`_). + Thanks `@alabuzhev (Alex Alabuzhev) <https://github.com/alabuzhev>`_. + +* Worked around GCC bug 67371 + (`#682 <https://github.com/fmtlib/fmt/issues/682>`_). + +* Fixed compilation with ``-fno-exceptions`` + (`#655 <https://github.com/fmtlib/fmt/pull/655>`_). + Thanks `@chenxiaolong (Andrew Gunnerson) <https://github.com/chenxiaolong>`_. + +* Made ``constexpr remove_prefix`` gcc version check tighter + (`#648 <https://github.com/fmtlib/fmt/issues/648>`_). + +* Renamed internal type enum constants to prevent collision with poorly written + C libraries (`#644 <https://github.com/fmtlib/fmt/issues/644>`_). + +* Added detection of ``wostream operator<<`` + (`#650 <https://github.com/fmtlib/fmt/issues/650>`_). + +* Fixed compilation on OpenBSD + (`#660 <https://github.com/fmtlib/fmt/pull/660>`_). + Thanks `@hubslave <https://github.com/hubslave>`_. + +* Fixed compilation on FreeBSD 12 + (`#732 <https://github.com/fmtlib/fmt/pull/732>`_). + Thanks `@dankm <https://github.com/dankm>`_. + +* Fixed compilation when there is a mismatch between ``-std`` options between + the library and user code + (`#664 <https://github.com/fmtlib/fmt/issues/664>`_). + +* Fixed compilation with GCC 7 and ``-std=c++11`` + (`#734 <https://github.com/fmtlib/fmt/issues/734>`_). + +* Improved generated binary code on GCC 7 and older + (`#668 <https://github.com/fmtlib/fmt/issues/668>`_). + +* Fixed handling of numeric alignment with no width + (`#675 <https://github.com/fmtlib/fmt/issues/675>`_). + +* Fixed handling of empty strings in UTF8/16 converters + (`#676 <https://github.com/fmtlib/fmt/pull/676>`_). + Thanks `@vgalka-sl (Vasili Galka) <https://github.com/vgalka-sl>`_. + +* Fixed formatting of an empty ``string_view`` + (`#689 <https://github.com/fmtlib/fmt/issues/689>`_). + +* Fixed detection of ``string_view`` on libc++ + (`#686 <https://github.com/fmtlib/fmt/issues/686>`_). + +* Fixed DLL issues (`#696 <https://github.com/fmtlib/fmt/pull/696>`_). + Thanks `@sebkoenig <https://github.com/sebkoenig>`_. + +* Fixed compile checks for mixing narrow and wide strings + (`#690 <https://github.com/fmtlib/fmt/issues/690>`_). + +* Disabled unsafe implicit conversion to ``std::string`` + (`#729 <https://github.com/fmtlib/fmt/issues/729>`_). + +* Fixed handling of reused format specs (as in ``fmt::join``) for pointers + (`#725 <https://github.com/fmtlib/fmt/pull/725>`_). + Thanks `@mwinterb <https://github.com/mwinterb>`_. + +* Fixed installation of ``fmt/ranges.h`` + (`#738 <https://github.com/fmtlib/fmt/pull/738>`_). + Thanks `@sv1990 <https://github.com/sv1990>`_. + +4.1.0 - 2017-12-20 +------------------ + +* Added ``fmt::to_wstring()`` in addition to ``fmt::to_string()`` + (`#559 <https://github.com/fmtlib/fmt/pull/559>`_). + Thanks `@alabuzhev (Alex Alabuzhev) <https://github.com/alabuzhev>`_. + +* Added support for C++17 ``std::string_view`` + (`#571 <https://github.com/fmtlib/fmt/pull/571>`_ and + `#578 <https://github.com/fmtlib/fmt/pull/578>`_). + Thanks `@thelostt (Mário Feroldi) <https://github.com/thelostt>`_ and + `@mwinterb <https://github.com/mwinterb>`_. + +* Enabled stream exceptions to catch errors + (`#581 <https://github.com/fmtlib/fmt/issues/581>`_). + Thanks `@crusader-mike <https://github.com/crusader-mike>`_. + +* Allowed formatting of class hierarchies with ``fmt::format_arg()`` + (`#547 <https://github.com/fmtlib/fmt/pull/547>`_). + Thanks `@rollbear (Björn Fahller) <https://github.com/rollbear>`_. + +* Removed limitations on character types + (`#563 <https://github.com/fmtlib/fmt/pull/563>`_). + Thanks `@Yelnats321 (Elnar Dakeshov) <https://github.com/Yelnats321>`_. + +* Conditionally enabled use of ``std::allocator_traits`` + (`#583 <https://github.com/fmtlib/fmt/pull/583>`_). + Thanks `@mwinterb <https://github.com/mwinterb>`_. + +* Added support for ``const`` variadic member function emulation with + ``FMT_VARIADIC_CONST`` (`#591 <https://github.com/fmtlib/fmt/pull/591>`_). + Thanks `@ludekvodicka (Ludek Vodicka) <https://github.com/ludekvodicka>`_. + +* Various bugfixes: bad overflow check, unsupported implicit type conversion + when determining formatting function, test segfaults + (`#551 <https://github.com/fmtlib/fmt/issues/551>`_), ill-formed macros + (`#542 <https://github.com/fmtlib/fmt/pull/542>`_) and ambiguous overloads + (`#580 <https://github.com/fmtlib/fmt/issues/580>`_). + Thanks `@xylosper (Byoung-young Lee) <https://github.com/xylosper>`_. + +* Prevented warnings on MSVC (`#605 <https://github.com/fmtlib/fmt/pull/605>`_, + `#602 <https://github.com/fmtlib/fmt/pull/602>`_, and + `#545 <https://github.com/fmtlib/fmt/pull/545>`_), + clang (`#582 <https://github.com/fmtlib/fmt/pull/582>`_), + GCC (`#573 <https://github.com/fmtlib/fmt/issues/573>`_), + various conversion warnings (`#609 <https://github.com/fmtlib/fmt/pull/609>`_, + `#567 <https://github.com/fmtlib/fmt/pull/567>`_, + `#553 <https://github.com/fmtlib/fmt/pull/553>`_ and + `#553 <https://github.com/fmtlib/fmt/pull/553>`_), and added ``override`` and + ``[[noreturn]]`` (`#549 <https://github.com/fmtlib/fmt/pull/549>`_ and + `#555 <https://github.com/fmtlib/fmt/issues/555>`_). + Thanks `@alabuzhev (Alex Alabuzhev) <https://github.com/alabuzhev>`_, + `@virgiliofornazin (Virgilio Alexandre Fornazin) + <https://gihtub.com/virgiliofornazin>`_, + `@alexanderbock (Alexander Bock) <https://github.com/alexanderbock>`_, + `@yumetodo <https://github.com/yumetodo>`_, + `@VaderY (Császár Mátyás) <https://github.com/VaderY>`_, + `@jpcima (JP Cimalando) <https://github.com/jpcima>`_, + `@thelostt (Mário Feroldi) <https://github.com/thelostt>`_, and + `@Manu343726 (Manu Sánchez) <https://github.com/Manu343726>`_. + +* Improved CMake: Used ``GNUInstallDirs`` to set installation location + (`#610 <https://github.com/fmtlib/fmt/pull/610>`_) and fixed warnings + (`#536 <https://github.com/fmtlib/fmt/pull/536>`_ and + `#556 <https://github.com/fmtlib/fmt/pull/556>`_). + Thanks `@mikecrowe (Mike Crowe) <https://github.com/mikecrowe>`_, + `@evgen231 <https://github.com/evgen231>`_ and + `@henryiii (Henry Schreiner) <https://github.com/henryiii>`_. + +4.0.0 - 2017-06-27 +------------------ + +* Removed old compatibility headers ``cppformat/*.h`` and CMake options + (`#527 <https://github.com/fmtlib/fmt/pull/527>`_). + Thanks `@maddinat0r (Alex Martin) <https://github.com/maddinat0r>`_. + +* Added ``string.h`` containing ``fmt::to_string()`` as alternative to + ``std::to_string()`` as well as other string writer functionality + (`#326 <https://github.com/fmtlib/fmt/issues/326>`_ and + `#441 <https://github.com/fmtlib/fmt/pull/441>`_): + + .. code:: c++ + + #include "fmt/string.h" - // %s format specifier can be used with any argument type. - fmt::printf("%s", 42); - - Thanks `@mojoBrendan <https://github.com/mojoBrendan>`_, - `@manylegged (Arthur Danskin) <https://github.com/manylegged>`_ and - `@spacemoose (Glen Stark) <https://github.com/spacemoose>`_. - See also `#360 <https://github.com/fmtlib/fmt/issues/360>`_, - `#335 <https://github.com/fmtlib/fmt/issues/335>`_ and - `#331 <https://github.com/fmtlib/fmt/issues/331>`_. - -* Added ``container.h`` containing a ``BasicContainerWriter`` - to write to containers like ``std::vector`` - (`#450 <https://github.com/fmtlib/fmt/pull/450>`_). - Thanks `@polyvertex (Jean-Charles Lefebvre) <https://github.com/polyvertex>`_. - -* Added ``fmt::join()`` function that takes a range and formats - its elements separated by a given string - (`#466 <https://github.com/fmtlib/fmt/pull/466>`_): - - .. code:: c++ + std::string answer = fmt::to_string(42); + + Thanks to `@glebov-andrey (Andrey Glebov) + <https://github.com/glebov-andrey>`_. + +* Moved ``fmt::printf()`` to new ``printf.h`` header and allowed ``%s`` as + generic specifier (`#453 <https://github.com/fmtlib/fmt/pull/453>`_), + made ``%.f`` more conformant to regular ``printf()`` + (`#490 <https://github.com/fmtlib/fmt/pull/490>`_), added custom writer + support (`#476 <https://github.com/fmtlib/fmt/issues/476>`_) and implemented + missing custom argument formatting + (`#339 <https://github.com/fmtlib/fmt/pull/339>`_ and + `#340 <https://github.com/fmtlib/fmt/pull/340>`_): + + .. code:: c++ + + #include "fmt/printf.h" - #include "fmt/format.h" + // %s format specifier can be used with any argument type. + fmt::printf("%s", 42); + + Thanks `@mojoBrendan <https://github.com/mojoBrendan>`_, + `@manylegged (Arthur Danskin) <https://github.com/manylegged>`_ and + `@spacemoose (Glen Stark) <https://github.com/spacemoose>`_. + See also `#360 <https://github.com/fmtlib/fmt/issues/360>`_, + `#335 <https://github.com/fmtlib/fmt/issues/335>`_ and + `#331 <https://github.com/fmtlib/fmt/issues/331>`_. + +* Added ``container.h`` containing a ``BasicContainerWriter`` + to write to containers like ``std::vector`` + (`#450 <https://github.com/fmtlib/fmt/pull/450>`_). + Thanks `@polyvertex (Jean-Charles Lefebvre) <https://github.com/polyvertex>`_. + +* Added ``fmt::join()`` function that takes a range and formats + its elements separated by a given string + (`#466 <https://github.com/fmtlib/fmt/pull/466>`_): + + .. code:: c++ + + #include "fmt/format.h" + + std::vector<double> v = {1.2, 3.4, 5.6}; + // Prints "(+01.20, +03.40, +05.60)". + fmt::print("({:+06.2f})", fmt::join(v.begin(), v.end(), ", ")); + + Thanks `@olivier80 <https://github.com/olivier80>`_. + +* Added support for custom formatting specifications to simplify customization + of built-in formatting (`#444 <https://github.com/fmtlib/fmt/pull/444>`_). + Thanks `@polyvertex (Jean-Charles Lefebvre) <https://github.com/polyvertex>`_. + See also `#439 <https://github.com/fmtlib/fmt/issues/439>`_. + +* Added ``fmt::format_system_error()`` for error code formatting + (`#323 <https://github.com/fmtlib/fmt/issues/323>`_ and + `#526 <https://github.com/fmtlib/fmt/pull/526>`_). + Thanks `@maddinat0r (Alex Martin) <https://github.com/maddinat0r>`_. + +* Added thread-safe ``fmt::localtime()`` and ``fmt::gmtime()`` + as replacement for the standard version to ``time.h`` + (`#396 <https://github.com/fmtlib/fmt/pull/396>`_). + Thanks `@codicodi <https://github.com/codicodi>`_. + +* Internal improvements to ``NamedArg`` and ``ArgLists`` + (`#389 <https://github.com/fmtlib/fmt/pull/389>`_ and + `#390 <https://github.com/fmtlib/fmt/pull/390>`_). + Thanks `@chronoxor <https://github.com/chronoxor>`_. + +* Fixed crash due to bug in ``FormatBuf`` + (`#493 <https://github.com/fmtlib/fmt/pull/493>`_). + Thanks `@effzeh <https://github.com/effzeh>`_. See also + `#480 <https://github.com/fmtlib/fmt/issues/480>`_ and + `#491 <https://github.com/fmtlib/fmt/issues/491>`_. + +* Fixed handling of wide strings in ``fmt::StringWriter``. + +* Improved compiler error messages + (`#357 <https://github.com/fmtlib/fmt/issues/357>`_). + +* Fixed various warnings and issues with various compilers + (`#494 <https://github.com/fmtlib/fmt/pull/494>`_, + `#499 <https://github.com/fmtlib/fmt/pull/499>`_, + `#483 <https://github.com/fmtlib/fmt/pull/483>`_, + `#485 <https://github.com/fmtlib/fmt/pull/485>`_, + `#482 <https://github.com/fmtlib/fmt/pull/482>`_, + `#475 <https://github.com/fmtlib/fmt/pull/475>`_, + `#473 <https://github.com/fmtlib/fmt/pull/473>`_ and + `#414 <https://github.com/fmtlib/fmt/pull/414>`_). + Thanks `@chronoxor <https://github.com/chronoxor>`_, + `@zhaohuaxishi <https://github.com/zhaohuaxishi>`_, + `@pkestene (Pierre Kestener) <https://github.com/pkestene>`_, + `@dschmidt (Dominik Schmidt) <https://github.com/dschmidt>`_ and + `@0x414c (Alexey Gorishny) <https://github.com/0x414c>`_ . + +* Improved CMake: targets are now namespaced + (`#511 <https://github.com/fmtlib/fmt/pull/511>`_ and + `#513 <https://github.com/fmtlib/fmt/pull/513>`_), supported header-only + ``printf.h`` (`#354 <https://github.com/fmtlib/fmt/pull/354>`_), fixed issue + with minimal supported library subset + (`#418 <https://github.com/fmtlib/fmt/issues/418>`_, + `#419 <https://github.com/fmtlib/fmt/pull/419>`_ and + `#420 <https://github.com/fmtlib/fmt/pull/420>`_). + Thanks `@bjoernthiel (Bjoern Thiel) <https://github.com/bjoernthiel>`_, + `@niosHD (Mario Werner) <https://github.com/niosHD>`_, + `@LogicalKnight (Sean LK) <https://github.com/LogicalKnight>`_ and + `@alabuzhev (Alex Alabuzhev) <https://github.com/alabuzhev>`_. + +* Improved documentation. Thanks to + `@pwm1234 (Phil) <https://github.com/pwm1234>`_ for + `#393 <https://github.com/fmtlib/fmt/pull/393>`_. + +3.0.2 - 2017-06-14 +------------------ + +* Added ``FMT_VERSION`` macro + (`#411 <https://github.com/fmtlib/fmt/issues/411>`_). + +* Used ``FMT_NULL`` instead of literal ``0`` + (`#409 <https://github.com/fmtlib/fmt/pull/409>`_). + Thanks `@alabuzhev (Alex Alabuzhev) <https://github.com/alabuzhev>`_. + +* Added extern templates for ``format_float`` + (`#413 <https://github.com/fmtlib/fmt/issues/413>`_). + +* Fixed implicit conversion issue + (`#507 <https://github.com/fmtlib/fmt/issues/507>`_). + +* Fixed signbit detection (`#423 <https://github.com/fmtlib/fmt/issues/423>`_). + +* Fixed naming collision (`#425 <https://github.com/fmtlib/fmt/issues/425>`_). + +* Fixed missing intrinsic for C++/CLI + (`#457 <https://github.com/fmtlib/fmt/pull/457>`_). + Thanks `@calumr (Calum Robinson) <https://github.com/calumr>`_ + +* Fixed Android detection (`#458 <https://github.com/fmtlib/fmt/pull/458>`_). + Thanks `@Gachapen (Magnus Bjerke Vik) <https://github.com/Gachapen>`_. + +* Use lean ``windows.h`` if not in header-only mode + (`#503 <https://github.com/fmtlib/fmt/pull/503>`_). + Thanks `@Quentin01 (Quentin Buathier) <https://github.com/Quentin01>`_. + +* Fixed issue with CMake exporting C++11 flag + (`#445 <https://github.com/fmtlib/fmt/pull/455>`_). + Thanks `@EricWF (Eric) <https://github.com/EricWF>`_. + +* Fixed issue with nvcc and MSVC compiler bug and MinGW + (`#505 <https://github.com/fmtlib/fmt/issues/505>`_). + +* Fixed DLL issues (`#469 <https://github.com/fmtlib/fmt/pull/469>`_ and + `#502 <https://github.com/fmtlib/fmt/pull/502>`_). + Thanks `@richardeakin (Richard Eakin) <https://github.com/richardeakin>`_ and + `@AndreasSchoenle (Andreas Schönle) <https://github.com/AndreasSchoenle>`_. + +* Fixed test compilation under FreeBSD + (`#433 <https://github.com/fmtlib/fmt/issues/433>`_). + +* Fixed various warnings (`#403 <https://github.com/fmtlib/fmt/pull/403>`_, + `#410 <https://github.com/fmtlib/fmt/pull/410>`_ and + `#510 <https://github.com/fmtlib/fmt/pull/510>`_). + Thanks `@Lecetem <https://github.com/Lectem>`_, + `@chenhayat (Chen Hayat) <https://github.com/chenhayat>`_ and + `@trozen <https://github.com/trozen>`_. + +* Worked around a broken ``__builtin_clz`` in clang with MS codegen + (`#519 <https://github.com/fmtlib/fmt/issues/519>`_). + +* Removed redundant include + (`#479 <https://github.com/fmtlib/fmt/issues/479>`_). + +* Fixed documentation issues. + +3.0.1 - 2016-11-01 +------------------ +* Fixed handling of thousands separator + (`#353 <https://github.com/fmtlib/fmt/issues/353>`_). + +* Fixed handling of ``unsigned char`` strings + (`#373 <https://github.com/fmtlib/fmt/issues/373>`_). + +* Corrected buffer growth when formatting time + (`#367 <https://github.com/fmtlib/fmt/issues/367>`_). + +* Removed warnings under MSVC and clang + (`#318 <https://github.com/fmtlib/fmt/issues/318>`_, + `#250 <https://github.com/fmtlib/fmt/issues/250>`_, also merged + `#385 <https://github.com/fmtlib/fmt/pull/385>`_ and + `#361 <https://github.com/fmtlib/fmt/pull/361>`_). + Thanks `@jcelerier (Jean-Michaël Celerier) <https://github.com/jcelerier>`_ + and `@nmoehrle (Nils Moehrle) <https://github.com/nmoehrle>`_. + +* Fixed compilation issues under Android + (`#327 <https://github.com/fmtlib/fmt/pull/327>`_, + `#345 <https://github.com/fmtlib/fmt/issues/345>`_ and + `#381 <https://github.com/fmtlib/fmt/pull/381>`_), + FreeBSD (`#358 <https://github.com/fmtlib/fmt/pull/358>`_), + Cygwin (`#388 <https://github.com/fmtlib/fmt/issues/388>`_), + MinGW (`#355 <https://github.com/fmtlib/fmt/issues/355>`_) as well as other + issues (`#350 <https://github.com/fmtlib/fmt/issues/350>`_, + `#366 <https://github.com/fmtlib/fmt/issues/355>`_, + `#348 <https://github.com/fmtlib/fmt/pull/348>`_, + `#402 <https://github.com/fmtlib/fmt/pull/402>`_, + `#405 <https://github.com/fmtlib/fmt/pull/405>`_). + Thanks to `@dpantele (Dmitry) <https://github.com/dpantele>`_, + `@hghwng (Hugh Wang) <https://github.com/hghwng>`_, + `@arvedarved (Tilman Keskinöz) <https://github.com/arvedarved>`_, + `@LogicalKnight (Sean) <https://github.com/LogicalKnight>`_ and + `@JanHellwig (Jan Hellwig) <https://github.com/janhellwig>`_. + +* Fixed some documentation issues and extended specification + (`#320 <https://github.com/fmtlib/fmt/issues/320>`_, + `#333 <https://github.com/fmtlib/fmt/pull/333>`_, + `#347 <https://github.com/fmtlib/fmt/issues/347>`_, + `#362 <https://github.com/fmtlib/fmt/pull/362>`_). + Thanks to `@smellman (Taro Matsuzawa aka. btm) + <https://github.com/smellman>`_. + +3.0.0 - 2016-05-07 +------------------ + +* The project has been renamed from C++ Format (cppformat) to fmt for + consistency with the used namespace and macro prefix + (`#307 <https://github.com/fmtlib/fmt/issues/307>`_). + Library headers are now located in the ``fmt`` directory: + + .. code:: c++ + + #include "fmt/format.h" + + Including ``format.h`` from the ``cppformat`` directory is deprecated + but works via a proxy header which will be removed in the next major version. - std::vector<double> v = {1.2, 3.4, 5.6}; - // Prints "(+01.20, +03.40, +05.60)". - fmt::print("({:+06.2f})", fmt::join(v.begin(), v.end(), ", ")); - - Thanks `@olivier80 <https://github.com/olivier80>`_. - -* Added support for custom formatting specifications to simplify customization - of built-in formatting (`#444 <https://github.com/fmtlib/fmt/pull/444>`_). - Thanks `@polyvertex (Jean-Charles Lefebvre) <https://github.com/polyvertex>`_. - See also `#439 <https://github.com/fmtlib/fmt/issues/439>`_. - -* Added ``fmt::format_system_error()`` for error code formatting - (`#323 <https://github.com/fmtlib/fmt/issues/323>`_ and - `#526 <https://github.com/fmtlib/fmt/pull/526>`_). - Thanks `@maddinat0r (Alex Martin) <https://github.com/maddinat0r>`_. - -* Added thread-safe ``fmt::localtime()`` and ``fmt::gmtime()`` - as replacement for the standard version to ``time.h`` - (`#396 <https://github.com/fmtlib/fmt/pull/396>`_). - Thanks `@codicodi <https://github.com/codicodi>`_. - -* Internal improvements to ``NamedArg`` and ``ArgLists`` - (`#389 <https://github.com/fmtlib/fmt/pull/389>`_ and - `#390 <https://github.com/fmtlib/fmt/pull/390>`_). - Thanks `@chronoxor <https://github.com/chronoxor>`_. - -* Fixed crash due to bug in ``FormatBuf`` - (`#493 <https://github.com/fmtlib/fmt/pull/493>`_). - Thanks `@effzeh <https://github.com/effzeh>`_. See also - `#480 <https://github.com/fmtlib/fmt/issues/480>`_ and - `#491 <https://github.com/fmtlib/fmt/issues/491>`_. - -* Fixed handling of wide strings in ``fmt::StringWriter``. - -* Improved compiler error messages - (`#357 <https://github.com/fmtlib/fmt/issues/357>`_). - -* Fixed various warnings and issues with various compilers - (`#494 <https://github.com/fmtlib/fmt/pull/494>`_, - `#499 <https://github.com/fmtlib/fmt/pull/499>`_, - `#483 <https://github.com/fmtlib/fmt/pull/483>`_, - `#485 <https://github.com/fmtlib/fmt/pull/485>`_, - `#482 <https://github.com/fmtlib/fmt/pull/482>`_, - `#475 <https://github.com/fmtlib/fmt/pull/475>`_, - `#473 <https://github.com/fmtlib/fmt/pull/473>`_ and - `#414 <https://github.com/fmtlib/fmt/pull/414>`_). - Thanks `@chronoxor <https://github.com/chronoxor>`_, - `@zhaohuaxishi <https://github.com/zhaohuaxishi>`_, - `@pkestene (Pierre Kestener) <https://github.com/pkestene>`_, - `@dschmidt (Dominik Schmidt) <https://github.com/dschmidt>`_ and - `@0x414c (Alexey Gorishny) <https://github.com/0x414c>`_ . - -* Improved CMake: targets are now namespaced - (`#511 <https://github.com/fmtlib/fmt/pull/511>`_ and - `#513 <https://github.com/fmtlib/fmt/pull/513>`_), supported header-only - ``printf.h`` (`#354 <https://github.com/fmtlib/fmt/pull/354>`_), fixed issue - with minimal supported library subset - (`#418 <https://github.com/fmtlib/fmt/issues/418>`_, - `#419 <https://github.com/fmtlib/fmt/pull/419>`_ and - `#420 <https://github.com/fmtlib/fmt/pull/420>`_). - Thanks `@bjoernthiel (Bjoern Thiel) <https://github.com/bjoernthiel>`_, - `@niosHD (Mario Werner) <https://github.com/niosHD>`_, - `@LogicalKnight (Sean LK) <https://github.com/LogicalKnight>`_ and - `@alabuzhev (Alex Alabuzhev) <https://github.com/alabuzhev>`_. - -* Improved documentation. Thanks to - `@pwm1234 (Phil) <https://github.com/pwm1234>`_ for - `#393 <https://github.com/fmtlib/fmt/pull/393>`_. - -3.0.2 - 2017-06-14 ------------------- - -* Added ``FMT_VERSION`` macro - (`#411 <https://github.com/fmtlib/fmt/issues/411>`_). - -* Used ``FMT_NULL`` instead of literal ``0`` - (`#409 <https://github.com/fmtlib/fmt/pull/409>`_). - Thanks `@alabuzhev (Alex Alabuzhev) <https://github.com/alabuzhev>`_. - -* Added extern templates for ``format_float`` - (`#413 <https://github.com/fmtlib/fmt/issues/413>`_). - -* Fixed implicit conversion issue - (`#507 <https://github.com/fmtlib/fmt/issues/507>`_). - -* Fixed signbit detection (`#423 <https://github.com/fmtlib/fmt/issues/423>`_). - -* Fixed naming collision (`#425 <https://github.com/fmtlib/fmt/issues/425>`_). - -* Fixed missing intrinsic for C++/CLI - (`#457 <https://github.com/fmtlib/fmt/pull/457>`_). - Thanks `@calumr (Calum Robinson) <https://github.com/calumr>`_ - -* Fixed Android detection (`#458 <https://github.com/fmtlib/fmt/pull/458>`_). - Thanks `@Gachapen (Magnus Bjerke Vik) <https://github.com/Gachapen>`_. - -* Use lean ``windows.h`` if not in header-only mode - (`#503 <https://github.com/fmtlib/fmt/pull/503>`_). - Thanks `@Quentin01 (Quentin Buathier) <https://github.com/Quentin01>`_. - -* Fixed issue with CMake exporting C++11 flag - (`#445 <https://github.com/fmtlib/fmt/pull/455>`_). - Thanks `@EricWF (Eric) <https://github.com/EricWF>`_. - -* Fixed issue with nvcc and MSVC compiler bug and MinGW - (`#505 <https://github.com/fmtlib/fmt/issues/505>`_). - -* Fixed DLL issues (`#469 <https://github.com/fmtlib/fmt/pull/469>`_ and - `#502 <https://github.com/fmtlib/fmt/pull/502>`_). - Thanks `@richardeakin (Richard Eakin) <https://github.com/richardeakin>`_ and - `@AndreasSchoenle (Andreas Schönle) <https://github.com/AndreasSchoenle>`_. - -* Fixed test compilation under FreeBSD - (`#433 <https://github.com/fmtlib/fmt/issues/433>`_). - -* Fixed various warnings (`#403 <https://github.com/fmtlib/fmt/pull/403>`_, - `#410 <https://github.com/fmtlib/fmt/pull/410>`_ and - `#510 <https://github.com/fmtlib/fmt/pull/510>`_). - Thanks `@Lecetem <https://github.com/Lectem>`_, - `@chenhayat (Chen Hayat) <https://github.com/chenhayat>`_ and - `@trozen <https://github.com/trozen>`_. - -* Worked around a broken ``__builtin_clz`` in clang with MS codegen - (`#519 <https://github.com/fmtlib/fmt/issues/519>`_). - -* Removed redundant include - (`#479 <https://github.com/fmtlib/fmt/issues/479>`_). - -* Fixed documentation issues. - -3.0.1 - 2016-11-01 ------------------- -* Fixed handling of thousands separator - (`#353 <https://github.com/fmtlib/fmt/issues/353>`_). - -* Fixed handling of ``unsigned char`` strings - (`#373 <https://github.com/fmtlib/fmt/issues/373>`_). - -* Corrected buffer growth when formatting time - (`#367 <https://github.com/fmtlib/fmt/issues/367>`_). - -* Removed warnings under MSVC and clang - (`#318 <https://github.com/fmtlib/fmt/issues/318>`_, - `#250 <https://github.com/fmtlib/fmt/issues/250>`_, also merged - `#385 <https://github.com/fmtlib/fmt/pull/385>`_ and - `#361 <https://github.com/fmtlib/fmt/pull/361>`_). - Thanks `@jcelerier (Jean-Michaël Celerier) <https://github.com/jcelerier>`_ - and `@nmoehrle (Nils Moehrle) <https://github.com/nmoehrle>`_. - -* Fixed compilation issues under Android - (`#327 <https://github.com/fmtlib/fmt/pull/327>`_, - `#345 <https://github.com/fmtlib/fmt/issues/345>`_ and - `#381 <https://github.com/fmtlib/fmt/pull/381>`_), - FreeBSD (`#358 <https://github.com/fmtlib/fmt/pull/358>`_), - Cygwin (`#388 <https://github.com/fmtlib/fmt/issues/388>`_), - MinGW (`#355 <https://github.com/fmtlib/fmt/issues/355>`_) as well as other - issues (`#350 <https://github.com/fmtlib/fmt/issues/350>`_, - `#366 <https://github.com/fmtlib/fmt/issues/355>`_, - `#348 <https://github.com/fmtlib/fmt/pull/348>`_, - `#402 <https://github.com/fmtlib/fmt/pull/402>`_, - `#405 <https://github.com/fmtlib/fmt/pull/405>`_). - Thanks to `@dpantele (Dmitry) <https://github.com/dpantele>`_, - `@hghwng (Hugh Wang) <https://github.com/hghwng>`_, - `@arvedarved (Tilman Keskinöz) <https://github.com/arvedarved>`_, - `@LogicalKnight (Sean) <https://github.com/LogicalKnight>`_ and - `@JanHellwig (Jan Hellwig) <https://github.com/janhellwig>`_. - -* Fixed some documentation issues and extended specification - (`#320 <https://github.com/fmtlib/fmt/issues/320>`_, - `#333 <https://github.com/fmtlib/fmt/pull/333>`_, - `#347 <https://github.com/fmtlib/fmt/issues/347>`_, - `#362 <https://github.com/fmtlib/fmt/pull/362>`_). - Thanks to `@smellman (Taro Matsuzawa aka. btm) - <https://github.com/smellman>`_. - -3.0.0 - 2016-05-07 ------------------- - -* The project has been renamed from C++ Format (cppformat) to fmt for - consistency with the used namespace and macro prefix - (`#307 <https://github.com/fmtlib/fmt/issues/307>`_). - Library headers are now located in the ``fmt`` directory: - - .. code:: c++ - - #include "fmt/format.h" - - Including ``format.h`` from the ``cppformat`` directory is deprecated - but works via a proxy header which will be removed in the next major version. - - The documentation is now available at https://fmt.dev. - -* Added support for `strftime <http://en.cppreference.com/w/cpp/chrono/c/strftime>`_-like - `date and time formatting <https://fmt.dev/3.0.0/api.html#date-and-time-formatting>`_ - (`#283 <https://github.com/fmtlib/fmt/issues/283>`_): - - .. code:: c++ - - #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)); - -* ``std::ostream`` support including formatting of user-defined types that provide - overloaded ``operator<<`` has been moved to ``fmt/ostream.h``: - - .. code:: c++ - - #include "fmt/ostream.h" - - class Date { - int year_, month_, day_; - public: - Date(int year, int month, int day) : year_(year), month_(month), day_(day) {} - - friend std::ostream &operator<<(std::ostream &os, const Date &d) { - return os << d.year_ << '-' << d.month_ << '-' << d.day_; - } - }; - - std::string s = fmt::format("The date is {}", Date(2012, 12, 9)); - // s == "The date is 2012-12-9" - -* Added support for `custom argument formatters - <https://fmt.dev/3.0.0/api.html#argument-formatters>`_ - (`#235 <https://github.com/fmtlib/fmt/issues/235>`_). - -* Added support for locale-specific integer formatting with the ``n`` specifier - (`#305 <https://github.com/fmtlib/fmt/issues/305>`_): - - .. code:: c++ - - std::setlocale(LC_ALL, "en_US.utf8"); - fmt::print("cppformat: {:n}\n", 1234567); // prints 1,234,567 - -* Sign is now preserved when formatting an integer with an incorrect ``printf`` - format specifier (`#265 <https://github.com/fmtlib/fmt/issues/265>`_): - - .. code:: c++ - - fmt::printf("%lld", -42); // prints -42 - - Note that it would be an undefined behavior in ``std::printf``. - -* Length modifiers such as ``ll`` are now optional in printf formatting - functions and the correct type is determined automatically - (`#255 <https://github.com/fmtlib/fmt/issues/255>`_): - - .. code:: c++ - - fmt::printf("%d", std::numeric_limits<long long>::max()); - - Note that it would be an undefined behavior in ``std::printf``. - -* Added initial support for custom formatters - (`#231 <https://github.com/fmtlib/fmt/issues/231>`_). - -* Fixed detection of user-defined literal support on Intel C++ compiler - (`#311 <https://github.com/fmtlib/fmt/issues/311>`_, - `#312 <https://github.com/fmtlib/fmt/pull/312>`_). - Thanks to `@dean0x7d (Dean Moldovan) <https://github.com/dean0x7d>`_ and - `@speth (Ray Speth) <https://github.com/speth>`_. - -* Reduced compile time - (`#243 <https://github.com/fmtlib/fmt/pull/243>`_, - `#249 <https://github.com/fmtlib/fmt/pull/249>`_, - `#317 <https://github.com/fmtlib/fmt/issues/317>`_): - - .. image:: https://cloud.githubusercontent.com/assets/4831417/11614060/ - b9e826d2-9c36-11e5-8666-d4131bf503ef.png - - .. image:: https://cloud.githubusercontent.com/assets/4831417/11614080/ - 6ac903cc-9c37-11e5-8165-26df6efae364.png - - Thanks to `@dean0x7d (Dean Moldovan) <https://github.com/dean0x7d>`_. - -* Compile test fixes (`#313 <https://github.com/fmtlib/fmt/pull/313>`_). - Thanks to `@dean0x7d (Dean Moldovan) <https://github.com/dean0x7d>`_. - -* Documentation fixes (`#239 <https://github.com/fmtlib/fmt/pull/239>`_, - `#248 <https://github.com/fmtlib/fmt/issues/248>`_, - `#252 <https://github.com/fmtlib/fmt/issues/252>`_, - `#258 <https://github.com/fmtlib/fmt/pull/258>`_, - `#260 <https://github.com/fmtlib/fmt/issues/260>`_, - `#301 <https://github.com/fmtlib/fmt/issues/301>`_, - `#309 <https://github.com/fmtlib/fmt/pull/309>`_). - Thanks to `@ReadmeCritic <https://github.com/ReadmeCritic>`_ - `@Gachapen (Magnus Bjerke Vik) <https://github.com/Gachapen>`_ and - `@jwilk (Jakub Wilk) <https://github.com/jwilk>`_. - -* Fixed compiler and sanitizer warnings - (`#244 <https://github.com/fmtlib/fmt/issues/244>`_, - `#256 <https://github.com/fmtlib/fmt/pull/256>`_, - `#259 <https://github.com/fmtlib/fmt/pull/259>`_, - `#263 <https://github.com/fmtlib/fmt/issues/263>`_, - `#274 <https://github.com/fmtlib/fmt/issues/274>`_, - `#277 <https://github.com/fmtlib/fmt/pull/277>`_, - `#286 <https://github.com/fmtlib/fmt/pull/286>`_, - `#291 <https://github.com/fmtlib/fmt/issues/291>`_, - `#296 <https://github.com/fmtlib/fmt/issues/296>`_, - `#308 <https://github.com/fmtlib/fmt/issues/308>`_) - Thanks to `@mwinterb <https://github.com/mwinterb>`_, - `@pweiskircher (Patrik Weiskircher) <https://github.com/pweiskircher>`_, - `@Naios <https://github.com/Naios>`_. - -* Improved compatibility with Windows Store apps - (`#280 <https://github.com/fmtlib/fmt/issues/280>`_, - `#285 <https://github.com/fmtlib/fmt/pull/285>`_) - Thanks to `@mwinterb <https://github.com/mwinterb>`_. - -* Added tests of compatibility with older C++ standards - (`#273 <https://github.com/fmtlib/fmt/pull/273>`_). - Thanks to `@niosHD <https://github.com/niosHD>`_. - -* Fixed Android build (`#271 <https://github.com/fmtlib/fmt/pull/271>`_). - Thanks to `@newnon <https://github.com/newnon>`_. - -* Changed ``ArgMap`` to be backed by a vector instead of a map. - (`#261 <https://github.com/fmtlib/fmt/issues/261>`_, - `#262 <https://github.com/fmtlib/fmt/pull/262>`_). - Thanks to `@mwinterb <https://github.com/mwinterb>`_. - -* Added ``fprintf`` overload that writes to a ``std::ostream`` - (`#251 <https://github.com/fmtlib/fmt/pull/251>`_). - Thanks to `nickhutchinson (Nicholas Hutchinson) <https://github.com/nickhutchinson>`_. - -* Export symbols when building a Windows DLL - (`#245 <https://github.com/fmtlib/fmt/pull/245>`_). - Thanks to `macdems (Maciek Dems) <https://github.com/macdems>`_. - -* Fixed compilation on Cygwin (`#304 <https://github.com/fmtlib/fmt/issues/304>`_). - -* Implemented a workaround for a bug in Apple LLVM version 4.2 of clang - (`#276 <https://github.com/fmtlib/fmt/issues/276>`_). - -* Implemented a workaround for Google Test bug - `#705 <https://github.com/google/googletest/issues/705>`_ on gcc 6 - (`#268 <https://github.com/fmtlib/fmt/issues/268>`_). - Thanks to `octoploid <https://github.com/octoploid>`_. - -* Removed Biicode support because the latter has been discontinued. - -2.1.1 - 2016-04-11 ------------------- - -* The install location for generated CMake files is now configurable via - the ``FMT_CMAKE_DIR`` CMake variable - (`#299 <https://github.com/fmtlib/fmt/pull/299>`_). - Thanks to `@niosHD <https://github.com/niosHD>`_. - -* Documentation fixes (`#252 <https://github.com/fmtlib/fmt/issues/252>`_). - -2.1.0 - 2016-03-21 ------------------- - -* Project layout and build system improvements - (`#267 <https://github.com/fmtlib/fmt/pull/267>`_): - - * The code have been moved to the ``cppformat`` directory. - Including ``format.h`` from the top-level directory is deprecated - but works via a proxy header which will be removed in the next - major version. - - * C++ Format CMake targets now have proper interface definitions. - - * Installed version of the library now supports the header-only - configuration. - - * Targets ``doc``, ``install``, and ``test`` are now disabled if C++ Format - is included as a CMake subproject. They can be enabled by setting - ``FMT_DOC``, ``FMT_INSTALL``, and ``FMT_TEST`` in the parent project. - - Thanks to `@niosHD <https://github.com/niosHD>`_. - -2.0.1 - 2016-03-13 ------------------- - -* Improved CMake find and package support - (`#264 <https://github.com/fmtlib/fmt/issues/264>`_). - Thanks to `@niosHD <https://github.com/niosHD>`_. - -* Fix compile error with Android NDK and mingw32 - (`#241 <https://github.com/fmtlib/fmt/issues/241>`_). - Thanks to `@Gachapen (Magnus Bjerke Vik) <https://github.com/Gachapen>`_. - -* Documentation fixes - (`#248 <https://github.com/fmtlib/fmt/issues/248>`_, - `#260 <https://github.com/fmtlib/fmt/issues/260>`_). - -2.0.0 - 2015-12-01 ------------------- - -General -~~~~~~~ - -* [Breaking] Named arguments - (`#169 <https://github.com/fmtlib/fmt/pull/169>`_, - `#173 <https://github.com/fmtlib/fmt/pull/173>`_, - `#174 <https://github.com/fmtlib/fmt/pull/174>`_): - - .. code:: c++ - - fmt::print("The answer is {answer}.", fmt::arg("answer", 42)); - - Thanks to `@jamboree <https://github.com/jamboree>`_. - -* [Experimental] User-defined literals for format and named arguments - (`#204 <https://github.com/fmtlib/fmt/pull/204>`_, - `#206 <https://github.com/fmtlib/fmt/pull/206>`_, - `#207 <https://github.com/fmtlib/fmt/pull/207>`_): - - .. code:: c++ - - using namespace fmt::literals; - fmt::print("The answer is {answer}.", "answer"_a=42); - - Thanks to `@dean0x7d (Dean Moldovan) <https://github.com/dean0x7d>`_. - -* [Breaking] Formatting of more than 16 arguments is now supported when using - variadic templates - (`#141 <https://github.com/fmtlib/fmt/issues/141>`_). - Thanks to `@Shauren <https://github.com/Shauren>`_. - -* Runtime width specification - (`#168 <https://github.com/fmtlib/fmt/pull/168>`_): - - .. code:: c++ - - fmt::format("{0:{1}}", 42, 5); // gives " 42" - - Thanks to `@jamboree <https://github.com/jamboree>`_. - -* [Breaking] Enums are now formatted with an overloaded ``std::ostream`` insertion - operator (``operator<<``) if available - (`#232 <https://github.com/fmtlib/fmt/issues/232>`_). - -* [Breaking] Changed default ``bool`` format to textual, "true" or "false" - (`#170 <https://github.com/fmtlib/fmt/issues/170>`_): - - .. code:: c++ - - fmt::print("{}", true); // prints "true" - - To print ``bool`` as a number use numeric format specifier such as ``d``: - - .. code:: c++ - - fmt::print("{:d}", true); // prints "1" - -* ``fmt::printf`` and ``fmt::sprintf`` now support formatting of ``bool`` with the - ``%s`` specifier giving textual output, "true" or "false" - (`#223 <https://github.com/fmtlib/fmt/pull/223>`_): - - .. code:: c++ - - fmt::printf("%s", true); // prints "true" - - Thanks to `@LarsGullik <https://github.com/LarsGullik>`_. - -* [Breaking] ``signed char`` and ``unsigned char`` are now formatted as integers by default - (`#217 <https://github.com/fmtlib/fmt/pull/217>`_). - -* [Breaking] Pointers to C strings can now be formatted with the ``p`` specifier - (`#223 <https://github.com/fmtlib/fmt/pull/223>`_): - - .. code:: c++ - - fmt::print("{:p}", "test"); // prints pointer value - - Thanks to `@LarsGullik <https://github.com/LarsGullik>`_. - -* [Breaking] ``fmt::printf`` and ``fmt::sprintf`` now print null pointers as ``(nil)`` - and null strings as ``(null)`` for consistency with glibc - (`#226 <https://github.com/fmtlib/fmt/pull/226>`_). - Thanks to `@LarsGullik <https://github.com/LarsGullik>`_. - -* [Breaking] ``fmt::(s)printf`` now supports formatting of objects of user-defined types - that provide an overloaded ``std::ostream`` insertion operator (``operator<<``) - (`#201 <https://github.com/fmtlib/fmt/issues/201>`_): - - .. code:: c++ - - fmt::printf("The date is %s", Date(2012, 12, 9)); - -* [Breaking] The ``Buffer`` template is now part of the public API and can be used - to implement custom memory buffers - (`#140 <https://github.com/fmtlib/fmt/issues/140>`_). - Thanks to `@polyvertex (Jean-Charles Lefebvre) <https://github.com/polyvertex>`_. - -* [Breaking] Improved compatibility between ``BasicStringRef`` and - `std::experimental::basic_string_view - <http://en.cppreference.com/w/cpp/experimental/basic_string_view>`_ - (`#100 <https://github.com/fmtlib/fmt/issues/100>`_, - `#159 <https://github.com/fmtlib/fmt/issues/159>`_, - `#183 <https://github.com/fmtlib/fmt/issues/183>`_): - - - Comparison operators now compare string content, not pointers - - ``BasicStringRef::c_str`` replaced by ``BasicStringRef::data`` - - ``BasicStringRef`` is no longer assumed to be null-terminated - - References to null-terminated strings are now represented by a new class, - ``BasicCStringRef``. - -* Dependency on pthreads introduced by Google Test is now optional - (`#185 <https://github.com/fmtlib/fmt/issues/185>`_). - -* New CMake options ``FMT_DOC``, ``FMT_INSTALL`` and ``FMT_TEST`` to control - generation of ``doc``, ``install`` and ``test`` targets respectively, on by default - (`#197 <https://github.com/fmtlib/fmt/issues/197>`_, - `#198 <https://github.com/fmtlib/fmt/issues/198>`_, - `#200 <https://github.com/fmtlib/fmt/issues/200>`_). - Thanks to `@maddinat0r (Alex Martin) <https://github.com/maddinat0r>`_. - -* ``noexcept`` is now used when compiling with MSVC2015 - (`#215 <https://github.com/fmtlib/fmt/pull/215>`_). - Thanks to `@dmkrepo (Dmitriy) <https://github.com/dmkrepo>`_. - -* Added an option to disable use of ``windows.h`` when ``FMT_USE_WINDOWS_H`` - is defined as 0 before including ``format.h`` - (`#171 <https://github.com/fmtlib/fmt/issues/171>`_). - Thanks to `@alfps (Alf P. Steinbach) <https://github.com/alfps>`_. - -* [Breaking] ``windows.h`` is now included with ``NOMINMAX`` unless - ``FMT_WIN_MINMAX`` is defined. This is done to prevent breaking code using - ``std::min`` and ``std::max`` and only affects the header-only configuration - (`#152 <https://github.com/fmtlib/fmt/issues/152>`_, - `#153 <https://github.com/fmtlib/fmt/pull/153>`_, - `#154 <https://github.com/fmtlib/fmt/pull/154>`_). - Thanks to `@DevO2012 <https://github.com/DevO2012>`_. - -* Improved support for custom character types - (`#171 <https://github.com/fmtlib/fmt/issues/171>`_). - Thanks to `@alfps (Alf P. Steinbach) <https://github.com/alfps>`_. - -* Added an option to disable use of IOStreams when ``FMT_USE_IOSTREAMS`` - is defined as 0 before including ``format.h`` - (`#205 <https://github.com/fmtlib/fmt/issues/205>`_, - `#208 <https://github.com/fmtlib/fmt/pull/208>`_). - Thanks to `@JodiTheTigger <https://github.com/JodiTheTigger>`_. - -* Improved detection of ``isnan``, ``isinf`` and ``signbit``. - -Optimization -~~~~~~~~~~~~ - -* Made formatting of user-defined types more efficient with a custom stream buffer - (`#92 <https://github.com/fmtlib/fmt/issues/92>`_, - `#230 <https://github.com/fmtlib/fmt/pull/230>`_). - Thanks to `@NotImplemented <https://github.com/NotImplemented>`_. - -* Further improved performance of ``fmt::Writer`` on integer formatting - and fixed a minor regression. Now it is ~7% faster than ``karma::generate`` - on Karma's benchmark - (`#186 <https://github.com/fmtlib/fmt/issues/186>`_). - -* [Breaking] Reduced `compiled code size - <https://github.com/fmtlib/fmt#compile-time-and-code-bloat>`_ - (`#143 <https://github.com/fmtlib/fmt/issues/143>`_, - `#149 <https://github.com/fmtlib/fmt/pull/149>`_). - -Distribution -~~~~~~~~~~~~ - -* [Breaking] Headers are now installed in - ``${CMAKE_INSTALL_PREFIX}/include/cppformat`` - (`#178 <https://github.com/fmtlib/fmt/issues/178>`_). - Thanks to `@jackyf (Eugene V. Lyubimkin) <https://github.com/jackyf>`_. - -* [Breaking] Changed the library name from ``format`` to ``cppformat`` - for consistency with the project name and to avoid potential conflicts - (`#178 <https://github.com/fmtlib/fmt/issues/178>`_). - Thanks to `@jackyf (Eugene V. Lyubimkin) <https://github.com/jackyf>`_. - -* C++ Format is now available in `Debian <https://www.debian.org/>`_ GNU/Linux - (`stretch <https://packages.debian.org/source/stretch/cppformat>`_, - `sid <https://packages.debian.org/source/sid/cppformat>`_) and - derived distributions such as - `Ubuntu <https://launchpad.net/ubuntu/+source/cppformat>`_ 15.10 and later - (`#155 <https://github.com/fmtlib/fmt/issues/155>`_):: - - $ sudo apt-get install libcppformat1-dev - - Thanks to `@jackyf (Eugene V. Lyubimkin) <https://github.com/jackyf>`_. - -* `Packages for Fedora and RHEL <https://admin.fedoraproject.org/pkgdb/package/cppformat/>`_ - are now available. Thanks to Dave Johansen. - -* C++ Format can now be installed via `Homebrew <http://brew.sh/>`_ on OS X - (`#157 <https://github.com/fmtlib/fmt/issues/157>`_):: - - $ brew install cppformat - - Thanks to `@ortho <https://github.com/ortho>`_, Anatoliy Bulukin. - -Documentation -~~~~~~~~~~~~~ - -* Migrated from ReadTheDocs to GitHub Pages for better responsiveness - and reliability - (`#128 <https://github.com/fmtlib/fmt/issues/128>`_). - New documentation address is http://cppformat.github.io/. - - -* Added `Building the documentation - <https://fmt.dev/2.0.0/usage.html#building-the-documentation>`_ - section to the documentation. - -* Documentation build script is now compatible with Python 3 and newer pip versions. - (`#189 <https://github.com/fmtlib/fmt/pull/189>`_, - `#209 <https://github.com/fmtlib/fmt/issues/209>`_). - Thanks to `@JodiTheTigger <https://github.com/JodiTheTigger>`_ and - `@xentec <https://github.com/xentec>`_. - -* Documentation fixes and improvements - (`#36 <https://github.com/fmtlib/fmt/issues/36>`_, - `#75 <https://github.com/fmtlib/fmt/issues/75>`_, - `#125 <https://github.com/fmtlib/fmt/issues/125>`_, - `#160 <https://github.com/fmtlib/fmt/pull/160>`_, - `#161 <https://github.com/fmtlib/fmt/pull/161>`_, - `#162 <https://github.com/fmtlib/fmt/issues/162>`_, - `#165 <https://github.com/fmtlib/fmt/issues/165>`_, - `#210 <https://github.com/fmtlib/fmt/issues/210>`_). - Thanks to `@syohex (Syohei YOSHIDA) <https://github.com/syohex>`_ and - bug reporters. - -* Fixed out-of-tree documentation build - (`#177 <https://github.com/fmtlib/fmt/issues/177>`_). - Thanks to `@jackyf (Eugene V. Lyubimkin) <https://github.com/jackyf>`_. - -Fixes -~~~~~ - -* Fixed ``initializer_list`` detection - (`#136 <https://github.com/fmtlib/fmt/issues/136>`_). - Thanks to `@Gachapen (Magnus Bjerke Vik) <https://github.com/Gachapen>`_. - -* [Breaking] Fixed formatting of enums with numeric format specifiers in - ``fmt::(s)printf`` - (`#131 <https://github.com/fmtlib/fmt/issues/131>`_, - `#139 <https://github.com/fmtlib/fmt/issues/139>`_): - - .. code:: c++ - - enum { ANSWER = 42 }; - fmt::printf("%d", ANSWER); - - Thanks to `@Naios <https://github.com/Naios>`_. - -* Improved compatibility with old versions of MinGW - (`#129 <https://github.com/fmtlib/fmt/issues/129>`_, - `#130 <https://github.com/fmtlib/fmt/pull/130>`_, - `#132 <https://github.com/fmtlib/fmt/issues/132>`_). - Thanks to `@cstamford (Christopher Stamford) <https://github.com/cstamford>`_. - -* Fixed a compile error on MSVC with disabled exceptions - (`#144 <https://github.com/fmtlib/fmt/issues/144>`_). - -* Added a workaround for broken implementation of variadic templates in MSVC2012 - (`#148 <https://github.com/fmtlib/fmt/issues/148>`_). - -* Placed the anonymous namespace within ``fmt`` namespace for the header-only - configuration - (`#171 <https://github.com/fmtlib/fmt/issues/171>`_). - Thanks to `@alfps (Alf P. Steinbach) <https://github.com/alfps>`_. - -* Fixed issues reported by Coverity Scan - (`#187 <https://github.com/fmtlib/fmt/issues/187>`_, - `#192 <https://github.com/fmtlib/fmt/issues/192>`_). - -* Implemented a workaround for a name lookup bug in MSVC2010 - (`#188 <https://github.com/fmtlib/fmt/issues/188>`_). - -* Fixed compiler warnings - (`#95 <https://github.com/fmtlib/fmt/issues/95>`_, - `#96 <https://github.com/fmtlib/fmt/issues/96>`_, - `#114 <https://github.com/fmtlib/fmt/pull/114>`_, - `#135 <https://github.com/fmtlib/fmt/issues/135>`_, - `#142 <https://github.com/fmtlib/fmt/issues/142>`_, - `#145 <https://github.com/fmtlib/fmt/issues/145>`_, - `#146 <https://github.com/fmtlib/fmt/issues/146>`_, - `#158 <https://github.com/fmtlib/fmt/issues/158>`_, - `#163 <https://github.com/fmtlib/fmt/issues/163>`_, - `#175 <https://github.com/fmtlib/fmt/issues/175>`_, - `#190 <https://github.com/fmtlib/fmt/issues/190>`_, - `#191 <https://github.com/fmtlib/fmt/pull/191>`_, - `#194 <https://github.com/fmtlib/fmt/issues/194>`_, - `#196 <https://github.com/fmtlib/fmt/pull/196>`_, - `#216 <https://github.com/fmtlib/fmt/issues/216>`_, - `#218 <https://github.com/fmtlib/fmt/pull/218>`_, - `#220 <https://github.com/fmtlib/fmt/pull/220>`_, - `#229 <https://github.com/fmtlib/fmt/pull/229>`_, - `#233 <https://github.com/fmtlib/fmt/issues/233>`_, - `#234 <https://github.com/fmtlib/fmt/issues/234>`_, - `#236 <https://github.com/fmtlib/fmt/pull/236>`_, - `#281 <https://github.com/fmtlib/fmt/issues/281>`_, - `#289 <https://github.com/fmtlib/fmt/issues/289>`_). - Thanks to `@seanmiddleditch (Sean Middleditch) <https://github.com/seanmiddleditch>`_, - `@dixlorenz (Dix Lorenz) <https://github.com/dixlorenz>`_, - `@CarterLi (李通洲) <https://github.com/CarterLi>`_, - `@Naios <https://github.com/Naios>`_, - `@fmatthew5876 (Matthew Fioravante) <https://github.com/fmatthew5876>`_, - `@LevskiWeng (Levski Weng) <https://github.com/LevskiWeng>`_, - `@rpopescu <https://github.com/rpopescu>`_, - `@gabime (Gabi Melman) <https://github.com/gabime>`_, - `@cubicool (Jeremy Moles) <https://github.com/cubicool>`_, - `@jkflying (Julian Kent) <https://github.com/jkflying>`_, - `@LogicalKnight (Sean L) <https://github.com/LogicalKnight>`_, - `@inguin (Ingo van Lil) <https://github.com/inguin>`_ and - `@Jopie64 (Johan) <https://github.com/Jopie64>`_. - -* Fixed portability issues (mostly causing test failures) on ARM, ppc64, ppc64le, - s390x and SunOS 5.11 i386 - (`#138 <https://github.com/fmtlib/fmt/issues/138>`_, - `#179 <https://github.com/fmtlib/fmt/issues/179>`_, - `#180 <https://github.com/fmtlib/fmt/issues/180>`_, - `#202 <https://github.com/fmtlib/fmt/issues/202>`_, - `#225 <https://github.com/fmtlib/fmt/issues/225>`_, - `Red Hat Bugzilla Bug 1260297 <https://bugzilla.redhat.com/show_bug.cgi?id=1260297>`_). - Thanks to `@Naios <https://github.com/Naios>`_, - `@jackyf (Eugene V. Lyubimkin) <https://github.com/jackyf>`_ and Dave Johansen. - -* Fixed a name conflict with macro ``free`` defined in - ``crtdbg.h`` when ``_CRTDBG_MAP_ALLOC`` is set - (`#211 <https://github.com/fmtlib/fmt/issues/211>`_). - -* Fixed shared library build on OS X - (`#212 <https://github.com/fmtlib/fmt/pull/212>`_). - Thanks to `@dean0x7d (Dean Moldovan) <https://github.com/dean0x7d>`_. - -* Fixed an overload conflict on MSVC when ``/Zc:wchar_t-`` option is specified - (`#214 <https://github.com/fmtlib/fmt/pull/214>`_). - Thanks to `@slavanap (Vyacheslav Napadovsky) <https://github.com/slavanap>`_. - -* Improved compatibility with MSVC 2008 - (`#236 <https://github.com/fmtlib/fmt/pull/236>`_). - Thanks to `@Jopie64 (Johan) <https://github.com/Jopie64>`_. - -* Improved compatibility with bcc32 - (`#227 <https://github.com/fmtlib/fmt/issues/227>`_). - -* Fixed ``static_assert`` detection on Clang - (`#228 <https://github.com/fmtlib/fmt/pull/228>`_). - Thanks to `@dean0x7d (Dean Moldovan) <https://github.com/dean0x7d>`_. - -1.1.0 - 2015-03-06 ------------------- - -* Added ``BasicArrayWriter``, a class template that provides operations for - formatting and writing data into a fixed-size array - (`#105 <https://github.com/fmtlib/fmt/issues/105>`_ and - `#122 <https://github.com/fmtlib/fmt/issues/122>`_): - - .. code:: c++ - - char buffer[100]; - fmt::ArrayWriter w(buffer); - w.write("The answer is {}", 42); - -* Added `0 A.D. <http://play0ad.com/>`_ and `PenUltima Online (POL) - <http://www.polserver.com/>`_ to the list of notable projects using C++ Format. - -* C++ Format now uses MSVC intrinsics for better formatting performance - (`#115 <https://github.com/fmtlib/fmt/pull/115>`_, - `#116 <https://github.com/fmtlib/fmt/pull/116>`_, - `#118 <https://github.com/fmtlib/fmt/pull/118>`_ and - `#121 <https://github.com/fmtlib/fmt/pull/121>`_). - Previously these optimizations where only used on GCC and Clang. - Thanks to `@CarterLi <https://github.com/CarterLi>`_ and - `@objectx <https://github.com/objectx>`_. - -* CMake install target (`#119 <https://github.com/fmtlib/fmt/pull/119>`_). - Thanks to `@TrentHouliston <https://github.com/TrentHouliston>`_. - - You can now install C++ Format with ``make install`` command. - -* Improved `Biicode <http://www.biicode.com/>`_ support - (`#98 <https://github.com/fmtlib/fmt/pull/98>`_ and - `#104 <https://github.com/fmtlib/fmt/pull/104>`_). Thanks to - `@MariadeAnton <https://github.com/MariadeAnton>`_ and - `@franramirez688 <https://github.com/franramirez688>`_. - -* Improved support for building with `Android NDK - <https://developer.android.com/tools/sdk/ndk/index.html>`_ - (`#107 <https://github.com/fmtlib/fmt/pull/107>`_). - Thanks to `@newnon <https://github.com/newnon>`_. - - The `android-ndk-example <https://github.com/fmtlib/android-ndk-example>`_ - repository provides and example of using C++ Format with Android NDK: - - .. image:: https://raw.githubusercontent.com/fmtlib/android-ndk-example/ - master/screenshot.png - -* Improved documentation of ``SystemError`` and ``WindowsError`` - (`#54 <https://github.com/fmtlib/fmt/issues/54>`_). - -* Various code improvements - (`#110 <https://github.com/fmtlib/fmt/pull/110>`_, - `#111 <https://github.com/fmtlib/fmt/pull/111>`_ - `#112 <https://github.com/fmtlib/fmt/pull/112>`_). - Thanks to `@CarterLi <https://github.com/CarterLi>`_. - -* Improved compile-time errors when formatting wide into narrow strings - (`#117 <https://github.com/fmtlib/fmt/issues/117>`_). - -* Fixed ``BasicWriter::write`` without formatting arguments when C++11 support - is disabled (`#109 <https://github.com/fmtlib/fmt/issues/109>`_). - -* Fixed header-only build on OS X with GCC 4.9 - (`#124 <https://github.com/fmtlib/fmt/issues/124>`_). - -* Fixed packaging issues (`#94 <https://github.com/fmtlib/fmt/issues/94>`_). - -* Added `changelog <https://github.com/fmtlib/fmt/blob/master/ChangeLog.rst>`_ - (`#103 <https://github.com/fmtlib/fmt/issues/103>`_). - -1.0.0 - 2015-02-05 ------------------- - -* Add support for a header-only configuration when ``FMT_HEADER_ONLY`` is - defined before including ``format.h``: - - .. code:: c++ - - #define FMT_HEADER_ONLY - #include "format.h" - -* Compute string length in the constructor of ``BasicStringRef`` - instead of the ``size`` method - (`#79 <https://github.com/fmtlib/fmt/issues/79>`_). - This eliminates size computation for string literals on reasonable optimizing - compilers. - -* Fix formatting of types with overloaded ``operator <<`` for ``std::wostream`` - (`#86 <https://github.com/fmtlib/fmt/issues/86>`_): - - .. code:: c++ - - fmt::format(L"The date is {0}", Date(2012, 12, 9)); - -* Fix linkage of tests on Arch Linux - (`#89 <https://github.com/fmtlib/fmt/issues/89>`_). - -* Allow precision specifier for non-float arguments - (`#90 <https://github.com/fmtlib/fmt/issues/90>`_): - - .. code:: c++ - - fmt::print("{:.3}\n", "Carpet"); // prints "Car" - -* Fix build on Android NDK - (`#93 <https://github.com/fmtlib/fmt/issues/93>`_) - -* Improvements to documentation build procedure. - -* Remove ``FMT_SHARED`` CMake variable in favor of standard `BUILD_SHARED_LIBS - <http://www.cmake.org/cmake/help/v3.0/variable/BUILD_SHARED_LIBS.html>`_. - -* Fix error handling in ``fmt::fprintf``. - -* Fix a number of warnings. - -0.12.0 - 2014-10-25 -------------------- - -* [Breaking] Improved separation between formatting and buffer management. - ``Writer`` is now a base class that cannot be instantiated directly. - The new ``MemoryWriter`` class implements the default buffer management - with small allocations done on stack. So ``fmt::Writer`` should be replaced - with ``fmt::MemoryWriter`` in variable declarations. - - Old code: - - .. code:: c++ - - fmt::Writer w; - - New code: - - .. code:: c++ - - fmt::MemoryWriter w; - - If you pass ``fmt::Writer`` by reference, you can continue to do so: - - .. code:: c++ - - void f(fmt::Writer &w); - - This doesn't affect the formatting API. - -* Support for custom memory allocators - (`#69 <https://github.com/fmtlib/fmt/issues/69>`_) - -* Formatting functions now accept `signed char` and `unsigned char` strings as - arguments (`#73 <https://github.com/fmtlib/fmt/issues/73>`_): - - .. code:: c++ - - auto s = format("GLSL version: {}", glGetString(GL_VERSION)); - -* Reduced code bloat. According to the new `benchmark results - <https://github.com/fmtlib/fmt#compile-time-and-code-bloat>`_, - cppformat is close to ``printf`` and by the order of magnitude better than - Boost Format in terms of compiled code size. - -* Improved appearance of the documentation on mobile by using the `Sphinx - Bootstrap theme <http://ryan-roemer.github.io/sphinx-bootstrap-theme/>`_: - - .. |old| image:: https://cloud.githubusercontent.com/assets/576385/4792130/ - cd256436-5de3-11e4-9a62-c077d0c2b003.png - - .. |new| image:: https://cloud.githubusercontent.com/assets/576385/4792131/ - cd29896c-5de3-11e4-8f59-cac952942bf0.png - - +-------+-------+ - | Old | New | - +-------+-------+ - | |old| | |new| | - +-------+-------+ - -0.11.0 - 2014-08-21 -------------------- - -* Safe printf implementation with a POSIX extension for positional arguments: - - .. code:: c++ - - fmt::printf("Elapsed time: %.2f seconds", 1.23); - fmt::printf("%1$s, %3$d %2$s", weekday, month, day); - -* Arguments of ``char`` type can now be formatted as integers - (Issue `#55 <https://github.com/fmtlib/fmt/issues/55>`_): - - .. code:: c++ - - fmt::format("0x{0:02X}", 'a'); - -* Deprecated parts of the API removed. - -* The library is now built and tested on MinGW with Appveyor in addition to - existing test platforms Linux/GCC, OS X/Clang, Windows/MSVC. - -0.10.0 - 2014-07-01 -------------------- - -**Improved API** - -* All formatting methods are now implemented as variadic functions instead - of using ``operator<<`` for feeding arbitrary arguments into a temporary - formatter object. This works both with C++11 where variadic templates are - used and with older standards where variadic functions are emulated by - providing lightweight wrapper functions defined with the ``FMT_VARIADIC`` - macro. You can use this macro for defining your own portable variadic - functions: - - .. code:: c++ - - void report_error(const char *format, const fmt::ArgList &args) { - fmt::print("Error: {}"); - fmt::print(format, args); - } - FMT_VARIADIC(void, report_error, const char *) - - report_error("file not found: {}", path); - - Apart from a more natural syntax, this also improves performance as there - is no need to construct temporary formatter objects and control arguments' - lifetimes. Because the wrapper functions are very lightweight, this doesn't - cause code bloat even in pre-C++11 mode. - -* Simplified common case of formatting an ``std::string``. Now it requires a - single function call: - - .. code:: c++ - - std::string s = format("The answer is {}.", 42); - - Previously it required 2 function calls: - - .. code:: c++ - - std::string s = str(Format("The answer is {}.") << 42); - - Instead of unsafe ``c_str`` function, ``fmt::Writer`` should be used directly - to bypass creation of ``std::string``: - - .. code:: c++ - - fmt::Writer w; - w.write("The answer is {}.", 42); - w.c_str(); // returns a C string - - This doesn't do dynamic memory allocation for small strings and is less error - prone as the lifetime of the string is the same as for ``std::string::c_str`` - which is well understood (hopefully). - -* Improved consistency in naming functions that are a part of the public API. - Now all public functions are lowercase following the standard library - conventions. Previously it was a combination of lowercase and - CapitalizedWords. - Issue `#50 <https://github.com/fmtlib/fmt/issues/50>`_. - -* Old functions are marked as deprecated and will be removed in the next - release. - -**Other Changes** - -* Experimental support for printf format specifications (work in progress): - - .. code:: c++ - - fmt::printf("The answer is %d.", 42); - std::string s = fmt::sprintf("Look, a %s!", "string"); - -* Support for hexadecimal floating point format specifiers ``a`` and ``A``: - - .. code:: c++ - - print("{:a}", -42.0); // Prints -0x1.5p+5 - print("{:A}", -42.0); // Prints -0X1.5P+5 - -* CMake option ``FMT_SHARED`` that specifies whether to build format as a - shared library (off by default). - -0.9.0 - 2014-05-13 ------------------- - -* More efficient implementation of variadic formatting functions. - -* ``Writer::Format`` now has a variadic overload: - - .. code:: c++ - - Writer out; - out.Format("Look, I'm {}!", "variadic"); - -* For efficiency and consistency with other overloads, variadic overload of - the ``Format`` function now returns ``Writer`` instead of ``std::string``. - Use the ``str`` function to convert it to ``std::string``: - - .. code:: c++ - - std::string s = str(Format("Look, I'm {}!", "variadic")); - -* Replaced formatter actions with output sinks: ``NoAction`` -> ``NullSink``, - ``Write`` -> ``FileSink``, ``ColorWriter`` -> ``ANSITerminalSink``. - This improves naming consistency and shouldn't affect client code unless - these classes are used directly which should be rarely needed. - -* Added ``ThrowSystemError`` function that formats a message and throws - ``SystemError`` containing the formatted message and system-specific error - description. For example, the following code - - .. code:: c++ - - FILE *f = fopen(filename, "r"); - if (!f) - ThrowSystemError(errno, "Failed to open file '{}'") << filename; - - will throw ``SystemError`` exception with description - "Failed to open file '<filename>': No such file or directory" if file - doesn't exist. - -* Support for AppVeyor continuous integration platform. - -* ``Format`` now throws ``SystemError`` in case of I/O errors. - -* Improve test infrastructure. Print functions are now tested by redirecting - the output to a pipe. - -0.8.0 - 2014-04-14 ------------------- - -* Initial release + The documentation is now available at https://fmt.dev. + +* Added support for `strftime <http://en.cppreference.com/w/cpp/chrono/c/strftime>`_-like + `date and time formatting <https://fmt.dev/3.0.0/api.html#date-and-time-formatting>`_ + (`#283 <https://github.com/fmtlib/fmt/issues/283>`_): + + .. code:: c++ + + #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)); + +* ``std::ostream`` support including formatting of user-defined types that provide + overloaded ``operator<<`` has been moved to ``fmt/ostream.h``: + + .. code:: c++ + + #include "fmt/ostream.h" + + class Date { + int year_, month_, day_; + public: + Date(int year, int month, int day) : year_(year), month_(month), day_(day) {} + + friend std::ostream &operator<<(std::ostream &os, const Date &d) { + return os << d.year_ << '-' << d.month_ << '-' << d.day_; + } + }; + + std::string s = fmt::format("The date is {}", Date(2012, 12, 9)); + // s == "The date is 2012-12-9" + +* Added support for `custom argument formatters + <https://fmt.dev/3.0.0/api.html#argument-formatters>`_ + (`#235 <https://github.com/fmtlib/fmt/issues/235>`_). + +* Added support for locale-specific integer formatting with the ``n`` specifier + (`#305 <https://github.com/fmtlib/fmt/issues/305>`_): + + .. code:: c++ + + std::setlocale(LC_ALL, "en_US.utf8"); + fmt::print("cppformat: {:n}\n", 1234567); // prints 1,234,567 + +* Sign is now preserved when formatting an integer with an incorrect ``printf`` + format specifier (`#265 <https://github.com/fmtlib/fmt/issues/265>`_): + + .. code:: c++ + + fmt::printf("%lld", -42); // prints -42 + + Note that it would be an undefined behavior in ``std::printf``. + +* Length modifiers such as ``ll`` are now optional in printf formatting + functions and the correct type is determined automatically + (`#255 <https://github.com/fmtlib/fmt/issues/255>`_): + + .. code:: c++ + + fmt::printf("%d", std::numeric_limits<long long>::max()); + + Note that it would be an undefined behavior in ``std::printf``. + +* Added initial support for custom formatters + (`#231 <https://github.com/fmtlib/fmt/issues/231>`_). + +* Fixed detection of user-defined literal support on Intel C++ compiler + (`#311 <https://github.com/fmtlib/fmt/issues/311>`_, + `#312 <https://github.com/fmtlib/fmt/pull/312>`_). + Thanks to `@dean0x7d (Dean Moldovan) <https://github.com/dean0x7d>`_ and + `@speth (Ray Speth) <https://github.com/speth>`_. + +* Reduced compile time + (`#243 <https://github.com/fmtlib/fmt/pull/243>`_, + `#249 <https://github.com/fmtlib/fmt/pull/249>`_, + `#317 <https://github.com/fmtlib/fmt/issues/317>`_): + + .. image:: https://cloud.githubusercontent.com/assets/4831417/11614060/ + b9e826d2-9c36-11e5-8666-d4131bf503ef.png + + .. image:: https://cloud.githubusercontent.com/assets/4831417/11614080/ + 6ac903cc-9c37-11e5-8165-26df6efae364.png + + Thanks to `@dean0x7d (Dean Moldovan) <https://github.com/dean0x7d>`_. + +* Compile test fixes (`#313 <https://github.com/fmtlib/fmt/pull/313>`_). + Thanks to `@dean0x7d (Dean Moldovan) <https://github.com/dean0x7d>`_. + +* Documentation fixes (`#239 <https://github.com/fmtlib/fmt/pull/239>`_, + `#248 <https://github.com/fmtlib/fmt/issues/248>`_, + `#252 <https://github.com/fmtlib/fmt/issues/252>`_, + `#258 <https://github.com/fmtlib/fmt/pull/258>`_, + `#260 <https://github.com/fmtlib/fmt/issues/260>`_, + `#301 <https://github.com/fmtlib/fmt/issues/301>`_, + `#309 <https://github.com/fmtlib/fmt/pull/309>`_). + Thanks to `@ReadmeCritic <https://github.com/ReadmeCritic>`_ + `@Gachapen (Magnus Bjerke Vik) <https://github.com/Gachapen>`_ and + `@jwilk (Jakub Wilk) <https://github.com/jwilk>`_. + +* Fixed compiler and sanitizer warnings + (`#244 <https://github.com/fmtlib/fmt/issues/244>`_, + `#256 <https://github.com/fmtlib/fmt/pull/256>`_, + `#259 <https://github.com/fmtlib/fmt/pull/259>`_, + `#263 <https://github.com/fmtlib/fmt/issues/263>`_, + `#274 <https://github.com/fmtlib/fmt/issues/274>`_, + `#277 <https://github.com/fmtlib/fmt/pull/277>`_, + `#286 <https://github.com/fmtlib/fmt/pull/286>`_, + `#291 <https://github.com/fmtlib/fmt/issues/291>`_, + `#296 <https://github.com/fmtlib/fmt/issues/296>`_, + `#308 <https://github.com/fmtlib/fmt/issues/308>`_) + Thanks to `@mwinterb <https://github.com/mwinterb>`_, + `@pweiskircher (Patrik Weiskircher) <https://github.com/pweiskircher>`_, + `@Naios <https://github.com/Naios>`_. + +* Improved compatibility with Windows Store apps + (`#280 <https://github.com/fmtlib/fmt/issues/280>`_, + `#285 <https://github.com/fmtlib/fmt/pull/285>`_) + Thanks to `@mwinterb <https://github.com/mwinterb>`_. + +* Added tests of compatibility with older C++ standards + (`#273 <https://github.com/fmtlib/fmt/pull/273>`_). + Thanks to `@niosHD <https://github.com/niosHD>`_. + +* Fixed Android build (`#271 <https://github.com/fmtlib/fmt/pull/271>`_). + Thanks to `@newnon <https://github.com/newnon>`_. + +* Changed ``ArgMap`` to be backed by a vector instead of a map. + (`#261 <https://github.com/fmtlib/fmt/issues/261>`_, + `#262 <https://github.com/fmtlib/fmt/pull/262>`_). + Thanks to `@mwinterb <https://github.com/mwinterb>`_. + +* Added ``fprintf`` overload that writes to a ``std::ostream`` + (`#251 <https://github.com/fmtlib/fmt/pull/251>`_). + Thanks to `nickhutchinson (Nicholas Hutchinson) <https://github.com/nickhutchinson>`_. + +* Export symbols when building a Windows DLL + (`#245 <https://github.com/fmtlib/fmt/pull/245>`_). + Thanks to `macdems (Maciek Dems) <https://github.com/macdems>`_. + +* Fixed compilation on Cygwin (`#304 <https://github.com/fmtlib/fmt/issues/304>`_). + +* Implemented a workaround for a bug in Apple LLVM version 4.2 of clang + (`#276 <https://github.com/fmtlib/fmt/issues/276>`_). + +* Implemented a workaround for Google Test bug + `#705 <https://github.com/google/googletest/issues/705>`_ on gcc 6 + (`#268 <https://github.com/fmtlib/fmt/issues/268>`_). + Thanks to `octoploid <https://github.com/octoploid>`_. + +* Removed Biicode support because the latter has been discontinued. + +2.1.1 - 2016-04-11 +------------------ + +* The install location for generated CMake files is now configurable via + the ``FMT_CMAKE_DIR`` CMake variable + (`#299 <https://github.com/fmtlib/fmt/pull/299>`_). + Thanks to `@niosHD <https://github.com/niosHD>`_. + +* Documentation fixes (`#252 <https://github.com/fmtlib/fmt/issues/252>`_). + +2.1.0 - 2016-03-21 +------------------ + +* Project layout and build system improvements + (`#267 <https://github.com/fmtlib/fmt/pull/267>`_): + + * The code have been moved to the ``cppformat`` directory. + Including ``format.h`` from the top-level directory is deprecated + but works via a proxy header which will be removed in the next + major version. + + * C++ Format CMake targets now have proper interface definitions. + + * Installed version of the library now supports the header-only + configuration. + + * Targets ``doc``, ``install``, and ``test`` are now disabled if C++ Format + is included as a CMake subproject. They can be enabled by setting + ``FMT_DOC``, ``FMT_INSTALL``, and ``FMT_TEST`` in the parent project. + + Thanks to `@niosHD <https://github.com/niosHD>`_. + +2.0.1 - 2016-03-13 +------------------ + +* Improved CMake find and package support + (`#264 <https://github.com/fmtlib/fmt/issues/264>`_). + Thanks to `@niosHD <https://github.com/niosHD>`_. + +* Fix compile error with Android NDK and mingw32 + (`#241 <https://github.com/fmtlib/fmt/issues/241>`_). + Thanks to `@Gachapen (Magnus Bjerke Vik) <https://github.com/Gachapen>`_. + +* Documentation fixes + (`#248 <https://github.com/fmtlib/fmt/issues/248>`_, + `#260 <https://github.com/fmtlib/fmt/issues/260>`_). + +2.0.0 - 2015-12-01 +------------------ + +General +~~~~~~~ + +* [Breaking] Named arguments + (`#169 <https://github.com/fmtlib/fmt/pull/169>`_, + `#173 <https://github.com/fmtlib/fmt/pull/173>`_, + `#174 <https://github.com/fmtlib/fmt/pull/174>`_): + + .. code:: c++ + + fmt::print("The answer is {answer}.", fmt::arg("answer", 42)); + + Thanks to `@jamboree <https://github.com/jamboree>`_. + +* [Experimental] User-defined literals for format and named arguments + (`#204 <https://github.com/fmtlib/fmt/pull/204>`_, + `#206 <https://github.com/fmtlib/fmt/pull/206>`_, + `#207 <https://github.com/fmtlib/fmt/pull/207>`_): + + .. code:: c++ + + using namespace fmt::literals; + fmt::print("The answer is {answer}.", "answer"_a=42); + + Thanks to `@dean0x7d (Dean Moldovan) <https://github.com/dean0x7d>`_. + +* [Breaking] Formatting of more than 16 arguments is now supported when using + variadic templates + (`#141 <https://github.com/fmtlib/fmt/issues/141>`_). + Thanks to `@Shauren <https://github.com/Shauren>`_. + +* Runtime width specification + (`#168 <https://github.com/fmtlib/fmt/pull/168>`_): + + .. code:: c++ + + fmt::format("{0:{1}}", 42, 5); // gives " 42" + + Thanks to `@jamboree <https://github.com/jamboree>`_. + +* [Breaking] Enums are now formatted with an overloaded ``std::ostream`` insertion + operator (``operator<<``) if available + (`#232 <https://github.com/fmtlib/fmt/issues/232>`_). + +* [Breaking] Changed default ``bool`` format to textual, "true" or "false" + (`#170 <https://github.com/fmtlib/fmt/issues/170>`_): + + .. code:: c++ + + fmt::print("{}", true); // prints "true" + + To print ``bool`` as a number use numeric format specifier such as ``d``: + + .. code:: c++ + + fmt::print("{:d}", true); // prints "1" + +* ``fmt::printf`` and ``fmt::sprintf`` now support formatting of ``bool`` with the + ``%s`` specifier giving textual output, "true" or "false" + (`#223 <https://github.com/fmtlib/fmt/pull/223>`_): + + .. code:: c++ + + fmt::printf("%s", true); // prints "true" + + Thanks to `@LarsGullik <https://github.com/LarsGullik>`_. + +* [Breaking] ``signed char`` and ``unsigned char`` are now formatted as integers by default + (`#217 <https://github.com/fmtlib/fmt/pull/217>`_). + +* [Breaking] Pointers to C strings can now be formatted with the ``p`` specifier + (`#223 <https://github.com/fmtlib/fmt/pull/223>`_): + + .. code:: c++ + + fmt::print("{:p}", "test"); // prints pointer value + + Thanks to `@LarsGullik <https://github.com/LarsGullik>`_. + +* [Breaking] ``fmt::printf`` and ``fmt::sprintf`` now print null pointers as ``(nil)`` + and null strings as ``(null)`` for consistency with glibc + (`#226 <https://github.com/fmtlib/fmt/pull/226>`_). + Thanks to `@LarsGullik <https://github.com/LarsGullik>`_. + +* [Breaking] ``fmt::(s)printf`` now supports formatting of objects of user-defined types + that provide an overloaded ``std::ostream`` insertion operator (``operator<<``) + (`#201 <https://github.com/fmtlib/fmt/issues/201>`_): + + .. code:: c++ + + fmt::printf("The date is %s", Date(2012, 12, 9)); + +* [Breaking] The ``Buffer`` template is now part of the public API and can be used + to implement custom memory buffers + (`#140 <https://github.com/fmtlib/fmt/issues/140>`_). + Thanks to `@polyvertex (Jean-Charles Lefebvre) <https://github.com/polyvertex>`_. + +* [Breaking] Improved compatibility between ``BasicStringRef`` and + `std::experimental::basic_string_view + <http://en.cppreference.com/w/cpp/experimental/basic_string_view>`_ + (`#100 <https://github.com/fmtlib/fmt/issues/100>`_, + `#159 <https://github.com/fmtlib/fmt/issues/159>`_, + `#183 <https://github.com/fmtlib/fmt/issues/183>`_): + + - Comparison operators now compare string content, not pointers + - ``BasicStringRef::c_str`` replaced by ``BasicStringRef::data`` + - ``BasicStringRef`` is no longer assumed to be null-terminated + + References to null-terminated strings are now represented by a new class, + ``BasicCStringRef``. + +* Dependency on pthreads introduced by Google Test is now optional + (`#185 <https://github.com/fmtlib/fmt/issues/185>`_). + +* New CMake options ``FMT_DOC``, ``FMT_INSTALL`` and ``FMT_TEST`` to control + generation of ``doc``, ``install`` and ``test`` targets respectively, on by default + (`#197 <https://github.com/fmtlib/fmt/issues/197>`_, + `#198 <https://github.com/fmtlib/fmt/issues/198>`_, + `#200 <https://github.com/fmtlib/fmt/issues/200>`_). + Thanks to `@maddinat0r (Alex Martin) <https://github.com/maddinat0r>`_. + +* ``noexcept`` is now used when compiling with MSVC2015 + (`#215 <https://github.com/fmtlib/fmt/pull/215>`_). + Thanks to `@dmkrepo (Dmitriy) <https://github.com/dmkrepo>`_. + +* Added an option to disable use of ``windows.h`` when ``FMT_USE_WINDOWS_H`` + is defined as 0 before including ``format.h`` + (`#171 <https://github.com/fmtlib/fmt/issues/171>`_). + Thanks to `@alfps (Alf P. Steinbach) <https://github.com/alfps>`_. + +* [Breaking] ``windows.h`` is now included with ``NOMINMAX`` unless + ``FMT_WIN_MINMAX`` is defined. This is done to prevent breaking code using + ``std::min`` and ``std::max`` and only affects the header-only configuration + (`#152 <https://github.com/fmtlib/fmt/issues/152>`_, + `#153 <https://github.com/fmtlib/fmt/pull/153>`_, + `#154 <https://github.com/fmtlib/fmt/pull/154>`_). + Thanks to `@DevO2012 <https://github.com/DevO2012>`_. + +* Improved support for custom character types + (`#171 <https://github.com/fmtlib/fmt/issues/171>`_). + Thanks to `@alfps (Alf P. Steinbach) <https://github.com/alfps>`_. + +* Added an option to disable use of IOStreams when ``FMT_USE_IOSTREAMS`` + is defined as 0 before including ``format.h`` + (`#205 <https://github.com/fmtlib/fmt/issues/205>`_, + `#208 <https://github.com/fmtlib/fmt/pull/208>`_). + Thanks to `@JodiTheTigger <https://github.com/JodiTheTigger>`_. + +* Improved detection of ``isnan``, ``isinf`` and ``signbit``. + +Optimization +~~~~~~~~~~~~ + +* Made formatting of user-defined types more efficient with a custom stream buffer + (`#92 <https://github.com/fmtlib/fmt/issues/92>`_, + `#230 <https://github.com/fmtlib/fmt/pull/230>`_). + Thanks to `@NotImplemented <https://github.com/NotImplemented>`_. + +* Further improved performance of ``fmt::Writer`` on integer formatting + and fixed a minor regression. Now it is ~7% faster than ``karma::generate`` + on Karma's benchmark + (`#186 <https://github.com/fmtlib/fmt/issues/186>`_). + +* [Breaking] Reduced `compiled code size + <https://github.com/fmtlib/fmt#compile-time-and-code-bloat>`_ + (`#143 <https://github.com/fmtlib/fmt/issues/143>`_, + `#149 <https://github.com/fmtlib/fmt/pull/149>`_). + +Distribution +~~~~~~~~~~~~ + +* [Breaking] Headers are now installed in + ``${CMAKE_INSTALL_PREFIX}/include/cppformat`` + (`#178 <https://github.com/fmtlib/fmt/issues/178>`_). + Thanks to `@jackyf (Eugene V. Lyubimkin) <https://github.com/jackyf>`_. + +* [Breaking] Changed the library name from ``format`` to ``cppformat`` + for consistency with the project name and to avoid potential conflicts + (`#178 <https://github.com/fmtlib/fmt/issues/178>`_). + Thanks to `@jackyf (Eugene V. Lyubimkin) <https://github.com/jackyf>`_. + +* C++ Format is now available in `Debian <https://www.debian.org/>`_ GNU/Linux + (`stretch <https://packages.debian.org/source/stretch/cppformat>`_, + `sid <https://packages.debian.org/source/sid/cppformat>`_) and + derived distributions such as + `Ubuntu <https://launchpad.net/ubuntu/+source/cppformat>`_ 15.10 and later + (`#155 <https://github.com/fmtlib/fmt/issues/155>`_):: + + $ sudo apt-get install libcppformat1-dev + + Thanks to `@jackyf (Eugene V. Lyubimkin) <https://github.com/jackyf>`_. + +* `Packages for Fedora and RHEL <https://admin.fedoraproject.org/pkgdb/package/cppformat/>`_ + are now available. Thanks to Dave Johansen. + +* C++ Format can now be installed via `Homebrew <http://brew.sh/>`_ on OS X + (`#157 <https://github.com/fmtlib/fmt/issues/157>`_):: + + $ brew install cppformat + + Thanks to `@ortho <https://github.com/ortho>`_, Anatoliy Bulukin. + +Documentation +~~~~~~~~~~~~~ + +* Migrated from ReadTheDocs to GitHub Pages for better responsiveness + and reliability + (`#128 <https://github.com/fmtlib/fmt/issues/128>`_). + New documentation address is http://cppformat.github.io/. + + +* Added `Building the documentation + <https://fmt.dev/2.0.0/usage.html#building-the-documentation>`_ + section to the documentation. + +* Documentation build script is now compatible with Python 3 and newer pip versions. + (`#189 <https://github.com/fmtlib/fmt/pull/189>`_, + `#209 <https://github.com/fmtlib/fmt/issues/209>`_). + Thanks to `@JodiTheTigger <https://github.com/JodiTheTigger>`_ and + `@xentec <https://github.com/xentec>`_. + +* Documentation fixes and improvements + (`#36 <https://github.com/fmtlib/fmt/issues/36>`_, + `#75 <https://github.com/fmtlib/fmt/issues/75>`_, + `#125 <https://github.com/fmtlib/fmt/issues/125>`_, + `#160 <https://github.com/fmtlib/fmt/pull/160>`_, + `#161 <https://github.com/fmtlib/fmt/pull/161>`_, + `#162 <https://github.com/fmtlib/fmt/issues/162>`_, + `#165 <https://github.com/fmtlib/fmt/issues/165>`_, + `#210 <https://github.com/fmtlib/fmt/issues/210>`_). + Thanks to `@syohex (Syohei YOSHIDA) <https://github.com/syohex>`_ and + bug reporters. + +* Fixed out-of-tree documentation build + (`#177 <https://github.com/fmtlib/fmt/issues/177>`_). + Thanks to `@jackyf (Eugene V. Lyubimkin) <https://github.com/jackyf>`_. + +Fixes +~~~~~ + +* Fixed ``initializer_list`` detection + (`#136 <https://github.com/fmtlib/fmt/issues/136>`_). + Thanks to `@Gachapen (Magnus Bjerke Vik) <https://github.com/Gachapen>`_. + +* [Breaking] Fixed formatting of enums with numeric format specifiers in + ``fmt::(s)printf`` + (`#131 <https://github.com/fmtlib/fmt/issues/131>`_, + `#139 <https://github.com/fmtlib/fmt/issues/139>`_): + + .. code:: c++ + + enum { ANSWER = 42 }; + fmt::printf("%d", ANSWER); + + Thanks to `@Naios <https://github.com/Naios>`_. + +* Improved compatibility with old versions of MinGW + (`#129 <https://github.com/fmtlib/fmt/issues/129>`_, + `#130 <https://github.com/fmtlib/fmt/pull/130>`_, + `#132 <https://github.com/fmtlib/fmt/issues/132>`_). + Thanks to `@cstamford (Christopher Stamford) <https://github.com/cstamford>`_. + +* Fixed a compile error on MSVC with disabled exceptions + (`#144 <https://github.com/fmtlib/fmt/issues/144>`_). + +* Added a workaround for broken implementation of variadic templates in MSVC2012 + (`#148 <https://github.com/fmtlib/fmt/issues/148>`_). + +* Placed the anonymous namespace within ``fmt`` namespace for the header-only + configuration + (`#171 <https://github.com/fmtlib/fmt/issues/171>`_). + Thanks to `@alfps (Alf P. Steinbach) <https://github.com/alfps>`_. + +* Fixed issues reported by Coverity Scan + (`#187 <https://github.com/fmtlib/fmt/issues/187>`_, + `#192 <https://github.com/fmtlib/fmt/issues/192>`_). + +* Implemented a workaround for a name lookup bug in MSVC2010 + (`#188 <https://github.com/fmtlib/fmt/issues/188>`_). + +* Fixed compiler warnings + (`#95 <https://github.com/fmtlib/fmt/issues/95>`_, + `#96 <https://github.com/fmtlib/fmt/issues/96>`_, + `#114 <https://github.com/fmtlib/fmt/pull/114>`_, + `#135 <https://github.com/fmtlib/fmt/issues/135>`_, + `#142 <https://github.com/fmtlib/fmt/issues/142>`_, + `#145 <https://github.com/fmtlib/fmt/issues/145>`_, + `#146 <https://github.com/fmtlib/fmt/issues/146>`_, + `#158 <https://github.com/fmtlib/fmt/issues/158>`_, + `#163 <https://github.com/fmtlib/fmt/issues/163>`_, + `#175 <https://github.com/fmtlib/fmt/issues/175>`_, + `#190 <https://github.com/fmtlib/fmt/issues/190>`_, + `#191 <https://github.com/fmtlib/fmt/pull/191>`_, + `#194 <https://github.com/fmtlib/fmt/issues/194>`_, + `#196 <https://github.com/fmtlib/fmt/pull/196>`_, + `#216 <https://github.com/fmtlib/fmt/issues/216>`_, + `#218 <https://github.com/fmtlib/fmt/pull/218>`_, + `#220 <https://github.com/fmtlib/fmt/pull/220>`_, + `#229 <https://github.com/fmtlib/fmt/pull/229>`_, + `#233 <https://github.com/fmtlib/fmt/issues/233>`_, + `#234 <https://github.com/fmtlib/fmt/issues/234>`_, + `#236 <https://github.com/fmtlib/fmt/pull/236>`_, + `#281 <https://github.com/fmtlib/fmt/issues/281>`_, + `#289 <https://github.com/fmtlib/fmt/issues/289>`_). + Thanks to `@seanmiddleditch (Sean Middleditch) <https://github.com/seanmiddleditch>`_, + `@dixlorenz (Dix Lorenz) <https://github.com/dixlorenz>`_, + `@CarterLi (李通洲) <https://github.com/CarterLi>`_, + `@Naios <https://github.com/Naios>`_, + `@fmatthew5876 (Matthew Fioravante) <https://github.com/fmatthew5876>`_, + `@LevskiWeng (Levski Weng) <https://github.com/LevskiWeng>`_, + `@rpopescu <https://github.com/rpopescu>`_, + `@gabime (Gabi Melman) <https://github.com/gabime>`_, + `@cubicool (Jeremy Moles) <https://github.com/cubicool>`_, + `@jkflying (Julian Kent) <https://github.com/jkflying>`_, + `@LogicalKnight (Sean L) <https://github.com/LogicalKnight>`_, + `@inguin (Ingo van Lil) <https://github.com/inguin>`_ and + `@Jopie64 (Johan) <https://github.com/Jopie64>`_. + +* Fixed portability issues (mostly causing test failures) on ARM, ppc64, ppc64le, + s390x and SunOS 5.11 i386 + (`#138 <https://github.com/fmtlib/fmt/issues/138>`_, + `#179 <https://github.com/fmtlib/fmt/issues/179>`_, + `#180 <https://github.com/fmtlib/fmt/issues/180>`_, + `#202 <https://github.com/fmtlib/fmt/issues/202>`_, + `#225 <https://github.com/fmtlib/fmt/issues/225>`_, + `Red Hat Bugzilla Bug 1260297 <https://bugzilla.redhat.com/show_bug.cgi?id=1260297>`_). + Thanks to `@Naios <https://github.com/Naios>`_, + `@jackyf (Eugene V. Lyubimkin) <https://github.com/jackyf>`_ and Dave Johansen. + +* Fixed a name conflict with macro ``free`` defined in + ``crtdbg.h`` when ``_CRTDBG_MAP_ALLOC`` is set + (`#211 <https://github.com/fmtlib/fmt/issues/211>`_). + +* Fixed shared library build on OS X + (`#212 <https://github.com/fmtlib/fmt/pull/212>`_). + Thanks to `@dean0x7d (Dean Moldovan) <https://github.com/dean0x7d>`_. + +* Fixed an overload conflict on MSVC when ``/Zc:wchar_t-`` option is specified + (`#214 <https://github.com/fmtlib/fmt/pull/214>`_). + Thanks to `@slavanap (Vyacheslav Napadovsky) <https://github.com/slavanap>`_. + +* Improved compatibility with MSVC 2008 + (`#236 <https://github.com/fmtlib/fmt/pull/236>`_). + Thanks to `@Jopie64 (Johan) <https://github.com/Jopie64>`_. + +* Improved compatibility with bcc32 + (`#227 <https://github.com/fmtlib/fmt/issues/227>`_). + +* Fixed ``static_assert`` detection on Clang + (`#228 <https://github.com/fmtlib/fmt/pull/228>`_). + Thanks to `@dean0x7d (Dean Moldovan) <https://github.com/dean0x7d>`_. + +1.1.0 - 2015-03-06 +------------------ + +* Added ``BasicArrayWriter``, a class template that provides operations for + formatting and writing data into a fixed-size array + (`#105 <https://github.com/fmtlib/fmt/issues/105>`_ and + `#122 <https://github.com/fmtlib/fmt/issues/122>`_): + + .. code:: c++ + + char buffer[100]; + fmt::ArrayWriter w(buffer); + w.write("The answer is {}", 42); + +* Added `0 A.D. <http://play0ad.com/>`_ and `PenUltima Online (POL) + <http://www.polserver.com/>`_ to the list of notable projects using C++ Format. + +* C++ Format now uses MSVC intrinsics for better formatting performance + (`#115 <https://github.com/fmtlib/fmt/pull/115>`_, + `#116 <https://github.com/fmtlib/fmt/pull/116>`_, + `#118 <https://github.com/fmtlib/fmt/pull/118>`_ and + `#121 <https://github.com/fmtlib/fmt/pull/121>`_). + Previously these optimizations where only used on GCC and Clang. + Thanks to `@CarterLi <https://github.com/CarterLi>`_ and + `@objectx <https://github.com/objectx>`_. + +* CMake install target (`#119 <https://github.com/fmtlib/fmt/pull/119>`_). + Thanks to `@TrentHouliston <https://github.com/TrentHouliston>`_. + + You can now install C++ Format with ``make install`` command. + +* Improved `Biicode <http://www.biicode.com/>`_ support + (`#98 <https://github.com/fmtlib/fmt/pull/98>`_ and + `#104 <https://github.com/fmtlib/fmt/pull/104>`_). Thanks to + `@MariadeAnton <https://github.com/MariadeAnton>`_ and + `@franramirez688 <https://github.com/franramirez688>`_. + +* Improved support for building with `Android NDK + <https://developer.android.com/tools/sdk/ndk/index.html>`_ + (`#107 <https://github.com/fmtlib/fmt/pull/107>`_). + Thanks to `@newnon <https://github.com/newnon>`_. + + The `android-ndk-example <https://github.com/fmtlib/android-ndk-example>`_ + repository provides and example of using C++ Format with Android NDK: + + .. image:: https://raw.githubusercontent.com/fmtlib/android-ndk-example/ + master/screenshot.png + +* Improved documentation of ``SystemError`` and ``WindowsError`` + (`#54 <https://github.com/fmtlib/fmt/issues/54>`_). + +* Various code improvements + (`#110 <https://github.com/fmtlib/fmt/pull/110>`_, + `#111 <https://github.com/fmtlib/fmt/pull/111>`_ + `#112 <https://github.com/fmtlib/fmt/pull/112>`_). + Thanks to `@CarterLi <https://github.com/CarterLi>`_. + +* Improved compile-time errors when formatting wide into narrow strings + (`#117 <https://github.com/fmtlib/fmt/issues/117>`_). + +* Fixed ``BasicWriter::write`` without formatting arguments when C++11 support + is disabled (`#109 <https://github.com/fmtlib/fmt/issues/109>`_). + +* Fixed header-only build on OS X with GCC 4.9 + (`#124 <https://github.com/fmtlib/fmt/issues/124>`_). + +* Fixed packaging issues (`#94 <https://github.com/fmtlib/fmt/issues/94>`_). + +* Added `changelog <https://github.com/fmtlib/fmt/blob/master/ChangeLog.rst>`_ + (`#103 <https://github.com/fmtlib/fmt/issues/103>`_). + +1.0.0 - 2015-02-05 +------------------ + +* Add support for a header-only configuration when ``FMT_HEADER_ONLY`` is + defined before including ``format.h``: + + .. code:: c++ + + #define FMT_HEADER_ONLY + #include "format.h" + +* Compute string length in the constructor of ``BasicStringRef`` + instead of the ``size`` method + (`#79 <https://github.com/fmtlib/fmt/issues/79>`_). + This eliminates size computation for string literals on reasonable optimizing + compilers. + +* Fix formatting of types with overloaded ``operator <<`` for ``std::wostream`` + (`#86 <https://github.com/fmtlib/fmt/issues/86>`_): + + .. code:: c++ + + fmt::format(L"The date is {0}", Date(2012, 12, 9)); + +* Fix linkage of tests on Arch Linux + (`#89 <https://github.com/fmtlib/fmt/issues/89>`_). + +* Allow precision specifier for non-float arguments + (`#90 <https://github.com/fmtlib/fmt/issues/90>`_): + + .. code:: c++ + + fmt::print("{:.3}\n", "Carpet"); // prints "Car" + +* Fix build on Android NDK + (`#93 <https://github.com/fmtlib/fmt/issues/93>`_) + +* Improvements to documentation build procedure. + +* Remove ``FMT_SHARED`` CMake variable in favor of standard `BUILD_SHARED_LIBS + <http://www.cmake.org/cmake/help/v3.0/variable/BUILD_SHARED_LIBS.html>`_. + +* Fix error handling in ``fmt::fprintf``. + +* Fix a number of warnings. + +0.12.0 - 2014-10-25 +------------------- + +* [Breaking] Improved separation between formatting and buffer management. + ``Writer`` is now a base class that cannot be instantiated directly. + The new ``MemoryWriter`` class implements the default buffer management + with small allocations done on stack. So ``fmt::Writer`` should be replaced + with ``fmt::MemoryWriter`` in variable declarations. + + Old code: + + .. code:: c++ + + fmt::Writer w; + + New code: + + .. code:: c++ + + fmt::MemoryWriter w; + + If you pass ``fmt::Writer`` by reference, you can continue to do so: + + .. code:: c++ + + void f(fmt::Writer &w); + + This doesn't affect the formatting API. + +* Support for custom memory allocators + (`#69 <https://github.com/fmtlib/fmt/issues/69>`_) + +* Formatting functions now accept `signed char` and `unsigned char` strings as + arguments (`#73 <https://github.com/fmtlib/fmt/issues/73>`_): + + .. code:: c++ + + auto s = format("GLSL version: {}", glGetString(GL_VERSION)); + +* Reduced code bloat. According to the new `benchmark results + <https://github.com/fmtlib/fmt#compile-time-and-code-bloat>`_, + cppformat is close to ``printf`` and by the order of magnitude better than + Boost Format in terms of compiled code size. + +* Improved appearance of the documentation on mobile by using the `Sphinx + Bootstrap theme <http://ryan-roemer.github.io/sphinx-bootstrap-theme/>`_: + + .. |old| image:: https://cloud.githubusercontent.com/assets/576385/4792130/ + cd256436-5de3-11e4-9a62-c077d0c2b003.png + + .. |new| image:: https://cloud.githubusercontent.com/assets/576385/4792131/ + cd29896c-5de3-11e4-8f59-cac952942bf0.png + + +-------+-------+ + | Old | New | + +-------+-------+ + | |old| | |new| | + +-------+-------+ + +0.11.0 - 2014-08-21 +------------------- + +* Safe printf implementation with a POSIX extension for positional arguments: + + .. code:: c++ + + fmt::printf("Elapsed time: %.2f seconds", 1.23); + fmt::printf("%1$s, %3$d %2$s", weekday, month, day); + +* Arguments of ``char`` type can now be formatted as integers + (Issue `#55 <https://github.com/fmtlib/fmt/issues/55>`_): + + .. code:: c++ + + fmt::format("0x{0:02X}", 'a'); + +* Deprecated parts of the API removed. + +* The library is now built and tested on MinGW with Appveyor in addition to + existing test platforms Linux/GCC, OS X/Clang, Windows/MSVC. + +0.10.0 - 2014-07-01 +------------------- + +**Improved API** + +* All formatting methods are now implemented as variadic functions instead + of using ``operator<<`` for feeding arbitrary arguments into a temporary + formatter object. This works both with C++11 where variadic templates are + used and with older standards where variadic functions are emulated by + providing lightweight wrapper functions defined with the ``FMT_VARIADIC`` + macro. You can use this macro for defining your own portable variadic + functions: + + .. code:: c++ + + void report_error(const char *format, const fmt::ArgList &args) { + fmt::print("Error: {}"); + fmt::print(format, args); + } + FMT_VARIADIC(void, report_error, const char *) + + report_error("file not found: {}", path); + + Apart from a more natural syntax, this also improves performance as there + is no need to construct temporary formatter objects and control arguments' + lifetimes. Because the wrapper functions are very lightweight, this doesn't + cause code bloat even in pre-C++11 mode. + +* Simplified common case of formatting an ``std::string``. Now it requires a + single function call: + + .. code:: c++ + + std::string s = format("The answer is {}.", 42); + + Previously it required 2 function calls: + + .. code:: c++ + + std::string s = str(Format("The answer is {}.") << 42); + + Instead of unsafe ``c_str`` function, ``fmt::Writer`` should be used directly + to bypass creation of ``std::string``: + + .. code:: c++ + + fmt::Writer w; + w.write("The answer is {}.", 42); + w.c_str(); // returns a C string + + This doesn't do dynamic memory allocation for small strings and is less error + prone as the lifetime of the string is the same as for ``std::string::c_str`` + which is well understood (hopefully). + +* Improved consistency in naming functions that are a part of the public API. + Now all public functions are lowercase following the standard library + conventions. Previously it was a combination of lowercase and + CapitalizedWords. + Issue `#50 <https://github.com/fmtlib/fmt/issues/50>`_. + +* Old functions are marked as deprecated and will be removed in the next + release. + +**Other Changes** + +* Experimental support for printf format specifications (work in progress): + + .. code:: c++ + + fmt::printf("The answer is %d.", 42); + std::string s = fmt::sprintf("Look, a %s!", "string"); + +* Support for hexadecimal floating point format specifiers ``a`` and ``A``: + + .. code:: c++ + + print("{:a}", -42.0); // Prints -0x1.5p+5 + print("{:A}", -42.0); // Prints -0X1.5P+5 + +* CMake option ``FMT_SHARED`` that specifies whether to build format as a + shared library (off by default). + +0.9.0 - 2014-05-13 +------------------ + +* More efficient implementation of variadic formatting functions. + +* ``Writer::Format`` now has a variadic overload: + + .. code:: c++ + + Writer out; + out.Format("Look, I'm {}!", "variadic"); + +* For efficiency and consistency with other overloads, variadic overload of + the ``Format`` function now returns ``Writer`` instead of ``std::string``. + Use the ``str`` function to convert it to ``std::string``: + + .. code:: c++ + + std::string s = str(Format("Look, I'm {}!", "variadic")); + +* Replaced formatter actions with output sinks: ``NoAction`` -> ``NullSink``, + ``Write`` -> ``FileSink``, ``ColorWriter`` -> ``ANSITerminalSink``. + This improves naming consistency and shouldn't affect client code unless + these classes are used directly which should be rarely needed. + +* Added ``ThrowSystemError`` function that formats a message and throws + ``SystemError`` containing the formatted message and system-specific error + description. For example, the following code + + .. code:: c++ + + FILE *f = fopen(filename, "r"); + if (!f) + ThrowSystemError(errno, "Failed to open file '{}'") << filename; + + will throw ``SystemError`` exception with description + "Failed to open file '<filename>': No such file or directory" if file + doesn't exist. + +* Support for AppVeyor continuous integration platform. + +* ``Format`` now throws ``SystemError`` in case of I/O errors. + +* Improve test infrastructure. Print functions are now tested by redirecting + the output to a pipe. + +0.8.0 - 2014-04-14 +------------------ + +* Initial release diff --git a/contrib/libs/fmt/LICENSE.rst b/contrib/libs/fmt/LICENSE.rst index ebe5baa825..f0ec3db4d2 100644 --- a/contrib/libs/fmt/LICENSE.rst +++ b/contrib/libs/fmt/LICENSE.rst @@ -1,27 +1,27 @@ -Copyright (c) 2012 - present, Victor Zverovich - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -"Software"), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - ---- Optional exception to the license --- - -As an exception, if, as a result of your compiling your source code, portions -of this Software are embedded into a machine-executable object form of such -source code, you may redistribute such embedded portions in such object form -without including the above copyright and permission notices. +Copyright (c) 2012 - present, Victor Zverovich + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +--- Optional exception to the license --- + +As an exception, if, as a result of your compiling your source code, portions +of this Software are embedded into a machine-executable object form of such +source code, you may redistribute such embedded portions in such object form +without including the above copyright and permission notices. diff --git a/contrib/libs/fmt/README.rst b/contrib/libs/fmt/README.rst index 2cfb786750..acddc70ef1 100644 --- a/contrib/libs/fmt/README.rst +++ b/contrib/libs/fmt/README.rst @@ -1,39 +1,39 @@ -{fmt} -===== - -.. image:: https://travis-ci.org/fmtlib/fmt.png?branch=master - :target: https://travis-ci.org/fmtlib/fmt - -.. image:: https://ci.appveyor.com/api/projects/status/ehjkiefde6gucy1v - :target: https://ci.appveyor.com/project/vitaut/fmt - +{fmt} +===== + +.. image:: https://travis-ci.org/fmtlib/fmt.png?branch=master + :target: https://travis-ci.org/fmtlib/fmt + +.. image:: https://ci.appveyor.com/api/projects/status/ehjkiefde6gucy1v + :target: https://ci.appveyor.com/project/vitaut/fmt + .. image:: https://oss-fuzz-build-logs.storage.googleapis.com/badges/fmt.svg :alt: fmt is continuously fuzzed at oss-fuzz :target: https://bugs.chromium.org/p/oss-fuzz/issues/list?\ colspec=ID%20Type%20Component%20Status%20Proj%20Reported%20Owner%20\ Summary&q=proj%3Dfmt&can=1 - -.. image:: https://img.shields.io/badge/stackoverflow-fmt-blue.svg - :alt: Ask questions at StackOverflow with the tag fmt - :target: https://stackoverflow.com/questions/tagged/fmt - + +.. image:: https://img.shields.io/badge/stackoverflow-fmt-blue.svg + :alt: Ask questions at StackOverflow with the tag fmt + :target: https://stackoverflow.com/questions/tagged/fmt + **{fmt}** is an open-source formatting library providing a fast and safe alternative to C stdio and C++ iostreams. - + If you like this project, please consider donating to BYSOL, an initiative to help victims of political repressions in Belarus: https://www.facebook.com/donate/759400044849707/108388587646909/. - + `Documentation <https://fmt.dev>`__ - + Q&A: ask questions on `StackOverflow with the tag fmt <https://stackoverflow.com/questions/tagged/fmt>`_. Try {fmt} in `Compiler Explorer <https://godbolt.org/z/Eq5763>`_. -Features --------- - +Features +-------- + * Simple `format API <https://fmt.dev/latest/api.html>`_ with positional arguments for localization * Implementation of `C++20 std::format @@ -42,12 +42,12 @@ Features `format <https://docs.python.org/3/library/stdtypes.html#str.format>`_ * Fast IEEE 754 floating-point formatter with correct rounding, shortness and round-trip guarantees -* Safe `printf implementation +* Safe `printf implementation <https://fmt.dev/latest/api.html#printf-formatting>`_ including the POSIX extension for positional arguments * Extensibility: `support for user-defined types <https://fmt.dev/latest/api.html#formatting-user-defined-types>`_ -* High performance: faster than common standard library implementations of +* High performance: faster than common standard library implementations of ``(s)printf``, iostreams, ``to_string`` and ``to_chars``, see `Speed tests`_ and `Converting a hundred million integers to strings per second <http://www.zverovich.net/2020/06/13/fast-int-to-string-revisited.html>`_ @@ -58,38 +58,38 @@ Features <https://github.com/fmtlib/fmt/tree/master/test>`_ and is `continuously fuzzed <https://bugs.chromium.org/p/oss-fuzz/issues/list?colspec=ID%20Type%20 Component%20Status%20Proj%20Reported%20Owner%20Summary&q=proj%3Dfmt&can=1>`_ -* Safety: the library is fully type safe, errors in format strings can be - reported at compile time, automatic memory management prevents buffer overflow +* Safety: the library is fully type safe, errors in format strings can be + reported at compile time, automatic memory management prevents buffer overflow errors -* Ease of use: small self-contained code base, no external dependencies, - permissive MIT `license - <https://github.com/fmtlib/fmt/blob/master/LICENSE.rst>`_ -* `Portability <https://fmt.dev/latest/index.html#portability>`_ with +* Ease of use: small self-contained code base, no external dependencies, + permissive MIT `license + <https://github.com/fmtlib/fmt/blob/master/LICENSE.rst>`_ +* `Portability <https://fmt.dev/latest/index.html#portability>`_ with consistent output across platforms and support for older compilers * Clean warning-free codebase even on high warning levels such as ``-Wall -Wextra -pedantic`` * Locale-independence by default * Optional header-only configuration enabled with the ``FMT_HEADER_ONLY`` macro - + See the `documentation <https://fmt.dev>`_ for more details. - -Examples --------- - + +Examples +-------- + **Print to stdout** (`run <https://godbolt.org/z/Tevcjh>`_) - -.. code:: c++ - + +.. code:: c++ + #include <fmt/core.h> int main() { fmt::print("Hello, world!\n"); } - + **Format a string** (`run <https://godbolt.org/z/oK8h33>`_) - -.. code:: c++ - + +.. code:: c++ + std::string s = fmt::format("The answer is {}.", 42); // s == "The answer is 42." @@ -97,69 +97,69 @@ Examples .. code:: c++ - std::string s = fmt::format("I'd rather be {1} than {0}.", "right", "happy"); - // s == "I'd rather be happy than right." - + std::string s = fmt::format("I'd rather be {1} than {0}.", "right", "happy"); + // s == "I'd rather be happy than right." + **Print chrono durations** (`run <https://godbolt.org/z/K8s4Mc>`_) - -.. code:: c++ - + +.. code:: c++ + #include <fmt/chrono.h> - + int main() { using namespace std::literals::chrono_literals; fmt::print("Default format: {} {}\n", 42s, 100ms); fmt::print("strftime-like format: {:%H:%M:%S}\n", 3h + 15min + 30s); } - + Output:: - + Default format: 42s 100ms strftime-like format: 03:15:30 - + **Print a container** (`run <https://godbolt.org/z/MjsY7c>`_) -.. code:: c++ - +.. code:: c++ + #include <vector> #include <fmt/ranges.h> - + int main() { std::vector<int> v = {1, 2, 3}; fmt::print("{}\n", v); } - + Output:: {1, 2, 3} **Check a format string at compile time** -.. code:: c++ - +.. code:: c++ + std::string s = fmt::format(FMT_STRING("{:d}"), "don't panic"); - + This gives a compile-time error because ``d`` is an invalid format specifier for a string. - + **Write a file from a single thread** - + .. code:: c++ - + #include <fmt/os.h> - + int main() { auto out = fmt::output_file("guide.txt"); out.print("Don't {}", "Panic"); } - + This can be `5 to 9 times faster than fprintf <http://www.zverovich.net/2020/08/04/optimal-file-buffer-size.html>`_. **Print with colors and text styles** -.. code:: c++ - +.. code:: c++ + #include <fmt/color.h> int main() { @@ -169,150 +169,150 @@ This can be `5 to 9 times faster than fprintf fmt::emphasis::underline, "Hello, {}!\n", "мир"); fmt::print(fg(fmt::color::steel_blue) | fmt::emphasis::italic, "Hello, {}!\n", "世界"); - } - + } + Output on a modern terminal: - + .. image:: https://user-images.githubusercontent.com/ 576385/88485597-d312f600-cf2b-11ea-9cbe-61f535a86e28.png - -Benchmarks ----------- - -Speed tests -~~~~~~~~~~~ - -================= ============= =========== -Library Method Run Time, s -================= ============= =========== -libc printf 1.04 -libc++ std::ostream 3.05 -{fmt} 6.1.1 fmt::print 0.75 -Boost Format 1.67 boost::format 7.24 -Folly Format folly::format 2.23 -================= ============= =========== - -{fmt} is the fastest of the benchmarked methods, ~35% faster than ``printf``. - -The above results were generated by building ``tinyformat_test.cpp`` on macOS + +Benchmarks +---------- + +Speed tests +~~~~~~~~~~~ + +================= ============= =========== +Library Method Run Time, s +================= ============= =========== +libc printf 1.04 +libc++ std::ostream 3.05 +{fmt} 6.1.1 fmt::print 0.75 +Boost Format 1.67 boost::format 7.24 +Folly Format folly::format 2.23 +================= ============= =========== + +{fmt} is the fastest of the benchmarked methods, ~35% faster than ``printf``. + +The above results were generated by building ``tinyformat_test.cpp`` on macOS 10.14.6 with ``clang++ -O3 -DNDEBUG -DSPEED_TEST -DHAVE_FORMAT``, and taking the best of three runs. In the test, the format string ``"%0.10f:%04d:%+g:%s:%p:%c:%%\n"`` -or equivalent is filled 2,000,000 times with output sent to ``/dev/null``; for -further details refer to the `source -<https://github.com/fmtlib/format-benchmark/blob/master/tinyformat_test.cpp>`_. - +or equivalent is filled 2,000,000 times with output sent to ``/dev/null``; for +further details refer to the `source +<https://github.com/fmtlib/format-benchmark/blob/master/tinyformat_test.cpp>`_. + {fmt} is up to 20-30x faster than ``std::ostringstream`` and ``sprintf`` on floating-point formatting (`dtoa-benchmark <https://github.com/fmtlib/dtoa-benchmark>`_) and faster than `double-conversion <https://github.com/google/double-conversion>`_ and `ryu <https://github.com/ulfjack/ryu>`_: - + .. image:: https://user-images.githubusercontent.com/576385/ 95684665-11719600-0ba8-11eb-8e5b-972ff4e49428.png :target: https://fmt.dev/unknown_mac64_clang12.0.html - -Compile time and code bloat -~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -The script `bloat-test.py -<https://github.com/fmtlib/format-benchmark/blob/master/bloat-test.py>`_ -from `format-benchmark <https://github.com/fmtlib/format-benchmark>`_ -tests compile time and code bloat for nontrivial projects. -It generates 100 translation units and uses ``printf()`` or its alternative -five times in each to simulate a medium sized project. The resulting -executable size and compile time (Apple LLVM version 8.1.0 (clang-802.0.42), -macOS Sierra, best of three) is shown in the following tables. - -**Optimized build (-O3)** - -============= =============== ==================== ================== -Method Compile Time, s Executable size, KiB Stripped size, KiB -============= =============== ==================== ================== -printf 2.6 29 26 -printf+string 16.4 29 26 -iostreams 31.1 59 55 -{fmt} 19.0 37 34 -Boost Format 91.9 226 203 -Folly Format 115.7 101 88 -============= =============== ==================== ================== - -As you can see, {fmt} has 60% less overhead in terms of resulting binary code -size compared to iostreams and comes pretty close to ``printf``. Boost Format -and Folly Format have the largest overheads. - -``printf+string`` is the same as ``printf`` but with extra ``<string>`` -include to measure the overhead of the latter. - -**Non-optimized build** - -============= =============== ==================== ================== -Method Compile Time, s Executable size, KiB Stripped size, KiB -============= =============== ==================== ================== -printf 2.2 33 30 -printf+string 16.0 33 30 -iostreams 28.3 56 52 -{fmt} 18.2 59 50 -Boost Format 54.1 365 303 -Folly Format 79.9 445 430 -============= =============== ==================== ================== - -``libc``, ``lib(std)c++`` and ``libfmt`` are all linked as shared libraries to -compare formatting function overhead only. Boost Format is a -header-only library so it doesn't provide any linkage options. - -Running the tests -~~~~~~~~~~~~~~~~~ - -Please refer to `Building the library`__ for the instructions on how to build -the library and run the unit tests. - -__ https://fmt.dev/latest/usage.html#building-the-library - -Benchmarks reside in a separate repository, -`format-benchmarks <https://github.com/fmtlib/format-benchmark>`_, -so to run the benchmarks you first need to clone this repository and -generate Makefiles with CMake:: - - $ git clone --recursive https://github.com/fmtlib/format-benchmark.git - $ cd format-benchmark - $ cmake . - -Then you can run the speed test:: - - $ make speed-test - -or the bloat test:: - - $ make bloat-test - -Projects using this library ---------------------------- - + +Compile time and code bloat +~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +The script `bloat-test.py +<https://github.com/fmtlib/format-benchmark/blob/master/bloat-test.py>`_ +from `format-benchmark <https://github.com/fmtlib/format-benchmark>`_ +tests compile time and code bloat for nontrivial projects. +It generates 100 translation units and uses ``printf()`` or its alternative +five times in each to simulate a medium sized project. The resulting +executable size and compile time (Apple LLVM version 8.1.0 (clang-802.0.42), +macOS Sierra, best of three) is shown in the following tables. + +**Optimized build (-O3)** + +============= =============== ==================== ================== +Method Compile Time, s Executable size, KiB Stripped size, KiB +============= =============== ==================== ================== +printf 2.6 29 26 +printf+string 16.4 29 26 +iostreams 31.1 59 55 +{fmt} 19.0 37 34 +Boost Format 91.9 226 203 +Folly Format 115.7 101 88 +============= =============== ==================== ================== + +As you can see, {fmt} has 60% less overhead in terms of resulting binary code +size compared to iostreams and comes pretty close to ``printf``. Boost Format +and Folly Format have the largest overheads. + +``printf+string`` is the same as ``printf`` but with extra ``<string>`` +include to measure the overhead of the latter. + +**Non-optimized build** + +============= =============== ==================== ================== +Method Compile Time, s Executable size, KiB Stripped size, KiB +============= =============== ==================== ================== +printf 2.2 33 30 +printf+string 16.0 33 30 +iostreams 28.3 56 52 +{fmt} 18.2 59 50 +Boost Format 54.1 365 303 +Folly Format 79.9 445 430 +============= =============== ==================== ================== + +``libc``, ``lib(std)c++`` and ``libfmt`` are all linked as shared libraries to +compare formatting function overhead only. Boost Format is a +header-only library so it doesn't provide any linkage options. + +Running the tests +~~~~~~~~~~~~~~~~~ + +Please refer to `Building the library`__ for the instructions on how to build +the library and run the unit tests. + +__ https://fmt.dev/latest/usage.html#building-the-library + +Benchmarks reside in a separate repository, +`format-benchmarks <https://github.com/fmtlib/format-benchmark>`_, +so to run the benchmarks you first need to clone this repository and +generate Makefiles with CMake:: + + $ git clone --recursive https://github.com/fmtlib/format-benchmark.git + $ cd format-benchmark + $ cmake . + +Then you can run the speed test:: + + $ make speed-test + +or the bloat test:: + + $ make bloat-test + +Projects using this library +--------------------------- + * `0 A.D. <https://play0ad.com/>`_: a free, open-source, cross-platform real-time strategy game - -* `AMPL/MP <https://github.com/ampl/mp>`_: + +* `AMPL/MP <https://github.com/ampl/mp>`_: an open-source library for mathematical programming * `Aseprite <https://github.com/aseprite/aseprite>`_: animated sprite editor & pixel art tool * `AvioBook <https://www.aviobook.aero/en>`_: a comprehensive aircraft - operations suite - + operations suite + * `Blizzard Battle.net <https://battle.net/>`_: an online gaming platform * `Celestia <https://celestia.space/>`_: real-time 3D visualization of space - + * `Ceph <https://ceph.com/>`_: a scalable distributed storage system - + * `ccache <https://ccache.dev/>`_: a compiler cache - + * `ClickHouse <https://github.com/ClickHouse/ClickHouse>`_: analytical database management system -* `CUAUV <http://cuauv.org/>`_: Cornell University's autonomous underwater - vehicle - +* `CUAUV <http://cuauv.org/>`_: Cornell University's autonomous underwater + vehicle + * `Drake <https://drake.mit.edu/>`_: a planning, control, and analysis toolbox for nonlinear dynamical systems (MIT) @@ -323,184 +323,184 @@ Projects using this library * `Folly <https://github.com/facebook/folly>`_: Facebook open-source library -* `HarpyWar/pvpgn <https://github.com/pvpgn/pvpgn-server>`_: - Player vs Player Gaming Network with tweaks - +* `HarpyWar/pvpgn <https://github.com/pvpgn/pvpgn-server>`_: + Player vs Player Gaming Network with tweaks + * `KBEngine <https://github.com/kbengine/kbengine>`_: an open-source MMOG server engine - + * `Keypirinha <https://keypirinha.com/>`_: a semantic launcher for Windows - + * `Kodi <https://kodi.tv/>`_ (formerly xbmc): home theater software - + * `Knuth <https://kth.cash/>`_: high-performance Bitcoin full-node - + * `Microsoft Verona <https://github.com/microsoft/verona>`_: research programming language for concurrent ownership - + * `MongoDB <https://mongodb.com/>`_: distributed document database - + * `MongoDB Smasher <https://github.com/duckie/mongo_smasher>`_: a small tool to - generate randomized datasets - + generate randomized datasets + * `OpenSpace <https://openspaceproject.com/>`_: an open-source astrovisualization framework - -* `PenUltima Online (POL) <https://www.polserver.com/>`_: + +* `PenUltima Online (POL) <https://www.polserver.com/>`_: an MMO server, compatible with most Ultima Online clients - + * `PyTorch <https://github.com/pytorch/pytorch>`_: an open-source machine learning library * `quasardb <https://www.quasardb.net/>`_: a distributed, high-performance, - associative database + associative database * `Quill <https://github.com/odygrd/quill>`_: asynchronous low-latency logging library - + * `QKW <https://github.com/ravijanjam/qkw>`_: generalizing aliasing to simplify navigation, and executing complex multi-line terminal command sequences - + * `redis-cerberus <https://github.com/HunanTV/redis-cerberus>`_: a Redis cluster - proxy - + proxy + * `redpanda <https://vectorized.io/redpanda>`_: a 10x faster Kafka® replacement for mission critical systems written in C++ * `rpclib <http://rpclib.net/>`_: a modern C++ msgpack-RPC server and client - library - + library + * `Salesforce Analytics Cloud <https://www.salesforce.com/analytics-cloud/overview/>`_: business intelligence software - + * `Scylla <https://www.scylladb.com/>`_: a Cassandra-compatible NoSQL data store - that can handle 1 million transactions per second on a single server - + that can handle 1 million transactions per second on a single server + * `Seastar <http://www.seastar-project.org/>`_: an advanced, open-source C++ - framework for high-performance server applications on modern hardware - + framework for high-performance server applications on modern hardware + * `spdlog <https://github.com/gabime/spdlog>`_: super fast C++ logging library - + * `Stellar <https://www.stellar.org/>`_: financial platform - + * `Touch Surgery <https://www.touchsurgery.com/>`_: surgery simulator - + * `TrinityCore <https://github.com/TrinityCore/TrinityCore>`_: open-source - MMORPG framework - + MMORPG framework + * `Windows Terminal <https://github.com/microsoft/terminal>`_: the new Windows terminal -`More... <https://github.com/search?q=fmtlib&type=Code>`_ - -If you are aware of other projects using this library, please let me know -by `email <mailto:victor.zverovich@gmail.com>`_ or by submitting an -`issue <https://github.com/fmtlib/fmt/issues>`_. - -Motivation ----------- - -So why yet another formatting library? - -There are plenty of methods for doing this task, from standard ones like -the printf family of function and iostreams to Boost Format and FastFormat -libraries. The reason for creating a new library is that every existing -solution that I found either had serious issues or didn't provide -all the features I needed. - -printf -~~~~~~ - -The good thing about ``printf`` is that it is pretty fast and readily available -being a part of the C standard library. The main drawback is that it -doesn't support user-defined types. ``printf`` also has safety issues although -they are somewhat mitigated with `__attribute__ ((format (printf, ...)) -<https://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html>`_ in GCC. -There is a POSIX extension that adds positional arguments required for -`i18n <https://en.wikipedia.org/wiki/Internationalization_and_localization>`_ -to ``printf`` but it is not a part of C99 and may not be available on some -platforms. - -iostreams -~~~~~~~~~ - -The main issue with iostreams is best illustrated with an example: - -.. code:: c++ - - std::cout << std::setprecision(2) << std::fixed << 1.23456 << "\n"; - -which is a lot of typing compared to printf: - -.. code:: c++ - - printf("%.2f\n", 1.23456); - -Matthew Wilson, the author of FastFormat, called this "chevron hell". iostreams -don't support positional arguments by design. - -The good part is that iostreams support user-defined types and are safe although -error handling is awkward. - -Boost Format -~~~~~~~~~~~~ - -This is a very powerful library which supports both ``printf``-like format -strings and positional arguments. Its main drawback is performance. According to +`More... <https://github.com/search?q=fmtlib&type=Code>`_ + +If you are aware of other projects using this library, please let me know +by `email <mailto:victor.zverovich@gmail.com>`_ or by submitting an +`issue <https://github.com/fmtlib/fmt/issues>`_. + +Motivation +---------- + +So why yet another formatting library? + +There are plenty of methods for doing this task, from standard ones like +the printf family of function and iostreams to Boost Format and FastFormat +libraries. The reason for creating a new library is that every existing +solution that I found either had serious issues or didn't provide +all the features I needed. + +printf +~~~~~~ + +The good thing about ``printf`` is that it is pretty fast and readily available +being a part of the C standard library. The main drawback is that it +doesn't support user-defined types. ``printf`` also has safety issues although +they are somewhat mitigated with `__attribute__ ((format (printf, ...)) +<https://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html>`_ in GCC. +There is a POSIX extension that adds positional arguments required for +`i18n <https://en.wikipedia.org/wiki/Internationalization_and_localization>`_ +to ``printf`` but it is not a part of C99 and may not be available on some +platforms. + +iostreams +~~~~~~~~~ + +The main issue with iostreams is best illustrated with an example: + +.. code:: c++ + + std::cout << std::setprecision(2) << std::fixed << 1.23456 << "\n"; + +which is a lot of typing compared to printf: + +.. code:: c++ + + printf("%.2f\n", 1.23456); + +Matthew Wilson, the author of FastFormat, called this "chevron hell". iostreams +don't support positional arguments by design. + +The good part is that iostreams support user-defined types and are safe although +error handling is awkward. + +Boost Format +~~~~~~~~~~~~ + +This is a very powerful library which supports both ``printf``-like format +strings and positional arguments. Its main drawback is performance. According to various, benchmarks it is much slower than other methods considered here. Boost -Format also has excessive build times and severe code bloat issues (see -`Benchmarks`_). - -FastFormat -~~~~~~~~~~ - +Format also has excessive build times and severe code bloat issues (see +`Benchmarks`_). + +FastFormat +~~~~~~~~~~ + This is an interesting library which is fast, safe and has positional arguments. However, it has significant limitations, citing its author: - - Three features that have no hope of being accommodated within the - current design are: - - * Leading zeros (or any other non-space padding) - * Octal/hexadecimal encoding - * Runtime width/alignment specification - + + Three features that have no hope of being accommodated within the + current design are: + + * Leading zeros (or any other non-space padding) + * Octal/hexadecimal encoding + * Runtime width/alignment specification + It is also quite big and has a heavy dependency, STLSoft, which might be too restrictive for using it in some projects. - -Boost Spirit.Karma -~~~~~~~~~~~~~~~~~~ - -This is not really a formatting library but I decided to include it here for -completeness. As iostreams, it suffers from the problem of mixing verbatim text -with arguments. The library is pretty fast, but slower on integer formatting + +Boost Spirit.Karma +~~~~~~~~~~~~~~~~~~ + +This is not really a formatting library but I decided to include it here for +completeness. As iostreams, it suffers from the problem of mixing verbatim text +with arguments. The library is pretty fast, but slower on integer formatting than ``fmt::format_to`` with format string compilation on Karma's own benchmark, see `Converting a hundred million integers to strings per second <http://www.zverovich.net/2020/06/13/fast-int-to-string-revisited.html>`_. - -License -------- - -{fmt} is distributed under the MIT `license -<https://github.com/fmtlib/fmt/blob/master/LICENSE.rst>`_. - + +License +------- + +{fmt} is distributed under the MIT `license +<https://github.com/fmtlib/fmt/blob/master/LICENSE.rst>`_. + Documentation License --------------------- The `Format String Syntax <https://fmt.dev/latest/syntax.html>`_ -section in the documentation is based on the one from Python `string module +section in the documentation is based on the one from Python `string module documentation <https://docs.python.org/3/library/string.html#module-string>`_. For this reason the documentation is distributed under the Python Software Foundation license available in `doc/python-license.txt -<https://raw.github.com/fmtlib/fmt/master/doc/python-license.txt>`_. +<https://raw.github.com/fmtlib/fmt/master/doc/python-license.txt>`_. It only applies if you distribute the documentation of {fmt}. - + Maintainers ----------- - -The {fmt} library is maintained by Victor Zverovich (`vitaut -<https://github.com/vitaut>`_) and Jonathan Müller (`foonathan -<https://github.com/foonathan>`_) with contributions from many other people. -See `Contributors <https://github.com/fmtlib/fmt/graphs/contributors>`_ and -`Releases <https://github.com/fmtlib/fmt/releases>`_ for some of the names. -Let us know if your contribution is not listed or mentioned incorrectly and -we'll make it right. + +The {fmt} library is maintained by Victor Zverovich (`vitaut +<https://github.com/vitaut>`_) and Jonathan Müller (`foonathan +<https://github.com/foonathan>`_) with contributions from many other people. +See `Contributors <https://github.com/fmtlib/fmt/graphs/contributors>`_ and +`Releases <https://github.com/fmtlib/fmt/releases>`_ for some of the names. +Let us know if your contribution is not listed or mentioned incorrectly and +we'll make it right. diff --git a/contrib/libs/fmt/include/fmt/chrono.h b/contrib/libs/fmt/include/fmt/chrono.h index fc279504f3..1a3b8d5e5c 100644 --- a/contrib/libs/fmt/include/fmt/chrono.h +++ b/contrib/libs/fmt/include/fmt/chrono.h @@ -1,371 +1,371 @@ -// Formatting library for C++ - chrono support -// -// Copyright (c) 2012 - present, Victor Zverovich -// All rights reserved. -// -// For the license information refer to format.h. - -#ifndef FMT_CHRONO_H_ -#define FMT_CHRONO_H_ - -#include <chrono> -#include <ctime> -#include <locale> -#include <sstream> - -#include "format.h" -#include "locale.h" - -FMT_BEGIN_NAMESPACE - -// Enable safe chrono durations, unless explicitly disabled. -#ifndef FMT_SAFE_DURATION_CAST -# define FMT_SAFE_DURATION_CAST 1 -#endif -#if FMT_SAFE_DURATION_CAST - -// For conversion between std::chrono::durations without undefined -// behaviour or erroneous results. -// This is a stripped down version of duration_cast, for inclusion in fmt. -// See https://github.com/pauldreik/safe_duration_cast -// -// Copyright Paul Dreik 2019 -namespace safe_duration_cast { - -template <typename To, typename From, - FMT_ENABLE_IF(!std::is_same<From, To>::value && - std::numeric_limits<From>::is_signed == - std::numeric_limits<To>::is_signed)> -FMT_CONSTEXPR To lossless_integral_conversion(const From from, int& ec) { - ec = 0; - using F = std::numeric_limits<From>; - using T = std::numeric_limits<To>; - static_assert(F::is_integer, "From must be integral"); - static_assert(T::is_integer, "To must be integral"); - - // A and B are both signed, or both unsigned. - if (F::digits <= T::digits) { - // From fits in To without any problem. - } else { - // From does not always fit in To, resort to a dynamic check. +// Formatting library for C++ - chrono support +// +// Copyright (c) 2012 - present, Victor Zverovich +// All rights reserved. +// +// For the license information refer to format.h. + +#ifndef FMT_CHRONO_H_ +#define FMT_CHRONO_H_ + +#include <chrono> +#include <ctime> +#include <locale> +#include <sstream> + +#include "format.h" +#include "locale.h" + +FMT_BEGIN_NAMESPACE + +// Enable safe chrono durations, unless explicitly disabled. +#ifndef FMT_SAFE_DURATION_CAST +# define FMT_SAFE_DURATION_CAST 1 +#endif +#if FMT_SAFE_DURATION_CAST + +// For conversion between std::chrono::durations without undefined +// behaviour or erroneous results. +// This is a stripped down version of duration_cast, for inclusion in fmt. +// See https://github.com/pauldreik/safe_duration_cast +// +// Copyright Paul Dreik 2019 +namespace safe_duration_cast { + +template <typename To, typename From, + FMT_ENABLE_IF(!std::is_same<From, To>::value && + std::numeric_limits<From>::is_signed == + std::numeric_limits<To>::is_signed)> +FMT_CONSTEXPR To lossless_integral_conversion(const From from, int& ec) { + ec = 0; + using F = std::numeric_limits<From>; + using T = std::numeric_limits<To>; + static_assert(F::is_integer, "From must be integral"); + static_assert(T::is_integer, "To must be integral"); + + // A and B are both signed, or both unsigned. + if (F::digits <= T::digits) { + // From fits in To without any problem. + } else { + // From does not always fit in To, resort to a dynamic check. if (from < (T::min)() || from > (T::max)()) { - // outside range. - ec = 1; - return {}; - } - } - return static_cast<To>(from); -} - -/** - * converts From to To, without loss. If the dynamic value of from - * can't be converted to To without loss, ec is set. - */ -template <typename To, typename From, - FMT_ENABLE_IF(!std::is_same<From, To>::value && - std::numeric_limits<From>::is_signed != - std::numeric_limits<To>::is_signed)> -FMT_CONSTEXPR To lossless_integral_conversion(const From from, int& ec) { - ec = 0; - using F = std::numeric_limits<From>; - using T = std::numeric_limits<To>; - static_assert(F::is_integer, "From must be integral"); - static_assert(T::is_integer, "To must be integral"); - + // outside range. + ec = 1; + return {}; + } + } + return static_cast<To>(from); +} + +/** + * converts From to To, without loss. If the dynamic value of from + * can't be converted to To without loss, ec is set. + */ +template <typename To, typename From, + FMT_ENABLE_IF(!std::is_same<From, To>::value && + std::numeric_limits<From>::is_signed != + std::numeric_limits<To>::is_signed)> +FMT_CONSTEXPR To lossless_integral_conversion(const From from, int& ec) { + ec = 0; + using F = std::numeric_limits<From>; + using T = std::numeric_limits<To>; + static_assert(F::is_integer, "From must be integral"); + static_assert(T::is_integer, "To must be integral"); + if (detail::const_check(F::is_signed && !T::is_signed)) { - // From may be negative, not allowed! + // From may be negative, not allowed! if (fmt::detail::is_negative(from)) { - ec = 1; - return {}; - } - // From is positive. Can it always fit in To? + ec = 1; + return {}; + } + // From is positive. Can it always fit in To? if (F::digits > T::digits && from > static_cast<From>(detail::max_value<To>())) { ec = 1; return {}; - } - } - + } + } + if (!F::is_signed && T::is_signed && F::digits >= T::digits && from > static_cast<From>(detail::max_value<To>())) { ec = 1; return {}; - } + } return static_cast<To>(from); // Lossless conversion. } - -template <typename To, typename From, - FMT_ENABLE_IF(std::is_same<From, To>::value)> -FMT_CONSTEXPR To lossless_integral_conversion(const From from, int& ec) { - ec = 0; - return from; -} // function - -// clang-format off -/** - * converts From to To if possible, otherwise ec is set. - * - * input | output - * ---------------------------------|--------------- - * NaN | NaN - * Inf | Inf - * normal, fits in output | converted (possibly lossy) - * normal, does not fit in output | ec is set - * subnormal | best effort - * -Inf | -Inf - */ -// clang-format on -template <typename To, typename From, - FMT_ENABLE_IF(!std::is_same<From, To>::value)> -FMT_CONSTEXPR To safe_float_conversion(const From from, int& ec) { - ec = 0; - using T = std::numeric_limits<To>; - static_assert(std::is_floating_point<From>::value, "From must be floating"); - static_assert(std::is_floating_point<To>::value, "To must be floating"); - - // catch the only happy case - if (std::isfinite(from)) { + +template <typename To, typename From, + FMT_ENABLE_IF(std::is_same<From, To>::value)> +FMT_CONSTEXPR To lossless_integral_conversion(const From from, int& ec) { + ec = 0; + return from; +} // function + +// clang-format off +/** + * converts From to To if possible, otherwise ec is set. + * + * input | output + * ---------------------------------|--------------- + * NaN | NaN + * Inf | Inf + * normal, fits in output | converted (possibly lossy) + * normal, does not fit in output | ec is set + * subnormal | best effort + * -Inf | -Inf + */ +// clang-format on +template <typename To, typename From, + FMT_ENABLE_IF(!std::is_same<From, To>::value)> +FMT_CONSTEXPR To safe_float_conversion(const From from, int& ec) { + ec = 0; + using T = std::numeric_limits<To>; + static_assert(std::is_floating_point<From>::value, "From must be floating"); + static_assert(std::is_floating_point<To>::value, "To must be floating"); + + // catch the only happy case + if (std::isfinite(from)) { if (from >= T::lowest() && from <= (T::max)()) { - return static_cast<To>(from); - } - // not within range. - ec = 1; - return {}; - } - - // nan and inf will be preserved - return static_cast<To>(from); -} // function - -template <typename To, typename From, - FMT_ENABLE_IF(std::is_same<From, To>::value)> -FMT_CONSTEXPR To safe_float_conversion(const From from, int& ec) { - ec = 0; - static_assert(std::is_floating_point<From>::value, "From must be floating"); - return from; -} - -/** - * safe duration cast between integral durations - */ -template <typename To, typename FromRep, typename FromPeriod, - FMT_ENABLE_IF(std::is_integral<FromRep>::value), - FMT_ENABLE_IF(std::is_integral<typename To::rep>::value)> -To safe_duration_cast(std::chrono::duration<FromRep, FromPeriod> from, - int& ec) { - using From = std::chrono::duration<FromRep, FromPeriod>; - ec = 0; - // the basic idea is that we need to convert from count() in the from type - // to count() in the To type, by multiplying it with this: - struct Factor - : std::ratio_divide<typename From::period, typename To::period> {}; - - static_assert(Factor::num > 0, "num must be positive"); - static_assert(Factor::den > 0, "den must be positive"); - - // the conversion is like this: multiply from.count() with Factor::num - // /Factor::den and convert it to To::rep, all this without - // overflow/underflow. let's start by finding a suitable type that can hold - // both To, From and Factor::num - using IntermediateRep = - typename std::common_type<typename From::rep, typename To::rep, - decltype(Factor::num)>::type; - - // safe conversion to IntermediateRep - IntermediateRep count = - lossless_integral_conversion<IntermediateRep>(from.count(), ec); + return static_cast<To>(from); + } + // not within range. + ec = 1; + return {}; + } + + // nan and inf will be preserved + return static_cast<To>(from); +} // function + +template <typename To, typename From, + FMT_ENABLE_IF(std::is_same<From, To>::value)> +FMT_CONSTEXPR To safe_float_conversion(const From from, int& ec) { + ec = 0; + static_assert(std::is_floating_point<From>::value, "From must be floating"); + return from; +} + +/** + * safe duration cast between integral durations + */ +template <typename To, typename FromRep, typename FromPeriod, + FMT_ENABLE_IF(std::is_integral<FromRep>::value), + FMT_ENABLE_IF(std::is_integral<typename To::rep>::value)> +To safe_duration_cast(std::chrono::duration<FromRep, FromPeriod> from, + int& ec) { + using From = std::chrono::duration<FromRep, FromPeriod>; + ec = 0; + // the basic idea is that we need to convert from count() in the from type + // to count() in the To type, by multiplying it with this: + struct Factor + : std::ratio_divide<typename From::period, typename To::period> {}; + + static_assert(Factor::num > 0, "num must be positive"); + static_assert(Factor::den > 0, "den must be positive"); + + // the conversion is like this: multiply from.count() with Factor::num + // /Factor::den and convert it to To::rep, all this without + // overflow/underflow. let's start by finding a suitable type that can hold + // both To, From and Factor::num + using IntermediateRep = + typename std::common_type<typename From::rep, typename To::rep, + decltype(Factor::num)>::type; + + // safe conversion to IntermediateRep + IntermediateRep count = + lossless_integral_conversion<IntermediateRep>(from.count(), ec); if (ec) return {}; - // multiply with Factor::num without overflow or underflow + // multiply with Factor::num without overflow or underflow if (detail::const_check(Factor::num != 1)) { const auto max1 = detail::max_value<IntermediateRep>() / Factor::num; - if (count > max1) { - ec = 1; - return {}; - } + if (count > max1) { + ec = 1; + return {}; + } const auto min1 = (std::numeric_limits<IntermediateRep>::min)() / Factor::num; - if (count < min1) { - ec = 1; - return {}; - } - count *= Factor::num; - } - + if (count < min1) { + ec = 1; + return {}; + } + count *= Factor::num; + } + if (detail::const_check(Factor::den != 1)) count /= Factor::den; auto tocount = lossless_integral_conversion<typename To::rep>(count, ec); return ec ? To() : To(tocount); -} - -/** - * safe duration_cast between floating point durations - */ -template <typename To, typename FromRep, typename FromPeriod, - FMT_ENABLE_IF(std::is_floating_point<FromRep>::value), - FMT_ENABLE_IF(std::is_floating_point<typename To::rep>::value)> -To safe_duration_cast(std::chrono::duration<FromRep, FromPeriod> from, - int& ec) { - using From = std::chrono::duration<FromRep, FromPeriod>; - ec = 0; - if (std::isnan(from.count())) { - // nan in, gives nan out. easy. - return To{std::numeric_limits<typename To::rep>::quiet_NaN()}; - } - // maybe we should also check if from is denormal, and decide what to do about - // it. - - // +-inf should be preserved. - if (std::isinf(from.count())) { - return To{from.count()}; - } - - // the basic idea is that we need to convert from count() in the from type - // to count() in the To type, by multiplying it with this: - struct Factor - : std::ratio_divide<typename From::period, typename To::period> {}; - - static_assert(Factor::num > 0, "num must be positive"); - static_assert(Factor::den > 0, "den must be positive"); - - // the conversion is like this: multiply from.count() with Factor::num - // /Factor::den and convert it to To::rep, all this without - // overflow/underflow. let's start by finding a suitable type that can hold - // both To, From and Factor::num - using IntermediateRep = - typename std::common_type<typename From::rep, typename To::rep, - decltype(Factor::num)>::type; - - // force conversion of From::rep -> IntermediateRep to be safe, - // even if it will never happen be narrowing in this context. - IntermediateRep count = - safe_float_conversion<IntermediateRep>(from.count(), ec); - if (ec) { - return {}; - } - - // multiply with Factor::num without overflow or underflow - if (Factor::num != 1) { +} + +/** + * safe duration_cast between floating point durations + */ +template <typename To, typename FromRep, typename FromPeriod, + FMT_ENABLE_IF(std::is_floating_point<FromRep>::value), + FMT_ENABLE_IF(std::is_floating_point<typename To::rep>::value)> +To safe_duration_cast(std::chrono::duration<FromRep, FromPeriod> from, + int& ec) { + using From = std::chrono::duration<FromRep, FromPeriod>; + ec = 0; + if (std::isnan(from.count())) { + // nan in, gives nan out. easy. + return To{std::numeric_limits<typename To::rep>::quiet_NaN()}; + } + // maybe we should also check if from is denormal, and decide what to do about + // it. + + // +-inf should be preserved. + if (std::isinf(from.count())) { + return To{from.count()}; + } + + // the basic idea is that we need to convert from count() in the from type + // to count() in the To type, by multiplying it with this: + struct Factor + : std::ratio_divide<typename From::period, typename To::period> {}; + + static_assert(Factor::num > 0, "num must be positive"); + static_assert(Factor::den > 0, "den must be positive"); + + // the conversion is like this: multiply from.count() with Factor::num + // /Factor::den and convert it to To::rep, all this without + // overflow/underflow. let's start by finding a suitable type that can hold + // both To, From and Factor::num + using IntermediateRep = + typename std::common_type<typename From::rep, typename To::rep, + decltype(Factor::num)>::type; + + // force conversion of From::rep -> IntermediateRep to be safe, + // even if it will never happen be narrowing in this context. + IntermediateRep count = + safe_float_conversion<IntermediateRep>(from.count(), ec); + if (ec) { + return {}; + } + + // multiply with Factor::num without overflow or underflow + if (Factor::num != 1) { constexpr auto max1 = detail::max_value<IntermediateRep>() / - static_cast<IntermediateRep>(Factor::num); - if (count > max1) { - ec = 1; - return {}; - } - constexpr auto min1 = std::numeric_limits<IntermediateRep>::lowest() / - static_cast<IntermediateRep>(Factor::num); - if (count < min1) { - ec = 1; - return {}; - } - count *= static_cast<IntermediateRep>(Factor::num); - } - - // this can't go wrong, right? den>0 is checked earlier. - if (Factor::den != 1) { - using common_t = typename std::common_type<IntermediateRep, intmax_t>::type; - count /= static_cast<common_t>(Factor::den); - } - - // convert to the to type, safely - using ToRep = typename To::rep; - - const ToRep tocount = safe_float_conversion<ToRep>(count, ec); - if (ec) { - return {}; - } - return To{tocount}; -} -} // namespace safe_duration_cast -#endif - -// Prevents expansion of a preceding token as a function-style macro. -// Usage: f FMT_NOMACRO() -#define FMT_NOMACRO - + static_cast<IntermediateRep>(Factor::num); + if (count > max1) { + ec = 1; + return {}; + } + constexpr auto min1 = std::numeric_limits<IntermediateRep>::lowest() / + static_cast<IntermediateRep>(Factor::num); + if (count < min1) { + ec = 1; + return {}; + } + count *= static_cast<IntermediateRep>(Factor::num); + } + + // this can't go wrong, right? den>0 is checked earlier. + if (Factor::den != 1) { + using common_t = typename std::common_type<IntermediateRep, intmax_t>::type; + count /= static_cast<common_t>(Factor::den); + } + + // convert to the to type, safely + using ToRep = typename To::rep; + + const ToRep tocount = safe_float_conversion<ToRep>(count, ec); + if (ec) { + return {}; + } + return To{tocount}; +} +} // namespace safe_duration_cast +#endif + +// Prevents expansion of a preceding token as a function-style macro. +// Usage: f FMT_NOMACRO() +#define FMT_NOMACRO + namespace detail { -inline null<> localtime_r FMT_NOMACRO(...) { return null<>(); } -inline null<> localtime_s(...) { return null<>(); } -inline null<> gmtime_r(...) { return null<>(); } -inline null<> gmtime_s(...) { return null<>(); } +inline null<> localtime_r FMT_NOMACRO(...) { return null<>(); } +inline null<> localtime_s(...) { return null<>(); } +inline null<> gmtime_r(...) { return null<>(); } +inline null<> gmtime_s(...) { return null<>(); } } // namespace detail - -// Thread-safe replacement for std::localtime -inline std::tm localtime(std::time_t time) { - struct dispatcher { - std::time_t time_; - std::tm tm_; - - dispatcher(std::time_t t) : time_(t) {} - - bool run() { + +// Thread-safe replacement for std::localtime +inline std::tm localtime(std::time_t time) { + struct dispatcher { + std::time_t time_; + std::tm tm_; + + dispatcher(std::time_t t) : time_(t) {} + + bool run() { using namespace fmt::detail; - return handle(localtime_r(&time_, &tm_)); - } - - bool handle(std::tm* tm) { return tm != nullptr; } - + return handle(localtime_r(&time_, &tm_)); + } + + bool handle(std::tm* tm) { return tm != nullptr; } + bool handle(detail::null<>) { using namespace fmt::detail; - return fallback(localtime_s(&tm_, &time_)); - } - - bool fallback(int res) { return res == 0; } - -#if !FMT_MSC_VER + return fallback(localtime_s(&tm_, &time_)); + } + + bool fallback(int res) { return res == 0; } + +#if !FMT_MSC_VER bool fallback(detail::null<>) { using namespace fmt::detail; - std::tm* tm = std::localtime(&time_); - if (tm) tm_ = *tm; - return tm != nullptr; - } -#endif - }; - dispatcher lt(time); - // Too big time values may be unsupported. - if (!lt.run()) FMT_THROW(format_error("time_t value out of range")); - return lt.tm_; -} - + std::tm* tm = std::localtime(&time_); + if (tm) tm_ = *tm; + return tm != nullptr; + } +#endif + }; + dispatcher lt(time); + // Too big time values may be unsupported. + if (!lt.run()) FMT_THROW(format_error("time_t value out of range")); + return lt.tm_; +} + inline std::tm localtime( std::chrono::time_point<std::chrono::system_clock> time_point) { return localtime(std::chrono::system_clock::to_time_t(time_point)); } -// Thread-safe replacement for std::gmtime -inline std::tm gmtime(std::time_t time) { - struct dispatcher { - std::time_t time_; - std::tm tm_; - - dispatcher(std::time_t t) : time_(t) {} - - bool run() { +// Thread-safe replacement for std::gmtime +inline std::tm gmtime(std::time_t time) { + struct dispatcher { + std::time_t time_; + std::tm tm_; + + dispatcher(std::time_t t) : time_(t) {} + + bool run() { using namespace fmt::detail; - return handle(gmtime_r(&time_, &tm_)); - } - - bool handle(std::tm* tm) { return tm != nullptr; } - + return handle(gmtime_r(&time_, &tm_)); + } + + bool handle(std::tm* tm) { return tm != nullptr; } + bool handle(detail::null<>) { using namespace fmt::detail; - return fallback(gmtime_s(&tm_, &time_)); - } - - bool fallback(int res) { return res == 0; } - -#if !FMT_MSC_VER + return fallback(gmtime_s(&tm_, &time_)); + } + + bool fallback(int res) { return res == 0; } + +#if !FMT_MSC_VER bool fallback(detail::null<>) { - std::tm* tm = std::gmtime(&time_); - if (tm) tm_ = *tm; - return tm != nullptr; - } -#endif - }; - dispatcher gt(time); - // Too big time values may be unsupported. - if (!gt.run()) FMT_THROW(format_error("time_t value out of range")); - return gt.tm_; -} - + std::tm* tm = std::gmtime(&time_); + if (tm) tm_ = *tm; + return tm != nullptr; + } +#endif + }; + dispatcher gt(time); + // Too big time values may be unsupported. + if (!gt.run()) FMT_THROW(format_error("time_t value out of range")); + return gt.tm_; +} + inline std::tm gmtime( std::chrono::time_point<std::chrono::system_clock> time_point) { return gmtime(std::chrono::system_clock::to_time_t(time_point)); @@ -374,15 +374,15 @@ inline std::tm gmtime( namespace detail { inline size_t strftime(char* str, size_t count, const char* format, const std::tm* time) { - return std::strftime(str, count, format, time); -} - + return std::strftime(str, count, format, time); +} + inline size_t strftime(wchar_t* str, size_t count, const wchar_t* format, const std::tm* time) { - return std::wcsftime(str, count, format, time); -} + return std::wcsftime(str, count, format, time); +} } // namespace detail - + template <typename Char> struct formatter<std::chrono::time_point<std::chrono::system_clock>, Char> : formatter<std::tm, Char> { @@ -394,380 +394,380 @@ struct formatter<std::chrono::time_point<std::chrono::system_clock>, Char> } }; -template <typename Char> struct formatter<std::tm, Char> { - template <typename ParseContext> - auto parse(ParseContext& ctx) -> decltype(ctx.begin()) { - auto it = ctx.begin(); - if (it != ctx.end() && *it == ':') ++it; - auto end = it; - while (end != ctx.end() && *end != '}') ++end; +template <typename Char> struct formatter<std::tm, Char> { + template <typename ParseContext> + auto parse(ParseContext& ctx) -> decltype(ctx.begin()) { + auto it = ctx.begin(); + if (it != ctx.end() && *it == ':') ++it; + auto end = it; + while (end != ctx.end() && *end != '}') ++end; tm_format.reserve(detail::to_unsigned(end - it + 1)); - tm_format.append(it, end); - tm_format.push_back('\0'); - return end; - } - - template <typename FormatContext> - auto format(const std::tm& tm, FormatContext& ctx) -> decltype(ctx.out()) { - basic_memory_buffer<Char> buf; + tm_format.append(it, end); + tm_format.push_back('\0'); + return end; + } + + template <typename FormatContext> + auto format(const std::tm& tm, FormatContext& ctx) -> decltype(ctx.out()) { + basic_memory_buffer<Char> buf; size_t start = buf.size(); - for (;;) { + for (;;) { size_t size = buf.capacity() - start; size_t count = detail::strftime(&buf[start], size, &tm_format[0], &tm); - if (count != 0) { - buf.resize(start + count); - break; - } - if (size >= tm_format.size() * 256) { - // If the buffer is 256 times larger than the format string, assume - // that `strftime` gives an empty result. There doesn't seem to be a - // better way to distinguish the two cases: - // https://github.com/fmtlib/fmt/issues/367 - break; - } + if (count != 0) { + buf.resize(start + count); + break; + } + if (size >= tm_format.size() * 256) { + // If the buffer is 256 times larger than the format string, assume + // that `strftime` gives an empty result. There doesn't seem to be a + // better way to distinguish the two cases: + // https://github.com/fmtlib/fmt/issues/367 + break; + } const size_t MIN_GROWTH = 10; - buf.reserve(buf.capacity() + (size > MIN_GROWTH ? size : MIN_GROWTH)); - } - return std::copy(buf.begin(), buf.end(), ctx.out()); - } - - basic_memory_buffer<Char> tm_format; -}; - + buf.reserve(buf.capacity() + (size > MIN_GROWTH ? size : MIN_GROWTH)); + } + return std::copy(buf.begin(), buf.end(), ctx.out()); + } + + basic_memory_buffer<Char> tm_format; +}; + namespace detail { -template <typename Period> FMT_CONSTEXPR const char* get_units() { - return nullptr; -} -template <> FMT_CONSTEXPR const char* get_units<std::atto>() { return "as"; } -template <> FMT_CONSTEXPR const char* get_units<std::femto>() { return "fs"; } -template <> FMT_CONSTEXPR const char* get_units<std::pico>() { return "ps"; } -template <> FMT_CONSTEXPR const char* get_units<std::nano>() { return "ns"; } -template <> FMT_CONSTEXPR const char* get_units<std::micro>() { return "µs"; } -template <> FMT_CONSTEXPR const char* get_units<std::milli>() { return "ms"; } -template <> FMT_CONSTEXPR const char* get_units<std::centi>() { return "cs"; } -template <> FMT_CONSTEXPR const char* get_units<std::deci>() { return "ds"; } -template <> FMT_CONSTEXPR const char* get_units<std::ratio<1>>() { return "s"; } -template <> FMT_CONSTEXPR const char* get_units<std::deca>() { return "das"; } -template <> FMT_CONSTEXPR const char* get_units<std::hecto>() { return "hs"; } -template <> FMT_CONSTEXPR const char* get_units<std::kilo>() { return "ks"; } -template <> FMT_CONSTEXPR const char* get_units<std::mega>() { return "Ms"; } -template <> FMT_CONSTEXPR const char* get_units<std::giga>() { return "Gs"; } -template <> FMT_CONSTEXPR const char* get_units<std::tera>() { return "Ts"; } -template <> FMT_CONSTEXPR const char* get_units<std::peta>() { return "Ps"; } -template <> FMT_CONSTEXPR const char* get_units<std::exa>() { return "Es"; } -template <> FMT_CONSTEXPR const char* get_units<std::ratio<60>>() { - return "m"; -} -template <> FMT_CONSTEXPR const char* get_units<std::ratio<3600>>() { - return "h"; -} - -enum class numeric_system { - standard, - // Alternative numeric system, e.g. 十二 instead of 12 in ja_JP locale. - alternative -}; - -// Parses a put_time-like format string and invokes handler actions. -template <typename Char, typename Handler> -FMT_CONSTEXPR const Char* parse_chrono_format(const Char* begin, - const Char* end, - Handler&& handler) { - auto ptr = begin; - while (ptr != end) { - auto c = *ptr; - if (c == '}') break; - if (c != '%') { - ++ptr; - continue; - } - if (begin != ptr) handler.on_text(begin, ptr); - ++ptr; // consume '%' - if (ptr == end) FMT_THROW(format_error("invalid format")); - c = *ptr++; - switch (c) { - case '%': - handler.on_text(ptr - 1, ptr); - break; - case 'n': { - const Char newline[] = {'\n'}; - handler.on_text(newline, newline + 1); - break; - } - case 't': { - const Char tab[] = {'\t'}; - handler.on_text(tab, tab + 1); - break; - } - // Day of the week: - case 'a': - handler.on_abbr_weekday(); - break; - case 'A': - handler.on_full_weekday(); - break; - case 'w': - handler.on_dec0_weekday(numeric_system::standard); - break; - case 'u': - handler.on_dec1_weekday(numeric_system::standard); - break; - // Month: - case 'b': - handler.on_abbr_month(); - break; - case 'B': - handler.on_full_month(); - break; - // Hour, minute, second: - case 'H': - handler.on_24_hour(numeric_system::standard); - break; - case 'I': - handler.on_12_hour(numeric_system::standard); - break; - case 'M': - handler.on_minute(numeric_system::standard); - break; - case 'S': - handler.on_second(numeric_system::standard); - break; - // Other: - case 'c': - handler.on_datetime(numeric_system::standard); - break; - case 'x': - handler.on_loc_date(numeric_system::standard); - break; - case 'X': - handler.on_loc_time(numeric_system::standard); - break; - case 'D': - handler.on_us_date(); - break; - case 'F': - handler.on_iso_date(); - break; - case 'r': - handler.on_12_hour_time(); - break; - case 'R': - handler.on_24_hour_time(); - break; - case 'T': - handler.on_iso_time(); - break; - case 'p': - handler.on_am_pm(); - break; - case 'Q': - handler.on_duration_value(); - break; - case 'q': - handler.on_duration_unit(); - break; - case 'z': - handler.on_utc_offset(); - break; - case 'Z': - handler.on_tz_name(); - break; - // Alternative representation: - case 'E': { - if (ptr == end) FMT_THROW(format_error("invalid format")); - c = *ptr++; - switch (c) { - case 'c': - handler.on_datetime(numeric_system::alternative); - break; - case 'x': - handler.on_loc_date(numeric_system::alternative); - break; - case 'X': - handler.on_loc_time(numeric_system::alternative); - break; - default: - FMT_THROW(format_error("invalid format")); - } - break; - } - case 'O': - if (ptr == end) FMT_THROW(format_error("invalid format")); - c = *ptr++; - switch (c) { - case 'w': - handler.on_dec0_weekday(numeric_system::alternative); - break; - case 'u': - handler.on_dec1_weekday(numeric_system::alternative); - break; - case 'H': - handler.on_24_hour(numeric_system::alternative); - break; - case 'I': - handler.on_12_hour(numeric_system::alternative); - break; - case 'M': - handler.on_minute(numeric_system::alternative); - break; - case 'S': - handler.on_second(numeric_system::alternative); - break; - default: - FMT_THROW(format_error("invalid format")); - } - break; - default: - FMT_THROW(format_error("invalid format")); - } - begin = ptr; - } - if (begin != ptr) handler.on_text(begin, ptr); - return ptr; -} - -struct chrono_format_checker { - FMT_NORETURN void report_no_date() { FMT_THROW(format_error("no date")); } - - template <typename Char> void on_text(const Char*, const Char*) {} - FMT_NORETURN void on_abbr_weekday() { report_no_date(); } - FMT_NORETURN void on_full_weekday() { report_no_date(); } - FMT_NORETURN void on_dec0_weekday(numeric_system) { report_no_date(); } - FMT_NORETURN void on_dec1_weekday(numeric_system) { report_no_date(); } - FMT_NORETURN void on_abbr_month() { report_no_date(); } - FMT_NORETURN void on_full_month() { report_no_date(); } - void on_24_hour(numeric_system) {} - void on_12_hour(numeric_system) {} - void on_minute(numeric_system) {} - void on_second(numeric_system) {} - FMT_NORETURN void on_datetime(numeric_system) { report_no_date(); } - FMT_NORETURN void on_loc_date(numeric_system) { report_no_date(); } - FMT_NORETURN void on_loc_time(numeric_system) { report_no_date(); } - FMT_NORETURN void on_us_date() { report_no_date(); } - FMT_NORETURN void on_iso_date() { report_no_date(); } - void on_12_hour_time() {} - void on_24_hour_time() {} - void on_iso_time() {} - void on_am_pm() {} - void on_duration_value() {} - void on_duration_unit() {} - FMT_NORETURN void on_utc_offset() { report_no_date(); } - FMT_NORETURN void on_tz_name() { report_no_date(); } -}; - -template <typename T, FMT_ENABLE_IF(std::is_integral<T>::value)> -inline bool isnan(T) { - return false; -} -template <typename T, FMT_ENABLE_IF(std::is_floating_point<T>::value)> -inline bool isnan(T value) { - return std::isnan(value); -} - -template <typename T, FMT_ENABLE_IF(std::is_integral<T>::value)> -inline bool isfinite(T) { - return true; -} -template <typename T, FMT_ENABLE_IF(std::is_floating_point<T>::value)> -inline bool isfinite(T value) { - return std::isfinite(value); -} - -// Converts value to int and checks that it's in the range [0, upper). -template <typename T, FMT_ENABLE_IF(std::is_integral<T>::value)> -inline int to_nonnegative_int(T value, int upper) { - FMT_ASSERT(value >= 0 && value <= upper, "invalid value"); - (void)upper; - return static_cast<int>(value); -} -template <typename T, FMT_ENABLE_IF(!std::is_integral<T>::value)> -inline int to_nonnegative_int(T value, int upper) { - FMT_ASSERT( - std::isnan(value) || (value >= 0 && value <= static_cast<T>(upper)), - "invalid value"); - (void)upper; - return static_cast<int>(value); -} - -template <typename T, FMT_ENABLE_IF(std::is_integral<T>::value)> -inline T mod(T x, int y) { - return x % static_cast<T>(y); -} -template <typename T, FMT_ENABLE_IF(std::is_floating_point<T>::value)> -inline T mod(T x, int y) { - return std::fmod(x, static_cast<T>(y)); -} - -// If T is an integral type, maps T to its unsigned counterpart, otherwise -// leaves it unchanged (unlike std::make_unsigned). -template <typename T, bool INTEGRAL = std::is_integral<T>::value> -struct make_unsigned_or_unchanged { - using type = T; -}; - -template <typename T> struct make_unsigned_or_unchanged<T, true> { - using type = typename std::make_unsigned<T>::type; -}; - -#if FMT_SAFE_DURATION_CAST -// throwing version of safe_duration_cast -template <typename To, typename FromRep, typename FromPeriod> -To fmt_safe_duration_cast(std::chrono::duration<FromRep, FromPeriod> from) { - int ec; - To to = safe_duration_cast::safe_duration_cast<To>(from, ec); - if (ec) FMT_THROW(format_error("cannot format duration")); - return to; -} -#endif - -template <typename Rep, typename Period, - FMT_ENABLE_IF(std::is_integral<Rep>::value)> -inline std::chrono::duration<Rep, std::milli> get_milliseconds( - std::chrono::duration<Rep, Period> d) { - // this may overflow and/or the result may not fit in the - // target type. -#if FMT_SAFE_DURATION_CAST - using CommonSecondsType = - typename std::common_type<decltype(d), std::chrono::seconds>::type; - const auto d_as_common = fmt_safe_duration_cast<CommonSecondsType>(d); - const auto d_as_whole_seconds = - fmt_safe_duration_cast<std::chrono::seconds>(d_as_common); - // this conversion should be nonproblematic - const auto diff = d_as_common - d_as_whole_seconds; - const auto ms = - fmt_safe_duration_cast<std::chrono::duration<Rep, std::milli>>(diff); - return ms; -#else - auto s = std::chrono::duration_cast<std::chrono::seconds>(d); - return std::chrono::duration_cast<std::chrono::milliseconds>(d - s); -#endif -} - -template <typename Rep, typename Period, - FMT_ENABLE_IF(std::is_floating_point<Rep>::value)> -inline std::chrono::duration<Rep, std::milli> get_milliseconds( - std::chrono::duration<Rep, Period> d) { - using common_type = typename std::common_type<Rep, std::intmax_t>::type; - auto ms = mod(d.count() * static_cast<common_type>(Period::num) / - static_cast<common_type>(Period::den) * 1000, - 1000); - return std::chrono::duration<Rep, std::milli>(static_cast<Rep>(ms)); -} - -template <typename Char, typename Rep, typename OutputIt> -OutputIt format_duration_value(OutputIt out, Rep val, int precision) { - const Char pr_f[] = {'{', ':', '.', '{', '}', 'f', '}', 0}; - if (precision >= 0) return format_to(out, pr_f, val, precision); - const Char fp_f[] = {'{', ':', 'g', '}', 0}; - const Char format[] = {'{', '}', 0}; - return format_to(out, std::is_floating_point<Rep>::value ? fp_f : format, - val); -} +template <typename Period> FMT_CONSTEXPR const char* get_units() { + return nullptr; +} +template <> FMT_CONSTEXPR const char* get_units<std::atto>() { return "as"; } +template <> FMT_CONSTEXPR const char* get_units<std::femto>() { return "fs"; } +template <> FMT_CONSTEXPR const char* get_units<std::pico>() { return "ps"; } +template <> FMT_CONSTEXPR const char* get_units<std::nano>() { return "ns"; } +template <> FMT_CONSTEXPR const char* get_units<std::micro>() { return "µs"; } +template <> FMT_CONSTEXPR const char* get_units<std::milli>() { return "ms"; } +template <> FMT_CONSTEXPR const char* get_units<std::centi>() { return "cs"; } +template <> FMT_CONSTEXPR const char* get_units<std::deci>() { return "ds"; } +template <> FMT_CONSTEXPR const char* get_units<std::ratio<1>>() { return "s"; } +template <> FMT_CONSTEXPR const char* get_units<std::deca>() { return "das"; } +template <> FMT_CONSTEXPR const char* get_units<std::hecto>() { return "hs"; } +template <> FMT_CONSTEXPR const char* get_units<std::kilo>() { return "ks"; } +template <> FMT_CONSTEXPR const char* get_units<std::mega>() { return "Ms"; } +template <> FMT_CONSTEXPR const char* get_units<std::giga>() { return "Gs"; } +template <> FMT_CONSTEXPR const char* get_units<std::tera>() { return "Ts"; } +template <> FMT_CONSTEXPR const char* get_units<std::peta>() { return "Ps"; } +template <> FMT_CONSTEXPR const char* get_units<std::exa>() { return "Es"; } +template <> FMT_CONSTEXPR const char* get_units<std::ratio<60>>() { + return "m"; +} +template <> FMT_CONSTEXPR const char* get_units<std::ratio<3600>>() { + return "h"; +} + +enum class numeric_system { + standard, + // Alternative numeric system, e.g. 十二 instead of 12 in ja_JP locale. + alternative +}; + +// Parses a put_time-like format string and invokes handler actions. +template <typename Char, typename Handler> +FMT_CONSTEXPR const Char* parse_chrono_format(const Char* begin, + const Char* end, + Handler&& handler) { + auto ptr = begin; + while (ptr != end) { + auto c = *ptr; + if (c == '}') break; + if (c != '%') { + ++ptr; + continue; + } + if (begin != ptr) handler.on_text(begin, ptr); + ++ptr; // consume '%' + if (ptr == end) FMT_THROW(format_error("invalid format")); + c = *ptr++; + switch (c) { + case '%': + handler.on_text(ptr - 1, ptr); + break; + case 'n': { + const Char newline[] = {'\n'}; + handler.on_text(newline, newline + 1); + break; + } + case 't': { + const Char tab[] = {'\t'}; + handler.on_text(tab, tab + 1); + break; + } + // Day of the week: + case 'a': + handler.on_abbr_weekday(); + break; + case 'A': + handler.on_full_weekday(); + break; + case 'w': + handler.on_dec0_weekday(numeric_system::standard); + break; + case 'u': + handler.on_dec1_weekday(numeric_system::standard); + break; + // Month: + case 'b': + handler.on_abbr_month(); + break; + case 'B': + handler.on_full_month(); + break; + // Hour, minute, second: + case 'H': + handler.on_24_hour(numeric_system::standard); + break; + case 'I': + handler.on_12_hour(numeric_system::standard); + break; + case 'M': + handler.on_minute(numeric_system::standard); + break; + case 'S': + handler.on_second(numeric_system::standard); + break; + // Other: + case 'c': + handler.on_datetime(numeric_system::standard); + break; + case 'x': + handler.on_loc_date(numeric_system::standard); + break; + case 'X': + handler.on_loc_time(numeric_system::standard); + break; + case 'D': + handler.on_us_date(); + break; + case 'F': + handler.on_iso_date(); + break; + case 'r': + handler.on_12_hour_time(); + break; + case 'R': + handler.on_24_hour_time(); + break; + case 'T': + handler.on_iso_time(); + break; + case 'p': + handler.on_am_pm(); + break; + case 'Q': + handler.on_duration_value(); + break; + case 'q': + handler.on_duration_unit(); + break; + case 'z': + handler.on_utc_offset(); + break; + case 'Z': + handler.on_tz_name(); + break; + // Alternative representation: + case 'E': { + if (ptr == end) FMT_THROW(format_error("invalid format")); + c = *ptr++; + switch (c) { + case 'c': + handler.on_datetime(numeric_system::alternative); + break; + case 'x': + handler.on_loc_date(numeric_system::alternative); + break; + case 'X': + handler.on_loc_time(numeric_system::alternative); + break; + default: + FMT_THROW(format_error("invalid format")); + } + break; + } + case 'O': + if (ptr == end) FMT_THROW(format_error("invalid format")); + c = *ptr++; + switch (c) { + case 'w': + handler.on_dec0_weekday(numeric_system::alternative); + break; + case 'u': + handler.on_dec1_weekday(numeric_system::alternative); + break; + case 'H': + handler.on_24_hour(numeric_system::alternative); + break; + case 'I': + handler.on_12_hour(numeric_system::alternative); + break; + case 'M': + handler.on_minute(numeric_system::alternative); + break; + case 'S': + handler.on_second(numeric_system::alternative); + break; + default: + FMT_THROW(format_error("invalid format")); + } + break; + default: + FMT_THROW(format_error("invalid format")); + } + begin = ptr; + } + if (begin != ptr) handler.on_text(begin, ptr); + return ptr; +} + +struct chrono_format_checker { + FMT_NORETURN void report_no_date() { FMT_THROW(format_error("no date")); } + + template <typename Char> void on_text(const Char*, const Char*) {} + FMT_NORETURN void on_abbr_weekday() { report_no_date(); } + FMT_NORETURN void on_full_weekday() { report_no_date(); } + FMT_NORETURN void on_dec0_weekday(numeric_system) { report_no_date(); } + FMT_NORETURN void on_dec1_weekday(numeric_system) { report_no_date(); } + FMT_NORETURN void on_abbr_month() { report_no_date(); } + FMT_NORETURN void on_full_month() { report_no_date(); } + void on_24_hour(numeric_system) {} + void on_12_hour(numeric_system) {} + void on_minute(numeric_system) {} + void on_second(numeric_system) {} + FMT_NORETURN void on_datetime(numeric_system) { report_no_date(); } + FMT_NORETURN void on_loc_date(numeric_system) { report_no_date(); } + FMT_NORETURN void on_loc_time(numeric_system) { report_no_date(); } + FMT_NORETURN void on_us_date() { report_no_date(); } + FMT_NORETURN void on_iso_date() { report_no_date(); } + void on_12_hour_time() {} + void on_24_hour_time() {} + void on_iso_time() {} + void on_am_pm() {} + void on_duration_value() {} + void on_duration_unit() {} + FMT_NORETURN void on_utc_offset() { report_no_date(); } + FMT_NORETURN void on_tz_name() { report_no_date(); } +}; + +template <typename T, FMT_ENABLE_IF(std::is_integral<T>::value)> +inline bool isnan(T) { + return false; +} +template <typename T, FMT_ENABLE_IF(std::is_floating_point<T>::value)> +inline bool isnan(T value) { + return std::isnan(value); +} + +template <typename T, FMT_ENABLE_IF(std::is_integral<T>::value)> +inline bool isfinite(T) { + return true; +} +template <typename T, FMT_ENABLE_IF(std::is_floating_point<T>::value)> +inline bool isfinite(T value) { + return std::isfinite(value); +} + +// Converts value to int and checks that it's in the range [0, upper). +template <typename T, FMT_ENABLE_IF(std::is_integral<T>::value)> +inline int to_nonnegative_int(T value, int upper) { + FMT_ASSERT(value >= 0 && value <= upper, "invalid value"); + (void)upper; + return static_cast<int>(value); +} +template <typename T, FMT_ENABLE_IF(!std::is_integral<T>::value)> +inline int to_nonnegative_int(T value, int upper) { + FMT_ASSERT( + std::isnan(value) || (value >= 0 && value <= static_cast<T>(upper)), + "invalid value"); + (void)upper; + return static_cast<int>(value); +} + +template <typename T, FMT_ENABLE_IF(std::is_integral<T>::value)> +inline T mod(T x, int y) { + return x % static_cast<T>(y); +} +template <typename T, FMT_ENABLE_IF(std::is_floating_point<T>::value)> +inline T mod(T x, int y) { + return std::fmod(x, static_cast<T>(y)); +} + +// If T is an integral type, maps T to its unsigned counterpart, otherwise +// leaves it unchanged (unlike std::make_unsigned). +template <typename T, bool INTEGRAL = std::is_integral<T>::value> +struct make_unsigned_or_unchanged { + using type = T; +}; + +template <typename T> struct make_unsigned_or_unchanged<T, true> { + using type = typename std::make_unsigned<T>::type; +}; + +#if FMT_SAFE_DURATION_CAST +// throwing version of safe_duration_cast +template <typename To, typename FromRep, typename FromPeriod> +To fmt_safe_duration_cast(std::chrono::duration<FromRep, FromPeriod> from) { + int ec; + To to = safe_duration_cast::safe_duration_cast<To>(from, ec); + if (ec) FMT_THROW(format_error("cannot format duration")); + return to; +} +#endif + +template <typename Rep, typename Period, + FMT_ENABLE_IF(std::is_integral<Rep>::value)> +inline std::chrono::duration<Rep, std::milli> get_milliseconds( + std::chrono::duration<Rep, Period> d) { + // this may overflow and/or the result may not fit in the + // target type. +#if FMT_SAFE_DURATION_CAST + using CommonSecondsType = + typename std::common_type<decltype(d), std::chrono::seconds>::type; + const auto d_as_common = fmt_safe_duration_cast<CommonSecondsType>(d); + const auto d_as_whole_seconds = + fmt_safe_duration_cast<std::chrono::seconds>(d_as_common); + // this conversion should be nonproblematic + const auto diff = d_as_common - d_as_whole_seconds; + const auto ms = + fmt_safe_duration_cast<std::chrono::duration<Rep, std::milli>>(diff); + return ms; +#else + auto s = std::chrono::duration_cast<std::chrono::seconds>(d); + return std::chrono::duration_cast<std::chrono::milliseconds>(d - s); +#endif +} + +template <typename Rep, typename Period, + FMT_ENABLE_IF(std::is_floating_point<Rep>::value)> +inline std::chrono::duration<Rep, std::milli> get_milliseconds( + std::chrono::duration<Rep, Period> d) { + using common_type = typename std::common_type<Rep, std::intmax_t>::type; + auto ms = mod(d.count() * static_cast<common_type>(Period::num) / + static_cast<common_type>(Period::den) * 1000, + 1000); + return std::chrono::duration<Rep, std::milli>(static_cast<Rep>(ms)); +} + +template <typename Char, typename Rep, typename OutputIt> +OutputIt format_duration_value(OutputIt out, Rep val, int precision) { + const Char pr_f[] = {'{', ':', '.', '{', '}', 'f', '}', 0}; + if (precision >= 0) return format_to(out, pr_f, val, precision); + const Char fp_f[] = {'{', ':', 'g', '}', 0}; + const Char format[] = {'{', '}', 0}; + return format_to(out, std::is_floating_point<Rep>::value ? fp_f : format, + val); +} template <typename Char, typename OutputIt> OutputIt copy_unit(string_view unit, OutputIt out, Char) { return std::copy(unit.begin(), unit.end(), out); } - + template <typename OutputIt> OutputIt copy_unit(string_view unit, OutputIt out, wchar_t) { // This works when wchar_t is UTF-32 because units only contain characters @@ -776,343 +776,343 @@ OutputIt copy_unit(string_view unit, OutputIt out, wchar_t) { return std::copy(u.c_str(), u.c_str() + u.size(), out); } -template <typename Char, typename Period, typename OutputIt> -OutputIt format_duration_unit(OutputIt out) { +template <typename Char, typename Period, typename OutputIt> +OutputIt format_duration_unit(OutputIt out) { if (const char* unit = get_units<Period>()) return copy_unit(string_view(unit), out, Char()); - const Char num_f[] = {'[', '{', '}', ']', 's', 0}; + const Char num_f[] = {'[', '{', '}', ']', 's', 0}; if (const_check(Period::den == 1)) return format_to(out, num_f, Period::num); - const Char num_def_f[] = {'[', '{', '}', '/', '{', '}', ']', 's', 0}; - return format_to(out, num_def_f, Period::num, Period::den); -} - -template <typename FormatContext, typename OutputIt, typename Rep, - typename Period> -struct chrono_formatter { - FormatContext& context; - OutputIt out; - int precision; - // rep is unsigned to avoid overflow. - using rep = - conditional_t<std::is_integral<Rep>::value && sizeof(Rep) < sizeof(int), - unsigned, typename make_unsigned_or_unchanged<Rep>::type>; - rep val; - using seconds = std::chrono::duration<rep>; - seconds s; - using milliseconds = std::chrono::duration<rep, std::milli>; - bool negative; - - using char_type = typename FormatContext::char_type; - - explicit chrono_formatter(FormatContext& ctx, OutputIt o, - std::chrono::duration<Rep, Period> d) - : context(ctx), - out(o), - val(static_cast<rep>(d.count())), - negative(false) { - if (d.count() < 0) { - val = 0 - val; - negative = true; - } - - // this may overflow and/or the result may not fit in the - // target type. -#if FMT_SAFE_DURATION_CAST - // might need checked conversion (rep!=Rep) - auto tmpval = std::chrono::duration<rep, Period>(val); - s = fmt_safe_duration_cast<seconds>(tmpval); -#else - s = std::chrono::duration_cast<seconds>( - std::chrono::duration<rep, Period>(val)); -#endif - } - - // returns true if nan or inf, writes to out. - bool handle_nan_inf() { - if (isfinite(val)) { - return false; - } - if (isnan(val)) { - write_nan(); - return true; - } - // must be +-inf - if (val > 0) { - write_pinf(); - } else { - write_ninf(); - } - return true; - } - - Rep hour() const { return static_cast<Rep>(mod((s.count() / 3600), 24)); } - - Rep hour12() const { - Rep hour = static_cast<Rep>(mod((s.count() / 3600), 12)); - return hour <= 0 ? 12 : hour; - } - - Rep minute() const { return static_cast<Rep>(mod((s.count() / 60), 60)); } - Rep second() const { return static_cast<Rep>(mod(s.count(), 60)); } - - std::tm time() const { - auto time = std::tm(); - time.tm_hour = to_nonnegative_int(hour(), 24); - time.tm_min = to_nonnegative_int(minute(), 60); - time.tm_sec = to_nonnegative_int(second(), 60); - return time; - } - - void write_sign() { - if (negative) { - *out++ = '-'; - negative = false; - } - } - - void write(Rep value, int width) { - write_sign(); - if (isnan(value)) return write_nan(); - uint32_or_64_or_128_t<int> n = - to_unsigned(to_nonnegative_int(value, max_value<int>())); + const Char num_def_f[] = {'[', '{', '}', '/', '{', '}', ']', 's', 0}; + return format_to(out, num_def_f, Period::num, Period::den); +} + +template <typename FormatContext, typename OutputIt, typename Rep, + typename Period> +struct chrono_formatter { + FormatContext& context; + OutputIt out; + int precision; + // rep is unsigned to avoid overflow. + using rep = + conditional_t<std::is_integral<Rep>::value && sizeof(Rep) < sizeof(int), + unsigned, typename make_unsigned_or_unchanged<Rep>::type>; + rep val; + using seconds = std::chrono::duration<rep>; + seconds s; + using milliseconds = std::chrono::duration<rep, std::milli>; + bool negative; + + using char_type = typename FormatContext::char_type; + + explicit chrono_formatter(FormatContext& ctx, OutputIt o, + std::chrono::duration<Rep, Period> d) + : context(ctx), + out(o), + val(static_cast<rep>(d.count())), + negative(false) { + if (d.count() < 0) { + val = 0 - val; + negative = true; + } + + // this may overflow and/or the result may not fit in the + // target type. +#if FMT_SAFE_DURATION_CAST + // might need checked conversion (rep!=Rep) + auto tmpval = std::chrono::duration<rep, Period>(val); + s = fmt_safe_duration_cast<seconds>(tmpval); +#else + s = std::chrono::duration_cast<seconds>( + std::chrono::duration<rep, Period>(val)); +#endif + } + + // returns true if nan or inf, writes to out. + bool handle_nan_inf() { + if (isfinite(val)) { + return false; + } + if (isnan(val)) { + write_nan(); + return true; + } + // must be +-inf + if (val > 0) { + write_pinf(); + } else { + write_ninf(); + } + return true; + } + + Rep hour() const { return static_cast<Rep>(mod((s.count() / 3600), 24)); } + + Rep hour12() const { + Rep hour = static_cast<Rep>(mod((s.count() / 3600), 12)); + return hour <= 0 ? 12 : hour; + } + + Rep minute() const { return static_cast<Rep>(mod((s.count() / 60), 60)); } + Rep second() const { return static_cast<Rep>(mod(s.count(), 60)); } + + std::tm time() const { + auto time = std::tm(); + time.tm_hour = to_nonnegative_int(hour(), 24); + time.tm_min = to_nonnegative_int(minute(), 60); + time.tm_sec = to_nonnegative_int(second(), 60); + return time; + } + + void write_sign() { + if (negative) { + *out++ = '-'; + negative = false; + } + } + + void write(Rep value, int width) { + write_sign(); + if (isnan(value)) return write_nan(); + uint32_or_64_or_128_t<int> n = + to_unsigned(to_nonnegative_int(value, max_value<int>())); int num_digits = detail::count_digits(n); - if (width > num_digits) out = std::fill_n(out, width - num_digits, '0'); + if (width > num_digits) out = std::fill_n(out, width - num_digits, '0'); out = format_decimal<char_type>(out, n, num_digits).end; - } - - void write_nan() { std::copy_n("nan", 3, out); } - void write_pinf() { std::copy_n("inf", 3, out); } - void write_ninf() { std::copy_n("-inf", 4, out); } - - void format_localized(const tm& time, char format, char modifier = 0) { - if (isnan(val)) return write_nan(); - auto locale = context.locale().template get<std::locale>(); - auto& facet = std::use_facet<std::time_put<char_type>>(locale); - std::basic_ostringstream<char_type> os; - os.imbue(locale); - facet.put(os, os, ' ', &time, format, modifier); - auto str = os.str(); - std::copy(str.begin(), str.end(), out); - } - - void on_text(const char_type* begin, const char_type* end) { - std::copy(begin, end, out); - } - - // These are not implemented because durations don't have date information. - void on_abbr_weekday() {} - void on_full_weekday() {} - void on_dec0_weekday(numeric_system) {} - void on_dec1_weekday(numeric_system) {} - void on_abbr_month() {} - void on_full_month() {} - void on_datetime(numeric_system) {} - void on_loc_date(numeric_system) {} - void on_loc_time(numeric_system) {} - void on_us_date() {} - void on_iso_date() {} - void on_utc_offset() {} - void on_tz_name() {} - - void on_24_hour(numeric_system ns) { - if (handle_nan_inf()) return; - - if (ns == numeric_system::standard) return write(hour(), 2); - auto time = tm(); - time.tm_hour = to_nonnegative_int(hour(), 24); - format_localized(time, 'H', 'O'); - } - - void on_12_hour(numeric_system ns) { - if (handle_nan_inf()) return; - - if (ns == numeric_system::standard) return write(hour12(), 2); - auto time = tm(); - time.tm_hour = to_nonnegative_int(hour12(), 12); - format_localized(time, 'I', 'O'); - } - - void on_minute(numeric_system ns) { - if (handle_nan_inf()) return; - - if (ns == numeric_system::standard) return write(minute(), 2); - auto time = tm(); - time.tm_min = to_nonnegative_int(minute(), 60); - format_localized(time, 'M', 'O'); - } - - void on_second(numeric_system ns) { - if (handle_nan_inf()) return; - - if (ns == numeric_system::standard) { - write(second(), 2); -#if FMT_SAFE_DURATION_CAST - // convert rep->Rep - using duration_rep = std::chrono::duration<rep, Period>; - using duration_Rep = std::chrono::duration<Rep, Period>; - auto tmpval = fmt_safe_duration_cast<duration_Rep>(duration_rep{val}); -#else - auto tmpval = std::chrono::duration<Rep, Period>(val); -#endif - auto ms = get_milliseconds(tmpval); - if (ms != std::chrono::milliseconds(0)) { - *out++ = '.'; - write(ms.count(), 3); - } - return; - } - auto time = tm(); - time.tm_sec = to_nonnegative_int(second(), 60); - format_localized(time, 'S', 'O'); - } - - void on_12_hour_time() { - if (handle_nan_inf()) return; - format_localized(time(), 'r'); - } - - void on_24_hour_time() { - if (handle_nan_inf()) { - *out++ = ':'; - handle_nan_inf(); - return; - } - - write(hour(), 2); - *out++ = ':'; - write(minute(), 2); - } - - void on_iso_time() { - on_24_hour_time(); - *out++ = ':'; - if (handle_nan_inf()) return; - write(second(), 2); - } - - void on_am_pm() { - if (handle_nan_inf()) return; - format_localized(time(), 'p'); - } - - void on_duration_value() { - if (handle_nan_inf()) return; - write_sign(); - out = format_duration_value<char_type>(out, val, precision); - } - - void on_duration_unit() { - out = format_duration_unit<char_type, Period>(out); - } -}; + } + + void write_nan() { std::copy_n("nan", 3, out); } + void write_pinf() { std::copy_n("inf", 3, out); } + void write_ninf() { std::copy_n("-inf", 4, out); } + + void format_localized(const tm& time, char format, char modifier = 0) { + if (isnan(val)) return write_nan(); + auto locale = context.locale().template get<std::locale>(); + auto& facet = std::use_facet<std::time_put<char_type>>(locale); + std::basic_ostringstream<char_type> os; + os.imbue(locale); + facet.put(os, os, ' ', &time, format, modifier); + auto str = os.str(); + std::copy(str.begin(), str.end(), out); + } + + void on_text(const char_type* begin, const char_type* end) { + std::copy(begin, end, out); + } + + // These are not implemented because durations don't have date information. + void on_abbr_weekday() {} + void on_full_weekday() {} + void on_dec0_weekday(numeric_system) {} + void on_dec1_weekday(numeric_system) {} + void on_abbr_month() {} + void on_full_month() {} + void on_datetime(numeric_system) {} + void on_loc_date(numeric_system) {} + void on_loc_time(numeric_system) {} + void on_us_date() {} + void on_iso_date() {} + void on_utc_offset() {} + void on_tz_name() {} + + void on_24_hour(numeric_system ns) { + if (handle_nan_inf()) return; + + if (ns == numeric_system::standard) return write(hour(), 2); + auto time = tm(); + time.tm_hour = to_nonnegative_int(hour(), 24); + format_localized(time, 'H', 'O'); + } + + void on_12_hour(numeric_system ns) { + if (handle_nan_inf()) return; + + if (ns == numeric_system::standard) return write(hour12(), 2); + auto time = tm(); + time.tm_hour = to_nonnegative_int(hour12(), 12); + format_localized(time, 'I', 'O'); + } + + void on_minute(numeric_system ns) { + if (handle_nan_inf()) return; + + if (ns == numeric_system::standard) return write(minute(), 2); + auto time = tm(); + time.tm_min = to_nonnegative_int(minute(), 60); + format_localized(time, 'M', 'O'); + } + + void on_second(numeric_system ns) { + if (handle_nan_inf()) return; + + if (ns == numeric_system::standard) { + write(second(), 2); +#if FMT_SAFE_DURATION_CAST + // convert rep->Rep + using duration_rep = std::chrono::duration<rep, Period>; + using duration_Rep = std::chrono::duration<Rep, Period>; + auto tmpval = fmt_safe_duration_cast<duration_Rep>(duration_rep{val}); +#else + auto tmpval = std::chrono::duration<Rep, Period>(val); +#endif + auto ms = get_milliseconds(tmpval); + if (ms != std::chrono::milliseconds(0)) { + *out++ = '.'; + write(ms.count(), 3); + } + return; + } + auto time = tm(); + time.tm_sec = to_nonnegative_int(second(), 60); + format_localized(time, 'S', 'O'); + } + + void on_12_hour_time() { + if (handle_nan_inf()) return; + format_localized(time(), 'r'); + } + + void on_24_hour_time() { + if (handle_nan_inf()) { + *out++ = ':'; + handle_nan_inf(); + return; + } + + write(hour(), 2); + *out++ = ':'; + write(minute(), 2); + } + + void on_iso_time() { + on_24_hour_time(); + *out++ = ':'; + if (handle_nan_inf()) return; + write(second(), 2); + } + + void on_am_pm() { + if (handle_nan_inf()) return; + format_localized(time(), 'p'); + } + + void on_duration_value() { + if (handle_nan_inf()) return; + write_sign(); + out = format_duration_value<char_type>(out, val, precision); + } + + void on_duration_unit() { + out = format_duration_unit<char_type, Period>(out); + } +}; } // namespace detail - -template <typename Rep, typename Period, typename Char> -struct formatter<std::chrono::duration<Rep, Period>, Char> { - private: - basic_format_specs<Char> specs; - int precision; + +template <typename Rep, typename Period, typename Char> +struct formatter<std::chrono::duration<Rep, Period>, Char> { + private: + basic_format_specs<Char> specs; + int precision; using arg_ref_type = detail::arg_ref<Char>; - arg_ref_type width_ref; - arg_ref_type precision_ref; - mutable basic_string_view<Char> format_str; - using duration = std::chrono::duration<Rep, Period>; - - struct spec_handler { - formatter& f; - basic_format_parse_context<Char>& context; - basic_string_view<Char> format_str; - - template <typename Id> FMT_CONSTEXPR arg_ref_type make_arg_ref(Id arg_id) { - context.check_arg_id(arg_id); - return arg_ref_type(arg_id); - } - - FMT_CONSTEXPR arg_ref_type make_arg_ref(basic_string_view<Char> arg_id) { - context.check_arg_id(arg_id); - return arg_ref_type(arg_id); - } - + arg_ref_type width_ref; + arg_ref_type precision_ref; + mutable basic_string_view<Char> format_str; + using duration = std::chrono::duration<Rep, Period>; + + struct spec_handler { + formatter& f; + basic_format_parse_context<Char>& context; + basic_string_view<Char> format_str; + + template <typename Id> FMT_CONSTEXPR arg_ref_type make_arg_ref(Id arg_id) { + context.check_arg_id(arg_id); + return arg_ref_type(arg_id); + } + + FMT_CONSTEXPR arg_ref_type make_arg_ref(basic_string_view<Char> arg_id) { + context.check_arg_id(arg_id); + return arg_ref_type(arg_id); + } + FMT_CONSTEXPR arg_ref_type make_arg_ref(detail::auto_id) { - return arg_ref_type(context.next_arg_id()); - } - - void on_error(const char* msg) { FMT_THROW(format_error(msg)); } - void on_fill(basic_string_view<Char> fill) { f.specs.fill = fill; } - void on_align(align_t align) { f.specs.align = align; } - void on_width(int width) { f.specs.width = width; } - void on_precision(int _precision) { f.precision = _precision; } - void end_precision() {} - - template <typename Id> void on_dynamic_width(Id arg_id) { - f.width_ref = make_arg_ref(arg_id); - } - - template <typename Id> void on_dynamic_precision(Id arg_id) { - f.precision_ref = make_arg_ref(arg_id); - } - }; - - using iterator = typename basic_format_parse_context<Char>::iterator; - struct parse_range { - iterator begin; - iterator end; - }; - - FMT_CONSTEXPR parse_range do_parse(basic_format_parse_context<Char>& ctx) { - auto begin = ctx.begin(), end = ctx.end(); - if (begin == end || *begin == '}') return {begin, begin}; - spec_handler handler{*this, ctx, format_str}; + return arg_ref_type(context.next_arg_id()); + } + + void on_error(const char* msg) { FMT_THROW(format_error(msg)); } + void on_fill(basic_string_view<Char> fill) { f.specs.fill = fill; } + void on_align(align_t align) { f.specs.align = align; } + void on_width(int width) { f.specs.width = width; } + void on_precision(int _precision) { f.precision = _precision; } + void end_precision() {} + + template <typename Id> void on_dynamic_width(Id arg_id) { + f.width_ref = make_arg_ref(arg_id); + } + + template <typename Id> void on_dynamic_precision(Id arg_id) { + f.precision_ref = make_arg_ref(arg_id); + } + }; + + using iterator = typename basic_format_parse_context<Char>::iterator; + struct parse_range { + iterator begin; + iterator end; + }; + + FMT_CONSTEXPR parse_range do_parse(basic_format_parse_context<Char>& ctx) { + auto begin = ctx.begin(), end = ctx.end(); + if (begin == end || *begin == '}') return {begin, begin}; + spec_handler handler{*this, ctx, format_str}; begin = detail::parse_align(begin, end, handler); - if (begin == end) return {begin, begin}; + if (begin == end) return {begin, begin}; begin = detail::parse_width(begin, end, handler); - if (begin == end) return {begin, begin}; - if (*begin == '.') { - if (std::is_floating_point<Rep>::value) + if (begin == end) return {begin, begin}; + if (*begin == '.') { + if (std::is_floating_point<Rep>::value) begin = detail::parse_precision(begin, end, handler); - else - handler.on_error("precision not allowed for this argument type"); - } + else + handler.on_error("precision not allowed for this argument type"); + } end = parse_chrono_format(begin, end, detail::chrono_format_checker()); - return {begin, end}; - } - - public: - formatter() : precision(-1) {} - - FMT_CONSTEXPR auto parse(basic_format_parse_context<Char>& ctx) - -> decltype(ctx.begin()) { - auto range = do_parse(ctx); - format_str = basic_string_view<Char>( + return {begin, end}; + } + + public: + formatter() : precision(-1) {} + + FMT_CONSTEXPR auto parse(basic_format_parse_context<Char>& ctx) + -> decltype(ctx.begin()) { + auto range = do_parse(ctx); + format_str = basic_string_view<Char>( &*range.begin, detail::to_unsigned(range.end - range.begin)); - return range.end; - } - - template <typename FormatContext> - auto format(const duration& d, FormatContext& ctx) -> decltype(ctx.out()) { - auto begin = format_str.begin(), end = format_str.end(); - // As a possible future optimization, we could avoid extra copying if width - // is not specified. - basic_memory_buffer<Char> buf; - auto out = std::back_inserter(buf); + return range.end; + } + + template <typename FormatContext> + auto format(const duration& d, FormatContext& ctx) -> decltype(ctx.out()) { + auto begin = format_str.begin(), end = format_str.end(); + // As a possible future optimization, we could avoid extra copying if width + // is not specified. + basic_memory_buffer<Char> buf; + auto out = std::back_inserter(buf); detail::handle_dynamic_spec<detail::width_checker>(specs.width, width_ref, ctx); detail::handle_dynamic_spec<detail::precision_checker>(precision, precision_ref, ctx); - if (begin == end || *begin == '}') { + if (begin == end || *begin == '}') { out = detail::format_duration_value<Char>(out, d.count(), precision); detail::format_duration_unit<Char, Period>(out); - } else { + } else { detail::chrono_formatter<FormatContext, decltype(out), Rep, Period> f( - ctx, out, d); - f.precision = precision; - parse_chrono_format(begin, end, f); - } + ctx, out, d); + f.precision = precision; + parse_chrono_format(begin, end, f); + } return detail::write( ctx.out(), basic_string_view<Char>(buf.data(), buf.size()), specs); - } -}; - -FMT_END_NAMESPACE - -#endif // FMT_CHRONO_H_ + } +}; + +FMT_END_NAMESPACE + +#endif // FMT_CHRONO_H_ diff --git a/contrib/libs/fmt/include/fmt/color.h b/contrib/libs/fmt/include/fmt/color.h index 7ef78aaa11..94e3419d1d 100644 --- a/contrib/libs/fmt/include/fmt/color.h +++ b/contrib/libs/fmt/include/fmt/color.h @@ -1,568 +1,568 @@ -// Formatting library for C++ - color support -// -// Copyright (c) 2018 - present, Victor Zverovich and fmt contributors -// All rights reserved. -// -// For the license information refer to format.h. - -#ifndef FMT_COLOR_H_ -#define FMT_COLOR_H_ - -#include "format.h" - -FMT_BEGIN_NAMESPACE - -enum class color : uint32_t { - alice_blue = 0xF0F8FF, // rgb(240,248,255) - antique_white = 0xFAEBD7, // rgb(250,235,215) - aqua = 0x00FFFF, // rgb(0,255,255) - aquamarine = 0x7FFFD4, // rgb(127,255,212) - azure = 0xF0FFFF, // rgb(240,255,255) - beige = 0xF5F5DC, // rgb(245,245,220) - bisque = 0xFFE4C4, // rgb(255,228,196) - black = 0x000000, // rgb(0,0,0) - blanched_almond = 0xFFEBCD, // rgb(255,235,205) - blue = 0x0000FF, // rgb(0,0,255) - blue_violet = 0x8A2BE2, // rgb(138,43,226) - brown = 0xA52A2A, // rgb(165,42,42) - burly_wood = 0xDEB887, // rgb(222,184,135) - cadet_blue = 0x5F9EA0, // rgb(95,158,160) - chartreuse = 0x7FFF00, // rgb(127,255,0) - chocolate = 0xD2691E, // rgb(210,105,30) - coral = 0xFF7F50, // rgb(255,127,80) - cornflower_blue = 0x6495ED, // rgb(100,149,237) - cornsilk = 0xFFF8DC, // rgb(255,248,220) - crimson = 0xDC143C, // rgb(220,20,60) - cyan = 0x00FFFF, // rgb(0,255,255) - dark_blue = 0x00008B, // rgb(0,0,139) - dark_cyan = 0x008B8B, // rgb(0,139,139) - dark_golden_rod = 0xB8860B, // rgb(184,134,11) - dark_gray = 0xA9A9A9, // rgb(169,169,169) - dark_green = 0x006400, // rgb(0,100,0) - dark_khaki = 0xBDB76B, // rgb(189,183,107) - dark_magenta = 0x8B008B, // rgb(139,0,139) - dark_olive_green = 0x556B2F, // rgb(85,107,47) - dark_orange = 0xFF8C00, // rgb(255,140,0) - dark_orchid = 0x9932CC, // rgb(153,50,204) - dark_red = 0x8B0000, // rgb(139,0,0) - dark_salmon = 0xE9967A, // rgb(233,150,122) - dark_sea_green = 0x8FBC8F, // rgb(143,188,143) - dark_slate_blue = 0x483D8B, // rgb(72,61,139) - dark_slate_gray = 0x2F4F4F, // rgb(47,79,79) - dark_turquoise = 0x00CED1, // rgb(0,206,209) - dark_violet = 0x9400D3, // rgb(148,0,211) - deep_pink = 0xFF1493, // rgb(255,20,147) - deep_sky_blue = 0x00BFFF, // rgb(0,191,255) - dim_gray = 0x696969, // rgb(105,105,105) - dodger_blue = 0x1E90FF, // rgb(30,144,255) - fire_brick = 0xB22222, // rgb(178,34,34) - floral_white = 0xFFFAF0, // rgb(255,250,240) - forest_green = 0x228B22, // rgb(34,139,34) - fuchsia = 0xFF00FF, // rgb(255,0,255) - gainsboro = 0xDCDCDC, // rgb(220,220,220) - ghost_white = 0xF8F8FF, // rgb(248,248,255) - gold = 0xFFD700, // rgb(255,215,0) - golden_rod = 0xDAA520, // rgb(218,165,32) - gray = 0x808080, // rgb(128,128,128) - green = 0x008000, // rgb(0,128,0) - green_yellow = 0xADFF2F, // rgb(173,255,47) - honey_dew = 0xF0FFF0, // rgb(240,255,240) - hot_pink = 0xFF69B4, // rgb(255,105,180) - indian_red = 0xCD5C5C, // rgb(205,92,92) - indigo = 0x4B0082, // rgb(75,0,130) - ivory = 0xFFFFF0, // rgb(255,255,240) - khaki = 0xF0E68C, // rgb(240,230,140) - lavender = 0xE6E6FA, // rgb(230,230,250) - lavender_blush = 0xFFF0F5, // rgb(255,240,245) - lawn_green = 0x7CFC00, // rgb(124,252,0) - lemon_chiffon = 0xFFFACD, // rgb(255,250,205) - light_blue = 0xADD8E6, // rgb(173,216,230) - light_coral = 0xF08080, // rgb(240,128,128) - light_cyan = 0xE0FFFF, // rgb(224,255,255) - light_golden_rod_yellow = 0xFAFAD2, // rgb(250,250,210) - light_gray = 0xD3D3D3, // rgb(211,211,211) - light_green = 0x90EE90, // rgb(144,238,144) - light_pink = 0xFFB6C1, // rgb(255,182,193) - light_salmon = 0xFFA07A, // rgb(255,160,122) - light_sea_green = 0x20B2AA, // rgb(32,178,170) - light_sky_blue = 0x87CEFA, // rgb(135,206,250) - light_slate_gray = 0x778899, // rgb(119,136,153) - light_steel_blue = 0xB0C4DE, // rgb(176,196,222) - light_yellow = 0xFFFFE0, // rgb(255,255,224) - lime = 0x00FF00, // rgb(0,255,0) - lime_green = 0x32CD32, // rgb(50,205,50) - linen = 0xFAF0E6, // rgb(250,240,230) - magenta = 0xFF00FF, // rgb(255,0,255) - maroon = 0x800000, // rgb(128,0,0) - medium_aquamarine = 0x66CDAA, // rgb(102,205,170) - medium_blue = 0x0000CD, // rgb(0,0,205) - medium_orchid = 0xBA55D3, // rgb(186,85,211) - medium_purple = 0x9370DB, // rgb(147,112,219) - medium_sea_green = 0x3CB371, // rgb(60,179,113) - medium_slate_blue = 0x7B68EE, // rgb(123,104,238) - medium_spring_green = 0x00FA9A, // rgb(0,250,154) - medium_turquoise = 0x48D1CC, // rgb(72,209,204) - medium_violet_red = 0xC71585, // rgb(199,21,133) - midnight_blue = 0x191970, // rgb(25,25,112) - mint_cream = 0xF5FFFA, // rgb(245,255,250) - misty_rose = 0xFFE4E1, // rgb(255,228,225) - moccasin = 0xFFE4B5, // rgb(255,228,181) - navajo_white = 0xFFDEAD, // rgb(255,222,173) - navy = 0x000080, // rgb(0,0,128) - old_lace = 0xFDF5E6, // rgb(253,245,230) - olive = 0x808000, // rgb(128,128,0) - olive_drab = 0x6B8E23, // rgb(107,142,35) - orange = 0xFFA500, // rgb(255,165,0) - orange_red = 0xFF4500, // rgb(255,69,0) - orchid = 0xDA70D6, // rgb(218,112,214) - pale_golden_rod = 0xEEE8AA, // rgb(238,232,170) - pale_green = 0x98FB98, // rgb(152,251,152) - pale_turquoise = 0xAFEEEE, // rgb(175,238,238) - pale_violet_red = 0xDB7093, // rgb(219,112,147) - papaya_whip = 0xFFEFD5, // rgb(255,239,213) - peach_puff = 0xFFDAB9, // rgb(255,218,185) - peru = 0xCD853F, // rgb(205,133,63) - pink = 0xFFC0CB, // rgb(255,192,203) - plum = 0xDDA0DD, // rgb(221,160,221) - powder_blue = 0xB0E0E6, // rgb(176,224,230) - purple = 0x800080, // rgb(128,0,128) - rebecca_purple = 0x663399, // rgb(102,51,153) - red = 0xFF0000, // rgb(255,0,0) - rosy_brown = 0xBC8F8F, // rgb(188,143,143) - royal_blue = 0x4169E1, // rgb(65,105,225) - saddle_brown = 0x8B4513, // rgb(139,69,19) - salmon = 0xFA8072, // rgb(250,128,114) - sandy_brown = 0xF4A460, // rgb(244,164,96) - sea_green = 0x2E8B57, // rgb(46,139,87) - sea_shell = 0xFFF5EE, // rgb(255,245,238) - sienna = 0xA0522D, // rgb(160,82,45) - silver = 0xC0C0C0, // rgb(192,192,192) - sky_blue = 0x87CEEB, // rgb(135,206,235) - slate_blue = 0x6A5ACD, // rgb(106,90,205) - slate_gray = 0x708090, // rgb(112,128,144) - snow = 0xFFFAFA, // rgb(255,250,250) - spring_green = 0x00FF7F, // rgb(0,255,127) - steel_blue = 0x4682B4, // rgb(70,130,180) - tan = 0xD2B48C, // rgb(210,180,140) - teal = 0x008080, // rgb(0,128,128) - thistle = 0xD8BFD8, // rgb(216,191,216) - tomato = 0xFF6347, // rgb(255,99,71) - turquoise = 0x40E0D0, // rgb(64,224,208) - violet = 0xEE82EE, // rgb(238,130,238) - wheat = 0xF5DEB3, // rgb(245,222,179) - white = 0xFFFFFF, // rgb(255,255,255) - white_smoke = 0xF5F5F5, // rgb(245,245,245) - yellow = 0xFFFF00, // rgb(255,255,0) - yellow_green = 0x9ACD32 // rgb(154,205,50) -}; // enum class color - -enum class terminal_color : uint8_t { - black = 30, - red, - green, - yellow, - blue, - magenta, - cyan, - white, - bright_black = 90, - bright_red, - bright_green, - bright_yellow, - bright_blue, - bright_magenta, - bright_cyan, - bright_white -}; - -enum class emphasis : uint8_t { - bold = 1, - italic = 1 << 1, - underline = 1 << 2, - strikethrough = 1 << 3 -}; - -// rgb is a struct for red, green and blue colors. -// Using the name "rgb" makes some editors show the color in a tooltip. -struct rgb { - FMT_CONSTEXPR rgb() : r(0), g(0), b(0) {} - FMT_CONSTEXPR rgb(uint8_t r_, uint8_t g_, uint8_t b_) : r(r_), g(g_), b(b_) {} - FMT_CONSTEXPR rgb(uint32_t hex) - : r((hex >> 16) & 0xFF), g((hex >> 8) & 0xFF), b(hex & 0xFF) {} - FMT_CONSTEXPR rgb(color hex) - : r((uint32_t(hex) >> 16) & 0xFF), - g((uint32_t(hex) >> 8) & 0xFF), - b(uint32_t(hex) & 0xFF) {} - uint8_t r; - uint8_t g; - uint8_t b; -}; - +// Formatting library for C++ - color support +// +// Copyright (c) 2018 - present, Victor Zverovich and fmt contributors +// All rights reserved. +// +// For the license information refer to format.h. + +#ifndef FMT_COLOR_H_ +#define FMT_COLOR_H_ + +#include "format.h" + +FMT_BEGIN_NAMESPACE + +enum class color : uint32_t { + alice_blue = 0xF0F8FF, // rgb(240,248,255) + antique_white = 0xFAEBD7, // rgb(250,235,215) + aqua = 0x00FFFF, // rgb(0,255,255) + aquamarine = 0x7FFFD4, // rgb(127,255,212) + azure = 0xF0FFFF, // rgb(240,255,255) + beige = 0xF5F5DC, // rgb(245,245,220) + bisque = 0xFFE4C4, // rgb(255,228,196) + black = 0x000000, // rgb(0,0,0) + blanched_almond = 0xFFEBCD, // rgb(255,235,205) + blue = 0x0000FF, // rgb(0,0,255) + blue_violet = 0x8A2BE2, // rgb(138,43,226) + brown = 0xA52A2A, // rgb(165,42,42) + burly_wood = 0xDEB887, // rgb(222,184,135) + cadet_blue = 0x5F9EA0, // rgb(95,158,160) + chartreuse = 0x7FFF00, // rgb(127,255,0) + chocolate = 0xD2691E, // rgb(210,105,30) + coral = 0xFF7F50, // rgb(255,127,80) + cornflower_blue = 0x6495ED, // rgb(100,149,237) + cornsilk = 0xFFF8DC, // rgb(255,248,220) + crimson = 0xDC143C, // rgb(220,20,60) + cyan = 0x00FFFF, // rgb(0,255,255) + dark_blue = 0x00008B, // rgb(0,0,139) + dark_cyan = 0x008B8B, // rgb(0,139,139) + dark_golden_rod = 0xB8860B, // rgb(184,134,11) + dark_gray = 0xA9A9A9, // rgb(169,169,169) + dark_green = 0x006400, // rgb(0,100,0) + dark_khaki = 0xBDB76B, // rgb(189,183,107) + dark_magenta = 0x8B008B, // rgb(139,0,139) + dark_olive_green = 0x556B2F, // rgb(85,107,47) + dark_orange = 0xFF8C00, // rgb(255,140,0) + dark_orchid = 0x9932CC, // rgb(153,50,204) + dark_red = 0x8B0000, // rgb(139,0,0) + dark_salmon = 0xE9967A, // rgb(233,150,122) + dark_sea_green = 0x8FBC8F, // rgb(143,188,143) + dark_slate_blue = 0x483D8B, // rgb(72,61,139) + dark_slate_gray = 0x2F4F4F, // rgb(47,79,79) + dark_turquoise = 0x00CED1, // rgb(0,206,209) + dark_violet = 0x9400D3, // rgb(148,0,211) + deep_pink = 0xFF1493, // rgb(255,20,147) + deep_sky_blue = 0x00BFFF, // rgb(0,191,255) + dim_gray = 0x696969, // rgb(105,105,105) + dodger_blue = 0x1E90FF, // rgb(30,144,255) + fire_brick = 0xB22222, // rgb(178,34,34) + floral_white = 0xFFFAF0, // rgb(255,250,240) + forest_green = 0x228B22, // rgb(34,139,34) + fuchsia = 0xFF00FF, // rgb(255,0,255) + gainsboro = 0xDCDCDC, // rgb(220,220,220) + ghost_white = 0xF8F8FF, // rgb(248,248,255) + gold = 0xFFD700, // rgb(255,215,0) + golden_rod = 0xDAA520, // rgb(218,165,32) + gray = 0x808080, // rgb(128,128,128) + green = 0x008000, // rgb(0,128,0) + green_yellow = 0xADFF2F, // rgb(173,255,47) + honey_dew = 0xF0FFF0, // rgb(240,255,240) + hot_pink = 0xFF69B4, // rgb(255,105,180) + indian_red = 0xCD5C5C, // rgb(205,92,92) + indigo = 0x4B0082, // rgb(75,0,130) + ivory = 0xFFFFF0, // rgb(255,255,240) + khaki = 0xF0E68C, // rgb(240,230,140) + lavender = 0xE6E6FA, // rgb(230,230,250) + lavender_blush = 0xFFF0F5, // rgb(255,240,245) + lawn_green = 0x7CFC00, // rgb(124,252,0) + lemon_chiffon = 0xFFFACD, // rgb(255,250,205) + light_blue = 0xADD8E6, // rgb(173,216,230) + light_coral = 0xF08080, // rgb(240,128,128) + light_cyan = 0xE0FFFF, // rgb(224,255,255) + light_golden_rod_yellow = 0xFAFAD2, // rgb(250,250,210) + light_gray = 0xD3D3D3, // rgb(211,211,211) + light_green = 0x90EE90, // rgb(144,238,144) + light_pink = 0xFFB6C1, // rgb(255,182,193) + light_salmon = 0xFFA07A, // rgb(255,160,122) + light_sea_green = 0x20B2AA, // rgb(32,178,170) + light_sky_blue = 0x87CEFA, // rgb(135,206,250) + light_slate_gray = 0x778899, // rgb(119,136,153) + light_steel_blue = 0xB0C4DE, // rgb(176,196,222) + light_yellow = 0xFFFFE0, // rgb(255,255,224) + lime = 0x00FF00, // rgb(0,255,0) + lime_green = 0x32CD32, // rgb(50,205,50) + linen = 0xFAF0E6, // rgb(250,240,230) + magenta = 0xFF00FF, // rgb(255,0,255) + maroon = 0x800000, // rgb(128,0,0) + medium_aquamarine = 0x66CDAA, // rgb(102,205,170) + medium_blue = 0x0000CD, // rgb(0,0,205) + medium_orchid = 0xBA55D3, // rgb(186,85,211) + medium_purple = 0x9370DB, // rgb(147,112,219) + medium_sea_green = 0x3CB371, // rgb(60,179,113) + medium_slate_blue = 0x7B68EE, // rgb(123,104,238) + medium_spring_green = 0x00FA9A, // rgb(0,250,154) + medium_turquoise = 0x48D1CC, // rgb(72,209,204) + medium_violet_red = 0xC71585, // rgb(199,21,133) + midnight_blue = 0x191970, // rgb(25,25,112) + mint_cream = 0xF5FFFA, // rgb(245,255,250) + misty_rose = 0xFFE4E1, // rgb(255,228,225) + moccasin = 0xFFE4B5, // rgb(255,228,181) + navajo_white = 0xFFDEAD, // rgb(255,222,173) + navy = 0x000080, // rgb(0,0,128) + old_lace = 0xFDF5E6, // rgb(253,245,230) + olive = 0x808000, // rgb(128,128,0) + olive_drab = 0x6B8E23, // rgb(107,142,35) + orange = 0xFFA500, // rgb(255,165,0) + orange_red = 0xFF4500, // rgb(255,69,0) + orchid = 0xDA70D6, // rgb(218,112,214) + pale_golden_rod = 0xEEE8AA, // rgb(238,232,170) + pale_green = 0x98FB98, // rgb(152,251,152) + pale_turquoise = 0xAFEEEE, // rgb(175,238,238) + pale_violet_red = 0xDB7093, // rgb(219,112,147) + papaya_whip = 0xFFEFD5, // rgb(255,239,213) + peach_puff = 0xFFDAB9, // rgb(255,218,185) + peru = 0xCD853F, // rgb(205,133,63) + pink = 0xFFC0CB, // rgb(255,192,203) + plum = 0xDDA0DD, // rgb(221,160,221) + powder_blue = 0xB0E0E6, // rgb(176,224,230) + purple = 0x800080, // rgb(128,0,128) + rebecca_purple = 0x663399, // rgb(102,51,153) + red = 0xFF0000, // rgb(255,0,0) + rosy_brown = 0xBC8F8F, // rgb(188,143,143) + royal_blue = 0x4169E1, // rgb(65,105,225) + saddle_brown = 0x8B4513, // rgb(139,69,19) + salmon = 0xFA8072, // rgb(250,128,114) + sandy_brown = 0xF4A460, // rgb(244,164,96) + sea_green = 0x2E8B57, // rgb(46,139,87) + sea_shell = 0xFFF5EE, // rgb(255,245,238) + sienna = 0xA0522D, // rgb(160,82,45) + silver = 0xC0C0C0, // rgb(192,192,192) + sky_blue = 0x87CEEB, // rgb(135,206,235) + slate_blue = 0x6A5ACD, // rgb(106,90,205) + slate_gray = 0x708090, // rgb(112,128,144) + snow = 0xFFFAFA, // rgb(255,250,250) + spring_green = 0x00FF7F, // rgb(0,255,127) + steel_blue = 0x4682B4, // rgb(70,130,180) + tan = 0xD2B48C, // rgb(210,180,140) + teal = 0x008080, // rgb(0,128,128) + thistle = 0xD8BFD8, // rgb(216,191,216) + tomato = 0xFF6347, // rgb(255,99,71) + turquoise = 0x40E0D0, // rgb(64,224,208) + violet = 0xEE82EE, // rgb(238,130,238) + wheat = 0xF5DEB3, // rgb(245,222,179) + white = 0xFFFFFF, // rgb(255,255,255) + white_smoke = 0xF5F5F5, // rgb(245,245,245) + yellow = 0xFFFF00, // rgb(255,255,0) + yellow_green = 0x9ACD32 // rgb(154,205,50) +}; // enum class color + +enum class terminal_color : uint8_t { + black = 30, + red, + green, + yellow, + blue, + magenta, + cyan, + white, + bright_black = 90, + bright_red, + bright_green, + bright_yellow, + bright_blue, + bright_magenta, + bright_cyan, + bright_white +}; + +enum class emphasis : uint8_t { + bold = 1, + italic = 1 << 1, + underline = 1 << 2, + strikethrough = 1 << 3 +}; + +// rgb is a struct for red, green and blue colors. +// Using the name "rgb" makes some editors show the color in a tooltip. +struct rgb { + FMT_CONSTEXPR rgb() : r(0), g(0), b(0) {} + FMT_CONSTEXPR rgb(uint8_t r_, uint8_t g_, uint8_t b_) : r(r_), g(g_), b(b_) {} + FMT_CONSTEXPR rgb(uint32_t hex) + : r((hex >> 16) & 0xFF), g((hex >> 8) & 0xFF), b(hex & 0xFF) {} + FMT_CONSTEXPR rgb(color hex) + : r((uint32_t(hex) >> 16) & 0xFF), + g((uint32_t(hex) >> 8) & 0xFF), + b(uint32_t(hex) & 0xFF) {} + uint8_t r; + uint8_t g; + uint8_t b; +}; + namespace detail { - -// color is a struct of either a rgb color or a terminal color. -struct color_type { - FMT_CONSTEXPR color_type() FMT_NOEXCEPT : is_rgb(), value{} {} - FMT_CONSTEXPR color_type(color rgb_color) FMT_NOEXCEPT : is_rgb(true), - value{} { - value.rgb_color = static_cast<uint32_t>(rgb_color); - } - FMT_CONSTEXPR color_type(rgb rgb_color) FMT_NOEXCEPT : is_rgb(true), value{} { - value.rgb_color = (static_cast<uint32_t>(rgb_color.r) << 16) | - (static_cast<uint32_t>(rgb_color.g) << 8) | rgb_color.b; - } - FMT_CONSTEXPR color_type(terminal_color term_color) FMT_NOEXCEPT : is_rgb(), - value{} { - value.term_color = static_cast<uint8_t>(term_color); - } - bool is_rgb; - union color_union { - uint8_t term_color; - uint32_t rgb_color; - } value; -}; + +// color is a struct of either a rgb color or a terminal color. +struct color_type { + FMT_CONSTEXPR color_type() FMT_NOEXCEPT : is_rgb(), value{} {} + FMT_CONSTEXPR color_type(color rgb_color) FMT_NOEXCEPT : is_rgb(true), + value{} { + value.rgb_color = static_cast<uint32_t>(rgb_color); + } + FMT_CONSTEXPR color_type(rgb rgb_color) FMT_NOEXCEPT : is_rgb(true), value{} { + value.rgb_color = (static_cast<uint32_t>(rgb_color.r) << 16) | + (static_cast<uint32_t>(rgb_color.g) << 8) | rgb_color.b; + } + FMT_CONSTEXPR color_type(terminal_color term_color) FMT_NOEXCEPT : is_rgb(), + value{} { + value.term_color = static_cast<uint8_t>(term_color); + } + bool is_rgb; + union color_union { + uint8_t term_color; + uint32_t rgb_color; + } value; +}; } // namespace detail - -// Experimental text formatting support. -class text_style { - public: - FMT_CONSTEXPR text_style(emphasis em = emphasis()) FMT_NOEXCEPT - : set_foreground_color(), - set_background_color(), - ems(em) {} - - FMT_CONSTEXPR text_style& operator|=(const text_style& rhs) { - if (!set_foreground_color) { - set_foreground_color = rhs.set_foreground_color; - foreground_color = rhs.foreground_color; - } else if (rhs.set_foreground_color) { - if (!foreground_color.is_rgb || !rhs.foreground_color.is_rgb) - FMT_THROW(format_error("can't OR a terminal color")); - foreground_color.value.rgb_color |= rhs.foreground_color.value.rgb_color; - } - - if (!set_background_color) { - set_background_color = rhs.set_background_color; - background_color = rhs.background_color; - } else if (rhs.set_background_color) { - if (!background_color.is_rgb || !rhs.background_color.is_rgb) - FMT_THROW(format_error("can't OR a terminal color")); - background_color.value.rgb_color |= rhs.background_color.value.rgb_color; - } - - ems = static_cast<emphasis>(static_cast<uint8_t>(ems) | - static_cast<uint8_t>(rhs.ems)); - return *this; - } - - friend FMT_CONSTEXPR text_style operator|(text_style lhs, - const text_style& rhs) { - return lhs |= rhs; - } - - FMT_CONSTEXPR text_style& operator&=(const text_style& rhs) { - if (!set_foreground_color) { - set_foreground_color = rhs.set_foreground_color; - foreground_color = rhs.foreground_color; - } else if (rhs.set_foreground_color) { - if (!foreground_color.is_rgb || !rhs.foreground_color.is_rgb) - FMT_THROW(format_error("can't AND a terminal color")); - foreground_color.value.rgb_color &= rhs.foreground_color.value.rgb_color; - } - - if (!set_background_color) { - set_background_color = rhs.set_background_color; - background_color = rhs.background_color; - } else if (rhs.set_background_color) { - if (!background_color.is_rgb || !rhs.background_color.is_rgb) - FMT_THROW(format_error("can't AND a terminal color")); - background_color.value.rgb_color &= rhs.background_color.value.rgb_color; - } - - ems = static_cast<emphasis>(static_cast<uint8_t>(ems) & - static_cast<uint8_t>(rhs.ems)); - return *this; - } - - friend FMT_CONSTEXPR text_style operator&(text_style lhs, - const text_style& rhs) { - return lhs &= rhs; - } - - FMT_CONSTEXPR bool has_foreground() const FMT_NOEXCEPT { - return set_foreground_color; - } - FMT_CONSTEXPR bool has_background() const FMT_NOEXCEPT { - return set_background_color; - } - FMT_CONSTEXPR bool has_emphasis() const FMT_NOEXCEPT { - return static_cast<uint8_t>(ems) != 0; - } + +// Experimental text formatting support. +class text_style { + public: + FMT_CONSTEXPR text_style(emphasis em = emphasis()) FMT_NOEXCEPT + : set_foreground_color(), + set_background_color(), + ems(em) {} + + FMT_CONSTEXPR text_style& operator|=(const text_style& rhs) { + if (!set_foreground_color) { + set_foreground_color = rhs.set_foreground_color; + foreground_color = rhs.foreground_color; + } else if (rhs.set_foreground_color) { + if (!foreground_color.is_rgb || !rhs.foreground_color.is_rgb) + FMT_THROW(format_error("can't OR a terminal color")); + foreground_color.value.rgb_color |= rhs.foreground_color.value.rgb_color; + } + + if (!set_background_color) { + set_background_color = rhs.set_background_color; + background_color = rhs.background_color; + } else if (rhs.set_background_color) { + if (!background_color.is_rgb || !rhs.background_color.is_rgb) + FMT_THROW(format_error("can't OR a terminal color")); + background_color.value.rgb_color |= rhs.background_color.value.rgb_color; + } + + ems = static_cast<emphasis>(static_cast<uint8_t>(ems) | + static_cast<uint8_t>(rhs.ems)); + return *this; + } + + friend FMT_CONSTEXPR text_style operator|(text_style lhs, + const text_style& rhs) { + return lhs |= rhs; + } + + FMT_CONSTEXPR text_style& operator&=(const text_style& rhs) { + if (!set_foreground_color) { + set_foreground_color = rhs.set_foreground_color; + foreground_color = rhs.foreground_color; + } else if (rhs.set_foreground_color) { + if (!foreground_color.is_rgb || !rhs.foreground_color.is_rgb) + FMT_THROW(format_error("can't AND a terminal color")); + foreground_color.value.rgb_color &= rhs.foreground_color.value.rgb_color; + } + + if (!set_background_color) { + set_background_color = rhs.set_background_color; + background_color = rhs.background_color; + } else if (rhs.set_background_color) { + if (!background_color.is_rgb || !rhs.background_color.is_rgb) + FMT_THROW(format_error("can't AND a terminal color")); + background_color.value.rgb_color &= rhs.background_color.value.rgb_color; + } + + ems = static_cast<emphasis>(static_cast<uint8_t>(ems) & + static_cast<uint8_t>(rhs.ems)); + return *this; + } + + friend FMT_CONSTEXPR text_style operator&(text_style lhs, + const text_style& rhs) { + return lhs &= rhs; + } + + FMT_CONSTEXPR bool has_foreground() const FMT_NOEXCEPT { + return set_foreground_color; + } + FMT_CONSTEXPR bool has_background() const FMT_NOEXCEPT { + return set_background_color; + } + FMT_CONSTEXPR bool has_emphasis() const FMT_NOEXCEPT { + return static_cast<uint8_t>(ems) != 0; + } FMT_CONSTEXPR detail::color_type get_foreground() const FMT_NOEXCEPT { - FMT_ASSERT(has_foreground(), "no foreground specified for this style"); - return foreground_color; - } + FMT_ASSERT(has_foreground(), "no foreground specified for this style"); + return foreground_color; + } FMT_CONSTEXPR detail::color_type get_background() const FMT_NOEXCEPT { - FMT_ASSERT(has_background(), "no background specified for this style"); - return background_color; - } - FMT_CONSTEXPR emphasis get_emphasis() const FMT_NOEXCEPT { - FMT_ASSERT(has_emphasis(), "no emphasis specified for this style"); - return ems; - } - - private: - FMT_CONSTEXPR text_style(bool is_foreground, + FMT_ASSERT(has_background(), "no background specified for this style"); + return background_color; + } + FMT_CONSTEXPR emphasis get_emphasis() const FMT_NOEXCEPT { + FMT_ASSERT(has_emphasis(), "no emphasis specified for this style"); + return ems; + } + + private: + FMT_CONSTEXPR text_style(bool is_foreground, detail::color_type text_color) FMT_NOEXCEPT - : set_foreground_color(), - set_background_color(), - ems() { - if (is_foreground) { - foreground_color = text_color; - set_foreground_color = true; - } else { - background_color = text_color; - set_background_color = true; - } - } - + : set_foreground_color(), + set_background_color(), + ems() { + if (is_foreground) { + foreground_color = text_color; + set_foreground_color = true; + } else { + background_color = text_color; + set_background_color = true; + } + } + friend FMT_CONSTEXPR_DECL text_style fg(detail::color_type foreground) - FMT_NOEXCEPT; + FMT_NOEXCEPT; friend FMT_CONSTEXPR_DECL text_style bg(detail::color_type background) - FMT_NOEXCEPT; - + FMT_NOEXCEPT; + detail::color_type foreground_color; detail::color_type background_color; - bool set_foreground_color; - bool set_background_color; - emphasis ems; -}; - + bool set_foreground_color; + bool set_background_color; + emphasis ems; +}; + FMT_CONSTEXPR text_style fg(detail::color_type foreground) FMT_NOEXCEPT { - return text_style(/*is_foreground=*/true, foreground); -} - + return text_style(/*is_foreground=*/true, foreground); +} + FMT_CONSTEXPR text_style bg(detail::color_type background) FMT_NOEXCEPT { - return text_style(/*is_foreground=*/false, background); -} - -FMT_CONSTEXPR text_style operator|(emphasis lhs, emphasis rhs) FMT_NOEXCEPT { - return text_style(lhs) | rhs; -} - + return text_style(/*is_foreground=*/false, background); +} + +FMT_CONSTEXPR text_style operator|(emphasis lhs, emphasis rhs) FMT_NOEXCEPT { + return text_style(lhs) | rhs; +} + namespace detail { - -template <typename Char> struct ansi_color_escape { + +template <typename Char> struct ansi_color_escape { FMT_CONSTEXPR ansi_color_escape(detail::color_type text_color, - const char* esc) FMT_NOEXCEPT { - // If we have a terminal color, we need to output another escape code - // sequence. - if (!text_color.is_rgb) { + const char* esc) FMT_NOEXCEPT { + // If we have a terminal color, we need to output another escape code + // sequence. + if (!text_color.is_rgb) { bool is_background = esc == detail::data::background_color; - uint32_t value = text_color.value.term_color; - // Background ASCII codes are the same as the foreground ones but with - // 10 more. - if (is_background) value += 10u; - + uint32_t value = text_color.value.term_color; + // Background ASCII codes are the same as the foreground ones but with + // 10 more. + if (is_background) value += 10u; + size_t index = 0; - buffer[index++] = static_cast<Char>('\x1b'); - buffer[index++] = static_cast<Char>('['); - - if (value >= 100u) { - buffer[index++] = static_cast<Char>('1'); - value %= 100u; - } - buffer[index++] = static_cast<Char>('0' + value / 10u); - buffer[index++] = static_cast<Char>('0' + value % 10u); - - buffer[index++] = static_cast<Char>('m'); - buffer[index++] = static_cast<Char>('\0'); - return; - } - - for (int i = 0; i < 7; i++) { - buffer[i] = static_cast<Char>(esc[i]); - } - rgb color(text_color.value.rgb_color); - to_esc(color.r, buffer + 7, ';'); - to_esc(color.g, buffer + 11, ';'); - to_esc(color.b, buffer + 15, 'm'); - buffer[19] = static_cast<Char>(0); - } - FMT_CONSTEXPR ansi_color_escape(emphasis em) FMT_NOEXCEPT { - uint8_t em_codes[4] = {}; - uint8_t em_bits = static_cast<uint8_t>(em); - if (em_bits & static_cast<uint8_t>(emphasis::bold)) em_codes[0] = 1; - if (em_bits & static_cast<uint8_t>(emphasis::italic)) em_codes[1] = 3; - if (em_bits & static_cast<uint8_t>(emphasis::underline)) em_codes[2] = 4; - if (em_bits & static_cast<uint8_t>(emphasis::strikethrough)) - em_codes[3] = 9; - + buffer[index++] = static_cast<Char>('\x1b'); + buffer[index++] = static_cast<Char>('['); + + if (value >= 100u) { + buffer[index++] = static_cast<Char>('1'); + value %= 100u; + } + buffer[index++] = static_cast<Char>('0' + value / 10u); + buffer[index++] = static_cast<Char>('0' + value % 10u); + + buffer[index++] = static_cast<Char>('m'); + buffer[index++] = static_cast<Char>('\0'); + return; + } + + for (int i = 0; i < 7; i++) { + buffer[i] = static_cast<Char>(esc[i]); + } + rgb color(text_color.value.rgb_color); + to_esc(color.r, buffer + 7, ';'); + to_esc(color.g, buffer + 11, ';'); + to_esc(color.b, buffer + 15, 'm'); + buffer[19] = static_cast<Char>(0); + } + FMT_CONSTEXPR ansi_color_escape(emphasis em) FMT_NOEXCEPT { + uint8_t em_codes[4] = {}; + uint8_t em_bits = static_cast<uint8_t>(em); + if (em_bits & static_cast<uint8_t>(emphasis::bold)) em_codes[0] = 1; + if (em_bits & static_cast<uint8_t>(emphasis::italic)) em_codes[1] = 3; + if (em_bits & static_cast<uint8_t>(emphasis::underline)) em_codes[2] = 4; + if (em_bits & static_cast<uint8_t>(emphasis::strikethrough)) + em_codes[3] = 9; + size_t index = 0; - for (int i = 0; i < 4; ++i) { - if (!em_codes[i]) continue; - buffer[index++] = static_cast<Char>('\x1b'); - buffer[index++] = static_cast<Char>('['); - buffer[index++] = static_cast<Char>('0' + em_codes[i]); - buffer[index++] = static_cast<Char>('m'); - } - buffer[index++] = static_cast<Char>(0); - } - FMT_CONSTEXPR operator const Char*() const FMT_NOEXCEPT { return buffer; } - - FMT_CONSTEXPR const Char* begin() const FMT_NOEXCEPT { return buffer; } - FMT_CONSTEXPR const Char* end() const FMT_NOEXCEPT { - return buffer + std::char_traits<Char>::length(buffer); - } - - private: - Char buffer[7u + 3u * 4u + 1u]; - - static FMT_CONSTEXPR void to_esc(uint8_t c, Char* out, - char delimiter) FMT_NOEXCEPT { - out[0] = static_cast<Char>('0' + c / 100); - out[1] = static_cast<Char>('0' + c / 10 % 10); - out[2] = static_cast<Char>('0' + c % 10); - out[3] = static_cast<Char>(delimiter); - } -}; - -template <typename Char> -FMT_CONSTEXPR ansi_color_escape<Char> make_foreground_color( + for (int i = 0; i < 4; ++i) { + if (!em_codes[i]) continue; + buffer[index++] = static_cast<Char>('\x1b'); + buffer[index++] = static_cast<Char>('['); + buffer[index++] = static_cast<Char>('0' + em_codes[i]); + buffer[index++] = static_cast<Char>('m'); + } + buffer[index++] = static_cast<Char>(0); + } + FMT_CONSTEXPR operator const Char*() const FMT_NOEXCEPT { return buffer; } + + FMT_CONSTEXPR const Char* begin() const FMT_NOEXCEPT { return buffer; } + FMT_CONSTEXPR const Char* end() const FMT_NOEXCEPT { + return buffer + std::char_traits<Char>::length(buffer); + } + + private: + Char buffer[7u + 3u * 4u + 1u]; + + static FMT_CONSTEXPR void to_esc(uint8_t c, Char* out, + char delimiter) FMT_NOEXCEPT { + out[0] = static_cast<Char>('0' + c / 100); + out[1] = static_cast<Char>('0' + c / 10 % 10); + out[2] = static_cast<Char>('0' + c % 10); + out[3] = static_cast<Char>(delimiter); + } +}; + +template <typename Char> +FMT_CONSTEXPR ansi_color_escape<Char> make_foreground_color( detail::color_type foreground) FMT_NOEXCEPT { return ansi_color_escape<Char>(foreground, detail::data::foreground_color); -} - -template <typename Char> -FMT_CONSTEXPR ansi_color_escape<Char> make_background_color( +} + +template <typename Char> +FMT_CONSTEXPR ansi_color_escape<Char> make_background_color( detail::color_type background) FMT_NOEXCEPT { return ansi_color_escape<Char>(background, detail::data::background_color); -} - -template <typename Char> -FMT_CONSTEXPR ansi_color_escape<Char> make_emphasis(emphasis em) FMT_NOEXCEPT { - return ansi_color_escape<Char>(em); -} - -template <typename Char> -inline void fputs(const Char* chars, FILE* stream) FMT_NOEXCEPT { - std::fputs(chars, stream); -} - -template <> -inline void fputs<wchar_t>(const wchar_t* chars, FILE* stream) FMT_NOEXCEPT { - std::fputws(chars, stream); -} - -template <typename Char> inline void reset_color(FILE* stream) FMT_NOEXCEPT { +} + +template <typename Char> +FMT_CONSTEXPR ansi_color_escape<Char> make_emphasis(emphasis em) FMT_NOEXCEPT { + return ansi_color_escape<Char>(em); +} + +template <typename Char> +inline void fputs(const Char* chars, FILE* stream) FMT_NOEXCEPT { + std::fputs(chars, stream); +} + +template <> +inline void fputs<wchar_t>(const wchar_t* chars, FILE* stream) FMT_NOEXCEPT { + std::fputws(chars, stream); +} + +template <typename Char> inline void reset_color(FILE* stream) FMT_NOEXCEPT { fputs(detail::data::reset_color, stream); -} - -template <> inline void reset_color<wchar_t>(FILE* stream) FMT_NOEXCEPT { +} + +template <> inline void reset_color<wchar_t>(FILE* stream) FMT_NOEXCEPT { fputs(detail::data::wreset_color, stream); -} - -template <typename Char> +} + +template <typename Char> inline void reset_color(buffer<Char>& buffer) FMT_NOEXCEPT { - const char* begin = data::reset_color; - const char* end = begin + sizeof(data::reset_color) - 1; - buffer.append(begin, end); -} - -template <typename Char> + const char* begin = data::reset_color; + const char* end = begin + sizeof(data::reset_color) - 1; + buffer.append(begin, end); +} + +template <typename Char> void vformat_to(buffer<Char>& buf, const text_style& ts, - basic_string_view<Char> format_str, + basic_string_view<Char> format_str, basic_format_args<buffer_context<type_identity_t<Char>>> args) { - bool has_style = false; - if (ts.has_emphasis()) { - has_style = true; + bool has_style = false; + if (ts.has_emphasis()) { + has_style = true; auto emphasis = detail::make_emphasis<Char>(ts.get_emphasis()); - buf.append(emphasis.begin(), emphasis.end()); - } - if (ts.has_foreground()) { - has_style = true; + buf.append(emphasis.begin(), emphasis.end()); + } + if (ts.has_foreground()) { + has_style = true; auto foreground = detail::make_foreground_color<Char>(ts.get_foreground()); - buf.append(foreground.begin(), foreground.end()); - } - if (ts.has_background()) { - has_style = true; + buf.append(foreground.begin(), foreground.end()); + } + if (ts.has_background()) { + has_style = true; auto background = detail::make_background_color<Char>(ts.get_background()); - buf.append(background.begin(), background.end()); - } + buf.append(background.begin(), background.end()); + } detail::vformat_to(buf, format_str, args); if (has_style) detail::reset_color<Char>(buf); -} +} } // namespace detail - -template <typename S, typename Char = char_t<S>> -void vprint(std::FILE* f, const text_style& ts, const S& format, + +template <typename S, typename Char = char_t<S>> +void vprint(std::FILE* f, const text_style& ts, const S& format, basic_format_args<buffer_context<type_identity_t<Char>>> args) { - basic_memory_buffer<Char> buf; + basic_memory_buffer<Char> buf; detail::vformat_to(buf, ts, to_string_view(format), args); - buf.push_back(Char(0)); + buf.push_back(Char(0)); detail::fputs(buf.data(), f); -} - -/** +} + +/** \rst - Formats a string and prints it to the specified file stream using ANSI - escape sequences to specify text formatting. + Formats a string and prints it to the specified file stream using ANSI + escape sequences to specify text formatting. **Example**:: - fmt::print(fmt::emphasis::bold | fg(fmt::color::red), - "Elapsed time: {0:.2f} seconds", 1.23); + fmt::print(fmt::emphasis::bold | fg(fmt::color::red), + "Elapsed time: {0:.2f} seconds", 1.23); \endrst - */ -template <typename S, typename... Args, + */ +template <typename S, typename... Args, FMT_ENABLE_IF(detail::is_string<S>::value)> -void print(std::FILE* f, const text_style& ts, const S& format_str, - const Args&... args) { +void print(std::FILE* f, const text_style& ts, const S& format_str, + const Args&... args) { vprint(f, ts, format_str, fmt::make_args_checked<Args...>(format_str, args...)); -} - -/** - Formats a string and prints it to stdout using ANSI escape sequences to - specify text formatting. - Example: - fmt::print(fmt::emphasis::bold | fg(fmt::color::red), - "Elapsed time: {0:.2f} seconds", 1.23); - */ -template <typename S, typename... Args, +} + +/** + Formats a string and prints it to stdout using ANSI escape sequences to + specify text formatting. + Example: + fmt::print(fmt::emphasis::bold | fg(fmt::color::red), + "Elapsed time: {0:.2f} seconds", 1.23); + */ +template <typename S, typename... Args, FMT_ENABLE_IF(detail::is_string<S>::value)> -void print(const text_style& ts, const S& format_str, const Args&... args) { - return print(stdout, ts, format_str, args...); -} - -template <typename S, typename Char = char_t<S>> -inline std::basic_string<Char> vformat( - const text_style& ts, const S& format_str, - basic_format_args<buffer_context<type_identity_t<Char>>> args) { - basic_memory_buffer<Char> buf; +void print(const text_style& ts, const S& format_str, const Args&... args) { + return print(stdout, ts, format_str, args...); +} + +template <typename S, typename Char = char_t<S>> +inline std::basic_string<Char> vformat( + const text_style& ts, const S& format_str, + basic_format_args<buffer_context<type_identity_t<Char>>> args) { + basic_memory_buffer<Char> buf; detail::vformat_to(buf, ts, to_string_view(format_str), args); - return fmt::to_string(buf); -} - -/** - \rst - Formats arguments and returns the result as a string using ANSI - escape sequences to specify text formatting. - - **Example**:: - - #include <fmt/color.h> - std::string message = fmt::format(fmt::emphasis::bold | fg(fmt::color::red), - "The answer is {}", 42); - \endrst -*/ -template <typename S, typename... Args, typename Char = char_t<S>> -inline std::basic_string<Char> format(const text_style& ts, const S& format_str, - const Args&... args) { - return vformat(ts, to_string_view(format_str), + return fmt::to_string(buf); +} + +/** + \rst + Formats arguments and returns the result as a string using ANSI + escape sequences to specify text formatting. + + **Example**:: + + #include <fmt/color.h> + std::string message = fmt::format(fmt::emphasis::bold | fg(fmt::color::red), + "The answer is {}", 42); + \endrst +*/ +template <typename S, typename... Args, typename Char = char_t<S>> +inline std::basic_string<Char> format(const text_style& ts, const S& format_str, + const Args&... args) { + return vformat(ts, to_string_view(format_str), fmt::make_args_checked<Args...>(format_str, args...)); -} - +} + /** Formats a string with the given text_style and writes the output to ``out``. */ @@ -598,6 +598,6 @@ inline auto format_to(OutputIt out, const text_style& ts, const S& format_str, fmt::make_args_checked<Args...>(format_str, args...)); } -FMT_END_NAMESPACE - -#endif // FMT_COLOR_H_ +FMT_END_NAMESPACE + +#endif // FMT_COLOR_H_ diff --git a/contrib/libs/fmt/include/fmt/compile.h b/contrib/libs/fmt/include/fmt/compile.h index d062988971..3a33b02014 100644 --- a/contrib/libs/fmt/include/fmt/compile.h +++ b/contrib/libs/fmt/include/fmt/compile.h @@ -1,20 +1,20 @@ -// Formatting library for C++ - experimental format string compilation -// -// Copyright (c) 2012 - present, Victor Zverovich and fmt contributors -// All rights reserved. -// -// For the license information refer to format.h. - -#ifndef FMT_COMPILE_H_ -#define FMT_COMPILE_H_ - -#include <vector> - -#include "format.h" - -FMT_BEGIN_NAMESPACE +// Formatting library for C++ - experimental format string compilation +// +// Copyright (c) 2012 - present, Victor Zverovich and fmt contributors +// All rights reserved. +// +// For the license information refer to format.h. + +#ifndef FMT_COMPILE_H_ +#define FMT_COMPILE_H_ + +#include <vector> + +#include "format.h" + +FMT_BEGIN_NAMESPACE namespace detail { - + // A compile-time string which is compiled into fast formatting code. class compiled_string {}; @@ -41,400 +41,400 @@ const T& first(const T& value, const Tail&...) { return value; } -// Part of a compiled format string. It can be either literal text or a -// replacement field. -template <typename Char> struct format_part { - enum class kind { arg_index, arg_name, text, replacement }; - - struct replacement { - arg_ref<Char> arg_id; - dynamic_format_specs<Char> specs; - }; - - kind part_kind; - union value { - int arg_index; - basic_string_view<Char> str; - replacement repl; - - FMT_CONSTEXPR value(int index = 0) : arg_index(index) {} - FMT_CONSTEXPR value(basic_string_view<Char> s) : str(s) {} - FMT_CONSTEXPR value(replacement r) : repl(r) {} - } val; - // Position past the end of the argument id. - const Char* arg_id_end = nullptr; - - FMT_CONSTEXPR format_part(kind k = kind::arg_index, value v = {}) - : part_kind(k), val(v) {} - - static FMT_CONSTEXPR format_part make_arg_index(int index) { - return format_part(kind::arg_index, index); - } - static FMT_CONSTEXPR format_part make_arg_name(basic_string_view<Char> name) { - return format_part(kind::arg_name, name); - } - static FMT_CONSTEXPR format_part make_text(basic_string_view<Char> text) { - return format_part(kind::text, text); - } - static FMT_CONSTEXPR format_part make_replacement(replacement repl) { - return format_part(kind::replacement, repl); - } -}; - -template <typename Char> struct part_counter { - unsigned num_parts = 0; - - FMT_CONSTEXPR void on_text(const Char* begin, const Char* end) { - if (begin != end) ++num_parts; - } - +// Part of a compiled format string. It can be either literal text or a +// replacement field. +template <typename Char> struct format_part { + enum class kind { arg_index, arg_name, text, replacement }; + + struct replacement { + arg_ref<Char> arg_id; + dynamic_format_specs<Char> specs; + }; + + kind part_kind; + union value { + int arg_index; + basic_string_view<Char> str; + replacement repl; + + FMT_CONSTEXPR value(int index = 0) : arg_index(index) {} + FMT_CONSTEXPR value(basic_string_view<Char> s) : str(s) {} + FMT_CONSTEXPR value(replacement r) : repl(r) {} + } val; + // Position past the end of the argument id. + const Char* arg_id_end = nullptr; + + FMT_CONSTEXPR format_part(kind k = kind::arg_index, value v = {}) + : part_kind(k), val(v) {} + + static FMT_CONSTEXPR format_part make_arg_index(int index) { + return format_part(kind::arg_index, index); + } + static FMT_CONSTEXPR format_part make_arg_name(basic_string_view<Char> name) { + return format_part(kind::arg_name, name); + } + static FMT_CONSTEXPR format_part make_text(basic_string_view<Char> text) { + return format_part(kind::text, text); + } + static FMT_CONSTEXPR format_part make_replacement(replacement repl) { + return format_part(kind::replacement, repl); + } +}; + +template <typename Char> struct part_counter { + unsigned num_parts = 0; + + FMT_CONSTEXPR void on_text(const Char* begin, const Char* end) { + if (begin != end) ++num_parts; + } + FMT_CONSTEXPR int on_arg_id() { return ++num_parts, 0; } FMT_CONSTEXPR int on_arg_id(int) { return ++num_parts, 0; } FMT_CONSTEXPR int on_arg_id(basic_string_view<Char>) { return ++num_parts, 0; } - + FMT_CONSTEXPR void on_replacement_field(int, const Char*) {} - + FMT_CONSTEXPR const Char* on_format_specs(int, const Char* begin, - const Char* end) { - // Find the matching brace. - unsigned brace_counter = 0; - for (; begin != end; ++begin) { - if (*begin == '{') { - ++brace_counter; - } else if (*begin == '}') { - if (brace_counter == 0u) break; - --brace_counter; - } - } - return begin; - } - - FMT_CONSTEXPR void on_error(const char*) {} -}; - -// Counts the number of parts in a format string. -template <typename Char> -FMT_CONSTEXPR unsigned count_parts(basic_string_view<Char> format_str) { - part_counter<Char> counter; - parse_format_string<true>(format_str, counter); - return counter.num_parts; -} - -template <typename Char, typename PartHandler> -class format_string_compiler : public error_handler { - private: - using part = format_part<Char>; - - PartHandler handler_; - part part_; - basic_string_view<Char> format_str_; - basic_format_parse_context<Char> parse_context_; - - public: - FMT_CONSTEXPR format_string_compiler(basic_string_view<Char> format_str, - PartHandler handler) - : handler_(handler), - format_str_(format_str), - parse_context_(format_str) {} - - FMT_CONSTEXPR void on_text(const Char* begin, const Char* end) { - if (begin != end) - handler_(part::make_text({begin, to_unsigned(end - begin)})); - } - + const Char* end) { + // Find the matching brace. + unsigned brace_counter = 0; + for (; begin != end; ++begin) { + if (*begin == '{') { + ++brace_counter; + } else if (*begin == '}') { + if (brace_counter == 0u) break; + --brace_counter; + } + } + return begin; + } + + FMT_CONSTEXPR void on_error(const char*) {} +}; + +// Counts the number of parts in a format string. +template <typename Char> +FMT_CONSTEXPR unsigned count_parts(basic_string_view<Char> format_str) { + part_counter<Char> counter; + parse_format_string<true>(format_str, counter); + return counter.num_parts; +} + +template <typename Char, typename PartHandler> +class format_string_compiler : public error_handler { + private: + using part = format_part<Char>; + + PartHandler handler_; + part part_; + basic_string_view<Char> format_str_; + basic_format_parse_context<Char> parse_context_; + + public: + FMT_CONSTEXPR format_string_compiler(basic_string_view<Char> format_str, + PartHandler handler) + : handler_(handler), + format_str_(format_str), + parse_context_(format_str) {} + + FMT_CONSTEXPR void on_text(const Char* begin, const Char* end) { + if (begin != end) + handler_(part::make_text({begin, to_unsigned(end - begin)})); + } + FMT_CONSTEXPR int on_arg_id() { - part_ = part::make_arg_index(parse_context_.next_arg_id()); + part_ = part::make_arg_index(parse_context_.next_arg_id()); return 0; - } - + } + FMT_CONSTEXPR int on_arg_id(int id) { - parse_context_.check_arg_id(id); - part_ = part::make_arg_index(id); + parse_context_.check_arg_id(id); + part_ = part::make_arg_index(id); return 0; - } - + } + FMT_CONSTEXPR int on_arg_id(basic_string_view<Char> id) { - part_ = part::make_arg_name(id); + part_ = part::make_arg_name(id); return 0; - } - + } + FMT_CONSTEXPR void on_replacement_field(int, const Char* ptr) { - part_.arg_id_end = ptr; - handler_(part_); - } - + part_.arg_id_end = ptr; + handler_(part_); + } + FMT_CONSTEXPR const Char* on_format_specs(int, const Char* begin, - const Char* end) { - auto repl = typename part::replacement(); - dynamic_specs_handler<basic_format_parse_context<Char>> handler( - repl.specs, parse_context_); - auto it = parse_format_specs(begin, end, handler); - if (*it != '}') on_error("missing '}' in format string"); - repl.arg_id = part_.part_kind == part::kind::arg_index - ? arg_ref<Char>(part_.val.arg_index) - : arg_ref<Char>(part_.val.str); - auto part = part::make_replacement(repl); - part.arg_id_end = begin; - handler_(part); - return it; - } -}; - -// Compiles a format string and invokes handler(part) for each parsed part. -template <bool IS_CONSTEXPR, typename Char, typename PartHandler> -FMT_CONSTEXPR void compile_format_string(basic_string_view<Char> format_str, - PartHandler handler) { - parse_format_string<IS_CONSTEXPR>( - format_str, - format_string_compiler<Char, PartHandler>(format_str, handler)); -} - + const Char* end) { + auto repl = typename part::replacement(); + dynamic_specs_handler<basic_format_parse_context<Char>> handler( + repl.specs, parse_context_); + auto it = parse_format_specs(begin, end, handler); + if (*it != '}') on_error("missing '}' in format string"); + repl.arg_id = part_.part_kind == part::kind::arg_index + ? arg_ref<Char>(part_.val.arg_index) + : arg_ref<Char>(part_.val.str); + auto part = part::make_replacement(repl); + part.arg_id_end = begin; + handler_(part); + return it; + } +}; + +// Compiles a format string and invokes handler(part) for each parsed part. +template <bool IS_CONSTEXPR, typename Char, typename PartHandler> +FMT_CONSTEXPR void compile_format_string(basic_string_view<Char> format_str, + PartHandler handler) { + parse_format_string<IS_CONSTEXPR>( + format_str, + format_string_compiler<Char, PartHandler>(format_str, handler)); +} + template <typename OutputIt, typename Context, typename Id> -void format_arg( +void format_arg( basic_format_parse_context<typename Context::char_type>& parse_ctx, - Context& ctx, Id arg_id) { + Context& ctx, Id arg_id) { ctx.advance_to(visit_format_arg( arg_formatter<OutputIt, typename Context::char_type>(ctx, &parse_ctx), ctx.arg(arg_id))); -} - -// vformat_to is defined in a subnamespace to prevent ADL. -namespace cf { +} + +// vformat_to is defined in a subnamespace to prevent ADL. +namespace cf { template <typename Context, typename OutputIt, typename CompiledFormat> auto vformat_to(OutputIt out, CompiledFormat& cf, basic_format_args<Context> args) -> typename Context::iterator { - using char_type = typename Context::char_type; - basic_format_parse_context<char_type> parse_ctx( - to_string_view(cf.format_str_)); + using char_type = typename Context::char_type; + basic_format_parse_context<char_type> parse_ctx( + to_string_view(cf.format_str_)); Context ctx(out, args); - - const auto& parts = cf.parts(); - for (auto part_it = std::begin(parts); part_it != std::end(parts); - ++part_it) { - const auto& part = *part_it; - const auto& value = part.val; - - using format_part_t = format_part<char_type>; - switch (part.part_kind) { - case format_part_t::kind::text: { - const auto text = value.str; - auto output = ctx.out(); - auto&& it = reserve(output, text.size()); - it = std::copy_n(text.begin(), text.size(), it); - ctx.advance_to(output); - break; - } - - case format_part_t::kind::arg_index: - advance_to(parse_ctx, part.arg_id_end); + + const auto& parts = cf.parts(); + for (auto part_it = std::begin(parts); part_it != std::end(parts); + ++part_it) { + const auto& part = *part_it; + const auto& value = part.val; + + using format_part_t = format_part<char_type>; + switch (part.part_kind) { + case format_part_t::kind::text: { + const auto text = value.str; + auto output = ctx.out(); + auto&& it = reserve(output, text.size()); + it = std::copy_n(text.begin(), text.size(), it); + ctx.advance_to(output); + break; + } + + case format_part_t::kind::arg_index: + advance_to(parse_ctx, part.arg_id_end); detail::format_arg<OutputIt>(parse_ctx, ctx, value.arg_index); - break; - - case format_part_t::kind::arg_name: - advance_to(parse_ctx, part.arg_id_end); + break; + + case format_part_t::kind::arg_name: + advance_to(parse_ctx, part.arg_id_end); detail::format_arg<OutputIt>(parse_ctx, ctx, value.str); - break; - - case format_part_t::kind::replacement: { - const auto& arg_id_value = value.repl.arg_id.val; - const auto arg = value.repl.arg_id.kind == arg_id_kind::index - ? ctx.arg(arg_id_value.index) - : ctx.arg(arg_id_value.name); - - auto specs = value.repl.specs; - - handle_dynamic_spec<width_checker>(specs.width, specs.width_ref, ctx); - handle_dynamic_spec<precision_checker>(specs.precision, - specs.precision_ref, ctx); - - error_handler h; - numeric_specs_checker<error_handler> checker(h, arg.type()); - if (specs.align == align::numeric) checker.require_numeric_argument(); - if (specs.sign != sign::none) checker.check_sign(); - if (specs.alt) checker.require_numeric_argument(); - if (specs.precision >= 0) checker.check_precision(); - - advance_to(parse_ctx, part.arg_id_end); - ctx.advance_to( + break; + + case format_part_t::kind::replacement: { + const auto& arg_id_value = value.repl.arg_id.val; + const auto arg = value.repl.arg_id.kind == arg_id_kind::index + ? ctx.arg(arg_id_value.index) + : ctx.arg(arg_id_value.name); + + auto specs = value.repl.specs; + + handle_dynamic_spec<width_checker>(specs.width, specs.width_ref, ctx); + handle_dynamic_spec<precision_checker>(specs.precision, + specs.precision_ref, ctx); + + error_handler h; + numeric_specs_checker<error_handler> checker(h, arg.type()); + if (specs.align == align::numeric) checker.require_numeric_argument(); + if (specs.sign != sign::none) checker.check_sign(); + if (specs.alt) checker.require_numeric_argument(); + if (specs.precision >= 0) checker.check_precision(); + + advance_to(parse_ctx, part.arg_id_end); + ctx.advance_to( visit_format_arg(arg_formatter<OutputIt, typename Context::char_type>( ctx, nullptr, &specs), arg)); - break; - } - } - } - return ctx.out(); -} -} // namespace cf - -struct basic_compiled_format {}; - -template <typename S, typename = void> -struct compiled_format_base : basic_compiled_format { - using char_type = char_t<S>; + break; + } + } + } + return ctx.out(); +} +} // namespace cf + +struct basic_compiled_format {}; + +template <typename S, typename = void> +struct compiled_format_base : basic_compiled_format { + using char_type = char_t<S>; using parts_container = std::vector<detail::format_part<char_type>>; - - parts_container compiled_parts; - - explicit compiled_format_base(basic_string_view<char_type> format_str) { - compile_format_string<false>(format_str, - [this](const format_part<char_type>& part) { - compiled_parts.push_back(part); - }); - } - - const parts_container& parts() const { return compiled_parts; } -}; - -template <typename Char, unsigned N> struct format_part_array { - format_part<Char> data[N] = {}; - FMT_CONSTEXPR format_part_array() = default; -}; - -template <typename Char, unsigned N> -FMT_CONSTEXPR format_part_array<Char, N> compile_to_parts( - basic_string_view<Char> format_str) { - format_part_array<Char, N> parts; - unsigned counter = 0; - // This is not a lambda for compatibility with older compilers. - struct { - format_part<Char>* parts; - unsigned* counter; - FMT_CONSTEXPR void operator()(const format_part<Char>& part) { - parts[(*counter)++] = part; - } - } collector{parts.data, &counter}; - compile_format_string<true>(format_str, collector); - if (counter < N) { - parts.data[counter] = - format_part<Char>::make_text(basic_string_view<Char>()); - } - return parts; -} - -template <typename T> constexpr const T& constexpr_max(const T& a, const T& b) { - return (a < b) ? b : a; -} - -template <typename S> -struct compiled_format_base<S, enable_if_t<is_compile_string<S>::value>> - : basic_compiled_format { - using char_type = char_t<S>; - - FMT_CONSTEXPR explicit compiled_format_base(basic_string_view<char_type>) {} - -// Workaround for old compilers. Format string compilation will not be -// performed there anyway. -#if FMT_USE_CONSTEXPR - static FMT_CONSTEXPR_DECL const unsigned num_format_parts = - constexpr_max(count_parts(to_string_view(S())), 1u); -#else - static const unsigned num_format_parts = 1; -#endif - - using parts_container = format_part<char_type>[num_format_parts]; - - const parts_container& parts() const { - static FMT_CONSTEXPR_DECL const auto compiled_parts = - compile_to_parts<char_type, num_format_parts>( + + parts_container compiled_parts; + + explicit compiled_format_base(basic_string_view<char_type> format_str) { + compile_format_string<false>(format_str, + [this](const format_part<char_type>& part) { + compiled_parts.push_back(part); + }); + } + + const parts_container& parts() const { return compiled_parts; } +}; + +template <typename Char, unsigned N> struct format_part_array { + format_part<Char> data[N] = {}; + FMT_CONSTEXPR format_part_array() = default; +}; + +template <typename Char, unsigned N> +FMT_CONSTEXPR format_part_array<Char, N> compile_to_parts( + basic_string_view<Char> format_str) { + format_part_array<Char, N> parts; + unsigned counter = 0; + // This is not a lambda for compatibility with older compilers. + struct { + format_part<Char>* parts; + unsigned* counter; + FMT_CONSTEXPR void operator()(const format_part<Char>& part) { + parts[(*counter)++] = part; + } + } collector{parts.data, &counter}; + compile_format_string<true>(format_str, collector); + if (counter < N) { + parts.data[counter] = + format_part<Char>::make_text(basic_string_view<Char>()); + } + return parts; +} + +template <typename T> constexpr const T& constexpr_max(const T& a, const T& b) { + return (a < b) ? b : a; +} + +template <typename S> +struct compiled_format_base<S, enable_if_t<is_compile_string<S>::value>> + : basic_compiled_format { + using char_type = char_t<S>; + + FMT_CONSTEXPR explicit compiled_format_base(basic_string_view<char_type>) {} + +// Workaround for old compilers. Format string compilation will not be +// performed there anyway. +#if FMT_USE_CONSTEXPR + static FMT_CONSTEXPR_DECL const unsigned num_format_parts = + constexpr_max(count_parts(to_string_view(S())), 1u); +#else + static const unsigned num_format_parts = 1; +#endif + + using parts_container = format_part<char_type>[num_format_parts]; + + const parts_container& parts() const { + static FMT_CONSTEXPR_DECL const auto compiled_parts = + compile_to_parts<char_type, num_format_parts>( detail::to_string_view(S())); - return compiled_parts.data; - } -}; - -template <typename S, typename... Args> -class compiled_format : private compiled_format_base<S> { - public: - using typename compiled_format_base<S>::char_type; - - private: - basic_string_view<char_type> format_str_; - + return compiled_parts.data; + } +}; + +template <typename S, typename... Args> +class compiled_format : private compiled_format_base<S> { + public: + using typename compiled_format_base<S>::char_type; + + private: + basic_string_view<char_type> format_str_; + template <typename Context, typename OutputIt, typename CompiledFormat> friend auto cf::vformat_to(OutputIt out, CompiledFormat& cf, - basic_format_args<Context> args) -> - typename Context::iterator; - - public: - compiled_format() = delete; - explicit constexpr compiled_format(basic_string_view<char_type> format_str) - : compiled_format_base<S>(format_str), format_str_(format_str) {} -}; - -#ifdef __cpp_if_constexpr -template <typename... Args> struct type_list {}; - -// Returns a reference to the argument at index N from [first, rest...]. -template <int N, typename T, typename... Args> + basic_format_args<Context> args) -> + typename Context::iterator; + + public: + compiled_format() = delete; + explicit constexpr compiled_format(basic_string_view<char_type> format_str) + : compiled_format_base<S>(format_str), format_str_(format_str) {} +}; + +#ifdef __cpp_if_constexpr +template <typename... Args> struct type_list {}; + +// Returns a reference to the argument at index N from [first, rest...]. +template <int N, typename T, typename... Args> constexpr const auto& get([[maybe_unused]] const T& first, [[maybe_unused]] const Args&... rest) { - static_assert(N < 1 + sizeof...(Args), "index is out of bounds"); - if constexpr (N == 0) - return first; - else - return get<N - 1>(rest...); -} - -template <int N, typename> struct get_type_impl; - -template <int N, typename... Args> struct get_type_impl<N, type_list<Args...>> { - using type = remove_cvref_t<decltype(get<N>(std::declval<Args>()...))>; -}; - -template <int N, typename T> -using get_type = typename get_type_impl<N, T>::type; - -template <typename T> struct is_compiled_format : std::false_type {}; - -template <typename Char> struct text { - basic_string_view<Char> data; - using char_type = Char; - - template <typename OutputIt, typename... Args> - OutputIt format(OutputIt out, const Args&...) const { + static_assert(N < 1 + sizeof...(Args), "index is out of bounds"); + if constexpr (N == 0) + return first; + else + return get<N - 1>(rest...); +} + +template <int N, typename> struct get_type_impl; + +template <int N, typename... Args> struct get_type_impl<N, type_list<Args...>> { + using type = remove_cvref_t<decltype(get<N>(std::declval<Args>()...))>; +}; + +template <int N, typename T> +using get_type = typename get_type_impl<N, T>::type; + +template <typename T> struct is_compiled_format : std::false_type {}; + +template <typename Char> struct text { + basic_string_view<Char> data; + using char_type = Char; + + template <typename OutputIt, typename... Args> + OutputIt format(OutputIt out, const Args&...) const { return write<Char>(out, data); - } -}; - -template <typename Char> -struct is_compiled_format<text<Char>> : std::true_type {}; - -template <typename Char> -constexpr text<Char> make_text(basic_string_view<Char> s, size_t pos, - size_t size) { - return {{&s[pos], size}}; -} - + } +}; + +template <typename Char> +struct is_compiled_format<text<Char>> : std::true_type {}; + +template <typename Char> +constexpr text<Char> make_text(basic_string_view<Char> s, size_t pos, + size_t size) { + return {{&s[pos], size}}; +} + template <typename Char> struct code_unit { Char value; using char_type = Char; - + template <typename OutputIt, typename... Args> OutputIt format(OutputIt out, const Args&...) const { return write<Char>(out, value); } }; - + template <typename Char> struct is_compiled_format<code_unit<Char>> : std::true_type {}; - -// A replacement field that refers to argument N. -template <typename Char, typename T, int N> struct field { - using char_type = Char; - - template <typename OutputIt, typename... Args> - OutputIt format(OutputIt out, const Args&... args) const { - // This ensures that the argument type is convertile to `const T&`. - const T& arg = get<N>(args...); + +// A replacement field that refers to argument N. +template <typename Char, typename T, int N> struct field { + using char_type = Char; + + template <typename OutputIt, typename... Args> + OutputIt format(OutputIt out, const Args&... args) const { + // This ensures that the argument type is convertile to `const T&`. + const T& arg = get<N>(args...); return write<Char>(out, arg); - } -}; - -template <typename Char, typename T, int N> -struct is_compiled_format<field<Char, T, N>> : std::true_type {}; - + } +}; + +template <typename Char, typename T, int N> +struct is_compiled_format<field<Char, T, N>> : std::true_type {}; + // A replacement field that refers to argument N and has format specifiers. template <typename Char, typename T, int N> struct spec_field { using char_type = Char; @@ -454,54 +454,54 @@ template <typename Char, typename T, int N> struct spec_field { template <typename Char, typename T, int N> struct is_compiled_format<spec_field<Char, T, N>> : std::true_type {}; -template <typename L, typename R> struct concat { - L lhs; - R rhs; - using char_type = typename L::char_type; - - template <typename OutputIt, typename... Args> - OutputIt format(OutputIt out, const Args&... args) const { - out = lhs.format(out, args...); - return rhs.format(out, args...); - } -}; - -template <typename L, typename R> -struct is_compiled_format<concat<L, R>> : std::true_type {}; - -template <typename L, typename R> -constexpr concat<L, R> make_concat(L lhs, R rhs) { - return {lhs, rhs}; -} - -struct unknown_format {}; - -template <typename Char> -constexpr size_t parse_text(basic_string_view<Char> str, size_t pos) { - for (size_t size = str.size(); pos != size; ++pos) { - if (str[pos] == '{' || str[pos] == '}') break; - } - return pos; -} - -template <typename Args, size_t POS, int ID, typename S> -constexpr auto compile_format_string(S format_str); - -template <typename Args, size_t POS, int ID, typename T, typename S> -constexpr auto parse_tail(T head, S format_str) { +template <typename L, typename R> struct concat { + L lhs; + R rhs; + using char_type = typename L::char_type; + + template <typename OutputIt, typename... Args> + OutputIt format(OutputIt out, const Args&... args) const { + out = lhs.format(out, args...); + return rhs.format(out, args...); + } +}; + +template <typename L, typename R> +struct is_compiled_format<concat<L, R>> : std::true_type {}; + +template <typename L, typename R> +constexpr concat<L, R> make_concat(L lhs, R rhs) { + return {lhs, rhs}; +} + +struct unknown_format {}; + +template <typename Char> +constexpr size_t parse_text(basic_string_view<Char> str, size_t pos) { + for (size_t size = str.size(); pos != size; ++pos) { + if (str[pos] == '{' || str[pos] == '}') break; + } + return pos; +} + +template <typename Args, size_t POS, int ID, typename S> +constexpr auto compile_format_string(S format_str); + +template <typename Args, size_t POS, int ID, typename T, typename S> +constexpr auto parse_tail(T head, S format_str) { if constexpr (POS != basic_string_view<typename S::char_type>(format_str).size()) { - constexpr auto tail = compile_format_string<Args, POS, ID>(format_str); - if constexpr (std::is_same<remove_cvref_t<decltype(tail)>, - unknown_format>()) - return tail; - else - return make_concat(head, tail); - } else { - return head; - } -} - + constexpr auto tail = compile_format_string<Args, POS, ID>(format_str); + if constexpr (std::is_same<remove_cvref_t<decltype(tail)>, + unknown_format>()) + return tail; + else + return make_concat(head, tail); + } else { + return head; + } +} + template <typename T, typename Char> struct parse_specs_result { formatter<T, Char> fmt; size_t end; @@ -518,19 +518,19 @@ constexpr parse_specs_result<T, Char> parse_specs(basic_string_view<Char> str, return {f, pos + (end - str.data()) + 1, ctx.next_arg_id()}; } -// Compiles a non-empty format string and returns the compiled representation -// or unknown_format() on unrecognized input. -template <typename Args, size_t POS, int ID, typename S> -constexpr auto compile_format_string(S format_str) { - using char_type = typename S::char_type; - constexpr basic_string_view<char_type> str = format_str; - if constexpr (str[POS] == '{') { - if (POS + 1 == str.size()) - throw format_error("unmatched '{' in format string"); - if constexpr (str[POS + 1] == '{') { - return parse_tail<Args, POS + 2, ID>(make_text(str, POS, 1), format_str); - } else if constexpr (str[POS + 1] == '}') { - using type = get_type<ID, Args>; +// Compiles a non-empty format string and returns the compiled representation +// or unknown_format() on unrecognized input. +template <typename Args, size_t POS, int ID, typename S> +constexpr auto compile_format_string(S format_str) { + using char_type = typename S::char_type; + constexpr basic_string_view<char_type> str = format_str; + if constexpr (str[POS] == '{') { + if (POS + 1 == str.size()) + throw format_error("unmatched '{' in format string"); + if constexpr (str[POS + 1] == '{') { + return parse_tail<Args, POS + 2, ID>(make_text(str, POS, 1), format_str); + } else if constexpr (str[POS + 1] == '}') { + using type = get_type<ID, Args>; return parse_tail<Args, POS + 2, ID + 1>(field<char_type, type, ID>(), format_str); } else if constexpr (str[POS + 1] == ':') { @@ -538,15 +538,15 @@ constexpr auto compile_format_string(S format_str) { constexpr auto result = parse_specs<type>(str, POS + 2, ID); return parse_tail<Args, result.end, result.next_arg_id>( spec_field<char_type, type, ID>{result.fmt}, format_str); - } else { - return unknown_format(); - } - } else if constexpr (str[POS] == '}') { - if (POS + 1 == str.size()) - throw format_error("unmatched '}' in format string"); - return parse_tail<Args, POS + 2, ID>(make_text(str, POS, 1), format_str); - } else { - constexpr auto end = parse_text(str, POS + 1); + } else { + return unknown_format(); + } + } else if constexpr (str[POS] == '}') { + if (POS + 1 == str.size()) + throw format_error("unmatched '}' in format string"); + return parse_tail<Args, POS + 2, ID>(make_text(str, POS, 1), format_str); + } else { + constexpr auto end = parse_text(str, POS + 1); if constexpr (end - POS > 1) { return parse_tail<Args, end, ID>(make_text(str, POS, end - POS), format_str); @@ -554,28 +554,28 @@ constexpr auto compile_format_string(S format_str) { return parse_tail<Args, end, ID>(code_unit<char_type>{str[POS]}, format_str); } - } -} - -template <typename... Args, typename S, + } +} + +template <typename... Args, typename S, FMT_ENABLE_IF(is_compile_string<S>::value || detail::is_compiled_string<S>::value)> -constexpr auto compile(S format_str) { - constexpr basic_string_view<typename S::char_type> str = format_str; - if constexpr (str.size() == 0) { +constexpr auto compile(S format_str) { + constexpr basic_string_view<typename S::char_type> str = format_str; + if constexpr (str.size() == 0) { return detail::make_text(str, 0, 0); - } else { - constexpr auto result = + } else { + constexpr auto result = detail::compile_format_string<detail::type_list<Args...>, 0, 0>( - format_str); - if constexpr (std::is_same<remove_cvref_t<decltype(result)>, + format_str); + if constexpr (std::is_same<remove_cvref_t<decltype(result)>, detail::unknown_format>()) { return detail::compiled_format<S, Args...>(to_string_view(format_str)); - } else { - return result; - } - } -} + } else { + return result; + } + } +} #else template <typename... Args, typename S, FMT_ENABLE_IF(is_compile_string<S>::value)> @@ -583,7 +583,7 @@ constexpr auto compile(S format_str) -> detail::compiled_format<S, Args...> { return detail::compiled_format<S, Args...>(to_string_view(format_str)); } #endif // __cpp_if_constexpr - + // Compiles the format string which must be a string literal. template <typename... Args, typename Char, size_t N> auto compile(const Char (&format_str)[N]) @@ -603,37 +603,37 @@ FMT_DEPRECATED auto compile(const Args&... args) #if FMT_USE_CONSTEXPR # ifdef __cpp_if_constexpr -template <typename CompiledFormat, typename... Args, - typename Char = typename CompiledFormat::char_type, +template <typename CompiledFormat, typename... Args, + typename Char = typename CompiledFormat::char_type, FMT_ENABLE_IF(detail::is_compiled_format<CompiledFormat>::value)> FMT_INLINE std::basic_string<Char> format(const CompiledFormat& cf, const Args&... args) { - basic_memory_buffer<Char> buffer; + basic_memory_buffer<Char> buffer; cf.format(detail::buffer_appender<Char>(buffer), args...); - return to_string(buffer); -} - -template <typename OutputIt, typename CompiledFormat, typename... Args, + return to_string(buffer); +} + +template <typename OutputIt, typename CompiledFormat, typename... Args, FMT_ENABLE_IF(detail::is_compiled_format<CompiledFormat>::value)> -OutputIt format_to(OutputIt out, const CompiledFormat& cf, - const Args&... args) { - return cf.format(out, args...); -} -# endif // __cpp_if_constexpr -#endif // FMT_USE_CONSTEXPR - -template <typename CompiledFormat, typename... Args, - typename Char = typename CompiledFormat::char_type, +OutputIt format_to(OutputIt out, const CompiledFormat& cf, + const Args&... args) { + return cf.format(out, args...); +} +# endif // __cpp_if_constexpr +#endif // FMT_USE_CONSTEXPR + +template <typename CompiledFormat, typename... Args, + typename Char = typename CompiledFormat::char_type, FMT_ENABLE_IF(std::is_base_of<detail::basic_compiled_format, - CompiledFormat>::value)> -std::basic_string<Char> format(const CompiledFormat& cf, const Args&... args) { - basic_memory_buffer<Char> buffer; - using context = buffer_context<Char>; + CompiledFormat>::value)> +std::basic_string<Char> format(const CompiledFormat& cf, const Args&... args) { + basic_memory_buffer<Char> buffer; + using context = buffer_context<Char>; detail::cf::vformat_to<context>(detail::buffer_appender<Char>(buffer), cf, make_format_args<context>(args...)); - return to_string(buffer); -} - + return to_string(buffer); +} + template <typename S, typename... Args, FMT_ENABLE_IF(detail::is_compiled_string<S>::value)> FMT_INLINE std::basic_string<typename S::char_type> format(const S&, @@ -649,17 +649,17 @@ FMT_INLINE std::basic_string<typename S::char_type> format(const S&, return format(compiled, std::forward<Args>(args)...); } -template <typename OutputIt, typename CompiledFormat, typename... Args, +template <typename OutputIt, typename CompiledFormat, typename... Args, FMT_ENABLE_IF(std::is_base_of<detail::basic_compiled_format, - CompiledFormat>::value)> -OutputIt format_to(OutputIt out, const CompiledFormat& cf, - const Args&... args) { - using char_type = typename CompiledFormat::char_type; - using context = format_context_t<OutputIt, char_type>; + CompiledFormat>::value)> +OutputIt format_to(OutputIt out, const CompiledFormat& cf, + const Args&... args) { + using char_type = typename CompiledFormat::char_type; + using context = format_context_t<OutputIt, char_type>; return detail::cf::vformat_to<context>(out, cf, make_format_args<context>(args...)); -} - +} + template <typename OutputIt, typename S, typename... Args, FMT_ENABLE_IF(detail::is_compiled_string<S>::value)> OutputIt format_to(OutputIt out, const S&, const Args&... args) { @@ -676,11 +676,11 @@ auto format_to_n(OutputIt out, size_t n, const CompiledFormat& cf, std::is_base_of<detail::basic_compiled_format, CompiledFormat>::value, format_to_n_result<OutputIt>>::type { - auto it = + auto it = format_to(detail::truncating_iterator<OutputIt>(out, n), cf, args...); - return {it.base(), it.count()}; -} - + return {it.base(), it.count()}; +} + template <typename OutputIt, typename S, typename... Args, FMT_ENABLE_IF(detail::is_compiled_string<S>::value)> format_to_n_result<OutputIt> format_to_n(OutputIt out, size_t n, const S&, @@ -691,11 +691,11 @@ format_to_n_result<OutputIt> format_to_n(OutputIt out, size_t n, const S&, return {it.base(), it.count()}; } -template <typename CompiledFormat, typename... Args> +template <typename CompiledFormat, typename... Args> size_t formatted_size(const CompiledFormat& cf, const Args&... args) { return format_to(detail::counting_iterator(), cf, args...).count(); -} - -FMT_END_NAMESPACE - -#endif // FMT_COMPILE_H_ +} + +FMT_END_NAMESPACE + +#endif // FMT_COMPILE_H_ diff --git a/contrib/libs/fmt/include/fmt/core.h b/contrib/libs/fmt/include/fmt/core.h index 2b568673b0..73a8015822 100644 --- a/contrib/libs/fmt/include/fmt/core.h +++ b/contrib/libs/fmt/include/fmt/core.h @@ -1,63 +1,63 @@ -// Formatting library for C++ - the core API -// -// Copyright (c) 2012 - present, Victor Zverovich -// All rights reserved. -// -// For the license information refer to format.h. - -#ifndef FMT_CORE_H_ -#define FMT_CORE_H_ - -#include <cstdio> // std::FILE -#include <cstring> -#include <functional> -#include <iterator> -#include <memory> -#include <string> -#include <type_traits> -#include <vector> - -// The fmt library version in the form major * 10000 + minor * 100 + patch. +// Formatting library for C++ - the core API +// +// Copyright (c) 2012 - present, Victor Zverovich +// All rights reserved. +// +// For the license information refer to format.h. + +#ifndef FMT_CORE_H_ +#define FMT_CORE_H_ + +#include <cstdio> // std::FILE +#include <cstring> +#include <functional> +#include <iterator> +#include <memory> +#include <string> +#include <type_traits> +#include <vector> + +// The fmt library version in the form major * 10000 + minor * 100 + patch. #define FMT_VERSION 70103 - -#ifdef __clang__ -# define FMT_CLANG_VERSION (__clang_major__ * 100 + __clang_minor__) -#else -# define FMT_CLANG_VERSION 0 -#endif - -#if defined(__GNUC__) && !defined(__clang__) -# define FMT_GCC_VERSION (__GNUC__ * 100 + __GNUC_MINOR__) -#else -# define FMT_GCC_VERSION 0 -#endif - + +#ifdef __clang__ +# define FMT_CLANG_VERSION (__clang_major__ * 100 + __clang_minor__) +#else +# define FMT_CLANG_VERSION 0 +#endif + +#if defined(__GNUC__) && !defined(__clang__) +# define FMT_GCC_VERSION (__GNUC__ * 100 + __GNUC_MINOR__) +#else +# define FMT_GCC_VERSION 0 +#endif + #if defined(__INTEL_COMPILER) # define FMT_ICC_VERSION __INTEL_COMPILER #else # define FMT_ICC_VERSION 0 #endif -#if __cplusplus >= 201103L || defined(__GXX_EXPERIMENTAL_CXX0X__) -# define FMT_HAS_GXX_CXX11 FMT_GCC_VERSION -#else -# define FMT_HAS_GXX_CXX11 0 -#endif - -#ifdef __NVCC__ -# define FMT_NVCC __NVCC__ -#else -# define FMT_NVCC 0 -#endif - -#ifdef _MSC_VER -# define FMT_MSC_VER _MSC_VER +#if __cplusplus >= 201103L || defined(__GXX_EXPERIMENTAL_CXX0X__) +# define FMT_HAS_GXX_CXX11 FMT_GCC_VERSION +#else +# define FMT_HAS_GXX_CXX11 0 +#endif + +#ifdef __NVCC__ +# define FMT_NVCC __NVCC__ +#else +# define FMT_NVCC 0 +#endif + +#ifdef _MSC_VER +# define FMT_MSC_VER _MSC_VER # define FMT_SUPPRESS_MSC_WARNING(n) __pragma(warning(suppress : n)) -#else -# define FMT_MSC_VER 0 +#else +# define FMT_MSC_VER 0 # define FMT_SUPPRESS_MSC_WARNING(n) -#endif - +#endif + #ifdef __has_feature # define FMT_HAS_FEATURE(x) __has_feature(x) #else @@ -83,93 +83,93 @@ #define FMT_HAS_CPP17_ATTRIBUTE(attribute) \ (__cplusplus >= 201703L && FMT_HAS_CPP_ATTRIBUTE(attribute)) -// Check if relaxed C++14 constexpr is supported. -// GCC doesn't allow throw in constexpr until version 6 (bug 67371). -#ifndef FMT_USE_CONSTEXPR -# define FMT_USE_CONSTEXPR \ - (FMT_HAS_FEATURE(cxx_relaxed_constexpr) || FMT_MSC_VER >= 1910 || \ - (FMT_GCC_VERSION >= 600 && __cplusplus >= 201402L)) && \ +// Check if relaxed C++14 constexpr is supported. +// GCC doesn't allow throw in constexpr until version 6 (bug 67371). +#ifndef FMT_USE_CONSTEXPR +# define FMT_USE_CONSTEXPR \ + (FMT_HAS_FEATURE(cxx_relaxed_constexpr) || FMT_MSC_VER >= 1910 || \ + (FMT_GCC_VERSION >= 600 && __cplusplus >= 201402L)) && \ !FMT_NVCC && !FMT_ICC_VERSION -#endif -#if FMT_USE_CONSTEXPR -# define FMT_CONSTEXPR constexpr -# define FMT_CONSTEXPR_DECL constexpr -#else -# define FMT_CONSTEXPR inline -# define FMT_CONSTEXPR_DECL -#endif - -#ifndef FMT_OVERRIDE +#endif +#if FMT_USE_CONSTEXPR +# define FMT_CONSTEXPR constexpr +# define FMT_CONSTEXPR_DECL constexpr +#else +# define FMT_CONSTEXPR inline +# define FMT_CONSTEXPR_DECL +#endif + +#ifndef FMT_OVERRIDE # if FMT_HAS_FEATURE(cxx_override_control) || \ - (FMT_GCC_VERSION >= 408 && FMT_HAS_GXX_CXX11) || FMT_MSC_VER >= 1900 -# define FMT_OVERRIDE override -# else -# define FMT_OVERRIDE -# endif -#endif - -// Check if exceptions are disabled. -#ifndef FMT_EXCEPTIONS -# if (defined(__GNUC__) && !defined(__EXCEPTIONS)) || \ - FMT_MSC_VER && !_HAS_EXCEPTIONS -# define FMT_EXCEPTIONS 0 -# else -# define FMT_EXCEPTIONS 1 -# endif -#endif - -// Define FMT_USE_NOEXCEPT to make fmt use noexcept (C++11 feature). -#ifndef FMT_USE_NOEXCEPT -# define FMT_USE_NOEXCEPT 0 -#endif - -#if FMT_USE_NOEXCEPT || FMT_HAS_FEATURE(cxx_noexcept) || \ - (FMT_GCC_VERSION >= 408 && FMT_HAS_GXX_CXX11) || FMT_MSC_VER >= 1900 -# define FMT_DETECTED_NOEXCEPT noexcept -# define FMT_HAS_CXX11_NOEXCEPT 1 -#else -# define FMT_DETECTED_NOEXCEPT throw() -# define FMT_HAS_CXX11_NOEXCEPT 0 -#endif - -#ifndef FMT_NOEXCEPT -# if FMT_EXCEPTIONS || FMT_HAS_CXX11_NOEXCEPT -# define FMT_NOEXCEPT FMT_DETECTED_NOEXCEPT -# else -# define FMT_NOEXCEPT -# endif -#endif - -// [[noreturn]] is disabled on MSVC and NVCC because of bogus unreachable code -// warnings. -#if FMT_EXCEPTIONS && FMT_HAS_CPP_ATTRIBUTE(noreturn) && !FMT_MSC_VER && \ - !FMT_NVCC -# define FMT_NORETURN [[noreturn]] -#else -# define FMT_NORETURN -#endif - -#ifndef FMT_DEPRECATED -# if FMT_HAS_CPP14_ATTRIBUTE(deprecated) || FMT_MSC_VER >= 1900 -# define FMT_DEPRECATED [[deprecated]] -# else + (FMT_GCC_VERSION >= 408 && FMT_HAS_GXX_CXX11) || FMT_MSC_VER >= 1900 +# define FMT_OVERRIDE override +# else +# define FMT_OVERRIDE +# endif +#endif + +// Check if exceptions are disabled. +#ifndef FMT_EXCEPTIONS +# if (defined(__GNUC__) && !defined(__EXCEPTIONS)) || \ + FMT_MSC_VER && !_HAS_EXCEPTIONS +# define FMT_EXCEPTIONS 0 +# else +# define FMT_EXCEPTIONS 1 +# endif +#endif + +// Define FMT_USE_NOEXCEPT to make fmt use noexcept (C++11 feature). +#ifndef FMT_USE_NOEXCEPT +# define FMT_USE_NOEXCEPT 0 +#endif + +#if FMT_USE_NOEXCEPT || FMT_HAS_FEATURE(cxx_noexcept) || \ + (FMT_GCC_VERSION >= 408 && FMT_HAS_GXX_CXX11) || FMT_MSC_VER >= 1900 +# define FMT_DETECTED_NOEXCEPT noexcept +# define FMT_HAS_CXX11_NOEXCEPT 1 +#else +# define FMT_DETECTED_NOEXCEPT throw() +# define FMT_HAS_CXX11_NOEXCEPT 0 +#endif + +#ifndef FMT_NOEXCEPT +# if FMT_EXCEPTIONS || FMT_HAS_CXX11_NOEXCEPT +# define FMT_NOEXCEPT FMT_DETECTED_NOEXCEPT +# else +# define FMT_NOEXCEPT +# endif +#endif + +// [[noreturn]] is disabled on MSVC and NVCC because of bogus unreachable code +// warnings. +#if FMT_EXCEPTIONS && FMT_HAS_CPP_ATTRIBUTE(noreturn) && !FMT_MSC_VER && \ + !FMT_NVCC +# define FMT_NORETURN [[noreturn]] +#else +# define FMT_NORETURN +#endif + +#ifndef FMT_DEPRECATED +# if FMT_HAS_CPP14_ATTRIBUTE(deprecated) || FMT_MSC_VER >= 1900 +# define FMT_DEPRECATED [[deprecated]] +# else # if (defined(__GNUC__) && !defined(__LCC__)) || defined(__clang__) -# define FMT_DEPRECATED __attribute__((deprecated)) -# elif FMT_MSC_VER -# define FMT_DEPRECATED __declspec(deprecated) -# else -# define FMT_DEPRECATED /* deprecated */ -# endif -# endif -#endif - -// Workaround broken [[deprecated]] in the Intel, PGI and NVCC compilers. +# define FMT_DEPRECATED __attribute__((deprecated)) +# elif FMT_MSC_VER +# define FMT_DEPRECATED __declspec(deprecated) +# else +# define FMT_DEPRECATED /* deprecated */ +# endif +# endif +#endif + +// Workaround broken [[deprecated]] in the Intel, PGI and NVCC compilers. #if FMT_ICC_VERSION || defined(__PGI) || FMT_NVCC -# define FMT_DEPRECATED_ALIAS -#else -# define FMT_DEPRECATED_ALIAS FMT_DEPRECATED -#endif - +# define FMT_DEPRECATED_ALIAS +#else +# define FMT_DEPRECATED_ALIAS FMT_DEPRECATED +#endif + #ifndef FMT_INLINE # if FMT_GCC_VERSION || FMT_CLANG_VERSION # define FMT_INLINE inline __attribute__((always_inline)) @@ -187,25 +187,25 @@ # endif #endif -#ifndef FMT_BEGIN_NAMESPACE +#ifndef FMT_BEGIN_NAMESPACE # if FMT_USE_INLINE_NAMESPACES -# define FMT_INLINE_NAMESPACE inline namespace -# define FMT_END_NAMESPACE \ - } \ - } -# else -# define FMT_INLINE_NAMESPACE namespace -# define FMT_END_NAMESPACE \ - } \ +# define FMT_INLINE_NAMESPACE inline namespace +# define FMT_END_NAMESPACE \ + } \ + } +# else +# define FMT_INLINE_NAMESPACE namespace +# define FMT_END_NAMESPACE \ + } \ using namespace v7; \ - } -# endif -# define FMT_BEGIN_NAMESPACE \ - namespace fmt { \ + } +# endif +# define FMT_BEGIN_NAMESPACE \ + namespace fmt { \ FMT_INLINE_NAMESPACE v7 { -#endif - -#if !defined(FMT_HEADER_ONLY) && defined(_WIN32) +#endif + +#if !defined(FMT_HEADER_ONLY) && defined(_WIN32) # define FMT_CLASS_API FMT_SUPPRESS_MSC_WARNING(4275) # ifdef FMT_EXPORT # define FMT_API __declspec(dllexport) @@ -214,307 +214,307 @@ # elif defined(FMT_SHARED) # define FMT_API __declspec(dllimport) # define FMT_EXTERN_TEMPLATE_API FMT_API -# endif +# endif #else -# define FMT_CLASS_API -#endif -#ifndef FMT_API +# define FMT_CLASS_API +#endif +#ifndef FMT_API # define FMT_API -#endif -#ifndef FMT_EXTERN_TEMPLATE_API -# define FMT_EXTERN_TEMPLATE_API -#endif -#ifndef FMT_INSTANTIATION_DEF_API -# define FMT_INSTANTIATION_DEF_API FMT_API -#endif - -#ifndef FMT_HEADER_ONLY -# define FMT_EXTERN extern -#else -# define FMT_EXTERN -#endif - -// libc++ supports string_view in pre-c++17. -#if (FMT_HAS_INCLUDE(<string_view>) && \ - (__cplusplus > 201402L || defined(_LIBCPP_VERSION))) || \ - (defined(_MSVC_LANG) && _MSVC_LANG > 201402L && _MSC_VER >= 1910) -# include <string_view> -# define FMT_USE_STRING_VIEW -#elif FMT_HAS_INCLUDE("experimental/string_view") && __cplusplus >= 201402L +#endif +#ifndef FMT_EXTERN_TEMPLATE_API +# define FMT_EXTERN_TEMPLATE_API +#endif +#ifndef FMT_INSTANTIATION_DEF_API +# define FMT_INSTANTIATION_DEF_API FMT_API +#endif + +#ifndef FMT_HEADER_ONLY +# define FMT_EXTERN extern +#else +# define FMT_EXTERN +#endif + +// libc++ supports string_view in pre-c++17. +#if (FMT_HAS_INCLUDE(<string_view>) && \ + (__cplusplus > 201402L || defined(_LIBCPP_VERSION))) || \ + (defined(_MSVC_LANG) && _MSVC_LANG > 201402L && _MSC_VER >= 1910) +# include <string_view> +# define FMT_USE_STRING_VIEW +#elif FMT_HAS_INCLUDE("experimental/string_view") && __cplusplus >= 201402L # error #include <experimental/string_view> -# define FMT_USE_EXPERIMENTAL_STRING_VIEW -#endif - -#ifndef FMT_UNICODE -# define FMT_UNICODE !FMT_MSC_VER -#endif -#if FMT_UNICODE && FMT_MSC_VER -# pragma execution_character_set("utf-8") -#endif - -FMT_BEGIN_NAMESPACE - -// Implementations of enable_if_t and other metafunctions for older systems. -template <bool B, class T = void> -using enable_if_t = typename std::enable_if<B, T>::type; -template <bool B, class T, class F> -using conditional_t = typename std::conditional<B, T, F>::type; -template <bool B> using bool_constant = std::integral_constant<bool, B>; -template <typename T> -using remove_reference_t = typename std::remove_reference<T>::type; -template <typename T> -using remove_const_t = typename std::remove_const<T>::type; -template <typename T> -using remove_cvref_t = typename std::remove_cv<remove_reference_t<T>>::type; -template <typename T> struct type_identity { using type = T; }; -template <typename T> using type_identity_t = typename type_identity<T>::type; - -struct monostate {}; - -// An enable_if helper to be used in template parameters which results in much -// shorter symbols: https://godbolt.org/z/sWw4vP. Extra parentheses are needed -// to workaround a bug in MSVC 2019 (see #1140 and #1186). -#define FMT_ENABLE_IF(...) enable_if_t<(__VA_ARGS__), int> = 0 - +# define FMT_USE_EXPERIMENTAL_STRING_VIEW +#endif + +#ifndef FMT_UNICODE +# define FMT_UNICODE !FMT_MSC_VER +#endif +#if FMT_UNICODE && FMT_MSC_VER +# pragma execution_character_set("utf-8") +#endif + +FMT_BEGIN_NAMESPACE + +// Implementations of enable_if_t and other metafunctions for older systems. +template <bool B, class T = void> +using enable_if_t = typename std::enable_if<B, T>::type; +template <bool B, class T, class F> +using conditional_t = typename std::conditional<B, T, F>::type; +template <bool B> using bool_constant = std::integral_constant<bool, B>; +template <typename T> +using remove_reference_t = typename std::remove_reference<T>::type; +template <typename T> +using remove_const_t = typename std::remove_const<T>::type; +template <typename T> +using remove_cvref_t = typename std::remove_cv<remove_reference_t<T>>::type; +template <typename T> struct type_identity { using type = T; }; +template <typename T> using type_identity_t = typename type_identity<T>::type; + +struct monostate {}; + +// An enable_if helper to be used in template parameters which results in much +// shorter symbols: https://godbolt.org/z/sWw4vP. Extra parentheses are needed +// to workaround a bug in MSVC 2019 (see #1140 and #1186). +#define FMT_ENABLE_IF(...) enable_if_t<(__VA_ARGS__), int> = 0 + namespace detail { - + // A helper function to suppress "conditional expression is constant" warnings. template <typename T> constexpr T const_check(T value) { return value; } - -FMT_NORETURN FMT_API void assert_fail(const char* file, int line, - const char* message); - -#ifndef FMT_ASSERT -# ifdef NDEBUG -// FMT_ASSERT is not empty to avoid -Werror=empty-body. -# define FMT_ASSERT(condition, message) ((void)0) -# else -# define FMT_ASSERT(condition, message) \ - ((condition) /* void() fails with -Winvalid-constexpr on clang 4.0.1 */ \ - ? (void)0 \ + +FMT_NORETURN FMT_API void assert_fail(const char* file, int line, + const char* message); + +#ifndef FMT_ASSERT +# ifdef NDEBUG +// FMT_ASSERT is not empty to avoid -Werror=empty-body. +# define FMT_ASSERT(condition, message) ((void)0) +# else +# define FMT_ASSERT(condition, message) \ + ((condition) /* void() fails with -Winvalid-constexpr on clang 4.0.1 */ \ + ? (void)0 \ : ::fmt::detail::assert_fail(__FILE__, __LINE__, (message))) -# endif -#endif - -#if defined(FMT_USE_STRING_VIEW) -template <typename Char> using std_string_view = std::basic_string_view<Char>; -#elif defined(FMT_USE_EXPERIMENTAL_STRING_VIEW) -template <typename Char> -using std_string_view = std::experimental::basic_string_view<Char>; -#else -template <typename T> struct std_string_view {}; -#endif - -#ifdef FMT_USE_INT128 -// Do nothing. +# endif +#endif + +#if defined(FMT_USE_STRING_VIEW) +template <typename Char> using std_string_view = std::basic_string_view<Char>; +#elif defined(FMT_USE_EXPERIMENTAL_STRING_VIEW) +template <typename Char> +using std_string_view = std::experimental::basic_string_view<Char>; +#else +template <typename T> struct std_string_view {}; +#endif + +#ifdef FMT_USE_INT128 +// Do nothing. #elif defined(__SIZEOF_INT128__) && !FMT_NVCC && \ !(FMT_CLANG_VERSION && FMT_MSC_VER) -# define FMT_USE_INT128 1 -using int128_t = __int128_t; -using uint128_t = __uint128_t; -#else -# define FMT_USE_INT128 0 -#endif -#if !FMT_USE_INT128 -struct int128_t {}; -struct uint128_t {}; -#endif - -// Casts a nonnegative integer to unsigned. -template <typename Int> -FMT_CONSTEXPR typename std::make_unsigned<Int>::type to_unsigned(Int value) { - FMT_ASSERT(value >= 0, "negative value"); - return static_cast<typename std::make_unsigned<Int>::type>(value); -} - +# define FMT_USE_INT128 1 +using int128_t = __int128_t; +using uint128_t = __uint128_t; +#else +# define FMT_USE_INT128 0 +#endif +#if !FMT_USE_INT128 +struct int128_t {}; +struct uint128_t {}; +#endif + +// Casts a nonnegative integer to unsigned. +template <typename Int> +FMT_CONSTEXPR typename std::make_unsigned<Int>::type to_unsigned(Int value) { + FMT_ASSERT(value >= 0, "negative value"); + return static_cast<typename std::make_unsigned<Int>::type>(value); +} + FMT_SUPPRESS_MSC_WARNING(4566) constexpr unsigned char micro[] = "\u00B5"; - -template <typename Char> constexpr bool is_unicode() { - return FMT_UNICODE || sizeof(Char) != 1 || - (sizeof(micro) == 3 && micro[0] == 0xC2 && micro[1] == 0xB5); -} - -#ifdef __cpp_char8_t -using char8_type = char8_t; -#else -enum char8_type : unsigned char {}; -#endif + +template <typename Char> constexpr bool is_unicode() { + return FMT_UNICODE || sizeof(Char) != 1 || + (sizeof(micro) == 3 && micro[0] == 0xC2 && micro[1] == 0xB5); +} + +#ifdef __cpp_char8_t +using char8_type = char8_t; +#else +enum char8_type : unsigned char {}; +#endif } // namespace detail - + #ifdef FMT_USE_INTERNAL namespace internal = detail; // DEPRECATED #endif - -/** - An implementation of ``std::basic_string_view`` for pre-C++17. It provides a - subset of the API. ``fmt::basic_string_view`` is used for format strings even - if ``std::string_view`` is available to prevent issues when a library is - compiled with a different ``-std`` option than the client code (which is not - recommended). - */ -template <typename Char> class basic_string_view { - private: - const Char* data_; - size_t size_; - - public: - using value_type = Char; - using iterator = const Char*; - + +/** + An implementation of ``std::basic_string_view`` for pre-C++17. It provides a + subset of the API. ``fmt::basic_string_view`` is used for format strings even + if ``std::string_view`` is available to prevent issues when a library is + compiled with a different ``-std`` option than the client code (which is not + recommended). + */ +template <typename Char> class basic_string_view { + private: + const Char* data_; + size_t size_; + + public: + using value_type = Char; + using iterator = const Char*; + constexpr basic_string_view() FMT_NOEXCEPT : data_(nullptr), size_(0) {} - - /** Constructs a string reference object from a C string and a size. */ + + /** Constructs a string reference object from a C string and a size. */ constexpr basic_string_view(const Char* s, size_t count) FMT_NOEXCEPT - : data_(s), - size_(count) {} - - /** - \rst - Constructs a string reference object from a C string computing - the size with ``std::char_traits<Char>::length``. - \endrst - */ -#if __cplusplus >= 201703L // C++17's char_traits::length() is constexpr. - FMT_CONSTEXPR -#endif - basic_string_view(const Char* s) - : data_(s), size_(std::char_traits<Char>::length(s)) {} - - /** Constructs a string reference from a ``std::basic_string`` object. */ - template <typename Traits, typename Alloc> - FMT_CONSTEXPR basic_string_view( - const std::basic_string<Char, Traits, Alloc>& s) FMT_NOEXCEPT - : data_(s.data()), - size_(s.size()) {} - + : data_(s), + size_(count) {} + + /** + \rst + Constructs a string reference object from a C string computing + the size with ``std::char_traits<Char>::length``. + \endrst + */ +#if __cplusplus >= 201703L // C++17's char_traits::length() is constexpr. + FMT_CONSTEXPR +#endif + basic_string_view(const Char* s) + : data_(s), size_(std::char_traits<Char>::length(s)) {} + + /** Constructs a string reference from a ``std::basic_string`` object. */ + template <typename Traits, typename Alloc> + FMT_CONSTEXPR basic_string_view( + const std::basic_string<Char, Traits, Alloc>& s) FMT_NOEXCEPT + : data_(s.data()), + size_(s.size()) {} + template <typename S, FMT_ENABLE_IF(std::is_same< S, detail::std_string_view<Char>>::value)> - FMT_CONSTEXPR basic_string_view(S s) FMT_NOEXCEPT : data_(s.data()), - size_(s.size()) {} - - /** Returns a pointer to the string data. */ + FMT_CONSTEXPR basic_string_view(S s) FMT_NOEXCEPT : data_(s.data()), + size_(s.size()) {} + + /** Returns a pointer to the string data. */ constexpr const Char* data() const { return data_; } - - /** Returns the string size. */ + + /** Returns the string size. */ constexpr size_t size() const { return size_; } - + constexpr iterator begin() const { return data_; } constexpr iterator end() const { return data_ + size_; } - + constexpr const Char& operator[](size_t pos) const { return data_[pos]; } - - FMT_CONSTEXPR void remove_prefix(size_t n) { - data_ += n; - size_ -= n; - } - - // Lexicographically compare this string reference to other. - int compare(basic_string_view other) const { - size_t str_size = size_ < other.size_ ? size_ : other.size_; - int result = std::char_traits<Char>::compare(data_, other.data_, str_size); - if (result == 0) - result = size_ == other.size_ ? 0 : (size_ < other.size_ ? -1 : 1); - return result; - } - - friend bool operator==(basic_string_view lhs, basic_string_view rhs) { - return lhs.compare(rhs) == 0; - } - friend bool operator!=(basic_string_view lhs, basic_string_view rhs) { - return lhs.compare(rhs) != 0; - } - friend bool operator<(basic_string_view lhs, basic_string_view rhs) { - return lhs.compare(rhs) < 0; - } - friend bool operator<=(basic_string_view lhs, basic_string_view rhs) { - return lhs.compare(rhs) <= 0; - } - friend bool operator>(basic_string_view lhs, basic_string_view rhs) { - return lhs.compare(rhs) > 0; - } - friend bool operator>=(basic_string_view lhs, basic_string_view rhs) { - return lhs.compare(rhs) >= 0; - } -}; - -using string_view = basic_string_view<char>; -using wstring_view = basic_string_view<wchar_t>; - -/** Specifies if ``T`` is a character type. Can be specialized by users. */ -template <typename T> struct is_char : std::false_type {}; -template <> struct is_char<char> : std::true_type {}; -template <> struct is_char<wchar_t> : std::true_type {}; + + FMT_CONSTEXPR void remove_prefix(size_t n) { + data_ += n; + size_ -= n; + } + + // Lexicographically compare this string reference to other. + int compare(basic_string_view other) const { + size_t str_size = size_ < other.size_ ? size_ : other.size_; + int result = std::char_traits<Char>::compare(data_, other.data_, str_size); + if (result == 0) + result = size_ == other.size_ ? 0 : (size_ < other.size_ ? -1 : 1); + return result; + } + + friend bool operator==(basic_string_view lhs, basic_string_view rhs) { + return lhs.compare(rhs) == 0; + } + friend bool operator!=(basic_string_view lhs, basic_string_view rhs) { + return lhs.compare(rhs) != 0; + } + friend bool operator<(basic_string_view lhs, basic_string_view rhs) { + return lhs.compare(rhs) < 0; + } + friend bool operator<=(basic_string_view lhs, basic_string_view rhs) { + return lhs.compare(rhs) <= 0; + } + friend bool operator>(basic_string_view lhs, basic_string_view rhs) { + return lhs.compare(rhs) > 0; + } + friend bool operator>=(basic_string_view lhs, basic_string_view rhs) { + return lhs.compare(rhs) >= 0; + } +}; + +using string_view = basic_string_view<char>; +using wstring_view = basic_string_view<wchar_t>; + +/** Specifies if ``T`` is a character type. Can be specialized by users. */ +template <typename T> struct is_char : std::false_type {}; +template <> struct is_char<char> : std::true_type {}; +template <> struct is_char<wchar_t> : std::true_type {}; template <> struct is_char<detail::char8_type> : std::true_type {}; -template <> struct is_char<char16_t> : std::true_type {}; -template <> struct is_char<char32_t> : std::true_type {}; - -/** - \rst - Returns a string view of `s`. In order to add custom string type support to - {fmt} provide an overload of `to_string_view` for it in the same namespace as - the type for the argument-dependent lookup to work. - - **Example**:: - - namespace my_ns { - inline string_view to_string_view(const my_string& s) { - return {s.data(), s.length()}; - } - } - std::string message = fmt::format(my_string("The answer is {}"), 42); - \endrst - */ -template <typename Char, FMT_ENABLE_IF(is_char<Char>::value)> -inline basic_string_view<Char> to_string_view(const Char* s) { - return s; -} - -template <typename Char, typename Traits, typename Alloc> -inline basic_string_view<Char> to_string_view( - const std::basic_string<Char, Traits, Alloc>& s) { - return s; -} - -template <typename Char> -inline basic_string_view<Char> to_string_view(basic_string_view<Char> s) { - return s; -} - -template <typename Char, +template <> struct is_char<char16_t> : std::true_type {}; +template <> struct is_char<char32_t> : std::true_type {}; + +/** + \rst + Returns a string view of `s`. In order to add custom string type support to + {fmt} provide an overload of `to_string_view` for it in the same namespace as + the type for the argument-dependent lookup to work. + + **Example**:: + + namespace my_ns { + inline string_view to_string_view(const my_string& s) { + return {s.data(), s.length()}; + } + } + std::string message = fmt::format(my_string("The answer is {}"), 42); + \endrst + */ +template <typename Char, FMT_ENABLE_IF(is_char<Char>::value)> +inline basic_string_view<Char> to_string_view(const Char* s) { + return s; +} + +template <typename Char, typename Traits, typename Alloc> +inline basic_string_view<Char> to_string_view( + const std::basic_string<Char, Traits, Alloc>& s) { + return s; +} + +template <typename Char> +inline basic_string_view<Char> to_string_view(basic_string_view<Char> s) { + return s; +} + +template <typename Char, FMT_ENABLE_IF(!std::is_empty<detail::std_string_view<Char>>::value)> inline basic_string_view<Char> to_string_view(detail::std_string_view<Char> s) { - return s; -} - -// A base class for compile-time strings. It is defined in the fmt namespace to + return s; +} + +// A base class for compile-time strings. It is defined in the fmt namespace to // make formatting functions visible via ADL, e.g. format(FMT_STRING("{}"), 42). -struct compile_string {}; - -template <typename S> -struct is_compile_string : std::is_base_of<compile_string, S> {}; - -template <typename S, FMT_ENABLE_IF(is_compile_string<S>::value)> -constexpr basic_string_view<typename S::char_type> to_string_view(const S& s) { - return s; -} - +struct compile_string {}; + +template <typename S> +struct is_compile_string : std::is_base_of<compile_string, S> {}; + +template <typename S, FMT_ENABLE_IF(is_compile_string<S>::value)> +constexpr basic_string_view<typename S::char_type> to_string_view(const S& s) { + return s; +} + namespace detail { -void to_string_view(...); +void to_string_view(...); using fmt::v7::to_string_view; - -// Specifies whether S is a string type convertible to fmt::basic_string_view. -// It should be a constexpr function but MSVC 2017 fails to compile it in -// enable_if and MSVC 2015 fails to compile it as an alias template. -template <typename S> -struct is_string : std::is_class<decltype(to_string_view(std::declval<S>()))> { -}; - -template <typename S, typename = void> struct char_t_impl {}; -template <typename S> struct char_t_impl<S, enable_if_t<is_string<S>::value>> { - using result = decltype(to_string_view(std::declval<S>())); - using type = typename result::value_type; -}; - + +// Specifies whether S is a string type convertible to fmt::basic_string_view. +// It should be a constexpr function but MSVC 2017 fails to compile it in +// enable_if and MSVC 2015 fails to compile it as an alias template. +template <typename S> +struct is_string : std::is_class<decltype(to_string_view(std::declval<S>()))> { +}; + +template <typename S, typename = void> struct char_t_impl {}; +template <typename S> struct char_t_impl<S, enable_if_t<is_string<S>::value>> { + using result = decltype(to_string_view(std::declval<S>())); + using type = typename result::value_type; +}; + // Reports a compile-time error if S is not a valid format string. template <typename..., typename S, FMT_ENABLE_IF(!is_compile_string<S>::value)> FMT_INLINE void check_format_string(const S&) { @@ -527,122 +527,122 @@ FMT_INLINE void check_format_string(const S&) { template <typename..., typename S, FMT_ENABLE_IF(is_compile_string<S>::value)> void check_format_string(S); -struct error_handler { +struct error_handler { constexpr error_handler() = default; constexpr error_handler(const error_handler&) = default; - - // This function is intentionally not constexpr to give a compile-time error. - FMT_NORETURN FMT_API void on_error(const char* message); -}; + + // This function is intentionally not constexpr to give a compile-time error. + FMT_NORETURN FMT_API void on_error(const char* message); +}; } // namespace detail - -/** String's character type. */ + +/** String's character type. */ template <typename S> using char_t = typename detail::char_t_impl<S>::type; - -/** - \rst - Parsing context consisting of a format string range being parsed and an - argument counter for automatic indexing. - - You can use one of the following type aliases for common character types: - - +-----------------------+-------------------------------------+ - | Type | Definition | - +=======================+=====================================+ - | format_parse_context | basic_format_parse_context<char> | - +-----------------------+-------------------------------------+ - | wformat_parse_context | basic_format_parse_context<wchar_t> | - +-----------------------+-------------------------------------+ - \endrst - */ + +/** + \rst + Parsing context consisting of a format string range being parsed and an + argument counter for automatic indexing. + + You can use one of the following type aliases for common character types: + + +-----------------------+-------------------------------------+ + | Type | Definition | + +=======================+=====================================+ + | format_parse_context | basic_format_parse_context<char> | + +-----------------------+-------------------------------------+ + | wformat_parse_context | basic_format_parse_context<wchar_t> | + +-----------------------+-------------------------------------+ + \endrst + */ template <typename Char, typename ErrorHandler = detail::error_handler> -class basic_format_parse_context : private ErrorHandler { - private: - basic_string_view<Char> format_str_; - int next_arg_id_; - - public: - using char_type = Char; - using iterator = typename basic_string_view<Char>::iterator; - +class basic_format_parse_context : private ErrorHandler { + private: + basic_string_view<Char> format_str_; + int next_arg_id_; + + public: + using char_type = Char; + using iterator = typename basic_string_view<Char>::iterator; + explicit constexpr basic_format_parse_context( basic_string_view<Char> format_str, ErrorHandler eh = {}, int next_arg_id = 0) : ErrorHandler(eh), format_str_(format_str), next_arg_id_(next_arg_id) {} - - /** - Returns an iterator to the beginning of the format string range being - parsed. - */ + + /** + Returns an iterator to the beginning of the format string range being + parsed. + */ constexpr iterator begin() const FMT_NOEXCEPT { return format_str_.begin(); } - - /** - Returns an iterator past the end of the format string range being parsed. - */ + + /** + Returns an iterator past the end of the format string range being parsed. + */ constexpr iterator end() const FMT_NOEXCEPT { return format_str_.end(); } - - /** Advances the begin iterator to ``it``. */ - FMT_CONSTEXPR void advance_to(iterator it) { + + /** Advances the begin iterator to ``it``. */ + FMT_CONSTEXPR void advance_to(iterator it) { format_str_.remove_prefix(detail::to_unsigned(it - begin())); - } - - /** - Reports an error if using the manual argument indexing; otherwise returns - the next argument index and switches to the automatic indexing. - */ - FMT_CONSTEXPR int next_arg_id() { + } + + /** + Reports an error if using the manual argument indexing; otherwise returns + the next argument index and switches to the automatic indexing. + */ + FMT_CONSTEXPR int next_arg_id() { // Don't check if the argument id is valid to avoid overhead and because it // will be checked during formatting anyway. - if (next_arg_id_ >= 0) return next_arg_id_++; - on_error("cannot switch from manual to automatic argument indexing"); - return 0; - } - - /** - Reports an error if using the automatic argument indexing; otherwise - switches to the manual indexing. - */ - FMT_CONSTEXPR void check_arg_id(int) { - if (next_arg_id_ > 0) - on_error("cannot switch from automatic to manual argument indexing"); - else - next_arg_id_ = -1; - } - - FMT_CONSTEXPR void check_arg_id(basic_string_view<Char>) {} - - FMT_CONSTEXPR void on_error(const char* message) { - ErrorHandler::on_error(message); - } - + if (next_arg_id_ >= 0) return next_arg_id_++; + on_error("cannot switch from manual to automatic argument indexing"); + return 0; + } + + /** + Reports an error if using the automatic argument indexing; otherwise + switches to the manual indexing. + */ + FMT_CONSTEXPR void check_arg_id(int) { + if (next_arg_id_ > 0) + on_error("cannot switch from automatic to manual argument indexing"); + else + next_arg_id_ = -1; + } + + FMT_CONSTEXPR void check_arg_id(basic_string_view<Char>) {} + + FMT_CONSTEXPR void on_error(const char* message) { + ErrorHandler::on_error(message); + } + constexpr ErrorHandler error_handler() const { return *this; } -}; - -using format_parse_context = basic_format_parse_context<char>; -using wformat_parse_context = basic_format_parse_context<wchar_t>; - -template <typename Context> class basic_format_arg; -template <typename Context> class basic_format_args; +}; + +using format_parse_context = basic_format_parse_context<char>; +using wformat_parse_context = basic_format_parse_context<wchar_t>; + +template <typename Context> class basic_format_arg; +template <typename Context> class basic_format_args; template <typename Context> class dynamic_format_arg_store; - -// A formatter for objects of type T. -template <typename T, typename Char = char, typename Enable = void> -struct formatter { - // A deleted default constructor indicates a disabled formatter. - formatter() = delete; -}; - -// Specifies if T has an enabled formatter specialization. A type can be -// formattable even if it doesn't have a formatter e.g. via a conversion. -template <typename T, typename Context> -using has_formatter = - std::is_constructible<typename Context::template formatter_type<T>>; - + +// A formatter for objects of type T. +template <typename T, typename Char = char, typename Enable = void> +struct formatter { + // A deleted default constructor indicates a disabled formatter. + formatter() = delete; +}; + +// Specifies if T has an enabled formatter specialization. A type can be +// formattable even if it doesn't have a formatter e.g. via a conversion. +template <typename T, typename Context> +using has_formatter = + std::is_constructible<typename Context::template formatter_type<T>>; + // Checks whether T is a container with contiguous storage. template <typename T> struct is_contiguous : std::false_type {}; template <typename Char> struct is_contiguous<std::basic_string<Char>> : std::true_type {}; - + namespace detail { // Extracts a reference to the container from back_insert_iterator. @@ -662,61 +662,61 @@ inline Container& get_container(std::back_insert_iterator<Container> it) { class and shouldn't be used directly, only via `~fmt::basic_memory_buffer`. \endrst */ -template <typename T> class buffer { - private: - T* ptr_; +template <typename T> class buffer { + private: + T* ptr_; size_t size_; size_t capacity_; - - protected: - // Don't initialize ptr_ since it is not accessed to save a few cycles. + + protected: + // Don't initialize ptr_ since it is not accessed to save a few cycles. FMT_SUPPRESS_MSC_WARNING(26495) buffer(size_t sz) FMT_NOEXCEPT : size_(sz), capacity_(sz) {} - + buffer(T* p = nullptr, size_t sz = 0, size_t cap = 0) FMT_NOEXCEPT - : ptr_(p), - size_(sz), - capacity_(cap) {} - + : ptr_(p), + size_(sz), + capacity_(cap) {} + ~buffer() = default; - /** Sets the buffer data and capacity. */ + /** Sets the buffer data and capacity. */ void set(T* buf_data, size_t buf_capacity) FMT_NOEXCEPT { - ptr_ = buf_data; - capacity_ = buf_capacity; - } - - /** Increases the buffer capacity to hold at least *capacity* elements. */ + ptr_ = buf_data; + capacity_ = buf_capacity; + } + + /** Increases the buffer capacity to hold at least *capacity* elements. */ virtual void grow(size_t capacity) = 0; - - public: - using value_type = T; - using const_reference = const T&; - - buffer(const buffer&) = delete; - void operator=(const buffer&) = delete; - - T* begin() FMT_NOEXCEPT { return ptr_; } - T* end() FMT_NOEXCEPT { return ptr_ + size_; } - - const T* begin() const FMT_NOEXCEPT { return ptr_; } - const T* end() const FMT_NOEXCEPT { return ptr_ + size_; } - - /** Returns the size of this buffer. */ + + public: + using value_type = T; + using const_reference = const T&; + + buffer(const buffer&) = delete; + void operator=(const buffer&) = delete; + + T* begin() FMT_NOEXCEPT { return ptr_; } + T* end() FMT_NOEXCEPT { return ptr_ + size_; } + + const T* begin() const FMT_NOEXCEPT { return ptr_; } + const T* end() const FMT_NOEXCEPT { return ptr_ + size_; } + + /** Returns the size of this buffer. */ size_t size() const FMT_NOEXCEPT { return size_; } - - /** Returns the capacity of this buffer. */ + + /** Returns the capacity of this buffer. */ size_t capacity() const FMT_NOEXCEPT { return capacity_; } - - /** Returns a pointer to the buffer data. */ - T* data() FMT_NOEXCEPT { return ptr_; } - - /** Returns a pointer to the buffer data. */ - const T* data() const FMT_NOEXCEPT { return ptr_; } - - /** Clears this buffer. */ - void clear() { size_ = 0; } - + + /** Returns a pointer to the buffer data. */ + T* data() FMT_NOEXCEPT { return ptr_; } + + /** Returns a pointer to the buffer data. */ + const T* data() const FMT_NOEXCEPT { return ptr_; } + + /** Clears this buffer. */ + void clear() { size_ = 0; } + // Tries resizing the buffer to contain *count* elements. If T is a POD type // the new elements may not be initialized. void try_resize(size_t count) { @@ -729,23 +729,23 @@ template <typename T> class buffer { // for at least one additional element either by increasing the capacity or by // flushing the buffer if it is full. void try_reserve(size_t new_capacity) { - if (new_capacity > capacity_) grow(new_capacity); - } - - void push_back(const T& value) { + if (new_capacity > capacity_) grow(new_capacity); + } + + void push_back(const T& value) { try_reserve(size_ + 1); - ptr_[size_++] = value; - } - - /** Appends data to the end of the buffer. */ - template <typename U> void append(const U* begin, const U* end); - - template <typename I> T& operator[](I index) { return ptr_[index]; } - template <typename I> const T& operator[](I index) const { - return ptr_[index]; - } -}; - + ptr_[size_++] = value; + } + + /** Appends data to the end of the buffer. */ + template <typename U> void append(const U* begin, const U* end); + + template <typename I> T& operator[](I index) { return ptr_[index]; } + template <typename I> const T& operator[](I index) const { + return ptr_[index]; + } +}; + struct buffer_traits { explicit buffer_traits(size_t) {} size_t count() const { return 0; } @@ -806,30 +806,30 @@ template <typename T> class iterator_buffer<T*, T> final : public buffer<T> { }; // A buffer that writes to a container with the contiguous storage. -template <typename Container> +template <typename Container> class iterator_buffer<std::back_insert_iterator<Container>, enable_if_t<is_contiguous<Container>::value, typename Container::value_type>> final : public buffer<typename Container::value_type> { - private: - Container& container_; - - protected: + private: + Container& container_; + + protected: void grow(size_t capacity) final FMT_OVERRIDE { - container_.resize(capacity); - this->set(&container_[0], capacity); - } - - public: + container_.resize(capacity); + this->set(&container_[0], capacity); + } + + public: explicit iterator_buffer(Container& c) - : buffer<typename Container::value_type>(c.size()), container_(c) {} + : buffer<typename Container::value_type>(c.size()), container_(c) {} explicit iterator_buffer(std::back_insert_iterator<Container> out, size_t = 0) : iterator_buffer(get_container(out)) {} std::back_insert_iterator<Container> out() { return std::back_inserter(container_); } -}; - +}; + // A buffer that counts the number of code units written discarding the output. template <typename T = char> class counting_buffer final : public buffer<T> { private: @@ -879,11 +879,11 @@ template <typename T> buffer<T>& get_buffer(buffer_appender<T>); template <typename OutputIt> OutputIt get_buffer_init(OutputIt out) { return out; -} +} template <typename T> buffer<T>& get_buffer_init(buffer_appender<T> out) { return get_container(out); } - + template <typename Buffer> auto get_iterator(Buffer& buf) -> decltype(buf.out()) { return buf.out(); @@ -892,18 +892,18 @@ template <typename T> buffer_appender<T> get_iterator(buffer<T>& buf) { return buffer_appender<T>(buf); } -template <typename T, typename Char = char, typename Enable = void> -struct fallback_formatter { - fallback_formatter() = delete; -}; - -// Specifies if T has an enabled fallback_formatter specialization. -template <typename T, typename Context> -using has_fallback_formatter = - std::is_constructible<fallback_formatter<T, typename Context::char_type>>; - +template <typename T, typename Char = char, typename Enable = void> +struct fallback_formatter { + fallback_formatter() = delete; +}; + +// Specifies if T has an enabled fallback_formatter specialization. +template <typename T, typename Context> +using has_fallback_formatter = + std::is_constructible<fallback_formatter<T, typename Context::char_type>>; + struct view {}; - + template <typename Char, typename T> struct named_arg : view { const Char* name; const T& value; @@ -974,100 +974,100 @@ template <typename... Args> constexpr size_t count_named_args() { return count<is_named_arg<Args>::value...>(); } -enum class type { - none_type, - // Integer types should go first, - int_type, - uint_type, - long_long_type, - ulong_long_type, - int128_type, - uint128_type, - bool_type, - char_type, - last_integer_type = char_type, - // followed by floating-point types. - float_type, - double_type, - long_double_type, - last_numeric_type = long_double_type, - cstring_type, - string_type, - pointer_type, - custom_type -}; - -// Maps core type T to the corresponding type enum constant. -template <typename T, typename Char> -struct type_constant : std::integral_constant<type, type::custom_type> {}; - -#define FMT_TYPE_CONSTANT(Type, constant) \ - template <typename Char> \ - struct type_constant<Type, Char> \ - : std::integral_constant<type, type::constant> {} - -FMT_TYPE_CONSTANT(int, int_type); -FMT_TYPE_CONSTANT(unsigned, uint_type); -FMT_TYPE_CONSTANT(long long, long_long_type); -FMT_TYPE_CONSTANT(unsigned long long, ulong_long_type); -FMT_TYPE_CONSTANT(int128_t, int128_type); -FMT_TYPE_CONSTANT(uint128_t, uint128_type); -FMT_TYPE_CONSTANT(bool, bool_type); -FMT_TYPE_CONSTANT(Char, char_type); -FMT_TYPE_CONSTANT(float, float_type); -FMT_TYPE_CONSTANT(double, double_type); -FMT_TYPE_CONSTANT(long double, long_double_type); -FMT_TYPE_CONSTANT(const Char*, cstring_type); -FMT_TYPE_CONSTANT(basic_string_view<Char>, string_type); -FMT_TYPE_CONSTANT(const void*, pointer_type); - +enum class type { + none_type, + // Integer types should go first, + int_type, + uint_type, + long_long_type, + ulong_long_type, + int128_type, + uint128_type, + bool_type, + char_type, + last_integer_type = char_type, + // followed by floating-point types. + float_type, + double_type, + long_double_type, + last_numeric_type = long_double_type, + cstring_type, + string_type, + pointer_type, + custom_type +}; + +// Maps core type T to the corresponding type enum constant. +template <typename T, typename Char> +struct type_constant : std::integral_constant<type, type::custom_type> {}; + +#define FMT_TYPE_CONSTANT(Type, constant) \ + template <typename Char> \ + struct type_constant<Type, Char> \ + : std::integral_constant<type, type::constant> {} + +FMT_TYPE_CONSTANT(int, int_type); +FMT_TYPE_CONSTANT(unsigned, uint_type); +FMT_TYPE_CONSTANT(long long, long_long_type); +FMT_TYPE_CONSTANT(unsigned long long, ulong_long_type); +FMT_TYPE_CONSTANT(int128_t, int128_type); +FMT_TYPE_CONSTANT(uint128_t, uint128_type); +FMT_TYPE_CONSTANT(bool, bool_type); +FMT_TYPE_CONSTANT(Char, char_type); +FMT_TYPE_CONSTANT(float, float_type); +FMT_TYPE_CONSTANT(double, double_type); +FMT_TYPE_CONSTANT(long double, long_double_type); +FMT_TYPE_CONSTANT(const Char*, cstring_type); +FMT_TYPE_CONSTANT(basic_string_view<Char>, string_type); +FMT_TYPE_CONSTANT(const void*, pointer_type); + constexpr bool is_integral_type(type t) { - return t > type::none_type && t <= type::last_integer_type; -} - + return t > type::none_type && t <= type::last_integer_type; +} + constexpr bool is_arithmetic_type(type t) { - return t > type::none_type && t <= type::last_numeric_type; -} - -template <typename Char> struct string_value { - const Char* data; + return t > type::none_type && t <= type::last_numeric_type; +} + +template <typename Char> struct string_value { + const Char* data; size_t size; -}; - +}; + template <typename Char> struct named_arg_value { const named_arg_info<Char>* data; size_t size; }; -template <typename Context> struct custom_value { +template <typename Context> struct custom_value { using parse_context = typename Context::parse_context_type; - const void* value; + const void* value; void (*format)(const void* arg, parse_context& parse_ctx, Context& ctx); -}; - -// A formatting argument value. -template <typename Context> class value { - public: - using char_type = typename Context::char_type; - - union { - int int_value; - unsigned uint_value; - long long long_long_value; - unsigned long long ulong_long_value; - int128_t int128_value; - uint128_t uint128_value; - bool bool_value; - char_type char_value; - float float_value; - double double_value; - long double long_double_value; - const void* pointer; - string_value<char_type> string; - custom_value<Context> custom; +}; + +// A formatting argument value. +template <typename Context> class value { + public: + using char_type = typename Context::char_type; + + union { + int int_value; + unsigned uint_value; + long long long_long_value; + unsigned long long ulong_long_value; + int128_t int128_value; + uint128_t uint128_value; + bool bool_value; + char_type char_value; + float float_value; + double double_value; + long double long_double_value; + const void* pointer; + string_value<char_type> string; + custom_value<Context> custom; named_arg_value<char_type> named_args; - }; - + }; + constexpr FMT_INLINE value(int val = 0) : int_value(val) {} constexpr FMT_INLINE value(unsigned val) : uint_value(val) {} FMT_INLINE value(long long val) : long_long_value(val) {} @@ -1081,304 +1081,304 @@ template <typename Context> class value { FMT_INLINE value(char_type val) : char_value(val) {} FMT_INLINE value(const char_type* val) { string.data = val; } FMT_INLINE value(basic_string_view<char_type> val) { - string.data = val.data(); - string.size = val.size(); - } + string.data = val.data(); + string.size = val.size(); + } FMT_INLINE value(const void* val) : pointer(val) {} FMT_INLINE value(const named_arg_info<char_type>* args, size_t size) : named_args{args, size} {} - + template <typename T> FMT_INLINE value(const T& val) { - custom.value = &val; - // Get the formatter type through the context to allow different contexts - // have different extension points, e.g. `formatter<T>` for `format` and - // `printf_formatter<T>` for `printf`. - custom.format = format_custom_arg< - T, conditional_t<has_formatter<T, Context>::value, - typename Context::template formatter_type<T>, - fallback_formatter<T, char_type>>>; - } - - private: - // Formats an argument of a custom type, such as a user-defined class. - template <typename T, typename Formatter> - static void format_custom_arg(const void* arg, - typename Context::parse_context_type& parse_ctx, - Context& ctx) { - Formatter f; - parse_ctx.advance_to(f.parse(parse_ctx)); - ctx.advance_to(f.format(*static_cast<const T*>(arg), ctx)); - } -}; - -template <typename Context, typename T> -FMT_CONSTEXPR basic_format_arg<Context> make_arg(const T& value); - -// To minimize the number of types we need to deal with, long is translated -// either to int or to long long depending on its size. -enum { long_short = sizeof(long) == sizeof(int) }; -using long_type = conditional_t<long_short, int, long long>; -using ulong_type = conditional_t<long_short, unsigned, unsigned long long>; - + custom.value = &val; + // Get the formatter type through the context to allow different contexts + // have different extension points, e.g. `formatter<T>` for `format` and + // `printf_formatter<T>` for `printf`. + custom.format = format_custom_arg< + T, conditional_t<has_formatter<T, Context>::value, + typename Context::template formatter_type<T>, + fallback_formatter<T, char_type>>>; + } + + private: + // Formats an argument of a custom type, such as a user-defined class. + template <typename T, typename Formatter> + static void format_custom_arg(const void* arg, + typename Context::parse_context_type& parse_ctx, + Context& ctx) { + Formatter f; + parse_ctx.advance_to(f.parse(parse_ctx)); + ctx.advance_to(f.format(*static_cast<const T*>(arg), ctx)); + } +}; + +template <typename Context, typename T> +FMT_CONSTEXPR basic_format_arg<Context> make_arg(const T& value); + +// To minimize the number of types we need to deal with, long is translated +// either to int or to long long depending on its size. +enum { long_short = sizeof(long) == sizeof(int) }; +using long_type = conditional_t<long_short, int, long long>; +using ulong_type = conditional_t<long_short, unsigned, unsigned long long>; + struct unformattable {}; -// Maps formatting arguments to core types. -template <typename Context> struct arg_mapper { - using char_type = typename Context::char_type; - - FMT_CONSTEXPR int map(signed char val) { return val; } - FMT_CONSTEXPR unsigned map(unsigned char val) { return val; } - FMT_CONSTEXPR int map(short val) { return val; } - FMT_CONSTEXPR unsigned map(unsigned short val) { return val; } - FMT_CONSTEXPR int map(int val) { return val; } - FMT_CONSTEXPR unsigned map(unsigned val) { return val; } - FMT_CONSTEXPR long_type map(long val) { return val; } - FMT_CONSTEXPR ulong_type map(unsigned long val) { return val; } - FMT_CONSTEXPR long long map(long long val) { return val; } - FMT_CONSTEXPR unsigned long long map(unsigned long long val) { return val; } - FMT_CONSTEXPR int128_t map(int128_t val) { return val; } - FMT_CONSTEXPR uint128_t map(uint128_t val) { return val; } - FMT_CONSTEXPR bool map(bool val) { return val; } - - template <typename T, FMT_ENABLE_IF(is_char<T>::value)> - FMT_CONSTEXPR char_type map(T val) { - static_assert( - std::is_same<T, char>::value || std::is_same<T, char_type>::value, - "mixing character types is disallowed"); - return val; - } - - FMT_CONSTEXPR float map(float val) { return val; } - FMT_CONSTEXPR double map(double val) { return val; } - FMT_CONSTEXPR long double map(long double val) { return val; } - - FMT_CONSTEXPR const char_type* map(char_type* val) { return val; } - FMT_CONSTEXPR const char_type* map(const char_type* val) { return val; } - template <typename T, FMT_ENABLE_IF(is_string<T>::value)> - FMT_CONSTEXPR basic_string_view<char_type> map(const T& val) { - static_assert(std::is_same<char_type, char_t<T>>::value, - "mixing character types is disallowed"); - return to_string_view(val); - } - template <typename T, - FMT_ENABLE_IF( - std::is_constructible<basic_string_view<char_type>, T>::value && - !is_string<T>::value && !has_formatter<T, Context>::value && - !has_fallback_formatter<T, Context>::value)> - FMT_CONSTEXPR basic_string_view<char_type> map(const T& val) { - return basic_string_view<char_type>(val); - } - template < - typename T, - FMT_ENABLE_IF( - std::is_constructible<std_string_view<char_type>, T>::value && - !std::is_constructible<basic_string_view<char_type>, T>::value && - !is_string<T>::value && !has_formatter<T, Context>::value && - !has_fallback_formatter<T, Context>::value)> - FMT_CONSTEXPR basic_string_view<char_type> map(const T& val) { - return std_string_view<char_type>(val); - } - FMT_CONSTEXPR const char* map(const signed char* val) { - static_assert(std::is_same<char_type, char>::value, "invalid string type"); - return reinterpret_cast<const char*>(val); - } - FMT_CONSTEXPR const char* map(const unsigned char* val) { - static_assert(std::is_same<char_type, char>::value, "invalid string type"); - return reinterpret_cast<const char*>(val); - } - FMT_CONSTEXPR const char* map(signed char* val) { - const auto* const_val = val; - return map(const_val); - } - FMT_CONSTEXPR const char* map(unsigned char* val) { - const auto* const_val = val; - return map(const_val); - } - - FMT_CONSTEXPR const void* map(void* val) { return val; } - FMT_CONSTEXPR const void* map(const void* val) { return val; } - FMT_CONSTEXPR const void* map(std::nullptr_t val) { return val; } - template <typename T> FMT_CONSTEXPR int map(const T*) { - // Formatting of arbitrary pointers is disallowed. If you want to output - // a pointer cast it to "void *" or "const void *". In particular, this - // forbids formatting of "[const] volatile char *" which is printed as bool - // by iostreams. - static_assert(!sizeof(T), "formatting of non-void pointers is disallowed"); - return 0; - } - - template <typename T, - FMT_ENABLE_IF(std::is_enum<T>::value && - !has_formatter<T, Context>::value && - !has_fallback_formatter<T, Context>::value)> - FMT_CONSTEXPR auto map(const T& val) - -> decltype(std::declval<arg_mapper>().map( - static_cast<typename std::underlying_type<T>::type>(val))) { - return map(static_cast<typename std::underlying_type<T>::type>(val)); - } - template <typename T, - FMT_ENABLE_IF(!is_string<T>::value && !is_char<T>::value && - (has_formatter<T, Context>::value || - has_fallback_formatter<T, Context>::value))> - FMT_CONSTEXPR const T& map(const T& val) { - return val; - } - - template <typename T> +// Maps formatting arguments to core types. +template <typename Context> struct arg_mapper { + using char_type = typename Context::char_type; + + FMT_CONSTEXPR int map(signed char val) { return val; } + FMT_CONSTEXPR unsigned map(unsigned char val) { return val; } + FMT_CONSTEXPR int map(short val) { return val; } + FMT_CONSTEXPR unsigned map(unsigned short val) { return val; } + FMT_CONSTEXPR int map(int val) { return val; } + FMT_CONSTEXPR unsigned map(unsigned val) { return val; } + FMT_CONSTEXPR long_type map(long val) { return val; } + FMT_CONSTEXPR ulong_type map(unsigned long val) { return val; } + FMT_CONSTEXPR long long map(long long val) { return val; } + FMT_CONSTEXPR unsigned long long map(unsigned long long val) { return val; } + FMT_CONSTEXPR int128_t map(int128_t val) { return val; } + FMT_CONSTEXPR uint128_t map(uint128_t val) { return val; } + FMT_CONSTEXPR bool map(bool val) { return val; } + + template <typename T, FMT_ENABLE_IF(is_char<T>::value)> + FMT_CONSTEXPR char_type map(T val) { + static_assert( + std::is_same<T, char>::value || std::is_same<T, char_type>::value, + "mixing character types is disallowed"); + return val; + } + + FMT_CONSTEXPR float map(float val) { return val; } + FMT_CONSTEXPR double map(double val) { return val; } + FMT_CONSTEXPR long double map(long double val) { return val; } + + FMT_CONSTEXPR const char_type* map(char_type* val) { return val; } + FMT_CONSTEXPR const char_type* map(const char_type* val) { return val; } + template <typename T, FMT_ENABLE_IF(is_string<T>::value)> + FMT_CONSTEXPR basic_string_view<char_type> map(const T& val) { + static_assert(std::is_same<char_type, char_t<T>>::value, + "mixing character types is disallowed"); + return to_string_view(val); + } + template <typename T, + FMT_ENABLE_IF( + std::is_constructible<basic_string_view<char_type>, T>::value && + !is_string<T>::value && !has_formatter<T, Context>::value && + !has_fallback_formatter<T, Context>::value)> + FMT_CONSTEXPR basic_string_view<char_type> map(const T& val) { + return basic_string_view<char_type>(val); + } + template < + typename T, + FMT_ENABLE_IF( + std::is_constructible<std_string_view<char_type>, T>::value && + !std::is_constructible<basic_string_view<char_type>, T>::value && + !is_string<T>::value && !has_formatter<T, Context>::value && + !has_fallback_formatter<T, Context>::value)> + FMT_CONSTEXPR basic_string_view<char_type> map(const T& val) { + return std_string_view<char_type>(val); + } + FMT_CONSTEXPR const char* map(const signed char* val) { + static_assert(std::is_same<char_type, char>::value, "invalid string type"); + return reinterpret_cast<const char*>(val); + } + FMT_CONSTEXPR const char* map(const unsigned char* val) { + static_assert(std::is_same<char_type, char>::value, "invalid string type"); + return reinterpret_cast<const char*>(val); + } + FMT_CONSTEXPR const char* map(signed char* val) { + const auto* const_val = val; + return map(const_val); + } + FMT_CONSTEXPR const char* map(unsigned char* val) { + const auto* const_val = val; + return map(const_val); + } + + FMT_CONSTEXPR const void* map(void* val) { return val; } + FMT_CONSTEXPR const void* map(const void* val) { return val; } + FMT_CONSTEXPR const void* map(std::nullptr_t val) { return val; } + template <typename T> FMT_CONSTEXPR int map(const T*) { + // Formatting of arbitrary pointers is disallowed. If you want to output + // a pointer cast it to "void *" or "const void *". In particular, this + // forbids formatting of "[const] volatile char *" which is printed as bool + // by iostreams. + static_assert(!sizeof(T), "formatting of non-void pointers is disallowed"); + return 0; + } + + template <typename T, + FMT_ENABLE_IF(std::is_enum<T>::value && + !has_formatter<T, Context>::value && + !has_fallback_formatter<T, Context>::value)> + FMT_CONSTEXPR auto map(const T& val) + -> decltype(std::declval<arg_mapper>().map( + static_cast<typename std::underlying_type<T>::type>(val))) { + return map(static_cast<typename std::underlying_type<T>::type>(val)); + } + template <typename T, + FMT_ENABLE_IF(!is_string<T>::value && !is_char<T>::value && + (has_formatter<T, Context>::value || + has_fallback_formatter<T, Context>::value))> + FMT_CONSTEXPR const T& map(const T& val) { + return val; + } + + template <typename T> FMT_CONSTEXPR auto map(const named_arg<char_type, T>& val) -> decltype(std::declval<arg_mapper>().map(val.value)) { return map(val.value); - } - + } + unformattable map(...) { return {}; } -}; - -// A type constant after applying arg_mapper<Context>. -template <typename T, typename Context> -using mapped_type_constant = - type_constant<decltype(arg_mapper<Context>().map(std::declval<const T&>())), - typename Context::char_type>; - +}; + +// A type constant after applying arg_mapper<Context>. +template <typename T, typename Context> +using mapped_type_constant = + type_constant<decltype(arg_mapper<Context>().map(std::declval<const T&>())), + typename Context::char_type>; + enum { packed_arg_bits = 4 }; -// Maximum number of arguments with packed types. +// Maximum number of arguments with packed types. enum { max_packed_args = 62 / packed_arg_bits }; -enum : unsigned long long { is_unpacked_bit = 1ULL << 63 }; +enum : unsigned long long { is_unpacked_bit = 1ULL << 63 }; enum : unsigned long long { has_named_args_bit = 1ULL << 62 }; } // namespace detail - -// A formatting argument. It is a trivially copyable/constructible type to -// allow storage in basic_memory_buffer. -template <typename Context> class basic_format_arg { - private: + +// A formatting argument. It is a trivially copyable/constructible type to +// allow storage in basic_memory_buffer. +template <typename Context> class basic_format_arg { + private: detail::value<Context> value_; detail::type type_; - - template <typename ContextType, typename T> + + template <typename ContextType, typename T> friend FMT_CONSTEXPR basic_format_arg<ContextType> detail::make_arg( - const T& value); - - template <typename Visitor, typename Ctx> - friend FMT_CONSTEXPR auto visit_format_arg(Visitor&& vis, - const basic_format_arg<Ctx>& arg) - -> decltype(vis(0)); - - friend class basic_format_args<Context>; + const T& value); + + template <typename Visitor, typename Ctx> + friend FMT_CONSTEXPR auto visit_format_arg(Visitor&& vis, + const basic_format_arg<Ctx>& arg) + -> decltype(vis(0)); + + friend class basic_format_args<Context>; friend class dynamic_format_arg_store<Context>; - - using char_type = typename Context::char_type; - + + using char_type = typename Context::char_type; + template <typename T, typename Char, size_t NUM_ARGS, size_t NUM_NAMED_ARGS> friend struct detail::arg_data; basic_format_arg(const detail::named_arg_info<char_type>* args, size_t size) : value_(args, size) {} - public: - class handle { - public: + public: + class handle { + public: explicit handle(detail::custom_value<Context> custom) : custom_(custom) {} - - void format(typename Context::parse_context_type& parse_ctx, - Context& ctx) const { - custom_.format(custom_.value, parse_ctx, ctx); - } - - private: + + void format(typename Context::parse_context_type& parse_ctx, + Context& ctx) const { + custom_.format(custom_.value, parse_ctx, ctx); + } + + private: detail::custom_value<Context> custom_; - }; - + }; + constexpr basic_format_arg() : type_(detail::type::none_type) {} - + constexpr explicit operator bool() const FMT_NOEXCEPT { return type_ != detail::type::none_type; - } - + } + detail::type type() const { return type_; } - + bool is_integral() const { return detail::is_integral_type(type_); } bool is_arithmetic() const { return detail::is_arithmetic_type(type_); } -}; - -/** - \rst - Visits an argument dispatching to the appropriate visit method based on - the argument type. For example, if the argument type is ``double`` then - ``vis(value)`` will be called with the value of type ``double``. - \endrst - */ -template <typename Visitor, typename Context> +}; + +/** + \rst + Visits an argument dispatching to the appropriate visit method based on + the argument type. For example, if the argument type is ``double`` then + ``vis(value)`` will be called with the value of type ``double``. + \endrst + */ +template <typename Visitor, typename Context> FMT_CONSTEXPR_DECL FMT_INLINE auto visit_format_arg( Visitor&& vis, const basic_format_arg<Context>& arg) -> decltype(vis(0)) { - using char_type = typename Context::char_type; - switch (arg.type_) { + using char_type = typename Context::char_type; + switch (arg.type_) { case detail::type::none_type: - break; + break; case detail::type::int_type: - return vis(arg.value_.int_value); + return vis(arg.value_.int_value); case detail::type::uint_type: - return vis(arg.value_.uint_value); + return vis(arg.value_.uint_value); case detail::type::long_long_type: - return vis(arg.value_.long_long_value); + return vis(arg.value_.long_long_value); case detail::type::ulong_long_type: - return vis(arg.value_.ulong_long_value); -#if FMT_USE_INT128 + return vis(arg.value_.ulong_long_value); +#if FMT_USE_INT128 case detail::type::int128_type: - return vis(arg.value_.int128_value); + return vis(arg.value_.int128_value); case detail::type::uint128_type: - return vis(arg.value_.uint128_value); -#else + return vis(arg.value_.uint128_value); +#else case detail::type::int128_type: case detail::type::uint128_type: - break; -#endif + break; +#endif case detail::type::bool_type: - return vis(arg.value_.bool_value); + return vis(arg.value_.bool_value); case detail::type::char_type: - return vis(arg.value_.char_value); + return vis(arg.value_.char_value); case detail::type::float_type: - return vis(arg.value_.float_value); + return vis(arg.value_.float_value); case detail::type::double_type: - return vis(arg.value_.double_value); + return vis(arg.value_.double_value); case detail::type::long_double_type: - return vis(arg.value_.long_double_value); + return vis(arg.value_.long_double_value); case detail::type::cstring_type: - return vis(arg.value_.string.data); + return vis(arg.value_.string.data); case detail::type::string_type: - return vis(basic_string_view<char_type>(arg.value_.string.data, - arg.value_.string.size)); + return vis(basic_string_view<char_type>(arg.value_.string.data, + arg.value_.string.size)); case detail::type::pointer_type: - return vis(arg.value_.pointer); + return vis(arg.value_.pointer); case detail::type::custom_type: - return vis(typename basic_format_arg<Context>::handle(arg.value_.custom)); - } - return vis(monostate()); -} - + return vis(typename basic_format_arg<Context>::handle(arg.value_.custom)); + } + return vis(monostate()); +} + template <typename T> struct formattable : std::false_type {}; - + namespace detail { - + // A workaround for gcc 4.8 to make void_t work in a SFINAE context. template <typename... Ts> struct void_t_impl { using type = void; }; template <typename... Ts> using void_t = typename detail::void_t_impl<Ts...>::type; - + template <typename It, typename T, typename Enable = void> struct is_output_iterator : std::false_type {}; - + template <typename It, typename T> struct is_output_iterator< It, T, void_t<typename std::iterator_traits<It>::iterator_category, decltype(*std::declval<It>() = std::declval<T>())>> : std::true_type {}; - + template <typename OutputIt> struct is_back_insert_iterator : std::false_type {}; template <typename Container> struct is_back_insert_iterator<std::back_insert_iterator<Container>> : std::true_type {}; - + template <typename OutputIt> struct is_contiguous_back_insert_iterator : std::false_type {}; template <typename Container> @@ -1388,36 +1388,36 @@ template <typename Char> struct is_contiguous_back_insert_iterator<buffer_appender<Char>> : std::true_type {}; -// A type-erased reference to an std::locale to avoid heavy <locale> include. -class locale_ref { - private: - const void* locale_; // A type-erased pointer to std::locale. - - public: - locale_ref() : locale_(nullptr) {} - template <typename Locale> explicit locale_ref(const Locale& loc); - - explicit operator bool() const FMT_NOEXCEPT { return locale_ != nullptr; } - - template <typename Locale> Locale get() const; -}; - -template <typename> constexpr unsigned long long encode_types() { return 0; } - -template <typename Context, typename Arg, typename... Args> -constexpr unsigned long long encode_types() { - return static_cast<unsigned>(mapped_type_constant<Arg, Context>::value) | - (encode_types<Context, Args...>() << packed_arg_bits); -} - -template <typename Context, typename T> -FMT_CONSTEXPR basic_format_arg<Context> make_arg(const T& value) { - basic_format_arg<Context> arg; - arg.type_ = mapped_type_constant<T, Context>::value; - arg.value_ = arg_mapper<Context>().map(value); - return arg; -} - +// A type-erased reference to an std::locale to avoid heavy <locale> include. +class locale_ref { + private: + const void* locale_; // A type-erased pointer to std::locale. + + public: + locale_ref() : locale_(nullptr) {} + template <typename Locale> explicit locale_ref(const Locale& loc); + + explicit operator bool() const FMT_NOEXCEPT { return locale_ != nullptr; } + + template <typename Locale> Locale get() const; +}; + +template <typename> constexpr unsigned long long encode_types() { return 0; } + +template <typename Context, typename Arg, typename... Args> +constexpr unsigned long long encode_types() { + return static_cast<unsigned>(mapped_type_constant<Arg, Context>::value) | + (encode_types<Context, Args...>() << packed_arg_bits); +} + +template <typename Context, typename T> +FMT_CONSTEXPR basic_format_arg<Context> make_arg(const T& value) { + basic_format_arg<Context> arg; + arg.type_ = mapped_type_constant<T, Context>::value; + arg.value_ = arg_mapper<Context>().map(value); + return arg; +} + template <typename T> int check(unformattable) { static_assert( formattable<T>(), @@ -1429,148 +1429,148 @@ template <typename T, typename U> inline const U& check(const U& val) { return val; } -// The type template parameter is there to avoid an ODR violation when using -// a fallback formatter in one translation unit and an implicit conversion in -// another (not recommended). -template <bool IS_PACKED, typename Context, type, typename T, - FMT_ENABLE_IF(IS_PACKED)> -inline value<Context> make_arg(const T& val) { +// The type template parameter is there to avoid an ODR violation when using +// a fallback formatter in one translation unit and an implicit conversion in +// another (not recommended). +template <bool IS_PACKED, typename Context, type, typename T, + FMT_ENABLE_IF(IS_PACKED)> +inline value<Context> make_arg(const T& val) { return check<T>(arg_mapper<Context>().map(val)); -} - -template <bool IS_PACKED, typename Context, type, typename T, - FMT_ENABLE_IF(!IS_PACKED)> -inline basic_format_arg<Context> make_arg(const T& value) { - return make_arg<Context>(value); -} - -template <typename T> struct is_reference_wrapper : std::false_type {}; -template <typename T> -struct is_reference_wrapper<std::reference_wrapper<T>> : std::true_type {}; - +} + +template <bool IS_PACKED, typename Context, type, typename T, + FMT_ENABLE_IF(!IS_PACKED)> +inline basic_format_arg<Context> make_arg(const T& value) { + return make_arg<Context>(value); +} + +template <typename T> struct is_reference_wrapper : std::false_type {}; +template <typename T> +struct is_reference_wrapper<std::reference_wrapper<T>> : std::true_type {}; + template <typename T> const T& unwrap(const T& v) { return v; } template <typename T> const T& unwrap(const std::reference_wrapper<T>& v) { return static_cast<const T&>(v); } -class dynamic_arg_list { - // Workaround for clang's -Wweak-vtables. Unlike for regular classes, for - // templates it doesn't complain about inability to deduce single translation - // unit for placing vtable. So storage_node_base is made a fake template. - template <typename = void> struct node { - virtual ~node() = default; - std::unique_ptr<node<>> next; - }; - - template <typename T> struct typed_node : node<> { - T value; - - template <typename Arg> - FMT_CONSTEXPR typed_node(const Arg& arg) : value(arg) {} - - template <typename Char> - FMT_CONSTEXPR typed_node(const basic_string_view<Char>& arg) - : value(arg.data(), arg.size()) {} - }; - - std::unique_ptr<node<>> head_; - - public: - template <typename T, typename Arg> const T& push(const Arg& arg) { +class dynamic_arg_list { + // Workaround for clang's -Wweak-vtables. Unlike for regular classes, for + // templates it doesn't complain about inability to deduce single translation + // unit for placing vtable. So storage_node_base is made a fake template. + template <typename = void> struct node { + virtual ~node() = default; + std::unique_ptr<node<>> next; + }; + + template <typename T> struct typed_node : node<> { + T value; + + template <typename Arg> + FMT_CONSTEXPR typed_node(const Arg& arg) : value(arg) {} + + template <typename Char> + FMT_CONSTEXPR typed_node(const basic_string_view<Char>& arg) + : value(arg.data(), arg.size()) {} + }; + + std::unique_ptr<node<>> head_; + + public: + template <typename T, typename Arg> const T& push(const Arg& arg) { auto new_node = std::unique_ptr<typed_node<T>>(new typed_node<T>(arg)); auto& value = new_node->value; new_node->next = std::move(head_); head_ = std::move(new_node); - return value; - } -}; + return value; + } +}; } // namespace detail - -// Formatting context. -template <typename OutputIt, typename Char> class basic_format_context { - public: - /** The character type for the output. */ - using char_type = Char; - - private: - OutputIt out_; - basic_format_args<basic_format_context> args_; + +// Formatting context. +template <typename OutputIt, typename Char> class basic_format_context { + public: + /** The character type for the output. */ + using char_type = Char; + + private: + OutputIt out_; + basic_format_args<basic_format_context> args_; detail::locale_ref loc_; - - public: - using iterator = OutputIt; - using format_arg = basic_format_arg<basic_format_context>; - using parse_context_type = basic_format_parse_context<Char>; - template <typename T> using formatter_type = formatter<T, char_type>; - - basic_format_context(const basic_format_context&) = delete; - void operator=(const basic_format_context&) = delete; - /** - Constructs a ``basic_format_context`` object. References to the arguments are - stored in the object so make sure they have appropriate lifetimes. - */ - basic_format_context(OutputIt out, - basic_format_args<basic_format_context> ctx_args, + + public: + using iterator = OutputIt; + using format_arg = basic_format_arg<basic_format_context>; + using parse_context_type = basic_format_parse_context<Char>; + template <typename T> using formatter_type = formatter<T, char_type>; + + basic_format_context(const basic_format_context&) = delete; + void operator=(const basic_format_context&) = delete; + /** + Constructs a ``basic_format_context`` object. References to the arguments are + stored in the object so make sure they have appropriate lifetimes. + */ + basic_format_context(OutputIt out, + basic_format_args<basic_format_context> ctx_args, detail::locale_ref loc = detail::locale_ref()) - : out_(out), args_(ctx_args), loc_(loc) {} - - format_arg arg(int id) const { return args_.get(id); } + : out_(out), args_(ctx_args), loc_(loc) {} + + format_arg arg(int id) const { return args_.get(id); } format_arg arg(basic_string_view<char_type> name) { return args_.get(name); } int arg_id(basic_string_view<char_type> name) { return args_.get_id(name); } const basic_format_args<basic_format_context>& args() const { return args_; } - + detail::error_handler error_handler() { return {}; } - void on_error(const char* message) { error_handler().on_error(message); } - - // Returns an iterator to the beginning of the output range. - iterator out() { return out_; } - - // Advances the begin iterator to ``it``. + void on_error(const char* message) { error_handler().on_error(message); } + + // Returns an iterator to the beginning of the output range. + iterator out() { return out_; } + + // Advances the begin iterator to ``it``. void advance_to(iterator it) { if (!detail::is_back_insert_iterator<iterator>()) out_ = it; } - + detail::locale_ref locale() { return loc_; } -}; - -template <typename Char> -using buffer_context = +}; + +template <typename Char> +using buffer_context = basic_format_context<detail::buffer_appender<Char>, Char>; -using format_context = buffer_context<char>; -using wformat_context = buffer_context<wchar_t>; - +using format_context = buffer_context<char>; +using wformat_context = buffer_context<wchar_t>; + // Workaround an alias issue: https://stackoverflow.com/q/62767544/471164. #define FMT_BUFFER_CONTEXT(Char) \ basic_format_context<detail::buffer_appender<Char>, Char> -/** - \rst - An array of references to arguments. It can be implicitly converted into - `~fmt::basic_format_args` for passing into type-erased formatting functions - such as `~fmt::vformat`. - \endrst - */ -template <typename Context, typename... Args> -class format_arg_store -#if FMT_GCC_VERSION && FMT_GCC_VERSION < 409 - // Workaround a GCC template argument substitution bug. - : public basic_format_args<Context> -#endif -{ - private: - static const size_t num_args = sizeof...(Args); +/** + \rst + An array of references to arguments. It can be implicitly converted into + `~fmt::basic_format_args` for passing into type-erased formatting functions + such as `~fmt::vformat`. + \endrst + */ +template <typename Context, typename... Args> +class format_arg_store +#if FMT_GCC_VERSION && FMT_GCC_VERSION < 409 + // Workaround a GCC template argument substitution bug. + : public basic_format_args<Context> +#endif +{ + private: + static const size_t num_args = sizeof...(Args); static const size_t num_named_args = detail::count_named_args<Args...>(); static const bool is_packed = num_args <= detail::max_packed_args; - + using value_type = conditional_t<is_packed, detail::value<Context>, - basic_format_arg<Context>>; - + basic_format_arg<Context>>; + detail::arg_data<value_type, typename Context::char_type, num_args, num_named_args> data_; - - friend class basic_format_args<Context>; - + + friend class basic_format_args<Context>; + static constexpr unsigned long long desc = (is_packed ? detail::encode_types<Context, Args...>() : detail::is_unpacked_bit | num_args) | @@ -1578,35 +1578,35 @@ class format_arg_store ? static_cast<unsigned long long>(detail::has_named_args_bit) : 0); - public: - format_arg_store(const Args&... args) - : -#if FMT_GCC_VERSION && FMT_GCC_VERSION < 409 - basic_format_args<Context>(*this), -#endif + public: + format_arg_store(const Args&... args) + : +#if FMT_GCC_VERSION && FMT_GCC_VERSION < 409 + basic_format_args<Context>(*this), +#endif data_{detail::make_arg< - is_packed, Context, + is_packed, Context, detail::mapped_type_constant<Args, Context>::value>(args)...} { detail::init_named_args(data_.named_args(), 0, 0, args...); - } -}; - -/** - \rst + } +}; + +/** + \rst Constructs a `~fmt::format_arg_store` object that contains references to - arguments and can be implicitly converted to `~fmt::format_args`. `Context` - can be omitted in which case it defaults to `~fmt::context`. - See `~fmt::arg` for lifetime considerations. - \endrst - */ -template <typename Context = format_context, typename... Args> -inline format_arg_store<Context, Args...> make_format_args( - const Args&... args) { - return {args...}; -} - -/** - \rst + arguments and can be implicitly converted to `~fmt::format_args`. `Context` + can be omitted in which case it defaults to `~fmt::context`. + See `~fmt::arg` for lifetime considerations. + \endrst + */ +template <typename Context = format_context, typename... Args> +inline format_arg_store<Context, Args...> make_format_args( + const Args&... args) { + return {args...}; +} + +/** + \rst Constructs a `~fmt::format_arg_store` object that contains references to arguments and can be implicitly converted to `~fmt::format_args`. If ``format_str`` is a compile-time string then `make_args_checked` checks @@ -1646,65 +1646,65 @@ inline detail::named_arg<Char, T> arg(const Char* name, const T& arg) { \rst A dynamic version of `fmt::format_arg_store`. It's equipped with a storage to potentially temporary objects which lifetimes - could be shorter than the format arguments object. - - It can be implicitly converted into `~fmt::basic_format_args` for passing - into type-erased formatting functions such as `~fmt::vformat`. - \endrst - */ -template <typename Context> -class dynamic_format_arg_store -#if FMT_GCC_VERSION && FMT_GCC_VERSION < 409 - // Workaround a GCC template argument substitution bug. - : public basic_format_args<Context> -#endif -{ - private: - using char_type = typename Context::char_type; - - template <typename T> struct need_copy { + could be shorter than the format arguments object. + + It can be implicitly converted into `~fmt::basic_format_args` for passing + into type-erased formatting functions such as `~fmt::vformat`. + \endrst + */ +template <typename Context> +class dynamic_format_arg_store +#if FMT_GCC_VERSION && FMT_GCC_VERSION < 409 + // Workaround a GCC template argument substitution bug. + : public basic_format_args<Context> +#endif +{ + private: + using char_type = typename Context::char_type; + + template <typename T> struct need_copy { static constexpr detail::type mapped_type = detail::mapped_type_constant<T, Context>::value; - - enum { + + enum { value = !(detail::is_reference_wrapper<T>::value || - std::is_same<T, basic_string_view<char_type>>::value || + std::is_same<T, basic_string_view<char_type>>::value || std::is_same<T, detail::std_string_view<char_type>>::value || (mapped_type != detail::type::cstring_type && mapped_type != detail::type::string_type && mapped_type != detail::type::custom_type)) - }; - }; - - template <typename T> + }; + }; + + template <typename T> using stored_type = conditional_t<detail::is_string<T>::value, - std::basic_string<char_type>, T>; - - // Storage of basic_format_arg must be contiguous. - std::vector<basic_format_arg<Context>> data_; + std::basic_string<char_type>, T>; + + // Storage of basic_format_arg must be contiguous. + std::vector<basic_format_arg<Context>> data_; std::vector<detail::named_arg_info<char_type>> named_info_; - - // Storage of arguments not fitting into basic_format_arg must grow - // without relocation because items in data_ refer to it. + + // Storage of arguments not fitting into basic_format_arg must grow + // without relocation because items in data_ refer to it. detail::dynamic_arg_list dynamic_args_; - - friend class basic_format_args<Context>; - - unsigned long long get_types() const { + + friend class basic_format_args<Context>; + + unsigned long long get_types() const { return detail::is_unpacked_bit | data_.size() | (named_info_.empty() ? 0ULL : static_cast<unsigned long long>(detail::has_named_args_bit)); - } - + } + const basic_format_arg<Context>* data() const { return named_info_.empty() ? data_.data() : data_.data() + 1; } - template <typename T> void emplace_arg(const T& arg) { + template <typename T> void emplace_arg(const T& arg) { data_.emplace_back(detail::make_arg<Context>(arg)); - } - + } + template <typename T> void emplace_arg(const detail::named_arg<char_type, T>& arg) { if (named_info_.empty()) { @@ -1722,34 +1722,34 @@ class dynamic_format_arg_store guard.release(); } - public: - /** - \rst + public: + /** + \rst Adds an argument into the dynamic store for later passing to a formatting - function. - + function. + Note that custom types and string types (but not string views) are copied into the store dynamically allocating memory if necessary. - - **Example**:: - - fmt::dynamic_format_arg_store<fmt::format_context> store; - store.push_back(42); - store.push_back("abc"); - store.push_back(1.5f); - std::string result = fmt::vformat("{} and {} and {}", store); - \endrst - */ - template <typename T> void push_back(const T& arg) { + + **Example**:: + + fmt::dynamic_format_arg_store<fmt::format_context> store; + store.push_back(42); + store.push_back("abc"); + store.push_back(1.5f); + std::string result = fmt::vformat("{} and {} and {}", store); + \endrst + */ + template <typename T> void push_back(const T& arg) { if (detail::const_check(need_copy<T>::value)) - emplace_arg(dynamic_args_.push<stored_type<T>>(arg)); - else + emplace_arg(dynamic_args_.push<stored_type<T>>(arg)); + else emplace_arg(detail::unwrap(arg)); - } - - /** + } + + /** \rst - Adds a reference to the argument into the dynamic store for later passing to + Adds a reference to the argument into the dynamic store for later passing to a formatting function. Supports named arguments wrapped in ``std::reference_wrapper`` via ``std::ref()``/``std::cref()``. @@ -1768,14 +1768,14 @@ class dynamic_format_arg_store std::string result = fmt::vformat("{} and {a1_}"); assert(result == "X234567890 and 42"); \endrst - */ - template <typename T> void push_back(std::reference_wrapper<T> arg) { - static_assert( + */ + template <typename T> void push_back(std::reference_wrapper<T> arg) { + static_assert( detail::is_named_arg<typename std::remove_cv<T>::type>::value || need_copy<T>::value, - "objects of built-in types and string views are always copied"); - emplace_arg(arg.get()); - } + "objects of built-in types and string views are always copied"); + emplace_arg(arg.get()); + } /** Adds named argument into the dynamic store for later passing to a formatting @@ -1813,86 +1813,86 @@ class dynamic_format_arg_store data_.reserve(new_cap); named_info_.reserve(new_cap_named); } -}; - -/** - \rst - A view of a collection of formatting arguments. To avoid lifetime issues it - should only be used as a parameter type in type-erased functions such as - ``vformat``:: - - void vlog(string_view format_str, format_args args); // OK - format_args args = make_format_args(42); // Error: dangling reference - \endrst - */ -template <typename Context> class basic_format_args { - public: - using size_type = int; - using format_arg = basic_format_arg<Context>; - - private: +}; + +/** + \rst + A view of a collection of formatting arguments. To avoid lifetime issues it + should only be used as a parameter type in type-erased functions such as + ``vformat``:: + + void vlog(string_view format_str, format_args args); // OK + format_args args = make_format_args(42); // Error: dangling reference + \endrst + */ +template <typename Context> class basic_format_args { + public: + using size_type = int; + using format_arg = basic_format_arg<Context>; + + private: // A descriptor that contains information about formatting arguments. // If the number of arguments is less or equal to max_packed_args then // argument types are passed in the descriptor. This reduces binary code size // per formatting function call. unsigned long long desc_; - union { + union { // If is_packed() returns true then argument values are stored in values_; // otherwise they are stored in args_. This is done to improve cache // locality and reduce compiled code size since storing larger objects - // may require more code (at least on x86-64) even if the same amount of - // data is actually copied to stack. It saves ~10% on the bloat test. + // may require more code (at least on x86-64) even if the same amount of + // data is actually copied to stack. It saves ~10% on the bloat test. const detail::value<Context>* values_; - const format_arg* args_; - }; - + const format_arg* args_; + }; + bool is_packed() const { return (desc_ & detail::is_unpacked_bit) == 0; } bool has_named_args() const { return (desc_ & detail::has_named_args_bit) != 0; } - + detail::type type(int index) const { int shift = index * detail::packed_arg_bits; unsigned int mask = (1 << detail::packed_arg_bits) - 1; return static_cast<detail::type>((desc_ >> shift) & mask); - } - + } + basic_format_args(unsigned long long desc, const detail::value<Context>* values) : desc_(desc), values_(values) {} basic_format_args(unsigned long long desc, const format_arg* args) : desc_(desc), args_(args) {} - - public: + + public: basic_format_args() : desc_(0) {} - - /** - \rst - Constructs a `basic_format_args` object from `~fmt::format_arg_store`. - \endrst - */ - template <typename... Args> + + /** + \rst + Constructs a `basic_format_args` object from `~fmt::format_arg_store`. + \endrst + */ + template <typename... Args> FMT_INLINE basic_format_args(const format_arg_store<Context, Args...>& store) : basic_format_args(store.desc, store.data_.args()) {} - - /** - \rst - Constructs a `basic_format_args` object from - `~fmt::dynamic_format_arg_store`. - \endrst - */ + + /** + \rst + Constructs a `basic_format_args` object from + `~fmt::dynamic_format_arg_store`. + \endrst + */ FMT_INLINE basic_format_args(const dynamic_format_arg_store<Context>& store) : basic_format_args(store.get_types(), store.data()) {} - - /** - \rst - Constructs a `basic_format_args` object from a dynamic set of arguments. - \endrst - */ - basic_format_args(const format_arg* args, int count) + + /** + \rst + Constructs a `basic_format_args` object from a dynamic set of arguments. + \endrst + */ + basic_format_args(const format_arg* args, int count) : basic_format_args(detail::is_unpacked_bit | detail::to_unsigned(count), args) {} - + /** Returns the argument with the specified id. */ format_arg get(int id) const { format_arg arg; @@ -1904,9 +1904,9 @@ template <typename Context> class basic_format_args { arg.type_ = type(id); if (arg.type_ == detail::type::none_type) return arg; arg.value_ = values_[id]; - return arg; - } - + return arg; + } + template <typename Char> format_arg get(basic_string_view<Char> name) const { int id = get_id(name); return id >= 0 ? get(id) : format_arg(); @@ -1922,13 +1922,13 @@ template <typename Context> class basic_format_args { return -1; } - int max_size() const { + int max_size() const { unsigned long long max_packed = detail::max_packed_args; - return static_cast<int>(is_packed() ? max_packed + return static_cast<int>(is_packed() ? max_packed : desc_ & ~detail::is_unpacked_bit); - } -}; - + } +}; + #ifdef FMT_ARM_ABI_COMPATIBILITY /** An alias to ``basic_format_args<format_context>``. */ // Separate types would result in shorter symbols but break ABI compatibility @@ -1937,41 +1937,41 @@ using format_args = basic_format_args<format_context>; using wformat_args = basic_format_args<wformat_context>; #else // DEPRECATED! These are kept for ABI compatibility. -// It is a separate type rather than an alias to make symbols readable. -struct format_args : basic_format_args<format_context> { - template <typename... Args> +// It is a separate type rather than an alias to make symbols readable. +struct format_args : basic_format_args<format_context> { + template <typename... Args> FMT_INLINE format_args(const Args&... args) : basic_format_args(args...) {} -}; -struct wformat_args : basic_format_args<wformat_context> { +}; +struct wformat_args : basic_format_args<wformat_context> { using basic_format_args::basic_format_args; -}; -#endif - +}; +#endif + namespace detail { - + template <typename Char, FMT_ENABLE_IF(!std::is_same<Char, char>::value)> -std::basic_string<Char> vformat( - basic_string_view<Char> format_str, - basic_format_args<buffer_context<type_identity_t<Char>>> args); - +std::basic_string<Char> vformat( + basic_string_view<Char> format_str, + basic_format_args<buffer_context<type_identity_t<Char>>> args); + FMT_API std::string vformat(string_view format_str, format_args args); -template <typename Char> +template <typename Char> void vformat_to( - buffer<Char>& buf, basic_string_view<Char> format_str, + buffer<Char>& buf, basic_string_view<Char> format_str, basic_format_args<FMT_BUFFER_CONTEXT(type_identity_t<Char>)> args, detail::locale_ref loc = {}); - -template <typename Char, typename Args, - FMT_ENABLE_IF(!std::is_same<Char, char>::value)> -inline void vprint_mojibake(std::FILE*, basic_string_view<Char>, const Args&) {} - -FMT_API void vprint_mojibake(std::FILE*, string_view, format_args); -#ifndef _WIN32 -inline void vprint_mojibake(std::FILE*, string_view, format_args) {} -#endif + +template <typename Char, typename Args, + FMT_ENABLE_IF(!std::is_same<Char, char>::value)> +inline void vprint_mojibake(std::FILE*, basic_string_view<Char>, const Args&) {} + +FMT_API void vprint_mojibake(std::FILE*, string_view, format_args); +#ifndef _WIN32 +inline void vprint_mojibake(std::FILE*, string_view, format_args) {} +#endif } // namespace detail - + /** Formats a string and writes the output to ``out``. */ // GCC 8 and earlier cannot handle std::back_insert_iterator<Container> with // vformat_to<ArgFormatter>(...) overload, so SFINAE on iterator type instead. @@ -1985,17 +1985,17 @@ auto vformat_to(OutputIt out, const S& format_str, return detail::get_iterator(buf); } -/** +/** \rst Formats arguments, writes the result to the output iterator ``out`` and returns the iterator past the end of the output range. - + **Example**:: - + std::vector<char> out; fmt::format_to(std::back_inserter(out), "{}", 42); \endrst - */ + */ // We cannot use FMT_ENABLE_IF because of a bug in gcc 8.3. template <typename OutputIt, typename S, typename... Args, bool enable = detail::is_output_iterator<OutputIt, char_t<S>>::value> @@ -2003,26 +2003,26 @@ inline auto format_to(OutputIt out, const S& format_str, Args&&... args) -> typename std::enable_if<enable, OutputIt>::type { const auto& vargs = fmt::make_args_checked<Args...>(format_str, args...); return vformat_to(out, to_string_view(format_str), vargs); -} - +} + template <typename OutputIt> struct format_to_n_result { /** Iterator past the end of the output range. */ OutputIt out; /** Total (not truncated) output size. */ size_t size; }; - + template <typename OutputIt, typename Char, typename... Args, FMT_ENABLE_IF(detail::is_output_iterator<OutputIt, Char>::value)> inline format_to_n_result<OutputIt> vformat_to_n( OutputIt out, size_t n, basic_string_view<Char> format_str, - basic_format_args<buffer_context<type_identity_t<Char>>> args) { + basic_format_args<buffer_context<type_identity_t<Char>>> args) { detail::iterator_buffer<OutputIt, Char, detail::fixed_buffer_traits> buf(out, n); detail::vformat_to(buf, format_str, args); return {buf.out(), buf.count()}; -} - +} + /** \rst Formats arguments, writes up to ``n`` characters of the result to the output @@ -2037,8 +2037,8 @@ inline auto format_to_n(OutputIt out, size_t n, const S& format_str, typename std::enable_if<enable, format_to_n_result<OutputIt>>::type { const auto& vargs = fmt::make_args_checked<Args...>(format_str, args...); return vformat_to_n(out, n, to_string_view(format_str), vargs); -} - +} + /** Returns the number of characters in the output of ``format(format_str, args...)``. @@ -2051,72 +2051,72 @@ inline size_t formatted_size(string_view format_str, Args&&... args) { return buf.count(); } -template <typename S, typename Char = char_t<S>> +template <typename S, typename Char = char_t<S>> FMT_INLINE std::basic_string<Char> vformat( - const S& format_str, - basic_format_args<buffer_context<type_identity_t<Char>>> args) { + const S& format_str, + basic_format_args<buffer_context<type_identity_t<Char>>> args) { return detail::vformat(to_string_view(format_str), args); -} - -/** - \rst - Formats arguments and returns the result as a string. - - **Example**:: - - #include <fmt/core.h> - std::string message = fmt::format("The answer is {}", 42); - \endrst -*/ -// Pass char_t as a default template parameter instead of using -// std::basic_string<char_t<S>> to reduce the symbol size. -template <typename S, typename... Args, typename Char = char_t<S>> +} + +/** + \rst + Formats arguments and returns the result as a string. + + **Example**:: + + #include <fmt/core.h> + std::string message = fmt::format("The answer is {}", 42); + \endrst +*/ +// Pass char_t as a default template parameter instead of using +// std::basic_string<char_t<S>> to reduce the symbol size. +template <typename S, typename... Args, typename Char = char_t<S>> FMT_INLINE std::basic_string<Char> format(const S& format_str, Args&&... args) { const auto& vargs = fmt::make_args_checked<Args...>(format_str, args...); return detail::vformat(to_string_view(format_str), vargs); -} - -FMT_API void vprint(string_view, format_args); -FMT_API void vprint(std::FILE*, string_view, format_args); - -/** - \rst - Formats ``args`` according to specifications in ``format_str`` and writes the - output to the file ``f``. Strings are assumed to be Unicode-encoded unless the - ``FMT_UNICODE`` macro is set to 0. - - **Example**:: - - fmt::print(stderr, "Don't {}!", "panic"); - \endrst - */ -template <typename S, typename... Args, typename Char = char_t<S>> -inline void print(std::FILE* f, const S& format_str, Args&&... args) { +} + +FMT_API void vprint(string_view, format_args); +FMT_API void vprint(std::FILE*, string_view, format_args); + +/** + \rst + Formats ``args`` according to specifications in ``format_str`` and writes the + output to the file ``f``. Strings are assumed to be Unicode-encoded unless the + ``FMT_UNICODE`` macro is set to 0. + + **Example**:: + + fmt::print(stderr, "Don't {}!", "panic"); + \endrst + */ +template <typename S, typename... Args, typename Char = char_t<S>> +inline void print(std::FILE* f, const S& format_str, Args&&... args) { const auto& vargs = fmt::make_args_checked<Args...>(format_str, args...); return detail::is_unicode<Char>() ? vprint(f, to_string_view(format_str), vargs) : detail::vprint_mojibake(f, to_string_view(format_str), vargs); -} - -/** - \rst - Formats ``args`` according to specifications in ``format_str`` and writes - the output to ``stdout``. Strings are assumed to be Unicode-encoded unless - the ``FMT_UNICODE`` macro is set to 0. - - **Example**:: - - fmt::print("Elapsed time: {0:.2f} seconds", 1.23); - \endrst - */ -template <typename S, typename... Args, typename Char = char_t<S>> -inline void print(const S& format_str, Args&&... args) { +} + +/** + \rst + Formats ``args`` according to specifications in ``format_str`` and writes + the output to ``stdout``. Strings are assumed to be Unicode-encoded unless + the ``FMT_UNICODE`` macro is set to 0. + + **Example**:: + + fmt::print("Elapsed time: {0:.2f} seconds", 1.23); + \endrst + */ +template <typename S, typename... Args, typename Char = char_t<S>> +inline void print(const S& format_str, Args&&... args) { const auto& vargs = fmt::make_args_checked<Args...>(format_str, args...); return detail::is_unicode<Char>() ? vprint(to_string_view(format_str), vargs) : detail::vprint_mojibake(stdout, to_string_view(format_str), vargs); -} -FMT_END_NAMESPACE - -#endif // FMT_CORE_H_ +} +FMT_END_NAMESPACE + +#endif // FMT_CORE_H_ diff --git a/contrib/libs/fmt/include/fmt/format-inl.h b/contrib/libs/fmt/include/fmt/format-inl.h index 65bd598458..8f2fe7354a 100644 --- a/contrib/libs/fmt/include/fmt/format-inl.h +++ b/contrib/libs/fmt/include/fmt/format-inl.h @@ -1,233 +1,233 @@ -// Formatting library for C++ - implementation -// -// Copyright (c) 2012 - 2016, Victor Zverovich -// All rights reserved. -// -// For the license information refer to format.h. - -#ifndef FMT_FORMAT_INL_H_ -#define FMT_FORMAT_INL_H_ - -#include <cassert> -#include <cctype> -#include <climits> -#include <cmath> -#include <cstdarg> +// Formatting library for C++ - implementation +// +// Copyright (c) 2012 - 2016, Victor Zverovich +// All rights reserved. +// +// For the license information refer to format.h. + +#ifndef FMT_FORMAT_INL_H_ +#define FMT_FORMAT_INL_H_ + +#include <cassert> +#include <cctype> +#include <climits> +#include <cmath> +#include <cstdarg> #include <cstring> // std::memmove -#include <cwchar> +#include <cwchar> #include <exception> - + #ifndef FMT_STATIC_THOUSANDS_SEPARATOR -# include <locale> -#endif - -#ifdef _WIN32 +# include <locale> +#endif + +#ifdef _WIN32 # include <io.h> // _isatty -#endif - +#endif + #include "format.h" - -// Dummy implementations of strerror_r and strerror_s called if corresponding -// system functions are not available. + +// Dummy implementations of strerror_r and strerror_s called if corresponding +// system functions are not available. inline fmt::detail::null<> strerror_r(int, char*, ...) { return {}; } inline fmt::detail::null<> strerror_s(char*, size_t, ...) { return {}; } - -FMT_BEGIN_NAMESPACE + +FMT_BEGIN_NAMESPACE namespace detail { - -FMT_FUNC void assert_fail(const char* file, int line, const char* message) { + +FMT_FUNC void assert_fail(const char* file, int line, const char* message) { // Use unchecked std::fprintf to avoid triggering another assertion when // writing to stderr fails std::fprintf(stderr, "%s:%d: assertion failed: %s", file, line, message); // Chosen instead of std::abort to satisfy Clang in CUDA mode during device // code pass. std::terminate(); -} - -#ifndef _MSC_VER -# define FMT_SNPRINTF snprintf -#else // _MSC_VER -inline int fmt_snprintf(char* buffer, size_t size, const char* format, ...) { - va_list args; - va_start(args, format); - int result = vsnprintf_s(buffer, size, _TRUNCATE, format, args); - va_end(args); - return result; -} -# define FMT_SNPRINTF fmt_snprintf -#endif // _MSC_VER - -// A portable thread-safe version of strerror. -// Sets buffer to point to a string describing the error code. -// This can be either a pointer to a string stored in buffer, -// or a pointer to some static immutable string. -// Returns one of the following values: -// 0 - success -// ERANGE - buffer is not large enough to store the error message -// other - failure -// Buffer should be at least of size 1. +} + +#ifndef _MSC_VER +# define FMT_SNPRINTF snprintf +#else // _MSC_VER +inline int fmt_snprintf(char* buffer, size_t size, const char* format, ...) { + va_list args; + va_start(args, format); + int result = vsnprintf_s(buffer, size, _TRUNCATE, format, args); + va_end(args); + return result; +} +# define FMT_SNPRINTF fmt_snprintf +#endif // _MSC_VER + +// A portable thread-safe version of strerror. +// Sets buffer to point to a string describing the error code. +// This can be either a pointer to a string stored in buffer, +// or a pointer to some static immutable string. +// Returns one of the following values: +// 0 - success +// ERANGE - buffer is not large enough to store the error message +// other - failure +// Buffer should be at least of size 1. inline int safe_strerror(int error_code, char*& buffer, size_t buffer_size) FMT_NOEXCEPT { - FMT_ASSERT(buffer != nullptr && buffer_size != 0, "invalid buffer"); - - class dispatcher { - private: - int error_code_; - char*& buffer_; + FMT_ASSERT(buffer != nullptr && buffer_size != 0, "invalid buffer"); + + class dispatcher { + private: + int error_code_; + char*& buffer_; size_t buffer_size_; - - // A noop assignment operator to avoid bogus warnings. - void operator=(const dispatcher&) {} - - // Handle the result of XSI-compliant version of strerror_r. - int handle(int result) { - // glibc versions before 2.13 return result in errno. - return result == -1 ? errno : result; - } - - // Handle the result of GNU-specific version of strerror_r. - FMT_MAYBE_UNUSED - int handle(char* message) { - // If the buffer is full then the message is probably truncated. - if (message == buffer_ && strlen(buffer_) == buffer_size_ - 1) - return ERANGE; - buffer_ = message; - return 0; - } - - // Handle the case when strerror_r is not available. - FMT_MAYBE_UNUSED + + // A noop assignment operator to avoid bogus warnings. + void operator=(const dispatcher&) {} + + // Handle the result of XSI-compliant version of strerror_r. + int handle(int result) { + // glibc versions before 2.13 return result in errno. + return result == -1 ? errno : result; + } + + // Handle the result of GNU-specific version of strerror_r. + FMT_MAYBE_UNUSED + int handle(char* message) { + // If the buffer is full then the message is probably truncated. + if (message == buffer_ && strlen(buffer_) == buffer_size_ - 1) + return ERANGE; + buffer_ = message; + return 0; + } + + // Handle the case when strerror_r is not available. + FMT_MAYBE_UNUSED int handle(detail::null<>) { - return fallback(strerror_s(buffer_, buffer_size_, error_code_)); - } - - // Fallback to strerror_s when strerror_r is not available. - FMT_MAYBE_UNUSED - int fallback(int result) { - // If the buffer is full then the message is probably truncated. - return result == 0 && strlen(buffer_) == buffer_size_ - 1 ? ERANGE - : result; - } - -#if !FMT_MSC_VER - // Fallback to strerror if strerror_r and strerror_s are not available. + return fallback(strerror_s(buffer_, buffer_size_, error_code_)); + } + + // Fallback to strerror_s when strerror_r is not available. + FMT_MAYBE_UNUSED + int fallback(int result) { + // If the buffer is full then the message is probably truncated. + return result == 0 && strlen(buffer_) == buffer_size_ - 1 ? ERANGE + : result; + } + +#if !FMT_MSC_VER + // Fallback to strerror if strerror_r and strerror_s are not available. int fallback(detail::null<>) { - errno = 0; - buffer_ = strerror(error_code_); - return errno; - } -#endif - - public: + errno = 0; + buffer_ = strerror(error_code_); + return errno; + } +#endif + + public: dispatcher(int err_code, char*& buf, size_t buf_size) - : error_code_(err_code), buffer_(buf), buffer_size_(buf_size) {} - - int run() { return handle(strerror_r(error_code_, buffer_, buffer_size_)); } - }; - return dispatcher(error_code, buffer, buffer_size).run(); -} - + : error_code_(err_code), buffer_(buf), buffer_size_(buf_size) {} + + int run() { return handle(strerror_r(error_code_, buffer_, buffer_size_)); } + }; + return dispatcher(error_code, buffer, buffer_size).run(); +} + FMT_FUNC void format_error_code(detail::buffer<char>& out, int error_code, - string_view message) FMT_NOEXCEPT { - // Report error code making sure that the output fits into - // inline_buffer_size to avoid dynamic memory allocation and potential - // bad_alloc. + string_view message) FMT_NOEXCEPT { + // Report error code making sure that the output fits into + // inline_buffer_size to avoid dynamic memory allocation and potential + // bad_alloc. out.try_resize(0); - static const char SEP[] = ": "; - static const char ERROR_STR[] = "error "; - // Subtract 2 to account for terminating null characters in SEP and ERROR_STR. + static const char SEP[] = ": "; + static const char ERROR_STR[] = "error "; + // Subtract 2 to account for terminating null characters in SEP and ERROR_STR. size_t error_code_size = sizeof(SEP) + sizeof(ERROR_STR) - 2; - auto abs_value = static_cast<uint32_or_64_or_128_t<int>>(error_code); + auto abs_value = static_cast<uint32_or_64_or_128_t<int>>(error_code); if (detail::is_negative(error_code)) { - abs_value = 0 - abs_value; - ++error_code_size; - } + abs_value = 0 - abs_value; + ++error_code_size; + } error_code_size += detail::to_unsigned(detail::count_digits(abs_value)); auto it = buffer_appender<char>(out); if (message.size() <= inline_buffer_size - error_code_size) format_to(it, "{}{}", message, SEP); format_to(it, "{}{}", ERROR_STR, error_code); - assert(out.size() <= inline_buffer_size); -} - -FMT_FUNC void report_error(format_func func, int error_code, - string_view message) FMT_NOEXCEPT { - memory_buffer full_message; - func(full_message, error_code, message); - // Don't use fwrite_fully because the latter may throw. - (void)std::fwrite(full_message.data(), full_message.size(), 1, stderr); - std::fputc('\n', stderr); -} - -// A wrapper around fwrite that throws on error. + assert(out.size() <= inline_buffer_size); +} + +FMT_FUNC void report_error(format_func func, int error_code, + string_view message) FMT_NOEXCEPT { + memory_buffer full_message; + func(full_message, error_code, message); + // Don't use fwrite_fully because the latter may throw. + (void)std::fwrite(full_message.data(), full_message.size(), 1, stderr); + std::fputc('\n', stderr); +} + +// A wrapper around fwrite that throws on error. inline void fwrite_fully(const void* ptr, size_t size, size_t count, FILE* stream) { - size_t written = std::fwrite(ptr, size, count, stream); - if (written < count) FMT_THROW(system_error(errno, "cannot write to file")); -} + size_t written = std::fwrite(ptr, size, count, stream); + if (written < count) FMT_THROW(system_error(errno, "cannot write to file")); +} } // namespace detail - -#if !defined(FMT_STATIC_THOUSANDS_SEPARATOR) + +#if !defined(FMT_STATIC_THOUSANDS_SEPARATOR) namespace detail { - -template <typename Locale> -locale_ref::locale_ref(const Locale& loc) : locale_(&loc) { - static_assert(std::is_same<Locale, std::locale>::value, ""); -} - -template <typename Locale> Locale locale_ref::get() const { - static_assert(std::is_same<Locale, std::locale>::value, ""); - return locale_ ? *static_cast<const std::locale*>(locale_) : std::locale(); -} - -template <typename Char> FMT_FUNC std::string grouping_impl(locale_ref loc) { - return std::use_facet<std::numpunct<Char>>(loc.get<std::locale>()).grouping(); -} -template <typename Char> FMT_FUNC Char thousands_sep_impl(locale_ref loc) { - return std::use_facet<std::numpunct<Char>>(loc.get<std::locale>()) - .thousands_sep(); -} -template <typename Char> FMT_FUNC Char decimal_point_impl(locale_ref loc) { - return std::use_facet<std::numpunct<Char>>(loc.get<std::locale>()) - .decimal_point(); -} + +template <typename Locale> +locale_ref::locale_ref(const Locale& loc) : locale_(&loc) { + static_assert(std::is_same<Locale, std::locale>::value, ""); +} + +template <typename Locale> Locale locale_ref::get() const { + static_assert(std::is_same<Locale, std::locale>::value, ""); + return locale_ ? *static_cast<const std::locale*>(locale_) : std::locale(); +} + +template <typename Char> FMT_FUNC std::string grouping_impl(locale_ref loc) { + return std::use_facet<std::numpunct<Char>>(loc.get<std::locale>()).grouping(); +} +template <typename Char> FMT_FUNC Char thousands_sep_impl(locale_ref loc) { + return std::use_facet<std::numpunct<Char>>(loc.get<std::locale>()) + .thousands_sep(); +} +template <typename Char> FMT_FUNC Char decimal_point_impl(locale_ref loc) { + return std::use_facet<std::numpunct<Char>>(loc.get<std::locale>()) + .decimal_point(); +} } // namespace detail -#else -template <typename Char> +#else +template <typename Char> FMT_FUNC std::string detail::grouping_impl(locale_ref) { - return "\03"; -} + return "\03"; +} template <typename Char> FMT_FUNC Char detail::thousands_sep_impl(locale_ref) { - return FMT_STATIC_THOUSANDS_SEPARATOR; -} + return FMT_STATIC_THOUSANDS_SEPARATOR; +} template <typename Char> FMT_FUNC Char detail::decimal_point_impl(locale_ref) { - return '.'; -} -#endif - -FMT_API FMT_FUNC format_error::~format_error() FMT_NOEXCEPT = default; -FMT_API FMT_FUNC system_error::~system_error() FMT_NOEXCEPT = default; - -FMT_FUNC void system_error::init(int err_code, string_view format_str, - format_args args) { - error_code_ = err_code; - memory_buffer buffer; - format_system_error(buffer, err_code, vformat(format_str, args)); - std::runtime_error& base = *this; - base = std::runtime_error(to_string(buffer)); -} - + return '.'; +} +#endif + +FMT_API FMT_FUNC format_error::~format_error() FMT_NOEXCEPT = default; +FMT_API FMT_FUNC system_error::~system_error() FMT_NOEXCEPT = default; + +FMT_FUNC void system_error::init(int err_code, string_view format_str, + format_args args) { + error_code_ = err_code; + memory_buffer buffer; + format_system_error(buffer, err_code, vformat(format_str, args)); + std::runtime_error& base = *this; + base = std::runtime_error(to_string(buffer)); +} + namespace detail { - + template <> FMT_FUNC int count_digits<4>(detail::fallback_uintptr n) { - // fallback_uintptr is always stored in little endian. - int i = static_cast<int>(sizeof(void*)) - 1; - while (i > 0 && n.value[i] == 0) --i; - auto char_digits = std::numeric_limits<unsigned char>::digits / 4; - return i >= 0 ? i * char_digits + count_digits<4, unsigned>(n.value[i]) : 1; -} - -template <typename T> + // fallback_uintptr is always stored in little endian. + int i = static_cast<int>(sizeof(void*)) - 1; + while (i > 0 && n.value[i] == 0) --i; + auto char_digits = std::numeric_limits<unsigned char>::digits / 4; + return i >= 0 ? i * char_digits + count_digits<4, unsigned>(n.value[i]) : 1; +} + +template <typename T> const typename basic_data<T>::digit_pair basic_data<T>::digits[] = { {'0', '0'}, {'0', '1'}, {'0', '2'}, {'0', '3'}, {'0', '4'}, {'0', '5'}, {'0', '6'}, {'0', '7'}, {'0', '8'}, {'0', '9'}, {'1', '0'}, {'1', '1'}, @@ -246,28 +246,28 @@ const typename basic_data<T>::digit_pair basic_data<T>::digits[] = { {'8', '4'}, {'8', '5'}, {'8', '6'}, {'8', '7'}, {'8', '8'}, {'8', '9'}, {'9', '0'}, {'9', '1'}, {'9', '2'}, {'9', '3'}, {'9', '4'}, {'9', '5'}, {'9', '6'}, {'9', '7'}, {'9', '8'}, {'9', '9'}}; - -template <typename T> -const char basic_data<T>::hex_digits[] = "0123456789abcdef"; - -#define FMT_POWERS_OF_10(factor) \ - factor * 10, (factor)*100, (factor)*1000, (factor)*10000, (factor)*100000, \ - (factor)*1000000, (factor)*10000000, (factor)*100000000, \ - (factor)*1000000000 - -template <typename T> -const uint64_t basic_data<T>::powers_of_10_64[] = { - 1, FMT_POWERS_OF_10(1), FMT_POWERS_OF_10(1000000000ULL), - 10000000000000000000ULL}; - -template <typename T> -const uint32_t basic_data<T>::zero_or_powers_of_10_32[] = {0, - FMT_POWERS_OF_10(1)}; -template <typename T> -const uint64_t basic_data<T>::zero_or_powers_of_10_64[] = { - 0, FMT_POWERS_OF_10(1), FMT_POWERS_OF_10(1000000000ULL), - 10000000000000000000ULL}; - + +template <typename T> +const char basic_data<T>::hex_digits[] = "0123456789abcdef"; + +#define FMT_POWERS_OF_10(factor) \ + factor * 10, (factor)*100, (factor)*1000, (factor)*10000, (factor)*100000, \ + (factor)*1000000, (factor)*10000000, (factor)*100000000, \ + (factor)*1000000000 + +template <typename T> +const uint64_t basic_data<T>::powers_of_10_64[] = { + 1, FMT_POWERS_OF_10(1), FMT_POWERS_OF_10(1000000000ULL), + 10000000000000000000ULL}; + +template <typename T> +const uint32_t basic_data<T>::zero_or_powers_of_10_32[] = {0, + FMT_POWERS_OF_10(1)}; +template <typename T> +const uint64_t basic_data<T>::zero_or_powers_of_10_64[] = { + 0, FMT_POWERS_OF_10(1), FMT_POWERS_OF_10(1000000000ULL), + 10000000000000000000ULL}; + template <typename T> const uint32_t basic_data<T>::zero_or_powers_of_10_32_new[] = { 0, 0, FMT_POWERS_OF_10(1)}; @@ -277,55 +277,55 @@ const uint64_t basic_data<T>::zero_or_powers_of_10_64_new[] = { 0, 0, FMT_POWERS_OF_10(1), FMT_POWERS_OF_10(1000000000ULL), 10000000000000000000ULL}; -// Normalized 64-bit significands of pow(10, k), for k = -348, -340, ..., 340. -// These are generated by support/compute-powers.py. -template <typename T> +// Normalized 64-bit significands of pow(10, k), for k = -348, -340, ..., 340. +// These are generated by support/compute-powers.py. +template <typename T> const uint64_t basic_data<T>::grisu_pow10_significands[] = { - 0xfa8fd5a0081c0288, 0xbaaee17fa23ebf76, 0x8b16fb203055ac76, - 0xcf42894a5dce35ea, 0x9a6bb0aa55653b2d, 0xe61acf033d1a45df, - 0xab70fe17c79ac6ca, 0xff77b1fcbebcdc4f, 0xbe5691ef416bd60c, - 0x8dd01fad907ffc3c, 0xd3515c2831559a83, 0x9d71ac8fada6c9b5, - 0xea9c227723ee8bcb, 0xaecc49914078536d, 0x823c12795db6ce57, - 0xc21094364dfb5637, 0x9096ea6f3848984f, 0xd77485cb25823ac7, - 0xa086cfcd97bf97f4, 0xef340a98172aace5, 0xb23867fb2a35b28e, - 0x84c8d4dfd2c63f3b, 0xc5dd44271ad3cdba, 0x936b9fcebb25c996, - 0xdbac6c247d62a584, 0xa3ab66580d5fdaf6, 0xf3e2f893dec3f126, - 0xb5b5ada8aaff80b8, 0x87625f056c7c4a8b, 0xc9bcff6034c13053, - 0x964e858c91ba2655, 0xdff9772470297ebd, 0xa6dfbd9fb8e5b88f, - 0xf8a95fcf88747d94, 0xb94470938fa89bcf, 0x8a08f0f8bf0f156b, - 0xcdb02555653131b6, 0x993fe2c6d07b7fac, 0xe45c10c42a2b3b06, - 0xaa242499697392d3, 0xfd87b5f28300ca0e, 0xbce5086492111aeb, - 0x8cbccc096f5088cc, 0xd1b71758e219652c, 0x9c40000000000000, - 0xe8d4a51000000000, 0xad78ebc5ac620000, 0x813f3978f8940984, - 0xc097ce7bc90715b3, 0x8f7e32ce7bea5c70, 0xd5d238a4abe98068, - 0x9f4f2726179a2245, 0xed63a231d4c4fb27, 0xb0de65388cc8ada8, - 0x83c7088e1aab65db, 0xc45d1df942711d9a, 0x924d692ca61be758, - 0xda01ee641a708dea, 0xa26da3999aef774a, 0xf209787bb47d6b85, - 0xb454e4a179dd1877, 0x865b86925b9bc5c2, 0xc83553c5c8965d3d, - 0x952ab45cfa97a0b3, 0xde469fbd99a05fe3, 0xa59bc234db398c25, - 0xf6c69a72a3989f5c, 0xb7dcbf5354e9bece, 0x88fcf317f22241e2, - 0xcc20ce9bd35c78a5, 0x98165af37b2153df, 0xe2a0b5dc971f303a, - 0xa8d9d1535ce3b396, 0xfb9b7cd9a4a7443c, 0xbb764c4ca7a44410, - 0x8bab8eefb6409c1a, 0xd01fef10a657842c, 0x9b10a4e5e9913129, - 0xe7109bfba19c0c9d, 0xac2820d9623bf429, 0x80444b5e7aa7cf85, - 0xbf21e44003acdd2d, 0x8e679c2f5e44ff8f, 0xd433179d9c8cb841, - 0x9e19db92b4e31ba9, 0xeb96bf6ebadf77d9, 0xaf87023b9bf0ee6b, -}; - -// Binary exponents of pow(10, k), for k = -348, -340, ..., 340, corresponding -// to significands above. -template <typename T> + 0xfa8fd5a0081c0288, 0xbaaee17fa23ebf76, 0x8b16fb203055ac76, + 0xcf42894a5dce35ea, 0x9a6bb0aa55653b2d, 0xe61acf033d1a45df, + 0xab70fe17c79ac6ca, 0xff77b1fcbebcdc4f, 0xbe5691ef416bd60c, + 0x8dd01fad907ffc3c, 0xd3515c2831559a83, 0x9d71ac8fada6c9b5, + 0xea9c227723ee8bcb, 0xaecc49914078536d, 0x823c12795db6ce57, + 0xc21094364dfb5637, 0x9096ea6f3848984f, 0xd77485cb25823ac7, + 0xa086cfcd97bf97f4, 0xef340a98172aace5, 0xb23867fb2a35b28e, + 0x84c8d4dfd2c63f3b, 0xc5dd44271ad3cdba, 0x936b9fcebb25c996, + 0xdbac6c247d62a584, 0xa3ab66580d5fdaf6, 0xf3e2f893dec3f126, + 0xb5b5ada8aaff80b8, 0x87625f056c7c4a8b, 0xc9bcff6034c13053, + 0x964e858c91ba2655, 0xdff9772470297ebd, 0xa6dfbd9fb8e5b88f, + 0xf8a95fcf88747d94, 0xb94470938fa89bcf, 0x8a08f0f8bf0f156b, + 0xcdb02555653131b6, 0x993fe2c6d07b7fac, 0xe45c10c42a2b3b06, + 0xaa242499697392d3, 0xfd87b5f28300ca0e, 0xbce5086492111aeb, + 0x8cbccc096f5088cc, 0xd1b71758e219652c, 0x9c40000000000000, + 0xe8d4a51000000000, 0xad78ebc5ac620000, 0x813f3978f8940984, + 0xc097ce7bc90715b3, 0x8f7e32ce7bea5c70, 0xd5d238a4abe98068, + 0x9f4f2726179a2245, 0xed63a231d4c4fb27, 0xb0de65388cc8ada8, + 0x83c7088e1aab65db, 0xc45d1df942711d9a, 0x924d692ca61be758, + 0xda01ee641a708dea, 0xa26da3999aef774a, 0xf209787bb47d6b85, + 0xb454e4a179dd1877, 0x865b86925b9bc5c2, 0xc83553c5c8965d3d, + 0x952ab45cfa97a0b3, 0xde469fbd99a05fe3, 0xa59bc234db398c25, + 0xf6c69a72a3989f5c, 0xb7dcbf5354e9bece, 0x88fcf317f22241e2, + 0xcc20ce9bd35c78a5, 0x98165af37b2153df, 0xe2a0b5dc971f303a, + 0xa8d9d1535ce3b396, 0xfb9b7cd9a4a7443c, 0xbb764c4ca7a44410, + 0x8bab8eefb6409c1a, 0xd01fef10a657842c, 0x9b10a4e5e9913129, + 0xe7109bfba19c0c9d, 0xac2820d9623bf429, 0x80444b5e7aa7cf85, + 0xbf21e44003acdd2d, 0x8e679c2f5e44ff8f, 0xd433179d9c8cb841, + 0x9e19db92b4e31ba9, 0xeb96bf6ebadf77d9, 0xaf87023b9bf0ee6b, +}; + +// Binary exponents of pow(10, k), for k = -348, -340, ..., 340, corresponding +// to significands above. +template <typename T> const int16_t basic_data<T>::grisu_pow10_exponents[] = { - -1220, -1193, -1166, -1140, -1113, -1087, -1060, -1034, -1007, -980, -954, - -927, -901, -874, -847, -821, -794, -768, -741, -715, -688, -661, - -635, -608, -582, -555, -529, -502, -475, -449, -422, -396, -369, - -343, -316, -289, -263, -236, -210, -183, -157, -130, -103, -77, - -50, -24, 3, 30, 56, 83, 109, 136, 162, 189, 216, - 242, 269, 295, 322, 348, 375, 402, 428, 455, 481, 508, - 534, 561, 588, 614, 641, 667, 694, 720, 747, 774, 800, - 827, 853, 880, 907, 933, 960, 986, 1013, 1039, 1066}; - -template <typename T> + -1220, -1193, -1166, -1140, -1113, -1087, -1060, -1034, -1007, -980, -954, + -927, -901, -874, -847, -821, -794, -768, -741, -715, -688, -661, + -635, -608, -582, -555, -529, -502, -475, -449, -422, -396, -369, + -343, -316, -289, -263, -236, -210, -183, -157, -130, -103, -77, + -50, -24, 3, 30, 56, 83, 109, 136, 162, 189, 216, + 242, 269, 295, 322, 348, 375, 402, 428, 455, 481, 508, + 534, 561, 588, 614, 641, 667, 694, 720, 747, 774, 800, + 827, 853, 880, 907, 933, 960, 986, 1013, 1039, 1066}; + +template <typename T> const divtest_table_entry<uint32_t> basic_data<T>::divtest_table_for_pow5_32[] = {{0x00000001, 0xffffffff}, {0xcccccccd, 0x33333333}, {0xc28f5c29, 0x0a3d70a3}, {0x26e978d5, 0x020c49ba}, @@ -1064,385 +1064,385 @@ const uint32_t basic_data<T>::dragonbox_pow10_recovery_errors[] = { #endif template <typename T> -const char basic_data<T>::foreground_color[] = "\x1b[38;2;"; -template <typename T> -const char basic_data<T>::background_color[] = "\x1b[48;2;"; -template <typename T> const char basic_data<T>::reset_color[] = "\x1b[0m"; -template <typename T> const wchar_t basic_data<T>::wreset_color[] = L"\x1b[0m"; -template <typename T> const char basic_data<T>::signs[] = {0, '-', '+', ' '}; +const char basic_data<T>::foreground_color[] = "\x1b[38;2;"; +template <typename T> +const char basic_data<T>::background_color[] = "\x1b[48;2;"; +template <typename T> const char basic_data<T>::reset_color[] = "\x1b[0m"; +template <typename T> const wchar_t basic_data<T>::wreset_color[] = L"\x1b[0m"; +template <typename T> const char basic_data<T>::signs[] = {0, '-', '+', ' '}; template <typename T> const char basic_data<T>::left_padding_shifts[] = {31, 31, 0, 1, 0}; template <typename T> const char basic_data<T>::right_padding_shifts[] = {0, 31, 0, 1, 0}; - -template <typename T> struct bits { - static FMT_CONSTEXPR_DECL const int value = - static_cast<int>(sizeof(T) * std::numeric_limits<unsigned char>::digits); -}; - -class fp; -template <int SHIFT = 0> fp normalize(fp value); - -// Lower (upper) boundary is a value half way between a floating-point value -// and its predecessor (successor). Boundaries have the same exponent as the -// value so only significands are stored. -struct boundaries { - uint64_t lower; - uint64_t upper; -}; - -// A handmade floating-point number f * pow(2, e). -class fp { - private: - using significand_type = uint64_t; - + +template <typename T> struct bits { + static FMT_CONSTEXPR_DECL const int value = + static_cast<int>(sizeof(T) * std::numeric_limits<unsigned char>::digits); +}; + +class fp; +template <int SHIFT = 0> fp normalize(fp value); + +// Lower (upper) boundary is a value half way between a floating-point value +// and its predecessor (successor). Boundaries have the same exponent as the +// value so only significands are stored. +struct boundaries { + uint64_t lower; + uint64_t upper; +}; + +// A handmade floating-point number f * pow(2, e). +class fp { + private: + using significand_type = uint64_t; + template <typename Float> using is_supported_float = bool_constant<sizeof(Float) == sizeof(uint64_t) || sizeof(Float) == sizeof(uint32_t)>; - public: - significand_type f; - int e; - - // All sizes are in bits. - // Subtract 1 to account for an implicit most significant bit in the - // normalized form. - static FMT_CONSTEXPR_DECL const int double_significand_size = - std::numeric_limits<double>::digits - 1; - static FMT_CONSTEXPR_DECL const uint64_t implicit_bit = - 1ULL << double_significand_size; - static FMT_CONSTEXPR_DECL const int significand_size = - bits<significand_type>::value; - - fp() : f(0), e(0) {} - fp(uint64_t f_val, int e_val) : f(f_val), e(e_val) {} - - // Constructs fp from an IEEE754 double. It is a template to prevent compile - // errors on platforms where double is not IEEE754. - template <typename Double> explicit fp(Double d) { assign(d); } - - // Assigns d to this and return true iff predecessor is closer than successor. + public: + significand_type f; + int e; + + // All sizes are in bits. + // Subtract 1 to account for an implicit most significant bit in the + // normalized form. + static FMT_CONSTEXPR_DECL const int double_significand_size = + std::numeric_limits<double>::digits - 1; + static FMT_CONSTEXPR_DECL const uint64_t implicit_bit = + 1ULL << double_significand_size; + static FMT_CONSTEXPR_DECL const int significand_size = + bits<significand_type>::value; + + fp() : f(0), e(0) {} + fp(uint64_t f_val, int e_val) : f(f_val), e(e_val) {} + + // Constructs fp from an IEEE754 double. It is a template to prevent compile + // errors on platforms where double is not IEEE754. + template <typename Double> explicit fp(Double d) { assign(d); } + + // Assigns d to this and return true iff predecessor is closer than successor. template <typename Float, FMT_ENABLE_IF(is_supported_float<Float>::value)> bool assign(Float d) { // Assume float is in the format [sign][exponent][significand]. using limits = std::numeric_limits<Float>; const int float_significand_size = limits::digits - 1; - const int exponent_size = + const int exponent_size = bits<Float>::value - float_significand_size - 1; // -1 for sign const uint64_t float_implicit_bit = 1ULL << float_significand_size; const uint64_t significand_mask = float_implicit_bit - 1; - const uint64_t exponent_mask = (~0ULL >> 1) & ~significand_mask; - const int exponent_bias = (1 << exponent_size) - limits::max_exponent - 1; + const uint64_t exponent_mask = (~0ULL >> 1) & ~significand_mask; + const int exponent_bias = (1 << exponent_size) - limits::max_exponent - 1; constexpr bool is_double = sizeof(Float) == sizeof(uint64_t); auto u = bit_cast<conditional_t<is_double, uint64_t, uint32_t>>(d); - f = u & significand_mask; - int biased_e = + f = u & significand_mask; + int biased_e = static_cast<int>((u & exponent_mask) >> float_significand_size); - // Predecessor is closer if d is a normalized power of 2 (f == 0) other than - // the smallest normalized number (biased_e > 1). - bool is_predecessor_closer = f == 0 && biased_e > 1; - if (biased_e != 0) + // Predecessor is closer if d is a normalized power of 2 (f == 0) other than + // the smallest normalized number (biased_e > 1). + bool is_predecessor_closer = f == 0 && biased_e > 1; + if (biased_e != 0) f += float_implicit_bit; - else - biased_e = 1; // Subnormals use biased exponent 1 (min exponent). + else + biased_e = 1; // Subnormals use biased exponent 1 (min exponent). e = biased_e - exponent_bias - float_significand_size; - return is_predecessor_closer; - } - + return is_predecessor_closer; + } + template <typename Float, FMT_ENABLE_IF(!is_supported_float<Float>::value)> bool assign(Float) { - *this = fp(); - return false; - } -}; - -// Normalizes the value converted from double and multiplied by (1 << SHIFT). -template <int SHIFT> fp normalize(fp value) { - // Handle subnormals. - const auto shifted_implicit_bit = fp::implicit_bit << SHIFT; - while ((value.f & shifted_implicit_bit) == 0) { - value.f <<= 1; - --value.e; - } - // Subtract 1 to account for hidden bit. - const auto offset = - fp::significand_size - fp::double_significand_size - SHIFT - 1; - value.f <<= offset; - value.e -= offset; - return value; -} - -inline bool operator==(fp x, fp y) { return x.f == y.f && x.e == y.e; } - -// Computes lhs * rhs / pow(2, 64) rounded to nearest with half-up tie breaking. -inline uint64_t multiply(uint64_t lhs, uint64_t rhs) { -#if FMT_USE_INT128 - auto product = static_cast<__uint128_t>(lhs) * rhs; - auto f = static_cast<uint64_t>(product >> 64); - return (static_cast<uint64_t>(product) & (1ULL << 63)) != 0 ? f + 1 : f; -#else - // Multiply 32-bit parts of significands. - uint64_t mask = (1ULL << 32) - 1; - uint64_t a = lhs >> 32, b = lhs & mask; - uint64_t c = rhs >> 32, d = rhs & mask; - uint64_t ac = a * c, bc = b * c, ad = a * d, bd = b * d; - // Compute mid 64-bit of result and round. - uint64_t mid = (bd >> 32) + (ad & mask) + (bc & mask) + (1U << 31); - return ac + (ad >> 32) + (bc >> 32) + (mid >> 32); -#endif -} - -inline fp operator*(fp x, fp y) { return {multiply(x.f, y.f), x.e + y.e + 64}; } - -// Returns a cached power of 10 `c_k = c_k.f * pow(2, c_k.e)` such that its -// (binary) exponent satisfies `min_exponent <= c_k.e <= min_exponent + 28`. -inline fp get_cached_power(int min_exponent, int& pow10_exponent) { + *this = fp(); + return false; + } +}; + +// Normalizes the value converted from double and multiplied by (1 << SHIFT). +template <int SHIFT> fp normalize(fp value) { + // Handle subnormals. + const auto shifted_implicit_bit = fp::implicit_bit << SHIFT; + while ((value.f & shifted_implicit_bit) == 0) { + value.f <<= 1; + --value.e; + } + // Subtract 1 to account for hidden bit. + const auto offset = + fp::significand_size - fp::double_significand_size - SHIFT - 1; + value.f <<= offset; + value.e -= offset; + return value; +} + +inline bool operator==(fp x, fp y) { return x.f == y.f && x.e == y.e; } + +// Computes lhs * rhs / pow(2, 64) rounded to nearest with half-up tie breaking. +inline uint64_t multiply(uint64_t lhs, uint64_t rhs) { +#if FMT_USE_INT128 + auto product = static_cast<__uint128_t>(lhs) * rhs; + auto f = static_cast<uint64_t>(product >> 64); + return (static_cast<uint64_t>(product) & (1ULL << 63)) != 0 ? f + 1 : f; +#else + // Multiply 32-bit parts of significands. + uint64_t mask = (1ULL << 32) - 1; + uint64_t a = lhs >> 32, b = lhs & mask; + uint64_t c = rhs >> 32, d = rhs & mask; + uint64_t ac = a * c, bc = b * c, ad = a * d, bd = b * d; + // Compute mid 64-bit of result and round. + uint64_t mid = (bd >> 32) + (ad & mask) + (bc & mask) + (1U << 31); + return ac + (ad >> 32) + (bc >> 32) + (mid >> 32); +#endif +} + +inline fp operator*(fp x, fp y) { return {multiply(x.f, y.f), x.e + y.e + 64}; } + +// Returns a cached power of 10 `c_k = c_k.f * pow(2, c_k.e)` such that its +// (binary) exponent satisfies `min_exponent <= c_k.e <= min_exponent + 28`. +inline fp get_cached_power(int min_exponent, int& pow10_exponent) { const int shift = 32; const auto significand = static_cast<int64_t>(data::log10_2_significand); - int index = static_cast<int>( + int index = static_cast<int>( ((min_exponent + fp::significand_size - 1) * (significand >> shift) + ((int64_t(1) << shift) - 1)) // ceil >> 32 // arithmetic shift - ); - // Decimal exponent of the first (smallest) cached power of 10. - const int first_dec_exp = -348; - // Difference between 2 consecutive decimal exponents in cached powers of 10. - const int dec_exp_step = 8; - index = (index - first_dec_exp - 1) / dec_exp_step + 1; - pow10_exponent = first_dec_exp + index * dec_exp_step; + ); + // Decimal exponent of the first (smallest) cached power of 10. + const int first_dec_exp = -348; + // Difference between 2 consecutive decimal exponents in cached powers of 10. + const int dec_exp_step = 8; + index = (index - first_dec_exp - 1) / dec_exp_step + 1; + pow10_exponent = first_dec_exp + index * dec_exp_step; return {data::grisu_pow10_significands[index], data::grisu_pow10_exponents[index]}; -} - -// A simple accumulator to hold the sums of terms in bigint::square if uint128_t -// is not available. -struct accumulator { - uint64_t lower; - uint64_t upper; - - accumulator() : lower(0), upper(0) {} - explicit operator uint32_t() const { return static_cast<uint32_t>(lower); } - - void operator+=(uint64_t n) { - lower += n; - if (lower < n) ++upper; - } - void operator>>=(int shift) { - assert(shift == 32); - (void)shift; - lower = (upper << 32) | (lower >> 32); - upper >>= 32; - } -}; - -class bigint { - private: - // A bigint is stored as an array of bigits (big digits), with bigit at index - // 0 being the least significant one. - using bigit = uint32_t; - using double_bigit = uint64_t; - enum { bigits_capacity = 32 }; - basic_memory_buffer<bigit, bigits_capacity> bigits_; - int exp_; - - bigit operator[](int index) const { return bigits_[to_unsigned(index)]; } - bigit& operator[](int index) { return bigits_[to_unsigned(index)]; } - - static FMT_CONSTEXPR_DECL const int bigit_bits = bits<bigit>::value; - - friend struct formatter<bigint>; - - void subtract_bigits(int index, bigit other, bigit& borrow) { - auto result = static_cast<double_bigit>((*this)[index]) - other - borrow; - (*this)[index] = static_cast<bigit>(result); - borrow = static_cast<bigit>(result >> (bigit_bits * 2 - 1)); - } - - void remove_leading_zeros() { - int num_bigits = static_cast<int>(bigits_.size()) - 1; - while (num_bigits > 0 && (*this)[num_bigits] == 0) --num_bigits; - bigits_.resize(to_unsigned(num_bigits + 1)); - } - - // Computes *this -= other assuming aligned bigints and *this >= other. - void subtract_aligned(const bigint& other) { - FMT_ASSERT(other.exp_ >= exp_, "unaligned bigints"); - FMT_ASSERT(compare(*this, other) >= 0, ""); - bigit borrow = 0; - int i = other.exp_ - exp_; +} + +// A simple accumulator to hold the sums of terms in bigint::square if uint128_t +// is not available. +struct accumulator { + uint64_t lower; + uint64_t upper; + + accumulator() : lower(0), upper(0) {} + explicit operator uint32_t() const { return static_cast<uint32_t>(lower); } + + void operator+=(uint64_t n) { + lower += n; + if (lower < n) ++upper; + } + void operator>>=(int shift) { + assert(shift == 32); + (void)shift; + lower = (upper << 32) | (lower >> 32); + upper >>= 32; + } +}; + +class bigint { + private: + // A bigint is stored as an array of bigits (big digits), with bigit at index + // 0 being the least significant one. + using bigit = uint32_t; + using double_bigit = uint64_t; + enum { bigits_capacity = 32 }; + basic_memory_buffer<bigit, bigits_capacity> bigits_; + int exp_; + + bigit operator[](int index) const { return bigits_[to_unsigned(index)]; } + bigit& operator[](int index) { return bigits_[to_unsigned(index)]; } + + static FMT_CONSTEXPR_DECL const int bigit_bits = bits<bigit>::value; + + friend struct formatter<bigint>; + + void subtract_bigits(int index, bigit other, bigit& borrow) { + auto result = static_cast<double_bigit>((*this)[index]) - other - borrow; + (*this)[index] = static_cast<bigit>(result); + borrow = static_cast<bigit>(result >> (bigit_bits * 2 - 1)); + } + + void remove_leading_zeros() { + int num_bigits = static_cast<int>(bigits_.size()) - 1; + while (num_bigits > 0 && (*this)[num_bigits] == 0) --num_bigits; + bigits_.resize(to_unsigned(num_bigits + 1)); + } + + // Computes *this -= other assuming aligned bigints and *this >= other. + void subtract_aligned(const bigint& other) { + FMT_ASSERT(other.exp_ >= exp_, "unaligned bigints"); + FMT_ASSERT(compare(*this, other) >= 0, ""); + bigit borrow = 0; + int i = other.exp_ - exp_; for (size_t j = 0, n = other.bigits_.size(); j != n; ++i, ++j) - subtract_bigits(i, other.bigits_[j], borrow); - while (borrow > 0) subtract_bigits(i, 0, borrow); - remove_leading_zeros(); - } - - void multiply(uint32_t value) { - const double_bigit wide_value = value; - bigit carry = 0; - for (size_t i = 0, n = bigits_.size(); i < n; ++i) { - double_bigit result = bigits_[i] * wide_value + carry; - bigits_[i] = static_cast<bigit>(result); - carry = static_cast<bigit>(result >> bigit_bits); - } - if (carry != 0) bigits_.push_back(carry); - } - - void multiply(uint64_t value) { - const bigit mask = ~bigit(0); - const double_bigit lower = value & mask; - const double_bigit upper = value >> bigit_bits; - double_bigit carry = 0; - for (size_t i = 0, n = bigits_.size(); i < n; ++i) { - double_bigit result = bigits_[i] * lower + (carry & mask); - carry = - bigits_[i] * upper + (result >> bigit_bits) + (carry >> bigit_bits); - bigits_[i] = static_cast<bigit>(result); - } - while (carry != 0) { - bigits_.push_back(carry & mask); - carry >>= bigit_bits; - } - } - - public: - bigint() : exp_(0) {} - explicit bigint(uint64_t n) { assign(n); } - ~bigint() { assert(bigits_.capacity() <= bigits_capacity); } - - bigint(const bigint&) = delete; - void operator=(const bigint&) = delete; - - void assign(const bigint& other) { + subtract_bigits(i, other.bigits_[j], borrow); + while (borrow > 0) subtract_bigits(i, 0, borrow); + remove_leading_zeros(); + } + + void multiply(uint32_t value) { + const double_bigit wide_value = value; + bigit carry = 0; + for (size_t i = 0, n = bigits_.size(); i < n; ++i) { + double_bigit result = bigits_[i] * wide_value + carry; + bigits_[i] = static_cast<bigit>(result); + carry = static_cast<bigit>(result >> bigit_bits); + } + if (carry != 0) bigits_.push_back(carry); + } + + void multiply(uint64_t value) { + const bigit mask = ~bigit(0); + const double_bigit lower = value & mask; + const double_bigit upper = value >> bigit_bits; + double_bigit carry = 0; + for (size_t i = 0, n = bigits_.size(); i < n; ++i) { + double_bigit result = bigits_[i] * lower + (carry & mask); + carry = + bigits_[i] * upper + (result >> bigit_bits) + (carry >> bigit_bits); + bigits_[i] = static_cast<bigit>(result); + } + while (carry != 0) { + bigits_.push_back(carry & mask); + carry >>= bigit_bits; + } + } + + public: + bigint() : exp_(0) {} + explicit bigint(uint64_t n) { assign(n); } + ~bigint() { assert(bigits_.capacity() <= bigits_capacity); } + + bigint(const bigint&) = delete; + void operator=(const bigint&) = delete; + + void assign(const bigint& other) { auto size = other.bigits_.size(); bigits_.resize(size); - auto data = other.bigits_.data(); + auto data = other.bigits_.data(); std::copy(data, data + size, make_checked(bigits_.data(), size)); - exp_ = other.exp_; - } - - void assign(uint64_t n) { - size_t num_bigits = 0; - do { - bigits_[num_bigits++] = n & ~bigit(0); - n >>= bigit_bits; - } while (n != 0); - bigits_.resize(num_bigits); - exp_ = 0; - } - - int num_bigits() const { return static_cast<int>(bigits_.size()) + exp_; } - + exp_ = other.exp_; + } + + void assign(uint64_t n) { + size_t num_bigits = 0; + do { + bigits_[num_bigits++] = n & ~bigit(0); + n >>= bigit_bits; + } while (n != 0); + bigits_.resize(num_bigits); + exp_ = 0; + } + + int num_bigits() const { return static_cast<int>(bigits_.size()) + exp_; } + FMT_NOINLINE bigint& operator<<=(int shift) { - assert(shift >= 0); - exp_ += shift / bigit_bits; - shift %= bigit_bits; - if (shift == 0) return *this; - bigit carry = 0; - for (size_t i = 0, n = bigits_.size(); i < n; ++i) { - bigit c = bigits_[i] >> (bigit_bits - shift); - bigits_[i] = (bigits_[i] << shift) + carry; - carry = c; - } - if (carry != 0) bigits_.push_back(carry); - return *this; - } - - template <typename Int> bigint& operator*=(Int value) { - FMT_ASSERT(value > 0, ""); - multiply(uint32_or_64_or_128_t<Int>(value)); - return *this; - } - - friend int compare(const bigint& lhs, const bigint& rhs) { - int num_lhs_bigits = lhs.num_bigits(), num_rhs_bigits = rhs.num_bigits(); - if (num_lhs_bigits != num_rhs_bigits) - return num_lhs_bigits > num_rhs_bigits ? 1 : -1; - int i = static_cast<int>(lhs.bigits_.size()) - 1; - int j = static_cast<int>(rhs.bigits_.size()) - 1; - int end = i - j; - if (end < 0) end = 0; - for (; i >= end; --i, --j) { - bigit lhs_bigit = lhs[i], rhs_bigit = rhs[j]; - if (lhs_bigit != rhs_bigit) return lhs_bigit > rhs_bigit ? 1 : -1; - } - if (i != j) return i > j ? 1 : -1; - return 0; - } - - // Returns compare(lhs1 + lhs2, rhs). - friend int add_compare(const bigint& lhs1, const bigint& lhs2, - const bigint& rhs) { - int max_lhs_bigits = (std::max)(lhs1.num_bigits(), lhs2.num_bigits()); - int num_rhs_bigits = rhs.num_bigits(); - if (max_lhs_bigits + 1 < num_rhs_bigits) return -1; - if (max_lhs_bigits > num_rhs_bigits) return 1; - auto get_bigit = [](const bigint& n, int i) -> bigit { - return i >= n.exp_ && i < n.num_bigits() ? n[i - n.exp_] : 0; - }; - double_bigit borrow = 0; - int min_exp = (std::min)((std::min)(lhs1.exp_, lhs2.exp_), rhs.exp_); - for (int i = num_rhs_bigits - 1; i >= min_exp; --i) { - double_bigit sum = - static_cast<double_bigit>(get_bigit(lhs1, i)) + get_bigit(lhs2, i); - bigit rhs_bigit = get_bigit(rhs, i); - if (sum > rhs_bigit + borrow) return 1; - borrow = rhs_bigit + borrow - sum; - if (borrow > 1) return -1; - borrow <<= bigit_bits; - } - return borrow != 0 ? -1 : 0; - } - - // Assigns pow(10, exp) to this bigint. - void assign_pow10(int exp) { - assert(exp >= 0); - if (exp == 0) return assign(1); - // Find the top bit. - int bitmask = 1; - while (exp >= bitmask) bitmask <<= 1; - bitmask >>= 1; - // pow(10, exp) = pow(5, exp) * pow(2, exp). First compute pow(5, exp) by - // repeated squaring and multiplication. - assign(5); - bitmask >>= 1; - while (bitmask != 0) { - square(); - if ((exp & bitmask) != 0) *this *= 5; - bitmask >>= 1; - } - *this <<= exp; // Multiply by pow(2, exp) by shifting. - } - - void square() { - basic_memory_buffer<bigit, bigits_capacity> n(std::move(bigits_)); - int num_bigits = static_cast<int>(bigits_.size()); - int num_result_bigits = 2 * num_bigits; - bigits_.resize(to_unsigned(num_result_bigits)); - using accumulator_t = conditional_t<FMT_USE_INT128, uint128_t, accumulator>; - auto sum = accumulator_t(); - for (int bigit_index = 0; bigit_index < num_bigits; ++bigit_index) { - // Compute bigit at position bigit_index of the result by adding - // cross-product terms n[i] * n[j] such that i + j == bigit_index. - for (int i = 0, j = bigit_index; j >= 0; ++i, --j) { - // Most terms are multiplied twice which can be optimized in the future. - sum += static_cast<double_bigit>(n[i]) * n[j]; - } - (*this)[bigit_index] = static_cast<bigit>(sum); - sum >>= bits<bigit>::value; // Compute the carry. - } - // Do the same for the top half. - for (int bigit_index = num_bigits; bigit_index < num_result_bigits; - ++bigit_index) { - for (int j = num_bigits - 1, i = bigit_index - j; i < num_bigits;) - sum += static_cast<double_bigit>(n[i++]) * n[j--]; - (*this)[bigit_index] = static_cast<bigit>(sum); - sum >>= bits<bigit>::value; - } - --num_result_bigits; - remove_leading_zeros(); - exp_ *= 2; - } - + assert(shift >= 0); + exp_ += shift / bigit_bits; + shift %= bigit_bits; + if (shift == 0) return *this; + bigit carry = 0; + for (size_t i = 0, n = bigits_.size(); i < n; ++i) { + bigit c = bigits_[i] >> (bigit_bits - shift); + bigits_[i] = (bigits_[i] << shift) + carry; + carry = c; + } + if (carry != 0) bigits_.push_back(carry); + return *this; + } + + template <typename Int> bigint& operator*=(Int value) { + FMT_ASSERT(value > 0, ""); + multiply(uint32_or_64_or_128_t<Int>(value)); + return *this; + } + + friend int compare(const bigint& lhs, const bigint& rhs) { + int num_lhs_bigits = lhs.num_bigits(), num_rhs_bigits = rhs.num_bigits(); + if (num_lhs_bigits != num_rhs_bigits) + return num_lhs_bigits > num_rhs_bigits ? 1 : -1; + int i = static_cast<int>(lhs.bigits_.size()) - 1; + int j = static_cast<int>(rhs.bigits_.size()) - 1; + int end = i - j; + if (end < 0) end = 0; + for (; i >= end; --i, --j) { + bigit lhs_bigit = lhs[i], rhs_bigit = rhs[j]; + if (lhs_bigit != rhs_bigit) return lhs_bigit > rhs_bigit ? 1 : -1; + } + if (i != j) return i > j ? 1 : -1; + return 0; + } + + // Returns compare(lhs1 + lhs2, rhs). + friend int add_compare(const bigint& lhs1, const bigint& lhs2, + const bigint& rhs) { + int max_lhs_bigits = (std::max)(lhs1.num_bigits(), lhs2.num_bigits()); + int num_rhs_bigits = rhs.num_bigits(); + if (max_lhs_bigits + 1 < num_rhs_bigits) return -1; + if (max_lhs_bigits > num_rhs_bigits) return 1; + auto get_bigit = [](const bigint& n, int i) -> bigit { + return i >= n.exp_ && i < n.num_bigits() ? n[i - n.exp_] : 0; + }; + double_bigit borrow = 0; + int min_exp = (std::min)((std::min)(lhs1.exp_, lhs2.exp_), rhs.exp_); + for (int i = num_rhs_bigits - 1; i >= min_exp; --i) { + double_bigit sum = + static_cast<double_bigit>(get_bigit(lhs1, i)) + get_bigit(lhs2, i); + bigit rhs_bigit = get_bigit(rhs, i); + if (sum > rhs_bigit + borrow) return 1; + borrow = rhs_bigit + borrow - sum; + if (borrow > 1) return -1; + borrow <<= bigit_bits; + } + return borrow != 0 ? -1 : 0; + } + + // Assigns pow(10, exp) to this bigint. + void assign_pow10(int exp) { + assert(exp >= 0); + if (exp == 0) return assign(1); + // Find the top bit. + int bitmask = 1; + while (exp >= bitmask) bitmask <<= 1; + bitmask >>= 1; + // pow(10, exp) = pow(5, exp) * pow(2, exp). First compute pow(5, exp) by + // repeated squaring and multiplication. + assign(5); + bitmask >>= 1; + while (bitmask != 0) { + square(); + if ((exp & bitmask) != 0) *this *= 5; + bitmask >>= 1; + } + *this <<= exp; // Multiply by pow(2, exp) by shifting. + } + + void square() { + basic_memory_buffer<bigit, bigits_capacity> n(std::move(bigits_)); + int num_bigits = static_cast<int>(bigits_.size()); + int num_result_bigits = 2 * num_bigits; + bigits_.resize(to_unsigned(num_result_bigits)); + using accumulator_t = conditional_t<FMT_USE_INT128, uint128_t, accumulator>; + auto sum = accumulator_t(); + for (int bigit_index = 0; bigit_index < num_bigits; ++bigit_index) { + // Compute bigit at position bigit_index of the result by adding + // cross-product terms n[i] * n[j] such that i + j == bigit_index. + for (int i = 0, j = bigit_index; j >= 0; ++i, --j) { + // Most terms are multiplied twice which can be optimized in the future. + sum += static_cast<double_bigit>(n[i]) * n[j]; + } + (*this)[bigit_index] = static_cast<bigit>(sum); + sum >>= bits<bigit>::value; // Compute the carry. + } + // Do the same for the top half. + for (int bigit_index = num_bigits; bigit_index < num_result_bigits; + ++bigit_index) { + for (int j = num_bigits - 1, i = bigit_index - j; i < num_bigits;) + sum += static_cast<double_bigit>(n[i++]) * n[j--]; + (*this)[bigit_index] = static_cast<bigit>(sum); + sum >>= bits<bigit>::value; + } + --num_result_bigits; + remove_leading_zeros(); + exp_ *= 2; + } + // If this bigint has a bigger exponent than other, adds trailing zero to make // exponents equal. This simplifies some operations such as subtraction. void align(const bigint& other) { @@ -1456,193 +1456,193 @@ class bigint { exp_ -= exp_difference; } - // Divides this bignum by divisor, assigning the remainder to this and - // returning the quotient. - int divmod_assign(const bigint& divisor) { - FMT_ASSERT(this != &divisor, ""); - if (compare(*this, divisor) < 0) return 0; - FMT_ASSERT(divisor.bigits_[divisor.bigits_.size() - 1u] != 0, ""); + // Divides this bignum by divisor, assigning the remainder to this and + // returning the quotient. + int divmod_assign(const bigint& divisor) { + FMT_ASSERT(this != &divisor, ""); + if (compare(*this, divisor) < 0) return 0; + FMT_ASSERT(divisor.bigits_[divisor.bigits_.size() - 1u] != 0, ""); align(divisor); - int quotient = 0; - do { - subtract_aligned(divisor); - ++quotient; - } while (compare(*this, divisor) >= 0); - return quotient; - } -}; - -enum class round_direction { unknown, up, down }; - -// Given the divisor (normally a power of 10), the remainder = v % divisor for -// some number v and the error, returns whether v should be rounded up, down, or -// whether the rounding direction can't be determined due to error. -// error should be less than divisor / 2. -inline round_direction get_round_direction(uint64_t divisor, uint64_t remainder, - uint64_t error) { - FMT_ASSERT(remainder < divisor, ""); // divisor - remainder won't overflow. - FMT_ASSERT(error < divisor, ""); // divisor - error won't overflow. - FMT_ASSERT(error < divisor - error, ""); // error * 2 won't overflow. - // Round down if (remainder + error) * 2 <= divisor. - if (remainder <= divisor - remainder && error * 2 <= divisor - remainder * 2) - return round_direction::down; - // Round up if (remainder - error) * 2 >= divisor. - if (remainder >= error && - remainder - error >= divisor - (remainder - error)) { - return round_direction::up; - } - return round_direction::unknown; -} - -namespace digits { -enum result { - more, // Generate more digits. - done, // Done generating digits. - error // Digit generation cancelled due to an error. -}; -} - -// Generates output using the Grisu digit-gen algorithm. -// error: the size of the region (lower, upper) outside of which numbers -// definitely do not round to value (Delta in Grisu3). -template <typename Handler> -FMT_ALWAYS_INLINE digits::result grisu_gen_digits(fp value, uint64_t error, - int& exp, Handler& handler) { - const fp one(1ULL << -value.e, value.e); - // The integral part of scaled value (p1 in Grisu) = value / one. It cannot be - // zero because it contains a product of two 64-bit numbers with MSB set (due - // to normalization) - 1, shifted right by at most 60 bits. - auto integral = static_cast<uint32_t>(value.f >> -one.e); - FMT_ASSERT(integral != 0, ""); - FMT_ASSERT(integral == value.f >> -one.e, ""); - // The fractional part of scaled value (p2 in Grisu) c = value % one. - uint64_t fractional = value.f & (one.f - 1); + int quotient = 0; + do { + subtract_aligned(divisor); + ++quotient; + } while (compare(*this, divisor) >= 0); + return quotient; + } +}; + +enum class round_direction { unknown, up, down }; + +// Given the divisor (normally a power of 10), the remainder = v % divisor for +// some number v and the error, returns whether v should be rounded up, down, or +// whether the rounding direction can't be determined due to error. +// error should be less than divisor / 2. +inline round_direction get_round_direction(uint64_t divisor, uint64_t remainder, + uint64_t error) { + FMT_ASSERT(remainder < divisor, ""); // divisor - remainder won't overflow. + FMT_ASSERT(error < divisor, ""); // divisor - error won't overflow. + FMT_ASSERT(error < divisor - error, ""); // error * 2 won't overflow. + // Round down if (remainder + error) * 2 <= divisor. + if (remainder <= divisor - remainder && error * 2 <= divisor - remainder * 2) + return round_direction::down; + // Round up if (remainder - error) * 2 >= divisor. + if (remainder >= error && + remainder - error >= divisor - (remainder - error)) { + return round_direction::up; + } + return round_direction::unknown; +} + +namespace digits { +enum result { + more, // Generate more digits. + done, // Done generating digits. + error // Digit generation cancelled due to an error. +}; +} + +// Generates output using the Grisu digit-gen algorithm. +// error: the size of the region (lower, upper) outside of which numbers +// definitely do not round to value (Delta in Grisu3). +template <typename Handler> +FMT_ALWAYS_INLINE digits::result grisu_gen_digits(fp value, uint64_t error, + int& exp, Handler& handler) { + const fp one(1ULL << -value.e, value.e); + // The integral part of scaled value (p1 in Grisu) = value / one. It cannot be + // zero because it contains a product of two 64-bit numbers with MSB set (due + // to normalization) - 1, shifted right by at most 60 bits. + auto integral = static_cast<uint32_t>(value.f >> -one.e); + FMT_ASSERT(integral != 0, ""); + FMT_ASSERT(integral == value.f >> -one.e, ""); + // The fractional part of scaled value (p2 in Grisu) c = value % one. + uint64_t fractional = value.f & (one.f - 1); exp = count_digits(integral); // kappa in Grisu. - // Divide by 10 to prevent overflow. - auto result = handler.on_start(data::powers_of_10_64[exp - 1] << -one.e, - value.f / 10, error * 10, exp); - if (result != digits::more) return result; - // Generate digits for the integral part. This can produce up to 10 digits. - do { - uint32_t digit = 0; - auto divmod_integral = [&](uint32_t divisor) { - digit = integral / divisor; - integral %= divisor; - }; - // This optimization by Milo Yip reduces the number of integer divisions by - // one per iteration. - switch (exp) { - case 10: - divmod_integral(1000000000); - break; - case 9: - divmod_integral(100000000); - break; - case 8: - divmod_integral(10000000); - break; - case 7: - divmod_integral(1000000); - break; - case 6: - divmod_integral(100000); - break; - case 5: - divmod_integral(10000); - break; - case 4: - divmod_integral(1000); - break; - case 3: - divmod_integral(100); - break; - case 2: - divmod_integral(10); - break; - case 1: - digit = integral; - integral = 0; - break; - default: - FMT_ASSERT(false, "invalid number of digits"); - } - --exp; + // Divide by 10 to prevent overflow. + auto result = handler.on_start(data::powers_of_10_64[exp - 1] << -one.e, + value.f / 10, error * 10, exp); + if (result != digits::more) return result; + // Generate digits for the integral part. This can produce up to 10 digits. + do { + uint32_t digit = 0; + auto divmod_integral = [&](uint32_t divisor) { + digit = integral / divisor; + integral %= divisor; + }; + // This optimization by Milo Yip reduces the number of integer divisions by + // one per iteration. + switch (exp) { + case 10: + divmod_integral(1000000000); + break; + case 9: + divmod_integral(100000000); + break; + case 8: + divmod_integral(10000000); + break; + case 7: + divmod_integral(1000000); + break; + case 6: + divmod_integral(100000); + break; + case 5: + divmod_integral(10000); + break; + case 4: + divmod_integral(1000); + break; + case 3: + divmod_integral(100); + break; + case 2: + divmod_integral(10); + break; + case 1: + digit = integral; + integral = 0; + break; + default: + FMT_ASSERT(false, "invalid number of digits"); + } + --exp; auto remainder = (static_cast<uint64_t>(integral) << -one.e) + fractional; - result = handler.on_digit(static_cast<char>('0' + digit), - data::powers_of_10_64[exp] << -one.e, remainder, - error, exp, true); - if (result != digits::more) return result; - } while (exp > 0); - // Generate digits for the fractional part. - for (;;) { - fractional *= 10; - error *= 10; + result = handler.on_digit(static_cast<char>('0' + digit), + data::powers_of_10_64[exp] << -one.e, remainder, + error, exp, true); + if (result != digits::more) return result; + } while (exp > 0); + // Generate digits for the fractional part. + for (;;) { + fractional *= 10; + error *= 10; char digit = static_cast<char>('0' + (fractional >> -one.e)); - fractional &= one.f - 1; - --exp; - result = handler.on_digit(digit, one.f, fractional, error, exp, false); - if (result != digits::more) return result; - } -} - -// The fixed precision digit handler. -struct fixed_handler { - char* buf; - int size; - int precision; - int exp10; - bool fixed; - - digits::result on_start(uint64_t divisor, uint64_t remainder, uint64_t error, - int& exp) { - // Non-fixed formats require at least one digit and no precision adjustment. - if (!fixed) return digits::more; - // Adjust fixed precision by exponent because it is relative to decimal - // point. - precision += exp + exp10; - // Check if precision is satisfied just by leading zeros, e.g. - // format("{:.2f}", 0.001) gives "0.00" without generating any digits. - if (precision > 0) return digits::more; - if (precision < 0) return digits::done; - auto dir = get_round_direction(divisor, remainder, error); - if (dir == round_direction::unknown) return digits::error; - buf[size++] = dir == round_direction::up ? '1' : '0'; - return digits::done; - } - - digits::result on_digit(char digit, uint64_t divisor, uint64_t remainder, - uint64_t error, int, bool integral) { - FMT_ASSERT(remainder < divisor, ""); - buf[size++] = digit; + fractional &= one.f - 1; + --exp; + result = handler.on_digit(digit, one.f, fractional, error, exp, false); + if (result != digits::more) return result; + } +} + +// The fixed precision digit handler. +struct fixed_handler { + char* buf; + int size; + int precision; + int exp10; + bool fixed; + + digits::result on_start(uint64_t divisor, uint64_t remainder, uint64_t error, + int& exp) { + // Non-fixed formats require at least one digit and no precision adjustment. + if (!fixed) return digits::more; + // Adjust fixed precision by exponent because it is relative to decimal + // point. + precision += exp + exp10; + // Check if precision is satisfied just by leading zeros, e.g. + // format("{:.2f}", 0.001) gives "0.00" without generating any digits. + if (precision > 0) return digits::more; + if (precision < 0) return digits::done; + auto dir = get_round_direction(divisor, remainder, error); + if (dir == round_direction::unknown) return digits::error; + buf[size++] = dir == round_direction::up ? '1' : '0'; + return digits::done; + } + + digits::result on_digit(char digit, uint64_t divisor, uint64_t remainder, + uint64_t error, int, bool integral) { + FMT_ASSERT(remainder < divisor, ""); + buf[size++] = digit; if (!integral && error >= remainder) return digits::error; - if (size < precision) return digits::more; - if (!integral) { - // Check if error * 2 < divisor with overflow prevention. - // The check is not needed for the integral part because error = 1 - // and divisor > (1 << 32) there. - if (error >= divisor || error >= divisor - error) return digits::error; - } else { - FMT_ASSERT(error == 1 && divisor > 2, ""); - } - auto dir = get_round_direction(divisor, remainder, error); - if (dir != round_direction::up) - return dir == round_direction::down ? digits::done : digits::error; - ++buf[size - 1]; - for (int i = size - 1; i > 0 && buf[i] > '9'; --i) { - buf[i] = '0'; - ++buf[i - 1]; - } - if (buf[0] > '9') { - buf[0] = '1'; + if (size < precision) return digits::more; + if (!integral) { + // Check if error * 2 < divisor with overflow prevention. + // The check is not needed for the integral part because error = 1 + // and divisor > (1 << 32) there. + if (error >= divisor || error >= divisor - error) return digits::error; + } else { + FMT_ASSERT(error == 1 && divisor > 2, ""); + } + auto dir = get_round_direction(divisor, remainder, error); + if (dir != round_direction::up) + return dir == round_direction::down ? digits::done : digits::error; + ++buf[size - 1]; + for (int i = size - 1; i > 0 && buf[i] > '9'; --i) { + buf[i] = '0'; + ++buf[i - 1]; + } + if (buf[0] > '9') { + buf[0] = '1'; if (fixed) buf[size++] = '0'; else ++exp10; - } - return digits::done; - } -}; - + } + return digits::done; + } +}; + // Implementation of Dragonbox algorithm: https://github.com/jk-jeon/dragonbox. namespace dragonbox { // Computes 128-bit result of multiplication of two 64-bit unsigned integers. @@ -1656,7 +1656,7 @@ FMT_SAFEBUFFERS inline uint128_wrapper umul128(uint64_t x, return result; #else const uint64_t mask = (uint64_t(1) << 32) - uint64_t(1); - + uint64_t a = x >> 32; uint64_t b = x & mask; uint64_t c = y >> 32; @@ -1832,8 +1832,8 @@ template <> struct cache_accessor<float> { FMT_ASSERT(k >= float_info<float>::min_k && k <= float_info<float>::max_k, "k is out of range"); return data::dragonbox_pow10_significands_64[k - float_info<float>::min_k]; - } - + } + static carrier_uint compute_mul(carrier_uint u, const cache_entry_type& cache) FMT_NOEXCEPT { return umul96_upper32(u, cache); @@ -2070,9 +2070,9 @@ FMT_ALWAYS_INLINE int remove_trailing_zeros(uint64_t& n) FMT_NOEXCEPT { quotient >>= (s - 8); n = quotient; return s; - } - } - + } + } + // Otherwise, work with the remainder auto quotient = static_cast<uint32_t>(n / 100000000); auto remainder = static_cast<uint32_t>(n - 100000000 * quotient); @@ -2234,7 +2234,7 @@ FMT_SAFEBUFFERS decimal_fp<T> to_decimal(T x) FMT_NOEXCEPT { --ret_value.significand; r = float_info<T>::big_divisor; goto small_divisor_case_label; - } + } } else { // r == deltai; compare fractional parts // Check conditions in the order different from the paper @@ -2245,9 +2245,9 @@ FMT_SAFEBUFFERS decimal_fp<T> to_decimal(T x) FMT_NOEXCEPT { !cache_accessor<T>::compute_mul_parity(two_fl, cache, beta_minus_1)) { goto small_divisor_case_label; } - } + } ret_value.exponent = minus_k + float_info<T>::kappa + 1; - + // We may need to remove trailing zeros ret_value.exponent += remove_trailing_zeros(ret_value.significand); return ret_value; @@ -2306,60 +2306,60 @@ small_divisor_case_label: } } // namespace dragonbox -// Formats value using a variation of the Fixed-Precision Positive -// Floating-Point Printout ((FPP)^2) algorithm by Steele & White: -// https://fmt.dev/p372-steele.pdf. -template <typename Double> +// Formats value using a variation of the Fixed-Precision Positive +// Floating-Point Printout ((FPP)^2) algorithm by Steele & White: +// https://fmt.dev/p372-steele.pdf. +template <typename Double> void fallback_format(Double d, int num_digits, bool binary32, buffer<char>& buf, int& exp10) { - bigint numerator; // 2 * R in (FPP)^2. - bigint denominator; // 2 * S in (FPP)^2. - // lower and upper are differences between value and corresponding boundaries. - bigint lower; // (M^- in (FPP)^2). - bigint upper_store; // upper's value if different from lower. - bigint* upper = nullptr; // (M^+ in (FPP)^2). - fp value; - // Shift numerator and denominator by an extra bit or two (if lower boundary - // is closer) to make lower and upper integers. This eliminates multiplication - // by 2 during later computations. + bigint numerator; // 2 * R in (FPP)^2. + bigint denominator; // 2 * S in (FPP)^2. + // lower and upper are differences between value and corresponding boundaries. + bigint lower; // (M^- in (FPP)^2). + bigint upper_store; // upper's value if different from lower. + bigint* upper = nullptr; // (M^+ in (FPP)^2). + fp value; + // Shift numerator and denominator by an extra bit or two (if lower boundary + // is closer) to make lower and upper integers. This eliminates multiplication + // by 2 during later computations. const bool is_predecessor_closer = binary32 ? value.assign(static_cast<float>(d)) : value.assign(d); int shift = is_predecessor_closer ? 2 : 1; - uint64_t significand = value.f << shift; - if (value.e >= 0) { - numerator.assign(significand); - numerator <<= value.e; - lower.assign(1); - lower <<= value.e; - if (shift != 1) { - upper_store.assign(1); - upper_store <<= value.e + 1; - upper = &upper_store; - } - denominator.assign_pow10(exp10); + uint64_t significand = value.f << shift; + if (value.e >= 0) { + numerator.assign(significand); + numerator <<= value.e; + lower.assign(1); + lower <<= value.e; + if (shift != 1) { + upper_store.assign(1); + upper_store <<= value.e + 1; + upper = &upper_store; + } + denominator.assign_pow10(exp10); denominator <<= shift; - } else if (exp10 < 0) { - numerator.assign_pow10(-exp10); - lower.assign(numerator); - if (shift != 1) { - upper_store.assign(numerator); - upper_store <<= 1; - upper = &upper_store; - } - numerator *= significand; - denominator.assign(1); - denominator <<= shift - value.e; - } else { - numerator.assign(significand); - denominator.assign_pow10(exp10); - denominator <<= shift - value.e; - lower.assign(1); - if (shift != 1) { - upper_store.assign(1ULL << 1); - upper = &upper_store; - } - } - // Invariant: value == (numerator / denominator) * pow(10, exp10). + } else if (exp10 < 0) { + numerator.assign_pow10(-exp10); + lower.assign(numerator); + if (shift != 1) { + upper_store.assign(numerator); + upper_store <<= 1; + upper = &upper_store; + } + numerator *= significand; + denominator.assign(1); + denominator <<= shift - value.e; + } else { + numerator.assign(significand); + denominator.assign_pow10(exp10); + denominator <<= shift - value.e; + lower.assign(1); + if (shift != 1) { + upper_store.assign(1ULL << 1); + upper = &upper_store; + } + } + // Invariant: value == (numerator / denominator) * pow(10, exp10). if (num_digits < 0) { // Generate the shortest representation. if (!upper) upper = &lower; @@ -2374,7 +2374,7 @@ void fallback_format(Double d, int num_digits, bool binary32, buffer<char>& buf, data[num_digits++] = static_cast<char>('0' + digit); if (low || high) { if (!low) { - ++data[num_digits - 1]; + ++data[num_digits - 1]; } else if (high) { int result = add_compare(numerator, numerator, denominator); // Round half to even. @@ -2384,11 +2384,11 @@ void fallback_format(Double d, int num_digits, bool binary32, buffer<char>& buf, buf.try_resize(to_unsigned(num_digits)); exp10 -= num_digits - 1; return; - } + } numerator *= 10; lower *= 10; if (upper != &lower) *upper *= 10; - } + } } // Generate the given number of digits. exp10 -= num_digits - 1; @@ -2402,8 +2402,8 @@ void fallback_format(Double d, int num_digits, bool binary32, buffer<char>& buf, for (int i = 0; i < num_digits - 1; ++i) { int digit = numerator.divmod_assign(denominator); buf[i] = static_cast<char>('0' + digit); - numerator *= 10; - } + numerator *= 10; + } int digit = numerator.divmod_assign(denominator); auto result = add_compare(numerator, numerator, denominator); if (result > 0 || (result == 0 && (digit % 2) != 0)) { @@ -2424,26 +2424,26 @@ void fallback_format(Double d, int num_digits, bool binary32, buffer<char>& buf, ++digit; } buf[num_digits - 1] = static_cast<char>('0' + digit); -} - -template <typename T> -int format_float(T value, int precision, float_specs specs, buffer<char>& buf) { - static_assert(!std::is_same<T, float>::value, ""); - FMT_ASSERT(value >= 0, "value is negative"); - - const bool fixed = specs.format == float_format::fixed; - if (value <= 0) { // <= instead of == to silence a warning. - if (precision <= 0 || !fixed) { - buf.push_back('0'); - return 0; - } +} + +template <typename T> +int format_float(T value, int precision, float_specs specs, buffer<char>& buf) { + static_assert(!std::is_same<T, float>::value, ""); + FMT_ASSERT(value >= 0, "value is negative"); + + const bool fixed = specs.format == float_format::fixed; + if (value <= 0) { // <= instead of == to silence a warning. + if (precision <= 0 || !fixed) { + buf.push_back('0'); + return 0; + } buf.try_resize(to_unsigned(precision)); - std::uninitialized_fill_n(buf.data(), precision, '0'); - return -precision; - } - - if (!specs.use_grisu) return snprintf_float(value, precision, specs, buf); - + std::uninitialized_fill_n(buf.data(), precision, '0'); + return -precision; + } + + if (!specs.use_grisu) return snprintf_float(value, precision, specs, buf); + if (precision < 0) { // Use Dragonbox for the shortest format. if (specs.binary32) { @@ -2458,9 +2458,9 @@ int format_float(T value, int precision, float_specs specs, buffer<char>& buf) { // Use Grisu + Dragon4 for the given precision: // https://www.cs.tufts.edu/~nr/cs257/archive/florian-loitsch/printf.pdf. - int exp = 0; - const int min_exp = -60; // alpha in Grisu. - int cached_exp10 = 0; // K in Grisu. + int exp = 0; + const int min_exp = -60; // alpha in Grisu. + int cached_exp10 = 0; // K in Grisu. fp normalized = normalize(fp(value)); const auto cached_pow = get_cached_power( min_exp - (normalized.e + fp::significand_size), cached_exp10); @@ -2473,7 +2473,7 @@ int format_float(T value, int precision, float_specs specs, buffer<char>& buf) { if (grisu_gen_digits(normalized, 1, exp, handler) == digits::error) { exp += handler.size - cached_exp10 - 1; fallback_format(value, handler.precision, specs.binary32, buf, exp); - } else { + } else { exp += handler.exp10; buf.try_resize(to_unsigned(handler.size)); } @@ -2483,164 +2483,164 @@ int format_float(T value, int precision, float_specs specs, buffer<char>& buf) { while (num_digits > 0 && buf[num_digits - 1] == '0') { --num_digits; ++exp; - } + } buf.try_resize(num_digits); - } + } return exp; } // namespace detail - -template <typename T> -int snprintf_float(T value, int precision, float_specs specs, - buffer<char>& buf) { - // Buffer capacity must be non-zero, otherwise MSVC's vsnprintf_s will fail. - FMT_ASSERT(buf.capacity() > buf.size(), "empty buffer"); - static_assert(!std::is_same<T, float>::value, ""); - - // Subtract 1 to account for the difference in precision since we use %e for - // both general and exponent format. - if (specs.format == float_format::general || - specs.format == float_format::exp) - precision = (precision >= 0 ? precision : 6) - 1; - - // Build the format string. + +template <typename T> +int snprintf_float(T value, int precision, float_specs specs, + buffer<char>& buf) { + // Buffer capacity must be non-zero, otherwise MSVC's vsnprintf_s will fail. + FMT_ASSERT(buf.capacity() > buf.size(), "empty buffer"); + static_assert(!std::is_same<T, float>::value, ""); + + // Subtract 1 to account for the difference in precision since we use %e for + // both general and exponent format. + if (specs.format == float_format::general || + specs.format == float_format::exp) + precision = (precision >= 0 ? precision : 6) - 1; + + // Build the format string. enum { max_format_size = 7 }; // The longest format is "%#.*Le". - char format[max_format_size]; - char* format_ptr = format; - *format_ptr++ = '%'; - if (specs.showpoint && specs.format == float_format::hex) *format_ptr++ = '#'; - if (precision >= 0) { - *format_ptr++ = '.'; - *format_ptr++ = '*'; - } - if (std::is_same<T, long double>()) *format_ptr++ = 'L'; - *format_ptr++ = specs.format != float_format::hex - ? (specs.format == float_format::fixed ? 'f' : 'e') - : (specs.upper ? 'A' : 'a'); - *format_ptr = '\0'; - - // Format using snprintf. - auto offset = buf.size(); - for (;;) { - auto begin = buf.data() + offset; - auto capacity = buf.capacity() - offset; + char format[max_format_size]; + char* format_ptr = format; + *format_ptr++ = '%'; + if (specs.showpoint && specs.format == float_format::hex) *format_ptr++ = '#'; + if (precision >= 0) { + *format_ptr++ = '.'; + *format_ptr++ = '*'; + } + if (std::is_same<T, long double>()) *format_ptr++ = 'L'; + *format_ptr++ = specs.format != float_format::hex + ? (specs.format == float_format::fixed ? 'f' : 'e') + : (specs.upper ? 'A' : 'a'); + *format_ptr = '\0'; + + // Format using snprintf. + auto offset = buf.size(); + for (;;) { + auto begin = buf.data() + offset; + auto capacity = buf.capacity() - offset; #ifdef FMT_FUZZ - if (precision > 100000) - throw std::runtime_error( - "fuzz mode - avoid large allocation inside snprintf"); -#endif - // Suppress the warning about a nonliteral format string. + if (precision > 100000) + throw std::runtime_error( + "fuzz mode - avoid large allocation inside snprintf"); +#endif + // Suppress the warning about a nonliteral format string. // Cannot use auto because of a bug in MinGW (#1532). - int (*snprintf_ptr)(char*, size_t, const char*, ...) = FMT_SNPRINTF; - int result = precision >= 0 - ? snprintf_ptr(begin, capacity, format, precision, value) - : snprintf_ptr(begin, capacity, format, value); - if (result < 0) { + int (*snprintf_ptr)(char*, size_t, const char*, ...) = FMT_SNPRINTF; + int result = precision >= 0 + ? snprintf_ptr(begin, capacity, format, precision, value) + : snprintf_ptr(begin, capacity, format, value); + if (result < 0) { // The buffer will grow exponentially. buf.try_reserve(buf.capacity() + 1); - continue; - } - auto size = to_unsigned(result); - // Size equal to capacity means that the last character was truncated. - if (size >= capacity) { + continue; + } + auto size = to_unsigned(result); + // Size equal to capacity means that the last character was truncated. + if (size >= capacity) { buf.try_reserve(size + offset + 1); // Add 1 for the terminating '\0'. - continue; - } - auto is_digit = [](char c) { return c >= '0' && c <= '9'; }; - if (specs.format == float_format::fixed) { - if (precision == 0) { + continue; + } + auto is_digit = [](char c) { return c >= '0' && c <= '9'; }; + if (specs.format == float_format::fixed) { + if (precision == 0) { buf.try_resize(size); - return 0; - } - // Find and remove the decimal point. - auto end = begin + size, p = end; - do { - --p; - } while (is_digit(*p)); - int fraction_size = static_cast<int>(end - p - 1); - std::memmove(p, p + 1, to_unsigned(fraction_size)); + return 0; + } + // Find and remove the decimal point. + auto end = begin + size, p = end; + do { + --p; + } while (is_digit(*p)); + int fraction_size = static_cast<int>(end - p - 1); + std::memmove(p, p + 1, to_unsigned(fraction_size)); buf.try_resize(size - 1); - return -fraction_size; - } - if (specs.format == float_format::hex) { + return -fraction_size; + } + if (specs.format == float_format::hex) { buf.try_resize(size + offset); - return 0; - } - // Find and parse the exponent. - auto end = begin + size, exp_pos = end; - do { - --exp_pos; - } while (*exp_pos != 'e'); - char sign = exp_pos[1]; - assert(sign == '+' || sign == '-'); - int exp = 0; - auto p = exp_pos + 2; // Skip 'e' and sign. - do { - assert(is_digit(*p)); - exp = exp * 10 + (*p++ - '0'); - } while (p != end); - if (sign == '-') exp = -exp; - int fraction_size = 0; - if (exp_pos != begin + 1) { - // Remove trailing zeros. - auto fraction_end = exp_pos - 1; - while (*fraction_end == '0') --fraction_end; - // Move the fractional part left to get rid of the decimal point. - fraction_size = static_cast<int>(fraction_end - begin - 1); - std::memmove(begin + 1, begin + 2, to_unsigned(fraction_size)); - } + return 0; + } + // Find and parse the exponent. + auto end = begin + size, exp_pos = end; + do { + --exp_pos; + } while (*exp_pos != 'e'); + char sign = exp_pos[1]; + assert(sign == '+' || sign == '-'); + int exp = 0; + auto p = exp_pos + 2; // Skip 'e' and sign. + do { + assert(is_digit(*p)); + exp = exp * 10 + (*p++ - '0'); + } while (p != end); + if (sign == '-') exp = -exp; + int fraction_size = 0; + if (exp_pos != begin + 1) { + // Remove trailing zeros. + auto fraction_end = exp_pos - 1; + while (*fraction_end == '0') --fraction_end; + // Move the fractional part left to get rid of the decimal point. + fraction_size = static_cast<int>(fraction_end - begin - 1); + std::memmove(begin + 1, begin + 2, to_unsigned(fraction_size)); + } buf.try_resize(to_unsigned(fraction_size) + offset + 1); - return exp - fraction_size; - } -} - -// A public domain branchless UTF-8 decoder by Christopher Wellons: -// https://github.com/skeeto/branchless-utf8 -/* Decode the next character, c, from buf, reporting errors in e. - * - * Since this is a branchless decoder, four bytes will be read from the - * buffer regardless of the actual length of the next character. This - * means the buffer _must_ have at least three bytes of zero padding - * following the end of the data stream. - * - * Errors are reported in e, which will be non-zero if the parsed - * character was somehow invalid: invalid byte sequence, non-canonical - * encoding, or a surrogate half. - * - * The function returns a pointer to the next character. When an error - * occurs, this pointer will be a guess that depends on the particular - * error, but it will always advance at least one byte. - */ + return exp - fraction_size; + } +} + +// A public domain branchless UTF-8 decoder by Christopher Wellons: +// https://github.com/skeeto/branchless-utf8 +/* Decode the next character, c, from buf, reporting errors in e. + * + * Since this is a branchless decoder, four bytes will be read from the + * buffer regardless of the actual length of the next character. This + * means the buffer _must_ have at least three bytes of zero padding + * following the end of the data stream. + * + * Errors are reported in e, which will be non-zero if the parsed + * character was somehow invalid: invalid byte sequence, non-canonical + * encoding, or a surrogate half. + * + * The function returns a pointer to the next character. When an error + * occurs, this pointer will be a guess that depends on the particular + * error, but it will always advance at least one byte. + */ inline const char* utf8_decode(const char* buf, uint32_t* c, int* e) { - static const int masks[] = {0x00, 0x7f, 0x1f, 0x0f, 0x07}; - static const uint32_t mins[] = {4194304, 0, 128, 2048, 65536}; - static const int shiftc[] = {0, 18, 12, 6, 0}; - static const int shifte[] = {0, 6, 4, 2, 0}; - + static const int masks[] = {0x00, 0x7f, 0x1f, 0x0f, 0x07}; + static const uint32_t mins[] = {4194304, 0, 128, 2048, 65536}; + static const int shiftc[] = {0, 18, 12, 6, 0}; + static const int shifte[] = {0, 6, 4, 2, 0}; + int len = code_point_length(buf); const char* next = buf + len; - - // Assume a four-byte character and load four bytes. Unused bits are - // shifted out. + + // Assume a four-byte character and load four bytes. Unused bits are + // shifted out. auto s = reinterpret_cast<const unsigned char*>(buf); - *c = uint32_t(s[0] & masks[len]) << 18; - *c |= uint32_t(s[1] & 0x3f) << 12; - *c |= uint32_t(s[2] & 0x3f) << 6; - *c |= uint32_t(s[3] & 0x3f) << 0; - *c >>= shiftc[len]; - - // Accumulate the various error conditions. - *e = (*c < mins[len]) << 6; // non-canonical encoding - *e |= ((*c >> 11) == 0x1b) << 7; // surrogate half? - *e |= (*c > 0x10FFFF) << 8; // out of range? - *e |= (s[1] & 0xc0) >> 2; - *e |= (s[2] & 0xc0) >> 4; - *e |= (s[3]) >> 6; - *e ^= 0x2a; // top two bits of each tail byte correct? - *e >>= shifte[len]; - - return next; -} - + *c = uint32_t(s[0] & masks[len]) << 18; + *c |= uint32_t(s[1] & 0x3f) << 12; + *c |= uint32_t(s[2] & 0x3f) << 6; + *c |= uint32_t(s[3] & 0x3f) << 0; + *c >>= shiftc[len]; + + // Accumulate the various error conditions. + *e = (*c < mins[len]) << 6; // non-canonical encoding + *e |= ((*c >> 11) == 0x1b) << 7; // surrogate half? + *e |= (*c > 0x10FFFF) << 8; // out of range? + *e |= (s[1] & 0xc0) >> 2; + *e |= (s[2] & 0xc0) >> 4; + *e |= (s[3]) >> 6; + *e ^= 0x2a; // top two bits of each tail byte correct? + *e >>= shifte[len]; + + return next; +} + struct stringifier { template <typename T> FMT_INLINE std::string operator()(T value) const { return to_string(value); @@ -2656,92 +2656,92 @@ struct stringifier { } // namespace detail template <> struct formatter<detail::bigint> { - format_parse_context::iterator parse(format_parse_context& ctx) { - return ctx.begin(); - } - + format_parse_context::iterator parse(format_parse_context& ctx) { + return ctx.begin(); + } + format_context::iterator format(const detail::bigint& n, - format_context& ctx) { - auto out = ctx.out(); - bool first = true; - for (auto i = n.bigits_.size(); i > 0; --i) { - auto value = n.bigits_[i - 1u]; - if (first) { - out = format_to(out, "{:x}", value); - first = false; - continue; - } - out = format_to(out, "{:08x}", value); - } - if (n.exp_ > 0) + format_context& ctx) { + auto out = ctx.out(); + bool first = true; + for (auto i = n.bigits_.size(); i > 0; --i) { + auto value = n.bigits_[i - 1u]; + if (first) { + out = format_to(out, "{:x}", value); + first = false; + continue; + } + out = format_to(out, "{:08x}", value); + } + if (n.exp_ > 0) out = format_to(out, "p{}", n.exp_ * detail::bigint::bigit_bits); - return out; - } -}; - + return out; + } +}; + FMT_FUNC detail::utf8_to_utf16::utf8_to_utf16(string_view s) { - auto transcode = [this](const char* p) { - auto cp = uint32_t(); - auto error = 0; - p = utf8_decode(p, &cp, &error); - if (error != 0) FMT_THROW(std::runtime_error("invalid utf8")); - if (cp <= 0xFFFF) { - buffer_.push_back(static_cast<wchar_t>(cp)); - } else { - cp -= 0x10000; - buffer_.push_back(static_cast<wchar_t>(0xD800 + (cp >> 10))); - buffer_.push_back(static_cast<wchar_t>(0xDC00 + (cp & 0x3FF))); - } - return p; - }; - auto p = s.data(); - const size_t block_size = 4; // utf8_decode always reads blocks of 4 chars. - if (s.size() >= block_size) { - for (auto end = p + s.size() - block_size + 1; p < end;) p = transcode(p); - } - if (auto num_chars_left = s.data() + s.size() - p) { - char buf[2 * block_size - 1] = {}; - memcpy(buf, p, to_unsigned(num_chars_left)); - p = buf; - do { - p = transcode(p); - } while (p - buf < num_chars_left); - } - buffer_.push_back(0); -} - + auto transcode = [this](const char* p) { + auto cp = uint32_t(); + auto error = 0; + p = utf8_decode(p, &cp, &error); + if (error != 0) FMT_THROW(std::runtime_error("invalid utf8")); + if (cp <= 0xFFFF) { + buffer_.push_back(static_cast<wchar_t>(cp)); + } else { + cp -= 0x10000; + buffer_.push_back(static_cast<wchar_t>(0xD800 + (cp >> 10))); + buffer_.push_back(static_cast<wchar_t>(0xDC00 + (cp & 0x3FF))); + } + return p; + }; + auto p = s.data(); + const size_t block_size = 4; // utf8_decode always reads blocks of 4 chars. + if (s.size() >= block_size) { + for (auto end = p + s.size() - block_size + 1; p < end;) p = transcode(p); + } + if (auto num_chars_left = s.data() + s.size() - p) { + char buf[2 * block_size - 1] = {}; + memcpy(buf, p, to_unsigned(num_chars_left)); + p = buf; + do { + p = transcode(p); + } while (p - buf < num_chars_left); + } + buffer_.push_back(0); +} + FMT_FUNC void format_system_error(detail::buffer<char>& out, int error_code, - string_view message) FMT_NOEXCEPT { - FMT_TRY { - memory_buffer buf; - buf.resize(inline_buffer_size); - for (;;) { - char* system_message = &buf[0]; - int result = + string_view message) FMT_NOEXCEPT { + FMT_TRY { + memory_buffer buf; + buf.resize(inline_buffer_size); + for (;;) { + char* system_message = &buf[0]; + int result = detail::safe_strerror(error_code, system_message, buf.size()); - if (result == 0) { + if (result == 0) { format_to(detail::buffer_appender<char>(out), "{}: {}", message, system_message); - return; - } - if (result != ERANGE) - break; // Can't get error message, report error code instead. - buf.resize(buf.size() * 2); - } - } - FMT_CATCH(...) {} - format_error_code(out, error_code, message); -} - + return; + } + if (result != ERANGE) + break; // Can't get error message, report error code instead. + buf.resize(buf.size() * 2); + } + } + FMT_CATCH(...) {} + format_error_code(out, error_code, message); +} + FMT_FUNC void detail::error_handler::on_error(const char* message) { - FMT_THROW(format_error(message)); -} - -FMT_FUNC void report_system_error(int error_code, - fmt::string_view message) FMT_NOEXCEPT { - report_error(format_system_error, error_code, message); -} - + FMT_THROW(format_error(message)); +} + +FMT_FUNC void report_system_error(int error_code, + fmt::string_view message) FMT_NOEXCEPT { + report_error(format_system_error, error_code, message); +} + FMT_FUNC std::string detail::vformat(string_view format_str, format_args args) { if (format_str.size() == 2 && equal2(format_str.data(), "{}")) { auto arg = args.get(0); @@ -2761,41 +2761,41 @@ extern "C" __declspec(dllimport) int __stdcall WriteConsoleW( // } // namespace detail #endif -FMT_FUNC void vprint(std::FILE* f, string_view format_str, format_args args) { - memory_buffer buffer; +FMT_FUNC void vprint(std::FILE* f, string_view format_str, format_args args) { + memory_buffer buffer; detail::vformat_to(buffer, format_str, basic_format_args<buffer_context<char>>(args)); -#ifdef _WIN32 - auto fd = _fileno(f); - if (_isatty(fd)) { +#ifdef _WIN32 + auto fd = _fileno(f); + if (_isatty(fd)) { detail::utf8_to_utf16 u16(string_view(buffer.data(), buffer.size())); auto written = detail::dword(); if (!detail::WriteConsoleW(reinterpret_cast<void*>(_get_osfhandle(fd)), u16.c_str(), static_cast<uint32_t>(u16.size()), &written, nullptr)) { - FMT_THROW(format_error("failed to write to console")); - } - return; - } -#endif + FMT_THROW(format_error("failed to write to console")); + } + return; + } +#endif detail::fwrite_fully(buffer.data(), 1, buffer.size(), f); -} - -#ifdef _WIN32 -// Print assuming legacy (non-Unicode) encoding. +} + +#ifdef _WIN32 +// Print assuming legacy (non-Unicode) encoding. FMT_FUNC void detail::vprint_mojibake(std::FILE* f, string_view format_str, format_args args) { - memory_buffer buffer; + memory_buffer buffer; detail::vformat_to(buffer, format_str, basic_format_args<buffer_context<char>>(args)); - fwrite_fully(buffer.data(), 1, buffer.size(), f); -} -#endif - -FMT_FUNC void vprint(string_view format_str, format_args args) { - vprint(stdout, format_str, args); -} - -FMT_END_NAMESPACE - -#endif // FMT_FORMAT_INL_H_ + fwrite_fully(buffer.data(), 1, buffer.size(), f); +} +#endif + +FMT_FUNC void vprint(string_view format_str, format_args args) { + vprint(stdout, format_str, args); +} + +FMT_END_NAMESPACE + +#endif // FMT_FORMAT_INL_H_ diff --git a/contrib/libs/fmt/include/fmt/format.h b/contrib/libs/fmt/include/fmt/format.h index f45fdb0789..9d0a42be85 100644 --- a/contrib/libs/fmt/include/fmt/format.h +++ b/contrib/libs/fmt/include/fmt/format.h @@ -1,92 +1,92 @@ -/* - Formatting library for C++ - - Copyright (c) 2012 - present, Victor Zverovich - - Permission is hereby granted, free of charge, to any person obtaining - a copy of this software and associated documentation files (the - "Software"), to deal in the Software without restriction, including - without limitation the rights to use, copy, modify, merge, publish, - distribute, sublicense, and/or sell copies of the Software, and to - permit persons to whom the Software is furnished to do so, subject to - the following conditions: - - The above copyright notice and this permission notice shall be - included in all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - - --- Optional exception to the license --- - - As an exception, if, as a result of your compiling your source code, portions - of this Software are embedded into a machine-executable object form of such - source code, you may redistribute such embedded portions in such object form - without including the above copyright and permission notices. - */ - -#ifndef FMT_FORMAT_H_ -#define FMT_FORMAT_H_ - -#include <algorithm> -#include <cerrno> -#include <cmath> -#include <cstdint> -#include <limits> -#include <memory> -#include <stdexcept> - -#include "core.h" - -#ifdef __INTEL_COMPILER -# define FMT_ICC_VERSION __INTEL_COMPILER -#elif defined(__ICL) -# define FMT_ICC_VERSION __ICL -#else -# define FMT_ICC_VERSION 0 -#endif - -#ifdef __NVCC__ -# define FMT_CUDA_VERSION (__CUDACC_VER_MAJOR__ * 100 + __CUDACC_VER_MINOR__) -#else -# define FMT_CUDA_VERSION 0 -#endif - -#ifdef __has_builtin -# define FMT_HAS_BUILTIN(x) __has_builtin(x) -#else -# define FMT_HAS_BUILTIN(x) 0 -#endif - -#if FMT_GCC_VERSION || FMT_CLANG_VERSION -# define FMT_NOINLINE __attribute__((noinline)) -#else -# define FMT_NOINLINE -#endif - -#if __cplusplus == 201103L || __cplusplus == 201402L +/* + Formatting library for C++ + + Copyright (c) 2012 - present, Victor Zverovich + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + "Software"), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to + permit persons to whom the Software is furnished to do so, subject to + the following conditions: + + The above copyright notice and this permission notice shall be + included in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + --- Optional exception to the license --- + + As an exception, if, as a result of your compiling your source code, portions + of this Software are embedded into a machine-executable object form of such + source code, you may redistribute such embedded portions in such object form + without including the above copyright and permission notices. + */ + +#ifndef FMT_FORMAT_H_ +#define FMT_FORMAT_H_ + +#include <algorithm> +#include <cerrno> +#include <cmath> +#include <cstdint> +#include <limits> +#include <memory> +#include <stdexcept> + +#include "core.h" + +#ifdef __INTEL_COMPILER +# define FMT_ICC_VERSION __INTEL_COMPILER +#elif defined(__ICL) +# define FMT_ICC_VERSION __ICL +#else +# define FMT_ICC_VERSION 0 +#endif + +#ifdef __NVCC__ +# define FMT_CUDA_VERSION (__CUDACC_VER_MAJOR__ * 100 + __CUDACC_VER_MINOR__) +#else +# define FMT_CUDA_VERSION 0 +#endif + +#ifdef __has_builtin +# define FMT_HAS_BUILTIN(x) __has_builtin(x) +#else +# define FMT_HAS_BUILTIN(x) 0 +#endif + +#if FMT_GCC_VERSION || FMT_CLANG_VERSION +# define FMT_NOINLINE __attribute__((noinline)) +#else +# define FMT_NOINLINE +#endif + +#if __cplusplus == 201103L || __cplusplus == 201402L # if defined(__INTEL_COMPILER) || defined(__PGI) # define FMT_FALLTHROUGH # elif defined(__clang__) -# define FMT_FALLTHROUGH [[clang::fallthrough]] +# define FMT_FALLTHROUGH [[clang::fallthrough]] # elif FMT_GCC_VERSION >= 700 && \ (!defined(__EDG_VERSION__) || __EDG_VERSION__ >= 520) -# define FMT_FALLTHROUGH [[gnu::fallthrough]] -# else -# define FMT_FALLTHROUGH -# endif -#elif FMT_HAS_CPP17_ATTRIBUTE(fallthrough) || \ - (defined(_MSVC_LANG) && _MSVC_LANG >= 201703L) -# define FMT_FALLTHROUGH [[fallthrough]] -#else -# define FMT_FALLTHROUGH -#endif - +# define FMT_FALLTHROUGH [[gnu::fallthrough]] +# else +# define FMT_FALLTHROUGH +# endif +#elif FMT_HAS_CPP17_ATTRIBUTE(fallthrough) || \ + (defined(_MSVC_LANG) && _MSVC_LANG >= 201703L) +# define FMT_FALLTHROUGH [[fallthrough]] +#else +# define FMT_FALLTHROUGH +#endif + #ifndef FMT_MAYBE_UNUSED # if FMT_HAS_CPP17_ATTRIBUTE(maybe_unused) # define FMT_MAYBE_UNUSED [[maybe_unused]] @@ -95,52 +95,52 @@ # endif #endif -#ifndef FMT_THROW -# if FMT_EXCEPTIONS -# if FMT_MSC_VER || FMT_NVCC -FMT_BEGIN_NAMESPACE +#ifndef FMT_THROW +# if FMT_EXCEPTIONS +# if FMT_MSC_VER || FMT_NVCC +FMT_BEGIN_NAMESPACE namespace detail { -template <typename Exception> inline void do_throw(const Exception& x) { - // Silence unreachable code warnings in MSVC and NVCC because these - // are nearly impossible to fix in a generic code. - volatile bool b = true; - if (b) throw x; -} +template <typename Exception> inline void do_throw(const Exception& x) { + // Silence unreachable code warnings in MSVC and NVCC because these + // are nearly impossible to fix in a generic code. + volatile bool b = true; + if (b) throw x; +} } // namespace detail -FMT_END_NAMESPACE +FMT_END_NAMESPACE # define FMT_THROW(x) detail::do_throw(x) -# else -# define FMT_THROW(x) throw x -# endif -# else -# define FMT_THROW(x) \ - do { \ - static_cast<void>(sizeof(x)); \ - FMT_ASSERT(false, ""); \ - } while (false) -# endif -#endif - -#if FMT_EXCEPTIONS -# define FMT_TRY try -# define FMT_CATCH(x) catch (x) -#else -# define FMT_TRY if (true) -# define FMT_CATCH(x) if (false) -#endif - -#ifndef FMT_USE_USER_DEFINED_LITERALS +# else +# define FMT_THROW(x) throw x +# endif +# else +# define FMT_THROW(x) \ + do { \ + static_cast<void>(sizeof(x)); \ + FMT_ASSERT(false, ""); \ + } while (false) +# endif +#endif + +#if FMT_EXCEPTIONS +# define FMT_TRY try +# define FMT_CATCH(x) catch (x) +#else +# define FMT_TRY if (true) +# define FMT_CATCH(x) if (false) +#endif + +#ifndef FMT_USE_USER_DEFINED_LITERALS // EDG based compilers (Intel, NVIDIA, Elbrus, etc), GCC and MSVC support UDLs. # if (FMT_HAS_FEATURE(cxx_user_literals) || FMT_GCC_VERSION >= 407 || \ FMT_MSC_VER >= 1900) && \ (!defined(__EDG_VERSION__) || __EDG_VERSION__ >= /* UDL feature */ 480) -# define FMT_USE_USER_DEFINED_LITERALS 1 -# else -# define FMT_USE_USER_DEFINED_LITERALS 0 -# endif -#endif - -#ifndef FMT_USE_UDL_TEMPLATE +# define FMT_USE_USER_DEFINED_LITERALS 1 +# else +# define FMT_USE_USER_DEFINED_LITERALS 0 +# endif +#endif + +#ifndef FMT_USE_UDL_TEMPLATE // EDG frontend based compilers (icc, nvcc, PGI, etc) and GCC < 6.4 do not // properly support UDL templates and GCC >= 9 warns about them. # if FMT_USE_USER_DEFINED_LITERALS && \ @@ -148,24 +148,24 @@ FMT_END_NAMESPACE ((FMT_GCC_VERSION >= 604 && __cplusplus >= 201402L) || \ FMT_CLANG_VERSION >= 304) && \ !defined(__PGI) && !defined(__NVCC__) -# define FMT_USE_UDL_TEMPLATE 1 -# else -# define FMT_USE_UDL_TEMPLATE 0 -# endif -#endif - -#ifndef FMT_USE_FLOAT -# define FMT_USE_FLOAT 1 -#endif - -#ifndef FMT_USE_DOUBLE -# define FMT_USE_DOUBLE 1 -#endif - -#ifndef FMT_USE_LONG_DOUBLE -# define FMT_USE_LONG_DOUBLE 1 -#endif - +# define FMT_USE_UDL_TEMPLATE 1 +# else +# define FMT_USE_UDL_TEMPLATE 0 +# endif +#endif + +#ifndef FMT_USE_FLOAT +# define FMT_USE_FLOAT 1 +#endif + +#ifndef FMT_USE_DOUBLE +# define FMT_USE_DOUBLE 1 +#endif + +#ifndef FMT_USE_LONG_DOUBLE +# define FMT_USE_LONG_DOUBLE 1 +#endif + // Defining FMT_REDUCE_INT_INSTANTIATIONS to 1, will reduce the number of // int_writer template instances to just one by only using the largest integer // type. This results in a reduction in binary size but will cause a decrease in @@ -174,77 +174,77 @@ FMT_END_NAMESPACE # define FMT_REDUCE_INT_INSTANTIATIONS 0 #endif -// __builtin_clz is broken in clang with Microsoft CodeGen: -// https://github.com/fmtlib/fmt/issues/519 -#if (FMT_GCC_VERSION || FMT_HAS_BUILTIN(__builtin_clz)) && !FMT_MSC_VER -# define FMT_BUILTIN_CLZ(n) __builtin_clz(n) -#endif -#if (FMT_GCC_VERSION || FMT_HAS_BUILTIN(__builtin_clzll)) && !FMT_MSC_VER -# define FMT_BUILTIN_CLZLL(n) __builtin_clzll(n) -#endif +// __builtin_clz is broken in clang with Microsoft CodeGen: +// https://github.com/fmtlib/fmt/issues/519 +#if (FMT_GCC_VERSION || FMT_HAS_BUILTIN(__builtin_clz)) && !FMT_MSC_VER +# define FMT_BUILTIN_CLZ(n) __builtin_clz(n) +#endif +#if (FMT_GCC_VERSION || FMT_HAS_BUILTIN(__builtin_clzll)) && !FMT_MSC_VER +# define FMT_BUILTIN_CLZLL(n) __builtin_clzll(n) +#endif #if (FMT_GCC_VERSION || FMT_HAS_BUILTIN(__builtin_ctz)) # define FMT_BUILTIN_CTZ(n) __builtin_ctz(n) #endif #if (FMT_GCC_VERSION || FMT_HAS_BUILTIN(__builtin_ctzll)) # define FMT_BUILTIN_CTZLL(n) __builtin_ctzll(n) #endif - + #if FMT_MSC_VER # include <intrin.h> // _BitScanReverse[64], _BitScanForward[64], _umul128 #endif -// Some compilers masquerade as both MSVC and GCC-likes or otherwise support -// __builtin_clz and __builtin_clzll, so only define FMT_BUILTIN_CLZ using the -// MSVC intrinsics if the clz and clzll builtins are not available. +// Some compilers masquerade as both MSVC and GCC-likes or otherwise support +// __builtin_clz and __builtin_clzll, so only define FMT_BUILTIN_CLZ using the +// MSVC intrinsics if the clz and clzll builtins are not available. #if FMT_MSC_VER && !defined(FMT_BUILTIN_CLZLL) && \ !defined(FMT_BUILTIN_CTZLL) && !defined(_MANAGED) -FMT_BEGIN_NAMESPACE +FMT_BEGIN_NAMESPACE namespace detail { -// Avoid Clang with Microsoft CodeGen's -Wunknown-pragmas warning. -# ifndef __clang__ +// Avoid Clang with Microsoft CodeGen's -Wunknown-pragmas warning. +# ifndef __clang__ # pragma intrinsic(_BitScanForward) -# pragma intrinsic(_BitScanReverse) -# endif +# pragma intrinsic(_BitScanReverse) +# endif # if defined(_WIN64) && !defined(__clang__) # pragma intrinsic(_BitScanForward64) # pragma intrinsic(_BitScanReverse64) # endif inline int clz(uint32_t x) { - unsigned long r = 0; - _BitScanReverse(&r, x); - FMT_ASSERT(x != 0, ""); - // Static analysis complains about using uninitialized data - // "r", but the only way that can happen is if "x" is 0, - // which the callers guarantee to not happen. + unsigned long r = 0; + _BitScanReverse(&r, x); + FMT_ASSERT(x != 0, ""); + // Static analysis complains about using uninitialized data + // "r", but the only way that can happen is if "x" is 0, + // which the callers guarantee to not happen. FMT_SUPPRESS_MSC_WARNING(6102) return 31 ^ static_cast<int>(r); -} +} # define FMT_BUILTIN_CLZ(n) detail::clz(n) - + inline int clzll(uint64_t x) { - unsigned long r = 0; -# ifdef _WIN64 - _BitScanReverse64(&r, x); -# else - // Scan the high 32 bits. + unsigned long r = 0; +# ifdef _WIN64 + _BitScanReverse64(&r, x); +# else + // Scan the high 32 bits. if (_BitScanReverse(&r, static_cast<uint32_t>(x >> 32))) return 63 ^ (r + 32); - // Scan the low 32 bits. - _BitScanReverse(&r, static_cast<uint32_t>(x)); -# endif + // Scan the low 32 bits. + _BitScanReverse(&r, static_cast<uint32_t>(x)); +# endif FMT_ASSERT(x != 0, ""); FMT_SUPPRESS_MSC_WARNING(6102) // Suppress a bogus static analysis warning. return 63 ^ static_cast<int>(r); } # define FMT_BUILTIN_CLZLL(n) detail::clzll(n) - + inline int ctz(uint32_t x) { unsigned long r = 0; _BitScanForward(&r, x); - FMT_ASSERT(x != 0, ""); + FMT_ASSERT(x != 0, ""); FMT_SUPPRESS_MSC_WARNING(6102) // Suppress a bogus static analysis warning. return static_cast<int>(r); -} +} # define FMT_BUILTIN_CTZ(n) detail::ctz(n) inline int ctzll(uint64_t x) { @@ -264,75 +264,75 @@ inline int ctzll(uint64_t x) { } # define FMT_BUILTIN_CTZLL(n) detail::ctzll(n) } // namespace detail -FMT_END_NAMESPACE -#endif - -// Enable the deprecated numeric alignment. +FMT_END_NAMESPACE +#endif + +// Enable the deprecated numeric alignment. #ifndef FMT_DEPRECATED_NUMERIC_ALIGN # define FMT_DEPRECATED_NUMERIC_ALIGN 0 -#endif - -FMT_BEGIN_NAMESPACE +#endif + +FMT_BEGIN_NAMESPACE namespace detail { - -// An equivalent of `*reinterpret_cast<Dest*>(&source)` that doesn't have -// undefined behavior (e.g. due to type aliasing). -// Example: uint64_t d = bit_cast<uint64_t>(2.718); -template <typename Dest, typename Source> -inline Dest bit_cast(const Source& source) { - static_assert(sizeof(Dest) == sizeof(Source), "size mismatch"); - Dest dest; - std::memcpy(&dest, &source, sizeof(dest)); - return dest; -} - -inline bool is_big_endian() { - const auto u = 1u; - struct bytes { - char data[sizeof(u)]; - }; - return bit_cast<bytes>(u).data[0] == 0; -} - -// A fallback implementation of uintptr_t for systems that lack it. -struct fallback_uintptr { - unsigned char value[sizeof(void*)]; - - fallback_uintptr() = default; - explicit fallback_uintptr(const void* p) { - *this = bit_cast<fallback_uintptr>(p); - if (is_big_endian()) { - for (size_t i = 0, j = sizeof(void*) - 1; i < j; ++i, --j) - std::swap(value[i], value[j]); - } - } -}; -#ifdef UINTPTR_MAX -using uintptr_t = ::uintptr_t; -inline uintptr_t to_uintptr(const void* p) { return bit_cast<uintptr_t>(p); } -#else -using uintptr_t = fallback_uintptr; -inline fallback_uintptr to_uintptr(const void* p) { - return fallback_uintptr(p); -} -#endif - -// Returns the largest possible value for type T. Same as -// std::numeric_limits<T>::max() but shorter and not affected by the max macro. -template <typename T> constexpr T max_value() { - return (std::numeric_limits<T>::max)(); -} -template <typename T> constexpr int num_bits() { - return std::numeric_limits<T>::digits; -} + +// An equivalent of `*reinterpret_cast<Dest*>(&source)` that doesn't have +// undefined behavior (e.g. due to type aliasing). +// Example: uint64_t d = bit_cast<uint64_t>(2.718); +template <typename Dest, typename Source> +inline Dest bit_cast(const Source& source) { + static_assert(sizeof(Dest) == sizeof(Source), "size mismatch"); + Dest dest; + std::memcpy(&dest, &source, sizeof(dest)); + return dest; +} + +inline bool is_big_endian() { + const auto u = 1u; + struct bytes { + char data[sizeof(u)]; + }; + return bit_cast<bytes>(u).data[0] == 0; +} + +// A fallback implementation of uintptr_t for systems that lack it. +struct fallback_uintptr { + unsigned char value[sizeof(void*)]; + + fallback_uintptr() = default; + explicit fallback_uintptr(const void* p) { + *this = bit_cast<fallback_uintptr>(p); + if (is_big_endian()) { + for (size_t i = 0, j = sizeof(void*) - 1; i < j; ++i, --j) + std::swap(value[i], value[j]); + } + } +}; +#ifdef UINTPTR_MAX +using uintptr_t = ::uintptr_t; +inline uintptr_t to_uintptr(const void* p) { return bit_cast<uintptr_t>(p); } +#else +using uintptr_t = fallback_uintptr; +inline fallback_uintptr to_uintptr(const void* p) { + return fallback_uintptr(p); +} +#endif + +// Returns the largest possible value for type T. Same as +// std::numeric_limits<T>::max() but shorter and not affected by the max macro. +template <typename T> constexpr T max_value() { + return (std::numeric_limits<T>::max)(); +} +template <typename T> constexpr int num_bits() { + return std::numeric_limits<T>::digits; +} // std::numeric_limits<T>::digits may return 0 for 128-bit ints. template <> constexpr int num_bits<int128_t>() { return 128; } template <> constexpr int num_bits<uint128_t>() { return 128; } -template <> constexpr int num_bits<fallback_uintptr>() { - return static_cast<int>(sizeof(void*) * - std::numeric_limits<unsigned char>::digits); -} - +template <> constexpr int num_bits<fallback_uintptr>() { + return static_cast<int>(sizeof(void*) * + std::numeric_limits<unsigned char>::digits); +} + FMT_INLINE void assume(bool condition) { (void)condition; #if FMT_HAS_BUILTIN(__builtin_assume) @@ -340,43 +340,43 @@ FMT_INLINE void assume(bool condition) { #endif } -// An approximation of iterator_t for pre-C++20 systems. -template <typename T> -using iterator_t = decltype(std::begin(std::declval<T&>())); +// An approximation of iterator_t for pre-C++20 systems. +template <typename T> +using iterator_t = decltype(std::begin(std::declval<T&>())); template <typename T> using sentinel_t = decltype(std::end(std::declval<T&>())); - -// A workaround for std::string not having mutable data() until C++17. -template <typename Char> inline Char* get_data(std::basic_string<Char>& s) { - return &s[0]; -} -template <typename Container> -inline typename Container::value_type* get_data(Container& c) { - return c.data(); -} - -#if defined(_SECURE_SCL) && _SECURE_SCL && !defined(_LIBCPP_VERSION) -// Make a checked iterator to avoid MSVC warnings. -template <typename T> using checked_ptr = stdext::checked_array_iterator<T*>; + +// A workaround for std::string not having mutable data() until C++17. +template <typename Char> inline Char* get_data(std::basic_string<Char>& s) { + return &s[0]; +} +template <typename Container> +inline typename Container::value_type* get_data(Container& c) { + return c.data(); +} + +#if defined(_SECURE_SCL) && _SECURE_SCL && !defined(_LIBCPP_VERSION) +// Make a checked iterator to avoid MSVC warnings. +template <typename T> using checked_ptr = stdext::checked_array_iterator<T*>; template <typename T> checked_ptr<T> make_checked(T* p, size_t size) { - return {p, size}; -} -#else -template <typename T> using checked_ptr = T*; + return {p, size}; +} +#else +template <typename T> using checked_ptr = T*; template <typename T> inline T* make_checked(T* p, size_t) { return p; } -#endif - -template <typename Container, FMT_ENABLE_IF(is_contiguous<Container>::value)> +#endif + +template <typename Container, FMT_ENABLE_IF(is_contiguous<Container>::value)> #if FMT_CLANG_VERSION __attribute__((no_sanitize("undefined"))) #endif inline checked_ptr<typename Container::value_type> reserve(std::back_insert_iterator<Container> it, size_t n) { - Container& c = get_container(it); + Container& c = get_container(it); size_t size = c.size(); - c.resize(size + n); - return make_checked(get_data(c) + size, n); -} - + c.resize(size + n); + return make_checked(get_data(c) + size, n); +} + template <typename T> inline buffer_appender<T> reserve(buffer_appender<T> it, size_t n) { buffer<T>& buf = get_container(it); @@ -407,187 +407,187 @@ inline std::back_insert_iterator<Container> base_iterator( return it; } -template <typename Iterator> +template <typename Iterator> inline Iterator base_iterator(Iterator, Iterator it) { - return it; -} - -// An output iterator that counts the number of objects written to it and -// discards them. -class counting_iterator { - private: + return it; +} + +// An output iterator that counts the number of objects written to it and +// discards them. +class counting_iterator { + private: size_t count_; - - public: - using iterator_category = std::output_iterator_tag; - using difference_type = std::ptrdiff_t; - using pointer = void; - using reference = void; - using _Unchecked_type = counting_iterator; // Mark iterator as checked. - - struct value_type { - template <typename T> void operator=(const T&) {} - }; - - counting_iterator() : count_(0) {} - + + public: + using iterator_category = std::output_iterator_tag; + using difference_type = std::ptrdiff_t; + using pointer = void; + using reference = void; + using _Unchecked_type = counting_iterator; // Mark iterator as checked. + + struct value_type { + template <typename T> void operator=(const T&) {} + }; + + counting_iterator() : count_(0) {} + size_t count() const { return count_; } - - counting_iterator& operator++() { - ++count_; - return *this; - } - counting_iterator operator++(int) { - auto it = *this; - ++*this; - return it; - } - + + counting_iterator& operator++() { + ++count_; + return *this; + } + counting_iterator operator++(int) { + auto it = *this; + ++*this; + return it; + } + friend counting_iterator operator+(counting_iterator it, difference_type n) { it.count_ += static_cast<size_t>(n); return it; } - value_type operator*() const { return {}; } -}; - -template <typename OutputIt> class truncating_iterator_base { - protected: - OutputIt out_; + value_type operator*() const { return {}; } +}; + +template <typename OutputIt> class truncating_iterator_base { + protected: + OutputIt out_; size_t limit_; size_t count_; - + truncating_iterator_base(OutputIt out, size_t limit) - : out_(out), limit_(limit), count_(0) {} - - public: - using iterator_category = std::output_iterator_tag; - using value_type = typename std::iterator_traits<OutputIt>::value_type; - using difference_type = void; - using pointer = void; - using reference = void; - using _Unchecked_type = - truncating_iterator_base; // Mark iterator as checked. - - OutputIt base() const { return out_; } + : out_(out), limit_(limit), count_(0) {} + + public: + using iterator_category = std::output_iterator_tag; + using value_type = typename std::iterator_traits<OutputIt>::value_type; + using difference_type = void; + using pointer = void; + using reference = void; + using _Unchecked_type = + truncating_iterator_base; // Mark iterator as checked. + + OutputIt base() const { return out_; } size_t count() const { return count_; } -}; - -// An output iterator that truncates the output and counts the number of objects -// written to it. -template <typename OutputIt, - typename Enable = typename std::is_void< - typename std::iterator_traits<OutputIt>::value_type>::type> -class truncating_iterator; - -template <typename OutputIt> -class truncating_iterator<OutputIt, std::false_type> - : public truncating_iterator_base<OutputIt> { - mutable typename truncating_iterator_base<OutputIt>::value_type blackhole_; - - public: - using value_type = typename truncating_iterator_base<OutputIt>::value_type; - +}; + +// An output iterator that truncates the output and counts the number of objects +// written to it. +template <typename OutputIt, + typename Enable = typename std::is_void< + typename std::iterator_traits<OutputIt>::value_type>::type> +class truncating_iterator; + +template <typename OutputIt> +class truncating_iterator<OutputIt, std::false_type> + : public truncating_iterator_base<OutputIt> { + mutable typename truncating_iterator_base<OutputIt>::value_type blackhole_; + + public: + using value_type = typename truncating_iterator_base<OutputIt>::value_type; + truncating_iterator(OutputIt out, size_t limit) - : truncating_iterator_base<OutputIt>(out, limit) {} - - truncating_iterator& operator++() { - if (this->count_++ < this->limit_) ++this->out_; - return *this; - } - - truncating_iterator operator++(int) { - auto it = *this; - ++*this; - return it; - } - - value_type& operator*() const { - return this->count_ < this->limit_ ? *this->out_ : blackhole_; - } -}; - -template <typename OutputIt> -class truncating_iterator<OutputIt, std::true_type> - : public truncating_iterator_base<OutputIt> { - public: + : truncating_iterator_base<OutputIt>(out, limit) {} + + truncating_iterator& operator++() { + if (this->count_++ < this->limit_) ++this->out_; + return *this; + } + + truncating_iterator operator++(int) { + auto it = *this; + ++*this; + return it; + } + + value_type& operator*() const { + return this->count_ < this->limit_ ? *this->out_ : blackhole_; + } +}; + +template <typename OutputIt> +class truncating_iterator<OutputIt, std::true_type> + : public truncating_iterator_base<OutputIt> { + public: truncating_iterator(OutputIt out, size_t limit) - : truncating_iterator_base<OutputIt>(out, limit) {} - - template <typename T> truncating_iterator& operator=(T val) { - if (this->count_++ < this->limit_) *this->out_++ = val; - return *this; - } - - truncating_iterator& operator++() { return *this; } - truncating_iterator& operator++(int) { return *this; } - truncating_iterator& operator*() { return *this; } -}; - -template <typename Char> -inline size_t count_code_points(basic_string_view<Char> s) { - return s.size(); -} - -// Counts the number of code points in a UTF-8 string. -inline size_t count_code_points(basic_string_view<char> s) { - const char* data = s.data(); - size_t num_code_points = 0; - for (size_t i = 0, size = s.size(); i != size; ++i) { - if ((data[i] & 0xc0) != 0x80) ++num_code_points; - } - return num_code_points; -} - -inline size_t count_code_points(basic_string_view<char8_type> s) { - return count_code_points(basic_string_view<char>( - reinterpret_cast<const char*>(s.data()), s.size())); -} - -template <typename Char> -inline size_t code_point_index(basic_string_view<Char> s, size_t n) { - size_t size = s.size(); - return n < size ? n : size; -} - -// Calculates the index of the nth code point in a UTF-8 string. -inline size_t code_point_index(basic_string_view<char8_type> s, size_t n) { - const char8_type* data = s.data(); - size_t num_code_points = 0; - for (size_t i = 0, size = s.size(); i != size; ++i) { - if ((data[i] & 0xc0) != 0x80 && ++num_code_points > n) { - return i; - } - } - return s.size(); -} - -template <typename InputIt, typename OutChar> -using needs_conversion = bool_constant< - std::is_same<typename std::iterator_traits<InputIt>::value_type, - char>::value && - std::is_same<OutChar, char8_type>::value>; - -template <typename OutChar, typename InputIt, typename OutputIt, - FMT_ENABLE_IF(!needs_conversion<InputIt, OutChar>::value)> -OutputIt copy_str(InputIt begin, InputIt end, OutputIt it) { - return std::copy(begin, end, it); -} - -template <typename OutChar, typename InputIt, typename OutputIt, - FMT_ENABLE_IF(needs_conversion<InputIt, OutChar>::value)> -OutputIt copy_str(InputIt begin, InputIt end, OutputIt it) { + : truncating_iterator_base<OutputIt>(out, limit) {} + + template <typename T> truncating_iterator& operator=(T val) { + if (this->count_++ < this->limit_) *this->out_++ = val; + return *this; + } + + truncating_iterator& operator++() { return *this; } + truncating_iterator& operator++(int) { return *this; } + truncating_iterator& operator*() { return *this; } +}; + +template <typename Char> +inline size_t count_code_points(basic_string_view<Char> s) { + return s.size(); +} + +// Counts the number of code points in a UTF-8 string. +inline size_t count_code_points(basic_string_view<char> s) { + const char* data = s.data(); + size_t num_code_points = 0; + for (size_t i = 0, size = s.size(); i != size; ++i) { + if ((data[i] & 0xc0) != 0x80) ++num_code_points; + } + return num_code_points; +} + +inline size_t count_code_points(basic_string_view<char8_type> s) { + return count_code_points(basic_string_view<char>( + reinterpret_cast<const char*>(s.data()), s.size())); +} + +template <typename Char> +inline size_t code_point_index(basic_string_view<Char> s, size_t n) { + size_t size = s.size(); + return n < size ? n : size; +} + +// Calculates the index of the nth code point in a UTF-8 string. +inline size_t code_point_index(basic_string_view<char8_type> s, size_t n) { + const char8_type* data = s.data(); + size_t num_code_points = 0; + for (size_t i = 0, size = s.size(); i != size; ++i) { + if ((data[i] & 0xc0) != 0x80 && ++num_code_points > n) { + return i; + } + } + return s.size(); +} + +template <typename InputIt, typename OutChar> +using needs_conversion = bool_constant< + std::is_same<typename std::iterator_traits<InputIt>::value_type, + char>::value && + std::is_same<OutChar, char8_type>::value>; + +template <typename OutChar, typename InputIt, typename OutputIt, + FMT_ENABLE_IF(!needs_conversion<InputIt, OutChar>::value)> +OutputIt copy_str(InputIt begin, InputIt end, OutputIt it) { + return std::copy(begin, end, it); +} + +template <typename OutChar, typename InputIt, typename OutputIt, + FMT_ENABLE_IF(needs_conversion<InputIt, OutChar>::value)> +OutputIt copy_str(InputIt begin, InputIt end, OutputIt it) { return std::transform(begin, end, it, [](char c) { return static_cast<char8_type>(c); }); -} - +} + template <typename Char, typename InputIt> inline counting_iterator copy_str(InputIt begin, InputIt end, counting_iterator it) { return it + (end - begin); -} - -template <typename T> +} + +template <typename T> using is_fast_float = bool_constant<std::numeric_limits<T>::is_iec559 && sizeof(T) <= sizeof(double)>; @@ -596,8 +596,8 @@ using is_fast_float = bool_constant<std::numeric_limits<T>::is_iec559 && #endif template <typename T> -template <typename U> -void buffer<T>::append(const U* begin, const U* end) { +template <typename U> +void buffer<T>::append(const U* begin, const U* end) { do { auto count = to_unsigned(end - begin); try_reserve(size_ + count); @@ -607,117 +607,117 @@ void buffer<T>::append(const U* begin, const U* end) { size_ += count; begin += count; } while (begin != end); -} - +} + template <typename OutputIt, typename T, typename Traits> void iterator_buffer<OutputIt, T, Traits>::flush() { out_ = std::copy_n(data_, this->limit(this->size()), out_); this->clear(); -} +} } // namespace detail - -// The number of characters to store in the basic_memory_buffer object itself -// to avoid dynamic memory allocation. -enum { inline_buffer_size = 500 }; - -/** - \rst - A dynamically growing memory buffer for trivially copyable/constructible types - with the first ``SIZE`` elements stored in the object itself. - - You can use one of the following type aliases for common character types: - - +----------------+------------------------------+ - | Type | Definition | - +================+==============================+ - | memory_buffer | basic_memory_buffer<char> | - +----------------+------------------------------+ - | wmemory_buffer | basic_memory_buffer<wchar_t> | - +----------------+------------------------------+ - - **Example**:: - - fmt::memory_buffer out; - format_to(out, "The answer is {}.", 42); - - This will append the following output to the ``out`` object: - - .. code-block:: none - - The answer is 42. - - The output can be converted to an ``std::string`` with ``to_string(out)``. - \endrst - */ + +// The number of characters to store in the basic_memory_buffer object itself +// to avoid dynamic memory allocation. +enum { inline_buffer_size = 500 }; + +/** + \rst + A dynamically growing memory buffer for trivially copyable/constructible types + with the first ``SIZE`` elements stored in the object itself. + + You can use one of the following type aliases for common character types: + + +----------------+------------------------------+ + | Type | Definition | + +================+==============================+ + | memory_buffer | basic_memory_buffer<char> | + +----------------+------------------------------+ + | wmemory_buffer | basic_memory_buffer<wchar_t> | + +----------------+------------------------------+ + + **Example**:: + + fmt::memory_buffer out; + format_to(out, "The answer is {}.", 42); + + This will append the following output to the ``out`` object: + + .. code-block:: none + + The answer is 42. + + The output can be converted to an ``std::string`` with ``to_string(out)``. + \endrst + */ template <typename T, size_t SIZE = inline_buffer_size, - typename Allocator = std::allocator<T>> + typename Allocator = std::allocator<T>> class basic_memory_buffer final : public detail::buffer<T> { - private: - T store_[SIZE]; - + private: + T store_[SIZE]; + // Don't inherit from Allocator avoid generating type_info for it. Allocator alloc_; - // Deallocate memory allocated by the buffer. - void deallocate() { - T* data = this->data(); + // Deallocate memory allocated by the buffer. + void deallocate() { + T* data = this->data(); if (data != store_) alloc_.deallocate(data, this->capacity()); - } - - protected: + } + + protected: void grow(size_t size) final FMT_OVERRIDE; - - public: - using value_type = T; - using const_reference = const T&; - - explicit basic_memory_buffer(const Allocator& alloc = Allocator()) + + public: + using value_type = T; + using const_reference = const T&; + + explicit basic_memory_buffer(const Allocator& alloc = Allocator()) : alloc_(alloc) { - this->set(store_, SIZE); - } + this->set(store_, SIZE); + } ~basic_memory_buffer() { deallocate(); } - - private: - // Move data from other to this buffer. - void move(basic_memory_buffer& other) { + + private: + // Move data from other to this buffer. + void move(basic_memory_buffer& other) { alloc_ = std::move(other.alloc_); - T* data = other.data(); + T* data = other.data(); size_t size = other.size(), capacity = other.capacity(); - if (data == other.store_) { - this->set(store_, capacity); - std::uninitialized_copy(other.store_, other.store_ + size, + if (data == other.store_) { + this->set(store_, capacity); + std::uninitialized_copy(other.store_, other.store_ + size, detail::make_checked(store_, capacity)); - } else { - this->set(data, capacity); - // Set pointer to the inline array so that delete is not called - // when deallocating. - other.set(other.store_, 0); - } - this->resize(size); - } - - public: - /** - \rst - Constructs a :class:`fmt::basic_memory_buffer` object moving the content - of the other object to it. - \endrst - */ - basic_memory_buffer(basic_memory_buffer&& other) FMT_NOEXCEPT { move(other); } - - /** - \rst - Moves the content of the other ``basic_memory_buffer`` object to this one. - \endrst - */ - basic_memory_buffer& operator=(basic_memory_buffer&& other) FMT_NOEXCEPT { - FMT_ASSERT(this != &other, ""); - deallocate(); - move(other); - return *this; - } - - // Returns a copy of the allocator associated with this buffer. + } else { + this->set(data, capacity); + // Set pointer to the inline array so that delete is not called + // when deallocating. + other.set(other.store_, 0); + } + this->resize(size); + } + + public: + /** + \rst + Constructs a :class:`fmt::basic_memory_buffer` object moving the content + of the other object to it. + \endrst + */ + basic_memory_buffer(basic_memory_buffer&& other) FMT_NOEXCEPT { move(other); } + + /** + \rst + Moves the content of the other ``basic_memory_buffer`` object to this one. + \endrst + */ + basic_memory_buffer& operator=(basic_memory_buffer&& other) FMT_NOEXCEPT { + FMT_ASSERT(this != &other, ""); + deallocate(); + move(other); + return *this; + } + + // Returns a copy of the allocator associated with this buffer. Allocator get_allocator() const { return alloc_; } /** @@ -735,83 +735,83 @@ class basic_memory_buffer final : public detail::buffer<T> { void append(const ContiguousRange& range) { append(range.data(), range.data() + range.size()); } -}; - +}; + template <typename T, size_t SIZE, typename Allocator> void basic_memory_buffer<T, SIZE, Allocator>::grow(size_t size) { #ifdef FMT_FUZZ if (size > 5000) throw std::runtime_error("fuzz mode - won't grow that much"); -#endif +#endif size_t old_capacity = this->capacity(); size_t new_capacity = old_capacity + old_capacity / 2; - if (size > new_capacity) new_capacity = size; - T* old_data = this->data(); + if (size > new_capacity) new_capacity = size; + T* old_data = this->data(); T* new_data = std::allocator_traits<Allocator>::allocate(alloc_, new_capacity); - // The following code doesn't throw, so the raw pointer above doesn't leak. - std::uninitialized_copy(old_data, old_data + this->size(), + // The following code doesn't throw, so the raw pointer above doesn't leak. + std::uninitialized_copy(old_data, old_data + this->size(), detail::make_checked(new_data, new_capacity)); - this->set(new_data, new_capacity); - // deallocate must not throw according to the standard, but even if it does, - // the buffer already uses the new storage and will deallocate it in - // destructor. + this->set(new_data, new_capacity); + // deallocate must not throw according to the standard, but even if it does, + // the buffer already uses the new storage and will deallocate it in + // destructor. if (old_data != store_) alloc_.deallocate(old_data, old_capacity); -} - -using memory_buffer = basic_memory_buffer<char>; -using wmemory_buffer = basic_memory_buffer<wchar_t>; - +} + +using memory_buffer = basic_memory_buffer<char>; +using wmemory_buffer = basic_memory_buffer<wchar_t>; + template <typename T, size_t SIZE, typename Allocator> struct is_contiguous<basic_memory_buffer<T, SIZE, Allocator>> : std::true_type { }; -/** A formatting error such as invalid format string. */ -FMT_CLASS_API -class FMT_API format_error : public std::runtime_error { - public: - explicit format_error(const char* message) : std::runtime_error(message) {} - explicit format_error(const std::string& message) - : std::runtime_error(message) {} - format_error(const format_error&) = default; - format_error& operator=(const format_error&) = default; - format_error(format_error&&) = default; - format_error& operator=(format_error&&) = default; - ~format_error() FMT_NOEXCEPT FMT_OVERRIDE; -}; - +/** A formatting error such as invalid format string. */ +FMT_CLASS_API +class FMT_API format_error : public std::runtime_error { + public: + explicit format_error(const char* message) : std::runtime_error(message) {} + explicit format_error(const std::string& message) + : std::runtime_error(message) {} + format_error(const format_error&) = default; + format_error& operator=(const format_error&) = default; + format_error(format_error&&) = default; + format_error& operator=(format_error&&) = default; + ~format_error() FMT_NOEXCEPT FMT_OVERRIDE; +}; + namespace detail { - + template <typename T> using is_signed = std::integral_constant<bool, std::numeric_limits<T>::is_signed || std::is_same<T, int128_t>::value>; -// Returns true if value is negative, false otherwise. -// Same as `value < 0` but doesn't produce warnings if T is an unsigned type. +// Returns true if value is negative, false otherwise. +// Same as `value < 0` but doesn't produce warnings if T is an unsigned type. template <typename T, FMT_ENABLE_IF(is_signed<T>::value)> -FMT_CONSTEXPR bool is_negative(T value) { - return value < 0; -} +FMT_CONSTEXPR bool is_negative(T value) { + return value < 0; +} template <typename T, FMT_ENABLE_IF(!is_signed<T>::value)> -FMT_CONSTEXPR bool is_negative(T) { - return false; -} - -template <typename T, FMT_ENABLE_IF(std::is_floating_point<T>::value)> -FMT_CONSTEXPR bool is_supported_floating_point(T) { - return (std::is_same<T, float>::value && FMT_USE_FLOAT) || - (std::is_same<T, double>::value && FMT_USE_DOUBLE) || - (std::is_same<T, long double>::value && FMT_USE_LONG_DOUBLE); -} - -// Smallest of uint32_t, uint64_t, uint128_t that is large enough to +FMT_CONSTEXPR bool is_negative(T) { + return false; +} + +template <typename T, FMT_ENABLE_IF(std::is_floating_point<T>::value)> +FMT_CONSTEXPR bool is_supported_floating_point(T) { + return (std::is_same<T, float>::value && FMT_USE_FLOAT) || + (std::is_same<T, double>::value && FMT_USE_DOUBLE) || + (std::is_same<T, long double>::value && FMT_USE_LONG_DOUBLE); +} + +// Smallest of uint32_t, uint64_t, uint128_t that is large enough to // represent all values of an integral type T. -template <typename T> +template <typename T> using uint32_or_64_or_128_t = conditional_t<num_bits<T>() <= 32 && !FMT_REDUCE_INT_INSTANTIATIONS, uint32_t, conditional_t<num_bits<T>() <= 64, uint64_t, uint128_t>>; - + // 128-bit integer type used internally struct FMT_EXTERN_TEMPLATE_API uint128_wrapper { uint128_wrapper() = default; @@ -863,9 +863,9 @@ template <typename T> struct FMT_EXTERN_TEMPLATE_API divtest_table_entry { T max_quotient; }; -// Static data is placed in this class template for the header-only config. -template <typename T = void> struct FMT_EXTERN_TEMPLATE_API basic_data { - static const uint64_t powers_of_10_64[]; +// Static data is placed in this class template for the header-only config. +template <typename T = void> struct FMT_EXTERN_TEMPLATE_API basic_data { + static const uint64_t powers_of_10_64[]; static const uint32_t zero_or_powers_of_10_32_new[]; static const uint64_t zero_or_powers_of_10_64_new[]; static const uint64_t grisu_pow10_significands[]; @@ -883,20 +883,20 @@ template <typename T = void> struct FMT_EXTERN_TEMPLATE_API basic_data { // GCC generates slightly better code for pairs than chars. using digit_pair = char[2]; static const digit_pair digits[]; - static const char hex_digits[]; - static const char foreground_color[]; - static const char background_color[]; - static const char reset_color[5]; - static const wchar_t wreset_color[5]; - static const char signs[]; + static const char hex_digits[]; + static const char foreground_color[]; + static const char background_color[]; + static const char reset_color[5]; + static const wchar_t wreset_color[5]; + static const char signs[]; static const char left_padding_shifts[5]; static const char right_padding_shifts[5]; // DEPRECATED! These are for ABI compatibility. static const uint32_t zero_or_powers_of_10_32[]; static const uint64_t zero_or_powers_of_10_64[]; -}; - +}; + // Maps bsr(n) to ceil(log10(pow(2, bsr(n) + 1) - 1)). // This is a function instead of an array to workaround a bug in GCC10 (#1810). FMT_INLINE uint16_t bsr2log10(int bsr) { @@ -909,74 +909,74 @@ FMT_INLINE uint16_t bsr2log10(int bsr) { } #ifndef FMT_EXPORTED -FMT_EXTERN template struct basic_data<void>; +FMT_EXTERN template struct basic_data<void>; #endif - -// This is a struct rather than an alias to avoid shadowing warnings in gcc. -struct data : basic_data<> {}; - -#ifdef FMT_BUILTIN_CLZLL -// Returns the number of decimal digits in n. Leading zeros are not counted -// except for n == 0 in which case count_digits returns 1. -inline int count_digits(uint64_t n) { + +// This is a struct rather than an alias to avoid shadowing warnings in gcc. +struct data : basic_data<> {}; + +#ifdef FMT_BUILTIN_CLZLL +// Returns the number of decimal digits in n. Leading zeros are not counted +// except for n == 0 in which case count_digits returns 1. +inline int count_digits(uint64_t n) { // https://github.com/fmtlib/format-benchmark/blob/master/digits10 auto t = bsr2log10(FMT_BUILTIN_CLZLL(n | 1) ^ 63); return t - (n < data::zero_or_powers_of_10_64_new[t]); -} -#else -// Fallback version of count_digits used when __builtin_clz is not available. -inline int count_digits(uint64_t n) { - int count = 1; - for (;;) { - // Integer division is slow so do it for a group of four digits instead - // of for every digit. The idea comes from the talk by Alexandrescu - // "Three Optimization Tips for C++". See speed-test for a comparison. - if (n < 10) return count; - if (n < 100) return count + 1; - if (n < 1000) return count + 2; - if (n < 10000) return count + 3; - n /= 10000u; - count += 4; - } -} -#endif - -#if FMT_USE_INT128 -inline int count_digits(uint128_t n) { - int count = 1; - for (;;) { - // Integer division is slow so do it for a group of four digits instead - // of for every digit. The idea comes from the talk by Alexandrescu - // "Three Optimization Tips for C++". See speed-test for a comparison. - if (n < 10) return count; - if (n < 100) return count + 1; - if (n < 1000) return count + 2; - if (n < 10000) return count + 3; - n /= 10000U; - count += 4; - } -} -#endif - -// Counts the number of digits in n. BITS = log2(radix). -template <unsigned BITS, typename UInt> inline int count_digits(UInt n) { - int num_digits = 0; - do { - ++num_digits; - } while ((n >>= BITS) != 0); - return num_digits; -} - +} +#else +// Fallback version of count_digits used when __builtin_clz is not available. +inline int count_digits(uint64_t n) { + int count = 1; + for (;;) { + // Integer division is slow so do it for a group of four digits instead + // of for every digit. The idea comes from the talk by Alexandrescu + // "Three Optimization Tips for C++". See speed-test for a comparison. + if (n < 10) return count; + if (n < 100) return count + 1; + if (n < 1000) return count + 2; + if (n < 10000) return count + 3; + n /= 10000u; + count += 4; + } +} +#endif + +#if FMT_USE_INT128 +inline int count_digits(uint128_t n) { + int count = 1; + for (;;) { + // Integer division is slow so do it for a group of four digits instead + // of for every digit. The idea comes from the talk by Alexandrescu + // "Three Optimization Tips for C++". See speed-test for a comparison. + if (n < 10) return count; + if (n < 100) return count + 1; + if (n < 1000) return count + 2; + if (n < 10000) return count + 3; + n /= 10000U; + count += 4; + } +} +#endif + +// Counts the number of digits in n. BITS = log2(radix). +template <unsigned BITS, typename UInt> inline int count_digits(UInt n) { + int num_digits = 0; + do { + ++num_digits; + } while ((n >>= BITS) != 0); + return num_digits; +} + template <> int count_digits<4>(detail::fallback_uintptr n); - -#if FMT_GCC_VERSION || FMT_CLANG_VERSION -# define FMT_ALWAYS_INLINE inline __attribute__((always_inline)) + +#if FMT_GCC_VERSION || FMT_CLANG_VERSION +# define FMT_ALWAYS_INLINE inline __attribute__((always_inline)) #elif FMT_MSC_VER # define FMT_ALWAYS_INLINE __forceinline -#else +#else # define FMT_ALWAYS_INLINE inline -#endif - +#endif + // To suppress unnecessary security cookie checks #if FMT_MSC_VER && !FMT_CLANG_VERSION # define FMT_SAFEBUFFERS __declspec(safebuffers) @@ -984,44 +984,44 @@ template <> int count_digits<4>(detail::fallback_uintptr n); # define FMT_SAFEBUFFERS #endif -#ifdef FMT_BUILTIN_CLZ -// Optional version of count_digits for better performance on 32-bit platforms. -inline int count_digits(uint32_t n) { +#ifdef FMT_BUILTIN_CLZ +// Optional version of count_digits for better performance on 32-bit platforms. +inline int count_digits(uint32_t n) { auto t = bsr2log10(FMT_BUILTIN_CLZ(n | 1) ^ 31); return t - (n < data::zero_or_powers_of_10_32_new[t]); -} -#endif - +} +#endif + template <typename Int> constexpr int digits10() FMT_NOEXCEPT { return std::numeric_limits<Int>::digits10; } template <> constexpr int digits10<int128_t>() FMT_NOEXCEPT { return 38; } template <> constexpr int digits10<uint128_t>() FMT_NOEXCEPT { return 38; } -template <typename Char> FMT_API std::string grouping_impl(locale_ref loc); -template <typename Char> inline std::string grouping(locale_ref loc) { - return grouping_impl<char>(loc); -} -template <> inline std::string grouping<wchar_t>(locale_ref loc) { - return grouping_impl<wchar_t>(loc); -} - -template <typename Char> FMT_API Char thousands_sep_impl(locale_ref loc); -template <typename Char> inline Char thousands_sep(locale_ref loc) { - return Char(thousands_sep_impl<char>(loc)); -} -template <> inline wchar_t thousands_sep(locale_ref loc) { - return thousands_sep_impl<wchar_t>(loc); -} - -template <typename Char> FMT_API Char decimal_point_impl(locale_ref loc); -template <typename Char> inline Char decimal_point(locale_ref loc) { - return Char(decimal_point_impl<char>(loc)); -} -template <> inline wchar_t decimal_point(locale_ref loc) { - return decimal_point_impl<wchar_t>(loc); -} - +template <typename Char> FMT_API std::string grouping_impl(locale_ref loc); +template <typename Char> inline std::string grouping(locale_ref loc) { + return grouping_impl<char>(loc); +} +template <> inline std::string grouping<wchar_t>(locale_ref loc) { + return grouping_impl<wchar_t>(loc); +} + +template <typename Char> FMT_API Char thousands_sep_impl(locale_ref loc); +template <typename Char> inline Char thousands_sep(locale_ref loc) { + return Char(thousands_sep_impl<char>(loc)); +} +template <> inline wchar_t thousands_sep(locale_ref loc) { + return thousands_sep_impl<wchar_t>(loc); +} + +template <typename Char> FMT_API Char decimal_point_impl(locale_ref loc); +template <typename Char> inline Char decimal_point(locale_ref loc) { + return Char(decimal_point_impl<char>(loc)); +} +template <> inline wchar_t decimal_point(locale_ref loc) { + return decimal_point_impl<wchar_t>(loc); +} + // Compares two characters for equality. template <typename Char> bool equal2(const Char* lhs, const char* rhs) { return lhs[0] == rhs[0] && lhs[1] == rhs[1]; @@ -1051,23 +1051,23 @@ inline format_decimal_result<Char*> format_decimal(Char* out, UInt value, FMT_ASSERT(size >= count_digits(value), "invalid digit count"); out += size; Char* end = out; - while (value >= 100) { - // Integer division is slow so do it for a group of two digits instead - // of for every digit. The idea comes from the talk by Alexandrescu - // "Three Optimization Tips for C++". See speed-test for a comparison. + while (value >= 100) { + // Integer division is slow so do it for a group of two digits instead + // of for every digit. The idea comes from the talk by Alexandrescu + // "Three Optimization Tips for C++". See speed-test for a comparison. out -= 2; copy2(out, data::digits[value % 100]); - value /= 100; - } - if (value < 10) { + value /= 100; + } + if (value < 10) { *--out = static_cast<Char>('0' + value); return {out, end}; - } + } out -= 2; copy2(out, data::digits[value]); return {out, end}; -} - +} + template <typename Char, typename UInt, typename Iterator, FMT_ENABLE_IF(!std::is_pointer<remove_cvref_t<Iterator>>::value)> inline format_decimal_result<Iterator> format_decimal(Iterator out, UInt value, @@ -1076,135 +1076,135 @@ inline format_decimal_result<Iterator> format_decimal(Iterator out, UInt value, Char buffer[digits10<UInt>() + 1]; auto end = format_decimal(buffer, value, size).end; return {out, detail::copy_str<Char>(buffer, end, out)}; -} - -template <unsigned BASE_BITS, typename Char, typename UInt> -inline Char* format_uint(Char* buffer, UInt value, int num_digits, - bool upper = false) { - buffer += num_digits; - Char* end = buffer; - do { - const char* digits = upper ? "0123456789ABCDEF" : data::hex_digits; - unsigned digit = (value & ((1 << BASE_BITS) - 1)); - *--buffer = static_cast<Char>(BASE_BITS < 4 ? static_cast<char>('0' + digit) - : digits[digit]); - } while ((value >>= BASE_BITS) != 0); - return end; -} - -template <unsigned BASE_BITS, typename Char> +} + +template <unsigned BASE_BITS, typename Char, typename UInt> +inline Char* format_uint(Char* buffer, UInt value, int num_digits, + bool upper = false) { + buffer += num_digits; + Char* end = buffer; + do { + const char* digits = upper ? "0123456789ABCDEF" : data::hex_digits; + unsigned digit = (value & ((1 << BASE_BITS) - 1)); + *--buffer = static_cast<Char>(BASE_BITS < 4 ? static_cast<char>('0' + digit) + : digits[digit]); + } while ((value >>= BASE_BITS) != 0); + return end; +} + +template <unsigned BASE_BITS, typename Char> Char* format_uint(Char* buffer, detail::fallback_uintptr n, int num_digits, - bool = false) { - auto char_digits = std::numeric_limits<unsigned char>::digits / 4; - int start = (num_digits + char_digits - 1) / char_digits - 1; - if (int start_digits = num_digits % char_digits) { - unsigned value = n.value[start--]; - buffer = format_uint<BASE_BITS>(buffer, value, start_digits); - } - for (; start >= 0; --start) { - unsigned value = n.value[start]; - buffer += char_digits; - auto p = buffer; - for (int i = 0; i < char_digits; ++i) { - unsigned digit = (value & ((1 << BASE_BITS) - 1)); - *--p = static_cast<Char>(data::hex_digits[digit]); - value >>= BASE_BITS; - } - } - return buffer; -} - -template <unsigned BASE_BITS, typename Char, typename It, typename UInt> -inline It format_uint(It out, UInt value, int num_digits, bool upper = false) { + bool = false) { + auto char_digits = std::numeric_limits<unsigned char>::digits / 4; + int start = (num_digits + char_digits - 1) / char_digits - 1; + if (int start_digits = num_digits % char_digits) { + unsigned value = n.value[start--]; + buffer = format_uint<BASE_BITS>(buffer, value, start_digits); + } + for (; start >= 0; --start) { + unsigned value = n.value[start]; + buffer += char_digits; + auto p = buffer; + for (int i = 0; i < char_digits; ++i) { + unsigned digit = (value & ((1 << BASE_BITS) - 1)); + *--p = static_cast<Char>(data::hex_digits[digit]); + value >>= BASE_BITS; + } + } + return buffer; +} + +template <unsigned BASE_BITS, typename Char, typename It, typename UInt> +inline It format_uint(It out, UInt value, int num_digits, bool upper = false) { if (auto ptr = to_pointer<Char>(out, to_unsigned(num_digits))) { format_uint<BASE_BITS>(ptr, value, num_digits, upper); return out; } - // Buffer should be large enough to hold all digits (digits / BASE_BITS + 1). - char buffer[num_bits<UInt>() / BASE_BITS + 1]; - format_uint<BASE_BITS>(buffer, value, num_digits, upper); + // Buffer should be large enough to hold all digits (digits / BASE_BITS + 1). + char buffer[num_bits<UInt>() / BASE_BITS + 1]; + format_uint<BASE_BITS>(buffer, value, num_digits, upper); return detail::copy_str<Char>(buffer, buffer + num_digits, out); -} - -// A converter from UTF-8 to UTF-16. -class utf8_to_utf16 { - private: - wmemory_buffer buffer_; - - public: - FMT_API explicit utf8_to_utf16(string_view s); - operator wstring_view() const { return {&buffer_[0], size()}; } - size_t size() const { return buffer_.size() - 1; } - const wchar_t* c_str() const { return &buffer_[0]; } - std::wstring str() const { return {&buffer_[0], size()}; } -}; - -template <typename T = void> struct null {}; - -// Workaround an array initialization issue in gcc 4.8. -template <typename Char> struct fill_t { - private: - enum { max_size = 4 }; +} + +// A converter from UTF-8 to UTF-16. +class utf8_to_utf16 { + private: + wmemory_buffer buffer_; + + public: + FMT_API explicit utf8_to_utf16(string_view s); + operator wstring_view() const { return {&buffer_[0], size()}; } + size_t size() const { return buffer_.size() - 1; } + const wchar_t* c_str() const { return &buffer_[0]; } + std::wstring str() const { return {&buffer_[0], size()}; } +}; + +template <typename T = void> struct null {}; + +// Workaround an array initialization issue in gcc 4.8. +template <typename Char> struct fill_t { + private: + enum { max_size = 4 }; Char data_[max_size] = {Char(' '), Char(0), Char(0), Char(0)}; unsigned char size_ = 1; - - public: - FMT_CONSTEXPR void operator=(basic_string_view<Char> s) { - auto size = s.size(); - if (size > max_size) { - FMT_THROW(format_error("invalid fill")); - return; - } - for (size_t i = 0; i < size; ++i) data_[i] = s[i]; - size_ = static_cast<unsigned char>(size); - } - - size_t size() const { return size_; } - const Char* data() const { return data_; } - - FMT_CONSTEXPR Char& operator[](size_t index) { return data_[index]; } - FMT_CONSTEXPR const Char& operator[](size_t index) const { - return data_[index]; - } -}; + + public: + FMT_CONSTEXPR void operator=(basic_string_view<Char> s) { + auto size = s.size(); + if (size > max_size) { + FMT_THROW(format_error("invalid fill")); + return; + } + for (size_t i = 0; i < size; ++i) data_[i] = s[i]; + size_ = static_cast<unsigned char>(size); + } + + size_t size() const { return size_; } + const Char* data() const { return data_; } + + FMT_CONSTEXPR Char& operator[](size_t index) { return data_[index]; } + FMT_CONSTEXPR const Char& operator[](size_t index) const { + return data_[index]; + } +}; } // namespace detail - -// We cannot use enum classes as bit fields because of a gcc bug -// https://gcc.gnu.org/bugzilla/show_bug.cgi?id=61414. -namespace align { -enum type { none, left, right, center, numeric }; -} -using align_t = align::type; - -namespace sign { -enum type { none, minus, plus, space }; -} -using sign_t = sign::type; - -// Format specifiers for built-in and string types. -template <typename Char> struct basic_format_specs { - int width; - int precision; - char type; - align_t align : 4; - sign_t sign : 3; - bool alt : 1; // Alternate form ('#'). + +// We cannot use enum classes as bit fields because of a gcc bug +// https://gcc.gnu.org/bugzilla/show_bug.cgi?id=61414. +namespace align { +enum type { none, left, right, center, numeric }; +} +using align_t = align::type; + +namespace sign { +enum type { none, minus, plus, space }; +} +using sign_t = sign::type; + +// Format specifiers for built-in and string types. +template <typename Char> struct basic_format_specs { + int width; + int precision; + char type; + align_t align : 4; + sign_t sign : 3; + bool alt : 1; // Alternate form ('#'). detail::fill_t<Char> fill; - - constexpr basic_format_specs() - : width(0), - precision(-1), - type(0), - align(align::none), - sign(sign::none), + + constexpr basic_format_specs() + : width(0), + precision(-1), + type(0), + align(align::none), + sign(sign::none), alt(false) {} -}; - -using format_specs = basic_format_specs<char>; - +}; + +using format_specs = basic_format_specs<char>; + namespace detail { namespace dragonbox { - + // Type-specific information that Dragonbox uses. template <class T> struct float_info; @@ -1276,217 +1276,217 @@ constexpr typename dragonbox::float_info<T>::carrier_uint exponent_mask() { << dragonbox::float_info<T>::significand_bits; } -// A floating-point presentation format. -enum class float_format : unsigned char { - general, // General: exponent notation or fixed point based on magnitude. - exp, // Exponent notation with the default precision of 6, e.g. 1.2e-3. - fixed, // Fixed point with the default precision of 6, e.g. 0.0012. - hex -}; - -struct float_specs { - int precision; - float_format format : 8; - sign_t sign : 8; - bool upper : 1; - bool locale : 1; - bool binary32 : 1; - bool use_grisu : 1; - bool showpoint : 1; -}; - -// Writes the exponent exp in the form "[+-]d{2,3}" to buffer. -template <typename Char, typename It> It write_exponent(int exp, It it) { - FMT_ASSERT(-10000 < exp && exp < 10000, "exponent out of range"); - if (exp < 0) { - *it++ = static_cast<Char>('-'); - exp = -exp; - } else { - *it++ = static_cast<Char>('+'); - } - if (exp >= 100) { +// A floating-point presentation format. +enum class float_format : unsigned char { + general, // General: exponent notation or fixed point based on magnitude. + exp, // Exponent notation with the default precision of 6, e.g. 1.2e-3. + fixed, // Fixed point with the default precision of 6, e.g. 0.0012. + hex +}; + +struct float_specs { + int precision; + float_format format : 8; + sign_t sign : 8; + bool upper : 1; + bool locale : 1; + bool binary32 : 1; + bool use_grisu : 1; + bool showpoint : 1; +}; + +// Writes the exponent exp in the form "[+-]d{2,3}" to buffer. +template <typename Char, typename It> It write_exponent(int exp, It it) { + FMT_ASSERT(-10000 < exp && exp < 10000, "exponent out of range"); + if (exp < 0) { + *it++ = static_cast<Char>('-'); + exp = -exp; + } else { + *it++ = static_cast<Char>('+'); + } + if (exp >= 100) { const char* top = data::digits[exp / 100]; - if (exp >= 1000) *it++ = static_cast<Char>(top[0]); - *it++ = static_cast<Char>(top[1]); - exp %= 100; - } + if (exp >= 1000) *it++ = static_cast<Char>(top[0]); + *it++ = static_cast<Char>(top[1]); + exp %= 100; + } const char* d = data::digits[exp]; - *it++ = static_cast<Char>(d[0]); - *it++ = static_cast<Char>(d[1]); - return it; -} - -template <typename T> -int format_float(T value, int precision, float_specs specs, buffer<char>& buf); - -// Formats a floating-point number with snprintf. -template <typename T> -int snprintf_float(T value, int precision, float_specs specs, - buffer<char>& buf); - -template <typename T> T promote_float(T value) { return value; } -inline double promote_float(float value) { return static_cast<double>(value); } - -template <typename Handler> -FMT_CONSTEXPR void handle_int_type_spec(char spec, Handler&& handler) { - switch (spec) { - case 0: - case 'd': - handler.on_dec(); - break; - case 'x': - case 'X': - handler.on_hex(); - break; - case 'b': - case 'B': - handler.on_bin(); - break; - case 'o': - handler.on_oct(); - break; + *it++ = static_cast<Char>(d[0]); + *it++ = static_cast<Char>(d[1]); + return it; +} + +template <typename T> +int format_float(T value, int precision, float_specs specs, buffer<char>& buf); + +// Formats a floating-point number with snprintf. +template <typename T> +int snprintf_float(T value, int precision, float_specs specs, + buffer<char>& buf); + +template <typename T> T promote_float(T value) { return value; } +inline double promote_float(float value) { return static_cast<double>(value); } + +template <typename Handler> +FMT_CONSTEXPR void handle_int_type_spec(char spec, Handler&& handler) { + switch (spec) { + case 0: + case 'd': + handler.on_dec(); + break; + case 'x': + case 'X': + handler.on_hex(); + break; + case 'b': + case 'B': + handler.on_bin(); + break; + case 'o': + handler.on_oct(); + break; #ifdef FMT_DEPRECATED_N_SPECIFIER - case 'n': + case 'n': #endif - case 'L': - handler.on_num(); - break; + case 'L': + handler.on_num(); + break; case 'c': handler.on_chr(); break; - default: - handler.on_error(); - } -} - -template <typename ErrorHandler = error_handler, typename Char> -FMT_CONSTEXPR float_specs parse_float_type_spec( - const basic_format_specs<Char>& specs, ErrorHandler&& eh = {}) { - auto result = float_specs(); - result.showpoint = specs.alt; - switch (specs.type) { - case 0: - result.format = float_format::general; - result.showpoint |= specs.precision > 0; - break; - case 'G': - result.upper = true; - FMT_FALLTHROUGH; - case 'g': - result.format = float_format::general; - break; - case 'E': - result.upper = true; - FMT_FALLTHROUGH; - case 'e': - result.format = float_format::exp; - result.showpoint |= specs.precision != 0; - break; - case 'F': - result.upper = true; - FMT_FALLTHROUGH; - case 'f': - result.format = float_format::fixed; - result.showpoint |= specs.precision != 0; - break; - case 'A': - result.upper = true; - FMT_FALLTHROUGH; - case 'a': - result.format = float_format::hex; - break; + default: + handler.on_error(); + } +} + +template <typename ErrorHandler = error_handler, typename Char> +FMT_CONSTEXPR float_specs parse_float_type_spec( + const basic_format_specs<Char>& specs, ErrorHandler&& eh = {}) { + auto result = float_specs(); + result.showpoint = specs.alt; + switch (specs.type) { + case 0: + result.format = float_format::general; + result.showpoint |= specs.precision > 0; + break; + case 'G': + result.upper = true; + FMT_FALLTHROUGH; + case 'g': + result.format = float_format::general; + break; + case 'E': + result.upper = true; + FMT_FALLTHROUGH; + case 'e': + result.format = float_format::exp; + result.showpoint |= specs.precision != 0; + break; + case 'F': + result.upper = true; + FMT_FALLTHROUGH; + case 'f': + result.format = float_format::fixed; + result.showpoint |= specs.precision != 0; + break; + case 'A': + result.upper = true; + FMT_FALLTHROUGH; + case 'a': + result.format = float_format::hex; + break; #ifdef FMT_DEPRECATED_N_SPECIFIER - case 'n': + case 'n': #endif case 'L': - result.locale = true; - break; - default: - eh.on_error("invalid type specifier"); - break; - } - return result; -} - -template <typename Char, typename Handler> -FMT_CONSTEXPR void handle_char_specs(const basic_format_specs<Char>* specs, - Handler&& handler) { - if (!specs) return handler.on_char(); - if (specs->type && specs->type != 'c') return handler.on_int(); - if (specs->align == align::numeric || specs->sign != sign::none || specs->alt) - handler.on_error("invalid format specifier for char"); - handler.on_char(); -} - -template <typename Char, typename Handler> -FMT_CONSTEXPR void handle_cstring_type_spec(Char spec, Handler&& handler) { - if (spec == 0 || spec == 's') - handler.on_string(); - else if (spec == 'p') - handler.on_pointer(); - else - handler.on_error("invalid type specifier"); -} - -template <typename Char, typename ErrorHandler> -FMT_CONSTEXPR void check_string_type_spec(Char spec, ErrorHandler&& eh) { - if (spec != 0 && spec != 's') eh.on_error("invalid type specifier"); -} - -template <typename Char, typename ErrorHandler> -FMT_CONSTEXPR void check_pointer_type_spec(Char spec, ErrorHandler&& eh) { - if (spec != 0 && spec != 'p') eh.on_error("invalid type specifier"); -} - -template <typename ErrorHandler> class int_type_checker : private ErrorHandler { - public: - FMT_CONSTEXPR explicit int_type_checker(ErrorHandler eh) : ErrorHandler(eh) {} - - FMT_CONSTEXPR void on_dec() {} - FMT_CONSTEXPR void on_hex() {} - FMT_CONSTEXPR void on_bin() {} - FMT_CONSTEXPR void on_oct() {} - FMT_CONSTEXPR void on_num() {} + result.locale = true; + break; + default: + eh.on_error("invalid type specifier"); + break; + } + return result; +} + +template <typename Char, typename Handler> +FMT_CONSTEXPR void handle_char_specs(const basic_format_specs<Char>* specs, + Handler&& handler) { + if (!specs) return handler.on_char(); + if (specs->type && specs->type != 'c') return handler.on_int(); + if (specs->align == align::numeric || specs->sign != sign::none || specs->alt) + handler.on_error("invalid format specifier for char"); + handler.on_char(); +} + +template <typename Char, typename Handler> +FMT_CONSTEXPR void handle_cstring_type_spec(Char spec, Handler&& handler) { + if (spec == 0 || spec == 's') + handler.on_string(); + else if (spec == 'p') + handler.on_pointer(); + else + handler.on_error("invalid type specifier"); +} + +template <typename Char, typename ErrorHandler> +FMT_CONSTEXPR void check_string_type_spec(Char spec, ErrorHandler&& eh) { + if (spec != 0 && spec != 's') eh.on_error("invalid type specifier"); +} + +template <typename Char, typename ErrorHandler> +FMT_CONSTEXPR void check_pointer_type_spec(Char spec, ErrorHandler&& eh) { + if (spec != 0 && spec != 'p') eh.on_error("invalid type specifier"); +} + +template <typename ErrorHandler> class int_type_checker : private ErrorHandler { + public: + FMT_CONSTEXPR explicit int_type_checker(ErrorHandler eh) : ErrorHandler(eh) {} + + FMT_CONSTEXPR void on_dec() {} + FMT_CONSTEXPR void on_hex() {} + FMT_CONSTEXPR void on_bin() {} + FMT_CONSTEXPR void on_oct() {} + FMT_CONSTEXPR void on_num() {} FMT_CONSTEXPR void on_chr() {} - - FMT_CONSTEXPR void on_error() { - ErrorHandler::on_error("invalid type specifier"); - } -}; - -template <typename ErrorHandler> -class char_specs_checker : public ErrorHandler { - private: - char type_; - - public: - FMT_CONSTEXPR char_specs_checker(char type, ErrorHandler eh) - : ErrorHandler(eh), type_(type) {} - - FMT_CONSTEXPR void on_int() { - handle_int_type_spec(type_, int_type_checker<ErrorHandler>(*this)); - } - FMT_CONSTEXPR void on_char() {} -}; - -template <typename ErrorHandler> -class cstring_type_checker : public ErrorHandler { - public: - FMT_CONSTEXPR explicit cstring_type_checker(ErrorHandler eh) - : ErrorHandler(eh) {} - - FMT_CONSTEXPR void on_string() {} - FMT_CONSTEXPR void on_pointer() {} -}; - -template <typename OutputIt, typename Char> -FMT_NOINLINE OutputIt fill(OutputIt it, size_t n, const fill_t<Char>& fill) { - auto fill_size = fill.size(); - if (fill_size == 1) return std::fill_n(it, n, fill[0]); - for (size_t i = 0; i < n; ++i) it = std::copy_n(fill.data(), fill_size, it); - return it; -} - + + FMT_CONSTEXPR void on_error() { + ErrorHandler::on_error("invalid type specifier"); + } +}; + +template <typename ErrorHandler> +class char_specs_checker : public ErrorHandler { + private: + char type_; + + public: + FMT_CONSTEXPR char_specs_checker(char type, ErrorHandler eh) + : ErrorHandler(eh), type_(type) {} + + FMT_CONSTEXPR void on_int() { + handle_int_type_spec(type_, int_type_checker<ErrorHandler>(*this)); + } + FMT_CONSTEXPR void on_char() {} +}; + +template <typename ErrorHandler> +class cstring_type_checker : public ErrorHandler { + public: + FMT_CONSTEXPR explicit cstring_type_checker(ErrorHandler eh) + : ErrorHandler(eh) {} + + FMT_CONSTEXPR void on_string() {} + FMT_CONSTEXPR void on_pointer() {} +}; + +template <typename OutputIt, typename Char> +FMT_NOINLINE OutputIt fill(OutputIt it, size_t n, const fill_t<Char>& fill) { + auto fill_size = fill.size(); + if (fill_size == 1) return std::fill_n(it, n, fill[0]); + for (size_t i = 0; i < n; ++i) it = std::copy_n(fill.data(), fill_size, it); + return it; +} + // Writes the output of f, padded according to format specifications in specs. // size: output size in code units. // width: output display width in (terminal) column positions. @@ -1507,7 +1507,7 @@ inline OutputIt write_padded(OutputIt out, it = fill(it, padding - left_padding, specs.fill); return base_iterator(out, it); } - + template <align::type align = align::left, typename OutputIt, typename Char, typename F> inline OutputIt write_padded(OutputIt out, @@ -1515,7 +1515,7 @@ inline OutputIt write_padded(OutputIt out, F&& f) { return write_padded<align>(out, specs, size, size, f); } - + template <typename Char, typename OutputIt> OutputIt write_bytes(OutputIt out, string_view bytes, const basic_format_specs<Char>& specs) { @@ -1525,29 +1525,29 @@ OutputIt write_bytes(OutputIt out, string_view bytes, return copy_str<Char>(data, data + bytes.size(), it); }); } - + // Data for write_int that doesn't depend on output iterator type. It is used to // avoid template code bloat. template <typename Char> struct write_int_data { size_t size; size_t padding; - + write_int_data(int num_digits, string_view prefix, const basic_format_specs<Char>& specs) : size(prefix.size() + to_unsigned(num_digits)), padding(0) { - if (specs.align == align::numeric) { + if (specs.align == align::numeric) { auto width = to_unsigned(specs.width); if (width > size) { padding = width - size; size = width; - } - } else if (specs.precision > num_digits) { - size = prefix.size() + to_unsigned(specs.precision); - padding = to_unsigned(specs.precision - num_digits); - } - } + } + } else if (specs.precision > num_digits) { + size = prefix.size() + to_unsigned(specs.precision); + padding = to_unsigned(specs.precision - num_digits); + } + } }; - + // Writes an integer in the format // <left-padding><prefix><numeric-padding><digits><right-padding> // where <digits> are written by f(it). @@ -1563,7 +1563,7 @@ OutputIt write_int(OutputIt out, int num_digits, string_view prefix, return f(it); }); } - + template <typename StrChar, typename Char, typename OutputIt> OutputIt write(OutputIt out, basic_string_view<StrChar> s, const basic_format_specs<Char>& specs) { @@ -1579,7 +1579,7 @@ OutputIt write(OutputIt out, basic_string_view<StrChar> s, return copy_str<Char>(data, data + size, it); }); } - + // The handle_int_type_spec handler that writes an integer. template <typename OutputIt, typename Char, typename UInt> struct int_writer { OutputIt out; @@ -1588,10 +1588,10 @@ template <typename OutputIt, typename Char, typename UInt> struct int_writer { UInt abs_value; char prefix[4]; unsigned prefix_size; - + using iterator = remove_reference_t<decltype(reserve(std::declval<OutputIt&>(), 0))>; - + string_view get_prefix() const { return string_view(prefix, prefix_size); } template <typename Int> @@ -1610,9 +1610,9 @@ template <typename OutputIt, typename Char, typename UInt> struct int_writer { } else if (specs.sign != sign::none && specs.sign != sign::minus) { prefix[0] = specs.sign == sign::plus ? '+' : ' '; ++prefix_size; - } + } } - + void on_dec() { auto num_digits = count_digits(abs_value); out = write_int( @@ -1620,7 +1620,7 @@ template <typename OutputIt, typename Char, typename UInt> struct int_writer { return format_decimal<Char>(it, abs_value, num_digits).end; }); } - + void on_hex() { if (specs.alt) { prefix[prefix_size++] = '0'; @@ -1633,19 +1633,19 @@ template <typename OutputIt, typename Char, typename UInt> struct int_writer { specs.type != 'x'); }); } - + void on_bin() { if (specs.alt) { prefix[prefix_size++] = '0'; prefix[prefix_size++] = static_cast<char>(specs.type); - } + } int num_digits = count_digits<1>(abs_value); out = write_int(out, num_digits, get_prefix(), specs, [this, num_digits](iterator it) { return format_uint<1, Char>(it, abs_value, num_digits); }); } - + void on_oct() { int num_digits = count_digits<3>(abs_value); if (specs.alt && specs.precision <= num_digits && abs_value != 0) { @@ -1658,9 +1658,9 @@ template <typename OutputIt, typename Char, typename UInt> struct int_writer { return format_uint<3, Char>(it, abs_value, num_digits); }); } - + enum { sep_size = 1 }; - + void on_num() { std::string groups = grouping<Char>(locale); if (groups.empty()) return on_dec(); @@ -1695,11 +1695,11 @@ template <typename OutputIt, typename Char, typename UInt> struct int_writer { if (group + 1 != groups.cend()) { digit_index = 0; ++group; - } + } std::uninitialized_copy(s.data(), s.data() + s.size(), make_checked(p, s.size())); p -= s.size(); - } + } *p-- = static_cast<Char>(*digits); if (prefix_size != 0) *p = static_cast<Char>('-'); auto data = buffer.data(); @@ -1707,14 +1707,14 @@ template <typename OutputIt, typename Char, typename UInt> struct int_writer { out, specs, usize, usize, [=](iterator it) { return copy_str<Char>(data, data + size, it); }); } - + void on_chr() { *out++ = static_cast<Char>(abs_value); } - + FMT_NORETURN void on_error() { FMT_THROW(format_error("invalid type specifier")); } }; - + template <typename Char, typename OutputIt> OutputIt write_nonfinite(OutputIt out, bool isinf, const basic_format_specs<Char>& specs, @@ -1730,14 +1730,14 @@ OutputIt write_nonfinite(OutputIt out, bool isinf, return copy_str<Char>(str, str + str_size, it); }); } - + // A decimal floating-point number significand * pow(10, exp). struct big_decimal_fp { const char* significand; int significand_size; int exponent; }; - + inline int get_significand_size(const big_decimal_fp& fp) { return fp.significand_size; } @@ -1745,7 +1745,7 @@ template <typename T> inline int get_significand_size(const dragonbox::decimal_fp<T>& fp) { return count_digits(fp.significand); } - + template <typename Char, typename OutputIt> inline OutputIt write_significand(OutputIt out, const char* significand, int& significand_size) { @@ -1756,7 +1756,7 @@ inline OutputIt write_significand(OutputIt out, UInt significand, int significand_size) { return format_decimal<Char>(out, significand, significand_size).end; } - + template <typename Char, typename UInt, FMT_ENABLE_IF(std::is_integral<UInt>::value)> inline Char* write_significand(Char* out, UInt significand, @@ -1772,7 +1772,7 @@ inline Char* write_significand(Char* out, UInt significand, out[integral_size] = decimal_point; return end; } - + template <typename OutputIt, typename UInt, typename Char, FMT_ENABLE_IF(!std::is_pointer<remove_cvref_t<OutputIt>>::value)> inline OutputIt write_significand(OutputIt out, UInt significand, @@ -1784,7 +1784,7 @@ inline OutputIt write_significand(OutputIt out, UInt significand, integral_size, decimal_point); return detail::copy_str<Char>(buffer, end, out); } - + template <typename OutputIt, typename Char> inline OutputIt write_significand(OutputIt out, const char* significand, int significand_size, int integral_size, @@ -1795,7 +1795,7 @@ inline OutputIt write_significand(OutputIt out, const char* significand, return detail::copy_str<Char>(significand + integral_size, significand + significand_size, out); } - + template <typename OutputIt, typename DecimalFP, typename Char> OutputIt write_float(OutputIt out, const DecimalFP& fp, const basic_format_specs<Char>& specs, float_specs fspecs, @@ -1806,7 +1806,7 @@ OutputIt write_float(OutputIt out, const DecimalFP& fp, auto sign = fspecs.sign; size_t size = to_unsigned(significand_size) + (sign ? 1 : 0); using iterator = remove_reference_t<decltype(reserve(out, 0))>; - + int output_exp = fp.exponent + significand_size - 1; auto use_exp_format = [=]() { if (fspecs.format == float_format::exp) return true; @@ -1824,11 +1824,11 @@ OutputIt write_float(OutputIt out, const DecimalFP& fp, size += to_unsigned(num_zeros); } else if (significand_size == 1) { decimal_point = Char(); - } + } auto abs_output_exp = output_exp >= 0 ? output_exp : -output_exp; int exp_digits = 2; if (abs_output_exp >= 100) exp_digits = abs_output_exp >= 1000 ? 4 : 3; - + size += to_unsigned((decimal_point ? 1 : 0) + 2 + exp_digits); char exp_char = fspecs.upper ? 'E' : 'e'; auto write = [=](iterator it) { @@ -1856,7 +1856,7 @@ OutputIt write_float(OutputIt out, const DecimalFP& fp, if (fspecs.showpoint) { if (num_zeros <= 0 && fspecs.format != float_format::fixed) num_zeros = 1; if (num_zeros > 0) size += to_unsigned(num_zeros); - } + } return write_padded<align::right>(out, specs, size, [&](iterator it) { if (sign) *it++ = static_cast<Char>(data::signs[sign]); it = write_significand<Char>(it, significand, significand_size); @@ -1892,7 +1892,7 @@ OutputIt write_float(OutputIt out, const DecimalFP& fp, return write_significand<Char>(it, significand, significand_size); }); } - + template <typename Char, typename OutputIt, typename T, FMT_ENABLE_IF(std::is_floating_point<T>::value)> OutputIt write(OutputIt out, T value, basic_format_specs<Char> specs, @@ -1906,10 +1906,10 @@ OutputIt write(OutputIt out, T value, basic_format_specs<Char> specs, } else if (fspecs.sign == sign::minus) { fspecs.sign = sign::none; } - + if (!std::isfinite(value)) return write_nonfinite(out, std::isinf(value), specs, fspecs); - + if (specs.align == align::numeric && fspecs.sign) { auto it = reserve(out, 1); *it++ = static_cast<Char>(data::signs[fspecs.sign]); @@ -1917,7 +1917,7 @@ OutputIt write(OutputIt out, T value, basic_format_specs<Char> specs, fspecs.sign = sign::none; if (specs.width != 0) --specs.width; } - + memory_buffer buffer; if (fspecs.format == float_format::hex) { if (fspecs.sign) buffer.push_back(data::signs[fspecs.sign]); @@ -1940,12 +1940,12 @@ OutputIt write(OutputIt out, T value, basic_format_specs<Char> specs, auto fp = big_decimal_fp{buffer.data(), static_cast<int>(buffer.size()), exp}; return write_float(out, fp, specs, fspecs, point); } - + template <typename Char, typename OutputIt, typename T, FMT_ENABLE_IF(is_fast_float<T>::value)> OutputIt write(OutputIt out, T value) { if (const_check(!is_supported_floating_point(value))) return out; - + using floaty = conditional_t<std::is_same<T, long double>::value, double, T>; using uint = typename dragonbox::float_info<floaty>::carrier_uint; auto bits = bit_cast<uint>(value); @@ -1993,21 +1993,21 @@ OutputIt write_ptr(OutputIt out, UIntPtr value, *it++ = static_cast<Char>('0'); *it++ = static_cast<Char>('x'); return format_uint<4, Char>(it, value, num_digits); - }; + }; return specs ? write_padded<align::right>(out, *specs, size, write) : base_iterator(out, write(reserve(out, size))); } - + template <typename T> struct is_integral : std::is_integral<T> {}; template <> struct is_integral<int128_t> : std::true_type {}; template <> struct is_integral<uint128_t> : std::true_type {}; - + template <typename Char, typename OutputIt> OutputIt write(OutputIt out, monostate) { FMT_ASSERT(false, ""); return out; } - + template <typename Char, typename OutputIt, FMT_ENABLE_IF(!std::is_same<Char, char>::value)> OutputIt write(OutputIt out, string_view value) { @@ -2046,24 +2046,24 @@ OutputIt write(OutputIt out, T value) { if (negative) *ptr++ = static_cast<Char>('-'); format_decimal<Char>(ptr, abs_value, num_digits); return out; - } + } if (negative) *it++ = static_cast<Char>('-'); it = format_decimal<Char>(it, abs_value, num_digits).end; return base_iterator(out, it); } - + template <typename Char, typename OutputIt> OutputIt write(OutputIt out, bool value) { return write<Char>(out, string_view(value ? "true" : "false")); } - + template <typename Char, typename OutputIt> OutputIt write(OutputIt out, Char value) { auto it = reserve(out, 1); *it++ = value; return base_iterator(out, it); } - + template <typename Char, typename OutputIt> OutputIt write(OutputIt out, const Char* value) { if (!value) { @@ -2074,7 +2074,7 @@ OutputIt write(OutputIt out, const Char* value) { } return out; } - + template <typename Char, typename OutputIt> OutputIt write(OutputIt out, const void* value) { return write_ptr<Char>(out, to_uintptr(value), nullptr); @@ -2105,8 +2105,8 @@ template <typename OutputIt, typename Char> struct default_arg_formatter { template <typename T> OutputIt operator()(T value) { return write<Char>(out, value); - } - + } + OutputIt operator()(typename basic_format_arg<context>::handle handle) { basic_format_parse_context<Char> parse_ctx({}); basic_format_context<OutputIt, Char> format_ctx(out, args, loc); @@ -2114,7 +2114,7 @@ template <typename OutputIt, typename Char> struct default_arg_formatter { return format_ctx.out(); } }; - + template <typename OutputIt, typename Char, typename ErrorHandler = error_handler> class arg_formatter_base { @@ -2122,18 +2122,18 @@ class arg_formatter_base { using iterator = OutputIt; using char_type = Char; using format_specs = basic_format_specs<Char>; - + private: iterator out_; locale_ref locale_; format_specs* specs_; - + // Attempts to reserve space for n extra characters in the output range. // Returns a pointer to the reserved range or a reference to out_. auto reserve(size_t n) -> decltype(detail::reserve(out_, n)) { return detail::reserve(out_, n); - } - + } + using reserve_iterator = remove_reference_t<decltype( detail::reserve(std::declval<iterator&>(), 0))>; @@ -2144,26 +2144,26 @@ class arg_formatter_base { out_ = w.out; } - void write(char value) { - auto&& it = reserve(1); - *it++ = value; - } - + void write(char value) { + auto&& it = reserve(1); + *it++ = value; + } + template <typename Ch, FMT_ENABLE_IF(std::is_same<Ch, Char>::value)> void write(Ch value) { out_ = detail::write<Char>(out_, value); - } - - void write(string_view value) { - auto&& it = reserve(value.size()); + } + + void write(string_view value) { + auto&& it = reserve(value.size()); it = copy_str<Char>(value.begin(), value.end(), it); - } - void write(wstring_view value) { + } + void write(wstring_view value) { static_assert(std::is_same<Char, wchar_t>::value, ""); - auto&& it = reserve(value.size()); - it = std::copy(value.begin(), value.end(), it); - } - + auto&& it = reserve(value.size()); + it = std::copy(value.begin(), value.end(), it); + } + template <typename Ch> void write(const Ch* s, size_t size, const format_specs& specs) { auto width = specs.width != 0 @@ -2172,24 +2172,24 @@ class arg_formatter_base { out_ = write_padded(out_, specs, size, width, [=](reserve_iterator it) { return copy_str<Char>(s, s + size, it); }); - } - + } + template <typename Ch> void write(basic_string_view<Ch> s, const format_specs& specs = {}) { out_ = detail::write(out_, s, specs); - } - + } + void write_pointer(const void* p) { out_ = write_ptr<char_type>(out_, to_uintptr(p), specs_); - } - + } + struct char_spec_handler : ErrorHandler { arg_formatter_base& formatter; Char value; - + char_spec_handler(arg_formatter_base& f, Char val) : formatter(f), value(val) {} - + void on_int() { // char is only formatted as int if there are specs. formatter.write_int(static_cast<int>(value), *formatter.specs_); @@ -2201,102 +2201,102 @@ class arg_formatter_base { formatter.write(value); } }; - + struct cstring_spec_handler : error_handler { arg_formatter_base& formatter; const Char* value; - + cstring_spec_handler(arg_formatter_base& f, const Char* val) : formatter(f), value(val) {} - + void on_string() { formatter.write(value); } void on_pointer() { formatter.write_pointer(value); } - }; - - protected: + }; + + protected: iterator out() { return out_; } - format_specs* specs() { return specs_; } - - void write(bool value) { + format_specs* specs() { return specs_; } + + void write(bool value) { if (specs_) write(string_view(value ? "true" : "false"), *specs_); else out_ = detail::write<Char>(out_, value); - } - + } + void write(const Char* value) { - if (!value) { - FMT_THROW(format_error("string pointer is null")); - } else { - auto length = std::char_traits<char_type>::length(value); - basic_string_view<char_type> sv(value, length); + if (!value) { + FMT_THROW(format_error("string pointer is null")); + } else { + auto length = std::char_traits<char_type>::length(value); + basic_string_view<char_type> sv(value, length); specs_ ? write(sv, *specs_) : write(sv); - } - } - - public: + } + } + + public: arg_formatter_base(OutputIt out, format_specs* s, locale_ref loc) : out_(out), locale_(loc), specs_(s) {} - - iterator operator()(monostate) { - FMT_ASSERT(false, "invalid argument type"); + + iterator operator()(monostate) { + FMT_ASSERT(false, "invalid argument type"); return out_; - } - - template <typename T, FMT_ENABLE_IF(is_integral<T>::value)> + } + + template <typename T, FMT_ENABLE_IF(is_integral<T>::value)> FMT_INLINE iterator operator()(T value) { - if (specs_) + if (specs_) write_int(value, *specs_); - else + else out_ = detail::write<Char>(out_, value); return out_; - } - + } + iterator operator()(Char value) { handle_char_specs(specs_, char_spec_handler(*this, static_cast<Char>(value))); return out_; - } - - iterator operator()(bool value) { - if (specs_ && specs_->type) return (*this)(value ? 1 : 0); - write(value != 0); + } + + iterator operator()(bool value) { + if (specs_ && specs_->type) return (*this)(value ? 1 : 0); + write(value != 0); return out_; - } - - template <typename T, FMT_ENABLE_IF(std::is_floating_point<T>::value)> - iterator operator()(T value) { + } + + template <typename T, FMT_ENABLE_IF(std::is_floating_point<T>::value)> + iterator operator()(T value) { auto specs = specs_ ? *specs_ : format_specs(); - if (const_check(is_supported_floating_point(value))) + if (const_check(is_supported_floating_point(value))) out_ = detail::write(out_, value, specs, locale_); - else - FMT_ASSERT(false, "unsupported float argument type"); + else + FMT_ASSERT(false, "unsupported float argument type"); return out_; - } - + } + iterator operator()(const Char* value) { if (!specs_) return write(value), out_; handle_cstring_type_spec(specs_->type, cstring_spec_handler(*this, value)); return out_; - } - + } + iterator operator()(basic_string_view<Char> value) { - if (specs_) { + if (specs_) { check_string_type_spec(specs_->type, error_handler()); write(value, *specs_); - } else { + } else { write(value); - } + } return out_; - } - - iterator operator()(const void* value) { + } + + iterator operator()(const void* value) { if (specs_) check_pointer_type_spec(specs_->type, error_handler()); - write_pointer(value); + write_pointer(value); return out_; - } -}; - + } +}; + /** The default argument formatter. */ template <typename OutputIt, typename Char> class arg_formatter : public arg_formatter_base<OutputIt, Char> { @@ -2339,431 +2339,431 @@ class arg_formatter : public arg_formatter_base<OutputIt, Char> { } }; -template <typename Char> FMT_CONSTEXPR bool is_name_start(Char c) { - return ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z') || '_' == c; -} - -// Parses the range [begin, end) as an unsigned integer. This function assumes -// that the range is non-empty and the first character is a digit. -template <typename Char, typename ErrorHandler> -FMT_CONSTEXPR int parse_nonnegative_int(const Char*& begin, const Char* end, - ErrorHandler&& eh) { - FMT_ASSERT(begin != end && '0' <= *begin && *begin <= '9', ""); - unsigned value = 0; - // Convert to unsigned to prevent a warning. - constexpr unsigned max_int = max_value<int>(); - unsigned big = max_int / 10; - do { - // Check for overflow. - if (value > big) { - value = max_int + 1; - break; - } - value = value * 10 + unsigned(*begin - '0'); - ++begin; - } while (begin != end && '0' <= *begin && *begin <= '9'); - if (value > max_int) eh.on_error("number is too big"); - return static_cast<int>(value); -} - -template <typename Context> class custom_formatter { - private: - using char_type = typename Context::char_type; - - basic_format_parse_context<char_type>& parse_ctx_; - Context& ctx_; - - public: - explicit custom_formatter(basic_format_parse_context<char_type>& parse_ctx, - Context& ctx) - : parse_ctx_(parse_ctx), ctx_(ctx) {} - +template <typename Char> FMT_CONSTEXPR bool is_name_start(Char c) { + return ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z') || '_' == c; +} + +// Parses the range [begin, end) as an unsigned integer. This function assumes +// that the range is non-empty and the first character is a digit. +template <typename Char, typename ErrorHandler> +FMT_CONSTEXPR int parse_nonnegative_int(const Char*& begin, const Char* end, + ErrorHandler&& eh) { + FMT_ASSERT(begin != end && '0' <= *begin && *begin <= '9', ""); + unsigned value = 0; + // Convert to unsigned to prevent a warning. + constexpr unsigned max_int = max_value<int>(); + unsigned big = max_int / 10; + do { + // Check for overflow. + if (value > big) { + value = max_int + 1; + break; + } + value = value * 10 + unsigned(*begin - '0'); + ++begin; + } while (begin != end && '0' <= *begin && *begin <= '9'); + if (value > max_int) eh.on_error("number is too big"); + return static_cast<int>(value); +} + +template <typename Context> class custom_formatter { + private: + using char_type = typename Context::char_type; + + basic_format_parse_context<char_type>& parse_ctx_; + Context& ctx_; + + public: + explicit custom_formatter(basic_format_parse_context<char_type>& parse_ctx, + Context& ctx) + : parse_ctx_(parse_ctx), ctx_(ctx) {} + void operator()(typename basic_format_arg<Context>::handle h) const { - h.format(parse_ctx_, ctx_); - } - + h.format(parse_ctx_, ctx_); + } + template <typename T> void operator()(T) const {} -}; - -template <typename T> -using is_integer = - bool_constant<is_integral<T>::value && !std::is_same<T, bool>::value && - !std::is_same<T, char>::value && - !std::is_same<T, wchar_t>::value>; - -template <typename ErrorHandler> class width_checker { - public: - explicit FMT_CONSTEXPR width_checker(ErrorHandler& eh) : handler_(eh) {} - - template <typename T, FMT_ENABLE_IF(is_integer<T>::value)> - FMT_CONSTEXPR unsigned long long operator()(T value) { - if (is_negative(value)) handler_.on_error("negative width"); - return static_cast<unsigned long long>(value); - } - - template <typename T, FMT_ENABLE_IF(!is_integer<T>::value)> - FMT_CONSTEXPR unsigned long long operator()(T) { - handler_.on_error("width is not integer"); - return 0; - } - - private: - ErrorHandler& handler_; -}; - -template <typename ErrorHandler> class precision_checker { - public: - explicit FMT_CONSTEXPR precision_checker(ErrorHandler& eh) : handler_(eh) {} - - template <typename T, FMT_ENABLE_IF(is_integer<T>::value)> - FMT_CONSTEXPR unsigned long long operator()(T value) { - if (is_negative(value)) handler_.on_error("negative precision"); - return static_cast<unsigned long long>(value); - } - - template <typename T, FMT_ENABLE_IF(!is_integer<T>::value)> - FMT_CONSTEXPR unsigned long long operator()(T) { - handler_.on_error("precision is not integer"); - return 0; - } - - private: - ErrorHandler& handler_; -}; - -// A format specifier handler that sets fields in basic_format_specs. -template <typename Char> class specs_setter { - public: - explicit FMT_CONSTEXPR specs_setter(basic_format_specs<Char>& specs) - : specs_(specs) {} - - FMT_CONSTEXPR specs_setter(const specs_setter& other) - : specs_(other.specs_) {} - - FMT_CONSTEXPR void on_align(align_t align) { specs_.align = align; } - FMT_CONSTEXPR void on_fill(basic_string_view<Char> fill) { - specs_.fill = fill; - } - FMT_CONSTEXPR void on_plus() { specs_.sign = sign::plus; } - FMT_CONSTEXPR void on_minus() { specs_.sign = sign::minus; } - FMT_CONSTEXPR void on_space() { specs_.sign = sign::space; } - FMT_CONSTEXPR void on_hash() { specs_.alt = true; } - - FMT_CONSTEXPR void on_zero() { - specs_.align = align::numeric; - specs_.fill[0] = Char('0'); - } - - FMT_CONSTEXPR void on_width(int width) { specs_.width = width; } - FMT_CONSTEXPR void on_precision(int precision) { - specs_.precision = precision; - } - FMT_CONSTEXPR void end_precision() {} - - FMT_CONSTEXPR void on_type(Char type) { - specs_.type = static_cast<char>(type); - } - - protected: - basic_format_specs<Char>& specs_; -}; - -template <typename ErrorHandler> class numeric_specs_checker { - public: +}; + +template <typename T> +using is_integer = + bool_constant<is_integral<T>::value && !std::is_same<T, bool>::value && + !std::is_same<T, char>::value && + !std::is_same<T, wchar_t>::value>; + +template <typename ErrorHandler> class width_checker { + public: + explicit FMT_CONSTEXPR width_checker(ErrorHandler& eh) : handler_(eh) {} + + template <typename T, FMT_ENABLE_IF(is_integer<T>::value)> + FMT_CONSTEXPR unsigned long long operator()(T value) { + if (is_negative(value)) handler_.on_error("negative width"); + return static_cast<unsigned long long>(value); + } + + template <typename T, FMT_ENABLE_IF(!is_integer<T>::value)> + FMT_CONSTEXPR unsigned long long operator()(T) { + handler_.on_error("width is not integer"); + return 0; + } + + private: + ErrorHandler& handler_; +}; + +template <typename ErrorHandler> class precision_checker { + public: + explicit FMT_CONSTEXPR precision_checker(ErrorHandler& eh) : handler_(eh) {} + + template <typename T, FMT_ENABLE_IF(is_integer<T>::value)> + FMT_CONSTEXPR unsigned long long operator()(T value) { + if (is_negative(value)) handler_.on_error("negative precision"); + return static_cast<unsigned long long>(value); + } + + template <typename T, FMT_ENABLE_IF(!is_integer<T>::value)> + FMT_CONSTEXPR unsigned long long operator()(T) { + handler_.on_error("precision is not integer"); + return 0; + } + + private: + ErrorHandler& handler_; +}; + +// A format specifier handler that sets fields in basic_format_specs. +template <typename Char> class specs_setter { + public: + explicit FMT_CONSTEXPR specs_setter(basic_format_specs<Char>& specs) + : specs_(specs) {} + + FMT_CONSTEXPR specs_setter(const specs_setter& other) + : specs_(other.specs_) {} + + FMT_CONSTEXPR void on_align(align_t align) { specs_.align = align; } + FMT_CONSTEXPR void on_fill(basic_string_view<Char> fill) { + specs_.fill = fill; + } + FMT_CONSTEXPR void on_plus() { specs_.sign = sign::plus; } + FMT_CONSTEXPR void on_minus() { specs_.sign = sign::minus; } + FMT_CONSTEXPR void on_space() { specs_.sign = sign::space; } + FMT_CONSTEXPR void on_hash() { specs_.alt = true; } + + FMT_CONSTEXPR void on_zero() { + specs_.align = align::numeric; + specs_.fill[0] = Char('0'); + } + + FMT_CONSTEXPR void on_width(int width) { specs_.width = width; } + FMT_CONSTEXPR void on_precision(int precision) { + specs_.precision = precision; + } + FMT_CONSTEXPR void end_precision() {} + + FMT_CONSTEXPR void on_type(Char type) { + specs_.type = static_cast<char>(type); + } + + protected: + basic_format_specs<Char>& specs_; +}; + +template <typename ErrorHandler> class numeric_specs_checker { + public: FMT_CONSTEXPR numeric_specs_checker(ErrorHandler& eh, detail::type arg_type) - : error_handler_(eh), arg_type_(arg_type) {} - - FMT_CONSTEXPR void require_numeric_argument() { - if (!is_arithmetic_type(arg_type_)) - error_handler_.on_error("format specifier requires numeric argument"); - } - - FMT_CONSTEXPR void check_sign() { - require_numeric_argument(); - if (is_integral_type(arg_type_) && arg_type_ != type::int_type && - arg_type_ != type::long_long_type && arg_type_ != type::char_type) { - error_handler_.on_error("format specifier requires signed argument"); - } - } - - FMT_CONSTEXPR void check_precision() { - if (is_integral_type(arg_type_) || arg_type_ == type::pointer_type) - error_handler_.on_error("precision not allowed for this argument type"); - } - - private: - ErrorHandler& error_handler_; + : error_handler_(eh), arg_type_(arg_type) {} + + FMT_CONSTEXPR void require_numeric_argument() { + if (!is_arithmetic_type(arg_type_)) + error_handler_.on_error("format specifier requires numeric argument"); + } + + FMT_CONSTEXPR void check_sign() { + require_numeric_argument(); + if (is_integral_type(arg_type_) && arg_type_ != type::int_type && + arg_type_ != type::long_long_type && arg_type_ != type::char_type) { + error_handler_.on_error("format specifier requires signed argument"); + } + } + + FMT_CONSTEXPR void check_precision() { + if (is_integral_type(arg_type_) || arg_type_ == type::pointer_type) + error_handler_.on_error("precision not allowed for this argument type"); + } + + private: + ErrorHandler& error_handler_; detail::type arg_type_; -}; - -// A format specifier handler that checks if specifiers are consistent with the -// argument type. -template <typename Handler> class specs_checker : public Handler { +}; + +// A format specifier handler that checks if specifiers are consistent with the +// argument type. +template <typename Handler> class specs_checker : public Handler { private: numeric_specs_checker<Handler> checker_; // Suppress an MSVC warning about using this in initializer list. FMT_CONSTEXPR Handler& error_handler() { return *this; } - public: + public: FMT_CONSTEXPR specs_checker(const Handler& handler, detail::type arg_type) : Handler(handler), checker_(error_handler(), arg_type) {} - - FMT_CONSTEXPR specs_checker(const specs_checker& other) + + FMT_CONSTEXPR specs_checker(const specs_checker& other) : Handler(other), checker_(error_handler(), other.arg_type_) {} - - FMT_CONSTEXPR void on_align(align_t align) { - if (align == align::numeric) checker_.require_numeric_argument(); - Handler::on_align(align); - } - - FMT_CONSTEXPR void on_plus() { - checker_.check_sign(); - Handler::on_plus(); - } - - FMT_CONSTEXPR void on_minus() { - checker_.check_sign(); - Handler::on_minus(); - } - - FMT_CONSTEXPR void on_space() { - checker_.check_sign(); - Handler::on_space(); - } - - FMT_CONSTEXPR void on_hash() { - checker_.require_numeric_argument(); - Handler::on_hash(); - } - - FMT_CONSTEXPR void on_zero() { - checker_.require_numeric_argument(); - Handler::on_zero(); - } - - FMT_CONSTEXPR void end_precision() { checker_.check_precision(); } -}; - -template <template <typename> class Handler, typename FormatArg, - typename ErrorHandler> -FMT_CONSTEXPR int get_dynamic_spec(FormatArg arg, ErrorHandler eh) { - unsigned long long value = visit_format_arg(Handler<ErrorHandler>(eh), arg); - if (value > to_unsigned(max_value<int>())) eh.on_error("number is too big"); - return static_cast<int>(value); -} - -struct auto_id {}; - + + FMT_CONSTEXPR void on_align(align_t align) { + if (align == align::numeric) checker_.require_numeric_argument(); + Handler::on_align(align); + } + + FMT_CONSTEXPR void on_plus() { + checker_.check_sign(); + Handler::on_plus(); + } + + FMT_CONSTEXPR void on_minus() { + checker_.check_sign(); + Handler::on_minus(); + } + + FMT_CONSTEXPR void on_space() { + checker_.check_sign(); + Handler::on_space(); + } + + FMT_CONSTEXPR void on_hash() { + checker_.require_numeric_argument(); + Handler::on_hash(); + } + + FMT_CONSTEXPR void on_zero() { + checker_.require_numeric_argument(); + Handler::on_zero(); + } + + FMT_CONSTEXPR void end_precision() { checker_.check_precision(); } +}; + +template <template <typename> class Handler, typename FormatArg, + typename ErrorHandler> +FMT_CONSTEXPR int get_dynamic_spec(FormatArg arg, ErrorHandler eh) { + unsigned long long value = visit_format_arg(Handler<ErrorHandler>(eh), arg); + if (value > to_unsigned(max_value<int>())) eh.on_error("number is too big"); + return static_cast<int>(value); +} + +struct auto_id {}; + template <typename Context, typename ID> FMT_CONSTEXPR typename Context::format_arg get_arg(Context& ctx, ID id) { - auto arg = ctx.arg(id); + auto arg = ctx.arg(id); if (!arg) ctx.on_error("argument not found"); - return arg; -} - -// The standard format specifier handler with checking. -template <typename ParseContext, typename Context> -class specs_handler : public specs_setter<typename Context::char_type> { - public: - using char_type = typename Context::char_type; - - FMT_CONSTEXPR specs_handler(basic_format_specs<char_type>& specs, - ParseContext& parse_ctx, Context& ctx) - : specs_setter<char_type>(specs), - parse_context_(parse_ctx), - context_(ctx) {} - - template <typename Id> FMT_CONSTEXPR void on_dynamic_width(Id arg_id) { - this->specs_.width = get_dynamic_spec<width_checker>( - get_arg(arg_id), context_.error_handler()); - } - - template <typename Id> FMT_CONSTEXPR void on_dynamic_precision(Id arg_id) { - this->specs_.precision = get_dynamic_spec<precision_checker>( - get_arg(arg_id), context_.error_handler()); - } - - void on_error(const char* message) { context_.on_error(message); } - - private: - // This is only needed for compatibility with gcc 4.4. - using format_arg = typename Context::format_arg; - - FMT_CONSTEXPR format_arg get_arg(auto_id) { + return arg; +} + +// The standard format specifier handler with checking. +template <typename ParseContext, typename Context> +class specs_handler : public specs_setter<typename Context::char_type> { + public: + using char_type = typename Context::char_type; + + FMT_CONSTEXPR specs_handler(basic_format_specs<char_type>& specs, + ParseContext& parse_ctx, Context& ctx) + : specs_setter<char_type>(specs), + parse_context_(parse_ctx), + context_(ctx) {} + + template <typename Id> FMT_CONSTEXPR void on_dynamic_width(Id arg_id) { + this->specs_.width = get_dynamic_spec<width_checker>( + get_arg(arg_id), context_.error_handler()); + } + + template <typename Id> FMT_CONSTEXPR void on_dynamic_precision(Id arg_id) { + this->specs_.precision = get_dynamic_spec<precision_checker>( + get_arg(arg_id), context_.error_handler()); + } + + void on_error(const char* message) { context_.on_error(message); } + + private: + // This is only needed for compatibility with gcc 4.4. + using format_arg = typename Context::format_arg; + + FMT_CONSTEXPR format_arg get_arg(auto_id) { return detail::get_arg(context_, parse_context_.next_arg_id()); - } - - FMT_CONSTEXPR format_arg get_arg(int arg_id) { - parse_context_.check_arg_id(arg_id); + } + + FMT_CONSTEXPR format_arg get_arg(int arg_id) { + parse_context_.check_arg_id(arg_id); return detail::get_arg(context_, arg_id); - } - - FMT_CONSTEXPR format_arg get_arg(basic_string_view<char_type> arg_id) { - parse_context_.check_arg_id(arg_id); + } + + FMT_CONSTEXPR format_arg get_arg(basic_string_view<char_type> arg_id) { + parse_context_.check_arg_id(arg_id); return detail::get_arg(context_, arg_id); - } - - ParseContext& parse_context_; - Context& context_; -}; - -enum class arg_id_kind { none, index, name }; - -// An argument reference. -template <typename Char> struct arg_ref { - FMT_CONSTEXPR arg_ref() : kind(arg_id_kind::none), val() {} - - FMT_CONSTEXPR explicit arg_ref(int index) - : kind(arg_id_kind::index), val(index) {} - FMT_CONSTEXPR explicit arg_ref(basic_string_view<Char> name) - : kind(arg_id_kind::name), val(name) {} - - FMT_CONSTEXPR arg_ref& operator=(int idx) { - kind = arg_id_kind::index; - val.index = idx; - return *this; - } - - arg_id_kind kind; - union value { - FMT_CONSTEXPR value(int id = 0) : index{id} {} - FMT_CONSTEXPR value(basic_string_view<Char> n) : name(n) {} - - int index; - basic_string_view<Char> name; - } val; -}; - -// Format specifiers with width and precision resolved at formatting rather -// than parsing time to allow re-using the same parsed specifiers with -// different sets of arguments (precompilation of format strings). -template <typename Char> -struct dynamic_format_specs : basic_format_specs<Char> { - arg_ref<Char> width_ref; - arg_ref<Char> precision_ref; -}; - -// Format spec handler that saves references to arguments representing dynamic -// width and precision to be resolved at formatting time. -template <typename ParseContext> -class dynamic_specs_handler - : public specs_setter<typename ParseContext::char_type> { - public: - using char_type = typename ParseContext::char_type; - - FMT_CONSTEXPR dynamic_specs_handler(dynamic_format_specs<char_type>& specs, - ParseContext& ctx) - : specs_setter<char_type>(specs), specs_(specs), context_(ctx) {} - - FMT_CONSTEXPR dynamic_specs_handler(const dynamic_specs_handler& other) - : specs_setter<char_type>(other), - specs_(other.specs_), - context_(other.context_) {} - - template <typename Id> FMT_CONSTEXPR void on_dynamic_width(Id arg_id) { - specs_.width_ref = make_arg_ref(arg_id); - } - - template <typename Id> FMT_CONSTEXPR void on_dynamic_precision(Id arg_id) { - specs_.precision_ref = make_arg_ref(arg_id); - } - - FMT_CONSTEXPR void on_error(const char* message) { - context_.on_error(message); - } - - private: - using arg_ref_type = arg_ref<char_type>; - - FMT_CONSTEXPR arg_ref_type make_arg_ref(int arg_id) { - context_.check_arg_id(arg_id); - return arg_ref_type(arg_id); - } - - FMT_CONSTEXPR arg_ref_type make_arg_ref(auto_id) { - return arg_ref_type(context_.next_arg_id()); - } - - FMT_CONSTEXPR arg_ref_type make_arg_ref(basic_string_view<char_type> arg_id) { - context_.check_arg_id(arg_id); - basic_string_view<char_type> format_str( - context_.begin(), to_unsigned(context_.end() - context_.begin())); - return arg_ref_type(arg_id); - } - - dynamic_format_specs<char_type>& specs_; - ParseContext& context_; -}; - -template <typename Char, typename IDHandler> -FMT_CONSTEXPR const Char* parse_arg_id(const Char* begin, const Char* end, - IDHandler&& handler) { - FMT_ASSERT(begin != end, ""); - Char c = *begin; - if (c == '}' || c == ':') { - handler(); - return begin; - } - if (c >= '0' && c <= '9') { - int index = 0; - if (c != '0') - index = parse_nonnegative_int(begin, end, handler); - else - ++begin; - if (begin == end || (*begin != '}' && *begin != ':')) - handler.on_error("invalid format string"); - else - handler(index); - return begin; - } - if (!is_name_start(c)) { - handler.on_error("invalid format string"); - return begin; - } - auto it = begin; - do { - ++it; - } while (it != end && (is_name_start(c = *it) || ('0' <= c && c <= '9'))); - handler(basic_string_view<Char>(begin, to_unsigned(it - begin))); - return it; -} - -// Adapts SpecHandler to IDHandler API for dynamic width. -template <typename SpecHandler, typename Char> struct width_adapter { - explicit FMT_CONSTEXPR width_adapter(SpecHandler& h) : handler(h) {} - - FMT_CONSTEXPR void operator()() { handler.on_dynamic_width(auto_id()); } - FMT_CONSTEXPR void operator()(int id) { handler.on_dynamic_width(id); } - FMT_CONSTEXPR void operator()(basic_string_view<Char> id) { - handler.on_dynamic_width(id); - } - - FMT_CONSTEXPR void on_error(const char* message) { - handler.on_error(message); - } - - SpecHandler& handler; -}; - -// Adapts SpecHandler to IDHandler API for dynamic precision. -template <typename SpecHandler, typename Char> struct precision_adapter { - explicit FMT_CONSTEXPR precision_adapter(SpecHandler& h) : handler(h) {} - - FMT_CONSTEXPR void operator()() { handler.on_dynamic_precision(auto_id()); } - FMT_CONSTEXPR void operator()(int id) { handler.on_dynamic_precision(id); } - FMT_CONSTEXPR void operator()(basic_string_view<Char> id) { - handler.on_dynamic_precision(id); - } - - FMT_CONSTEXPR void on_error(const char* message) { - handler.on_error(message); - } - - SpecHandler& handler; -}; - -template <typename Char> + } + + ParseContext& parse_context_; + Context& context_; +}; + +enum class arg_id_kind { none, index, name }; + +// An argument reference. +template <typename Char> struct arg_ref { + FMT_CONSTEXPR arg_ref() : kind(arg_id_kind::none), val() {} + + FMT_CONSTEXPR explicit arg_ref(int index) + : kind(arg_id_kind::index), val(index) {} + FMT_CONSTEXPR explicit arg_ref(basic_string_view<Char> name) + : kind(arg_id_kind::name), val(name) {} + + FMT_CONSTEXPR arg_ref& operator=(int idx) { + kind = arg_id_kind::index; + val.index = idx; + return *this; + } + + arg_id_kind kind; + union value { + FMT_CONSTEXPR value(int id = 0) : index{id} {} + FMT_CONSTEXPR value(basic_string_view<Char> n) : name(n) {} + + int index; + basic_string_view<Char> name; + } val; +}; + +// Format specifiers with width and precision resolved at formatting rather +// than parsing time to allow re-using the same parsed specifiers with +// different sets of arguments (precompilation of format strings). +template <typename Char> +struct dynamic_format_specs : basic_format_specs<Char> { + arg_ref<Char> width_ref; + arg_ref<Char> precision_ref; +}; + +// Format spec handler that saves references to arguments representing dynamic +// width and precision to be resolved at formatting time. +template <typename ParseContext> +class dynamic_specs_handler + : public specs_setter<typename ParseContext::char_type> { + public: + using char_type = typename ParseContext::char_type; + + FMT_CONSTEXPR dynamic_specs_handler(dynamic_format_specs<char_type>& specs, + ParseContext& ctx) + : specs_setter<char_type>(specs), specs_(specs), context_(ctx) {} + + FMT_CONSTEXPR dynamic_specs_handler(const dynamic_specs_handler& other) + : specs_setter<char_type>(other), + specs_(other.specs_), + context_(other.context_) {} + + template <typename Id> FMT_CONSTEXPR void on_dynamic_width(Id arg_id) { + specs_.width_ref = make_arg_ref(arg_id); + } + + template <typename Id> FMT_CONSTEXPR void on_dynamic_precision(Id arg_id) { + specs_.precision_ref = make_arg_ref(arg_id); + } + + FMT_CONSTEXPR void on_error(const char* message) { + context_.on_error(message); + } + + private: + using arg_ref_type = arg_ref<char_type>; + + FMT_CONSTEXPR arg_ref_type make_arg_ref(int arg_id) { + context_.check_arg_id(arg_id); + return arg_ref_type(arg_id); + } + + FMT_CONSTEXPR arg_ref_type make_arg_ref(auto_id) { + return arg_ref_type(context_.next_arg_id()); + } + + FMT_CONSTEXPR arg_ref_type make_arg_ref(basic_string_view<char_type> arg_id) { + context_.check_arg_id(arg_id); + basic_string_view<char_type> format_str( + context_.begin(), to_unsigned(context_.end() - context_.begin())); + return arg_ref_type(arg_id); + } + + dynamic_format_specs<char_type>& specs_; + ParseContext& context_; +}; + +template <typename Char, typename IDHandler> +FMT_CONSTEXPR const Char* parse_arg_id(const Char* begin, const Char* end, + IDHandler&& handler) { + FMT_ASSERT(begin != end, ""); + Char c = *begin; + if (c == '}' || c == ':') { + handler(); + return begin; + } + if (c >= '0' && c <= '9') { + int index = 0; + if (c != '0') + index = parse_nonnegative_int(begin, end, handler); + else + ++begin; + if (begin == end || (*begin != '}' && *begin != ':')) + handler.on_error("invalid format string"); + else + handler(index); + return begin; + } + if (!is_name_start(c)) { + handler.on_error("invalid format string"); + return begin; + } + auto it = begin; + do { + ++it; + } while (it != end && (is_name_start(c = *it) || ('0' <= c && c <= '9'))); + handler(basic_string_view<Char>(begin, to_unsigned(it - begin))); + return it; +} + +// Adapts SpecHandler to IDHandler API for dynamic width. +template <typename SpecHandler, typename Char> struct width_adapter { + explicit FMT_CONSTEXPR width_adapter(SpecHandler& h) : handler(h) {} + + FMT_CONSTEXPR void operator()() { handler.on_dynamic_width(auto_id()); } + FMT_CONSTEXPR void operator()(int id) { handler.on_dynamic_width(id); } + FMT_CONSTEXPR void operator()(basic_string_view<Char> id) { + handler.on_dynamic_width(id); + } + + FMT_CONSTEXPR void on_error(const char* message) { + handler.on_error(message); + } + + SpecHandler& handler; +}; + +// Adapts SpecHandler to IDHandler API for dynamic precision. +template <typename SpecHandler, typename Char> struct precision_adapter { + explicit FMT_CONSTEXPR precision_adapter(SpecHandler& h) : handler(h) {} + + FMT_CONSTEXPR void operator()() { handler.on_dynamic_precision(auto_id()); } + FMT_CONSTEXPR void operator()(int id) { handler.on_dynamic_precision(id); } + FMT_CONSTEXPR void operator()(basic_string_view<Char> id) { + handler.on_dynamic_precision(id); + } + + FMT_CONSTEXPR void on_error(const char* message) { + handler.on_error(message); + } + + SpecHandler& handler; +}; + +template <typename Char> FMT_CONSTEXPR int code_point_length(const Char* begin) { if (const_check(sizeof(Char) != 1)) return 1; constexpr char lengths[] = {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, @@ -2774,8 +2774,8 @@ FMT_CONSTEXPR int code_point_length(const Char* begin) { // iteration can start working on the next character. Neither Clang // nor GCC figure out this reordering on their own. return len + !len; -} - +} + template <typename Char> constexpr bool is_ascii_letter(Char c) { return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'); } @@ -2790,171 +2790,171 @@ constexpr typename std::underlying_type<Char>::type to_ascii(Char value) { return value; } -// Parses fill and alignment. -template <typename Char, typename Handler> -FMT_CONSTEXPR const Char* parse_align(const Char* begin, const Char* end, - Handler&& handler) { - FMT_ASSERT(begin != end, ""); - auto align = align::none; +// Parses fill and alignment. +template <typename Char, typename Handler> +FMT_CONSTEXPR const Char* parse_align(const Char* begin, const Char* end, + Handler&& handler) { + FMT_ASSERT(begin != end, ""); + auto align = align::none; auto p = begin + code_point_length(begin); if (p >= end) p = begin; - for (;;) { + for (;;) { switch (to_ascii(*p)) { - case '<': - align = align::left; - break; - case '>': - align = align::right; - break; + case '<': + align = align::left; + break; + case '>': + align = align::right; + break; #if FMT_DEPRECATED_NUMERIC_ALIGN - case '=': - align = align::numeric; - break; -#endif - case '^': - align = align::center; - break; - } - if (align != align::none) { - if (p != begin) { - auto c = *begin; - if (c == '{') - return handler.on_error("invalid fill character '{'"), begin; - handler.on_fill(basic_string_view<Char>(begin, to_unsigned(p - begin))); - begin = p + 1; - } else - ++begin; - handler.on_align(align); - break; - } else if (p == begin) { - break; - } - p = begin; - } - return begin; -} - -template <typename Char, typename Handler> -FMT_CONSTEXPR const Char* parse_width(const Char* begin, const Char* end, - Handler&& handler) { - FMT_ASSERT(begin != end, ""); - if ('0' <= *begin && *begin <= '9') { - handler.on_width(parse_nonnegative_int(begin, end, handler)); - } else if (*begin == '{') { - ++begin; - if (begin != end) - begin = parse_arg_id(begin, end, width_adapter<Handler, Char>(handler)); - if (begin == end || *begin != '}') - return handler.on_error("invalid format string"), begin; - ++begin; - } - return begin; -} - -template <typename Char, typename Handler> -FMT_CONSTEXPR const Char* parse_precision(const Char* begin, const Char* end, - Handler&& handler) { - ++begin; - auto c = begin != end ? *begin : Char(); - if ('0' <= c && c <= '9') { - handler.on_precision(parse_nonnegative_int(begin, end, handler)); - } else if (c == '{') { - ++begin; - if (begin != end) { - begin = - parse_arg_id(begin, end, precision_adapter<Handler, Char>(handler)); - } - if (begin == end || *begin++ != '}') - return handler.on_error("invalid format string"), begin; - } else { - return handler.on_error("missing precision specifier"), begin; - } - handler.end_precision(); - return begin; -} - -// Parses standard format specifiers and sends notifications about parsed -// components to handler. -template <typename Char, typename SpecHandler> -FMT_CONSTEXPR const Char* parse_format_specs(const Char* begin, const Char* end, - SpecHandler&& handler) { + case '=': + align = align::numeric; + break; +#endif + case '^': + align = align::center; + break; + } + if (align != align::none) { + if (p != begin) { + auto c = *begin; + if (c == '{') + return handler.on_error("invalid fill character '{'"), begin; + handler.on_fill(basic_string_view<Char>(begin, to_unsigned(p - begin))); + begin = p + 1; + } else + ++begin; + handler.on_align(align); + break; + } else if (p == begin) { + break; + } + p = begin; + } + return begin; +} + +template <typename Char, typename Handler> +FMT_CONSTEXPR const Char* parse_width(const Char* begin, const Char* end, + Handler&& handler) { + FMT_ASSERT(begin != end, ""); + if ('0' <= *begin && *begin <= '9') { + handler.on_width(parse_nonnegative_int(begin, end, handler)); + } else if (*begin == '{') { + ++begin; + if (begin != end) + begin = parse_arg_id(begin, end, width_adapter<Handler, Char>(handler)); + if (begin == end || *begin != '}') + return handler.on_error("invalid format string"), begin; + ++begin; + } + return begin; +} + +template <typename Char, typename Handler> +FMT_CONSTEXPR const Char* parse_precision(const Char* begin, const Char* end, + Handler&& handler) { + ++begin; + auto c = begin != end ? *begin : Char(); + if ('0' <= c && c <= '9') { + handler.on_precision(parse_nonnegative_int(begin, end, handler)); + } else if (c == '{') { + ++begin; + if (begin != end) { + begin = + parse_arg_id(begin, end, precision_adapter<Handler, Char>(handler)); + } + if (begin == end || *begin++ != '}') + return handler.on_error("invalid format string"), begin; + } else { + return handler.on_error("missing precision specifier"), begin; + } + handler.end_precision(); + return begin; +} + +// Parses standard format specifiers and sends notifications about parsed +// components to handler. +template <typename Char, typename SpecHandler> +FMT_CONSTEXPR const Char* parse_format_specs(const Char* begin, const Char* end, + SpecHandler&& handler) { if (begin == end) return begin; - - begin = parse_align(begin, end, handler); - if (begin == end) return begin; - - // Parse sign. + + begin = parse_align(begin, end, handler); + if (begin == end) return begin; + + // Parse sign. switch (to_ascii(*begin)) { - case '+': - handler.on_plus(); - ++begin; - break; - case '-': - handler.on_minus(); - ++begin; - break; - case ' ': - handler.on_space(); - ++begin; - break; - } - if (begin == end) return begin; - - if (*begin == '#') { - handler.on_hash(); - if (++begin == end) return begin; - } - - // Parse zero flag. - if (*begin == '0') { - handler.on_zero(); - if (++begin == end) return begin; - } - - begin = parse_width(begin, end, handler); - if (begin == end) return begin; - - // Parse precision. - if (*begin == '.') { - begin = parse_precision(begin, end, handler); - } - - // Parse type. - if (begin != end && *begin != '}') handler.on_type(*begin++); - return begin; -} - -// Return the result via the out param to workaround gcc bug 77539. -template <bool IS_CONSTEXPR, typename T, typename Ptr = const T*> -FMT_CONSTEXPR bool find(Ptr first, Ptr last, T value, Ptr& out) { - for (out = first; out != last; ++out) { - if (*out == value) return true; - } - return false; -} - -template <> -inline bool find<false, char>(const char* first, const char* last, char value, - const char*& out) { - out = static_cast<const char*>( + case '+': + handler.on_plus(); + ++begin; + break; + case '-': + handler.on_minus(); + ++begin; + break; + case ' ': + handler.on_space(); + ++begin; + break; + } + if (begin == end) return begin; + + if (*begin == '#') { + handler.on_hash(); + if (++begin == end) return begin; + } + + // Parse zero flag. + if (*begin == '0') { + handler.on_zero(); + if (++begin == end) return begin; + } + + begin = parse_width(begin, end, handler); + if (begin == end) return begin; + + // Parse precision. + if (*begin == '.') { + begin = parse_precision(begin, end, handler); + } + + // Parse type. + if (begin != end && *begin != '}') handler.on_type(*begin++); + return begin; +} + +// Return the result via the out param to workaround gcc bug 77539. +template <bool IS_CONSTEXPR, typename T, typename Ptr = const T*> +FMT_CONSTEXPR bool find(Ptr first, Ptr last, T value, Ptr& out) { + for (out = first; out != last; ++out) { + if (*out == value) return true; + } + return false; +} + +template <> +inline bool find<false, char>(const char* first, const char* last, char value, + const char*& out) { + out = static_cast<const char*>( std::memchr(first, value, detail::to_unsigned(last - first))); - return out != nullptr; -} - -template <typename Handler, typename Char> struct id_adapter { + return out != nullptr; +} + +template <typename Handler, typename Char> struct id_adapter { Handler& handler; int arg_id; FMT_CONSTEXPR void operator()() { arg_id = handler.on_arg_id(); } FMT_CONSTEXPR void operator()(int id) { arg_id = handler.on_arg_id(id); } - FMT_CONSTEXPR void operator()(basic_string_view<Char> id) { + FMT_CONSTEXPR void operator()(basic_string_view<Char> id) { arg_id = handler.on_arg_id(id); - } - FMT_CONSTEXPR void on_error(const char* message) { - handler.on_error(message); - } -}; - + } + FMT_CONSTEXPR void on_error(const char* message) { + handler.on_error(message); + } +}; + template <typename Char, typename Handler> FMT_CONSTEXPR const Char* parse_replacement_field(const Char* begin, const Char* end, @@ -2982,7 +2982,7 @@ FMT_CONSTEXPR const Char* parse_replacement_field(const Char* begin, return begin + 1; } -template <bool IS_CONSTEXPR, typename Char, typename Handler> +template <bool IS_CONSTEXPR, typename Char, typename Handler> FMT_CONSTEXPR_DECL FMT_INLINE void parse_format_string( basic_string_view<Char> format_str, Handler&& handler) { auto begin = format_str.data(); @@ -3008,45 +3008,45 @@ FMT_CONSTEXPR_DECL FMT_INLINE void parse_format_string( struct writer { FMT_CONSTEXPR void operator()(const Char* pbegin, const Char* pend) { if (pbegin == pend) return; - for (;;) { - const Char* p = nullptr; + for (;;) { + const Char* p = nullptr; if (!find<IS_CONSTEXPR>(pbegin, pend, '}', p)) return handler_.on_text(pbegin, pend); - ++p; + ++p; if (p == pend || *p != '}') - return handler_.on_error("unmatched '}' in format string"); + return handler_.on_error("unmatched '}' in format string"); handler_.on_text(pbegin, p); pbegin = p + 1; - } - } - Handler& handler_; - } write{handler}; - while (begin != end) { - // Doing two passes with memchr (one for '{' and another for '}') is up to - // 2.5x faster than the naive one-pass implementation on big format strings. - const Char* p = begin; - if (*begin != '{' && !find<IS_CONSTEXPR>(begin + 1, end, '{', p)) - return write(begin, end); - write(begin, p); + } + } + Handler& handler_; + } write{handler}; + while (begin != end) { + // Doing two passes with memchr (one for '{' and another for '}') is up to + // 2.5x faster than the naive one-pass implementation on big format strings. + const Char* p = begin; + if (*begin != '{' && !find<IS_CONSTEXPR>(begin + 1, end, '{', p)) + return write(begin, end); + write(begin, p); begin = parse_replacement_field(p, end, handler); - } -} - -template <typename T, typename ParseContext> -FMT_CONSTEXPR const typename ParseContext::char_type* parse_format_specs( - ParseContext& ctx) { - using char_type = typename ParseContext::char_type; - using context = buffer_context<char_type>; - using mapped_type = + } +} + +template <typename T, typename ParseContext> +FMT_CONSTEXPR const typename ParseContext::char_type* parse_format_specs( + ParseContext& ctx) { + using char_type = typename ParseContext::char_type; + using context = buffer_context<char_type>; + using mapped_type = conditional_t<detail::mapped_type_constant<T, context>::value != - type::custom_type, - decltype(arg_mapper<context>().map(std::declval<T>())), T>; - auto f = conditional_t<has_formatter<mapped_type, context>::value, - formatter<mapped_type, char_type>, + type::custom_type, + decltype(arg_mapper<context>().map(std::declval<T>())), T>; + auto f = conditional_t<has_formatter<mapped_type, context>::value, + formatter<mapped_type, char_type>, detail::fallback_formatter<T, char_type>>(); - return f.parse(ctx); -} - + return f.parse(ctx); +} + template <typename OutputIt, typename Char, typename Context> struct format_handler : detail::error_handler { basic_format_parse_context<Char> parse_context; @@ -3136,46 +3136,46 @@ class compile_parse_context using base::check_arg_id; }; -template <typename Char, typename ErrorHandler, typename... Args> -class format_string_checker { - public: - explicit FMT_CONSTEXPR format_string_checker( - basic_string_view<Char> format_str, ErrorHandler eh) +template <typename Char, typename ErrorHandler, typename... Args> +class format_string_checker { + public: + explicit FMT_CONSTEXPR format_string_checker( + basic_string_view<Char> format_str, ErrorHandler eh) : context_(format_str, num_args, eh), - parse_funcs_{&parse_format_specs<Args, parse_context_type>...} {} - - FMT_CONSTEXPR void on_text(const Char*, const Char*) {} - + parse_funcs_{&parse_format_specs<Args, parse_context_type>...} {} + + FMT_CONSTEXPR void on_text(const Char*, const Char*) {} + FMT_CONSTEXPR int on_arg_id() { return context_.next_arg_id(); } FMT_CONSTEXPR int on_arg_id(int id) { return context_.check_arg_id(id), id; } FMT_CONSTEXPR int on_arg_id(basic_string_view<Char>) { - on_error("compile-time checks don't support named arguments"); + on_error("compile-time checks don't support named arguments"); return 0; - } - + } + FMT_CONSTEXPR void on_replacement_field(int, const Char*) {} - + FMT_CONSTEXPR const Char* on_format_specs(int id, const Char* begin, const Char*) { - advance_to(context_, begin); + advance_to(context_, begin); return id < num_args ? parse_funcs_[id](context_) : begin; - } - - FMT_CONSTEXPR void on_error(const char* message) { - context_.on_error(message); - } - - private: + } + + FMT_CONSTEXPR void on_error(const char* message) { + context_.on_error(message); + } + + private: using parse_context_type = compile_parse_context<Char, ErrorHandler>; - enum { num_args = sizeof...(Args) }; - - // Format specifier parsing function. - using parse_func = const Char* (*)(parse_context_type&); - - parse_context_type context_; - parse_func parse_funcs_[num_args > 0 ? num_args : 1]; -}; - + enum { num_args = sizeof...(Args) }; + + // Format specifier parsing function. + using parse_func = const Char* (*)(parse_context_type&); + + parse_context_type context_; + parse_func parse_funcs_[num_args > 0 ? num_args : 1]; +}; + // Converts string literals to basic_string_view. template <typename Char, size_t N> FMT_CONSTEXPR basic_string_view<Char> compile_string_to_view( @@ -3184,8 +3184,8 @@ FMT_CONSTEXPR basic_string_view<Char> compile_string_to_view( // with raw character array (i.e. not defined as a string). return {s, N - ((std::char_traits<Char>::to_int_type(s[N - 1]) == 0) ? 1 : 0)}; -} - +} + // Converts string_view to basic_string_view. template <typename Char> FMT_CONSTEXPR basic_string_view<Char> compile_string_to_view( @@ -3218,142 +3218,142 @@ FMT_CONSTEXPR basic_string_view<Char> compile_string_to_view( */ #define FMT_STRING(s) FMT_STRING_IMPL(s, fmt::compile_string) -template <typename... Args, typename S, - enable_if_t<(is_compile_string<S>::value), int>> -void check_format_string(S format_str) { +template <typename... Args, typename S, + enable_if_t<(is_compile_string<S>::value), int>> +void check_format_string(S format_str) { FMT_CONSTEXPR_DECL auto s = to_string_view(format_str); using checker = format_string_checker<typename S::char_type, error_handler, remove_cvref_t<Args>...>; FMT_CONSTEXPR_DECL bool invalid_format = (parse_format_string<true>(s, checker(s, {})), true); - (void)invalid_format; -} - -template <template <typename> class Handler, typename Context> -void handle_dynamic_spec(int& value, arg_ref<typename Context::char_type> ref, - Context& ctx) { - switch (ref.kind) { - case arg_id_kind::none: - break; - case arg_id_kind::index: + (void)invalid_format; +} + +template <template <typename> class Handler, typename Context> +void handle_dynamic_spec(int& value, arg_ref<typename Context::char_type> ref, + Context& ctx) { + switch (ref.kind) { + case arg_id_kind::none: + break; + case arg_id_kind::index: value = detail::get_dynamic_spec<Handler>(ctx.arg(ref.val.index), ctx.error_handler()); - break; - case arg_id_kind::name: + break; + case arg_id_kind::name: value = detail::get_dynamic_spec<Handler>(ctx.arg(ref.val.name), ctx.error_handler()); - break; - } -} - + break; + } +} + using format_func = void (*)(detail::buffer<char>&, int, string_view); - -FMT_API void format_error_code(buffer<char>& out, int error_code, - string_view message) FMT_NOEXCEPT; - -FMT_API void report_error(format_func func, int error_code, - string_view message) FMT_NOEXCEPT; + +FMT_API void format_error_code(buffer<char>& out, int error_code, + string_view message) FMT_NOEXCEPT; + +FMT_API void report_error(format_func func, int error_code, + string_view message) FMT_NOEXCEPT; } // namespace detail - + template <typename OutputIt, typename Char> using arg_formatter FMT_DEPRECATED_ALIAS = detail::arg_formatter<OutputIt, Char>; - -/** - An error returned by an operating system or a language runtime, - for example a file opening error. -*/ -FMT_CLASS_API -class FMT_API system_error : public std::runtime_error { - private: - void init(int err_code, string_view format_str, format_args args); - - protected: - int error_code_; - - system_error() : std::runtime_error(""), error_code_(0) {} - - public: - /** - \rst - Constructs a :class:`fmt::system_error` object with a description - formatted with `fmt::format_system_error`. *message* and additional - arguments passed into the constructor are formatted similarly to - `fmt::format`. - - **Example**:: - - // This throws a system_error with the description - // cannot open file 'madeup': No such file or directory - // or similar (system message may vary). - const char *filename = "madeup"; - std::FILE *file = std::fopen(filename, "r"); - if (!file) - throw fmt::system_error(errno, "cannot open file '{}'", filename); - \endrst - */ - template <typename... Args> - system_error(int error_code, string_view message, const Args&... args) - : std::runtime_error("") { - init(error_code, message, make_format_args(args...)); - } - system_error(const system_error&) = default; - system_error& operator=(const system_error&) = default; - system_error(system_error&&) = default; - system_error& operator=(system_error&&) = default; - ~system_error() FMT_NOEXCEPT FMT_OVERRIDE; - - int error_code() const { return error_code_; } -}; - -/** - \rst - Formats an error returned by an operating system or a language runtime, - for example a file opening error, and writes it to *out* in the following - form: - - .. parsed-literal:: - *<message>*: *<system-message>* - - where *<message>* is the passed message and *<system-message>* is - the system message corresponding to the error code. - *error_code* is a system error code as given by ``errno``. - If *error_code* is not a valid error code such as -1, the system message - may look like "Unknown error -1" and is platform-dependent. - \endrst - */ + +/** + An error returned by an operating system or a language runtime, + for example a file opening error. +*/ +FMT_CLASS_API +class FMT_API system_error : public std::runtime_error { + private: + void init(int err_code, string_view format_str, format_args args); + + protected: + int error_code_; + + system_error() : std::runtime_error(""), error_code_(0) {} + + public: + /** + \rst + Constructs a :class:`fmt::system_error` object with a description + formatted with `fmt::format_system_error`. *message* and additional + arguments passed into the constructor are formatted similarly to + `fmt::format`. + + **Example**:: + + // This throws a system_error with the description + // cannot open file 'madeup': No such file or directory + // or similar (system message may vary). + const char *filename = "madeup"; + std::FILE *file = std::fopen(filename, "r"); + if (!file) + throw fmt::system_error(errno, "cannot open file '{}'", filename); + \endrst + */ + template <typename... Args> + system_error(int error_code, string_view message, const Args&... args) + : std::runtime_error("") { + init(error_code, message, make_format_args(args...)); + } + system_error(const system_error&) = default; + system_error& operator=(const system_error&) = default; + system_error(system_error&&) = default; + system_error& operator=(system_error&&) = default; + ~system_error() FMT_NOEXCEPT FMT_OVERRIDE; + + int error_code() const { return error_code_; } +}; + +/** + \rst + Formats an error returned by an operating system or a language runtime, + for example a file opening error, and writes it to *out* in the following + form: + + .. parsed-literal:: + *<message>*: *<system-message>* + + where *<message>* is the passed message and *<system-message>* is + the system message corresponding to the error code. + *error_code* is a system error code as given by ``errno``. + If *error_code* is not a valid error code such as -1, the system message + may look like "Unknown error -1" and is platform-dependent. + \endrst + */ FMT_API void format_system_error(detail::buffer<char>& out, int error_code, - string_view message) FMT_NOEXCEPT; - -// Reports a system error without throwing an exception. -// Can be used to report errors from destructors. -FMT_API void report_system_error(int error_code, - string_view message) FMT_NOEXCEPT; - -/** Fast integer formatter. */ -class format_int { - private: - // Buffer should be large enough to hold all digits (digits10 + 1), - // a sign and a null character. - enum { buffer_size = std::numeric_limits<unsigned long long>::digits10 + 3 }; - mutable char buffer_[buffer_size]; - char* str_; - + string_view message) FMT_NOEXCEPT; + +// Reports a system error without throwing an exception. +// Can be used to report errors from destructors. +FMT_API void report_system_error(int error_code, + string_view message) FMT_NOEXCEPT; + +/** Fast integer formatter. */ +class format_int { + private: + // Buffer should be large enough to hold all digits (digits10 + 1), + // a sign and a null character. + enum { buffer_size = std::numeric_limits<unsigned long long>::digits10 + 3 }; + mutable char buffer_[buffer_size]; + char* str_; + template <typename UInt> char* format_unsigned(UInt value) { auto n = static_cast<detail::uint32_or_64_or_128_t<UInt>>(value); return detail::format_decimal(buffer_, n, buffer_size - 1).begin; - } - + } + template <typename Int> char* format_signed(Int value) { auto abs_value = static_cast<detail::uint32_or_64_or_128_t<Int>>(value); - bool negative = value < 0; - if (negative) abs_value = 0 - abs_value; + bool negative = value < 0; + if (negative) abs_value = 0 - abs_value; auto begin = format_unsigned(abs_value); if (negative) *--begin = '-'; return begin; - } - - public: + } + + public: explicit format_int(int value) : str_(format_signed(value)) {} explicit format_int(long value) : str_(format_signed(value)) {} explicit format_int(long long value) : str_(format_signed(value)) {} @@ -3361,57 +3361,57 @@ class format_int { explicit format_int(unsigned long value) : str_(format_unsigned(value)) {} explicit format_int(unsigned long long value) : str_(format_unsigned(value)) {} - - /** Returns the number of characters written to the output buffer. */ + + /** Returns the number of characters written to the output buffer. */ size_t size() const { return detail::to_unsigned(buffer_ - str_ + buffer_size - 1); - } - - /** - Returns a pointer to the output buffer content. No terminating null - character is appended. - */ - const char* data() const { return str_; } - - /** - Returns a pointer to the output buffer content with terminating null - character appended. - */ - const char* c_str() const { - buffer_[buffer_size - 1] = '\0'; - return str_; - } - - /** - \rst - Returns the content of the output buffer as an ``std::string``. - \endrst - */ - std::string str() const { return std::string(str_, size()); } -}; - + } + + /** + Returns a pointer to the output buffer content. No terminating null + character is appended. + */ + const char* data() const { return str_; } + + /** + Returns a pointer to the output buffer content with terminating null + character appended. + */ + const char* c_str() const { + buffer_[buffer_size - 1] = '\0'; + return str_; + } + + /** + \rst + Returns the content of the output buffer as an ``std::string``. + \endrst + */ + std::string str() const { return std::string(str_, size()); } +}; + // A formatter specialization for the core types corresponding to detail::type -// constants. -template <typename T, typename Char> -struct formatter<T, Char, +// constants. +template <typename T, typename Char> +struct formatter<T, Char, enable_if_t<detail::type_constant<T, Char>::value != detail::type::custom_type>> { - FMT_CONSTEXPR formatter() = default; - - // Parses format specifiers stopping either at the end of the range or at the - // terminating '}'. - template <typename ParseContext> - FMT_CONSTEXPR auto parse(ParseContext& ctx) -> decltype(ctx.begin()) { + FMT_CONSTEXPR formatter() = default; + + // Parses format specifiers stopping either at the end of the range or at the + // terminating '}'. + template <typename ParseContext> + FMT_CONSTEXPR auto parse(ParseContext& ctx) -> decltype(ctx.begin()) { using handler_type = detail::dynamic_specs_handler<ParseContext>; auto type = detail::type_constant<T, Char>::value; detail::specs_checker<handler_type> handler(handler_type(specs_, ctx), type); - auto it = parse_format_specs(ctx.begin(), ctx.end(), handler); - auto eh = ctx.error_handler(); - switch (type) { + auto it = parse_format_specs(ctx.begin(), ctx.end(), handler); + auto eh = ctx.error_handler(); + switch (type) { case detail::type::none_type: - FMT_ASSERT(false, "invalid argument type"); - break; + FMT_ASSERT(false, "invalid argument type"); + break; case detail::type::int_type: case detail::type::uint_type: case detail::type::long_long_type: @@ -3419,320 +3419,320 @@ struct formatter<T, Char, case detail::type::int128_type: case detail::type::uint128_type: case detail::type::bool_type: - handle_int_type_spec(specs_.type, + handle_int_type_spec(specs_.type, detail::int_type_checker<decltype(eh)>(eh)); - break; + break; case detail::type::char_type: - handle_char_specs( + handle_char_specs( &specs_, detail::char_specs_checker<decltype(eh)>(specs_.type, eh)); - break; + break; case detail::type::float_type: if (detail::const_check(FMT_USE_FLOAT)) detail::parse_float_type_spec(specs_, eh); else - FMT_ASSERT(false, "float support disabled"); - break; + FMT_ASSERT(false, "float support disabled"); + break; case detail::type::double_type: if (detail::const_check(FMT_USE_DOUBLE)) detail::parse_float_type_spec(specs_, eh); else - FMT_ASSERT(false, "double support disabled"); - break; + FMT_ASSERT(false, "double support disabled"); + break; case detail::type::long_double_type: if (detail::const_check(FMT_USE_LONG_DOUBLE)) detail::parse_float_type_spec(specs_, eh); else - FMT_ASSERT(false, "long double support disabled"); - break; + FMT_ASSERT(false, "long double support disabled"); + break; case detail::type::cstring_type: detail::handle_cstring_type_spec( specs_.type, detail::cstring_type_checker<decltype(eh)>(eh)); - break; + break; case detail::type::string_type: detail::check_string_type_spec(specs_.type, eh); - break; + break; case detail::type::pointer_type: detail::check_pointer_type_spec(specs_.type, eh); - break; + break; case detail::type::custom_type: - // Custom format specifiers should be checked in parse functions of - // formatter specializations. - break; - } - return it; - } - - template <typename FormatContext> - auto format(const T& val, FormatContext& ctx) -> decltype(ctx.out()) { + // Custom format specifiers should be checked in parse functions of + // formatter specializations. + break; + } + return it; + } + + template <typename FormatContext> + auto format(const T& val, FormatContext& ctx) -> decltype(ctx.out()) { detail::handle_dynamic_spec<detail::width_checker>(specs_.width, specs_.width_ref, ctx); detail::handle_dynamic_spec<detail::precision_checker>( - specs_.precision, specs_.precision_ref, ctx); + specs_.precision, specs_.precision_ref, ctx); using af = detail::arg_formatter<typename FormatContext::iterator, typename FormatContext::char_type>; return visit_format_arg(af(ctx, nullptr, &specs_), detail::make_arg<FormatContext>(val)); - } - - private: + } + + private: detail::dynamic_format_specs<Char> specs_; -}; - -#define FMT_FORMAT_AS(Type, Base) \ - template <typename Char> \ - struct formatter<Type, Char> : formatter<Base, Char> { \ - template <typename FormatContext> \ - auto format(Type const& val, FormatContext& ctx) -> decltype(ctx.out()) { \ - return formatter<Base, Char>::format(val, ctx); \ - } \ - } - -FMT_FORMAT_AS(signed char, int); -FMT_FORMAT_AS(unsigned char, unsigned); -FMT_FORMAT_AS(short, int); -FMT_FORMAT_AS(unsigned short, unsigned); -FMT_FORMAT_AS(long, long long); -FMT_FORMAT_AS(unsigned long, unsigned long long); -FMT_FORMAT_AS(Char*, const Char*); -FMT_FORMAT_AS(std::basic_string<Char>, basic_string_view<Char>); -FMT_FORMAT_AS(std::nullptr_t, const void*); +}; + +#define FMT_FORMAT_AS(Type, Base) \ + template <typename Char> \ + struct formatter<Type, Char> : formatter<Base, Char> { \ + template <typename FormatContext> \ + auto format(Type const& val, FormatContext& ctx) -> decltype(ctx.out()) { \ + return formatter<Base, Char>::format(val, ctx); \ + } \ + } + +FMT_FORMAT_AS(signed char, int); +FMT_FORMAT_AS(unsigned char, unsigned); +FMT_FORMAT_AS(short, int); +FMT_FORMAT_AS(unsigned short, unsigned); +FMT_FORMAT_AS(long, long long); +FMT_FORMAT_AS(unsigned long, unsigned long long); +FMT_FORMAT_AS(Char*, const Char*); +FMT_FORMAT_AS(std::basic_string<Char>, basic_string_view<Char>); +FMT_FORMAT_AS(std::nullptr_t, const void*); FMT_FORMAT_AS(detail::std_string_view<Char>, basic_string_view<Char>); - -template <typename Char> -struct formatter<void*, Char> : formatter<const void*, Char> { - template <typename FormatContext> - auto format(void* val, FormatContext& ctx) -> decltype(ctx.out()) { - return formatter<const void*, Char>::format(val, ctx); - } -}; - -template <typename Char, size_t N> -struct formatter<Char[N], Char> : formatter<basic_string_view<Char>, Char> { - template <typename FormatContext> - auto format(const Char* val, FormatContext& ctx) -> decltype(ctx.out()) { - return formatter<basic_string_view<Char>, Char>::format(val, ctx); - } -}; - -// A formatter for types known only at run time such as variant alternatives. -// -// Usage: -// using variant = std::variant<int, std::string>; -// template <> -// struct formatter<variant>: dynamic_formatter<> { + +template <typename Char> +struct formatter<void*, Char> : formatter<const void*, Char> { + template <typename FormatContext> + auto format(void* val, FormatContext& ctx) -> decltype(ctx.out()) { + return formatter<const void*, Char>::format(val, ctx); + } +}; + +template <typename Char, size_t N> +struct formatter<Char[N], Char> : formatter<basic_string_view<Char>, Char> { + template <typename FormatContext> + auto format(const Char* val, FormatContext& ctx) -> decltype(ctx.out()) { + return formatter<basic_string_view<Char>, Char>::format(val, ctx); + } +}; + +// A formatter for types known only at run time such as variant alternatives. +// +// Usage: +// using variant = std::variant<int, std::string>; +// template <> +// struct formatter<variant>: dynamic_formatter<> { // auto format(const variant& v, format_context& ctx) { // return visit([&](const auto& val) { // return dynamic_formatter<>::format(val, ctx); // }, v); -// } -// }; -template <typename Char = char> class dynamic_formatter { - private: +// } +// }; +template <typename Char = char> class dynamic_formatter { + private: struct null_handler : detail::error_handler { - void on_align(align_t) {} - void on_plus() {} - void on_minus() {} - void on_space() {} - void on_hash() {} - }; - - public: - template <typename ParseContext> - auto parse(ParseContext& ctx) -> decltype(ctx.begin()) { - format_str_ = ctx.begin(); - // Checks are deferred to formatting time when the argument type is known. + void on_align(align_t) {} + void on_plus() {} + void on_minus() {} + void on_space() {} + void on_hash() {} + }; + + public: + template <typename ParseContext> + auto parse(ParseContext& ctx) -> decltype(ctx.begin()) { + format_str_ = ctx.begin(); + // Checks are deferred to formatting time when the argument type is known. detail::dynamic_specs_handler<ParseContext> handler(specs_, ctx); - return parse_format_specs(ctx.begin(), ctx.end(), handler); - } - - template <typename T, typename FormatContext> - auto format(const T& val, FormatContext& ctx) -> decltype(ctx.out()) { - handle_specs(ctx); + return parse_format_specs(ctx.begin(), ctx.end(), handler); + } + + template <typename T, typename FormatContext> + auto format(const T& val, FormatContext& ctx) -> decltype(ctx.out()) { + handle_specs(ctx); detail::specs_checker<null_handler> checker( null_handler(), detail::mapped_type_constant<T, FormatContext>::value); - checker.on_align(specs_.align); - switch (specs_.sign) { - case sign::none: - break; - case sign::plus: - checker.on_plus(); - break; - case sign::minus: - checker.on_minus(); - break; - case sign::space: - checker.on_space(); - break; - } - if (specs_.alt) checker.on_hash(); - if (specs_.precision >= 0) checker.end_precision(); + checker.on_align(specs_.align); + switch (specs_.sign) { + case sign::none: + break; + case sign::plus: + checker.on_plus(); + break; + case sign::minus: + checker.on_minus(); + break; + case sign::space: + checker.on_space(); + break; + } + if (specs_.alt) checker.on_hash(); + if (specs_.precision >= 0) checker.end_precision(); using af = detail::arg_formatter<typename FormatContext::iterator, typename FormatContext::char_type>; visit_format_arg(af(ctx, nullptr, &specs_), detail::make_arg<FormatContext>(val)); - return ctx.out(); - } - - private: - template <typename Context> void handle_specs(Context& ctx) { + return ctx.out(); + } + + private: + template <typename Context> void handle_specs(Context& ctx) { detail::handle_dynamic_spec<detail::width_checker>(specs_.width, specs_.width_ref, ctx); detail::handle_dynamic_spec<detail::precision_checker>( - specs_.precision, specs_.precision_ref, ctx); - } - + specs_.precision, specs_.precision_ref, ctx); + } + detail::dynamic_format_specs<Char> specs_; - const Char* format_str_; -}; - -template <typename Char, typename ErrorHandler> -FMT_CONSTEXPR void advance_to( - basic_format_parse_context<Char, ErrorHandler>& ctx, const Char* p) { - ctx.advance_to(ctx.begin() + (p - &*ctx.begin())); -} - + const Char* format_str_; +}; + +template <typename Char, typename ErrorHandler> +FMT_CONSTEXPR void advance_to( + basic_format_parse_context<Char, ErrorHandler>& ctx, const Char* p) { + ctx.advance_to(ctx.begin() + (p - &*ctx.begin())); +} + /** \rst Converts ``p`` to ``const void*`` for pointer formatting. - + **Example**:: - + auto s = fmt::format("{}", fmt::ptr(p)); \endrst */ -template <typename T> inline const void* ptr(const T* p) { return p; } -template <typename T> inline const void* ptr(const std::unique_ptr<T>& p) { - return p.get(); -} -template <typename T> inline const void* ptr(const std::shared_ptr<T>& p) { - return p.get(); -} - -class bytes { - private: - string_view data_; - friend struct formatter<bytes>; - - public: - explicit bytes(string_view data) : data_(data) {} -}; - -template <> struct formatter<bytes> { +template <typename T> inline const void* ptr(const T* p) { return p; } +template <typename T> inline const void* ptr(const std::unique_ptr<T>& p) { + return p.get(); +} +template <typename T> inline const void* ptr(const std::shared_ptr<T>& p) { + return p.get(); +} + +class bytes { + private: + string_view data_; + friend struct formatter<bytes>; + + public: + explicit bytes(string_view data) : data_(data) {} +}; + +template <> struct formatter<bytes> { private: detail::dynamic_format_specs<char> specs_; public: - template <typename ParseContext> - FMT_CONSTEXPR auto parse(ParseContext& ctx) -> decltype(ctx.begin()) { + template <typename ParseContext> + FMT_CONSTEXPR auto parse(ParseContext& ctx) -> decltype(ctx.begin()) { using handler_type = detail::dynamic_specs_handler<ParseContext>; detail::specs_checker<handler_type> handler(handler_type(specs_, ctx), detail::type::string_type); - auto it = parse_format_specs(ctx.begin(), ctx.end(), handler); + auto it = parse_format_specs(ctx.begin(), ctx.end(), handler); detail::check_string_type_spec(specs_.type, ctx.error_handler()); - return it; - } - - template <typename FormatContext> - auto format(bytes b, FormatContext& ctx) -> decltype(ctx.out()) { + return it; + } + + template <typename FormatContext> + auto format(bytes b, FormatContext& ctx) -> decltype(ctx.out()) { detail::handle_dynamic_spec<detail::width_checker>(specs_.width, specs_.width_ref, ctx); detail::handle_dynamic_spec<detail::precision_checker>( - specs_.precision, specs_.precision_ref, ctx); + specs_.precision, specs_.precision_ref, ctx); return detail::write_bytes(ctx.out(), b.data_, specs_); - } -}; - + } +}; + template <typename It, typename Sentinel, typename Char> struct arg_join : detail::view { - It begin; + It begin; Sentinel end; - basic_string_view<Char> sep; - + basic_string_view<Char> sep; + arg_join(It b, Sentinel e, basic_string_view<Char> s) : begin(b), end(e), sep(s) {} -}; - +}; + template <typename It, typename Sentinel, typename Char> struct formatter<arg_join<It, Sentinel, Char>, Char> - : formatter<typename std::iterator_traits<It>::value_type, Char> { - template <typename FormatContext> + : formatter<typename std::iterator_traits<It>::value_type, Char> { + template <typename FormatContext> auto format(const arg_join<It, Sentinel, Char>& value, FormatContext& ctx) - -> decltype(ctx.out()) { - using base = formatter<typename std::iterator_traits<It>::value_type, Char>; - auto it = value.begin; - auto out = ctx.out(); - if (it != value.end) { - out = base::format(*it++, ctx); - while (it != value.end) { - out = std::copy(value.sep.begin(), value.sep.end(), out); - ctx.advance_to(out); - out = base::format(*it++, ctx); - } - } - return out; - } -}; - -/** - Returns an object that formats the iterator range `[begin, end)` with elements - separated by `sep`. - */ + -> decltype(ctx.out()) { + using base = formatter<typename std::iterator_traits<It>::value_type, Char>; + auto it = value.begin; + auto out = ctx.out(); + if (it != value.end) { + out = base::format(*it++, ctx); + while (it != value.end) { + out = std::copy(value.sep.begin(), value.sep.end(), out); + ctx.advance_to(out); + out = base::format(*it++, ctx); + } + } + return out; + } +}; + +/** + Returns an object that formats the iterator range `[begin, end)` with elements + separated by `sep`. + */ template <typename It, typename Sentinel> arg_join<It, Sentinel, char> join(It begin, Sentinel end, string_view sep) { - return {begin, end, sep}; -} - + return {begin, end, sep}; +} + template <typename It, typename Sentinel> arg_join<It, Sentinel, wchar_t> join(It begin, Sentinel end, wstring_view sep) { - return {begin, end, sep}; -} - -/** - \rst - Returns an object that formats `range` with elements separated by `sep`. - - **Example**:: - - std::vector<int> v = {1, 2, 3}; - fmt::print("{}", fmt::join(v, ", ")); - // Output: "1, 2, 3" - - ``fmt::join`` applies passed format specifiers to the range elements:: - - fmt::print("{:02}", fmt::join(v, ", ")); - // Output: "01, 02, 03" - \endrst - */ -template <typename Range> + return {begin, end, sep}; +} + +/** + \rst + Returns an object that formats `range` with elements separated by `sep`. + + **Example**:: + + std::vector<int> v = {1, 2, 3}; + fmt::print("{}", fmt::join(v, ", ")); + // Output: "1, 2, 3" + + ``fmt::join`` applies passed format specifiers to the range elements:: + + fmt::print("{:02}", fmt::join(v, ", ")); + // Output: "01, 02, 03" + \endrst + */ +template <typename Range> arg_join<detail::iterator_t<Range>, detail::sentinel_t<Range>, char> join( Range&& range, string_view sep) { - return join(std::begin(range), std::end(range), sep); -} - -template <typename Range> + return join(std::begin(range), std::end(range), sep); +} + +template <typename Range> arg_join<detail::iterator_t<Range>, detail::sentinel_t<Range>, wchar_t> join( Range&& range, wstring_view sep) { - return join(std::begin(range), std::end(range), sep); -} - -/** - \rst - Converts *value* to ``std::string`` using the default format for type *T*. - - **Example**:: - - #include <fmt/format.h> - - std::string answer = fmt::to_string(42); - \endrst - */ + return join(std::begin(range), std::end(range), sep); +} + +/** + \rst + Converts *value* to ``std::string`` using the default format for type *T*. + + **Example**:: + + #include <fmt/format.h> + + std::string answer = fmt::to_string(42); + \endrst + */ template <typename T, FMT_ENABLE_IF(!std::is_integral<T>::value)> inline std::string to_string(const T& value) { std::string result; detail::write<char>(std::back_inserter(result), value); return result; -} - +} + template <typename T, FMT_ENABLE_IF(std::is_integral<T>::value)> inline std::string to_string(T value) { // The buffer should be large enough to store the number including the sign or @@ -3743,21 +3743,21 @@ inline std::string to_string(T value) { return std::string(begin, detail::write<char>(begin, value)); } -/** - Converts *value* to ``std::wstring`` using the default format for type *T*. - */ -template <typename T> inline std::wstring to_wstring(const T& value) { - return format(L"{}", value); -} - +/** + Converts *value* to ``std::wstring`` using the default format for type *T*. + */ +template <typename T> inline std::wstring to_wstring(const T& value) { + return format(L"{}", value); +} + template <typename Char, size_t SIZE> -std::basic_string<Char> to_string(const basic_memory_buffer<Char, SIZE>& buf) { +std::basic_string<Char> to_string(const basic_memory_buffer<Char, SIZE>& buf) { auto size = buf.size(); detail::assume(size < std::basic_string<Char>().max_size()); return std::basic_string<Char>(buf.data(), size); -} - -template <typename Char> +} + +template <typename Char> void detail::vformat_to( detail::buffer<Char>& buf, basic_string_view<Char> format_str, basic_format_args<buffer_context<type_identity_t<Char>>> args, @@ -3774,8 +3774,8 @@ void detail::vformat_to( format_handler<iterator, Char, buffer_context<Char>> h(out, format_str, args, loc); parse_format_string<false>(format_str, h); -} - +} + #ifndef FMT_HEADER_ONLY extern template void detail::vformat_to(detail::buffer<char>&, string_view, basic_format_args<format_context>, @@ -3805,156 +3805,156 @@ extern template int snprintf_float<long double>(long double value, } // namespace detail #endif -template <typename S, typename Char = char_t<S>, +template <typename S, typename Char = char_t<S>, FMT_ENABLE_IF(detail::is_string<S>::value)> inline void vformat_to( detail::buffer<Char>& buf, const S& format_str, basic_format_args<FMT_BUFFER_CONTEXT(type_identity_t<Char>)> args) { return detail::vformat_to(buf, to_string_view(format_str), args); -} - +} + template <typename S, typename... Args, size_t SIZE = inline_buffer_size, typename Char = enable_if_t<detail::is_string<S>::value, char_t<S>>> -inline typename buffer_context<Char>::iterator format_to( - basic_memory_buffer<Char, SIZE>& buf, const S& format_str, Args&&... args) { +inline typename buffer_context<Char>::iterator format_to( + basic_memory_buffer<Char, SIZE>& buf, const S& format_str, Args&&... args) { const auto& vargs = fmt::make_args_checked<Args...>(format_str, args...); detail::vformat_to(buf, to_string_view(format_str), vargs); return detail::buffer_appender<Char>(buf); -} - -template <typename OutputIt, typename Char = char> -using format_context_t = basic_format_context<OutputIt, Char>; - -template <typename OutputIt, typename Char = char> -using format_args_t = basic_format_args<format_context_t<OutputIt, Char>>; - -template <typename OutputIt, typename Char = typename OutputIt::value_type> +} + +template <typename OutputIt, typename Char = char> +using format_context_t = basic_format_context<OutputIt, Char>; + +template <typename OutputIt, typename Char = char> +using format_args_t = basic_format_args<format_context_t<OutputIt, Char>>; + +template <typename OutputIt, typename Char = typename OutputIt::value_type> using format_to_n_context FMT_DEPRECATED_ALIAS = buffer_context<Char>; - -template <typename OutputIt, typename Char = typename OutputIt::value_type> + +template <typename OutputIt, typename Char = typename OutputIt::value_type> using format_to_n_args FMT_DEPRECATED_ALIAS = basic_format_args<buffer_context<Char>>; - -template <typename OutputIt, typename Char, typename... Args> + +template <typename OutputIt, typename Char, typename... Args> FMT_DEPRECATED format_arg_store<buffer_context<Char>, Args...> -make_format_to_n_args(const Args&... args) { +make_format_to_n_args(const Args&... args) { return format_arg_store<buffer_context<Char>, Args...>(args...); -} - +} + template <typename Char, enable_if_t<(!std::is_same<Char, char>::value), int>> std::basic_string<Char> detail::vformat( - basic_string_view<Char> format_str, - basic_format_args<buffer_context<type_identity_t<Char>>> args) { - basic_memory_buffer<Char> buffer; + basic_string_view<Char> format_str, + basic_format_args<buffer_context<type_identity_t<Char>>> args) { + basic_memory_buffer<Char> buffer; detail::vformat_to(buffer, format_str, args); - return to_string(buffer); -} - -template <typename Char, FMT_ENABLE_IF(std::is_same<Char, wchar_t>::value)> -void vprint(std::FILE* f, basic_string_view<Char> format_str, - wformat_args args) { - wmemory_buffer buffer; + return to_string(buffer); +} + +template <typename Char, FMT_ENABLE_IF(std::is_same<Char, wchar_t>::value)> +void vprint(std::FILE* f, basic_string_view<Char> format_str, + wformat_args args) { + wmemory_buffer buffer; detail::vformat_to(buffer, format_str, args); - buffer.push_back(L'\0'); - if (std::fputws(buffer.data(), f) == -1) - FMT_THROW(system_error(errno, "cannot write to file")); -} - -template <typename Char, FMT_ENABLE_IF(std::is_same<Char, wchar_t>::value)> -void vprint(basic_string_view<Char> format_str, wformat_args args) { - vprint(stdout, format_str, args); -} - -#if FMT_USE_USER_DEFINED_LITERALS + buffer.push_back(L'\0'); + if (std::fputws(buffer.data(), f) == -1) + FMT_THROW(system_error(errno, "cannot write to file")); +} + +template <typename Char, FMT_ENABLE_IF(std::is_same<Char, wchar_t>::value)> +void vprint(basic_string_view<Char> format_str, wformat_args args) { + vprint(stdout, format_str, args); +} + +#if FMT_USE_USER_DEFINED_LITERALS namespace detail { - -# if FMT_USE_UDL_TEMPLATE -template <typename Char, Char... CHARS> class udl_formatter { - public: - template <typename... Args> - std::basic_string<Char> operator()(Args&&... args) const { + +# if FMT_USE_UDL_TEMPLATE +template <typename Char, Char... CHARS> class udl_formatter { + public: + template <typename... Args> + std::basic_string<Char> operator()(Args&&... args) const { static FMT_CONSTEXPR_DECL Char s[] = {CHARS..., '\0'}; return format(FMT_STRING(s), std::forward<Args>(args)...); - } -}; -# else -template <typename Char> struct udl_formatter { - basic_string_view<Char> str; - - template <typename... Args> - std::basic_string<Char> operator()(Args&&... args) const { - return format(str, std::forward<Args>(args)...); - } -}; -# endif // FMT_USE_UDL_TEMPLATE - -template <typename Char> struct udl_arg { + } +}; +# else +template <typename Char> struct udl_formatter { + basic_string_view<Char> str; + + template <typename... Args> + std::basic_string<Char> operator()(Args&&... args) const { + return format(str, std::forward<Args>(args)...); + } +}; +# endif // FMT_USE_UDL_TEMPLATE + +template <typename Char> struct udl_arg { const Char* str; - + template <typename T> named_arg<Char, T> operator=(T&& value) const { - return {str, std::forward<T>(value)}; - } -}; + return {str, std::forward<T>(value)}; + } +}; } // namespace detail - -inline namespace literals { -# if FMT_USE_UDL_TEMPLATE -# pragma GCC diagnostic push + +inline namespace literals { +# if FMT_USE_UDL_TEMPLATE +# pragma GCC diagnostic push # pragma GCC diagnostic ignored "-Wpedantic" -# if FMT_CLANG_VERSION -# pragma GCC diagnostic ignored "-Wgnu-string-literal-operator-template" -# endif -template <typename Char, Char... CHARS> +# if FMT_CLANG_VERSION +# pragma GCC diagnostic ignored "-Wgnu-string-literal-operator-template" +# endif +template <typename Char, Char... CHARS> FMT_CONSTEXPR detail::udl_formatter<Char, CHARS...> operator""_format() { - return {}; -} -# pragma GCC diagnostic pop -# else -/** - \rst - User-defined literal equivalent of :func:`fmt::format`. - - **Example**:: - - using namespace fmt::literals; - std::string message = "The answer is {}"_format(42); - \endrst - */ + return {}; +} +# pragma GCC diagnostic pop +# else +/** + \rst + User-defined literal equivalent of :func:`fmt::format`. + + **Example**:: + + using namespace fmt::literals; + std::string message = "The answer is {}"_format(42); + \endrst + */ FMT_CONSTEXPR detail::udl_formatter<char> operator"" _format(const char* s, size_t n) { - return {{s, n}}; -} + return {{s, n}}; +} FMT_CONSTEXPR detail::udl_formatter<wchar_t> operator"" _format( const wchar_t* s, size_t n) { - return {{s, n}}; -} -# endif // FMT_USE_UDL_TEMPLATE - -/** - \rst - User-defined literal equivalent of :func:`fmt::arg`. - - **Example**:: - - using namespace fmt::literals; - fmt::print("Elapsed time: {s:.2f} seconds", "s"_a=1.23); - \endrst - */ + return {{s, n}}; +} +# endif // FMT_USE_UDL_TEMPLATE + +/** + \rst + User-defined literal equivalent of :func:`fmt::arg`. + + **Example**:: + + using namespace fmt::literals; + fmt::print("Elapsed time: {s:.2f} seconds", "s"_a=1.23); + \endrst + */ FMT_CONSTEXPR detail::udl_arg<char> operator"" _a(const char* s, size_t) { return {s}; -} +} FMT_CONSTEXPR detail::udl_arg<wchar_t> operator"" _a(const wchar_t* s, size_t) { return {s}; -} -} // namespace literals -#endif // FMT_USE_USER_DEFINED_LITERALS -FMT_END_NAMESPACE - -#ifdef FMT_HEADER_ONLY -# define FMT_FUNC inline -# include "format-inl.h" -#else -# define FMT_FUNC -#endif - -#endif // FMT_FORMAT_H_ +} +} // namespace literals +#endif // FMT_USE_USER_DEFINED_LITERALS +FMT_END_NAMESPACE + +#ifdef FMT_HEADER_ONLY +# define FMT_FUNC inline +# include "format-inl.h" +#else +# define FMT_FUNC +#endif + +#endif // FMT_FORMAT_H_ diff --git a/contrib/libs/fmt/include/fmt/locale.h b/contrib/libs/fmt/include/fmt/locale.h index 8680761697..7301bf92a2 100644 --- a/contrib/libs/fmt/include/fmt/locale.h +++ b/contrib/libs/fmt/include/fmt/locale.h @@ -1,64 +1,64 @@ -// Formatting library for C++ - std::locale support -// -// Copyright (c) 2012 - present, Victor Zverovich -// All rights reserved. -// -// For the license information refer to format.h. - -#ifndef FMT_LOCALE_H_ -#define FMT_LOCALE_H_ - -#include <locale> - -#include "format.h" - -FMT_BEGIN_NAMESPACE - +// Formatting library for C++ - std::locale support +// +// Copyright (c) 2012 - present, Victor Zverovich +// All rights reserved. +// +// For the license information refer to format.h. + +#ifndef FMT_LOCALE_H_ +#define FMT_LOCALE_H_ + +#include <locale> + +#include "format.h" + +FMT_BEGIN_NAMESPACE + namespace detail { -template <typename Char> -std::basic_string<Char> vformat( - const std::locale& loc, basic_string_view<Char> format_str, - basic_format_args<buffer_context<type_identity_t<Char>>> args) { - basic_memory_buffer<Char> buffer; +template <typename Char> +std::basic_string<Char> vformat( + const std::locale& loc, basic_string_view<Char> format_str, + basic_format_args<buffer_context<type_identity_t<Char>>> args) { + basic_memory_buffer<Char> buffer; detail::vformat_to(buffer, format_str, args, detail::locale_ref(loc)); - return fmt::to_string(buffer); -} + return fmt::to_string(buffer); +} } // namespace detail - -template <typename S, typename Char = char_t<S>> -inline std::basic_string<Char> vformat( - const std::locale& loc, const S& format_str, - basic_format_args<buffer_context<type_identity_t<Char>>> args) { + +template <typename S, typename Char = char_t<S>> +inline std::basic_string<Char> vformat( + const std::locale& loc, const S& format_str, + basic_format_args<buffer_context<type_identity_t<Char>>> args) { return detail::vformat(loc, to_string_view(format_str), args); -} - -template <typename S, typename... Args, typename Char = char_t<S>> -inline std::basic_string<Char> format(const std::locale& loc, - const S& format_str, Args&&... args) { +} + +template <typename S, typename... Args, typename Char = char_t<S>> +inline std::basic_string<Char> format(const std::locale& loc, + const S& format_str, Args&&... args) { return detail::vformat(loc, to_string_view(format_str), fmt::make_args_checked<Args...>(format_str, args...)); -} - -template <typename S, typename OutputIt, typename... Args, +} + +template <typename S, typename OutputIt, typename... Args, typename Char = char_t<S>, FMT_ENABLE_IF(detail::is_output_iterator<OutputIt, Char>::value)> -inline OutputIt vformat_to( - OutputIt out, const std::locale& loc, const S& format_str, +inline OutputIt vformat_to( + OutputIt out, const std::locale& loc, const S& format_str, basic_format_args<buffer_context<type_identity_t<Char>>> args) { decltype(detail::get_buffer<Char>(out)) buf(detail::get_buffer_init(out)); vformat_to(buf, to_string_view(format_str), args, detail::locale_ref(loc)); return detail::get_iterator(buf); -} - -template <typename OutputIt, typename S, typename... Args, +} + +template <typename OutputIt, typename S, typename... Args, bool enable = detail::is_output_iterator<OutputIt, char_t<S>>::value> inline auto format_to(OutputIt out, const std::locale& loc, const S& format_str, Args&&... args) -> typename std::enable_if<enable, OutputIt>::type { const auto& vargs = fmt::make_args_checked<Args...>(format_str, args...); return vformat_to(out, loc, to_string_view(format_str), vargs); -} - -FMT_END_NAMESPACE - -#endif // FMT_LOCALE_H_ +} + +FMT_END_NAMESPACE + +#endif // FMT_LOCALE_H_ diff --git a/contrib/libs/fmt/include/fmt/os.h b/contrib/libs/fmt/include/fmt/os.h index 4f878da81b..141599f842 100644 --- a/contrib/libs/fmt/include/fmt/os.h +++ b/contrib/libs/fmt/include/fmt/os.h @@ -1,353 +1,353 @@ -// Formatting library for C++ - optional OS-specific functionality -// -// Copyright (c) 2012 - present, Victor Zverovich -// All rights reserved. -// -// For the license information refer to format.h. - -#ifndef FMT_OS_H_ -#define FMT_OS_H_ - -#if defined(__MINGW32__) || defined(__CYGWIN__) -// Workaround MinGW bug https://sourceforge.net/p/mingw/bugs/2024/. -# undef __STRICT_ANSI__ -#endif - -#include <cerrno> -#include <clocale> // for locale_t -#include <cstddef> -#include <cstdio> -#include <cstdlib> // for strtod_l - -#if defined __APPLE__ || defined(__FreeBSD__) -# include <xlocale.h> // for LC_NUMERIC_MASK on OS X -#endif - -#if defined(_WIN32) -# include <locale> // for libc++ locale_win32.h -#endif - -#include "format.h" - -// UWP doesn't provide _pipe. -#if FMT_HAS_INCLUDE("winapifamily.h") -# include <winapifamily.h> -#endif +// Formatting library for C++ - optional OS-specific functionality +// +// Copyright (c) 2012 - present, Victor Zverovich +// All rights reserved. +// +// For the license information refer to format.h. + +#ifndef FMT_OS_H_ +#define FMT_OS_H_ + +#if defined(__MINGW32__) || defined(__CYGWIN__) +// Workaround MinGW bug https://sourceforge.net/p/mingw/bugs/2024/. +# undef __STRICT_ANSI__ +#endif + +#include <cerrno> +#include <clocale> // for locale_t +#include <cstddef> +#include <cstdio> +#include <cstdlib> // for strtod_l + +#if defined __APPLE__ || defined(__FreeBSD__) +# include <xlocale.h> // for LC_NUMERIC_MASK on OS X +#endif + +#if defined(_WIN32) +# include <locale> // for libc++ locale_win32.h +#endif + +#include "format.h" + +// UWP doesn't provide _pipe. +#if FMT_HAS_INCLUDE("winapifamily.h") +# include <winapifamily.h> +#endif #if (FMT_HAS_INCLUDE(<fcntl.h>) || defined(__APPLE__) || \ defined(__linux__)) && \ - (!defined(WINAPI_FAMILY) || (WINAPI_FAMILY == WINAPI_FAMILY_DESKTOP_APP)) -# include <fcntl.h> // for O_RDONLY -# define FMT_USE_FCNTL 1 -#else -# define FMT_USE_FCNTL 0 -#endif - -#ifndef FMT_POSIX -# if defined(_WIN32) && !defined(__MINGW32__) -// Fix warnings about deprecated symbols. -# define FMT_POSIX(call) _##call -# else -# define FMT_POSIX(call) call -# endif -#endif - -// Calls to system functions are wrapped in FMT_SYSTEM for testability. -#ifdef FMT_SYSTEM -# define FMT_POSIX_CALL(call) FMT_SYSTEM(call) -#else + (!defined(WINAPI_FAMILY) || (WINAPI_FAMILY == WINAPI_FAMILY_DESKTOP_APP)) +# include <fcntl.h> // for O_RDONLY +# define FMT_USE_FCNTL 1 +#else +# define FMT_USE_FCNTL 0 +#endif + +#ifndef FMT_POSIX +# if defined(_WIN32) && !defined(__MINGW32__) +// Fix warnings about deprecated symbols. +# define FMT_POSIX(call) _##call +# else +# define FMT_POSIX(call) call +# endif +#endif + +// Calls to system functions are wrapped in FMT_SYSTEM for testability. +#ifdef FMT_SYSTEM +# define FMT_POSIX_CALL(call) FMT_SYSTEM(call) +#else # define FMT_SYSTEM(call) ::call -# ifdef _WIN32 -// Fix warnings about deprecated symbols. -# define FMT_POSIX_CALL(call) ::_##call -# else -# define FMT_POSIX_CALL(call) ::call -# endif -#endif - -// Retries the expression while it evaluates to error_result and errno -// equals to EINTR. -#ifndef _WIN32 -# define FMT_RETRY_VAL(result, expression, error_result) \ - do { \ - (result) = (expression); \ - } while ((result) == (error_result) && errno == EINTR) -#else -# define FMT_RETRY_VAL(result, expression, error_result) result = (expression) -#endif - -#define FMT_RETRY(result, expression) FMT_RETRY_VAL(result, expression, -1) - -FMT_BEGIN_NAMESPACE - -/** - \rst - A reference to a null-terminated string. It can be constructed from a C - string or ``std::string``. - - You can use one of the following type aliases for common character types: - - +---------------+-----------------------------+ - | Type | Definition | - +===============+=============================+ - | cstring_view | basic_cstring_view<char> | - +---------------+-----------------------------+ - | wcstring_view | basic_cstring_view<wchar_t> | - +---------------+-----------------------------+ - - This class is most useful as a parameter type to allow passing - different types of strings to a function, for example:: - - template <typename... Args> - std::string format(cstring_view format_str, const Args & ... args); - - format("{}", 42); - format(std::string("{}"), 42); - \endrst - */ -template <typename Char> class basic_cstring_view { - private: - const Char* data_; - - public: - /** Constructs a string reference object from a C string. */ - basic_cstring_view(const Char* s) : data_(s) {} - - /** - \rst - Constructs a string reference from an ``std::string`` object. - \endrst - */ - basic_cstring_view(const std::basic_string<Char>& s) : data_(s.c_str()) {} - - /** Returns the pointer to a C string. */ - const Char* c_str() const { return data_; } -}; - -using cstring_view = basic_cstring_view<char>; -using wcstring_view = basic_cstring_view<wchar_t>; - -// An error code. -class error_code { - private: - int value_; - - public: - explicit error_code(int value = 0) FMT_NOEXCEPT : value_(value) {} - - int get() const FMT_NOEXCEPT { return value_; } -}; - -#ifdef _WIN32 +# ifdef _WIN32 +// Fix warnings about deprecated symbols. +# define FMT_POSIX_CALL(call) ::_##call +# else +# define FMT_POSIX_CALL(call) ::call +# endif +#endif + +// Retries the expression while it evaluates to error_result and errno +// equals to EINTR. +#ifndef _WIN32 +# define FMT_RETRY_VAL(result, expression, error_result) \ + do { \ + (result) = (expression); \ + } while ((result) == (error_result) && errno == EINTR) +#else +# define FMT_RETRY_VAL(result, expression, error_result) result = (expression) +#endif + +#define FMT_RETRY(result, expression) FMT_RETRY_VAL(result, expression, -1) + +FMT_BEGIN_NAMESPACE + +/** + \rst + A reference to a null-terminated string. It can be constructed from a C + string or ``std::string``. + + You can use one of the following type aliases for common character types: + + +---------------+-----------------------------+ + | Type | Definition | + +===============+=============================+ + | cstring_view | basic_cstring_view<char> | + +---------------+-----------------------------+ + | wcstring_view | basic_cstring_view<wchar_t> | + +---------------+-----------------------------+ + + This class is most useful as a parameter type to allow passing + different types of strings to a function, for example:: + + template <typename... Args> + std::string format(cstring_view format_str, const Args & ... args); + + format("{}", 42); + format(std::string("{}"), 42); + \endrst + */ +template <typename Char> class basic_cstring_view { + private: + const Char* data_; + + public: + /** Constructs a string reference object from a C string. */ + basic_cstring_view(const Char* s) : data_(s) {} + + /** + \rst + Constructs a string reference from an ``std::string`` object. + \endrst + */ + basic_cstring_view(const std::basic_string<Char>& s) : data_(s.c_str()) {} + + /** Returns the pointer to a C string. */ + const Char* c_str() const { return data_; } +}; + +using cstring_view = basic_cstring_view<char>; +using wcstring_view = basic_cstring_view<wchar_t>; + +// An error code. +class error_code { + private: + int value_; + + public: + explicit error_code(int value = 0) FMT_NOEXCEPT : value_(value) {} + + int get() const FMT_NOEXCEPT { return value_; } +}; + +#ifdef _WIN32 namespace detail { -// A converter from UTF-16 to UTF-8. -// It is only provided for Windows since other systems support UTF-8 natively. -class utf16_to_utf8 { - private: - memory_buffer buffer_; - - public: - utf16_to_utf8() {} - FMT_API explicit utf16_to_utf8(wstring_view s); - operator string_view() const { return string_view(&buffer_[0], size()); } - size_t size() const { return buffer_.size() - 1; } - const char* c_str() const { return &buffer_[0]; } - std::string str() const { return std::string(&buffer_[0], size()); } - - // Performs conversion returning a system error code instead of - // throwing exception on conversion error. This method may still throw - // in case of memory allocation error. - FMT_API int convert(wstring_view s); -}; - -FMT_API void format_windows_error(buffer<char>& out, int error_code, - string_view message) FMT_NOEXCEPT; +// A converter from UTF-16 to UTF-8. +// It is only provided for Windows since other systems support UTF-8 natively. +class utf16_to_utf8 { + private: + memory_buffer buffer_; + + public: + utf16_to_utf8() {} + FMT_API explicit utf16_to_utf8(wstring_view s); + operator string_view() const { return string_view(&buffer_[0], size()); } + size_t size() const { return buffer_.size() - 1; } + const char* c_str() const { return &buffer_[0]; } + std::string str() const { return std::string(&buffer_[0], size()); } + + // Performs conversion returning a system error code instead of + // throwing exception on conversion error. This method may still throw + // in case of memory allocation error. + FMT_API int convert(wstring_view s); +}; + +FMT_API void format_windows_error(buffer<char>& out, int error_code, + string_view message) FMT_NOEXCEPT; } // namespace detail - -/** A Windows error. */ -class windows_error : public system_error { - private: - FMT_API void init(int error_code, string_view format_str, format_args args); - - public: - /** - \rst - Constructs a :class:`fmt::windows_error` object with the description - of the form - - .. parsed-literal:: - *<message>*: *<system-message>* - - where *<message>* is the formatted message and *<system-message>* is the - system message corresponding to the error code. - *error_code* is a Windows error code as given by ``GetLastError``. - If *error_code* is not a valid error code such as -1, the system message - will look like "error -1". - - **Example**:: - - // This throws a windows_error with the description - // cannot open file 'madeup': The system cannot find the file specified. - // or similar (system message may vary). - const char *filename = "madeup"; - LPOFSTRUCT of = LPOFSTRUCT(); - HFILE file = OpenFile(filename, &of, OF_READ); - if (file == HFILE_ERROR) { - throw fmt::windows_error(GetLastError(), - "cannot open file '{}'", filename); - } - \endrst - */ - template <typename... Args> - windows_error(int error_code, string_view message, const Args&... args) { - init(error_code, message, make_format_args(args...)); - } -}; - -// Reports a Windows error without throwing an exception. -// Can be used to report errors from destructors. -FMT_API void report_windows_error(int error_code, - string_view message) FMT_NOEXCEPT; -#endif // _WIN32 - -// A buffered file. -class buffered_file { - private: - FILE* file_; - - friend class file; - - explicit buffered_file(FILE* f) : file_(f) {} - - public: - buffered_file(const buffered_file&) = delete; - void operator=(const buffered_file&) = delete; - - // Constructs a buffered_file object which doesn't represent any file. - buffered_file() FMT_NOEXCEPT : file_(nullptr) {} - - // Destroys the object closing the file it represents if any. - FMT_API ~buffered_file() FMT_NOEXCEPT; - - public: - buffered_file(buffered_file&& other) FMT_NOEXCEPT : file_(other.file_) { - other.file_ = nullptr; - } - - buffered_file& operator=(buffered_file&& other) { - close(); - file_ = other.file_; - other.file_ = nullptr; - return *this; - } - - // Opens a file. - FMT_API buffered_file(cstring_view filename, cstring_view mode); - - // Closes the file. - FMT_API void close(); - - // Returns the pointer to a FILE object representing this file. - FILE* get() const FMT_NOEXCEPT { return file_; } - - // We place parentheses around fileno to workaround a bug in some versions - // of MinGW that define fileno as a macro. - FMT_API int(fileno)() const; - - void vprint(string_view format_str, format_args args) { - fmt::vprint(file_, format_str, args); - } - - template <typename... Args> - inline void print(string_view format_str, const Args&... args) { - vprint(format_str, make_format_args(args...)); - } -}; - -#if FMT_USE_FCNTL -// A file. Closed file is represented by a file object with descriptor -1. -// Methods that are not declared with FMT_NOEXCEPT may throw -// fmt::system_error in case of failure. Note that some errors such as -// closing the file multiple times will cause a crash on Windows rather -// than an exception. You can get standard behavior by overriding the -// invalid parameter handler with _set_invalid_parameter_handler. -class file { - private: - int fd_; // File descriptor. - - // Constructs a file object with a given descriptor. - explicit file(int fd) : fd_(fd) {} - - public: - // Possible values for the oflag argument to the constructor. - enum { - RDONLY = FMT_POSIX(O_RDONLY), // Open for reading only. - WRONLY = FMT_POSIX(O_WRONLY), // Open for writing only. + +/** A Windows error. */ +class windows_error : public system_error { + private: + FMT_API void init(int error_code, string_view format_str, format_args args); + + public: + /** + \rst + Constructs a :class:`fmt::windows_error` object with the description + of the form + + .. parsed-literal:: + *<message>*: *<system-message>* + + where *<message>* is the formatted message and *<system-message>* is the + system message corresponding to the error code. + *error_code* is a Windows error code as given by ``GetLastError``. + If *error_code* is not a valid error code such as -1, the system message + will look like "error -1". + + **Example**:: + + // This throws a windows_error with the description + // cannot open file 'madeup': The system cannot find the file specified. + // or similar (system message may vary). + const char *filename = "madeup"; + LPOFSTRUCT of = LPOFSTRUCT(); + HFILE file = OpenFile(filename, &of, OF_READ); + if (file == HFILE_ERROR) { + throw fmt::windows_error(GetLastError(), + "cannot open file '{}'", filename); + } + \endrst + */ + template <typename... Args> + windows_error(int error_code, string_view message, const Args&... args) { + init(error_code, message, make_format_args(args...)); + } +}; + +// Reports a Windows error without throwing an exception. +// Can be used to report errors from destructors. +FMT_API void report_windows_error(int error_code, + string_view message) FMT_NOEXCEPT; +#endif // _WIN32 + +// A buffered file. +class buffered_file { + private: + FILE* file_; + + friend class file; + + explicit buffered_file(FILE* f) : file_(f) {} + + public: + buffered_file(const buffered_file&) = delete; + void operator=(const buffered_file&) = delete; + + // Constructs a buffered_file object which doesn't represent any file. + buffered_file() FMT_NOEXCEPT : file_(nullptr) {} + + // Destroys the object closing the file it represents if any. + FMT_API ~buffered_file() FMT_NOEXCEPT; + + public: + buffered_file(buffered_file&& other) FMT_NOEXCEPT : file_(other.file_) { + other.file_ = nullptr; + } + + buffered_file& operator=(buffered_file&& other) { + close(); + file_ = other.file_; + other.file_ = nullptr; + return *this; + } + + // Opens a file. + FMT_API buffered_file(cstring_view filename, cstring_view mode); + + // Closes the file. + FMT_API void close(); + + // Returns the pointer to a FILE object representing this file. + FILE* get() const FMT_NOEXCEPT { return file_; } + + // We place parentheses around fileno to workaround a bug in some versions + // of MinGW that define fileno as a macro. + FMT_API int(fileno)() const; + + void vprint(string_view format_str, format_args args) { + fmt::vprint(file_, format_str, args); + } + + template <typename... Args> + inline void print(string_view format_str, const Args&... args) { + vprint(format_str, make_format_args(args...)); + } +}; + +#if FMT_USE_FCNTL +// A file. Closed file is represented by a file object with descriptor -1. +// Methods that are not declared with FMT_NOEXCEPT may throw +// fmt::system_error in case of failure. Note that some errors such as +// closing the file multiple times will cause a crash on Windows rather +// than an exception. You can get standard behavior by overriding the +// invalid parameter handler with _set_invalid_parameter_handler. +class file { + private: + int fd_; // File descriptor. + + // Constructs a file object with a given descriptor. + explicit file(int fd) : fd_(fd) {} + + public: + // Possible values for the oflag argument to the constructor. + enum { + RDONLY = FMT_POSIX(O_RDONLY), // Open for reading only. + WRONLY = FMT_POSIX(O_WRONLY), // Open for writing only. RDWR = FMT_POSIX(O_RDWR), // Open for reading and writing. CREATE = FMT_POSIX(O_CREAT), // Create if the file doesn't exist. APPEND = FMT_POSIX(O_APPEND) // Open in append mode. - }; - - // Constructs a file object which doesn't represent any file. - file() FMT_NOEXCEPT : fd_(-1) {} - - // Opens a file and constructs a file object representing this file. - FMT_API file(cstring_view path, int oflag); - - public: - file(const file&) = delete; - void operator=(const file&) = delete; - - file(file&& other) FMT_NOEXCEPT : fd_(other.fd_) { other.fd_ = -1; } - - file& operator=(file&& other) FMT_NOEXCEPT { - close(); - fd_ = other.fd_; - other.fd_ = -1; - return *this; - } - - // Destroys the object closing the file it represents if any. - FMT_API ~file() FMT_NOEXCEPT; - - // Returns the file descriptor. - int descriptor() const FMT_NOEXCEPT { return fd_; } - - // Closes the file. - FMT_API void close(); - - // Returns the file size. The size has signed type for consistency with - // stat::st_size. - FMT_API long long size() const; - - // Attempts to read count bytes from the file into the specified buffer. + }; + + // Constructs a file object which doesn't represent any file. + file() FMT_NOEXCEPT : fd_(-1) {} + + // Opens a file and constructs a file object representing this file. + FMT_API file(cstring_view path, int oflag); + + public: + file(const file&) = delete; + void operator=(const file&) = delete; + + file(file&& other) FMT_NOEXCEPT : fd_(other.fd_) { other.fd_ = -1; } + + file& operator=(file&& other) FMT_NOEXCEPT { + close(); + fd_ = other.fd_; + other.fd_ = -1; + return *this; + } + + // Destroys the object closing the file it represents if any. + FMT_API ~file() FMT_NOEXCEPT; + + // Returns the file descriptor. + int descriptor() const FMT_NOEXCEPT { return fd_; } + + // Closes the file. + FMT_API void close(); + + // Returns the file size. The size has signed type for consistency with + // stat::st_size. + FMT_API long long size() const; + + // Attempts to read count bytes from the file into the specified buffer. FMT_API size_t read(void* buffer, size_t count); - - // Attempts to write count bytes from the specified buffer to the file. + + // Attempts to write count bytes from the specified buffer to the file. FMT_API size_t write(const void* buffer, size_t count); - - // Duplicates a file descriptor with the dup function and returns - // the duplicate as a file object. - FMT_API static file dup(int fd); - - // Makes fd be the copy of this file descriptor, closing fd first if - // necessary. - FMT_API void dup2(int fd); - - // Makes fd be the copy of this file descriptor, closing fd first if - // necessary. - FMT_API void dup2(int fd, error_code& ec) FMT_NOEXCEPT; - - // Creates a pipe setting up read_end and write_end file objects for reading - // and writing respectively. - FMT_API static void pipe(file& read_end, file& write_end); - - // Creates a buffered_file object associated with this file and detaches - // this file object from the file. - FMT_API buffered_file fdopen(const char* mode); -}; - -// Returns the memory page size. -long getpagesize(); + + // Duplicates a file descriptor with the dup function and returns + // the duplicate as a file object. + FMT_API static file dup(int fd); + + // Makes fd be the copy of this file descriptor, closing fd first if + // necessary. + FMT_API void dup2(int fd); + + // Makes fd be the copy of this file descriptor, closing fd first if + // necessary. + FMT_API void dup2(int fd, error_code& ec) FMT_NOEXCEPT; + + // Creates a pipe setting up read_end and write_end file objects for reading + // and writing respectively. + FMT_API static void pipe(file& read_end, file& write_end); + + // Creates a buffered_file object associated with this file and detaches + // this file object from the file. + FMT_API buffered_file fdopen(const char* mode); +}; + +// Returns the memory page size. +long getpagesize(); namespace detail { @@ -433,52 +433,52 @@ template <typename... T> inline ostream output_file(cstring_view path, T... params) { return {path, detail::ostream_params(params...)}; } -#endif // FMT_USE_FCNTL - -#ifdef FMT_LOCALE -// A "C" numeric locale. -class locale { - private: -# if defined(_WIN32) && !defined(_LIBCPP_VERSION) - using locale_t = _locale_t; - - static void freelocale(locale_t loc) { _free_locale(loc); } - - static double strtod_l(const char* nptr, char** endptr, _locale_t loc) { - return _strtod_l(nptr, endptr, loc); - } -# endif - - locale_t locale_; - - public: - using type = locale_t; - locale(const locale&) = delete; - void operator=(const locale&) = delete; - - locale() { -# if !defined(_WIN32) || defined(_LIBCPP_VERSION) - locale_ = FMT_SYSTEM(newlocale(LC_NUMERIC_MASK, "C", nullptr)); -# else - locale_ = _create_locale(LC_NUMERIC, "C"); -# endif - if (!locale_) FMT_THROW(system_error(errno, "cannot create locale")); - } - ~locale() { freelocale(locale_); } - - type get() const { return locale_; } - - // Converts string to floating-point number and advances str past the end - // of the parsed input. - double strtod(const char*& str) const { - char* end = nullptr; - double result = strtod_l(str, &end, locale_); - str = end; - return result; - } -}; -using Locale FMT_DEPRECATED_ALIAS = locale; -#endif // FMT_LOCALE -FMT_END_NAMESPACE - -#endif // FMT_OS_H_ +#endif // FMT_USE_FCNTL + +#ifdef FMT_LOCALE +// A "C" numeric locale. +class locale { + private: +# if defined(_WIN32) && !defined(_LIBCPP_VERSION) + using locale_t = _locale_t; + + static void freelocale(locale_t loc) { _free_locale(loc); } + + static double strtod_l(const char* nptr, char** endptr, _locale_t loc) { + return _strtod_l(nptr, endptr, loc); + } +# endif + + locale_t locale_; + + public: + using type = locale_t; + locale(const locale&) = delete; + void operator=(const locale&) = delete; + + locale() { +# if !defined(_WIN32) || defined(_LIBCPP_VERSION) + locale_ = FMT_SYSTEM(newlocale(LC_NUMERIC_MASK, "C", nullptr)); +# else + locale_ = _create_locale(LC_NUMERIC, "C"); +# endif + if (!locale_) FMT_THROW(system_error(errno, "cannot create locale")); + } + ~locale() { freelocale(locale_); } + + type get() const { return locale_; } + + // Converts string to floating-point number and advances str past the end + // of the parsed input. + double strtod(const char*& str) const { + char* end = nullptr; + double result = strtod_l(str, &end, locale_); + str = end; + return result; + } +}; +using Locale FMT_DEPRECATED_ALIAS = locale; +#endif // FMT_LOCALE +FMT_END_NAMESPACE + +#endif // FMT_OS_H_ diff --git a/contrib/libs/fmt/include/fmt/ostream.h b/contrib/libs/fmt/include/fmt/ostream.h index 5fb2f341b9..29c58ec13b 100644 --- a/contrib/libs/fmt/include/fmt/ostream.h +++ b/contrib/libs/fmt/include/fmt/ostream.h @@ -1,63 +1,63 @@ -// Formatting library for C++ - std::ostream support -// -// Copyright (c) 2012 - present, Victor Zverovich -// All rights reserved. -// -// For the license information refer to format.h. - -#ifndef FMT_OSTREAM_H_ -#define FMT_OSTREAM_H_ - -#include <ostream> - -#include "format.h" - -FMT_BEGIN_NAMESPACE - +// Formatting library for C++ - std::ostream support +// +// Copyright (c) 2012 - present, Victor Zverovich +// All rights reserved. +// +// For the license information refer to format.h. + +#ifndef FMT_OSTREAM_H_ +#define FMT_OSTREAM_H_ + +#include <ostream> + +#include "format.h" + +FMT_BEGIN_NAMESPACE + template <typename Char> class basic_printf_parse_context; -template <typename OutputIt, typename Char> class basic_printf_context; - +template <typename OutputIt, typename Char> class basic_printf_context; + namespace detail { - -template <class Char> class formatbuf : public std::basic_streambuf<Char> { - private: - using int_type = typename std::basic_streambuf<Char>::int_type; - using traits_type = typename std::basic_streambuf<Char>::traits_type; - - buffer<Char>& buffer_; - - public: - formatbuf(buffer<Char>& buf) : buffer_(buf) {} - - protected: - // The put-area is actually always empty. This makes the implementation - // simpler and has the advantage that the streambuf and the buffer are always - // in sync and sputc never writes into uninitialized memory. The obvious - // disadvantage is that each call to sputc always results in a (virtual) call - // to overflow. There is no disadvantage here for sputn since this always - // results in a call to xsputn. - - int_type overflow(int_type ch = traits_type::eof()) FMT_OVERRIDE { - if (!traits_type::eq_int_type(ch, traits_type::eof())) - buffer_.push_back(static_cast<Char>(ch)); - return ch; - } - - std::streamsize xsputn(const Char* s, std::streamsize count) FMT_OVERRIDE { - buffer_.append(s, s + count); - return count; - } -}; - + +template <class Char> class formatbuf : public std::basic_streambuf<Char> { + private: + using int_type = typename std::basic_streambuf<Char>::int_type; + using traits_type = typename std::basic_streambuf<Char>::traits_type; + + buffer<Char>& buffer_; + + public: + formatbuf(buffer<Char>& buf) : buffer_(buf) {} + + protected: + // The put-area is actually always empty. This makes the implementation + // simpler and has the advantage that the streambuf and the buffer are always + // in sync and sputc never writes into uninitialized memory. The obvious + // disadvantage is that each call to sputc always results in a (virtual) call + // to overflow. There is no disadvantage here for sputn since this always + // results in a call to xsputn. + + int_type overflow(int_type ch = traits_type::eof()) FMT_OVERRIDE { + if (!traits_type::eq_int_type(ch, traits_type::eof())) + buffer_.push_back(static_cast<Char>(ch)); + return ch; + } + + std::streamsize xsputn(const Char* s, std::streamsize count) FMT_OVERRIDE { + buffer_.append(s, s + count); + return count; + } +}; + struct converter { template <typename T, FMT_ENABLE_IF(is_integral<T>::value)> converter(T); }; -template <typename Char> struct test_stream : std::basic_ostream<Char> { - private: +template <typename Char> struct test_stream : std::basic_ostream<Char> { + private: void_t<> operator<<(converter); -}; - +}; + // Hide insertion operators for built-in types. template <typename Char, typename Traits> void_t<> operator<<(std::basic_ostream<Char, Traits>&, Char); @@ -70,108 +70,108 @@ void_t<> operator<<(std::basic_ostream<char, Traits>&, signed char); template <typename Traits> void_t<> operator<<(std::basic_ostream<char, Traits>&, unsigned char); -// Checks if T has a user-defined operator<< (e.g. not a member of -// std::ostream). -template <typename T, typename Char> class is_streamable { - private: - template <typename U> - static bool_constant<!std::is_same<decltype(std::declval<test_stream<Char>&>() - << std::declval<U>()), - void_t<>>::value> - test(int); - - template <typename> static std::false_type test(...); - - using result = decltype(test<T>(0)); - - public: - static const bool value = result::value; -}; - -// Write the content of buf to os. -template <typename Char> +// Checks if T has a user-defined operator<< (e.g. not a member of +// std::ostream). +template <typename T, typename Char> class is_streamable { + private: + template <typename U> + static bool_constant<!std::is_same<decltype(std::declval<test_stream<Char>&>() + << std::declval<U>()), + void_t<>>::value> + test(int); + + template <typename> static std::false_type test(...); + + using result = decltype(test<T>(0)); + + public: + static const bool value = result::value; +}; + +// Write the content of buf to os. +template <typename Char> void write_buffer(std::basic_ostream<Char>& os, buffer<Char>& buf) { - const Char* buf_data = buf.data(); - using unsigned_streamsize = std::make_unsigned<std::streamsize>::type; - unsigned_streamsize size = buf.size(); - unsigned_streamsize max_size = to_unsigned(max_value<std::streamsize>()); - do { - unsigned_streamsize n = size <= max_size ? size : max_size; - os.write(buf_data, static_cast<std::streamsize>(n)); - buf_data += n; - size -= n; - } while (size != 0); -} - -template <typename Char, typename T> -void format_value(buffer<Char>& buf, const T& value, - locale_ref loc = locale_ref()) { - formatbuf<Char> format_buf(buf); - std::basic_ostream<Char> output(&format_buf); -#if !defined(FMT_STATIC_THOUSANDS_SEPARATOR) - if (loc) output.imbue(loc.get<std::locale>()); -#endif + const Char* buf_data = buf.data(); + using unsigned_streamsize = std::make_unsigned<std::streamsize>::type; + unsigned_streamsize size = buf.size(); + unsigned_streamsize max_size = to_unsigned(max_value<std::streamsize>()); + do { + unsigned_streamsize n = size <= max_size ? size : max_size; + os.write(buf_data, static_cast<std::streamsize>(n)); + buf_data += n; + size -= n; + } while (size != 0); +} + +template <typename Char, typename T> +void format_value(buffer<Char>& buf, const T& value, + locale_ref loc = locale_ref()) { + formatbuf<Char> format_buf(buf); + std::basic_ostream<Char> output(&format_buf); +#if !defined(FMT_STATIC_THOUSANDS_SEPARATOR) + if (loc) output.imbue(loc.get<std::locale>()); +#endif output << value; - output.exceptions(std::ios_base::failbit | std::ios_base::badbit); + output.exceptions(std::ios_base::failbit | std::ios_base::badbit); buf.try_resize(buf.size()); -} - -// Formats an object of type T that has an overloaded ostream operator<<. -template <typename T, typename Char> -struct fallback_formatter<T, Char, enable_if_t<is_streamable<T, Char>::value>> - : private formatter<basic_string_view<Char>, Char> { +} + +// Formats an object of type T that has an overloaded ostream operator<<. +template <typename T, typename Char> +struct fallback_formatter<T, Char, enable_if_t<is_streamable<T, Char>::value>> + : private formatter<basic_string_view<Char>, Char> { FMT_CONSTEXPR auto parse(basic_format_parse_context<Char>& ctx) -> decltype(ctx.begin()) { - return formatter<basic_string_view<Char>, Char>::parse(ctx); - } - template <typename ParseCtx, - FMT_ENABLE_IF(std::is_same< - ParseCtx, basic_printf_parse_context<Char>>::value)> - auto parse(ParseCtx& ctx) -> decltype(ctx.begin()) { - return ctx.begin(); - } - - template <typename OutputIt> - auto format(const T& value, basic_format_context<OutputIt, Char>& ctx) - -> OutputIt { - basic_memory_buffer<Char> buffer; - format_value(buffer, value, ctx.locale()); - basic_string_view<Char> str(buffer.data(), buffer.size()); - return formatter<basic_string_view<Char>, Char>::format(str, ctx); - } - template <typename OutputIt> - auto format(const T& value, basic_printf_context<OutputIt, Char>& ctx) - -> OutputIt { - basic_memory_buffer<Char> buffer; - format_value(buffer, value, ctx.locale()); - return std::copy(buffer.begin(), buffer.end(), ctx.out()); - } -}; + return formatter<basic_string_view<Char>, Char>::parse(ctx); + } + template <typename ParseCtx, + FMT_ENABLE_IF(std::is_same< + ParseCtx, basic_printf_parse_context<Char>>::value)> + auto parse(ParseCtx& ctx) -> decltype(ctx.begin()) { + return ctx.begin(); + } + + template <typename OutputIt> + auto format(const T& value, basic_format_context<OutputIt, Char>& ctx) + -> OutputIt { + basic_memory_buffer<Char> buffer; + format_value(buffer, value, ctx.locale()); + basic_string_view<Char> str(buffer.data(), buffer.size()); + return formatter<basic_string_view<Char>, Char>::format(str, ctx); + } + template <typename OutputIt> + auto format(const T& value, basic_printf_context<OutputIt, Char>& ctx) + -> OutputIt { + basic_memory_buffer<Char> buffer; + format_value(buffer, value, ctx.locale()); + return std::copy(buffer.begin(), buffer.end(), ctx.out()); + } +}; } // namespace detail - -template <typename Char> -void vprint(std::basic_ostream<Char>& os, basic_string_view<Char> format_str, - basic_format_args<buffer_context<type_identity_t<Char>>> args) { - basic_memory_buffer<Char> buffer; + +template <typename Char> +void vprint(std::basic_ostream<Char>& os, basic_string_view<Char> format_str, + basic_format_args<buffer_context<type_identity_t<Char>>> args) { + basic_memory_buffer<Char> buffer; detail::vformat_to(buffer, format_str, args); detail::write_buffer(os, buffer); -} - -/** - \rst - Prints formatted data to the stream *os*. - - **Example**:: - - fmt::print(cerr, "Don't {}!", "panic"); - \endrst - */ -template <typename S, typename... Args, +} + +/** + \rst + Prints formatted data to the stream *os*. + + **Example**:: + + fmt::print(cerr, "Don't {}!", "panic"); + \endrst + */ +template <typename S, typename... Args, typename Char = enable_if_t<detail::is_string<S>::value, char_t<S>>> -void print(std::basic_ostream<Char>& os, const S& format_str, Args&&... args) { - vprint(os, to_string_view(format_str), +void print(std::basic_ostream<Char>& os, const S& format_str, Args&&... args) { + vprint(os, to_string_view(format_str), fmt::make_args_checked<Args...>(format_str, args...)); -} -FMT_END_NAMESPACE - -#endif // FMT_OSTREAM_H_ +} +FMT_END_NAMESPACE + +#endif // FMT_OSTREAM_H_ diff --git a/contrib/libs/fmt/include/fmt/printf.h b/contrib/libs/fmt/include/fmt/printf.h index b90948bf62..8c28ac2327 100644 --- a/contrib/libs/fmt/include/fmt/printf.h +++ b/contrib/libs/fmt/include/fmt/printf.h @@ -1,146 +1,146 @@ -// Formatting library for C++ - legacy printf implementation -// -// Copyright (c) 2012 - 2016, Victor Zverovich -// All rights reserved. -// -// For the license information refer to format.h. - -#ifndef FMT_PRINTF_H_ -#define FMT_PRINTF_H_ - -#include <algorithm> // std::max -#include <limits> // std::numeric_limits - -#include "ostream.h" - -FMT_BEGIN_NAMESPACE +// Formatting library for C++ - legacy printf implementation +// +// Copyright (c) 2012 - 2016, Victor Zverovich +// All rights reserved. +// +// For the license information refer to format.h. + +#ifndef FMT_PRINTF_H_ +#define FMT_PRINTF_H_ + +#include <algorithm> // std::max +#include <limits> // std::numeric_limits + +#include "ostream.h" + +FMT_BEGIN_NAMESPACE namespace detail { - -// Checks if a value fits in int - used to avoid warnings about comparing -// signed and unsigned integers. -template <bool IsSigned> struct int_checker { - template <typename T> static bool fits_in_int(T value) { - unsigned max = max_value<int>(); - return value <= max; - } - static bool fits_in_int(bool) { return true; } -}; - -template <> struct int_checker<true> { - template <typename T> static bool fits_in_int(T value) { - return value >= (std::numeric_limits<int>::min)() && - value <= max_value<int>(); - } - static bool fits_in_int(int) { return true; } -}; - -class printf_precision_handler { - public: - template <typename T, FMT_ENABLE_IF(std::is_integral<T>::value)> - int operator()(T value) { - if (!int_checker<std::numeric_limits<T>::is_signed>::fits_in_int(value)) - FMT_THROW(format_error("number is too big")); - return (std::max)(static_cast<int>(value), 0); - } - - template <typename T, FMT_ENABLE_IF(!std::is_integral<T>::value)> - int operator()(T) { - FMT_THROW(format_error("precision is not integer")); - return 0; - } -}; - -// An argument visitor that returns true iff arg is a zero integer. -class is_zero_int { - public: - template <typename T, FMT_ENABLE_IF(std::is_integral<T>::value)> - bool operator()(T value) { - return value == 0; - } - - template <typename T, FMT_ENABLE_IF(!std::is_integral<T>::value)> - bool operator()(T) { - return false; - } -}; - -template <typename T> struct make_unsigned_or_bool : std::make_unsigned<T> {}; - -template <> struct make_unsigned_or_bool<bool> { using type = bool; }; - -template <typename T, typename Context> class arg_converter { - private: - using char_type = typename Context::char_type; - - basic_format_arg<Context>& arg_; - char_type type_; - - public: - arg_converter(basic_format_arg<Context>& arg, char_type type) - : arg_(arg), type_(type) {} - - void operator()(bool value) { - if (type_ != 's') operator()<bool>(value); - } - - template <typename U, FMT_ENABLE_IF(std::is_integral<U>::value)> - void operator()(U value) { - bool is_signed = type_ == 'd' || type_ == 'i'; - using target_type = conditional_t<std::is_same<T, void>::value, U, T>; - if (const_check(sizeof(target_type) <= sizeof(int))) { - // Extra casts are used to silence warnings. - if (is_signed) { + +// Checks if a value fits in int - used to avoid warnings about comparing +// signed and unsigned integers. +template <bool IsSigned> struct int_checker { + template <typename T> static bool fits_in_int(T value) { + unsigned max = max_value<int>(); + return value <= max; + } + static bool fits_in_int(bool) { return true; } +}; + +template <> struct int_checker<true> { + template <typename T> static bool fits_in_int(T value) { + return value >= (std::numeric_limits<int>::min)() && + value <= max_value<int>(); + } + static bool fits_in_int(int) { return true; } +}; + +class printf_precision_handler { + public: + template <typename T, FMT_ENABLE_IF(std::is_integral<T>::value)> + int operator()(T value) { + if (!int_checker<std::numeric_limits<T>::is_signed>::fits_in_int(value)) + FMT_THROW(format_error("number is too big")); + return (std::max)(static_cast<int>(value), 0); + } + + template <typename T, FMT_ENABLE_IF(!std::is_integral<T>::value)> + int operator()(T) { + FMT_THROW(format_error("precision is not integer")); + return 0; + } +}; + +// An argument visitor that returns true iff arg is a zero integer. +class is_zero_int { + public: + template <typename T, FMT_ENABLE_IF(std::is_integral<T>::value)> + bool operator()(T value) { + return value == 0; + } + + template <typename T, FMT_ENABLE_IF(!std::is_integral<T>::value)> + bool operator()(T) { + return false; + } +}; + +template <typename T> struct make_unsigned_or_bool : std::make_unsigned<T> {}; + +template <> struct make_unsigned_or_bool<bool> { using type = bool; }; + +template <typename T, typename Context> class arg_converter { + private: + using char_type = typename Context::char_type; + + basic_format_arg<Context>& arg_; + char_type type_; + + public: + arg_converter(basic_format_arg<Context>& arg, char_type type) + : arg_(arg), type_(type) {} + + void operator()(bool value) { + if (type_ != 's') operator()<bool>(value); + } + + template <typename U, FMT_ENABLE_IF(std::is_integral<U>::value)> + void operator()(U value) { + bool is_signed = type_ == 'd' || type_ == 'i'; + using target_type = conditional_t<std::is_same<T, void>::value, U, T>; + if (const_check(sizeof(target_type) <= sizeof(int))) { + // Extra casts are used to silence warnings. + if (is_signed) { arg_ = detail::make_arg<Context>( - static_cast<int>(static_cast<target_type>(value))); - } else { - using unsigned_type = typename make_unsigned_or_bool<target_type>::type; + static_cast<int>(static_cast<target_type>(value))); + } else { + using unsigned_type = typename make_unsigned_or_bool<target_type>::type; arg_ = detail::make_arg<Context>( - static_cast<unsigned>(static_cast<unsigned_type>(value))); - } - } else { - if (is_signed) { - // glibc's printf doesn't sign extend arguments of smaller types: - // std::printf("%lld", -42); // prints "4294967254" - // but we don't have to do the same because it's a UB. + static_cast<unsigned>(static_cast<unsigned_type>(value))); + } + } else { + if (is_signed) { + // glibc's printf doesn't sign extend arguments of smaller types: + // std::printf("%lld", -42); // prints "4294967254" + // but we don't have to do the same because it's a UB. arg_ = detail::make_arg<Context>(static_cast<long long>(value)); - } else { + } else { arg_ = detail::make_arg<Context>( - static_cast<typename make_unsigned_or_bool<U>::type>(value)); - } - } - } - - template <typename U, FMT_ENABLE_IF(!std::is_integral<U>::value)> - void operator()(U) {} // No conversion needed for non-integral types. -}; - -// Converts an integer argument to T for printf, if T is an integral type. -// If T is void, the argument is converted to corresponding signed or unsigned -// type depending on the type specifier: 'd' and 'i' - signed, other - -// unsigned). -template <typename T, typename Context, typename Char> -void convert_arg(basic_format_arg<Context>& arg, Char type) { - visit_format_arg(arg_converter<T, Context>(arg, type), arg); -} - -// Converts an integer argument to char for printf. -template <typename Context> class char_converter { - private: - basic_format_arg<Context>& arg_; - - public: - explicit char_converter(basic_format_arg<Context>& arg) : arg_(arg) {} - - template <typename T, FMT_ENABLE_IF(std::is_integral<T>::value)> - void operator()(T value) { + static_cast<typename make_unsigned_or_bool<U>::type>(value)); + } + } + } + + template <typename U, FMT_ENABLE_IF(!std::is_integral<U>::value)> + void operator()(U) {} // No conversion needed for non-integral types. +}; + +// Converts an integer argument to T for printf, if T is an integral type. +// If T is void, the argument is converted to corresponding signed or unsigned +// type depending on the type specifier: 'd' and 'i' - signed, other - +// unsigned). +template <typename T, typename Context, typename Char> +void convert_arg(basic_format_arg<Context>& arg, Char type) { + visit_format_arg(arg_converter<T, Context>(arg, type), arg); +} + +// Converts an integer argument to char for printf. +template <typename Context> class char_converter { + private: + basic_format_arg<Context>& arg_; + + public: + explicit char_converter(basic_format_arg<Context>& arg) : arg_(arg) {} + + template <typename T, FMT_ENABLE_IF(std::is_integral<T>::value)> + void operator()(T value) { arg_ = detail::make_arg<Context>( - static_cast<typename Context::char_type>(value)); - } - - template <typename T, FMT_ENABLE_IF(!std::is_integral<T>::value)> - void operator()(T) {} // No conversion needed for non-integral types. -}; - + static_cast<typename Context::char_type>(value)); + } + + template <typename T, FMT_ENABLE_IF(!std::is_integral<T>::value)> + void operator()(T) {} // No conversion needed for non-integral types. +}; + // An argument visitor that return a pointer to a C string if argument is a // string or null otherwise. template <typename Char> struct get_cstring { @@ -148,365 +148,365 @@ template <typename Char> struct get_cstring { const Char* operator()(const Char* s) { return s; } }; -// Checks if an argument is a valid printf width specifier and sets -// left alignment if it is negative. -template <typename Char> class printf_width_handler { - private: - using format_specs = basic_format_specs<Char>; - - format_specs& specs_; - - public: - explicit printf_width_handler(format_specs& specs) : specs_(specs) {} - - template <typename T, FMT_ENABLE_IF(std::is_integral<T>::value)> - unsigned operator()(T value) { - auto width = static_cast<uint32_or_64_or_128_t<T>>(value); +// Checks if an argument is a valid printf width specifier and sets +// left alignment if it is negative. +template <typename Char> class printf_width_handler { + private: + using format_specs = basic_format_specs<Char>; + + format_specs& specs_; + + public: + explicit printf_width_handler(format_specs& specs) : specs_(specs) {} + + template <typename T, FMT_ENABLE_IF(std::is_integral<T>::value)> + unsigned operator()(T value) { + auto width = static_cast<uint32_or_64_or_128_t<T>>(value); if (detail::is_negative(value)) { - specs_.align = align::left; - width = 0 - width; - } - unsigned int_max = max_value<int>(); - if (width > int_max) FMT_THROW(format_error("number is too big")); - return static_cast<unsigned>(width); - } - - template <typename T, FMT_ENABLE_IF(!std::is_integral<T>::value)> - unsigned operator()(T) { - FMT_THROW(format_error("width is not integer")); - return 0; - } -}; - -template <typename Char, typename Context> + specs_.align = align::left; + width = 0 - width; + } + unsigned int_max = max_value<int>(); + if (width > int_max) FMT_THROW(format_error("number is too big")); + return static_cast<unsigned>(width); + } + + template <typename T, FMT_ENABLE_IF(!std::is_integral<T>::value)> + unsigned operator()(T) { + FMT_THROW(format_error("width is not integer")); + return 0; + } +}; + +template <typename Char, typename Context> void vprintf(buffer<Char>& buf, basic_string_view<Char> format, basic_format_args<Context> args) { Context(buffer_appender<Char>(buf), format, args).format(); -} +} } // namespace detail - + // For printing into memory_buffer. template <typename Char, typename Context> FMT_DEPRECATED void printf(detail::buffer<Char>& buf, basic_string_view<Char> format, basic_format_args<Context> args) { return detail::vprintf(buf, format, args); -} +} using detail::vprintf; - -template <typename Char> -class basic_printf_parse_context : public basic_format_parse_context<Char> { - using basic_format_parse_context<Char>::basic_format_parse_context; -}; -template <typename OutputIt, typename Char> class basic_printf_context; - -/** - \rst - The ``printf`` argument formatter. - \endrst - */ + +template <typename Char> +class basic_printf_parse_context : public basic_format_parse_context<Char> { + using basic_format_parse_context<Char>::basic_format_parse_context; +}; +template <typename OutputIt, typename Char> class basic_printf_context; + +/** + \rst + The ``printf`` argument formatter. + \endrst + */ template <typename OutputIt, typename Char> class printf_arg_formatter : public detail::arg_formatter_base<OutputIt, Char> { - public: + public: using iterator = OutputIt; - - private: + + private: using char_type = Char; using base = detail::arg_formatter_base<OutputIt, Char>; using context_type = basic_printf_context<OutputIt, Char>; - - context_type& context_; - - void write_null_pointer(char) { - this->specs()->type = 0; - this->write("(nil)"); - } - - void write_null_pointer(wchar_t) { - this->specs()->type = 0; - this->write(L"(nil)"); - } - - public: - using format_specs = typename base::format_specs; - - /** - \rst - Constructs an argument formatter object. - *buffer* is a reference to the output buffer and *specs* contains format - specifier information for standard argument types. - \endrst - */ - printf_arg_formatter(iterator iter, format_specs& specs, context_type& ctx) + + context_type& context_; + + void write_null_pointer(char) { + this->specs()->type = 0; + this->write("(nil)"); + } + + void write_null_pointer(wchar_t) { + this->specs()->type = 0; + this->write(L"(nil)"); + } + + public: + using format_specs = typename base::format_specs; + + /** + \rst + Constructs an argument formatter object. + *buffer* is a reference to the output buffer and *specs* contains format + specifier information for standard argument types. + \endrst + */ + printf_arg_formatter(iterator iter, format_specs& specs, context_type& ctx) : base(iter, &specs, detail::locale_ref()), context_(ctx) {} - + template <typename T, FMT_ENABLE_IF(fmt::detail::is_integral<T>::value)> - iterator operator()(T value) { - // MSVC2013 fails to compile separate overloads for bool and char_type so - // use std::is_same instead. - if (std::is_same<T, bool>::value) { - format_specs& fmt_specs = *this->specs(); - if (fmt_specs.type != 's') return base::operator()(value ? 1 : 0); - fmt_specs.type = 0; - this->write(value != 0); - } else if (std::is_same<T, char_type>::value) { - format_specs& fmt_specs = *this->specs(); - if (fmt_specs.type && fmt_specs.type != 'c') - return (*this)(static_cast<int>(value)); - fmt_specs.sign = sign::none; - fmt_specs.alt = false; + iterator operator()(T value) { + // MSVC2013 fails to compile separate overloads for bool and char_type so + // use std::is_same instead. + if (std::is_same<T, bool>::value) { + format_specs& fmt_specs = *this->specs(); + if (fmt_specs.type != 's') return base::operator()(value ? 1 : 0); + fmt_specs.type = 0; + this->write(value != 0); + } else if (std::is_same<T, char_type>::value) { + format_specs& fmt_specs = *this->specs(); + if (fmt_specs.type && fmt_specs.type != 'c') + return (*this)(static_cast<int>(value)); + fmt_specs.sign = sign::none; + fmt_specs.alt = false; fmt_specs.fill[0] = ' '; // Ignore '0' flag for char types. // align::numeric needs to be overwritten here since the '0' flag is // ignored for non-numeric types if (fmt_specs.align == align::none || fmt_specs.align == align::numeric) fmt_specs.align = align::right; - return base::operator()(value); - } else { - return base::operator()(value); - } - return this->out(); - } - - template <typename T, FMT_ENABLE_IF(std::is_floating_point<T>::value)> - iterator operator()(T value) { - return base::operator()(value); - } - - /** Formats a null-terminated C string. */ - iterator operator()(const char* value) { - if (value) - base::operator()(value); - else if (this->specs()->type == 'p') - write_null_pointer(char_type()); - else - this->write("(null)"); - return this->out(); - } - - /** Formats a null-terminated wide C string. */ - iterator operator()(const wchar_t* value) { - if (value) - base::operator()(value); - else if (this->specs()->type == 'p') - write_null_pointer(char_type()); - else - this->write(L"(null)"); - return this->out(); - } - - iterator operator()(basic_string_view<char_type> value) { - return base::operator()(value); - } - - iterator operator()(monostate value) { return base::operator()(value); } - - /** Formats a pointer. */ - iterator operator()(const void* value) { - if (value) return base::operator()(value); - this->specs()->type = 0; - write_null_pointer(char_type()); - return this->out(); - } - - /** Formats an argument of a custom (user-defined) type. */ - iterator operator()(typename basic_format_arg<context_type>::handle handle) { - handle.format(context_.parse_context(), context_); - return this->out(); - } -}; - -template <typename T> struct printf_formatter { - printf_formatter() = delete; - - template <typename ParseContext> - auto parse(ParseContext& ctx) -> decltype(ctx.begin()) { - return ctx.begin(); - } - - template <typename FormatContext> - auto format(const T& value, FormatContext& ctx) -> decltype(ctx.out()) { + return base::operator()(value); + } else { + return base::operator()(value); + } + return this->out(); + } + + template <typename T, FMT_ENABLE_IF(std::is_floating_point<T>::value)> + iterator operator()(T value) { + return base::operator()(value); + } + + /** Formats a null-terminated C string. */ + iterator operator()(const char* value) { + if (value) + base::operator()(value); + else if (this->specs()->type == 'p') + write_null_pointer(char_type()); + else + this->write("(null)"); + return this->out(); + } + + /** Formats a null-terminated wide C string. */ + iterator operator()(const wchar_t* value) { + if (value) + base::operator()(value); + else if (this->specs()->type == 'p') + write_null_pointer(char_type()); + else + this->write(L"(null)"); + return this->out(); + } + + iterator operator()(basic_string_view<char_type> value) { + return base::operator()(value); + } + + iterator operator()(monostate value) { return base::operator()(value); } + + /** Formats a pointer. */ + iterator operator()(const void* value) { + if (value) return base::operator()(value); + this->specs()->type = 0; + write_null_pointer(char_type()); + return this->out(); + } + + /** Formats an argument of a custom (user-defined) type. */ + iterator operator()(typename basic_format_arg<context_type>::handle handle) { + handle.format(context_.parse_context(), context_); + return this->out(); + } +}; + +template <typename T> struct printf_formatter { + printf_formatter() = delete; + + template <typename ParseContext> + auto parse(ParseContext& ctx) -> decltype(ctx.begin()) { + return ctx.begin(); + } + + template <typename FormatContext> + auto format(const T& value, FormatContext& ctx) -> decltype(ctx.out()) { detail::format_value(detail::get_container(ctx.out()), value); - return ctx.out(); - } -}; - + return ctx.out(); + } +}; + /** This template formats data and writes the output through an output iterator. */ -template <typename OutputIt, typename Char> class basic_printf_context { - public: - /** The character type for the output. */ - using char_type = Char; - using iterator = OutputIt; - using format_arg = basic_format_arg<basic_printf_context>; - using parse_context_type = basic_printf_parse_context<Char>; - template <typename T> using formatter_type = printf_formatter<T>; - - private: - using format_specs = basic_format_specs<char_type>; - - OutputIt out_; - basic_format_args<basic_printf_context> args_; - parse_context_type parse_ctx_; - - static void parse_flags(format_specs& specs, const Char*& it, - const Char* end); - - // Returns the argument with specified index or, if arg_index is -1, the next - // argument. - format_arg get_arg(int arg_index = -1); - - // Parses argument index, flags and width and returns the argument index. - int parse_header(const Char*& it, const Char* end, format_specs& specs); - - public: - /** - \rst +template <typename OutputIt, typename Char> class basic_printf_context { + public: + /** The character type for the output. */ + using char_type = Char; + using iterator = OutputIt; + using format_arg = basic_format_arg<basic_printf_context>; + using parse_context_type = basic_printf_parse_context<Char>; + template <typename T> using formatter_type = printf_formatter<T>; + + private: + using format_specs = basic_format_specs<char_type>; + + OutputIt out_; + basic_format_args<basic_printf_context> args_; + parse_context_type parse_ctx_; + + static void parse_flags(format_specs& specs, const Char*& it, + const Char* end); + + // Returns the argument with specified index or, if arg_index is -1, the next + // argument. + format_arg get_arg(int arg_index = -1); + + // Parses argument index, flags and width and returns the argument index. + int parse_header(const Char*& it, const Char* end, format_specs& specs); + + public: + /** + \rst Constructs a ``printf_context`` object. References to the arguments are stored in the context object so make sure they have appropriate lifetimes. - \endrst - */ - basic_printf_context(OutputIt out, basic_string_view<char_type> format_str, - basic_format_args<basic_printf_context> args) - : out_(out), args_(args), parse_ctx_(format_str) {} - - OutputIt out() { return out_; } - void advance_to(OutputIt it) { out_ = it; } - + \endrst + */ + basic_printf_context(OutputIt out, basic_string_view<char_type> format_str, + basic_format_args<basic_printf_context> args) + : out_(out), args_(args), parse_ctx_(format_str) {} + + OutputIt out() { return out_; } + void advance_to(OutputIt it) { out_ = it; } + detail::locale_ref locale() { return {}; } - - format_arg arg(int id) const { return args_.get(id); } - - parse_context_type& parse_context() { return parse_ctx_; } - - FMT_CONSTEXPR void on_error(const char* message) { - parse_ctx_.on_error(message); - } - - /** Formats stored arguments and writes the output to the range. */ + + format_arg arg(int id) const { return args_.get(id); } + + parse_context_type& parse_context() { return parse_ctx_; } + + FMT_CONSTEXPR void on_error(const char* message) { + parse_ctx_.on_error(message); + } + + /** Formats stored arguments and writes the output to the range. */ template <typename ArgFormatter = printf_arg_formatter<OutputIt, Char>> - OutputIt format(); -}; - -template <typename OutputIt, typename Char> -void basic_printf_context<OutputIt, Char>::parse_flags(format_specs& specs, - const Char*& it, - const Char* end) { - for (; it != end; ++it) { - switch (*it) { - case '-': - specs.align = align::left; - break; - case '+': - specs.sign = sign::plus; - break; - case '0': - specs.fill[0] = '0'; - break; - case ' ': + OutputIt format(); +}; + +template <typename OutputIt, typename Char> +void basic_printf_context<OutputIt, Char>::parse_flags(format_specs& specs, + const Char*& it, + const Char* end) { + for (; it != end; ++it) { + switch (*it) { + case '-': + specs.align = align::left; + break; + case '+': + specs.sign = sign::plus; + break; + case '0': + specs.fill[0] = '0'; + break; + case ' ': if (specs.sign != sign::plus) { specs.sign = sign::space; } - break; - case '#': - specs.alt = true; - break; - default: - return; - } - } -} - -template <typename OutputIt, typename Char> -typename basic_printf_context<OutputIt, Char>::format_arg -basic_printf_context<OutputIt, Char>::get_arg(int arg_index) { - if (arg_index < 0) - arg_index = parse_ctx_.next_arg_id(); - else - parse_ctx_.check_arg_id(--arg_index); + break; + case '#': + specs.alt = true; + break; + default: + return; + } + } +} + +template <typename OutputIt, typename Char> +typename basic_printf_context<OutputIt, Char>::format_arg +basic_printf_context<OutputIt, Char>::get_arg(int arg_index) { + if (arg_index < 0) + arg_index = parse_ctx_.next_arg_id(); + else + parse_ctx_.check_arg_id(--arg_index); return detail::get_arg(*this, arg_index); -} - -template <typename OutputIt, typename Char> -int basic_printf_context<OutputIt, Char>::parse_header(const Char*& it, - const Char* end, - format_specs& specs) { - int arg_index = -1; - char_type c = *it; - if (c >= '0' && c <= '9') { - // Parse an argument index (if followed by '$') or a width possibly - // preceded with '0' flag(s). +} + +template <typename OutputIt, typename Char> +int basic_printf_context<OutputIt, Char>::parse_header(const Char*& it, + const Char* end, + format_specs& specs) { + int arg_index = -1; + char_type c = *it; + if (c >= '0' && c <= '9') { + // Parse an argument index (if followed by '$') or a width possibly + // preceded with '0' flag(s). detail::error_handler eh; - int value = parse_nonnegative_int(it, end, eh); - if (it != end && *it == '$') { // value is an argument index - ++it; - arg_index = value; - } else { - if (c == '0') specs.fill[0] = '0'; - if (value != 0) { - // Nonzero value means that we parsed width and don't need to - // parse it or flags again, so return now. - specs.width = value; - return arg_index; - } - } - } - parse_flags(specs, it, end); - // Parse width. - if (it != end) { - if (*it >= '0' && *it <= '9') { + int value = parse_nonnegative_int(it, end, eh); + if (it != end && *it == '$') { // value is an argument index + ++it; + arg_index = value; + } else { + if (c == '0') specs.fill[0] = '0'; + if (value != 0) { + // Nonzero value means that we parsed width and don't need to + // parse it or flags again, so return now. + specs.width = value; + return arg_index; + } + } + } + parse_flags(specs, it, end); + // Parse width. + if (it != end) { + if (*it >= '0' && *it <= '9') { detail::error_handler eh; - specs.width = parse_nonnegative_int(it, end, eh); - } else if (*it == '*') { - ++it; - specs.width = static_cast<int>(visit_format_arg( + specs.width = parse_nonnegative_int(it, end, eh); + } else if (*it == '*') { + ++it; + specs.width = static_cast<int>(visit_format_arg( detail::printf_width_handler<char_type>(specs), get_arg())); - } - } - return arg_index; -} - -template <typename OutputIt, typename Char> -template <typename ArgFormatter> -OutputIt basic_printf_context<OutputIt, Char>::format() { - auto out = this->out(); - const Char* start = parse_ctx_.begin(); - const Char* end = parse_ctx_.end(); - auto it = start; - while (it != end) { - char_type c = *it++; - if (c != '%') continue; - if (it != end && *it == c) { - out = std::copy(start, it, out); - start = ++it; - continue; - } - out = std::copy(start, it - 1, out); - - format_specs specs; - specs.align = align::right; - - // Parse argument index, flags and width. - int arg_index = parse_header(it, end, specs); + } + } + return arg_index; +} + +template <typename OutputIt, typename Char> +template <typename ArgFormatter> +OutputIt basic_printf_context<OutputIt, Char>::format() { + auto out = this->out(); + const Char* start = parse_ctx_.begin(); + const Char* end = parse_ctx_.end(); + auto it = start; + while (it != end) { + char_type c = *it++; + if (c != '%') continue; + if (it != end && *it == c) { + out = std::copy(start, it, out); + start = ++it; + continue; + } + out = std::copy(start, it - 1, out); + + format_specs specs; + specs.align = align::right; + + // Parse argument index, flags and width. + int arg_index = parse_header(it, end, specs); if (arg_index == 0) on_error("argument not found"); - - // Parse precision. - if (it != end && *it == '.') { - ++it; - c = it != end ? *it : 0; - if ('0' <= c && c <= '9') { + + // Parse precision. + if (it != end && *it == '.') { + ++it; + c = it != end ? *it : 0; + if ('0' <= c && c <= '9') { detail::error_handler eh; - specs.precision = parse_nonnegative_int(it, end, eh); - } else if (c == '*') { - ++it; - specs.precision = static_cast<int>( + specs.precision = parse_nonnegative_int(it, end, eh); + } else if (c == '*') { + ++it; + specs.precision = static_cast<int>( visit_format_arg(detail::printf_precision_handler(), get_arg())); - } else { - specs.precision = 0; - } - } - - format_arg arg = get_arg(arg_index); + } else { + specs.precision = 0; + } + } + + format_arg arg = get_arg(arg_index); // For d, i, o, u, x, and X conversion specifiers, if a precision is // specified, the '0' flag is ignored if (specs.precision >= 0 && arg.is_integral()) @@ -521,231 +521,231 @@ OutputIt basic_printf_context<OutputIt, Char>::format() { detail::to_unsigned(nul != str_end ? nul - str : specs.precision))); } if (specs.alt && visit_format_arg(detail::is_zero_int(), arg)) - specs.alt = false; - if (specs.fill[0] == '0') { + specs.alt = false; + if (specs.fill[0] == '0') { if (arg.is_arithmetic() && specs.align != align::left) - specs.align = align::numeric; - else + specs.align = align::numeric; + else specs.fill[0] = ' '; // Ignore '0' flag for non-numeric types or if '-' // flag is also present. - } - - // Parse length and convert the argument to the required type. - c = it != end ? *it++ : 0; - char_type t = it != end ? *it : 0; + } + + // Parse length and convert the argument to the required type. + c = it != end ? *it++ : 0; + char_type t = it != end ? *it : 0; using detail::convert_arg; - switch (c) { - case 'h': - if (t == 'h') { - ++it; - t = it != end ? *it : 0; - convert_arg<signed char>(arg, t); - } else { - convert_arg<short>(arg, t); - } - break; - case 'l': - if (t == 'l') { - ++it; - t = it != end ? *it : 0; - convert_arg<long long>(arg, t); - } else { - convert_arg<long>(arg, t); - } - break; - case 'j': - convert_arg<intmax_t>(arg, t); - break; - case 'z': + switch (c) { + case 'h': + if (t == 'h') { + ++it; + t = it != end ? *it : 0; + convert_arg<signed char>(arg, t); + } else { + convert_arg<short>(arg, t); + } + break; + case 'l': + if (t == 'l') { + ++it; + t = it != end ? *it : 0; + convert_arg<long long>(arg, t); + } else { + convert_arg<long>(arg, t); + } + break; + case 'j': + convert_arg<intmax_t>(arg, t); + break; + case 'z': convert_arg<size_t>(arg, t); - break; - case 't': - convert_arg<std::ptrdiff_t>(arg, t); - break; - case 'L': - // printf produces garbage when 'L' is omitted for long double, no - // need to do the same. - break; - default: - --it; - convert_arg<void>(arg, c); - } - - // Parse type. - if (it == end) FMT_THROW(format_error("invalid format string")); - specs.type = static_cast<char>(*it++); - if (arg.is_integral()) { - // Normalize type. - switch (specs.type) { - case 'i': - case 'u': - specs.type = 'd'; - break; - case 'c': + break; + case 't': + convert_arg<std::ptrdiff_t>(arg, t); + break; + case 'L': + // printf produces garbage when 'L' is omitted for long double, no + // need to do the same. + break; + default: + --it; + convert_arg<void>(arg, c); + } + + // Parse type. + if (it == end) FMT_THROW(format_error("invalid format string")); + specs.type = static_cast<char>(*it++); + if (arg.is_integral()) { + // Normalize type. + switch (specs.type) { + case 'i': + case 'u': + specs.type = 'd'; + break; + case 'c': visit_format_arg(detail::char_converter<basic_printf_context>(arg), - arg); - break; - } - } - - start = it; - - // Format argument. + arg); + break; + } + } + + start = it; + + // Format argument. out = visit_format_arg(ArgFormatter(out, specs, *this), arg); - } - return std::copy(start, it, out); -} - -template <typename Char> -using basic_printf_context_t = + } + return std::copy(start, it, out); +} + +template <typename Char> +using basic_printf_context_t = basic_printf_context<detail::buffer_appender<Char>, Char>; - -using printf_context = basic_printf_context_t<char>; -using wprintf_context = basic_printf_context_t<wchar_t>; - -using printf_args = basic_format_args<printf_context>; -using wprintf_args = basic_format_args<wprintf_context>; - -/** - \rst - Constructs an `~fmt::format_arg_store` object that contains references to - arguments and can be implicitly converted to `~fmt::printf_args`. - \endrst - */ -template <typename... Args> -inline format_arg_store<printf_context, Args...> make_printf_args( - const Args&... args) { - return {args...}; -} - -/** - \rst - Constructs an `~fmt::format_arg_store` object that contains references to - arguments and can be implicitly converted to `~fmt::wprintf_args`. - \endrst - */ -template <typename... Args> -inline format_arg_store<wprintf_context, Args...> make_wprintf_args( - const Args&... args) { - return {args...}; -} - -template <typename S, typename Char = char_t<S>> -inline std::basic_string<Char> vsprintf( - const S& format, - basic_format_args<basic_printf_context_t<type_identity_t<Char>>> args) { - basic_memory_buffer<Char> buffer; + +using printf_context = basic_printf_context_t<char>; +using wprintf_context = basic_printf_context_t<wchar_t>; + +using printf_args = basic_format_args<printf_context>; +using wprintf_args = basic_format_args<wprintf_context>; + +/** + \rst + Constructs an `~fmt::format_arg_store` object that contains references to + arguments and can be implicitly converted to `~fmt::printf_args`. + \endrst + */ +template <typename... Args> +inline format_arg_store<printf_context, Args...> make_printf_args( + const Args&... args) { + return {args...}; +} + +/** + \rst + Constructs an `~fmt::format_arg_store` object that contains references to + arguments and can be implicitly converted to `~fmt::wprintf_args`. + \endrst + */ +template <typename... Args> +inline format_arg_store<wprintf_context, Args...> make_wprintf_args( + const Args&... args) { + return {args...}; +} + +template <typename S, typename Char = char_t<S>> +inline std::basic_string<Char> vsprintf( + const S& format, + basic_format_args<basic_printf_context_t<type_identity_t<Char>>> args) { + basic_memory_buffer<Char> buffer; vprintf(buffer, to_string_view(format), args); - return to_string(buffer); -} - -/** - \rst - Formats arguments and returns the result as a string. - - **Example**:: - - std::string message = fmt::sprintf("The answer is %d", 42); - \endrst -*/ -template <typename S, typename... Args, + return to_string(buffer); +} + +/** + \rst + Formats arguments and returns the result as a string. + + **Example**:: + + std::string message = fmt::sprintf("The answer is %d", 42); + \endrst +*/ +template <typename S, typename... Args, typename Char = enable_if_t<detail::is_string<S>::value, char_t<S>>> -inline std::basic_string<Char> sprintf(const S& format, const Args&... args) { - using context = basic_printf_context_t<Char>; - return vsprintf(to_string_view(format), make_format_args<context>(args...)); -} - -template <typename S, typename Char = char_t<S>> -inline int vfprintf( - std::FILE* f, const S& format, - basic_format_args<basic_printf_context_t<type_identity_t<Char>>> args) { - basic_memory_buffer<Char> buffer; +inline std::basic_string<Char> sprintf(const S& format, const Args&... args) { + using context = basic_printf_context_t<Char>; + return vsprintf(to_string_view(format), make_format_args<context>(args...)); +} + +template <typename S, typename Char = char_t<S>> +inline int vfprintf( + std::FILE* f, const S& format, + basic_format_args<basic_printf_context_t<type_identity_t<Char>>> args) { + basic_memory_buffer<Char> buffer; vprintf(buffer, to_string_view(format), args); size_t size = buffer.size(); - return std::fwrite(buffer.data(), sizeof(Char), size, f) < size - ? -1 - : static_cast<int>(size); -} - -/** - \rst - Prints formatted data to the file *f*. - - **Example**:: - - fmt::fprintf(stderr, "Don't %s!", "panic"); - \endrst - */ -template <typename S, typename... Args, + return std::fwrite(buffer.data(), sizeof(Char), size, f) < size + ? -1 + : static_cast<int>(size); +} + +/** + \rst + Prints formatted data to the file *f*. + + **Example**:: + + fmt::fprintf(stderr, "Don't %s!", "panic"); + \endrst + */ +template <typename S, typename... Args, typename Char = enable_if_t<detail::is_string<S>::value, char_t<S>>> -inline int fprintf(std::FILE* f, const S& format, const Args&... args) { - using context = basic_printf_context_t<Char>; - return vfprintf(f, to_string_view(format), - make_format_args<context>(args...)); -} - -template <typename S, typename Char = char_t<S>> -inline int vprintf( - const S& format, - basic_format_args<basic_printf_context_t<type_identity_t<Char>>> args) { - return vfprintf(stdout, to_string_view(format), args); -} - -/** - \rst - Prints formatted data to ``stdout``. - - **Example**:: - - fmt::printf("Elapsed time: %.2f seconds", 1.23); - \endrst - */ -template <typename S, typename... Args, +inline int fprintf(std::FILE* f, const S& format, const Args&... args) { + using context = basic_printf_context_t<Char>; + return vfprintf(f, to_string_view(format), + make_format_args<context>(args...)); +} + +template <typename S, typename Char = char_t<S>> +inline int vprintf( + const S& format, + basic_format_args<basic_printf_context_t<type_identity_t<Char>>> args) { + return vfprintf(stdout, to_string_view(format), args); +} + +/** + \rst + Prints formatted data to ``stdout``. + + **Example**:: + + fmt::printf("Elapsed time: %.2f seconds", 1.23); + \endrst + */ +template <typename S, typename... Args, FMT_ENABLE_IF(detail::is_string<S>::value)> -inline int printf(const S& format_str, const Args&... args) { - using context = basic_printf_context_t<char_t<S>>; - return vprintf(to_string_view(format_str), - make_format_args<context>(args...)); -} - -template <typename S, typename Char = char_t<S>> -inline int vfprintf( - std::basic_ostream<Char>& os, const S& format, - basic_format_args<basic_printf_context_t<type_identity_t<Char>>> args) { - basic_memory_buffer<Char> buffer; +inline int printf(const S& format_str, const Args&... args) { + using context = basic_printf_context_t<char_t<S>>; + return vprintf(to_string_view(format_str), + make_format_args<context>(args...)); +} + +template <typename S, typename Char = char_t<S>> +inline int vfprintf( + std::basic_ostream<Char>& os, const S& format, + basic_format_args<basic_printf_context_t<type_identity_t<Char>>> args) { + basic_memory_buffer<Char> buffer; vprintf(buffer, to_string_view(format), args); detail::write_buffer(os, buffer); - return static_cast<int>(buffer.size()); -} - -/** Formats arguments and writes the output to the range. */ -template <typename ArgFormatter, typename Char, - typename Context = - basic_printf_context<typename ArgFormatter::iterator, Char>> -typename ArgFormatter::iterator vprintf( + return static_cast<int>(buffer.size()); +} + +/** Formats arguments and writes the output to the range. */ +template <typename ArgFormatter, typename Char, + typename Context = + basic_printf_context<typename ArgFormatter::iterator, Char>> +typename ArgFormatter::iterator vprintf( detail::buffer<Char>& out, basic_string_view<Char> format_str, - basic_format_args<type_identity_t<Context>> args) { - typename ArgFormatter::iterator iter(out); - Context(iter, format_str, args).template format<ArgFormatter>(); - return iter; -} - -/** - \rst - Prints formatted data to the stream *os*. - - **Example**:: - - fmt::fprintf(cerr, "Don't %s!", "panic"); - \endrst - */ -template <typename S, typename... Args, typename Char = char_t<S>> -inline int fprintf(std::basic_ostream<Char>& os, const S& format_str, - const Args&... args) { - using context = basic_printf_context_t<Char>; - return vfprintf(os, to_string_view(format_str), - make_format_args<context>(args...)); -} -FMT_END_NAMESPACE - -#endif // FMT_PRINTF_H_ + basic_format_args<type_identity_t<Context>> args) { + typename ArgFormatter::iterator iter(out); + Context(iter, format_str, args).template format<ArgFormatter>(); + return iter; +} + +/** + \rst + Prints formatted data to the stream *os*. + + **Example**:: + + fmt::fprintf(cerr, "Don't %s!", "panic"); + \endrst + */ +template <typename S, typename... Args, typename Char = char_t<S>> +inline int fprintf(std::basic_ostream<Char>& os, const S& format_str, + const Args&... args) { + using context = basic_printf_context_t<Char>; + return vfprintf(os, to_string_view(format_str), + make_format_args<context>(args...)); +} +FMT_END_NAMESPACE + +#endif // FMT_PRINTF_H_ diff --git a/contrib/libs/fmt/include/fmt/ranges.h b/contrib/libs/fmt/include/fmt/ranges.h index 750661c4e3..632f04949c 100644 --- a/contrib/libs/fmt/include/fmt/ranges.h +++ b/contrib/libs/fmt/include/fmt/ranges.h @@ -1,253 +1,253 @@ -// Formatting library for C++ - experimental range support -// -// Copyright (c) 2012 - present, Victor Zverovich -// All rights reserved. -// -// For the license information refer to format.h. -// -// Copyright (c) 2018 - present, Remotion (Igor Schulz) -// All Rights Reserved -// {fmt} support for ranges, containers and types tuple interface. - -#ifndef FMT_RANGES_H_ -#define FMT_RANGES_H_ - -#include <initializer_list> -#include <type_traits> - -#include "format.h" - -// output only up to N items from the range. -#ifndef FMT_RANGE_OUTPUT_LENGTH_LIMIT -# define FMT_RANGE_OUTPUT_LENGTH_LIMIT 256 -#endif - -FMT_BEGIN_NAMESPACE - -template <typename Char> struct formatting_base { - template <typename ParseContext> - FMT_CONSTEXPR auto parse(ParseContext& ctx) -> decltype(ctx.begin()) { - return ctx.begin(); - } -}; - -template <typename Char, typename Enable = void> -struct formatting_range : formatting_base<Char> { +// Formatting library for C++ - experimental range support +// +// Copyright (c) 2012 - present, Victor Zverovich +// All rights reserved. +// +// For the license information refer to format.h. +// +// Copyright (c) 2018 - present, Remotion (Igor Schulz) +// All Rights Reserved +// {fmt} support for ranges, containers and types tuple interface. + +#ifndef FMT_RANGES_H_ +#define FMT_RANGES_H_ + +#include <initializer_list> +#include <type_traits> + +#include "format.h" + +// output only up to N items from the range. +#ifndef FMT_RANGE_OUTPUT_LENGTH_LIMIT +# define FMT_RANGE_OUTPUT_LENGTH_LIMIT 256 +#endif + +FMT_BEGIN_NAMESPACE + +template <typename Char> struct formatting_base { + template <typename ParseContext> + FMT_CONSTEXPR auto parse(ParseContext& ctx) -> decltype(ctx.begin()) { + return ctx.begin(); + } +}; + +template <typename Char, typename Enable = void> +struct formatting_range : formatting_base<Char> { static FMT_CONSTEXPR_DECL const size_t range_length_limit = - FMT_RANGE_OUTPUT_LENGTH_LIMIT; // output only up to N items from the - // range. - Char prefix; - Char delimiter; - Char postfix; - formatting_range() : prefix('{'), delimiter(','), postfix('}') {} - static FMT_CONSTEXPR_DECL const bool add_delimiter_spaces = true; - static FMT_CONSTEXPR_DECL const bool add_prepostfix_space = false; -}; - -template <typename Char, typename Enable = void> -struct formatting_tuple : formatting_base<Char> { - Char prefix; - Char delimiter; - Char postfix; - formatting_tuple() : prefix('('), delimiter(','), postfix(')') {} - static FMT_CONSTEXPR_DECL const bool add_delimiter_spaces = true; - static FMT_CONSTEXPR_DECL const bool add_prepostfix_space = false; -}; - + FMT_RANGE_OUTPUT_LENGTH_LIMIT; // output only up to N items from the + // range. + Char prefix; + Char delimiter; + Char postfix; + formatting_range() : prefix('{'), delimiter(','), postfix('}') {} + static FMT_CONSTEXPR_DECL const bool add_delimiter_spaces = true; + static FMT_CONSTEXPR_DECL const bool add_prepostfix_space = false; +}; + +template <typename Char, typename Enable = void> +struct formatting_tuple : formatting_base<Char> { + Char prefix; + Char delimiter; + Char postfix; + formatting_tuple() : prefix('('), delimiter(','), postfix(')') {} + static FMT_CONSTEXPR_DECL const bool add_delimiter_spaces = true; + static FMT_CONSTEXPR_DECL const bool add_prepostfix_space = false; +}; + namespace detail { - -template <typename RangeT, typename OutputIterator> -OutputIterator copy(const RangeT& range, OutputIterator out) { - for (auto it = range.begin(), end = range.end(); it != end; ++it) - *out++ = *it; - return out; -} - -template <typename OutputIterator> -OutputIterator copy(const char* str, OutputIterator out) { - while (*str) *out++ = *str++; - return out; -} - -template <typename OutputIterator> -OutputIterator copy(char ch, OutputIterator out) { - *out++ = ch; - return out; -} - -/// Return true value if T has std::string interface, like std::string_view. -template <typename T> class is_like_std_string { - template <typename U> - static auto check(U* p) - -> decltype((void)p->find('a'), p->length(), (void)p->data(), int()); - template <typename> static void check(...); - - public: - static FMT_CONSTEXPR_DECL const bool value = - is_string<T>::value || !std::is_void<decltype(check<T>(nullptr))>::value; -}; - -template <typename Char> -struct is_like_std_string<fmt::basic_string_view<Char>> : std::true_type {}; - -template <typename... Ts> struct conditional_helper {}; - -template <typename T, typename _ = void> struct is_range_ : std::false_type {}; - -#if !FMT_MSC_VER || FMT_MSC_VER > 1800 -template <typename T> -struct is_range_< - T, conditional_t<false, - conditional_helper<decltype(std::declval<T>().begin()), - decltype(std::declval<T>().end())>, - void>> : std::true_type {}; -#endif - -/// tuple_size and tuple_element check. -template <typename T> class is_tuple_like_ { - template <typename U> - static auto check(U* p) -> decltype(std::tuple_size<U>::value, int()); - template <typename> static void check(...); - - public: - static FMT_CONSTEXPR_DECL const bool value = - !std::is_void<decltype(check<T>(nullptr))>::value; -}; - -// Check for integer_sequence -#if defined(__cpp_lib_integer_sequence) || FMT_MSC_VER >= 1900 -template <typename T, T... N> -using integer_sequence = std::integer_sequence<T, N...>; + +template <typename RangeT, typename OutputIterator> +OutputIterator copy(const RangeT& range, OutputIterator out) { + for (auto it = range.begin(), end = range.end(); it != end; ++it) + *out++ = *it; + return out; +} + +template <typename OutputIterator> +OutputIterator copy(const char* str, OutputIterator out) { + while (*str) *out++ = *str++; + return out; +} + +template <typename OutputIterator> +OutputIterator copy(char ch, OutputIterator out) { + *out++ = ch; + return out; +} + +/// Return true value if T has std::string interface, like std::string_view. +template <typename T> class is_like_std_string { + template <typename U> + static auto check(U* p) + -> decltype((void)p->find('a'), p->length(), (void)p->data(), int()); + template <typename> static void check(...); + + public: + static FMT_CONSTEXPR_DECL const bool value = + is_string<T>::value || !std::is_void<decltype(check<T>(nullptr))>::value; +}; + +template <typename Char> +struct is_like_std_string<fmt::basic_string_view<Char>> : std::true_type {}; + +template <typename... Ts> struct conditional_helper {}; + +template <typename T, typename _ = void> struct is_range_ : std::false_type {}; + +#if !FMT_MSC_VER || FMT_MSC_VER > 1800 +template <typename T> +struct is_range_< + T, conditional_t<false, + conditional_helper<decltype(std::declval<T>().begin()), + decltype(std::declval<T>().end())>, + void>> : std::true_type {}; +#endif + +/// tuple_size and tuple_element check. +template <typename T> class is_tuple_like_ { + template <typename U> + static auto check(U* p) -> decltype(std::tuple_size<U>::value, int()); + template <typename> static void check(...); + + public: + static FMT_CONSTEXPR_DECL const bool value = + !std::is_void<decltype(check<T>(nullptr))>::value; +}; + +// Check for integer_sequence +#if defined(__cpp_lib_integer_sequence) || FMT_MSC_VER >= 1900 +template <typename T, T... N> +using integer_sequence = std::integer_sequence<T, N...>; template <size_t... N> using index_sequence = std::index_sequence<N...>; template <size_t N> using make_index_sequence = std::make_index_sequence<N>; -#else -template <typename T, T... N> struct integer_sequence { - using value_type = T; - +#else +template <typename T, T... N> struct integer_sequence { + using value_type = T; + static FMT_CONSTEXPR size_t size() { return sizeof...(N); } -}; - +}; + template <size_t... N> using index_sequence = integer_sequence<size_t, N...>; - + template <typename T, size_t N, T... Ns> -struct make_integer_sequence : make_integer_sequence<T, N - 1, N - 1, Ns...> {}; -template <typename T, T... Ns> -struct make_integer_sequence<T, 0, Ns...> : integer_sequence<T, Ns...> {}; - +struct make_integer_sequence : make_integer_sequence<T, N - 1, N - 1, Ns...> {}; +template <typename T, T... Ns> +struct make_integer_sequence<T, 0, Ns...> : integer_sequence<T, Ns...> {}; + template <size_t N> using make_index_sequence = make_integer_sequence<size_t, N>; -#endif - -template <class Tuple, class F, size_t... Is> -void for_each(index_sequence<Is...>, Tuple&& tup, F&& f) FMT_NOEXCEPT { - using std::get; - // using free function get<I>(T) now. - const int _[] = {0, ((void)f(get<Is>(tup)), 0)...}; - (void)_; // blocks warnings -} - -template <class T> -FMT_CONSTEXPR make_index_sequence<std::tuple_size<T>::value> get_indexes( - T const&) { - return {}; -} - -template <class Tuple, class F> void for_each(Tuple&& tup, F&& f) { - const auto indexes = get_indexes(tup); - for_each(indexes, std::forward<Tuple>(tup), std::forward<F>(f)); -} - +#endif + +template <class Tuple, class F, size_t... Is> +void for_each(index_sequence<Is...>, Tuple&& tup, F&& f) FMT_NOEXCEPT { + using std::get; + // using free function get<I>(T) now. + const int _[] = {0, ((void)f(get<Is>(tup)), 0)...}; + (void)_; // blocks warnings +} + +template <class T> +FMT_CONSTEXPR make_index_sequence<std::tuple_size<T>::value> get_indexes( + T const&) { + return {}; +} + +template <class Tuple, class F> void for_each(Tuple&& tup, F&& f) { + const auto indexes = get_indexes(tup); + for_each(indexes, std::forward<Tuple>(tup), std::forward<F>(f)); +} + template <typename Range> using value_type = remove_cvref_t<decltype(*std::declval<Range>().begin())>; -template <typename Arg, FMT_ENABLE_IF(!is_like_std_string< - typename std::decay<Arg>::type>::value)> -FMT_CONSTEXPR const char* format_str_quoted(bool add_space, const Arg&) { - return add_space ? " {}" : "{}"; -} - -template <typename Arg, FMT_ENABLE_IF(is_like_std_string< - typename std::decay<Arg>::type>::value)> -FMT_CONSTEXPR const char* format_str_quoted(bool add_space, const Arg&) { - return add_space ? " \"{}\"" : "\"{}\""; -} - -FMT_CONSTEXPR const char* format_str_quoted(bool add_space, const char*) { - return add_space ? " \"{}\"" : "\"{}\""; -} -FMT_CONSTEXPR const wchar_t* format_str_quoted(bool add_space, const wchar_t*) { - return add_space ? L" \"{}\"" : L"\"{}\""; -} - -FMT_CONSTEXPR const char* format_str_quoted(bool add_space, const char) { - return add_space ? " '{}'" : "'{}'"; -} -FMT_CONSTEXPR const wchar_t* format_str_quoted(bool add_space, const wchar_t) { - return add_space ? L" '{}'" : L"'{}'"; -} +template <typename Arg, FMT_ENABLE_IF(!is_like_std_string< + typename std::decay<Arg>::type>::value)> +FMT_CONSTEXPR const char* format_str_quoted(bool add_space, const Arg&) { + return add_space ? " {}" : "{}"; +} + +template <typename Arg, FMT_ENABLE_IF(is_like_std_string< + typename std::decay<Arg>::type>::value)> +FMT_CONSTEXPR const char* format_str_quoted(bool add_space, const Arg&) { + return add_space ? " \"{}\"" : "\"{}\""; +} + +FMT_CONSTEXPR const char* format_str_quoted(bool add_space, const char*) { + return add_space ? " \"{}\"" : "\"{}\""; +} +FMT_CONSTEXPR const wchar_t* format_str_quoted(bool add_space, const wchar_t*) { + return add_space ? L" \"{}\"" : L"\"{}\""; +} + +FMT_CONSTEXPR const char* format_str_quoted(bool add_space, const char) { + return add_space ? " '{}'" : "'{}'"; +} +FMT_CONSTEXPR const wchar_t* format_str_quoted(bool add_space, const wchar_t) { + return add_space ? L" '{}'" : L"'{}'"; +} } // namespace detail - -template <typename T> struct is_tuple_like { - static FMT_CONSTEXPR_DECL const bool value = + +template <typename T> struct is_tuple_like { + static FMT_CONSTEXPR_DECL const bool value = detail::is_tuple_like_<T>::value && !detail::is_range_<T>::value; -}; - -template <typename TupleT, typename Char> -struct formatter<TupleT, Char, enable_if_t<fmt::is_tuple_like<TupleT>::value>> { - private: - // C++11 generic lambda for format() - template <typename FormatContext> struct format_each { - template <typename T> void operator()(const T& v) { - if (i > 0) { - if (formatting.add_prepostfix_space) { - *out++ = ' '; - } +}; + +template <typename TupleT, typename Char> +struct formatter<TupleT, Char, enable_if_t<fmt::is_tuple_like<TupleT>::value>> { + private: + // C++11 generic lambda for format() + template <typename FormatContext> struct format_each { + template <typename T> void operator()(const T& v) { + if (i > 0) { + if (formatting.add_prepostfix_space) { + *out++ = ' '; + } out = detail::copy(formatting.delimiter, out); - } - out = format_to(out, + } + out = format_to(out, detail::format_str_quoted( - (formatting.add_delimiter_spaces && i > 0), v), - v); - ++i; - } - - formatting_tuple<Char>& formatting; + (formatting.add_delimiter_spaces && i > 0), v), + v); + ++i; + } + + formatting_tuple<Char>& formatting; size_t& i; - typename std::add_lvalue_reference<decltype( - std::declval<FormatContext>().out())>::type out; - }; - - public: - formatting_tuple<Char> formatting; - - template <typename ParseContext> - FMT_CONSTEXPR auto parse(ParseContext& ctx) -> decltype(ctx.begin()) { - return formatting.parse(ctx); - } - - template <typename FormatContext = format_context> - auto format(const TupleT& values, FormatContext& ctx) -> decltype(ctx.out()) { - auto out = ctx.out(); + typename std::add_lvalue_reference<decltype( + std::declval<FormatContext>().out())>::type out; + }; + + public: + formatting_tuple<Char> formatting; + + template <typename ParseContext> + FMT_CONSTEXPR auto parse(ParseContext& ctx) -> decltype(ctx.begin()) { + return formatting.parse(ctx); + } + + template <typename FormatContext = format_context> + auto format(const TupleT& values, FormatContext& ctx) -> decltype(ctx.out()) { + auto out = ctx.out(); size_t i = 0; detail::copy(formatting.prefix, out); - + detail::for_each(values, format_each<FormatContext>{formatting, i, out}); - if (formatting.add_prepostfix_space) { - *out++ = ' '; - } + if (formatting.add_prepostfix_space) { + *out++ = ' '; + } detail::copy(formatting.postfix, out); - - return ctx.out(); - } -}; - -template <typename T, typename Char> struct is_range { - static FMT_CONSTEXPR_DECL const bool value = + + return ctx.out(); + } +}; + +template <typename T, typename Char> struct is_range { + static FMT_CONSTEXPR_DECL const bool value = detail::is_range_<T>::value && !detail::is_like_std_string<T>::value && - !std::is_convertible<T, std::basic_string<Char>>::value && + !std::is_convertible<T, std::basic_string<Char>>::value && !std::is_constructible<detail::std_string_view<Char>, T>::value; -}; - +}; + template <typename T, typename Char> struct formatter< T, Char, @@ -260,137 +260,137 @@ struct formatter< format_context>::value) #endif >> { - formatting_range<Char> formatting; - - template <typename ParseContext> - FMT_CONSTEXPR auto parse(ParseContext& ctx) -> decltype(ctx.begin()) { - return formatting.parse(ctx); - } - - template <typename FormatContext> + formatting_range<Char> formatting; + + template <typename ParseContext> + FMT_CONSTEXPR auto parse(ParseContext& ctx) -> decltype(ctx.begin()) { + return formatting.parse(ctx); + } + + template <typename FormatContext> typename FormatContext::iterator format(const T& values, FormatContext& ctx) { auto out = detail::copy(formatting.prefix, ctx.out()); size_t i = 0; auto it = values.begin(); auto end = values.end(); for (; it != end; ++it) { - if (i > 0) { - if (formatting.add_prepostfix_space) *out++ = ' '; + if (i > 0) { + if (formatting.add_prepostfix_space) *out++ = ' '; out = detail::copy(formatting.delimiter, out); - } - out = format_to(out, + } + out = format_to(out, detail::format_str_quoted( - (formatting.add_delimiter_spaces && i > 0), *it), - *it); - if (++i > formatting.range_length_limit) { - out = format_to(out, " ... <other elements>"); - break; - } - } - if (formatting.add_prepostfix_space) *out++ = ' '; + (formatting.add_delimiter_spaces && i > 0), *it), + *it); + if (++i > formatting.range_length_limit) { + out = format_to(out, " ... <other elements>"); + break; + } + } + if (formatting.add_prepostfix_space) *out++ = ' '; return detail::copy(formatting.postfix, out); - } -}; - + } +}; + template <typename Char, typename... T> struct tuple_arg_join : detail::view { - const std::tuple<T...>& tuple; - basic_string_view<Char> sep; - - tuple_arg_join(const std::tuple<T...>& t, basic_string_view<Char> s) - : tuple{t}, sep{s} {} -}; - -template <typename Char, typename... T> -struct formatter<tuple_arg_join<Char, T...>, Char> { - template <typename ParseContext> - FMT_CONSTEXPR auto parse(ParseContext& ctx) -> decltype(ctx.begin()) { - return ctx.begin(); - } - - template <typename FormatContext> - typename FormatContext::iterator format( - const tuple_arg_join<Char, T...>& value, FormatContext& ctx) { + const std::tuple<T...>& tuple; + basic_string_view<Char> sep; + + tuple_arg_join(const std::tuple<T...>& t, basic_string_view<Char> s) + : tuple{t}, sep{s} {} +}; + +template <typename Char, typename... T> +struct formatter<tuple_arg_join<Char, T...>, Char> { + template <typename ParseContext> + FMT_CONSTEXPR auto parse(ParseContext& ctx) -> decltype(ctx.begin()) { + return ctx.begin(); + } + + template <typename FormatContext> + typename FormatContext::iterator format( + const tuple_arg_join<Char, T...>& value, FormatContext& ctx) { return format(value, ctx, detail::make_index_sequence<sizeof...(T)>{}); - } - - private: - template <typename FormatContext, size_t... N> - typename FormatContext::iterator format( - const tuple_arg_join<Char, T...>& value, FormatContext& ctx, + } + + private: + template <typename FormatContext, size_t... N> + typename FormatContext::iterator format( + const tuple_arg_join<Char, T...>& value, FormatContext& ctx, detail::index_sequence<N...>) { - return format_args(value, ctx, std::get<N>(value.tuple)...); - } - - template <typename FormatContext> - typename FormatContext::iterator format_args( - const tuple_arg_join<Char, T...>&, FormatContext& ctx) { - // NOTE: for compilers that support C++17, this empty function instantiation - // can be replaced with a constexpr branch in the variadic overload. - return ctx.out(); - } - - template <typename FormatContext, typename Arg, typename... Args> - typename FormatContext::iterator format_args( - const tuple_arg_join<Char, T...>& value, FormatContext& ctx, - const Arg& arg, const Args&... args) { - using base = formatter<typename std::decay<Arg>::type, Char>; - auto out = ctx.out(); - out = base{}.format(arg, ctx); - if (sizeof...(Args) > 0) { - out = std::copy(value.sep.begin(), value.sep.end(), out); - ctx.advance_to(out); - return format_args(value, ctx, args...); - } - return out; - } -}; - -/** - \rst - Returns an object that formats `tuple` with elements separated by `sep`. - - **Example**:: - - std::tuple<int, char> t = {1, 'a'}; - fmt::print("{}", fmt::join(t, ", ")); - // Output: "1, a" - \endrst - */ -template <typename... T> -FMT_CONSTEXPR tuple_arg_join<char, T...> join(const std::tuple<T...>& tuple, - string_view sep) { - return {tuple, sep}; -} - -template <typename... T> -FMT_CONSTEXPR tuple_arg_join<wchar_t, T...> join(const std::tuple<T...>& tuple, - wstring_view sep) { - return {tuple, sep}; -} - -/** - \rst - Returns an object that formats `initializer_list` with elements separated by - `sep`. - - **Example**:: - - fmt::print("{}", fmt::join({1, 2, 3}, ", ")); - // Output: "1, 2, 3" - \endrst - */ -template <typename T> + return format_args(value, ctx, std::get<N>(value.tuple)...); + } + + template <typename FormatContext> + typename FormatContext::iterator format_args( + const tuple_arg_join<Char, T...>&, FormatContext& ctx) { + // NOTE: for compilers that support C++17, this empty function instantiation + // can be replaced with a constexpr branch in the variadic overload. + return ctx.out(); + } + + template <typename FormatContext, typename Arg, typename... Args> + typename FormatContext::iterator format_args( + const tuple_arg_join<Char, T...>& value, FormatContext& ctx, + const Arg& arg, const Args&... args) { + using base = formatter<typename std::decay<Arg>::type, Char>; + auto out = ctx.out(); + out = base{}.format(arg, ctx); + if (sizeof...(Args) > 0) { + out = std::copy(value.sep.begin(), value.sep.end(), out); + ctx.advance_to(out); + return format_args(value, ctx, args...); + } + return out; + } +}; + +/** + \rst + Returns an object that formats `tuple` with elements separated by `sep`. + + **Example**:: + + std::tuple<int, char> t = {1, 'a'}; + fmt::print("{}", fmt::join(t, ", ")); + // Output: "1, a" + \endrst + */ +template <typename... T> +FMT_CONSTEXPR tuple_arg_join<char, T...> join(const std::tuple<T...>& tuple, + string_view sep) { + return {tuple, sep}; +} + +template <typename... T> +FMT_CONSTEXPR tuple_arg_join<wchar_t, T...> join(const std::tuple<T...>& tuple, + wstring_view sep) { + return {tuple, sep}; +} + +/** + \rst + Returns an object that formats `initializer_list` with elements separated by + `sep`. + + **Example**:: + + fmt::print("{}", fmt::join({1, 2, 3}, ", ")); + // Output: "1, 2, 3" + \endrst + */ +template <typename T> arg_join<const T*, const T*, char> join(std::initializer_list<T> list, string_view sep) { - return join(std::begin(list), std::end(list), sep); -} - -template <typename T> + return join(std::begin(list), std::end(list), sep); +} + +template <typename T> arg_join<const T*, const T*, wchar_t> join(std::initializer_list<T> list, wstring_view sep) { - return join(std::begin(list), std::end(list), sep); -} - -FMT_END_NAMESPACE - -#endif // FMT_RANGES_H_ + return join(std::begin(list), std::end(list), sep); +} + +FMT_END_NAMESPACE + +#endif // FMT_RANGES_H_ diff --git a/contrib/libs/fmt/src/format.cc b/contrib/libs/fmt/src/format.cc index 76ca91e7a9..6141d964a7 100644 --- a/contrib/libs/fmt/src/format.cc +++ b/contrib/libs/fmt/src/format.cc @@ -1,34 +1,34 @@ -// Formatting library for C++ -// -// Copyright (c) 2012 - 2016, Victor Zverovich -// All rights reserved. -// -// For the license information refer to format.h. - -#include "fmt/format-inl.h" - -FMT_BEGIN_NAMESPACE +// Formatting library for C++ +// +// Copyright (c) 2012 - 2016, Victor Zverovich +// All rights reserved. +// +// For the license information refer to format.h. + +#include "fmt/format-inl.h" + +FMT_BEGIN_NAMESPACE namespace detail { - -template <typename T> -int format_float(char* buf, std::size_t size, const char* format, int precision, - T value) { + +template <typename T> +int format_float(char* buf, std::size_t size, const char* format, int precision, + T value) { #ifdef FMT_FUZZ - if (precision > 100000) - throw std::runtime_error( - "fuzz mode - avoid large allocation inside snprintf"); -#endif - // Suppress the warning about nonliteral format string. - int (*snprintf_ptr)(char*, size_t, const char*, ...) = FMT_SNPRINTF; - return precision < 0 ? snprintf_ptr(buf, size, format, value) - : snprintf_ptr(buf, size, format, precision, value); -} - + if (precision > 100000) + throw std::runtime_error( + "fuzz mode - avoid large allocation inside snprintf"); +#endif + // Suppress the warning about nonliteral format string. + int (*snprintf_ptr)(char*, size_t, const char*, ...) = FMT_SNPRINTF; + return precision < 0 ? snprintf_ptr(buf, size, format, value) + : snprintf_ptr(buf, size, format, precision, value); +} + template FMT_API dragonbox::decimal_fp<float> dragonbox::to_decimal(float x) FMT_NOEXCEPT; template FMT_API dragonbox::decimal_fp<double> dragonbox::to_decimal(double x) FMT_NOEXCEPT; - + // DEPRECATED! This function exists for ABI compatibility. template <typename Char> typename basic_format_context<std::back_insert_iterator<buffer<Char>>, @@ -46,7 +46,7 @@ vformat_to(buffer<Char>& buf, basic_string_view<Char> format_str, format_handler<iterator, Char, context> h(out, format_str, args, {}); parse_format_string<false>(format_str, h); return out; -} +} template basic_format_context<std::back_insert_iterator<buffer<char>>, char>::iterator vformat_to(buffer<char>&, string_view, @@ -54,30 +54,30 @@ vformat_to(buffer<char>&, string_view, std::back_insert_iterator<buffer<type_identity_t<char>>>, type_identity_t<char>>>); } // namespace detail - + template struct FMT_INSTANTIATION_DEF_API detail::basic_data<void>; - -// Workaround a bug in MSVC2013 that prevents instantiation of format_float. + +// Workaround a bug in MSVC2013 that prevents instantiation of format_float. int (*instantiate_format_float)(double, int, detail::float_specs, detail::buffer<char>&) = detail::format_float; - -#ifndef FMT_STATIC_THOUSANDS_SEPARATOR + +#ifndef FMT_STATIC_THOUSANDS_SEPARATOR template FMT_API detail::locale_ref::locale_ref(const std::locale& loc); template FMT_API std::locale detail::locale_ref::get<std::locale>() const; -#endif - -// Explicit instantiations for char. - +#endif + +// Explicit instantiations for char. + template FMT_API std::string detail::grouping_impl<char>(locale_ref); template FMT_API char detail::thousands_sep_impl(locale_ref); template FMT_API char detail::decimal_point_impl(locale_ref); - + template FMT_API void detail::buffer<char>::append(const char*, const char*); - + template FMT_API void detail::vformat_to( detail::buffer<char>&, string_view, basic_format_args<FMT_BUFFER_CONTEXT(char)>, detail::locale_ref); - + template FMT_API int detail::snprintf_float(double, int, detail::float_specs, detail::buffer<char>&); template FMT_API int detail::snprintf_float(long double, int, @@ -87,13 +87,13 @@ template FMT_API int detail::format_float(double, int, detail::float_specs, detail::buffer<char>&); template FMT_API int detail::format_float(long double, int, detail::float_specs, detail::buffer<char>&); - -// Explicit instantiations for wchar_t. - + +// Explicit instantiations for wchar_t. + template FMT_API std::string detail::grouping_impl<wchar_t>(locale_ref); template FMT_API wchar_t detail::thousands_sep_impl(locale_ref); template FMT_API wchar_t detail::decimal_point_impl(locale_ref); - + template FMT_API void detail::buffer<wchar_t>::append(const wchar_t*, const wchar_t*); -FMT_END_NAMESPACE +FMT_END_NAMESPACE diff --git a/contrib/libs/fmt/src/os.cc b/contrib/libs/fmt/src/os.cc index 8c5552c750..6850024588 100644 --- a/contrib/libs/fmt/src/os.cc +++ b/contrib/libs/fmt/src/os.cc @@ -1,322 +1,322 @@ -// Formatting library for C++ - optional OS-specific functionality -// -// Copyright (c) 2012 - 2016, Victor Zverovich -// All rights reserved. -// -// For the license information refer to format.h. - -// Disable bogus MSVC warnings. -#if !defined(_CRT_SECURE_NO_WARNINGS) && defined(_MSC_VER) -# define _CRT_SECURE_NO_WARNINGS -#endif - -#include "fmt/os.h" - -#include <climits> - -#if FMT_USE_FCNTL -# include <sys/stat.h> -# include <sys/types.h> - -# ifndef _WIN32 -# include <unistd.h> -# else -# ifndef WIN32_LEAN_AND_MEAN -# define WIN32_LEAN_AND_MEAN -# endif -# include <io.h> -# include <windows.h> - -# define O_CREAT _O_CREAT -# define O_TRUNC _O_TRUNC - -# ifndef S_IRUSR -# define S_IRUSR _S_IREAD -# endif - -# ifndef S_IWUSR -# define S_IWUSR _S_IWRITE -# endif - -# ifdef __MINGW32__ -# define _SH_DENYNO 0x40 -# endif -# endif // _WIN32 -#endif // FMT_USE_FCNTL - -#ifdef _WIN32 -# include <windows.h> -#endif - -#ifdef fileno -# undef fileno -#endif - -namespace { -#ifdef _WIN32 -// Return type of read and write functions. -using RWResult = int; - -// On Windows the count argument to read and write is unsigned, so convert -// it from size_t preventing integer overflow. -inline unsigned convert_rwcount(std::size_t count) { - return count <= UINT_MAX ? static_cast<unsigned>(count) : UINT_MAX; -} +// Formatting library for C++ - optional OS-specific functionality +// +// Copyright (c) 2012 - 2016, Victor Zverovich +// All rights reserved. +// +// For the license information refer to format.h. + +// Disable bogus MSVC warnings. +#if !defined(_CRT_SECURE_NO_WARNINGS) && defined(_MSC_VER) +# define _CRT_SECURE_NO_WARNINGS +#endif + +#include "fmt/os.h" + +#include <climits> + +#if FMT_USE_FCNTL +# include <sys/stat.h> +# include <sys/types.h> + +# ifndef _WIN32 +# include <unistd.h> +# else +# ifndef WIN32_LEAN_AND_MEAN +# define WIN32_LEAN_AND_MEAN +# endif +# include <io.h> +# include <windows.h> + +# define O_CREAT _O_CREAT +# define O_TRUNC _O_TRUNC + +# ifndef S_IRUSR +# define S_IRUSR _S_IREAD +# endif + +# ifndef S_IWUSR +# define S_IWUSR _S_IWRITE +# endif + +# ifdef __MINGW32__ +# define _SH_DENYNO 0x40 +# endif +# endif // _WIN32 +#endif // FMT_USE_FCNTL + +#ifdef _WIN32 +# include <windows.h> +#endif + +#ifdef fileno +# undef fileno +#endif + +namespace { +#ifdef _WIN32 +// Return type of read and write functions. +using RWResult = int; + +// On Windows the count argument to read and write is unsigned, so convert +// it from size_t preventing integer overflow. +inline unsigned convert_rwcount(std::size_t count) { + return count <= UINT_MAX ? static_cast<unsigned>(count) : UINT_MAX; +} #elif FMT_USE_FCNTL -// Return type of read and write functions. -using RWResult = ssize_t; - -inline std::size_t convert_rwcount(std::size_t count) { return count; } -#endif -} // namespace - -FMT_BEGIN_NAMESPACE - -#ifdef _WIN32 +// Return type of read and write functions. +using RWResult = ssize_t; + +inline std::size_t convert_rwcount(std::size_t count) { return count; } +#endif +} // namespace + +FMT_BEGIN_NAMESPACE + +#ifdef _WIN32 detail::utf16_to_utf8::utf16_to_utf8(wstring_view s) { - if (int error_code = convert(s)) { - FMT_THROW(windows_error(error_code, - "cannot convert string from UTF-16 to UTF-8")); - } -} - + if (int error_code = convert(s)) { + FMT_THROW(windows_error(error_code, + "cannot convert string from UTF-16 to UTF-8")); + } +} + int detail::utf16_to_utf8::convert(wstring_view s) { - if (s.size() > INT_MAX) return ERROR_INVALID_PARAMETER; - int s_size = static_cast<int>(s.size()); - if (s_size == 0) { - // WideCharToMultiByte does not support zero length, handle separately. - buffer_.resize(1); - buffer_[0] = 0; - return 0; - } - - int length = WideCharToMultiByte(CP_UTF8, 0, s.data(), s_size, nullptr, 0, - nullptr, nullptr); - if (length == 0) return GetLastError(); - buffer_.resize(length + 1); - length = WideCharToMultiByte(CP_UTF8, 0, s.data(), s_size, &buffer_[0], - length, nullptr, nullptr); - if (length == 0) return GetLastError(); - buffer_[length] = 0; - return 0; -} - -void windows_error::init(int err_code, string_view format_str, - format_args args) { - error_code_ = err_code; - memory_buffer buffer; + if (s.size() > INT_MAX) return ERROR_INVALID_PARAMETER; + int s_size = static_cast<int>(s.size()); + if (s_size == 0) { + // WideCharToMultiByte does not support zero length, handle separately. + buffer_.resize(1); + buffer_[0] = 0; + return 0; + } + + int length = WideCharToMultiByte(CP_UTF8, 0, s.data(), s_size, nullptr, 0, + nullptr, nullptr); + if (length == 0) return GetLastError(); + buffer_.resize(length + 1); + length = WideCharToMultiByte(CP_UTF8, 0, s.data(), s_size, &buffer_[0], + length, nullptr, nullptr); + if (length == 0) return GetLastError(); + buffer_[length] = 0; + return 0; +} + +void windows_error::init(int err_code, string_view format_str, + format_args args) { + error_code_ = err_code; + memory_buffer buffer; detail::format_windows_error(buffer, err_code, vformat(format_str, args)); - std::runtime_error& base = *this; - base = std::runtime_error(to_string(buffer)); -} - + std::runtime_error& base = *this; + base = std::runtime_error(to_string(buffer)); +} + void detail::format_windows_error(detail::buffer<char>& out, int error_code, string_view message) FMT_NOEXCEPT { - FMT_TRY { - wmemory_buffer buf; - buf.resize(inline_buffer_size); - for (;;) { - wchar_t* system_message = &buf[0]; - int result = FormatMessageW( - FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, nullptr, - error_code, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), system_message, - static_cast<uint32_t>(buf.size()), nullptr); - if (result != 0) { - utf16_to_utf8 utf8_message; - if (utf8_message.convert(system_message) == ERROR_SUCCESS) { + FMT_TRY { + wmemory_buffer buf; + buf.resize(inline_buffer_size); + for (;;) { + wchar_t* system_message = &buf[0]; + int result = FormatMessageW( + FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, nullptr, + error_code, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), system_message, + static_cast<uint32_t>(buf.size()), nullptr); + if (result != 0) { + utf16_to_utf8 utf8_message; + if (utf8_message.convert(system_message) == ERROR_SUCCESS) { format_to(buffer_appender<char>(out), "{}: {}", message, utf8_message); - return; - } - break; - } - if (GetLastError() != ERROR_INSUFFICIENT_BUFFER) - break; // Can't get error message, report error code instead. - buf.resize(buf.size() * 2); - } - } - FMT_CATCH(...) {} - format_error_code(out, error_code, message); -} - -void report_windows_error(int error_code, - fmt::string_view message) FMT_NOEXCEPT { + return; + } + break; + } + if (GetLastError() != ERROR_INSUFFICIENT_BUFFER) + break; // Can't get error message, report error code instead. + buf.resize(buf.size() * 2); + } + } + FMT_CATCH(...) {} + format_error_code(out, error_code, message); +} + +void report_windows_error(int error_code, + fmt::string_view message) FMT_NOEXCEPT { report_error(detail::format_windows_error, error_code, message); -} -#endif // _WIN32 - -buffered_file::~buffered_file() FMT_NOEXCEPT { - if (file_ && FMT_SYSTEM(fclose(file_)) != 0) - report_system_error(errno, "cannot close file"); -} - -buffered_file::buffered_file(cstring_view filename, cstring_view mode) { - FMT_RETRY_VAL(file_, FMT_SYSTEM(fopen(filename.c_str(), mode.c_str())), - nullptr); - if (!file_) - FMT_THROW(system_error(errno, "cannot open file {}", filename.c_str())); -} - -void buffered_file::close() { - if (!file_) return; - int result = FMT_SYSTEM(fclose(file_)); - file_ = nullptr; - if (result != 0) FMT_THROW(system_error(errno, "cannot close file")); -} - -// A macro used to prevent expansion of fileno on broken versions of MinGW. -#define FMT_ARGS - -int buffered_file::fileno() const { - int fd = FMT_POSIX_CALL(fileno FMT_ARGS(file_)); - if (fd == -1) FMT_THROW(system_error(errno, "cannot get file descriptor")); - return fd; -} - -#if FMT_USE_FCNTL -file::file(cstring_view path, int oflag) { - int mode = S_IRUSR | S_IWUSR; -# if defined(_WIN32) && !defined(__MINGW32__) - fd_ = -1; - FMT_POSIX_CALL(sopen_s(&fd_, path.c_str(), oflag, _SH_DENYNO, mode)); -# else - FMT_RETRY(fd_, FMT_POSIX_CALL(open(path.c_str(), oflag, mode))); -# endif - if (fd_ == -1) - FMT_THROW(system_error(errno, "cannot open file {}", path.c_str())); -} - -file::~file() FMT_NOEXCEPT { - // Don't retry close in case of EINTR! - // See http://linux.derkeiler.com/Mailing-Lists/Kernel/2005-09/3000.html - if (fd_ != -1 && FMT_POSIX_CALL(close(fd_)) != 0) - report_system_error(errno, "cannot close file"); -} - -void file::close() { - if (fd_ == -1) return; - // Don't retry close in case of EINTR! - // See http://linux.derkeiler.com/Mailing-Lists/Kernel/2005-09/3000.html - int result = FMT_POSIX_CALL(close(fd_)); - fd_ = -1; - if (result != 0) FMT_THROW(system_error(errno, "cannot close file")); -} - -long long file::size() const { -# ifdef _WIN32 - // Use GetFileSize instead of GetFileSizeEx for the case when _WIN32_WINNT - // is less than 0x0500 as is the case with some default MinGW builds. - // Both functions support large file sizes. - DWORD size_upper = 0; - HANDLE handle = reinterpret_cast<HANDLE>(_get_osfhandle(fd_)); - DWORD size_lower = FMT_SYSTEM(GetFileSize(handle, &size_upper)); - if (size_lower == INVALID_FILE_SIZE) { - DWORD error = GetLastError(); - if (error != NO_ERROR) - FMT_THROW(windows_error(GetLastError(), "cannot get file size")); - } - unsigned long long long_size = size_upper; - return (long_size << sizeof(DWORD) * CHAR_BIT) | size_lower; -# else - using Stat = struct stat; - Stat file_stat = Stat(); - if (FMT_POSIX_CALL(fstat(fd_, &file_stat)) == -1) - FMT_THROW(system_error(errno, "cannot get file attributes")); - static_assert(sizeof(long long) >= sizeof(file_stat.st_size), - "return type of file::size is not large enough"); - return file_stat.st_size; -# endif -} - -std::size_t file::read(void* buffer, std::size_t count) { - RWResult result = 0; - FMT_RETRY(result, FMT_POSIX_CALL(read(fd_, buffer, convert_rwcount(count)))); - if (result < 0) FMT_THROW(system_error(errno, "cannot read from file")); +} +#endif // _WIN32 + +buffered_file::~buffered_file() FMT_NOEXCEPT { + if (file_ && FMT_SYSTEM(fclose(file_)) != 0) + report_system_error(errno, "cannot close file"); +} + +buffered_file::buffered_file(cstring_view filename, cstring_view mode) { + FMT_RETRY_VAL(file_, FMT_SYSTEM(fopen(filename.c_str(), mode.c_str())), + nullptr); + if (!file_) + FMT_THROW(system_error(errno, "cannot open file {}", filename.c_str())); +} + +void buffered_file::close() { + if (!file_) return; + int result = FMT_SYSTEM(fclose(file_)); + file_ = nullptr; + if (result != 0) FMT_THROW(system_error(errno, "cannot close file")); +} + +// A macro used to prevent expansion of fileno on broken versions of MinGW. +#define FMT_ARGS + +int buffered_file::fileno() const { + int fd = FMT_POSIX_CALL(fileno FMT_ARGS(file_)); + if (fd == -1) FMT_THROW(system_error(errno, "cannot get file descriptor")); + return fd; +} + +#if FMT_USE_FCNTL +file::file(cstring_view path, int oflag) { + int mode = S_IRUSR | S_IWUSR; +# if defined(_WIN32) && !defined(__MINGW32__) + fd_ = -1; + FMT_POSIX_CALL(sopen_s(&fd_, path.c_str(), oflag, _SH_DENYNO, mode)); +# else + FMT_RETRY(fd_, FMT_POSIX_CALL(open(path.c_str(), oflag, mode))); +# endif + if (fd_ == -1) + FMT_THROW(system_error(errno, "cannot open file {}", path.c_str())); +} + +file::~file() FMT_NOEXCEPT { + // Don't retry close in case of EINTR! + // See http://linux.derkeiler.com/Mailing-Lists/Kernel/2005-09/3000.html + if (fd_ != -1 && FMT_POSIX_CALL(close(fd_)) != 0) + report_system_error(errno, "cannot close file"); +} + +void file::close() { + if (fd_ == -1) return; + // Don't retry close in case of EINTR! + // See http://linux.derkeiler.com/Mailing-Lists/Kernel/2005-09/3000.html + int result = FMT_POSIX_CALL(close(fd_)); + fd_ = -1; + if (result != 0) FMT_THROW(system_error(errno, "cannot close file")); +} + +long long file::size() const { +# ifdef _WIN32 + // Use GetFileSize instead of GetFileSizeEx for the case when _WIN32_WINNT + // is less than 0x0500 as is the case with some default MinGW builds. + // Both functions support large file sizes. + DWORD size_upper = 0; + HANDLE handle = reinterpret_cast<HANDLE>(_get_osfhandle(fd_)); + DWORD size_lower = FMT_SYSTEM(GetFileSize(handle, &size_upper)); + if (size_lower == INVALID_FILE_SIZE) { + DWORD error = GetLastError(); + if (error != NO_ERROR) + FMT_THROW(windows_error(GetLastError(), "cannot get file size")); + } + unsigned long long long_size = size_upper; + return (long_size << sizeof(DWORD) * CHAR_BIT) | size_lower; +# else + using Stat = struct stat; + Stat file_stat = Stat(); + if (FMT_POSIX_CALL(fstat(fd_, &file_stat)) == -1) + FMT_THROW(system_error(errno, "cannot get file attributes")); + static_assert(sizeof(long long) >= sizeof(file_stat.st_size), + "return type of file::size is not large enough"); + return file_stat.st_size; +# endif +} + +std::size_t file::read(void* buffer, std::size_t count) { + RWResult result = 0; + FMT_RETRY(result, FMT_POSIX_CALL(read(fd_, buffer, convert_rwcount(count)))); + if (result < 0) FMT_THROW(system_error(errno, "cannot read from file")); return detail::to_unsigned(result); -} - -std::size_t file::write(const void* buffer, std::size_t count) { - RWResult result = 0; - FMT_RETRY(result, FMT_POSIX_CALL(write(fd_, buffer, convert_rwcount(count)))); - if (result < 0) FMT_THROW(system_error(errno, "cannot write to file")); +} + +std::size_t file::write(const void* buffer, std::size_t count) { + RWResult result = 0; + FMT_RETRY(result, FMT_POSIX_CALL(write(fd_, buffer, convert_rwcount(count)))); + if (result < 0) FMT_THROW(system_error(errno, "cannot write to file")); return detail::to_unsigned(result); -} - -file file::dup(int fd) { - // Don't retry as dup doesn't return EINTR. - // http://pubs.opengroup.org/onlinepubs/009695399/functions/dup.html - int new_fd = FMT_POSIX_CALL(dup(fd)); - if (new_fd == -1) - FMT_THROW(system_error(errno, "cannot duplicate file descriptor {}", fd)); - return file(new_fd); -} - -void file::dup2(int fd) { - int result = 0; - FMT_RETRY(result, FMT_POSIX_CALL(dup2(fd_, fd))); - if (result == -1) { - FMT_THROW(system_error(errno, "cannot duplicate file descriptor {} to {}", - fd_, fd)); - } -} - -void file::dup2(int fd, error_code& ec) FMT_NOEXCEPT { - int result = 0; - FMT_RETRY(result, FMT_POSIX_CALL(dup2(fd_, fd))); - if (result == -1) ec = error_code(errno); -} - -void file::pipe(file& read_end, file& write_end) { - // Close the descriptors first to make sure that assignments don't throw - // and there are no leaks. - read_end.close(); - write_end.close(); - int fds[2] = {}; -# ifdef _WIN32 - // Make the default pipe capacity same as on Linux 2.6.11+. - enum { DEFAULT_CAPACITY = 65536 }; - int result = FMT_POSIX_CALL(pipe(fds, DEFAULT_CAPACITY, _O_BINARY)); -# else - // Don't retry as the pipe function doesn't return EINTR. - // http://pubs.opengroup.org/onlinepubs/009696799/functions/pipe.html - int result = FMT_POSIX_CALL(pipe(fds)); -# endif - if (result != 0) FMT_THROW(system_error(errno, "cannot create pipe")); - // The following assignments don't throw because read_fd and write_fd - // are closed. - read_end = file(fds[0]); - write_end = file(fds[1]); -} - -buffered_file file::fdopen(const char* mode) { +} + +file file::dup(int fd) { + // Don't retry as dup doesn't return EINTR. + // http://pubs.opengroup.org/onlinepubs/009695399/functions/dup.html + int new_fd = FMT_POSIX_CALL(dup(fd)); + if (new_fd == -1) + FMT_THROW(system_error(errno, "cannot duplicate file descriptor {}", fd)); + return file(new_fd); +} + +void file::dup2(int fd) { + int result = 0; + FMT_RETRY(result, FMT_POSIX_CALL(dup2(fd_, fd))); + if (result == -1) { + FMT_THROW(system_error(errno, "cannot duplicate file descriptor {} to {}", + fd_, fd)); + } +} + +void file::dup2(int fd, error_code& ec) FMT_NOEXCEPT { + int result = 0; + FMT_RETRY(result, FMT_POSIX_CALL(dup2(fd_, fd))); + if (result == -1) ec = error_code(errno); +} + +void file::pipe(file& read_end, file& write_end) { + // Close the descriptors first to make sure that assignments don't throw + // and there are no leaks. + read_end.close(); + write_end.close(); + int fds[2] = {}; +# ifdef _WIN32 + // Make the default pipe capacity same as on Linux 2.6.11+. + enum { DEFAULT_CAPACITY = 65536 }; + int result = FMT_POSIX_CALL(pipe(fds, DEFAULT_CAPACITY, _O_BINARY)); +# else + // Don't retry as the pipe function doesn't return EINTR. + // http://pubs.opengroup.org/onlinepubs/009696799/functions/pipe.html + int result = FMT_POSIX_CALL(pipe(fds)); +# endif + if (result != 0) FMT_THROW(system_error(errno, "cannot create pipe")); + // The following assignments don't throw because read_fd and write_fd + // are closed. + read_end = file(fds[0]); + write_end = file(fds[1]); +} + +buffered_file file::fdopen(const char* mode) { // Don't retry as fdopen doesn't return EINTR. # if defined(__MINGW32__) && defined(_POSIX_) FILE* f = ::fdopen(fd_, mode); # else - FILE* f = FMT_POSIX_CALL(fdopen(fd_, mode)); + FILE* f = FMT_POSIX_CALL(fdopen(fd_, mode)); +# endif + if (!f) + FMT_THROW( + system_error(errno, "cannot associate stream with file descriptor")); + buffered_file bf(f); + fd_ = -1; + return bf; +} + +long getpagesize() { +# ifdef _WIN32 + SYSTEM_INFO si; + GetSystemInfo(&si); + return si.dwPageSize; +# else + long size = FMT_POSIX_CALL(sysconf(_SC_PAGESIZE)); + if (size < 0) FMT_THROW(system_error(errno, "cannot get memory page size")); + return size; # endif - if (!f) - FMT_THROW( - system_error(errno, "cannot associate stream with file descriptor")); - buffered_file bf(f); - fd_ = -1; - return bf; -} - -long getpagesize() { -# ifdef _WIN32 - SYSTEM_INFO si; - GetSystemInfo(&si); - return si.dwPageSize; -# else - long size = FMT_POSIX_CALL(sysconf(_SC_PAGESIZE)); - if (size < 0) FMT_THROW(system_error(errno, "cannot get memory page size")); - return size; -# endif -} +} FMT_API void ostream::grow(size_t) { if (this->size() == this->capacity()) flush(); } -#endif // FMT_USE_FCNTL -FMT_END_NAMESPACE +#endif // FMT_USE_FCNTL +FMT_END_NAMESPACE diff --git a/contrib/libs/fmt/test/assert-test.cc b/contrib/libs/fmt/test/assert-test.cc index 41fb29a92f..73f622e56b 100644 --- a/contrib/libs/fmt/test/assert-test.cc +++ b/contrib/libs/fmt/test/assert-test.cc @@ -1,32 +1,32 @@ // Formatting library for C++ - FMT_ASSERT test -// +// // It is a separate test to minimize the number of EXPECT_DEBUG_DEATH checks // which are slow on some platforms. In other tests FMT_ASSERT is made to throw // an exception which is much faster and easier to check. // -// Copyright (c) 2012 - present, Victor Zverovich -// All rights reserved. -// -// For the license information refer to format.h. - -#include "fmt/core.h" -#include <gtest/gtest.h> - -TEST(AssertTest, Fail) { -#if GTEST_HAS_DEATH_TEST - EXPECT_DEBUG_DEATH(FMT_ASSERT(false, "don't panic!"), "don't panic!"); -#else - fmt::print("warning: death tests are not supported\n"); -#endif -} - -bool test_condition = false; - -TEST(AssertTest, DanglingElse) { - bool executed_else = false; - if (test_condition) - FMT_ASSERT(true, ""); - else - executed_else = true; - EXPECT_TRUE(executed_else); -} +// Copyright (c) 2012 - present, Victor Zverovich +// All rights reserved. +// +// For the license information refer to format.h. + +#include "fmt/core.h" +#include <gtest/gtest.h> + +TEST(AssertTest, Fail) { +#if GTEST_HAS_DEATH_TEST + EXPECT_DEBUG_DEATH(FMT_ASSERT(false, "don't panic!"), "don't panic!"); +#else + fmt::print("warning: death tests are not supported\n"); +#endif +} + +bool test_condition = false; + +TEST(AssertTest, DanglingElse) { + bool executed_else = false; + if (test_condition) + FMT_ASSERT(true, ""); + else + executed_else = true; + EXPECT_TRUE(executed_else); +} diff --git a/contrib/libs/fmt/test/assert-test/ya.make b/contrib/libs/fmt/test/assert-test/ya.make index e861be6557..22d19ae00a 100644 --- a/contrib/libs/fmt/test/assert-test/ya.make +++ b/contrib/libs/fmt/test/assert-test/ya.make @@ -1,37 +1,37 @@ -# Generated by devtools/yamaker. - +# Generated by devtools/yamaker. + GTEST() - + WITHOUT_LICENSE_TEXTS() - + OWNER( orivej g:cpp-contrib ) -LICENSE(MIT) - -PEERDIR( - contrib/libs/fmt - contrib/libs/fmt/test -) - -NO_COMPILER_WARNINGS() - -NO_UTIL() - -CFLAGS( - -DFMT_LOCALE - -DFMT_SHARED - -DGTEST_HAS_STD_WSTRING=1 - -DGTEST_LANG_CXX11=0 - -D_SILENCE_TR1_NAMESPACE_DEPRECATION_WARNING=1 -) - -SRCDIR(contrib/libs/fmt/test) - -SRCS( - assert-test.cc -) - -END() +LICENSE(MIT) + +PEERDIR( + contrib/libs/fmt + contrib/libs/fmt/test +) + +NO_COMPILER_WARNINGS() + +NO_UTIL() + +CFLAGS( + -DFMT_LOCALE + -DFMT_SHARED + -DGTEST_HAS_STD_WSTRING=1 + -DGTEST_LANG_CXX11=0 + -D_SILENCE_TR1_NAMESPACE_DEPRECATION_WARNING=1 +) + +SRCDIR(contrib/libs/fmt/test) + +SRCS( + assert-test.cc +) + +END() diff --git a/contrib/libs/fmt/test/chrono-test.cc b/contrib/libs/fmt/test/chrono-test.cc index eb132ef95e..fa383c1446 100644 --- a/contrib/libs/fmt/test/chrono-test.cc +++ b/contrib/libs/fmt/test/chrono-test.cc @@ -1,100 +1,100 @@ -// Formatting library for C++ - time formatting tests -// -// Copyright (c) 2012 - present, Victor Zverovich -// All rights reserved. -// -// For the license information refer to format.h. - -#ifdef WIN32 -# define _CRT_SECURE_NO_WARNINGS -#endif - -#include "fmt/chrono.h" - -#include <iomanip> - +// Formatting library for C++ - time formatting tests +// +// Copyright (c) 2012 - present, Victor Zverovich +// All rights reserved. +// +// For the license information refer to format.h. + +#ifdef WIN32 +# define _CRT_SECURE_NO_WARNINGS +#endif + +#include "fmt/chrono.h" + +#include <iomanip> + #include "gtest-extra.h" -std::tm make_tm() { - auto time = std::tm(); - time.tm_mday = 1; - return time; -} - -std::tm make_hour(int h) { - auto time = make_tm(); - time.tm_hour = h; - return time; -} - -std::tm make_minute(int m) { - auto time = make_tm(); - time.tm_min = m; - return time; -} - -std::tm make_second(int s) { - auto time = make_tm(); - time.tm_sec = s; - return time; -} - -std::string format_tm(const std::tm& time, const char* spec, - const std::locale& loc) { - auto& facet = std::use_facet<std::time_put<char>>(loc); - std::ostringstream os; - os.imbue(loc); - facet.put(os, os, ' ', &time, spec, spec + std::strlen(spec)); - return os.str(); -} - -TEST(TimeTest, Format) { - std::tm tm = std::tm(); - tm.tm_year = 116; - tm.tm_mon = 3; - tm.tm_mday = 25; - EXPECT_EQ("The date is 2016-04-25.", - fmt::format("The date is {:%Y-%m-%d}.", tm)); -} - -TEST(TimeTest, GrowBuffer) { - std::string s = "{:"; - for (int i = 0; i < 30; ++i) s += "%c"; - s += "}\n"; - std::time_t t = std::time(nullptr); - fmt::format(s, *std::localtime(&t)); -} - -TEST(TimeTest, FormatToEmptyContainer) { - std::string s; - auto time = std::tm(); - time.tm_sec = 42; - fmt::format_to(std::back_inserter(s), "{:%S}", time); - EXPECT_EQ(s, "42"); -} - -TEST(TimeTest, EmptyResult) { EXPECT_EQ("", fmt::format("{}", std::tm())); } - -static bool EqualTime(const std::tm& lhs, const std::tm& rhs) { - return lhs.tm_sec == rhs.tm_sec && lhs.tm_min == rhs.tm_min && - lhs.tm_hour == rhs.tm_hour && lhs.tm_mday == rhs.tm_mday && - lhs.tm_mon == rhs.tm_mon && lhs.tm_year == rhs.tm_year && - lhs.tm_wday == rhs.tm_wday && lhs.tm_yday == rhs.tm_yday && - lhs.tm_isdst == rhs.tm_isdst; -} - -TEST(TimeTest, LocalTime) { - std::time_t t = std::time(nullptr); - std::tm tm = *std::localtime(&t); - EXPECT_TRUE(EqualTime(tm, fmt::localtime(t))); -} - -TEST(TimeTest, GMTime) { - std::time_t t = std::time(nullptr); - std::tm tm = *std::gmtime(&t); - EXPECT_TRUE(EqualTime(tm, fmt::gmtime(t))); -} - +std::tm make_tm() { + auto time = std::tm(); + time.tm_mday = 1; + return time; +} + +std::tm make_hour(int h) { + auto time = make_tm(); + time.tm_hour = h; + return time; +} + +std::tm make_minute(int m) { + auto time = make_tm(); + time.tm_min = m; + return time; +} + +std::tm make_second(int s) { + auto time = make_tm(); + time.tm_sec = s; + return time; +} + +std::string format_tm(const std::tm& time, const char* spec, + const std::locale& loc) { + auto& facet = std::use_facet<std::time_put<char>>(loc); + std::ostringstream os; + os.imbue(loc); + facet.put(os, os, ' ', &time, spec, spec + std::strlen(spec)); + return os.str(); +} + +TEST(TimeTest, Format) { + std::tm tm = std::tm(); + tm.tm_year = 116; + tm.tm_mon = 3; + tm.tm_mday = 25; + EXPECT_EQ("The date is 2016-04-25.", + fmt::format("The date is {:%Y-%m-%d}.", tm)); +} + +TEST(TimeTest, GrowBuffer) { + std::string s = "{:"; + for (int i = 0; i < 30; ++i) s += "%c"; + s += "}\n"; + std::time_t t = std::time(nullptr); + fmt::format(s, *std::localtime(&t)); +} + +TEST(TimeTest, FormatToEmptyContainer) { + std::string s; + auto time = std::tm(); + time.tm_sec = 42; + fmt::format_to(std::back_inserter(s), "{:%S}", time); + EXPECT_EQ(s, "42"); +} + +TEST(TimeTest, EmptyResult) { EXPECT_EQ("", fmt::format("{}", std::tm())); } + +static bool EqualTime(const std::tm& lhs, const std::tm& rhs) { + return lhs.tm_sec == rhs.tm_sec && lhs.tm_min == rhs.tm_min && + lhs.tm_hour == rhs.tm_hour && lhs.tm_mday == rhs.tm_mday && + lhs.tm_mon == rhs.tm_mon && lhs.tm_year == rhs.tm_year && + lhs.tm_wday == rhs.tm_wday && lhs.tm_yday == rhs.tm_yday && + lhs.tm_isdst == rhs.tm_isdst; +} + +TEST(TimeTest, LocalTime) { + std::time_t t = std::time(nullptr); + std::tm tm = *std::localtime(&t); + EXPECT_TRUE(EqualTime(tm, fmt::localtime(t))); +} + +TEST(TimeTest, GMTime) { + std::time_t t = std::time(nullptr); + std::tm tm = *std::gmtime(&t); + EXPECT_TRUE(EqualTime(tm, fmt::gmtime(t))); +} + TEST(TimeTest, TimePoint) { std::chrono::system_clock::time_point point = std::chrono::system_clock::now(); @@ -106,293 +106,293 @@ TEST(TimeTest, TimePoint) { EXPECT_EQ(strftime_output, fmt::format("It is {:%Y-%m-%d %H:%M:%S}", point)); } -#define EXPECT_TIME(spec, time, duration) \ - { \ - std::locale loc("ja_JP.utf8"); \ - EXPECT_EQ(format_tm(time, spec, loc), \ - fmt::format(loc, "{:" spec "}", duration)); \ - } - -#ifndef FMT_STATIC_THOUSANDS_SEPARATOR - -TEST(ChronoTest, FormatDefault) { - EXPECT_EQ("42s", fmt::format("{}", std::chrono::seconds(42))); - EXPECT_EQ("42as", - fmt::format("{}", std::chrono::duration<int, std::atto>(42))); - EXPECT_EQ("42fs", - fmt::format("{}", std::chrono::duration<int, std::femto>(42))); - EXPECT_EQ("42ps", - fmt::format("{}", std::chrono::duration<int, std::pico>(42))); - EXPECT_EQ("42ns", fmt::format("{}", std::chrono::nanoseconds(42))); - EXPECT_EQ("42µs", fmt::format("{}", std::chrono::microseconds(42))); - EXPECT_EQ("42ms", fmt::format("{}", std::chrono::milliseconds(42))); - EXPECT_EQ("42cs", - fmt::format("{}", std::chrono::duration<int, std::centi>(42))); - EXPECT_EQ("42ds", - fmt::format("{}", std::chrono::duration<int, std::deci>(42))); - EXPECT_EQ("42s", fmt::format("{}", std::chrono::seconds(42))); - EXPECT_EQ("42das", - fmt::format("{}", std::chrono::duration<int, std::deca>(42))); - EXPECT_EQ("42hs", - fmt::format("{}", std::chrono::duration<int, std::hecto>(42))); - EXPECT_EQ("42ks", - fmt::format("{}", std::chrono::duration<int, std::kilo>(42))); - EXPECT_EQ("42Ms", - fmt::format("{}", std::chrono::duration<int, std::mega>(42))); - EXPECT_EQ("42Gs", - fmt::format("{}", std::chrono::duration<int, std::giga>(42))); - EXPECT_EQ("42Ts", - fmt::format("{}", std::chrono::duration<int, std::tera>(42))); - EXPECT_EQ("42Ps", - fmt::format("{}", std::chrono::duration<int, std::peta>(42))); - EXPECT_EQ("42Es", - fmt::format("{}", std::chrono::duration<int, std::exa>(42))); - EXPECT_EQ("42m", fmt::format("{}", std::chrono::minutes(42))); - EXPECT_EQ("42h", fmt::format("{}", std::chrono::hours(42))); - EXPECT_EQ( - "42[15]s", - fmt::format("{}", std::chrono::duration<int, std::ratio<15, 1>>(42))); - EXPECT_EQ( - "42[15/4]s", - fmt::format("{}", std::chrono::duration<int, std::ratio<15, 4>>(42))); -} - -TEST(ChronoTest, FormatWide) { - EXPECT_EQ(L"42s", fmt::format(L"{}", std::chrono::seconds(42))); - EXPECT_EQ(L"42as", - fmt::format(L"{}", std::chrono::duration<int, std::atto>(42))); - EXPECT_EQ(L"42fs", - fmt::format(L"{}", std::chrono::duration<int, std::femto>(42))); - EXPECT_EQ(L"42ps", - fmt::format(L"{}", std::chrono::duration<int, std::pico>(42))); - EXPECT_EQ(L"42ns", fmt::format(L"{}", std::chrono::nanoseconds(42))); - EXPECT_EQ(L"42\u00B5s", fmt::format(L"{}", std::chrono::microseconds(42))); - EXPECT_EQ(L"42ms", fmt::format(L"{}", std::chrono::milliseconds(42))); - EXPECT_EQ(L"42cs", - fmt::format(L"{}", std::chrono::duration<int, std::centi>(42))); - EXPECT_EQ(L"42ds", - fmt::format(L"{}", std::chrono::duration<int, std::deci>(42))); - EXPECT_EQ(L"42s", fmt::format(L"{}", std::chrono::seconds(42))); - EXPECT_EQ(L"42das", - fmt::format(L"{}", std::chrono::duration<int, std::deca>(42))); - EXPECT_EQ(L"42hs", - fmt::format(L"{}", std::chrono::duration<int, std::hecto>(42))); - EXPECT_EQ(L"42ks", - fmt::format(L"{}", std::chrono::duration<int, std::kilo>(42))); - EXPECT_EQ(L"42Ms", - fmt::format(L"{}", std::chrono::duration<int, std::mega>(42))); - EXPECT_EQ(L"42Gs", - fmt::format(L"{}", std::chrono::duration<int, std::giga>(42))); - EXPECT_EQ(L"42Ts", - fmt::format(L"{}", std::chrono::duration<int, std::tera>(42))); - EXPECT_EQ(L"42Ps", - fmt::format(L"{}", std::chrono::duration<int, std::peta>(42))); - EXPECT_EQ(L"42Es", - fmt::format(L"{}", std::chrono::duration<int, std::exa>(42))); - EXPECT_EQ(L"42m", fmt::format(L"{}", std::chrono::minutes(42))); - EXPECT_EQ(L"42h", fmt::format(L"{}", std::chrono::hours(42))); - EXPECT_EQ( - L"42[15]s", - fmt::format(L"{}", std::chrono::duration<int, std::ratio<15, 1>>(42))); - EXPECT_EQ( - L"42[15/4]s", - fmt::format(L"{}", std::chrono::duration<int, std::ratio<15, 4>>(42))); -} - -TEST(ChronoTest, Align) { - auto s = std::chrono::seconds(42); - EXPECT_EQ("42s ", fmt::format("{:5}", s)); - EXPECT_EQ("42s ", fmt::format("{:{}}", s, 5)); - EXPECT_EQ(" 42s", fmt::format("{:>5}", s)); - EXPECT_EQ("**42s**", fmt::format("{:*^7}", s)); - EXPECT_EQ("03:25:45 ", - fmt::format("{:12%H:%M:%S}", std::chrono::seconds(12345))); - EXPECT_EQ(" 03:25:45", - fmt::format("{:>12%H:%M:%S}", std::chrono::seconds(12345))); - EXPECT_EQ("~~03:25:45~~", - fmt::format("{:~^12%H:%M:%S}", std::chrono::seconds(12345))); - EXPECT_EQ("03:25:45 ", - fmt::format("{:{}%H:%M:%S}", std::chrono::seconds(12345), 12)); -} - -TEST(ChronoTest, FormatSpecs) { - EXPECT_EQ("%", fmt::format("{:%%}", std::chrono::seconds(0))); - EXPECT_EQ("\n", fmt::format("{:%n}", std::chrono::seconds(0))); - EXPECT_EQ("\t", fmt::format("{:%t}", std::chrono::seconds(0))); - EXPECT_EQ("00", fmt::format("{:%S}", std::chrono::seconds(0))); - EXPECT_EQ("00", fmt::format("{:%S}", std::chrono::seconds(60))); - EXPECT_EQ("42", fmt::format("{:%S}", std::chrono::seconds(42))); - EXPECT_EQ("01.234", fmt::format("{:%S}", std::chrono::milliseconds(1234))); - EXPECT_EQ("00", fmt::format("{:%M}", std::chrono::minutes(0))); - EXPECT_EQ("00", fmt::format("{:%M}", std::chrono::minutes(60))); - EXPECT_EQ("42", fmt::format("{:%M}", std::chrono::minutes(42))); - EXPECT_EQ("01", fmt::format("{:%M}", std::chrono::seconds(61))); - EXPECT_EQ("00", fmt::format("{:%H}", std::chrono::hours(0))); - EXPECT_EQ("00", fmt::format("{:%H}", std::chrono::hours(24))); - EXPECT_EQ("14", fmt::format("{:%H}", std::chrono::hours(14))); - EXPECT_EQ("01", fmt::format("{:%H}", std::chrono::minutes(61))); - EXPECT_EQ("12", fmt::format("{:%I}", std::chrono::hours(0))); - EXPECT_EQ("12", fmt::format("{:%I}", std::chrono::hours(12))); - EXPECT_EQ("12", fmt::format("{:%I}", std::chrono::hours(24))); - EXPECT_EQ("04", fmt::format("{:%I}", std::chrono::hours(4))); - EXPECT_EQ("02", fmt::format("{:%I}", std::chrono::hours(14))); - EXPECT_EQ("03:25:45", - fmt::format("{:%H:%M:%S}", std::chrono::seconds(12345))); - EXPECT_EQ("03:25", fmt::format("{:%R}", std::chrono::seconds(12345))); - EXPECT_EQ("03:25:45", fmt::format("{:%T}", std::chrono::seconds(12345))); - EXPECT_EQ("12345", fmt::format("{:%Q}", std::chrono::seconds(12345))); - EXPECT_EQ("s", fmt::format("{:%q}", std::chrono::seconds(12345))); -} - -TEST(ChronoTest, InvalidSpecs) { - auto sec = std::chrono::seconds(0); - EXPECT_THROW_MSG(fmt::format("{:%a}", sec), fmt::format_error, "no date"); - EXPECT_THROW_MSG(fmt::format("{:%A}", sec), fmt::format_error, "no date"); - EXPECT_THROW_MSG(fmt::format("{:%c}", sec), fmt::format_error, "no date"); - EXPECT_THROW_MSG(fmt::format("{:%x}", sec), fmt::format_error, "no date"); - EXPECT_THROW_MSG(fmt::format("{:%Ex}", sec), fmt::format_error, "no date"); - EXPECT_THROW_MSG(fmt::format("{:%X}", sec), fmt::format_error, "no date"); - EXPECT_THROW_MSG(fmt::format("{:%EX}", sec), fmt::format_error, "no date"); - EXPECT_THROW_MSG(fmt::format("{:%D}", sec), fmt::format_error, "no date"); - EXPECT_THROW_MSG(fmt::format("{:%F}", sec), fmt::format_error, "no date"); - EXPECT_THROW_MSG(fmt::format("{:%Ec}", sec), fmt::format_error, "no date"); - EXPECT_THROW_MSG(fmt::format("{:%w}", sec), fmt::format_error, "no date"); - EXPECT_THROW_MSG(fmt::format("{:%u}", sec), fmt::format_error, "no date"); - EXPECT_THROW_MSG(fmt::format("{:%b}", sec), fmt::format_error, "no date"); - EXPECT_THROW_MSG(fmt::format("{:%B}", sec), fmt::format_error, "no date"); - EXPECT_THROW_MSG(fmt::format("{:%z}", sec), fmt::format_error, "no date"); - EXPECT_THROW_MSG(fmt::format("{:%Z}", sec), fmt::format_error, "no date"); - EXPECT_THROW_MSG(fmt::format("{:%Eq}", sec), fmt::format_error, - "invalid format"); - EXPECT_THROW_MSG(fmt::format("{:%Oq}", sec), fmt::format_error, - "invalid format"); -} - -TEST(ChronoTest, Locale) { - const char* loc_name = "ja_JP.utf8"; - bool has_locale = false; - std::locale loc; - try { - loc = std::locale(loc_name); - has_locale = true; - } catch (const std::runtime_error&) { - } - if (!has_locale) { - fmt::print("{} locale is missing.\n", loc_name); - return; - } - EXPECT_TIME("%OH", make_hour(14), std::chrono::hours(14)); - EXPECT_TIME("%OI", make_hour(14), std::chrono::hours(14)); - EXPECT_TIME("%OM", make_minute(42), std::chrono::minutes(42)); - EXPECT_TIME("%OS", make_second(42), std::chrono::seconds(42)); - auto time = make_tm(); - time.tm_hour = 3; - time.tm_min = 25; - time.tm_sec = 45; - auto sec = std::chrono::seconds(12345); - EXPECT_TIME("%r", time, sec); - EXPECT_TIME("%p", time, sec); -} - -typedef std::chrono::duration<double, std::milli> dms; - -TEST(ChronoTest, FormatDefaultFP) { - typedef std::chrono::duration<float> fs; - EXPECT_EQ("1.234s", fmt::format("{}", fs(1.234))); - typedef std::chrono::duration<float, std::milli> fms; - EXPECT_EQ("1.234ms", fmt::format("{}", fms(1.234))); - typedef std::chrono::duration<double> ds; - EXPECT_EQ("1.234s", fmt::format("{}", ds(1.234))); - EXPECT_EQ("1.234ms", fmt::format("{}", dms(1.234))); -} - -TEST(ChronoTest, FormatPrecision) { - EXPECT_THROW_MSG(fmt::format("{:.2}", std::chrono::seconds(42)), - fmt::format_error, - "precision not allowed for this argument type"); - EXPECT_EQ("1.2ms", fmt::format("{:.1}", dms(1.234))); - EXPECT_EQ("1.23ms", fmt::format("{:.{}}", dms(1.234), 2)); -} - -TEST(ChronoTest, FormatFullSpecs) { - EXPECT_EQ("1.2ms ", fmt::format("{:6.1}", dms(1.234))); - EXPECT_EQ(" 1.23ms", fmt::format("{:>8.{}}", dms(1.234), 2)); - EXPECT_EQ(" 1.2ms ", fmt::format("{:^{}.{}}", dms(1.234), 7, 1)); - EXPECT_EQ(" 1.23ms ", fmt::format("{0:^{2}.{1}}", dms(1.234), 2, 8)); - EXPECT_EQ("=1.234ms=", fmt::format("{:=^{}.{}}", dms(1.234), 9, 3)); - EXPECT_EQ("*1.2340ms*", fmt::format("{:*^10.4}", dms(1.234))); -} - -TEST(ChronoTest, FormatSimpleQq) { - typedef std::chrono::duration<float> fs; - EXPECT_EQ("1.234 s", fmt::format("{:%Q %q}", fs(1.234))); - typedef std::chrono::duration<float, std::milli> fms; - EXPECT_EQ("1.234 ms", fmt::format("{:%Q %q}", fms(1.234))); - typedef std::chrono::duration<double> ds; - EXPECT_EQ("1.234 s", fmt::format("{:%Q %q}", ds(1.234))); - EXPECT_EQ("1.234 ms", fmt::format("{:%Q %q}", dms(1.234))); -} - -TEST(ChronoTest, FormatPrecisionQq) { - EXPECT_THROW_MSG(fmt::format("{:.2%Q %q}", std::chrono::seconds(42)), - fmt::format_error, - "precision not allowed for this argument type"); - EXPECT_EQ("1.2 ms", fmt::format("{:.1%Q %q}", dms(1.234))); - EXPECT_EQ("1.23 ms", fmt::format("{:.{}%Q %q}", dms(1.234), 2)); -} - -TEST(ChronoTest, FormatFullSpecsQq) { - EXPECT_EQ("1.2 ms ", fmt::format("{:7.1%Q %q}", dms(1.234))); - EXPECT_EQ(" 1.23 ms", fmt::format("{:>8.{}%Q %q}", dms(1.234), 2)); - EXPECT_EQ(" 1.2 ms ", fmt::format("{:^{}.{}%Q %q}", dms(1.234), 8, 1)); - EXPECT_EQ(" 1.23 ms ", fmt::format("{0:^{2}.{1}%Q %q}", dms(1.234), 2, 9)); - EXPECT_EQ("=1.234 ms=", fmt::format("{:=^{}.{}%Q %q}", dms(1.234), 10, 3)); - EXPECT_EQ("*1.2340 ms*", fmt::format("{:*^11.4%Q %q}", dms(1.234))); -} - -TEST(ChronoTest, InvalidWidthId) { - EXPECT_THROW(fmt::format("{:{o}", std::chrono::seconds(0)), - fmt::format_error); -} - -TEST(ChronoTest, InvalidColons) { - EXPECT_THROW(fmt::format("{0}=:{0::", std::chrono::seconds(0)), - fmt::format_error); -} - -TEST(ChronoTest, NegativeDurations) { - EXPECT_EQ("-12345", fmt::format("{:%Q}", std::chrono::seconds(-12345))); - EXPECT_EQ("-03:25:45", - fmt::format("{:%H:%M:%S}", std::chrono::seconds(-12345))); - EXPECT_EQ("-00:01", - fmt::format("{:%M:%S}", std::chrono::duration<double>(-1))); - EXPECT_EQ("s", fmt::format("{:%q}", std::chrono::seconds(-12345))); - EXPECT_EQ("-00.127", - fmt::format("{:%S}", - std::chrono::duration<signed char, std::milli>{-127})); - auto min = std::numeric_limits<int>::min(); - EXPECT_EQ(fmt::format("{}", min), - fmt::format("{:%Q}", std::chrono::duration<int>(min))); -} - -TEST(ChronoTest, SpecialDurations) { - EXPECT_EQ( - "40.", - fmt::format("{:%S}", std::chrono::duration<double>(1e20)).substr(0, 3)); - auto nan = std::numeric_limits<double>::quiet_NaN(); - EXPECT_EQ( - "nan nan nan nan nan:nan nan", - fmt::format("{:%I %H %M %S %R %r}", std::chrono::duration<double>(nan))); - fmt::format("{:%S}", - std::chrono::duration<float, std::atto>(1.79400457e+31f)); - EXPECT_EQ(fmt::format("{}", std::chrono::duration<float, std::exa>(1)), - "1Es"); - EXPECT_EQ(fmt::format("{}", std::chrono::duration<float, std::atto>(1)), - "1as"); - EXPECT_EQ(fmt::format("{:%R}", std::chrono::duration<char, std::mega>{2}), - "03:33"); - EXPECT_EQ(fmt::format("{:%T}", std::chrono::duration<char, std::mega>{2}), - "03:33:20"); -} - -#endif // FMT_STATIC_THOUSANDS_SEPARATOR +#define EXPECT_TIME(spec, time, duration) \ + { \ + std::locale loc("ja_JP.utf8"); \ + EXPECT_EQ(format_tm(time, spec, loc), \ + fmt::format(loc, "{:" spec "}", duration)); \ + } + +#ifndef FMT_STATIC_THOUSANDS_SEPARATOR + +TEST(ChronoTest, FormatDefault) { + EXPECT_EQ("42s", fmt::format("{}", std::chrono::seconds(42))); + EXPECT_EQ("42as", + fmt::format("{}", std::chrono::duration<int, std::atto>(42))); + EXPECT_EQ("42fs", + fmt::format("{}", std::chrono::duration<int, std::femto>(42))); + EXPECT_EQ("42ps", + fmt::format("{}", std::chrono::duration<int, std::pico>(42))); + EXPECT_EQ("42ns", fmt::format("{}", std::chrono::nanoseconds(42))); + EXPECT_EQ("42µs", fmt::format("{}", std::chrono::microseconds(42))); + EXPECT_EQ("42ms", fmt::format("{}", std::chrono::milliseconds(42))); + EXPECT_EQ("42cs", + fmt::format("{}", std::chrono::duration<int, std::centi>(42))); + EXPECT_EQ("42ds", + fmt::format("{}", std::chrono::duration<int, std::deci>(42))); + EXPECT_EQ("42s", fmt::format("{}", std::chrono::seconds(42))); + EXPECT_EQ("42das", + fmt::format("{}", std::chrono::duration<int, std::deca>(42))); + EXPECT_EQ("42hs", + fmt::format("{}", std::chrono::duration<int, std::hecto>(42))); + EXPECT_EQ("42ks", + fmt::format("{}", std::chrono::duration<int, std::kilo>(42))); + EXPECT_EQ("42Ms", + fmt::format("{}", std::chrono::duration<int, std::mega>(42))); + EXPECT_EQ("42Gs", + fmt::format("{}", std::chrono::duration<int, std::giga>(42))); + EXPECT_EQ("42Ts", + fmt::format("{}", std::chrono::duration<int, std::tera>(42))); + EXPECT_EQ("42Ps", + fmt::format("{}", std::chrono::duration<int, std::peta>(42))); + EXPECT_EQ("42Es", + fmt::format("{}", std::chrono::duration<int, std::exa>(42))); + EXPECT_EQ("42m", fmt::format("{}", std::chrono::minutes(42))); + EXPECT_EQ("42h", fmt::format("{}", std::chrono::hours(42))); + EXPECT_EQ( + "42[15]s", + fmt::format("{}", std::chrono::duration<int, std::ratio<15, 1>>(42))); + EXPECT_EQ( + "42[15/4]s", + fmt::format("{}", std::chrono::duration<int, std::ratio<15, 4>>(42))); +} + +TEST(ChronoTest, FormatWide) { + EXPECT_EQ(L"42s", fmt::format(L"{}", std::chrono::seconds(42))); + EXPECT_EQ(L"42as", + fmt::format(L"{}", std::chrono::duration<int, std::atto>(42))); + EXPECT_EQ(L"42fs", + fmt::format(L"{}", std::chrono::duration<int, std::femto>(42))); + EXPECT_EQ(L"42ps", + fmt::format(L"{}", std::chrono::duration<int, std::pico>(42))); + EXPECT_EQ(L"42ns", fmt::format(L"{}", std::chrono::nanoseconds(42))); + EXPECT_EQ(L"42\u00B5s", fmt::format(L"{}", std::chrono::microseconds(42))); + EXPECT_EQ(L"42ms", fmt::format(L"{}", std::chrono::milliseconds(42))); + EXPECT_EQ(L"42cs", + fmt::format(L"{}", std::chrono::duration<int, std::centi>(42))); + EXPECT_EQ(L"42ds", + fmt::format(L"{}", std::chrono::duration<int, std::deci>(42))); + EXPECT_EQ(L"42s", fmt::format(L"{}", std::chrono::seconds(42))); + EXPECT_EQ(L"42das", + fmt::format(L"{}", std::chrono::duration<int, std::deca>(42))); + EXPECT_EQ(L"42hs", + fmt::format(L"{}", std::chrono::duration<int, std::hecto>(42))); + EXPECT_EQ(L"42ks", + fmt::format(L"{}", std::chrono::duration<int, std::kilo>(42))); + EXPECT_EQ(L"42Ms", + fmt::format(L"{}", std::chrono::duration<int, std::mega>(42))); + EXPECT_EQ(L"42Gs", + fmt::format(L"{}", std::chrono::duration<int, std::giga>(42))); + EXPECT_EQ(L"42Ts", + fmt::format(L"{}", std::chrono::duration<int, std::tera>(42))); + EXPECT_EQ(L"42Ps", + fmt::format(L"{}", std::chrono::duration<int, std::peta>(42))); + EXPECT_EQ(L"42Es", + fmt::format(L"{}", std::chrono::duration<int, std::exa>(42))); + EXPECT_EQ(L"42m", fmt::format(L"{}", std::chrono::minutes(42))); + EXPECT_EQ(L"42h", fmt::format(L"{}", std::chrono::hours(42))); + EXPECT_EQ( + L"42[15]s", + fmt::format(L"{}", std::chrono::duration<int, std::ratio<15, 1>>(42))); + EXPECT_EQ( + L"42[15/4]s", + fmt::format(L"{}", std::chrono::duration<int, std::ratio<15, 4>>(42))); +} + +TEST(ChronoTest, Align) { + auto s = std::chrono::seconds(42); + EXPECT_EQ("42s ", fmt::format("{:5}", s)); + EXPECT_EQ("42s ", fmt::format("{:{}}", s, 5)); + EXPECT_EQ(" 42s", fmt::format("{:>5}", s)); + EXPECT_EQ("**42s**", fmt::format("{:*^7}", s)); + EXPECT_EQ("03:25:45 ", + fmt::format("{:12%H:%M:%S}", std::chrono::seconds(12345))); + EXPECT_EQ(" 03:25:45", + fmt::format("{:>12%H:%M:%S}", std::chrono::seconds(12345))); + EXPECT_EQ("~~03:25:45~~", + fmt::format("{:~^12%H:%M:%S}", std::chrono::seconds(12345))); + EXPECT_EQ("03:25:45 ", + fmt::format("{:{}%H:%M:%S}", std::chrono::seconds(12345), 12)); +} + +TEST(ChronoTest, FormatSpecs) { + EXPECT_EQ("%", fmt::format("{:%%}", std::chrono::seconds(0))); + EXPECT_EQ("\n", fmt::format("{:%n}", std::chrono::seconds(0))); + EXPECT_EQ("\t", fmt::format("{:%t}", std::chrono::seconds(0))); + EXPECT_EQ("00", fmt::format("{:%S}", std::chrono::seconds(0))); + EXPECT_EQ("00", fmt::format("{:%S}", std::chrono::seconds(60))); + EXPECT_EQ("42", fmt::format("{:%S}", std::chrono::seconds(42))); + EXPECT_EQ("01.234", fmt::format("{:%S}", std::chrono::milliseconds(1234))); + EXPECT_EQ("00", fmt::format("{:%M}", std::chrono::minutes(0))); + EXPECT_EQ("00", fmt::format("{:%M}", std::chrono::minutes(60))); + EXPECT_EQ("42", fmt::format("{:%M}", std::chrono::minutes(42))); + EXPECT_EQ("01", fmt::format("{:%M}", std::chrono::seconds(61))); + EXPECT_EQ("00", fmt::format("{:%H}", std::chrono::hours(0))); + EXPECT_EQ("00", fmt::format("{:%H}", std::chrono::hours(24))); + EXPECT_EQ("14", fmt::format("{:%H}", std::chrono::hours(14))); + EXPECT_EQ("01", fmt::format("{:%H}", std::chrono::minutes(61))); + EXPECT_EQ("12", fmt::format("{:%I}", std::chrono::hours(0))); + EXPECT_EQ("12", fmt::format("{:%I}", std::chrono::hours(12))); + EXPECT_EQ("12", fmt::format("{:%I}", std::chrono::hours(24))); + EXPECT_EQ("04", fmt::format("{:%I}", std::chrono::hours(4))); + EXPECT_EQ("02", fmt::format("{:%I}", std::chrono::hours(14))); + EXPECT_EQ("03:25:45", + fmt::format("{:%H:%M:%S}", std::chrono::seconds(12345))); + EXPECT_EQ("03:25", fmt::format("{:%R}", std::chrono::seconds(12345))); + EXPECT_EQ("03:25:45", fmt::format("{:%T}", std::chrono::seconds(12345))); + EXPECT_EQ("12345", fmt::format("{:%Q}", std::chrono::seconds(12345))); + EXPECT_EQ("s", fmt::format("{:%q}", std::chrono::seconds(12345))); +} + +TEST(ChronoTest, InvalidSpecs) { + auto sec = std::chrono::seconds(0); + EXPECT_THROW_MSG(fmt::format("{:%a}", sec), fmt::format_error, "no date"); + EXPECT_THROW_MSG(fmt::format("{:%A}", sec), fmt::format_error, "no date"); + EXPECT_THROW_MSG(fmt::format("{:%c}", sec), fmt::format_error, "no date"); + EXPECT_THROW_MSG(fmt::format("{:%x}", sec), fmt::format_error, "no date"); + EXPECT_THROW_MSG(fmt::format("{:%Ex}", sec), fmt::format_error, "no date"); + EXPECT_THROW_MSG(fmt::format("{:%X}", sec), fmt::format_error, "no date"); + EXPECT_THROW_MSG(fmt::format("{:%EX}", sec), fmt::format_error, "no date"); + EXPECT_THROW_MSG(fmt::format("{:%D}", sec), fmt::format_error, "no date"); + EXPECT_THROW_MSG(fmt::format("{:%F}", sec), fmt::format_error, "no date"); + EXPECT_THROW_MSG(fmt::format("{:%Ec}", sec), fmt::format_error, "no date"); + EXPECT_THROW_MSG(fmt::format("{:%w}", sec), fmt::format_error, "no date"); + EXPECT_THROW_MSG(fmt::format("{:%u}", sec), fmt::format_error, "no date"); + EXPECT_THROW_MSG(fmt::format("{:%b}", sec), fmt::format_error, "no date"); + EXPECT_THROW_MSG(fmt::format("{:%B}", sec), fmt::format_error, "no date"); + EXPECT_THROW_MSG(fmt::format("{:%z}", sec), fmt::format_error, "no date"); + EXPECT_THROW_MSG(fmt::format("{:%Z}", sec), fmt::format_error, "no date"); + EXPECT_THROW_MSG(fmt::format("{:%Eq}", sec), fmt::format_error, + "invalid format"); + EXPECT_THROW_MSG(fmt::format("{:%Oq}", sec), fmt::format_error, + "invalid format"); +} + +TEST(ChronoTest, Locale) { + const char* loc_name = "ja_JP.utf8"; + bool has_locale = false; + std::locale loc; + try { + loc = std::locale(loc_name); + has_locale = true; + } catch (const std::runtime_error&) { + } + if (!has_locale) { + fmt::print("{} locale is missing.\n", loc_name); + return; + } + EXPECT_TIME("%OH", make_hour(14), std::chrono::hours(14)); + EXPECT_TIME("%OI", make_hour(14), std::chrono::hours(14)); + EXPECT_TIME("%OM", make_minute(42), std::chrono::minutes(42)); + EXPECT_TIME("%OS", make_second(42), std::chrono::seconds(42)); + auto time = make_tm(); + time.tm_hour = 3; + time.tm_min = 25; + time.tm_sec = 45; + auto sec = std::chrono::seconds(12345); + EXPECT_TIME("%r", time, sec); + EXPECT_TIME("%p", time, sec); +} + +typedef std::chrono::duration<double, std::milli> dms; + +TEST(ChronoTest, FormatDefaultFP) { + typedef std::chrono::duration<float> fs; + EXPECT_EQ("1.234s", fmt::format("{}", fs(1.234))); + typedef std::chrono::duration<float, std::milli> fms; + EXPECT_EQ("1.234ms", fmt::format("{}", fms(1.234))); + typedef std::chrono::duration<double> ds; + EXPECT_EQ("1.234s", fmt::format("{}", ds(1.234))); + EXPECT_EQ("1.234ms", fmt::format("{}", dms(1.234))); +} + +TEST(ChronoTest, FormatPrecision) { + EXPECT_THROW_MSG(fmt::format("{:.2}", std::chrono::seconds(42)), + fmt::format_error, + "precision not allowed for this argument type"); + EXPECT_EQ("1.2ms", fmt::format("{:.1}", dms(1.234))); + EXPECT_EQ("1.23ms", fmt::format("{:.{}}", dms(1.234), 2)); +} + +TEST(ChronoTest, FormatFullSpecs) { + EXPECT_EQ("1.2ms ", fmt::format("{:6.1}", dms(1.234))); + EXPECT_EQ(" 1.23ms", fmt::format("{:>8.{}}", dms(1.234), 2)); + EXPECT_EQ(" 1.2ms ", fmt::format("{:^{}.{}}", dms(1.234), 7, 1)); + EXPECT_EQ(" 1.23ms ", fmt::format("{0:^{2}.{1}}", dms(1.234), 2, 8)); + EXPECT_EQ("=1.234ms=", fmt::format("{:=^{}.{}}", dms(1.234), 9, 3)); + EXPECT_EQ("*1.2340ms*", fmt::format("{:*^10.4}", dms(1.234))); +} + +TEST(ChronoTest, FormatSimpleQq) { + typedef std::chrono::duration<float> fs; + EXPECT_EQ("1.234 s", fmt::format("{:%Q %q}", fs(1.234))); + typedef std::chrono::duration<float, std::milli> fms; + EXPECT_EQ("1.234 ms", fmt::format("{:%Q %q}", fms(1.234))); + typedef std::chrono::duration<double> ds; + EXPECT_EQ("1.234 s", fmt::format("{:%Q %q}", ds(1.234))); + EXPECT_EQ("1.234 ms", fmt::format("{:%Q %q}", dms(1.234))); +} + +TEST(ChronoTest, FormatPrecisionQq) { + EXPECT_THROW_MSG(fmt::format("{:.2%Q %q}", std::chrono::seconds(42)), + fmt::format_error, + "precision not allowed for this argument type"); + EXPECT_EQ("1.2 ms", fmt::format("{:.1%Q %q}", dms(1.234))); + EXPECT_EQ("1.23 ms", fmt::format("{:.{}%Q %q}", dms(1.234), 2)); +} + +TEST(ChronoTest, FormatFullSpecsQq) { + EXPECT_EQ("1.2 ms ", fmt::format("{:7.1%Q %q}", dms(1.234))); + EXPECT_EQ(" 1.23 ms", fmt::format("{:>8.{}%Q %q}", dms(1.234), 2)); + EXPECT_EQ(" 1.2 ms ", fmt::format("{:^{}.{}%Q %q}", dms(1.234), 8, 1)); + EXPECT_EQ(" 1.23 ms ", fmt::format("{0:^{2}.{1}%Q %q}", dms(1.234), 2, 9)); + EXPECT_EQ("=1.234 ms=", fmt::format("{:=^{}.{}%Q %q}", dms(1.234), 10, 3)); + EXPECT_EQ("*1.2340 ms*", fmt::format("{:*^11.4%Q %q}", dms(1.234))); +} + +TEST(ChronoTest, InvalidWidthId) { + EXPECT_THROW(fmt::format("{:{o}", std::chrono::seconds(0)), + fmt::format_error); +} + +TEST(ChronoTest, InvalidColons) { + EXPECT_THROW(fmt::format("{0}=:{0::", std::chrono::seconds(0)), + fmt::format_error); +} + +TEST(ChronoTest, NegativeDurations) { + EXPECT_EQ("-12345", fmt::format("{:%Q}", std::chrono::seconds(-12345))); + EXPECT_EQ("-03:25:45", + fmt::format("{:%H:%M:%S}", std::chrono::seconds(-12345))); + EXPECT_EQ("-00:01", + fmt::format("{:%M:%S}", std::chrono::duration<double>(-1))); + EXPECT_EQ("s", fmt::format("{:%q}", std::chrono::seconds(-12345))); + EXPECT_EQ("-00.127", + fmt::format("{:%S}", + std::chrono::duration<signed char, std::milli>{-127})); + auto min = std::numeric_limits<int>::min(); + EXPECT_EQ(fmt::format("{}", min), + fmt::format("{:%Q}", std::chrono::duration<int>(min))); +} + +TEST(ChronoTest, SpecialDurations) { + EXPECT_EQ( + "40.", + fmt::format("{:%S}", std::chrono::duration<double>(1e20)).substr(0, 3)); + auto nan = std::numeric_limits<double>::quiet_NaN(); + EXPECT_EQ( + "nan nan nan nan nan:nan nan", + fmt::format("{:%I %H %M %S %R %r}", std::chrono::duration<double>(nan))); + fmt::format("{:%S}", + std::chrono::duration<float, std::atto>(1.79400457e+31f)); + EXPECT_EQ(fmt::format("{}", std::chrono::duration<float, std::exa>(1)), + "1Es"); + EXPECT_EQ(fmt::format("{}", std::chrono::duration<float, std::atto>(1)), + "1as"); + EXPECT_EQ(fmt::format("{:%R}", std::chrono::duration<char, std::mega>{2}), + "03:33"); + EXPECT_EQ(fmt::format("{:%T}", std::chrono::duration<char, std::mega>{2}), + "03:33:20"); +} + +#endif // FMT_STATIC_THOUSANDS_SEPARATOR diff --git a/contrib/libs/fmt/test/chrono-test/ya.make b/contrib/libs/fmt/test/chrono-test/ya.make index 1e1c0d91e1..7982d65069 100644 --- a/contrib/libs/fmt/test/chrono-test/ya.make +++ b/contrib/libs/fmt/test/chrono-test/ya.make @@ -1,37 +1,37 @@ -# Generated by devtools/yamaker. - +# Generated by devtools/yamaker. + GTEST() - + WITHOUT_LICENSE_TEXTS() - + OWNER( orivej g:cpp-contrib ) -LICENSE(MIT) - -PEERDIR( - contrib/libs/fmt - contrib/libs/fmt/test -) - -NO_COMPILER_WARNINGS() - -NO_UTIL() - -CFLAGS( - -DFMT_LOCALE - -DFMT_SHARED - -DGTEST_HAS_STD_WSTRING=1 - -DGTEST_LANG_CXX11=0 - -D_SILENCE_TR1_NAMESPACE_DEPRECATION_WARNING=1 -) - -SRCDIR(contrib/libs/fmt/test) - -SRCS( - chrono-test.cc -) - -END() +LICENSE(MIT) + +PEERDIR( + contrib/libs/fmt + contrib/libs/fmt/test +) + +NO_COMPILER_WARNINGS() + +NO_UTIL() + +CFLAGS( + -DFMT_LOCALE + -DFMT_SHARED + -DGTEST_HAS_STD_WSTRING=1 + -DGTEST_LANG_CXX11=0 + -D_SILENCE_TR1_NAMESPACE_DEPRECATION_WARNING=1 +) + +SRCDIR(contrib/libs/fmt/test) + +SRCS( + chrono-test.cc +) + +END() diff --git a/contrib/libs/fmt/test/color-test.cc b/contrib/libs/fmt/test/color-test.cc index b229aa1abf..3073808541 100644 --- a/contrib/libs/fmt/test/color-test.cc +++ b/contrib/libs/fmt/test/color-test.cc @@ -1,93 +1,93 @@ -// Formatting library for C++ - color tests -// -// Copyright (c) 2012 - present, Victor Zverovich -// All rights reserved. -// -// For the license information refer to format.h. - -#include "fmt/color.h" +// Formatting library for C++ - color tests +// +// Copyright (c) 2012 - present, Victor Zverovich +// All rights reserved. +// +// For the license information refer to format.h. + +#include "fmt/color.h" #include <iterator> #include <string> #include <utility> -#include "gtest-extra.h" - -TEST(ColorsTest, ColorsPrint) { - EXPECT_WRITE(stdout, fmt::print(fg(fmt::rgb(255, 20, 30)), "rgb(255,20,30)"), - "\x1b[38;2;255;020;030mrgb(255,20,30)\x1b[0m"); - EXPECT_WRITE(stdout, fmt::print(fg(fmt::color::blue), "blue"), - "\x1b[38;2;000;000;255mblue\x1b[0m"); - EXPECT_WRITE( - stdout, - fmt::print(fg(fmt::color::blue) | bg(fmt::color::red), "two color"), - "\x1b[38;2;000;000;255m\x1b[48;2;255;000;000mtwo color\x1b[0m"); - EXPECT_WRITE(stdout, fmt::print(fmt::emphasis::bold, "bold"), - "\x1b[1mbold\x1b[0m"); - EXPECT_WRITE(stdout, fmt::print(fmt::emphasis::italic, "italic"), - "\x1b[3mitalic\x1b[0m"); - EXPECT_WRITE(stdout, fmt::print(fmt::emphasis::underline, "underline"), - "\x1b[4munderline\x1b[0m"); - EXPECT_WRITE(stdout, - fmt::print(fmt::emphasis::strikethrough, "strikethrough"), - "\x1b[9mstrikethrough\x1b[0m"); - EXPECT_WRITE( - stdout, - fmt::print(fg(fmt::color::blue) | fmt::emphasis::bold, "blue/bold"), - "\x1b[1m\x1b[38;2;000;000;255mblue/bold\x1b[0m"); - EXPECT_WRITE(stderr, fmt::print(stderr, fmt::emphasis::bold, "bold error"), - "\x1b[1mbold error\x1b[0m"); - EXPECT_WRITE(stderr, fmt::print(stderr, fg(fmt::color::blue), "blue log"), - "\x1b[38;2;000;000;255mblue log\x1b[0m"); - EXPECT_WRITE(stdout, fmt::print(fmt::text_style(), "hi"), "hi"); - EXPECT_WRITE(stdout, fmt::print(fg(fmt::terminal_color::red), "tred"), - "\x1b[31mtred\x1b[0m"); - EXPECT_WRITE(stdout, fmt::print(bg(fmt::terminal_color::cyan), "tcyan"), - "\x1b[46mtcyan\x1b[0m"); - EXPECT_WRITE(stdout, - fmt::print(fg(fmt::terminal_color::bright_green), "tbgreen"), - "\x1b[92mtbgreen\x1b[0m"); - EXPECT_WRITE(stdout, - fmt::print(bg(fmt::terminal_color::bright_magenta), "tbmagenta"), - "\x1b[105mtbmagenta\x1b[0m"); -} - -TEST(ColorsTest, Format) { - EXPECT_EQ(fmt::format(fg(fmt::rgb(255, 20, 30)), "rgb(255,20,30)"), - "\x1b[38;2;255;020;030mrgb(255,20,30)\x1b[0m"); - EXPECT_EQ(fmt::format(fg(fmt::rgb(255, 20, 30)), L"rgb(255,20,30) wide"), - L"\x1b[38;2;255;020;030mrgb(255,20,30) wide\x1b[0m"); - EXPECT_EQ(fmt::format(fg(fmt::color::blue), "blue"), - "\x1b[38;2;000;000;255mblue\x1b[0m"); - EXPECT_EQ( - fmt::format(fg(fmt::color::blue) | bg(fmt::color::red), "two color"), - "\x1b[38;2;000;000;255m\x1b[48;2;255;000;000mtwo color\x1b[0m"); - EXPECT_EQ(fmt::format(fmt::emphasis::bold, "bold"), "\x1b[1mbold\x1b[0m"); - EXPECT_EQ(fmt::format(fmt::emphasis::italic, "italic"), - "\x1b[3mitalic\x1b[0m"); - EXPECT_EQ(fmt::format(fmt::emphasis::underline, "underline"), - "\x1b[4munderline\x1b[0m"); - EXPECT_EQ(fmt::format(fmt::emphasis::strikethrough, "strikethrough"), - "\x1b[9mstrikethrough\x1b[0m"); - EXPECT_EQ( - fmt::format(fg(fmt::color::blue) | fmt::emphasis::bold, "blue/bold"), - "\x1b[1m\x1b[38;2;000;000;255mblue/bold\x1b[0m"); - EXPECT_EQ(fmt::format(fmt::emphasis::bold, "bold error"), - "\x1b[1mbold error\x1b[0m"); - EXPECT_EQ(fmt::format(fg(fmt::color::blue), "blue log"), - "\x1b[38;2;000;000;255mblue log\x1b[0m"); - EXPECT_EQ(fmt::format(fmt::text_style(), "hi"), "hi"); - EXPECT_EQ(fmt::format(fg(fmt::terminal_color::red), "tred"), - "\x1b[31mtred\x1b[0m"); - EXPECT_EQ(fmt::format(bg(fmt::terminal_color::cyan), "tcyan"), - "\x1b[46mtcyan\x1b[0m"); - EXPECT_EQ(fmt::format(fg(fmt::terminal_color::bright_green), "tbgreen"), - "\x1b[92mtbgreen\x1b[0m"); - EXPECT_EQ(fmt::format(bg(fmt::terminal_color::bright_magenta), "tbmagenta"), - "\x1b[105mtbmagenta\x1b[0m"); - EXPECT_EQ(fmt::format(fg(fmt::terminal_color::red), "{}", "foo"), - "\x1b[31mfoo\x1b[0m"); -} +#include "gtest-extra.h" + +TEST(ColorsTest, ColorsPrint) { + EXPECT_WRITE(stdout, fmt::print(fg(fmt::rgb(255, 20, 30)), "rgb(255,20,30)"), + "\x1b[38;2;255;020;030mrgb(255,20,30)\x1b[0m"); + EXPECT_WRITE(stdout, fmt::print(fg(fmt::color::blue), "blue"), + "\x1b[38;2;000;000;255mblue\x1b[0m"); + EXPECT_WRITE( + stdout, + fmt::print(fg(fmt::color::blue) | bg(fmt::color::red), "two color"), + "\x1b[38;2;000;000;255m\x1b[48;2;255;000;000mtwo color\x1b[0m"); + EXPECT_WRITE(stdout, fmt::print(fmt::emphasis::bold, "bold"), + "\x1b[1mbold\x1b[0m"); + EXPECT_WRITE(stdout, fmt::print(fmt::emphasis::italic, "italic"), + "\x1b[3mitalic\x1b[0m"); + EXPECT_WRITE(stdout, fmt::print(fmt::emphasis::underline, "underline"), + "\x1b[4munderline\x1b[0m"); + EXPECT_WRITE(stdout, + fmt::print(fmt::emphasis::strikethrough, "strikethrough"), + "\x1b[9mstrikethrough\x1b[0m"); + EXPECT_WRITE( + stdout, + fmt::print(fg(fmt::color::blue) | fmt::emphasis::bold, "blue/bold"), + "\x1b[1m\x1b[38;2;000;000;255mblue/bold\x1b[0m"); + EXPECT_WRITE(stderr, fmt::print(stderr, fmt::emphasis::bold, "bold error"), + "\x1b[1mbold error\x1b[0m"); + EXPECT_WRITE(stderr, fmt::print(stderr, fg(fmt::color::blue), "blue log"), + "\x1b[38;2;000;000;255mblue log\x1b[0m"); + EXPECT_WRITE(stdout, fmt::print(fmt::text_style(), "hi"), "hi"); + EXPECT_WRITE(stdout, fmt::print(fg(fmt::terminal_color::red), "tred"), + "\x1b[31mtred\x1b[0m"); + EXPECT_WRITE(stdout, fmt::print(bg(fmt::terminal_color::cyan), "tcyan"), + "\x1b[46mtcyan\x1b[0m"); + EXPECT_WRITE(stdout, + fmt::print(fg(fmt::terminal_color::bright_green), "tbgreen"), + "\x1b[92mtbgreen\x1b[0m"); + EXPECT_WRITE(stdout, + fmt::print(bg(fmt::terminal_color::bright_magenta), "tbmagenta"), + "\x1b[105mtbmagenta\x1b[0m"); +} + +TEST(ColorsTest, Format) { + EXPECT_EQ(fmt::format(fg(fmt::rgb(255, 20, 30)), "rgb(255,20,30)"), + "\x1b[38;2;255;020;030mrgb(255,20,30)\x1b[0m"); + EXPECT_EQ(fmt::format(fg(fmt::rgb(255, 20, 30)), L"rgb(255,20,30) wide"), + L"\x1b[38;2;255;020;030mrgb(255,20,30) wide\x1b[0m"); + EXPECT_EQ(fmt::format(fg(fmt::color::blue), "blue"), + "\x1b[38;2;000;000;255mblue\x1b[0m"); + EXPECT_EQ( + fmt::format(fg(fmt::color::blue) | bg(fmt::color::red), "two color"), + "\x1b[38;2;000;000;255m\x1b[48;2;255;000;000mtwo color\x1b[0m"); + EXPECT_EQ(fmt::format(fmt::emphasis::bold, "bold"), "\x1b[1mbold\x1b[0m"); + EXPECT_EQ(fmt::format(fmt::emphasis::italic, "italic"), + "\x1b[3mitalic\x1b[0m"); + EXPECT_EQ(fmt::format(fmt::emphasis::underline, "underline"), + "\x1b[4munderline\x1b[0m"); + EXPECT_EQ(fmt::format(fmt::emphasis::strikethrough, "strikethrough"), + "\x1b[9mstrikethrough\x1b[0m"); + EXPECT_EQ( + fmt::format(fg(fmt::color::blue) | fmt::emphasis::bold, "blue/bold"), + "\x1b[1m\x1b[38;2;000;000;255mblue/bold\x1b[0m"); + EXPECT_EQ(fmt::format(fmt::emphasis::bold, "bold error"), + "\x1b[1mbold error\x1b[0m"); + EXPECT_EQ(fmt::format(fg(fmt::color::blue), "blue log"), + "\x1b[38;2;000;000;255mblue log\x1b[0m"); + EXPECT_EQ(fmt::format(fmt::text_style(), "hi"), "hi"); + EXPECT_EQ(fmt::format(fg(fmt::terminal_color::red), "tred"), + "\x1b[31mtred\x1b[0m"); + EXPECT_EQ(fmt::format(bg(fmt::terminal_color::cyan), "tcyan"), + "\x1b[46mtcyan\x1b[0m"); + EXPECT_EQ(fmt::format(fg(fmt::terminal_color::bright_green), "tbgreen"), + "\x1b[92mtbgreen\x1b[0m"); + EXPECT_EQ(fmt::format(bg(fmt::terminal_color::bright_magenta), "tbmagenta"), + "\x1b[105mtbmagenta\x1b[0m"); + EXPECT_EQ(fmt::format(fg(fmt::terminal_color::red), "{}", "foo"), + "\x1b[31mfoo\x1b[0m"); +} TEST(ColorsTest, FormatToOutAcceptsTextStyle) { fmt::text_style ts = fg(fmt::rgb(255, 20, 30)); diff --git a/contrib/libs/fmt/test/color-test/ya.make b/contrib/libs/fmt/test/color-test/ya.make index 1c224fe251..22e6654b0f 100644 --- a/contrib/libs/fmt/test/color-test/ya.make +++ b/contrib/libs/fmt/test/color-test/ya.make @@ -1,37 +1,37 @@ -# Generated by devtools/yamaker. - +# Generated by devtools/yamaker. + GTEST() - + WITHOUT_LICENSE_TEXTS() - + OWNER( orivej g:cpp-contrib ) -LICENSE(MIT) - -PEERDIR( - contrib/libs/fmt - contrib/libs/fmt/test -) - -NO_COMPILER_WARNINGS() - -NO_UTIL() - -CFLAGS( - -DFMT_LOCALE - -DFMT_SHARED - -DGTEST_HAS_STD_WSTRING=1 - -DGTEST_LANG_CXX11=0 - -D_SILENCE_TR1_NAMESPACE_DEPRECATION_WARNING=1 -) - -SRCDIR(contrib/libs/fmt/test) - -SRCS( - color-test.cc -) - -END() +LICENSE(MIT) + +PEERDIR( + contrib/libs/fmt + contrib/libs/fmt/test +) + +NO_COMPILER_WARNINGS() + +NO_UTIL() + +CFLAGS( + -DFMT_LOCALE + -DFMT_SHARED + -DGTEST_HAS_STD_WSTRING=1 + -DGTEST_LANG_CXX11=0 + -D_SILENCE_TR1_NAMESPACE_DEPRECATION_WARNING=1 +) + +SRCDIR(contrib/libs/fmt/test) + +SRCS( + color-test.cc +) + +END() diff --git a/contrib/libs/fmt/test/compile-test.cc b/contrib/libs/fmt/test/compile-test.cc index ad23980e62..9bb9bb7d9e 100644 --- a/contrib/libs/fmt/test/compile-test.cc +++ b/contrib/libs/fmt/test/compile-test.cc @@ -1,122 +1,122 @@ -// Formatting library for C++ - formatting library tests -// -// Copyright (c) 2012 - present, Victor Zverovich -// All rights reserved. -// -// For the license information refer to format.h. - -#include <string> +// Formatting library for C++ - formatting library tests +// +// Copyright (c) 2012 - present, Victor Zverovich +// All rights reserved. +// +// For the license information refer to format.h. + +#include <string> #include <type_traits> - + // Check that fmt/compile.h compiles with windows.h included before it. -#ifdef _WIN32 -# include <windows.h> -#endif - -#include "fmt/compile.h" -#include <gmock/gmock.h> -#include "gtest-extra.h" -#include "util.h" - -// compiletime_prepared_parts_type_provider is useful only with relaxed -// constexpr. -#if FMT_USE_CONSTEXPR -template <unsigned EXPECTED_PARTS_COUNT, typename Format> -void check_prepared_parts_type(Format format) { +#ifdef _WIN32 +# include <windows.h> +#endif + +#include "fmt/compile.h" +#include <gmock/gmock.h> +#include "gtest-extra.h" +#include "util.h" + +// compiletime_prepared_parts_type_provider is useful only with relaxed +// constexpr. +#if FMT_USE_CONSTEXPR +template <unsigned EXPECTED_PARTS_COUNT, typename Format> +void check_prepared_parts_type(Format format) { typedef fmt::detail::compiled_format_base<decltype(format)> provider; typedef fmt::detail::format_part<char> - expected_parts_type[EXPECTED_PARTS_COUNT]; - static_assert(std::is_same<typename provider::parts_container, - expected_parts_type>::value, - "CompileTimePreparedPartsTypeProvider test failed"); -} - -TEST(CompileTest, CompileTimePreparedPartsTypeProvider) { - check_prepared_parts_type<1u>(FMT_STRING("text")); - check_prepared_parts_type<1u>(FMT_STRING("{}")); - check_prepared_parts_type<2u>(FMT_STRING("text{}")); - check_prepared_parts_type<2u>(FMT_STRING("{}text")); - check_prepared_parts_type<3u>(FMT_STRING("text{}text")); - check_prepared_parts_type<3u>(FMT_STRING("{:{}.{}} {:{}}")); - - check_prepared_parts_type<3u>(FMT_STRING("{{{}}}")); // '{', 'argument', '}' - check_prepared_parts_type<2u>(FMT_STRING("text{{")); // 'text', '{' - check_prepared_parts_type<3u>(FMT_STRING("text{{ ")); // 'text', '{', ' ' - check_prepared_parts_type<2u>(FMT_STRING("}}text")); // '}', text - check_prepared_parts_type<2u>(FMT_STRING("text}}text")); // 'text}', 'text' - check_prepared_parts_type<4u>( - FMT_STRING("text{{}}text")); // 'text', '{', '}', 'text' -} -#endif - -TEST(CompileTest, PassStringLiteralFormat) { + expected_parts_type[EXPECTED_PARTS_COUNT]; + static_assert(std::is_same<typename provider::parts_container, + expected_parts_type>::value, + "CompileTimePreparedPartsTypeProvider test failed"); +} + +TEST(CompileTest, CompileTimePreparedPartsTypeProvider) { + check_prepared_parts_type<1u>(FMT_STRING("text")); + check_prepared_parts_type<1u>(FMT_STRING("{}")); + check_prepared_parts_type<2u>(FMT_STRING("text{}")); + check_prepared_parts_type<2u>(FMT_STRING("{}text")); + check_prepared_parts_type<3u>(FMT_STRING("text{}text")); + check_prepared_parts_type<3u>(FMT_STRING("{:{}.{}} {:{}}")); + + check_prepared_parts_type<3u>(FMT_STRING("{{{}}}")); // '{', 'argument', '}' + check_prepared_parts_type<2u>(FMT_STRING("text{{")); // 'text', '{' + check_prepared_parts_type<3u>(FMT_STRING("text{{ ")); // 'text', '{', ' ' + check_prepared_parts_type<2u>(FMT_STRING("}}text")); // '}', text + check_prepared_parts_type<2u>(FMT_STRING("text}}text")); // 'text}', 'text' + check_prepared_parts_type<4u>( + FMT_STRING("text{{}}text")); // 'text', '{', '}', 'text' +} +#endif + +TEST(CompileTest, PassStringLiteralFormat) { const auto prepared = fmt::detail::compile<int>("test {}"); - EXPECT_EQ("test 42", fmt::format(prepared, 42)); + EXPECT_EQ("test 42", fmt::format(prepared, 42)); const auto wprepared = fmt::detail::compile<int>(L"test {}"); - EXPECT_EQ(L"test 42", fmt::format(wprepared, 42)); -} - -TEST(CompileTest, FormatToArrayOfChars) { - char buffer[32] = {0}; + EXPECT_EQ(L"test 42", fmt::format(wprepared, 42)); +} + +TEST(CompileTest, FormatToArrayOfChars) { + char buffer[32] = {0}; const auto prepared = fmt::detail::compile<int>("4{}"); fmt::format_to(fmt::detail::make_checked(buffer, 32), prepared, 2); - EXPECT_EQ(std::string("42"), buffer); - wchar_t wbuffer[32] = {0}; + EXPECT_EQ(std::string("42"), buffer); + wchar_t wbuffer[32] = {0}; const auto wprepared = fmt::detail::compile<int>(L"4{}"); fmt::format_to(fmt::detail::make_checked(wbuffer, 32), wprepared, 2); - EXPECT_EQ(std::wstring(L"42"), wbuffer); -} - -TEST(CompileTest, FormatToIterator) { - std::string s(2, ' '); + EXPECT_EQ(std::wstring(L"42"), wbuffer); +} + +TEST(CompileTest, FormatToIterator) { + std::string s(2, ' '); const auto prepared = fmt::detail::compile<int>("4{}"); - fmt::format_to(s.begin(), prepared, 2); - EXPECT_EQ("42", s); - std::wstring ws(2, L' '); + fmt::format_to(s.begin(), prepared, 2); + EXPECT_EQ("42", s); + std::wstring ws(2, L' '); const auto wprepared = fmt::detail::compile<int>(L"4{}"); - fmt::format_to(ws.begin(), wprepared, 2); - EXPECT_EQ(L"42", ws); -} - -TEST(CompileTest, FormatToN) { - char buf[5]; + fmt::format_to(ws.begin(), wprepared, 2); + EXPECT_EQ(L"42", ws); +} + +TEST(CompileTest, FormatToN) { + char buf[5]; auto f = fmt::detail::compile<int>("{:10}"); - auto result = fmt::format_to_n(buf, 5, f, 42); - EXPECT_EQ(result.size, 10); - EXPECT_EQ(result.out, buf + 5); - EXPECT_EQ(fmt::string_view(buf, 5), " "); -} - -TEST(CompileTest, FormattedSize) { + auto result = fmt::format_to_n(buf, 5, f, 42); + EXPECT_EQ(result.size, 10); + EXPECT_EQ(result.out, buf + 5); + EXPECT_EQ(fmt::string_view(buf, 5), " "); +} + +TEST(CompileTest, FormattedSize) { auto f = fmt::detail::compile<int>("{:10}"); - EXPECT_EQ(fmt::formatted_size(f, 42), 10); -} - -TEST(CompileTest, MultipleTypes) { + EXPECT_EQ(fmt::formatted_size(f, 42), 10); +} + +TEST(CompileTest, MultipleTypes) { auto f = fmt::detail::compile<int, int>("{} {}"); - EXPECT_EQ(fmt::format(f, 42, 42), "42 42"); -} - + EXPECT_EQ(fmt::format(f, 42, 42), "42 42"); +} + struct test_formattable {}; - -FMT_BEGIN_NAMESPACE + +FMT_BEGIN_NAMESPACE template <> struct formatter<test_formattable> : formatter<const char*> { template <typename FormatContext> auto format(test_formattable, FormatContext& ctx) -> decltype(ctx.out()) { - return formatter<const char*>::format("foo", ctx); - } -}; -FMT_END_NAMESPACE - -TEST(CompileTest, FormatUserDefinedType) { + return formatter<const char*>::format("foo", ctx); + } +}; +FMT_END_NAMESPACE + +TEST(CompileTest, FormatUserDefinedType) { auto f = fmt::detail::compile<test_formattable>("{}"); EXPECT_EQ(fmt::format(f, test_formattable()), "foo"); -} - -TEST(CompileTest, EmptyFormatString) { +} + +TEST(CompileTest, EmptyFormatString) { auto f = fmt::detail::compile<>(""); - EXPECT_EQ(fmt::format(f), ""); -} + EXPECT_EQ(fmt::format(f), ""); +} #ifdef __cpp_if_constexpr TEST(CompileTest, FormatDefault) { diff --git a/contrib/libs/fmt/test/compile-test/ya.make b/contrib/libs/fmt/test/compile-test/ya.make index e5bb486acd..0173e7e70f 100644 --- a/contrib/libs/fmt/test/compile-test/ya.make +++ b/contrib/libs/fmt/test/compile-test/ya.make @@ -1,37 +1,37 @@ -# Generated by devtools/yamaker. - +# Generated by devtools/yamaker. + GTEST() - + WITHOUT_LICENSE_TEXTS() - + OWNER( orivej g:cpp-contrib ) -LICENSE(MIT) - -PEERDIR( - contrib/libs/fmt - contrib/libs/fmt/test -) - -NO_COMPILER_WARNINGS() - -NO_UTIL() - -CFLAGS( - -DFMT_LOCALE - -DFMT_SHARED - -DGTEST_HAS_STD_WSTRING=1 - -DGTEST_LANG_CXX11=0 - -D_SILENCE_TR1_NAMESPACE_DEPRECATION_WARNING=1 -) - -SRCDIR(contrib/libs/fmt/test) - -SRCS( - compile-test.cc -) - -END() +LICENSE(MIT) + +PEERDIR( + contrib/libs/fmt + contrib/libs/fmt/test +) + +NO_COMPILER_WARNINGS() + +NO_UTIL() + +CFLAGS( + -DFMT_LOCALE + -DFMT_SHARED + -DGTEST_HAS_STD_WSTRING=1 + -DGTEST_LANG_CXX11=0 + -D_SILENCE_TR1_NAMESPACE_DEPRECATION_WARNING=1 +) + +SRCDIR(contrib/libs/fmt/test) + +SRCS( + compile-test.cc +) + +END() diff --git a/contrib/libs/fmt/test/core-test.cc b/contrib/libs/fmt/test/core-test.cc index ae0824762a..a5fd01fa4d 100644 --- a/contrib/libs/fmt/test/core-test.cc +++ b/contrib/libs/fmt/test/core-test.cc @@ -1,86 +1,86 @@ -// Formatting library for C++ - core tests -// -// Copyright (c) 2012 - present, Victor Zverovich -// All rights reserved. -// -// For the license information refer to format.h. - -#include <algorithm> -#include <climits> -#include <cstring> -#include <functional> -#include <iterator> -#include <limits> -#include <memory> -#include <string> -#include <type_traits> - -#include <gmock/gmock.h> -#include "test-assert.h" - -// Check if fmt/core.h compiles with windows.h included before it. -#ifdef _WIN32 -# include <windows.h> -#endif - -#include "fmt/core.h" - -#undef min -#undef max - -using fmt::basic_format_arg; -using fmt::string_view; +// Formatting library for C++ - core tests +// +// Copyright (c) 2012 - present, Victor Zverovich +// All rights reserved. +// +// For the license information refer to format.h. + +#include <algorithm> +#include <climits> +#include <cstring> +#include <functional> +#include <iterator> +#include <limits> +#include <memory> +#include <string> +#include <type_traits> + +#include <gmock/gmock.h> +#include "test-assert.h" + +// Check if fmt/core.h compiles with windows.h included before it. +#ifdef _WIN32 +# include <windows.h> +#endif + +#include "fmt/core.h" + +#undef min +#undef max + +using fmt::basic_format_arg; +using fmt::string_view; using fmt::detail::buffer; using fmt::detail::make_arg; using fmt::detail::value; - -using testing::_; + +using testing::_; using testing::Invoke; using testing::Return; -using testing::StrictMock; - -struct test_struct {}; - -FMT_BEGIN_NAMESPACE -template <typename Char> struct formatter<test_struct, Char> { - template <typename ParseContext> - auto parse(ParseContext& ctx) -> decltype(ctx.begin()) { - return ctx.begin(); - } - +using testing::StrictMock; + +struct test_struct {}; + +FMT_BEGIN_NAMESPACE +template <typename Char> struct formatter<test_struct, Char> { + template <typename ParseContext> + auto parse(ParseContext& ctx) -> decltype(ctx.begin()) { + return ctx.begin(); + } + auto format(test_struct, format_context& ctx) -> decltype(ctx.out()) { - const Char* test = "test"; - return std::copy_n(test, std::strlen(test), ctx.out()); - } -}; -FMT_END_NAMESPACE - -#if !FMT_GCC_VERSION || FMT_GCC_VERSION >= 470 -TEST(BufferTest, Noncopyable) { - EXPECT_FALSE(std::is_copy_constructible<buffer<char>>::value); -# if !FMT_MSC_VER - // std::is_copy_assignable is broken in MSVC2013. - EXPECT_FALSE(std::is_copy_assignable<buffer<char>>::value); -# endif -} - -TEST(BufferTest, Nonmoveable) { - EXPECT_FALSE(std::is_move_constructible<buffer<char>>::value); -# if !FMT_MSC_VER - // std::is_move_assignable is broken in MSVC2013. - EXPECT_FALSE(std::is_move_assignable<buffer<char>>::value); -# endif -} -#endif - + const Char* test = "test"; + return std::copy_n(test, std::strlen(test), ctx.out()); + } +}; +FMT_END_NAMESPACE + +#if !FMT_GCC_VERSION || FMT_GCC_VERSION >= 470 +TEST(BufferTest, Noncopyable) { + EXPECT_FALSE(std::is_copy_constructible<buffer<char>>::value); +# if !FMT_MSC_VER + // std::is_copy_assignable is broken in MSVC2013. + EXPECT_FALSE(std::is_copy_assignable<buffer<char>>::value); +# endif +} + +TEST(BufferTest, Nonmoveable) { + EXPECT_FALSE(std::is_move_constructible<buffer<char>>::value); +# if !FMT_MSC_VER + // std::is_move_assignable is broken in MSVC2013. + EXPECT_FALSE(std::is_move_assignable<buffer<char>>::value); +# endif +} +#endif + TEST(BufferTest, Indestructible) { static_assert(!std::is_destructible<fmt::detail::buffer<int>>(), "buffer's destructor is protected"); } - + template <typename T> struct mock_buffer final : buffer<T> { MOCK_METHOD1(do_grow, size_t(size_t capacity)); - + void grow(size_t capacity) { this->set(this->data(), do_grow(capacity)); } mock_buffer(T* data = nullptr, size_t capacity = 0) { @@ -88,64 +88,64 @@ template <typename T> struct mock_buffer final : buffer<T> { ON_CALL(*this, do_grow(_)).WillByDefault(Invoke([](size_t capacity) { return capacity; })); - } -}; - -TEST(BufferTest, Ctor) { - { - mock_buffer<int> buffer; - EXPECT_EQ(nullptr, buffer.data()); - EXPECT_EQ(static_cast<size_t>(0), buffer.size()); - EXPECT_EQ(static_cast<size_t>(0), buffer.capacity()); - } - { - int dummy; - mock_buffer<int> buffer(&dummy); - EXPECT_EQ(&dummy, &buffer[0]); - EXPECT_EQ(static_cast<size_t>(0), buffer.size()); - EXPECT_EQ(static_cast<size_t>(0), buffer.capacity()); - } - { - int dummy; + } +}; + +TEST(BufferTest, Ctor) { + { + mock_buffer<int> buffer; + EXPECT_EQ(nullptr, buffer.data()); + EXPECT_EQ(static_cast<size_t>(0), buffer.size()); + EXPECT_EQ(static_cast<size_t>(0), buffer.capacity()); + } + { + int dummy; + mock_buffer<int> buffer(&dummy); + EXPECT_EQ(&dummy, &buffer[0]); + EXPECT_EQ(static_cast<size_t>(0), buffer.size()); + EXPECT_EQ(static_cast<size_t>(0), buffer.capacity()); + } + { + int dummy; size_t capacity = std::numeric_limits<size_t>::max(); - mock_buffer<int> buffer(&dummy, capacity); - EXPECT_EQ(&dummy, &buffer[0]); - EXPECT_EQ(static_cast<size_t>(0), buffer.size()); - EXPECT_EQ(capacity, buffer.capacity()); - } -} - -TEST(BufferTest, Access) { - char data[10]; - mock_buffer<char> buffer(data, sizeof(data)); - buffer[0] = 11; - EXPECT_EQ(11, buffer[0]); - buffer[3] = 42; - EXPECT_EQ(42, *(&buffer[0] + 3)); + mock_buffer<int> buffer(&dummy, capacity); + EXPECT_EQ(&dummy, &buffer[0]); + EXPECT_EQ(static_cast<size_t>(0), buffer.size()); + EXPECT_EQ(capacity, buffer.capacity()); + } +} + +TEST(BufferTest, Access) { + char data[10]; + mock_buffer<char> buffer(data, sizeof(data)); + buffer[0] = 11; + EXPECT_EQ(11, buffer[0]); + buffer[3] = 42; + EXPECT_EQ(42, *(&buffer[0] + 3)); const fmt::detail::buffer<char>& const_buffer = buffer; - EXPECT_EQ(42, const_buffer[3]); -} - + EXPECT_EQ(42, const_buffer[3]); +} + TEST(BufferTest, TryResize) { - char data[123]; - mock_buffer<char> buffer(data, sizeof(data)); - buffer[10] = 42; - EXPECT_EQ(42, buffer[10]); + char data[123]; + mock_buffer<char> buffer(data, sizeof(data)); + buffer[10] = 42; + EXPECT_EQ(42, buffer[10]); buffer.try_resize(20); - EXPECT_EQ(20u, buffer.size()); - EXPECT_EQ(123u, buffer.capacity()); - EXPECT_EQ(42, buffer[10]); + EXPECT_EQ(20u, buffer.size()); + EXPECT_EQ(123u, buffer.capacity()); + EXPECT_EQ(42, buffer[10]); buffer.try_resize(5); - EXPECT_EQ(5u, buffer.size()); - EXPECT_EQ(123u, buffer.capacity()); - EXPECT_EQ(42, buffer[10]); + EXPECT_EQ(5u, buffer.size()); + EXPECT_EQ(123u, buffer.capacity()); + EXPECT_EQ(42, buffer[10]); // Check if try_resize calls grow. - EXPECT_CALL(buffer, do_grow(124)); + EXPECT_CALL(buffer, do_grow(124)); buffer.try_resize(124); - EXPECT_CALL(buffer, do_grow(200)); + EXPECT_CALL(buffer, do_grow(200)); buffer.try_resize(200); -} - +} + TEST(BufferTest, TryResizePartial) { char data[10]; mock_buffer<char> buffer(data, sizeof(data)); @@ -155,30 +155,30 @@ TEST(BufferTest, TryResizePartial) { EXPECT_EQ(buffer.size(), 15); } -TEST(BufferTest, Clear) { +TEST(BufferTest, Clear) { mock_buffer<char> buffer; EXPECT_CALL(buffer, do_grow(20)); buffer.try_resize(20); buffer.try_resize(0); - EXPECT_EQ(static_cast<size_t>(0), buffer.size()); - EXPECT_EQ(20u, buffer.capacity()); -} - -TEST(BufferTest, Append) { - char data[15]; - mock_buffer<char> buffer(data, 10); + EXPECT_EQ(static_cast<size_t>(0), buffer.size()); + EXPECT_EQ(20u, buffer.capacity()); +} + +TEST(BufferTest, Append) { + char data[15]; + mock_buffer<char> buffer(data, 10); auto test = "test"; - buffer.append(test, test + 5); - EXPECT_STREQ(test, &buffer[0]); - EXPECT_EQ(5u, buffer.size()); + buffer.append(test, test + 5); + EXPECT_STREQ(test, &buffer[0]); + EXPECT_EQ(5u, buffer.size()); buffer.try_resize(10); - EXPECT_CALL(buffer, do_grow(12)); - buffer.append(test, test + 2); - EXPECT_EQ('t', buffer[10]); - EXPECT_EQ('e', buffer[11]); - EXPECT_EQ(12u, buffer.size()); -} - + EXPECT_CALL(buffer, do_grow(12)); + buffer.append(test, test + 2); + EXPECT_EQ('t', buffer[10]); + EXPECT_EQ('e', buffer[11]); + EXPECT_EQ(12u, buffer.size()); +} + TEST(BufferTest, AppendPartial) { char data[10]; mock_buffer<char> buffer(data, sizeof(data)); @@ -193,262 +193,262 @@ TEST(BufferTest, AppendPartial) { buffer.append(test, test + 15); } -TEST(BufferTest, AppendAllocatesEnoughStorage) { - char data[19]; - mock_buffer<char> buffer(data, 10); +TEST(BufferTest, AppendAllocatesEnoughStorage) { + char data[19]; + mock_buffer<char> buffer(data, 10); auto test = "abcdefgh"; buffer.try_resize(10); - EXPECT_CALL(buffer, do_grow(19)); - buffer.append(test, test + 9); -} - -TEST(ArgTest, FormatArgs) { + EXPECT_CALL(buffer, do_grow(19)); + buffer.append(test, test + 9); +} + +TEST(ArgTest, FormatArgs) { auto args = fmt::format_args(); - EXPECT_FALSE(args.get(1)); -} - -struct custom_context { - using char_type = char; - using parse_context_type = fmt::format_parse_context; - - template <typename T> struct formatter_type { - template <typename ParseContext> - auto parse(ParseContext& ctx) -> decltype(ctx.begin()) { - return ctx.begin(); - } - - const char* format(const T&, custom_context& ctx) { - ctx.called = true; - return nullptr; - } - }; - - bool called; - fmt::format_parse_context ctx; - - fmt::format_parse_context& parse_context() { return ctx; } - void advance_to(const char*) {} -}; - -TEST(ArgTest, MakeValueWithCustomContext) { + EXPECT_FALSE(args.get(1)); +} + +struct custom_context { + using char_type = char; + using parse_context_type = fmt::format_parse_context; + + template <typename T> struct formatter_type { + template <typename ParseContext> + auto parse(ParseContext& ctx) -> decltype(ctx.begin()) { + return ctx.begin(); + } + + const char* format(const T&, custom_context& ctx) { + ctx.called = true; + return nullptr; + } + }; + + bool called; + fmt::format_parse_context ctx; + + fmt::format_parse_context& parse_context() { return ctx; } + void advance_to(const char*) {} +}; + +TEST(ArgTest, MakeValueWithCustomContext) { auto t = test_struct(); fmt::detail::value<custom_context> arg( fmt::detail::arg_mapper<custom_context>().map(t)); - custom_context ctx = {false, fmt::format_parse_context("")}; - arg.custom.format(&t, ctx.parse_context(), ctx); - EXPECT_TRUE(ctx.called); -} - -FMT_BEGIN_NAMESPACE + custom_context ctx = {false, fmt::format_parse_context("")}; + arg.custom.format(&t, ctx.parse_context(), ctx); + EXPECT_TRUE(ctx.called); +} + +FMT_BEGIN_NAMESPACE namespace detail { -template <typename Char> -bool operator==(custom_value<Char> lhs, custom_value<Char> rhs) { - return lhs.value == rhs.value; -} +template <typename Char> +bool operator==(custom_value<Char> lhs, custom_value<Char> rhs) { + return lhs.value == rhs.value; +} } // namespace detail -FMT_END_NAMESPACE - -// Use a unique result type to make sure that there are no undesirable -// conversions. -struct test_result {}; - -template <typename T> struct mock_visitor { +FMT_END_NAMESPACE + +// Use a unique result type to make sure that there are no undesirable +// conversions. +struct test_result {}; + +template <typename T> struct mock_visitor { template <typename U> struct result { using type = test_result; }; - - mock_visitor() { + + mock_visitor() { ON_CALL(*this, visit(_)).WillByDefault(Return(test_result())); - } - - MOCK_METHOD1_T(visit, test_result(T value)); - MOCK_METHOD0_T(unexpected, void()); - - test_result operator()(T value) { return visit(value); } - - template <typename U> test_result operator()(U) { - unexpected(); - return test_result(); - } -}; - + } + + MOCK_METHOD1_T(visit, test_result(T value)); + MOCK_METHOD0_T(unexpected, void()); + + test_result operator()(T value) { return visit(value); } + + template <typename U> test_result operator()(U) { + unexpected(); + return test_result(); + } +}; + template <typename T> struct visit_type { using type = T; }; - + #define VISIT_TYPE(type_, visit_type_) \ template <> struct visit_type<type_> { using type = visit_type_; } - -VISIT_TYPE(signed char, int); -VISIT_TYPE(unsigned char, unsigned); -VISIT_TYPE(short, int); -VISIT_TYPE(unsigned short, unsigned); - -#if LONG_MAX == INT_MAX -VISIT_TYPE(long, int); -VISIT_TYPE(unsigned long, unsigned); -#else -VISIT_TYPE(long, long long); -VISIT_TYPE(unsigned long, unsigned long long); -#endif - -#define CHECK_ARG_(Char, expected, value) \ - { \ - testing::StrictMock<mock_visitor<decltype(expected)>> visitor; \ - EXPECT_CALL(visitor, visit(expected)); \ + +VISIT_TYPE(signed char, int); +VISIT_TYPE(unsigned char, unsigned); +VISIT_TYPE(short, int); +VISIT_TYPE(unsigned short, unsigned); + +#if LONG_MAX == INT_MAX +VISIT_TYPE(long, int); +VISIT_TYPE(unsigned long, unsigned); +#else +VISIT_TYPE(long, long long); +VISIT_TYPE(unsigned long, unsigned long long); +#endif + +#define CHECK_ARG_(Char, expected, value) \ + { \ + testing::StrictMock<mock_visitor<decltype(expected)>> visitor; \ + EXPECT_CALL(visitor, visit(expected)); \ using iterator = std::back_insert_iterator<buffer<Char>>; \ - fmt::visit_format_arg( \ - visitor, make_arg<fmt::basic_format_context<iterator, Char>>(value)); \ - } - -#define CHECK_ARG(value, typename_) \ - { \ + fmt::visit_format_arg( \ + visitor, make_arg<fmt::basic_format_context<iterator, Char>>(value)); \ + } + +#define CHECK_ARG(value, typename_) \ + { \ using value_type = decltype(value); \ typename_ visit_type<value_type>::type expected = value; \ - CHECK_ARG_(char, expected, value) \ - CHECK_ARG_(wchar_t, expected, value) \ - } - -template <typename T> class NumericArgTest : public testing::Test {}; - + CHECK_ARG_(char, expected, value) \ + CHECK_ARG_(wchar_t, expected, value) \ + } + +template <typename T> class NumericArgTest : public testing::Test {}; + using types = ::testing::Types<bool, signed char, unsigned char, signed, unsigned short, int, unsigned, long, unsigned long, long long, unsigned long long, float, double, long double>; TYPED_TEST_CASE(NumericArgTest, types); - -template <typename T> + +template <typename T> fmt::enable_if_t<std::is_integral<T>::value, T> test_value() { - return static_cast<T>(42); -} - -template <typename T> + return static_cast<T>(42); +} + +template <typename T> fmt::enable_if_t<std::is_floating_point<T>::value, T> test_value() { - return static_cast<T>(4.2); -} - -TYPED_TEST(NumericArgTest, MakeAndVisit) { - CHECK_ARG(test_value<TypeParam>(), typename); - CHECK_ARG(std::numeric_limits<TypeParam>::min(), typename); - CHECK_ARG(std::numeric_limits<TypeParam>::max(), typename); -} - -TEST(ArgTest, CharArg) { - CHECK_ARG_(char, 'a', 'a'); - CHECK_ARG_(wchar_t, L'a', 'a'); - CHECK_ARG_(wchar_t, L'a', L'a'); -} - -TEST(ArgTest, StringArg) { - char str_data[] = "test"; - char* str = str_data; - const char* cstr = str; - CHECK_ARG_(char, cstr, str); - + return static_cast<T>(4.2); +} + +TYPED_TEST(NumericArgTest, MakeAndVisit) { + CHECK_ARG(test_value<TypeParam>(), typename); + CHECK_ARG(std::numeric_limits<TypeParam>::min(), typename); + CHECK_ARG(std::numeric_limits<TypeParam>::max(), typename); +} + +TEST(ArgTest, CharArg) { + CHECK_ARG_(char, 'a', 'a'); + CHECK_ARG_(wchar_t, L'a', 'a'); + CHECK_ARG_(wchar_t, L'a', L'a'); +} + +TEST(ArgTest, StringArg) { + char str_data[] = "test"; + char* str = str_data; + const char* cstr = str; + CHECK_ARG_(char, cstr, str); + auto sref = string_view(str); - CHECK_ARG_(char, sref, std::string(str)); -} - -TEST(ArgTest, WStringArg) { - wchar_t str_data[] = L"test"; - wchar_t* str = str_data; - const wchar_t* cstr = str; - - fmt::wstring_view sref(str); - CHECK_ARG_(wchar_t, cstr, str); - CHECK_ARG_(wchar_t, cstr, cstr); - CHECK_ARG_(wchar_t, sref, std::wstring(str)); - CHECK_ARG_(wchar_t, sref, fmt::wstring_view(str)); -} - -TEST(ArgTest, PointerArg) { - void* p = nullptr; - const void* cp = nullptr; - CHECK_ARG_(char, cp, p); - CHECK_ARG_(wchar_t, cp, p); - CHECK_ARG(cp, ); -} - -struct check_custom { - test_result operator()( - fmt::basic_format_arg<fmt::format_context>::handle h) const { + CHECK_ARG_(char, sref, std::string(str)); +} + +TEST(ArgTest, WStringArg) { + wchar_t str_data[] = L"test"; + wchar_t* str = str_data; + const wchar_t* cstr = str; + + fmt::wstring_view sref(str); + CHECK_ARG_(wchar_t, cstr, str); + CHECK_ARG_(wchar_t, cstr, cstr); + CHECK_ARG_(wchar_t, sref, std::wstring(str)); + CHECK_ARG_(wchar_t, sref, fmt::wstring_view(str)); +} + +TEST(ArgTest, PointerArg) { + void* p = nullptr; + const void* cp = nullptr; + CHECK_ARG_(char, cp, p); + CHECK_ARG_(wchar_t, cp, p); + CHECK_ARG(cp, ); +} + +struct check_custom { + test_result operator()( + fmt::basic_format_arg<fmt::format_context>::handle h) const { struct test_buffer final : fmt::detail::buffer<char> { - char data[10]; + char data[10]; test_buffer() : fmt::detail::buffer<char>(data, 0, 10) {} void grow(size_t) {} - } buffer; - fmt::format_parse_context parse_ctx(""); + } buffer; + fmt::format_parse_context parse_ctx(""); fmt::format_context ctx{fmt::detail::buffer_appender<char>(buffer), fmt::format_args()}; - h.format(parse_ctx, ctx); - EXPECT_EQ("test", std::string(buffer.data, buffer.size())); - return test_result(); - } -}; - -TEST(ArgTest, CustomArg) { - test_struct test; + h.format(parse_ctx, ctx); + EXPECT_EQ("test", std::string(buffer.data, buffer.size())); + return test_result(); + } +}; + +TEST(ArgTest, CustomArg) { + test_struct test; using visitor = mock_visitor<fmt::basic_format_arg<fmt::format_context>::handle>; - testing::StrictMock<visitor> v; + testing::StrictMock<visitor> v; EXPECT_CALL(v, visit(_)).WillOnce(Invoke(check_custom())); - fmt::visit_format_arg(v, make_arg<fmt::format_context>(test)); -} - -TEST(ArgTest, VisitInvalidArg) { - testing::StrictMock<mock_visitor<fmt::monostate>> visitor; - EXPECT_CALL(visitor, visit(_)); - fmt::basic_format_arg<fmt::format_context> arg; - fmt::visit_format_arg(visitor, arg); -} - -TEST(FormatDynArgsTest, Basic) { - fmt::dynamic_format_arg_store<fmt::format_context> store; - store.push_back(42); - store.push_back("abc1"); - store.push_back(1.5f); + fmt::visit_format_arg(v, make_arg<fmt::format_context>(test)); +} + +TEST(ArgTest, VisitInvalidArg) { + testing::StrictMock<mock_visitor<fmt::monostate>> visitor; + EXPECT_CALL(visitor, visit(_)); + fmt::basic_format_arg<fmt::format_context> arg; + fmt::visit_format_arg(visitor, arg); +} + +TEST(FormatDynArgsTest, Basic) { + fmt::dynamic_format_arg_store<fmt::format_context> store; + store.push_back(42); + store.push_back("abc1"); + store.push_back(1.5f); EXPECT_EQ("42 and abc1 and 1.5", fmt::vformat("{} and {} and {}", store)); -} - -TEST(FormatDynArgsTest, StringsAndRefs) { - // Unfortunately the tests are compiled with old ABI so strings use COW. - fmt::dynamic_format_arg_store<fmt::format_context> store; - char str[] = "1234567890"; - store.push_back(str); - store.push_back(std::cref(str)); - store.push_back(fmt::string_view{str}); - str[0] = 'X'; - - std::string result = fmt::vformat("{} and {} and {}", store); - EXPECT_EQ("1234567890 and X234567890 and X234567890", result); -} - -struct custom_type { - int i = 0; -}; - -FMT_BEGIN_NAMESPACE -template <> struct formatter<custom_type> { - auto parse(format_parse_context& ctx) const -> decltype(ctx.begin()) { - return ctx.begin(); - } - - template <typename FormatContext> - auto format(const custom_type& p, FormatContext& ctx) -> decltype(ctx.out()) { - return format_to(ctx.out(), "cust={}", p.i); - } -}; -FMT_END_NAMESPACE - -TEST(FormatDynArgsTest, CustomFormat) { - fmt::dynamic_format_arg_store<fmt::format_context> store; - custom_type c{}; - store.push_back(c); - ++c.i; - store.push_back(c); - ++c.i; - store.push_back(std::cref(c)); - ++c.i; - std::string result = fmt::vformat("{} and {} and {}", store); - EXPECT_EQ("cust=0 and cust=1 and cust=3", result); -} - +} + +TEST(FormatDynArgsTest, StringsAndRefs) { + // Unfortunately the tests are compiled with old ABI so strings use COW. + fmt::dynamic_format_arg_store<fmt::format_context> store; + char str[] = "1234567890"; + store.push_back(str); + store.push_back(std::cref(str)); + store.push_back(fmt::string_view{str}); + str[0] = 'X'; + + std::string result = fmt::vformat("{} and {} and {}", store); + EXPECT_EQ("1234567890 and X234567890 and X234567890", result); +} + +struct custom_type { + int i = 0; +}; + +FMT_BEGIN_NAMESPACE +template <> struct formatter<custom_type> { + auto parse(format_parse_context& ctx) const -> decltype(ctx.begin()) { + return ctx.begin(); + } + + template <typename FormatContext> + auto format(const custom_type& p, FormatContext& ctx) -> decltype(ctx.out()) { + return format_to(ctx.out(), "cust={}", p.i); + } +}; +FMT_END_NAMESPACE + +TEST(FormatDynArgsTest, CustomFormat) { + fmt::dynamic_format_arg_store<fmt::format_context> store; + custom_type c{}; + store.push_back(c); + ++c.i; + store.push_back(c); + ++c.i; + store.push_back(std::cref(c)); + ++c.i; + std::string result = fmt::vformat("{} and {} and {}", store); + EXPECT_EQ("cust=0 and cust=1 and cust=3", result); +} + TEST(FormatDynArgsTest, NamedInt) { fmt::dynamic_format_arg_store<fmt::format_context> store; store.push_back(fmt::arg("a1", 42)); @@ -464,28 +464,28 @@ TEST(FormatDynArgsTest, NamedStrings) { EXPECT_EQ("1234567890 and X234567890", fmt::vformat("{a1} and {a2}", store)); } -TEST(FormatDynArgsTest, NamedArgByRef) { - fmt::dynamic_format_arg_store<fmt::format_context> store; - - // Note: fmt::arg() constructs an object which holds a reference - // to its value. It's not an aggregate, so it doesn't extend the - // reference lifetime. As a result, it's a very bad idea passing temporary - // as a named argument value. Only GCC with optimization level >0 - // complains about this. - // - // A real life usecase is when you have both name and value alive - // guarantee their lifetime and thus don't want them to be copied into - // storages. - int a1_val{42}; - auto a1 = fmt::arg("a1_", a1_val); +TEST(FormatDynArgsTest, NamedArgByRef) { + fmt::dynamic_format_arg_store<fmt::format_context> store; + + // Note: fmt::arg() constructs an object which holds a reference + // to its value. It's not an aggregate, so it doesn't extend the + // reference lifetime. As a result, it's a very bad idea passing temporary + // as a named argument value. Only GCC with optimization level >0 + // complains about this. + // + // A real life usecase is when you have both name and value alive + // guarantee their lifetime and thus don't want them to be copied into + // storages. + int a1_val{42}; + auto a1 = fmt::arg("a1_", a1_val); store.push_back("abc"); store.push_back(1.5f); - store.push_back(std::cref(a1)); - + store.push_back(std::cref(a1)); + std::string result = fmt::vformat("{a1_} and {} and {} and {}", store); EXPECT_EQ("42 and abc and 1.5 and 42", result); } - + TEST(FormatDynArgsTest, NamedCustomFormat) { fmt::dynamic_format_arg_store<fmt::format_context> store; custom_type c{}; @@ -504,7 +504,7 @@ TEST(FormatDynArgsTest, Clear) { store.push_back(42); std::string result = fmt::vformat("{}", store); - EXPECT_EQ("42", result); + EXPECT_EQ("42", result); store.push_back(43); result = fmt::vformat("{} and {}", store); @@ -514,8 +514,8 @@ TEST(FormatDynArgsTest, Clear) { store.push_back(44); result = fmt::vformat("{}", store); EXPECT_EQ("44", result); -} - +} + TEST(FormatDynArgsTest, Reserve) { fmt::dynamic_format_arg_store<fmt::format_context> store; store.reserve(2, 1); @@ -525,249 +525,249 @@ TEST(FormatDynArgsTest, Reserve) { EXPECT_EQ("42 and 1.5", result); } -struct copy_throwable { - copy_throwable() {} - copy_throwable(const copy_throwable&) { throw "deal with it"; } -}; - -FMT_BEGIN_NAMESPACE -template <> struct formatter<copy_throwable> { - auto parse(format_parse_context& ctx) const -> decltype(ctx.begin()) { - return ctx.begin(); - } - auto format(copy_throwable, format_context& ctx) -> decltype(ctx.out()) { - return ctx.out(); - } -}; -FMT_END_NAMESPACE - -TEST(FormatDynArgsTest, ThrowOnCopy) { - fmt::dynamic_format_arg_store<fmt::format_context> store; - store.push_back(std::string("foo")); - try { - store.push_back(copy_throwable()); - } catch (...) { - } - EXPECT_EQ(fmt::vformat("{}", store), "foo"); -} - -TEST(StringViewTest, ValueType) { - static_assert(std::is_same<string_view::value_type, char>::value, ""); -} - -TEST(StringViewTest, Length) { - // Test that string_view::size() returns string length, not buffer size. - char str[100] = "some string"; - EXPECT_EQ(std::strlen(str), string_view(str).size()); - EXPECT_LT(std::strlen(str), sizeof(str)); -} - -// Check string_view's comparison operator. -template <template <typename> class Op> void check_op() { - const char* inputs[] = {"foo", "fop", "fo"}; +struct copy_throwable { + copy_throwable() {} + copy_throwable(const copy_throwable&) { throw "deal with it"; } +}; + +FMT_BEGIN_NAMESPACE +template <> struct formatter<copy_throwable> { + auto parse(format_parse_context& ctx) const -> decltype(ctx.begin()) { + return ctx.begin(); + } + auto format(copy_throwable, format_context& ctx) -> decltype(ctx.out()) { + return ctx.out(); + } +}; +FMT_END_NAMESPACE + +TEST(FormatDynArgsTest, ThrowOnCopy) { + fmt::dynamic_format_arg_store<fmt::format_context> store; + store.push_back(std::string("foo")); + try { + store.push_back(copy_throwable()); + } catch (...) { + } + EXPECT_EQ(fmt::vformat("{}", store), "foo"); +} + +TEST(StringViewTest, ValueType) { + static_assert(std::is_same<string_view::value_type, char>::value, ""); +} + +TEST(StringViewTest, Length) { + // Test that string_view::size() returns string length, not buffer size. + char str[100] = "some string"; + EXPECT_EQ(std::strlen(str), string_view(str).size()); + EXPECT_LT(std::strlen(str), sizeof(str)); +} + +// Check string_view's comparison operator. +template <template <typename> class Op> void check_op() { + const char* inputs[] = {"foo", "fop", "fo"}; size_t num_inputs = sizeof(inputs) / sizeof(*inputs); for (size_t i = 0; i < num_inputs; ++i) { for (size_t j = 0; j < num_inputs; ++j) { - string_view lhs(inputs[i]), rhs(inputs[j]); - EXPECT_EQ(Op<int>()(lhs.compare(rhs), 0), Op<string_view>()(lhs, rhs)); - } - } -} - -TEST(StringViewTest, Compare) { - EXPECT_EQ(string_view("foo").compare(string_view("foo")), 0); - EXPECT_GT(string_view("fop").compare(string_view("foo")), 0); - EXPECT_LT(string_view("foo").compare(string_view("fop")), 0); - EXPECT_GT(string_view("foo").compare(string_view("fo")), 0); - EXPECT_LT(string_view("fo").compare(string_view("foo")), 0); - check_op<std::equal_to>(); - check_op<std::not_equal_to>(); - check_op<std::less>(); - check_op<std::less_equal>(); - check_op<std::greater>(); - check_op<std::greater_equal>(); -} - -struct enabled_formatter {}; -struct disabled_formatter {}; -struct disabled_formatter_convertible { - operator int() const { return 42; } -}; - -FMT_BEGIN_NAMESPACE -template <> struct formatter<enabled_formatter> { - auto parse(format_parse_context& ctx) -> decltype(ctx.begin()) { - return ctx.begin(); - } - auto format(enabled_formatter, format_context& ctx) -> decltype(ctx.out()) { - return ctx.out(); - } -}; -FMT_END_NAMESPACE - -TEST(CoreTest, HasFormatter) { - using fmt::has_formatter; - using context = fmt::format_context; - static_assert(has_formatter<enabled_formatter, context>::value, ""); - static_assert(!has_formatter<disabled_formatter, context>::value, ""); - static_assert(!has_formatter<disabled_formatter_convertible, context>::value, - ""); -} - -struct convertible_to_int { - operator int() const { return 42; } -}; - -struct convertible_to_c_string { - operator const char*() const { return "foo"; } -}; - -FMT_BEGIN_NAMESPACE -template <> struct formatter<convertible_to_int> { - auto parse(format_parse_context& ctx) -> decltype(ctx.begin()) { - return ctx.begin(); - } - auto format(convertible_to_int, format_context& ctx) -> decltype(ctx.out()) { - return std::copy_n("foo", 3, ctx.out()); - } -}; - -template <> struct formatter<convertible_to_c_string> { - auto parse(format_parse_context& ctx) -> decltype(ctx.begin()) { - return ctx.begin(); - } - auto format(convertible_to_c_string, format_context& ctx) - -> decltype(ctx.out()) { - return std::copy_n("bar", 3, ctx.out()); - } -}; -FMT_END_NAMESPACE - -TEST(CoreTest, FormatterOverridesImplicitConversion) { - EXPECT_EQ(fmt::format("{}", convertible_to_int()), "foo"); - EXPECT_EQ(fmt::format("{}", convertible_to_c_string()), "bar"); -} - -namespace my_ns { -template <typename Char> class my_string { + string_view lhs(inputs[i]), rhs(inputs[j]); + EXPECT_EQ(Op<int>()(lhs.compare(rhs), 0), Op<string_view>()(lhs, rhs)); + } + } +} + +TEST(StringViewTest, Compare) { + EXPECT_EQ(string_view("foo").compare(string_view("foo")), 0); + EXPECT_GT(string_view("fop").compare(string_view("foo")), 0); + EXPECT_LT(string_view("foo").compare(string_view("fop")), 0); + EXPECT_GT(string_view("foo").compare(string_view("fo")), 0); + EXPECT_LT(string_view("fo").compare(string_view("foo")), 0); + check_op<std::equal_to>(); + check_op<std::not_equal_to>(); + check_op<std::less>(); + check_op<std::less_equal>(); + check_op<std::greater>(); + check_op<std::greater_equal>(); +} + +struct enabled_formatter {}; +struct disabled_formatter {}; +struct disabled_formatter_convertible { + operator int() const { return 42; } +}; + +FMT_BEGIN_NAMESPACE +template <> struct formatter<enabled_formatter> { + auto parse(format_parse_context& ctx) -> decltype(ctx.begin()) { + return ctx.begin(); + } + auto format(enabled_formatter, format_context& ctx) -> decltype(ctx.out()) { + return ctx.out(); + } +}; +FMT_END_NAMESPACE + +TEST(CoreTest, HasFormatter) { + using fmt::has_formatter; + using context = fmt::format_context; + static_assert(has_formatter<enabled_formatter, context>::value, ""); + static_assert(!has_formatter<disabled_formatter, context>::value, ""); + static_assert(!has_formatter<disabled_formatter_convertible, context>::value, + ""); +} + +struct convertible_to_int { + operator int() const { return 42; } +}; + +struct convertible_to_c_string { + operator const char*() const { return "foo"; } +}; + +FMT_BEGIN_NAMESPACE +template <> struct formatter<convertible_to_int> { + auto parse(format_parse_context& ctx) -> decltype(ctx.begin()) { + return ctx.begin(); + } + auto format(convertible_to_int, format_context& ctx) -> decltype(ctx.out()) { + return std::copy_n("foo", 3, ctx.out()); + } +}; + +template <> struct formatter<convertible_to_c_string> { + auto parse(format_parse_context& ctx) -> decltype(ctx.begin()) { + return ctx.begin(); + } + auto format(convertible_to_c_string, format_context& ctx) + -> decltype(ctx.out()) { + return std::copy_n("bar", 3, ctx.out()); + } +}; +FMT_END_NAMESPACE + +TEST(CoreTest, FormatterOverridesImplicitConversion) { + EXPECT_EQ(fmt::format("{}", convertible_to_int()), "foo"); + EXPECT_EQ(fmt::format("{}", convertible_to_c_string()), "bar"); +} + +namespace my_ns { +template <typename Char> class my_string { private: std::basic_string<Char> s_; - public: - my_string(const Char* s) : s_(s) {} - const Char* data() const FMT_NOEXCEPT { return s_.data(); } + public: + my_string(const Char* s) : s_(s) {} + const Char* data() const FMT_NOEXCEPT { return s_.data(); } size_t length() const FMT_NOEXCEPT { return s_.size(); } - operator const Char*() const { return s_.c_str(); } -}; - -template <typename Char> -inline fmt::basic_string_view<Char> to_string_view(const my_string<Char>& s) - FMT_NOEXCEPT { - return {s.data(), s.length()}; -} - -struct non_string {}; -} // namespace my_ns - -template <typename T> class IsStringTest : public testing::Test {}; - -typedef ::testing::Types<char, wchar_t, char16_t, char32_t> StringCharTypes; -TYPED_TEST_CASE(IsStringTest, StringCharTypes); - -namespace { -template <typename Char> -struct derived_from_string_view : fmt::basic_string_view<Char> {}; -} // namespace - -TYPED_TEST(IsStringTest, IsString) { + operator const Char*() const { return s_.c_str(); } +}; + +template <typename Char> +inline fmt::basic_string_view<Char> to_string_view(const my_string<Char>& s) + FMT_NOEXCEPT { + return {s.data(), s.length()}; +} + +struct non_string {}; +} // namespace my_ns + +template <typename T> class IsStringTest : public testing::Test {}; + +typedef ::testing::Types<char, wchar_t, char16_t, char32_t> StringCharTypes; +TYPED_TEST_CASE(IsStringTest, StringCharTypes); + +namespace { +template <typename Char> +struct derived_from_string_view : fmt::basic_string_view<Char> {}; +} // namespace + +TYPED_TEST(IsStringTest, IsString) { EXPECT_TRUE(fmt::detail::is_string<TypeParam*>::value); EXPECT_TRUE(fmt::detail::is_string<const TypeParam*>::value); EXPECT_TRUE(fmt::detail::is_string<TypeParam[2]>::value); EXPECT_TRUE(fmt::detail::is_string<const TypeParam[2]>::value); EXPECT_TRUE(fmt::detail::is_string<std::basic_string<TypeParam>>::value); EXPECT_TRUE(fmt::detail::is_string<fmt::basic_string_view<TypeParam>>::value); - EXPECT_TRUE( + EXPECT_TRUE( fmt::detail::is_string<derived_from_string_view<TypeParam>>::value); using string_view = fmt::detail::std_string_view<TypeParam>; - EXPECT_TRUE(std::is_empty<string_view>::value != + EXPECT_TRUE(std::is_empty<string_view>::value != fmt::detail::is_string<string_view>::value); EXPECT_TRUE(fmt::detail::is_string<my_ns::my_string<TypeParam>>::value); EXPECT_FALSE(fmt::detail::is_string<my_ns::non_string>::value); -} - -TEST(CoreTest, Format) { - // This should work without including fmt/format.h. -#ifdef FMT_FORMAT_H_ -# error fmt/format.h must not be included in the core test -#endif - EXPECT_EQ(fmt::format("{}", 42), "42"); -} - -TEST(CoreTest, FormatTo) { - // This should work without including fmt/format.h. -#ifdef FMT_FORMAT_H_ -# error fmt/format.h must not be included in the core test -#endif - std::string s; - fmt::format_to(std::back_inserter(s), "{}", 42); - EXPECT_EQ(s, "42"); -} - -TEST(CoreTest, ToStringViewForeignStrings) { - using namespace my_ns; - EXPECT_EQ(to_string_view(my_string<char>("42")), "42"); +} + +TEST(CoreTest, Format) { + // This should work without including fmt/format.h. +#ifdef FMT_FORMAT_H_ +# error fmt/format.h must not be included in the core test +#endif + EXPECT_EQ(fmt::format("{}", 42), "42"); +} + +TEST(CoreTest, FormatTo) { + // This should work without including fmt/format.h. +#ifdef FMT_FORMAT_H_ +# error fmt/format.h must not be included in the core test +#endif + std::string s; + fmt::format_to(std::back_inserter(s), "{}", 42); + EXPECT_EQ(s, "42"); +} + +TEST(CoreTest, ToStringViewForeignStrings) { + using namespace my_ns; + EXPECT_EQ(to_string_view(my_string<char>("42")), "42"); fmt::detail::type type = fmt::detail::mapped_type_constant<my_string<char>, fmt::format_context>::value; EXPECT_EQ(type, fmt::detail::type::string_type); -} - -TEST(CoreTest, FormatForeignStrings) { - using namespace my_ns; - EXPECT_EQ(fmt::format(my_string<char>("{}"), 42), "42"); -} - -struct implicitly_convertible_to_string { - operator std::string() const { return "foo"; } -}; - -struct implicitly_convertible_to_string_view { - operator fmt::string_view() const { return "foo"; } -}; - +} + +TEST(CoreTest, FormatForeignStrings) { + using namespace my_ns; + EXPECT_EQ(fmt::format(my_string<char>("{}"), 42), "42"); +} + +struct implicitly_convertible_to_string { + operator std::string() const { return "foo"; } +}; + +struct implicitly_convertible_to_string_view { + operator fmt::string_view() const { return "foo"; } +}; + TEST(CoreTest, FormatImplicitlyConvertibleToStringView) { - EXPECT_EQ("foo", fmt::format("{}", implicitly_convertible_to_string_view())); -} - -// std::is_constructible is broken in MSVC until version 2015. -#if !FMT_MSC_VER || FMT_MSC_VER >= 1900 -struct explicitly_convertible_to_string_view { - explicit operator fmt::string_view() const { return "foo"; } -}; - + EXPECT_EQ("foo", fmt::format("{}", implicitly_convertible_to_string_view())); +} + +// std::is_constructible is broken in MSVC until version 2015. +#if !FMT_MSC_VER || FMT_MSC_VER >= 1900 +struct explicitly_convertible_to_string_view { + explicit operator fmt::string_view() const { return "foo"; } +}; + TEST(CoreTest, FormatExplicitlyConvertibleToStringView) { - EXPECT_EQ("foo", fmt::format("{}", explicitly_convertible_to_string_view())); -} - -# ifdef FMT_USE_STRING_VIEW -struct explicitly_convertible_to_std_string_view { - explicit operator std::string_view() const { return "foo"; } -}; - + EXPECT_EQ("foo", fmt::format("{}", explicitly_convertible_to_string_view())); +} + +# ifdef FMT_USE_STRING_VIEW +struct explicitly_convertible_to_std_string_view { + explicit operator std::string_view() const { return "foo"; } +}; + TEST(CoreTest, FormatExplicitlyConvertibleToStdStringView) { - EXPECT_EQ("foo", - fmt::format("{}", explicitly_convertible_to_std_string_view())); -} -# endif -#endif - -struct disabled_rvalue_conversion { - operator const char*() const& { return "foo"; } - operator const char*() & { return "foo"; } - operator const char*() const&& = delete; - operator const char*() && = delete; -}; - + EXPECT_EQ("foo", + fmt::format("{}", explicitly_convertible_to_std_string_view())); +} +# endif +#endif + +struct disabled_rvalue_conversion { + operator const char*() const& { return "foo"; } + operator const char*() & { return "foo"; } + operator const char*() const&& = delete; + operator const char*() && = delete; +}; + TEST(CoreTest, DisabledRValueConversion) { - EXPECT_EQ("foo", fmt::format("{}", disabled_rvalue_conversion())); -} + EXPECT_EQ("foo", fmt::format("{}", disabled_rvalue_conversion())); +} diff --git a/contrib/libs/fmt/test/core-test/ya.make b/contrib/libs/fmt/test/core-test/ya.make index 650db81964..8c320f4810 100644 --- a/contrib/libs/fmt/test/core-test/ya.make +++ b/contrib/libs/fmt/test/core-test/ya.make @@ -1,37 +1,37 @@ -# Generated by devtools/yamaker. - +# Generated by devtools/yamaker. + GTEST() - + WITHOUT_LICENSE_TEXTS() - + OWNER( orivej g:cpp-contrib ) -LICENSE(MIT) - -PEERDIR( - contrib/libs/fmt - contrib/libs/fmt/test -) - -NO_COMPILER_WARNINGS() - -NO_UTIL() - -CFLAGS( - -DFMT_LOCALE - -DFMT_SHARED - -DGTEST_HAS_STD_WSTRING=1 - -DGTEST_LANG_CXX11=0 - -D_SILENCE_TR1_NAMESPACE_DEPRECATION_WARNING=1 -) - -SRCDIR(contrib/libs/fmt/test) - -SRCS( - core-test.cc -) - -END() +LICENSE(MIT) + +PEERDIR( + contrib/libs/fmt + contrib/libs/fmt/test +) + +NO_COMPILER_WARNINGS() + +NO_UTIL() + +CFLAGS( + -DFMT_LOCALE + -DFMT_SHARED + -DGTEST_HAS_STD_WSTRING=1 + -DGTEST_LANG_CXX11=0 + -D_SILENCE_TR1_NAMESPACE_DEPRECATION_WARNING=1 +) + +SRCDIR(contrib/libs/fmt/test) + +SRCS( + core-test.cc +) + +END() diff --git a/contrib/libs/fmt/test/format-impl-test.cc b/contrib/libs/fmt/test/format-impl-test.cc index afe182e02c..66b55b5381 100644 --- a/contrib/libs/fmt/test/format-impl-test.cc +++ b/contrib/libs/fmt/test/format-impl-test.cc @@ -1,220 +1,220 @@ -// Formatting library for C++ - formatting library implementation tests -// -// Copyright (c) 2012 - present, Victor Zverovich -// All rights reserved. -// -// For the license information refer to format.h. - -#define FMT_NOEXCEPT -#undef FMT_SHARED -#include "test-assert.h" - -// Include format.cc instead of format.h to test implementation. -#include <algorithm> -#include <cstring> - -#include "../src/format.cc" -#include "fmt/printf.h" -#include <gmock/gmock.h> -#include "gtest-extra.h" -#include "util.h" - +// Formatting library for C++ - formatting library implementation tests +// +// Copyright (c) 2012 - present, Victor Zverovich +// All rights reserved. +// +// For the license information refer to format.h. + +#define FMT_NOEXCEPT +#undef FMT_SHARED +#include "test-assert.h" + +// Include format.cc instead of format.h to test implementation. +#include <algorithm> +#include <cstring> + +#include "../src/format.cc" +#include "fmt/printf.h" +#include <gmock/gmock.h> +#include "gtest-extra.h" +#include "util.h" + #ifdef _WIN32 # include <windows.h> # undef max #endif - + using fmt::detail::bigint; using fmt::detail::fp; using fmt::detail::max_value; - -static_assert(!std::is_copy_constructible<bigint>::value, ""); -static_assert(!std::is_copy_assignable<bigint>::value, ""); - -TEST(BigIntTest, Construct) { - EXPECT_EQ("", fmt::format("{}", bigint())); - EXPECT_EQ("42", fmt::format("{}", bigint(0x42))); - EXPECT_EQ("123456789abcedf0", fmt::format("{}", bigint(0x123456789abcedf0))); -} - -TEST(BigIntTest, Compare) { - bigint n1(42); - bigint n2(42); - EXPECT_EQ(compare(n1, n2), 0); - n2 <<= 32; - EXPECT_LT(compare(n1, n2), 0); - bigint n3(43); - EXPECT_LT(compare(n1, n3), 0); - EXPECT_GT(compare(n3, n1), 0); - bigint n4(42 * 0x100000001); - EXPECT_LT(compare(n2, n4), 0); - EXPECT_GT(compare(n4, n2), 0); -} - -TEST(BigIntTest, AddCompare) { - EXPECT_LT( - add_compare(bigint(0xffffffff), bigint(0xffffffff), bigint(1) <<= 64), 0); - EXPECT_LT(add_compare(bigint(1) <<= 32, bigint(1), bigint(1) <<= 96), 0); - EXPECT_GT(add_compare(bigint(1) <<= 32, bigint(0), bigint(0xffffffff)), 0); - EXPECT_GT(add_compare(bigint(0), bigint(1) <<= 32, bigint(0xffffffff)), 0); - EXPECT_GT(add_compare(bigint(42), bigint(1), bigint(42)), 0); - EXPECT_GT(add_compare(bigint(0xffffffff), bigint(1), bigint(0xffffffff)), 0); - EXPECT_LT(add_compare(bigint(10), bigint(10), bigint(22)), 0); - EXPECT_LT(add_compare(bigint(0x100000010), bigint(0x100000010), - bigint(0x300000010)), - 0); - EXPECT_GT(add_compare(bigint(0x1ffffffff), bigint(0x100000002), - bigint(0x300000000)), - 0); - EXPECT_EQ(add_compare(bigint(0x1ffffffff), bigint(0x100000002), - bigint(0x300000001)), - 0); - EXPECT_LT(add_compare(bigint(0x1ffffffff), bigint(0x100000002), - bigint(0x300000002)), - 0); - EXPECT_LT(add_compare(bigint(0x1ffffffff), bigint(0x100000002), - bigint(0x300000003)), - 0); -} - -TEST(BigIntTest, ShiftLeft) { - bigint n(0x42); - n <<= 0; - EXPECT_EQ("42", fmt::format("{}", n)); - n <<= 1; - EXPECT_EQ("84", fmt::format("{}", n)); - n <<= 25; - EXPECT_EQ("108000000", fmt::format("{}", n)); -} - -TEST(BigIntTest, Multiply) { - bigint n(0x42); - EXPECT_THROW(n *= 0, assertion_failure); - n *= 1; - EXPECT_EQ("42", fmt::format("{}", n)); - n *= 2; - EXPECT_EQ("84", fmt::format("{}", n)); - n *= 0x12345678; - EXPECT_EQ("962fc95e0", fmt::format("{}", n)); - bigint bigmax(max_value<uint32_t>()); - bigmax *= max_value<uint32_t>(); - EXPECT_EQ("fffffffe00000001", fmt::format("{}", bigmax)); - bigmax.assign(max_value<uint64_t>()); - bigmax *= max_value<uint64_t>(); - EXPECT_EQ("fffffffffffffffe0000000000000001", fmt::format("{}", bigmax)); -} - -TEST(BigIntTest, Accumulator) { + +static_assert(!std::is_copy_constructible<bigint>::value, ""); +static_assert(!std::is_copy_assignable<bigint>::value, ""); + +TEST(BigIntTest, Construct) { + EXPECT_EQ("", fmt::format("{}", bigint())); + EXPECT_EQ("42", fmt::format("{}", bigint(0x42))); + EXPECT_EQ("123456789abcedf0", fmt::format("{}", bigint(0x123456789abcedf0))); +} + +TEST(BigIntTest, Compare) { + bigint n1(42); + bigint n2(42); + EXPECT_EQ(compare(n1, n2), 0); + n2 <<= 32; + EXPECT_LT(compare(n1, n2), 0); + bigint n3(43); + EXPECT_LT(compare(n1, n3), 0); + EXPECT_GT(compare(n3, n1), 0); + bigint n4(42 * 0x100000001); + EXPECT_LT(compare(n2, n4), 0); + EXPECT_GT(compare(n4, n2), 0); +} + +TEST(BigIntTest, AddCompare) { + EXPECT_LT( + add_compare(bigint(0xffffffff), bigint(0xffffffff), bigint(1) <<= 64), 0); + EXPECT_LT(add_compare(bigint(1) <<= 32, bigint(1), bigint(1) <<= 96), 0); + EXPECT_GT(add_compare(bigint(1) <<= 32, bigint(0), bigint(0xffffffff)), 0); + EXPECT_GT(add_compare(bigint(0), bigint(1) <<= 32, bigint(0xffffffff)), 0); + EXPECT_GT(add_compare(bigint(42), bigint(1), bigint(42)), 0); + EXPECT_GT(add_compare(bigint(0xffffffff), bigint(1), bigint(0xffffffff)), 0); + EXPECT_LT(add_compare(bigint(10), bigint(10), bigint(22)), 0); + EXPECT_LT(add_compare(bigint(0x100000010), bigint(0x100000010), + bigint(0x300000010)), + 0); + EXPECT_GT(add_compare(bigint(0x1ffffffff), bigint(0x100000002), + bigint(0x300000000)), + 0); + EXPECT_EQ(add_compare(bigint(0x1ffffffff), bigint(0x100000002), + bigint(0x300000001)), + 0); + EXPECT_LT(add_compare(bigint(0x1ffffffff), bigint(0x100000002), + bigint(0x300000002)), + 0); + EXPECT_LT(add_compare(bigint(0x1ffffffff), bigint(0x100000002), + bigint(0x300000003)), + 0); +} + +TEST(BigIntTest, ShiftLeft) { + bigint n(0x42); + n <<= 0; + EXPECT_EQ("42", fmt::format("{}", n)); + n <<= 1; + EXPECT_EQ("84", fmt::format("{}", n)); + n <<= 25; + EXPECT_EQ("108000000", fmt::format("{}", n)); +} + +TEST(BigIntTest, Multiply) { + bigint n(0x42); + EXPECT_THROW(n *= 0, assertion_failure); + n *= 1; + EXPECT_EQ("42", fmt::format("{}", n)); + n *= 2; + EXPECT_EQ("84", fmt::format("{}", n)); + n *= 0x12345678; + EXPECT_EQ("962fc95e0", fmt::format("{}", n)); + bigint bigmax(max_value<uint32_t>()); + bigmax *= max_value<uint32_t>(); + EXPECT_EQ("fffffffe00000001", fmt::format("{}", bigmax)); + bigmax.assign(max_value<uint64_t>()); + bigmax *= max_value<uint64_t>(); + EXPECT_EQ("fffffffffffffffe0000000000000001", fmt::format("{}", bigmax)); +} + +TEST(BigIntTest, Accumulator) { fmt::detail::accumulator acc; - EXPECT_EQ(acc.lower, 0); - EXPECT_EQ(acc.upper, 0); - acc.upper = 12; - acc.lower = 34; - EXPECT_EQ(static_cast<uint32_t>(acc), 34); - acc += 56; - EXPECT_EQ(acc.lower, 90); + EXPECT_EQ(acc.lower, 0); + EXPECT_EQ(acc.upper, 0); + acc.upper = 12; + acc.lower = 34; + EXPECT_EQ(static_cast<uint32_t>(acc), 34); + acc += 56; + EXPECT_EQ(acc.lower, 90); acc += fmt::detail::max_value<uint64_t>(); - EXPECT_EQ(acc.upper, 13); - EXPECT_EQ(acc.lower, 89); - acc >>= 32; - EXPECT_EQ(acc.upper, 0); - EXPECT_EQ(acc.lower, 13 * 0x100000000); -} - -TEST(BigIntTest, Square) { - bigint n0(0); - n0.square(); - EXPECT_EQ("0", fmt::format("{}", n0)); - bigint n1(0x100); - n1.square(); - EXPECT_EQ("10000", fmt::format("{}", n1)); - bigint n2(0xfffffffff); - n2.square(); - EXPECT_EQ("ffffffffe000000001", fmt::format("{}", n2)); - bigint n3(max_value<uint64_t>()); - n3.square(); - EXPECT_EQ("fffffffffffffffe0000000000000001", fmt::format("{}", n3)); - bigint n4; - n4.assign_pow10(10); - EXPECT_EQ("2540be400", fmt::format("{}", n4)); -} - -TEST(BigIntTest, DivModAssignZeroDivisor) { - bigint zero(0); - EXPECT_THROW(bigint(0).divmod_assign(zero), assertion_failure); - EXPECT_THROW(bigint(42).divmod_assign(zero), assertion_failure); -} - -TEST(BigIntTest, DivModAssignSelf) { - bigint n(100); - EXPECT_THROW(n.divmod_assign(n), assertion_failure); -} - -TEST(BigIntTest, DivModAssignUnaligned) { - // (42 << 340) / pow(10, 100): - bigint n1(42); - n1 <<= 340; - bigint n2; - n2.assign_pow10(100); - int result = n1.divmod_assign(n2); - EXPECT_EQ(result, 9406); - EXPECT_EQ("10f8353019583bfc29ffc8f564e1b9f9d819dbb4cf783e4507eca1539220p96", - fmt::format("{}", n1)); -} - -TEST(BigIntTest, DivModAssign) { - // 100 / 10: - bigint n1(100); - int result = n1.divmod_assign(bigint(10)); - EXPECT_EQ(result, 10); - EXPECT_EQ("0", fmt::format("{}", n1)); - // pow(10, 100) / (42 << 320): - n1.assign_pow10(100); - result = n1.divmod_assign(bigint(42) <<= 320); - EXPECT_EQ(result, 111); - EXPECT_EQ("13ad2594c37ceb0b2784c4ce0bf38ace408e211a7caab24308a82e8f10p96", - fmt::format("{}", n1)); - // 42 / 100: - bigint n2(42); - n1.assign_pow10(2); - result = n2.divmod_assign(n1); - EXPECT_EQ(result, 0); - EXPECT_EQ("2a", fmt::format("{}", n2)); -} - -template <bool is_iec559> void run_double_tests() { - fmt::print("warning: double is not IEC559, skipping FP tests\n"); -} - -template <> void run_double_tests<true>() { - // Construct from double. - EXPECT_EQ(fp(1.23), fp(0x13ae147ae147aeu, -52)); -} - -TEST(FPTest, DoubleTests) { - run_double_tests<std::numeric_limits<double>::is_iec559>(); -} - -TEST(FPTest, Normalize) { - const auto v = fp(0xbeef, 42); - auto normalized = normalize(v); - EXPECT_EQ(0xbeef000000000000, normalized.f); - EXPECT_EQ(-6, normalized.e); -} - -TEST(FPTest, Multiply) { - auto v = fp(123ULL << 32, 4) * fp(56ULL << 32, 7); - EXPECT_EQ(v.f, 123u * 56u); - EXPECT_EQ(v.e, 4 + 7 + 64); - v = fp(123ULL << 32, 4) * fp(567ULL << 31, 8); - EXPECT_EQ(v.f, (123 * 567 + 1u) / 2); - EXPECT_EQ(v.e, 4 + 8 + 64); -} - -TEST(FPTest, GetCachedPower) { + EXPECT_EQ(acc.upper, 13); + EXPECT_EQ(acc.lower, 89); + acc >>= 32; + EXPECT_EQ(acc.upper, 0); + EXPECT_EQ(acc.lower, 13 * 0x100000000); +} + +TEST(BigIntTest, Square) { + bigint n0(0); + n0.square(); + EXPECT_EQ("0", fmt::format("{}", n0)); + bigint n1(0x100); + n1.square(); + EXPECT_EQ("10000", fmt::format("{}", n1)); + bigint n2(0xfffffffff); + n2.square(); + EXPECT_EQ("ffffffffe000000001", fmt::format("{}", n2)); + bigint n3(max_value<uint64_t>()); + n3.square(); + EXPECT_EQ("fffffffffffffffe0000000000000001", fmt::format("{}", n3)); + bigint n4; + n4.assign_pow10(10); + EXPECT_EQ("2540be400", fmt::format("{}", n4)); +} + +TEST(BigIntTest, DivModAssignZeroDivisor) { + bigint zero(0); + EXPECT_THROW(bigint(0).divmod_assign(zero), assertion_failure); + EXPECT_THROW(bigint(42).divmod_assign(zero), assertion_failure); +} + +TEST(BigIntTest, DivModAssignSelf) { + bigint n(100); + EXPECT_THROW(n.divmod_assign(n), assertion_failure); +} + +TEST(BigIntTest, DivModAssignUnaligned) { + // (42 << 340) / pow(10, 100): + bigint n1(42); + n1 <<= 340; + bigint n2; + n2.assign_pow10(100); + int result = n1.divmod_assign(n2); + EXPECT_EQ(result, 9406); + EXPECT_EQ("10f8353019583bfc29ffc8f564e1b9f9d819dbb4cf783e4507eca1539220p96", + fmt::format("{}", n1)); +} + +TEST(BigIntTest, DivModAssign) { + // 100 / 10: + bigint n1(100); + int result = n1.divmod_assign(bigint(10)); + EXPECT_EQ(result, 10); + EXPECT_EQ("0", fmt::format("{}", n1)); + // pow(10, 100) / (42 << 320): + n1.assign_pow10(100); + result = n1.divmod_assign(bigint(42) <<= 320); + EXPECT_EQ(result, 111); + EXPECT_EQ("13ad2594c37ceb0b2784c4ce0bf38ace408e211a7caab24308a82e8f10p96", + fmt::format("{}", n1)); + // 42 / 100: + bigint n2(42); + n1.assign_pow10(2); + result = n2.divmod_assign(n1); + EXPECT_EQ(result, 0); + EXPECT_EQ("2a", fmt::format("{}", n2)); +} + +template <bool is_iec559> void run_double_tests() { + fmt::print("warning: double is not IEC559, skipping FP tests\n"); +} + +template <> void run_double_tests<true>() { + // Construct from double. + EXPECT_EQ(fp(1.23), fp(0x13ae147ae147aeu, -52)); +} + +TEST(FPTest, DoubleTests) { + run_double_tests<std::numeric_limits<double>::is_iec559>(); +} + +TEST(FPTest, Normalize) { + const auto v = fp(0xbeef, 42); + auto normalized = normalize(v); + EXPECT_EQ(0xbeef000000000000, normalized.f); + EXPECT_EQ(-6, normalized.e); +} + +TEST(FPTest, Multiply) { + auto v = fp(123ULL << 32, 4) * fp(56ULL << 32, 7); + EXPECT_EQ(v.f, 123u * 56u); + EXPECT_EQ(v.e, 4 + 7 + 64); + v = fp(123ULL << 32, 4) * fp(567ULL << 31, 8); + EXPECT_EQ(v.f, (123 * 567 + 1u) / 2); + EXPECT_EQ(v.e, 4 + 8 + 64); +} + +TEST(FPTest, GetCachedPower) { using limits = std::numeric_limits<double>; - for (auto exp = limits::min_exponent; exp <= limits::max_exponent; ++exp) { - int dec_exp = 0; + for (auto exp = limits::min_exponent; exp <= limits::max_exponent; ++exp) { + int dec_exp = 0; auto fp = fmt::detail::get_cached_power(exp, dec_exp); bigint exact, cache(fp.f); if (dec_exp >= 0) { @@ -245,9 +245,9 @@ TEST(FPTest, GetCachedPower) { EXPECT_EQ(exact_str.size(), cache_str.size()); EXPECT_EQ(exact_str.substr(0, 16), cache_str.substr(0, 16)); } - } -} - + } +} + TEST(FPTest, DragonboxMaxK) { using fmt::detail::dragonbox::floor_log10_pow2; using float_info = fmt::detail::dragonbox::float_info<float>; @@ -261,182 +261,182 @@ TEST(FPTest, DragonboxMaxK) { double_info::significand_bits)); } -TEST(FPTest, GetRoundDirection) { +TEST(FPTest, GetRoundDirection) { using fmt::detail::get_round_direction; using fmt::detail::round_direction; - EXPECT_EQ(round_direction::down, get_round_direction(100, 50, 0)); - EXPECT_EQ(round_direction::up, get_round_direction(100, 51, 0)); - EXPECT_EQ(round_direction::down, get_round_direction(100, 40, 10)); - EXPECT_EQ(round_direction::up, get_round_direction(100, 60, 10)); - for (size_t i = 41; i < 60; ++i) - EXPECT_EQ(round_direction::unknown, get_round_direction(100, i, 10)); - uint64_t max = max_value<uint64_t>(); - EXPECT_THROW(get_round_direction(100, 100, 0), assertion_failure); - EXPECT_THROW(get_round_direction(100, 0, 100), assertion_failure); - EXPECT_THROW(get_round_direction(100, 0, 50), assertion_failure); - // Check that remainder + error doesn't overflow. - EXPECT_EQ(round_direction::up, get_round_direction(max, max - 1, 2)); - // Check that 2 * (remainder + error) doesn't overflow. - EXPECT_EQ(round_direction::unknown, - get_round_direction(max, max / 2 + 1, max / 2)); - // Check that remainder - error doesn't overflow. - EXPECT_EQ(round_direction::unknown, get_round_direction(100, 40, 41)); - // Check that 2 * (remainder - error) doesn't overflow. - EXPECT_EQ(round_direction::up, get_round_direction(max, max - 1, 1)); -} - -TEST(FPTest, FixedHandler) { + EXPECT_EQ(round_direction::down, get_round_direction(100, 50, 0)); + EXPECT_EQ(round_direction::up, get_round_direction(100, 51, 0)); + EXPECT_EQ(round_direction::down, get_round_direction(100, 40, 10)); + EXPECT_EQ(round_direction::up, get_round_direction(100, 60, 10)); + for (size_t i = 41; i < 60; ++i) + EXPECT_EQ(round_direction::unknown, get_round_direction(100, i, 10)); + uint64_t max = max_value<uint64_t>(); + EXPECT_THROW(get_round_direction(100, 100, 0), assertion_failure); + EXPECT_THROW(get_round_direction(100, 0, 100), assertion_failure); + EXPECT_THROW(get_round_direction(100, 0, 50), assertion_failure); + // Check that remainder + error doesn't overflow. + EXPECT_EQ(round_direction::up, get_round_direction(max, max - 1, 2)); + // Check that 2 * (remainder + error) doesn't overflow. + EXPECT_EQ(round_direction::unknown, + get_round_direction(max, max / 2 + 1, max / 2)); + // Check that remainder - error doesn't overflow. + EXPECT_EQ(round_direction::unknown, get_round_direction(100, 40, 41)); + // Check that 2 * (remainder - error) doesn't overflow. + EXPECT_EQ(round_direction::up, get_round_direction(max, max - 1, 1)); +} + +TEST(FPTest, FixedHandler) { struct handler : fmt::detail::fixed_handler { - char buffer[10]; + char buffer[10]; handler(int prec = 0) : fmt::detail::fixed_handler() { - buf = buffer; - precision = prec; - } - }; - int exp = 0; - handler().on_digit('0', 100, 99, 0, exp, false); - EXPECT_THROW(handler().on_digit('0', 100, 100, 0, exp, false), - assertion_failure); + buf = buffer; + precision = prec; + } + }; + int exp = 0; + handler().on_digit('0', 100, 99, 0, exp, false); + EXPECT_THROW(handler().on_digit('0', 100, 100, 0, exp, false), + assertion_failure); namespace digits = fmt::detail::digits; EXPECT_EQ(handler(1).on_digit('0', 100, 10, 10, exp, false), digits::error); - // Check that divisor - error doesn't overflow. - EXPECT_EQ(handler(1).on_digit('0', 100, 10, 101, exp, false), digits::error); - // Check that 2 * error doesn't overflow. - uint64_t max = max_value<uint64_t>(); - EXPECT_EQ(handler(1).on_digit('0', max, 10, max - 1, exp, false), - digits::error); -} - -TEST(FPTest, GrisuFormatCompilesWithNonIEEEDouble) { - fmt::memory_buffer buf; + // Check that divisor - error doesn't overflow. + EXPECT_EQ(handler(1).on_digit('0', 100, 10, 101, exp, false), digits::error); + // Check that 2 * error doesn't overflow. + uint64_t max = max_value<uint64_t>(); + EXPECT_EQ(handler(1).on_digit('0', max, 10, max - 1, exp, false), + digits::error); +} + +TEST(FPTest, GrisuFormatCompilesWithNonIEEEDouble) { + fmt::memory_buffer buf; format_float(0.42, -1, fmt::detail::float_specs(), buf); -} - -template <typename T> struct value_extractor { - T operator()(T value) { return value; } - - template <typename U> FMT_NORETURN T operator()(U) { - throw std::runtime_error(fmt::format("invalid type {}", typeid(U).name())); - } - -#if FMT_USE_INT128 - // Apple Clang does not define typeid for __int128_t and __uint128_t. +} + +template <typename T> struct value_extractor { + T operator()(T value) { return value; } + + template <typename U> FMT_NORETURN T operator()(U) { + throw std::runtime_error(fmt::format("invalid type {}", typeid(U).name())); + } + +#if FMT_USE_INT128 + // Apple Clang does not define typeid for __int128_t and __uint128_t. FMT_NORETURN T operator()(fmt::detail::int128_t) { - throw std::runtime_error("invalid type __int128_t"); - } - + throw std::runtime_error("invalid type __int128_t"); + } + FMT_NORETURN T operator()(fmt::detail::uint128_t) { - throw std::runtime_error("invalid type __uint128_t"); - } -#endif -}; - -TEST(FormatTest, ArgConverter) { - long long value = max_value<long long>(); + throw std::runtime_error("invalid type __uint128_t"); + } +#endif +}; + +TEST(FormatTest, ArgConverter) { + long long value = max_value<long long>(); auto arg = fmt::detail::make_arg<fmt::format_context>(value); - fmt::visit_format_arg( + fmt::visit_format_arg( fmt::detail::arg_converter<long long, fmt::format_context>(arg, 'd'), - arg); - EXPECT_EQ(value, fmt::visit_format_arg(value_extractor<long long>(), arg)); -} - -TEST(FormatTest, StrError) { - char* message = nullptr; - char buffer[BUFFER_SIZE]; + arg); + EXPECT_EQ(value, fmt::visit_format_arg(value_extractor<long long>(), arg)); +} + +TEST(FormatTest, StrError) { + char* message = nullptr; + char buffer[BUFFER_SIZE]; EXPECT_ASSERT(fmt::detail::safe_strerror(EDOM, message = nullptr, 0), - "invalid buffer"); + "invalid buffer"); EXPECT_ASSERT(fmt::detail::safe_strerror(EDOM, message = buffer, 0), - "invalid buffer"); - buffer[0] = 'x'; -#if defined(_GNU_SOURCE) && !defined(__COVERITY__) - // Use invalid error code to make sure that safe_strerror returns an error - // message in the buffer rather than a pointer to a static string. - int error_code = -1; -#else - int error_code = EDOM; -#endif - - int result = + "invalid buffer"); + buffer[0] = 'x'; +#if defined(_GNU_SOURCE) && !defined(__COVERITY__) + // Use invalid error code to make sure that safe_strerror returns an error + // message in the buffer rather than a pointer to a static string. + int error_code = -1; +#else + int error_code = EDOM; +#endif + + int result = fmt::detail::safe_strerror(error_code, message = buffer, BUFFER_SIZE); - EXPECT_EQ(result, 0); + EXPECT_EQ(result, 0); size_t message_size = std::strlen(message); - EXPECT_GE(BUFFER_SIZE - 1u, message_size); - EXPECT_EQ(get_system_error(error_code), message); - - // safe_strerror never uses buffer on MinGW. -#if !defined(__MINGW32__) && !defined(__sun) - result = + EXPECT_GE(BUFFER_SIZE - 1u, message_size); + EXPECT_EQ(get_system_error(error_code), message); + + // safe_strerror never uses buffer on MinGW. +#if !defined(__MINGW32__) && !defined(__sun) + result = fmt::detail::safe_strerror(error_code, message = buffer, message_size); - EXPECT_EQ(ERANGE, result); + EXPECT_EQ(ERANGE, result); result = fmt::detail::safe_strerror(error_code, message = buffer, 1); - EXPECT_EQ(buffer, message); // Message should point to buffer. - EXPECT_EQ(ERANGE, result); - EXPECT_STREQ("", message); -#endif -} - -TEST(FormatTest, FormatErrorCode) { - std::string msg = "error 42", sep = ": "; - { - fmt::memory_buffer buffer; - format_to(buffer, "garbage"); + EXPECT_EQ(buffer, message); // Message should point to buffer. + EXPECT_EQ(ERANGE, result); + EXPECT_STREQ("", message); +#endif +} + +TEST(FormatTest, FormatErrorCode) { + std::string msg = "error 42", sep = ": "; + { + fmt::memory_buffer buffer; + format_to(buffer, "garbage"); fmt::detail::format_error_code(buffer, 42, "test"); - EXPECT_EQ("test: " + msg, to_string(buffer)); - } - { - fmt::memory_buffer buffer; - std::string prefix(fmt::inline_buffer_size - msg.size() - sep.size() + 1, - 'x'); + EXPECT_EQ("test: " + msg, to_string(buffer)); + } + { + fmt::memory_buffer buffer; + std::string prefix(fmt::inline_buffer_size - msg.size() - sep.size() + 1, + 'x'); fmt::detail::format_error_code(buffer, 42, prefix); - EXPECT_EQ(msg, to_string(buffer)); - } - int codes[] = {42, -1}; + EXPECT_EQ(msg, to_string(buffer)); + } + int codes[] = {42, -1}; for (size_t i = 0, n = sizeof(codes) / sizeof(*codes); i < n; ++i) { - // Test maximum buffer size. - msg = fmt::format("error {}", codes[i]); - fmt::memory_buffer buffer; - std::string prefix(fmt::inline_buffer_size - msg.size() - sep.size(), 'x'); + // Test maximum buffer size. + msg = fmt::format("error {}", codes[i]); + fmt::memory_buffer buffer; + std::string prefix(fmt::inline_buffer_size - msg.size() - sep.size(), 'x'); fmt::detail::format_error_code(buffer, codes[i], prefix); - EXPECT_EQ(prefix + sep + msg, to_string(buffer)); + EXPECT_EQ(prefix + sep + msg, to_string(buffer)); size_t size = fmt::inline_buffer_size; - EXPECT_EQ(size, buffer.size()); - buffer.resize(0); - // Test with a message that doesn't fit into the buffer. - prefix += 'x'; + EXPECT_EQ(size, buffer.size()); + buffer.resize(0); + // Test with a message that doesn't fit into the buffer. + prefix += 'x'; fmt::detail::format_error_code(buffer, codes[i], prefix); - EXPECT_EQ(msg, to_string(buffer)); - } -} - -TEST(FormatTest, CountCodePoints) { + EXPECT_EQ(msg, to_string(buffer)); + } +} + +TEST(FormatTest, CountCodePoints) { EXPECT_EQ(4, fmt::detail::count_code_points( fmt::basic_string_view<fmt::detail::char8_type>( reinterpret_cast<const fmt::detail::char8_type*>("ёжик")))); -} - +} + // Tests fmt::detail::count_digits for integer type Int. -template <typename Int> void test_count_digits() { +template <typename Int> void test_count_digits() { for (Int i = 0; i < 10; ++i) EXPECT_EQ(1u, fmt::detail::count_digits(i)); - for (Int i = 1, n = 1, end = max_value<Int>() / 10; n <= end; ++i) { - n *= 10; + for (Int i = 1, n = 1, end = max_value<Int>() / 10; n <= end; ++i) { + n *= 10; EXPECT_EQ(i, fmt::detail::count_digits(n - 1)); EXPECT_EQ(i + 1, fmt::detail::count_digits(n)); - } -} - -TEST(UtilTest, CountDigits) { - test_count_digits<uint32_t>(); - test_count_digits<uint64_t>(); -} - + } +} + +TEST(UtilTest, CountDigits) { + test_count_digits<uint32_t>(); + test_count_digits<uint64_t>(); +} + TEST(UtilTest, WriteFallbackUIntPtr) { std::string s; fmt::detail::write_ptr<char>( std::back_inserter(s), fmt::detail::fallback_uintptr(reinterpret_cast<void*>(0xface)), nullptr); EXPECT_EQ(s, "0xface"); -} +} #ifdef _WIN32 TEST(UtilTest, WriteConsoleSignature) { diff --git a/contrib/libs/fmt/test/format-impl-test/ya.make b/contrib/libs/fmt/test/format-impl-test/ya.make index 74364407b5..f8612f4120 100644 --- a/contrib/libs/fmt/test/format-impl-test/ya.make +++ b/contrib/libs/fmt/test/format-impl-test/ya.make @@ -1,37 +1,37 @@ -# Generated by devtools/yamaker. - +# Generated by devtools/yamaker. + GTEST() - + WITHOUT_LICENSE_TEXTS() - + OWNER( orivej g:cpp-contrib ) -LICENSE(MIT) - -PEERDIR( - contrib/libs/fmt - contrib/libs/fmt/test -) - -NO_COMPILER_WARNINGS() - -NO_UTIL() - -CFLAGS( - -DFMT_LOCALE - -DFMT_SHARED - -DGTEST_HAS_STD_WSTRING=1 - -DGTEST_LANG_CXX11=0 - -D_SILENCE_TR1_NAMESPACE_DEPRECATION_WARNING=1 -) - -SRCDIR(contrib/libs/fmt/test) - -SRCS( - format-impl-test.cc -) - -END() +LICENSE(MIT) + +PEERDIR( + contrib/libs/fmt + contrib/libs/fmt/test +) + +NO_COMPILER_WARNINGS() + +NO_UTIL() + +CFLAGS( + -DFMT_LOCALE + -DFMT_SHARED + -DGTEST_HAS_STD_WSTRING=1 + -DGTEST_LANG_CXX11=0 + -D_SILENCE_TR1_NAMESPACE_DEPRECATION_WARNING=1 +) + +SRCDIR(contrib/libs/fmt/test) + +SRCS( + format-impl-test.cc +) + +END() diff --git a/contrib/libs/fmt/test/format-test.cc b/contrib/libs/fmt/test/format-test.cc index 9acae430c3..6164ad60d6 100644 --- a/contrib/libs/fmt/test/format-test.cc +++ b/contrib/libs/fmt/test/format-test.cc @@ -1,178 +1,178 @@ -// Formatting library for C++ - formatting library tests -// -// Copyright (c) 2012 - present, Victor Zverovich -// All rights reserved. -// -// For the license information refer to format.h. - -#include <stdint.h> - -#include <cctype> -#include <cfloat> -#include <climits> -#include <cmath> -#include <cstring> -#include <list> -#include <memory> -#include <string> - -// Check if fmt/format.h compiles with windows.h included before it. -#ifdef _WIN32 -# include <windows.h> -#endif - -// Check if fmt/format.h compiles with the X11 index macro defined. -#define index(x, y) no nice things - -#include "fmt/format.h" - -#undef index - -#include <gmock/gmock.h> -#include "gtest-extra.h" -#include "mock-allocator.h" -#include "util.h" - -#undef ERROR - -using fmt::basic_memory_buffer; -using fmt::format; -using fmt::format_error; -using fmt::memory_buffer; -using fmt::string_view; -using fmt::wmemory_buffer; -using fmt::wstring_view; +// Formatting library for C++ - formatting library tests +// +// Copyright (c) 2012 - present, Victor Zverovich +// All rights reserved. +// +// For the license information refer to format.h. + +#include <stdint.h> + +#include <cctype> +#include <cfloat> +#include <climits> +#include <cmath> +#include <cstring> +#include <list> +#include <memory> +#include <string> + +// Check if fmt/format.h compiles with windows.h included before it. +#ifdef _WIN32 +# include <windows.h> +#endif + +// Check if fmt/format.h compiles with the X11 index macro defined. +#define index(x, y) no nice things + +#include "fmt/format.h" + +#undef index + +#include <gmock/gmock.h> +#include "gtest-extra.h" +#include "mock-allocator.h" +#include "util.h" + +#undef ERROR + +using fmt::basic_memory_buffer; +using fmt::format; +using fmt::format_error; +using fmt::memory_buffer; +using fmt::string_view; +using fmt::wmemory_buffer; +using fmt::wstring_view; using fmt::detail::max_value; - -using testing::Return; -using testing::StrictMock; - -namespace { - -#if !FMT_GCC_VERSION || FMT_GCC_VERSION >= 408 -template <typename Char, typename T> bool check_enabled_formatter() { - static_assert(std::is_default_constructible<fmt::formatter<T, Char>>::value, - ""); - return true; -} - -template <typename Char, typename... T> void check_enabled_formatters() { - auto dummy = {check_enabled_formatter<Char, T>()...}; - (void)dummy; -} - -TEST(FormatterTest, TestFormattersEnabled) { - check_enabled_formatters<char, bool, char, signed char, unsigned char, short, - unsigned short, int, unsigned, long, unsigned long, - long long, unsigned long long, float, double, - long double, void*, const void*, char*, const char*, - std::string, std::nullptr_t>(); - check_enabled_formatters<wchar_t, bool, wchar_t, signed char, unsigned char, - short, unsigned short, int, unsigned, long, - unsigned long, long long, unsigned long long, float, - double, long double, void*, const void*, wchar_t*, - const wchar_t*, std::wstring, std::nullptr_t>(); -} -#endif - -// Format value using the standard library. -template <typename Char, typename T> -void std_format(const T& value, std::basic_string<Char>& result) { - std::basic_ostringstream<Char> os; - os << value; - result = os.str(); -} - -#ifdef __MINGW32__ -// Workaround a bug in formatting long double in MinGW. -void std_format(long double value, std::string& result) { - char buffer[100]; - safe_sprintf(buffer, "%Lg", value); - result = buffer; -} -void std_format(long double value, std::wstring& result) { - wchar_t buffer[100]; - swprintf(buffer, L"%Lg", value); - result = buffer; -} -#endif -} // namespace - -struct uint32_pair { - uint32_t u[2]; -}; - -TEST(UtilTest, BitCast) { + +using testing::Return; +using testing::StrictMock; + +namespace { + +#if !FMT_GCC_VERSION || FMT_GCC_VERSION >= 408 +template <typename Char, typename T> bool check_enabled_formatter() { + static_assert(std::is_default_constructible<fmt::formatter<T, Char>>::value, + ""); + return true; +} + +template <typename Char, typename... T> void check_enabled_formatters() { + auto dummy = {check_enabled_formatter<Char, T>()...}; + (void)dummy; +} + +TEST(FormatterTest, TestFormattersEnabled) { + check_enabled_formatters<char, bool, char, signed char, unsigned char, short, + unsigned short, int, unsigned, long, unsigned long, + long long, unsigned long long, float, double, + long double, void*, const void*, char*, const char*, + std::string, std::nullptr_t>(); + check_enabled_formatters<wchar_t, bool, wchar_t, signed char, unsigned char, + short, unsigned short, int, unsigned, long, + unsigned long, long long, unsigned long long, float, + double, long double, void*, const void*, wchar_t*, + const wchar_t*, std::wstring, std::nullptr_t>(); +} +#endif + +// Format value using the standard library. +template <typename Char, typename T> +void std_format(const T& value, std::basic_string<Char>& result) { + std::basic_ostringstream<Char> os; + os << value; + result = os.str(); +} + +#ifdef __MINGW32__ +// Workaround a bug in formatting long double in MinGW. +void std_format(long double value, std::string& result) { + char buffer[100]; + safe_sprintf(buffer, "%Lg", value); + result = buffer; +} +void std_format(long double value, std::wstring& result) { + wchar_t buffer[100]; + swprintf(buffer, L"%Lg", value); + result = buffer; +} +#endif +} // namespace + +struct uint32_pair { + uint32_t u[2]; +}; + +TEST(UtilTest, BitCast) { auto s = fmt::detail::bit_cast<uint32_pair>(uint64_t{42}); EXPECT_EQ(fmt::detail::bit_cast<uint64_t>(s), 42ull); s = fmt::detail::bit_cast<uint32_pair>(uint64_t(~0ull)); EXPECT_EQ(fmt::detail::bit_cast<uint64_t>(s), ~0ull); -} - -TEST(UtilTest, Increment) { - char s[10] = "123"; - increment(s); - EXPECT_STREQ("124", s); - s[2] = '8'; - increment(s); - EXPECT_STREQ("129", s); - increment(s); - EXPECT_STREQ("130", s); - s[1] = s[2] = '9'; - increment(s); - EXPECT_STREQ("200", s); -} - -TEST(UtilTest, ParseNonnegativeInt) { - if (max_value<int>() != static_cast<int>(static_cast<unsigned>(1) << 31)) { - fmt::print("Skipping parse_nonnegative_int test\n"); - return; - } - fmt::string_view s = "10000000000"; - auto begin = s.begin(), end = s.end(); - EXPECT_THROW_MSG( +} + +TEST(UtilTest, Increment) { + char s[10] = "123"; + increment(s); + EXPECT_STREQ("124", s); + s[2] = '8'; + increment(s); + EXPECT_STREQ("129", s); + increment(s); + EXPECT_STREQ("130", s); + s[1] = s[2] = '9'; + increment(s); + EXPECT_STREQ("200", s); +} + +TEST(UtilTest, ParseNonnegativeInt) { + if (max_value<int>() != static_cast<int>(static_cast<unsigned>(1) << 31)) { + fmt::print("Skipping parse_nonnegative_int test\n"); + return; + } + fmt::string_view s = "10000000000"; + auto begin = s.begin(), end = s.end(); + EXPECT_THROW_MSG( parse_nonnegative_int(begin, end, fmt::detail::error_handler()), - fmt::format_error, "number is too big"); - s = "2147483649"; - begin = s.begin(); - end = s.end(); - EXPECT_THROW_MSG( + fmt::format_error, "number is too big"); + s = "2147483649"; + begin = s.begin(); + end = s.end(); + EXPECT_THROW_MSG( parse_nonnegative_int(begin, end, fmt::detail::error_handler()), - fmt::format_error, "number is too big"); -} - -TEST(IteratorTest, CountingIterator) { + fmt::format_error, "number is too big"); +} + +TEST(IteratorTest, CountingIterator) { fmt::detail::counting_iterator it; - auto prev = it++; - EXPECT_EQ(prev.count(), 0); - EXPECT_EQ(it.count(), 1); + auto prev = it++; + EXPECT_EQ(prev.count(), 0); + EXPECT_EQ(it.count(), 1); EXPECT_EQ((it + 41).count(), 42); -} - -TEST(IteratorTest, TruncatingIterator) { - char* p = nullptr; +} + +TEST(IteratorTest, TruncatingIterator) { + char* p = nullptr; fmt::detail::truncating_iterator<char*> it(p, 3); - auto prev = it++; - EXPECT_EQ(prev.base(), p); - EXPECT_EQ(it.base(), p + 1); -} - -TEST(IteratorTest, TruncatingBackInserter) { - std::string buffer; - auto bi = std::back_inserter(buffer); + auto prev = it++; + EXPECT_EQ(prev.base(), p); + EXPECT_EQ(it.base(), p + 1); +} + +TEST(IteratorTest, TruncatingBackInserter) { + std::string buffer; + auto bi = std::back_inserter(buffer); fmt::detail::truncating_iterator<decltype(bi)> it(bi, 2); - *it++ = '4'; - *it++ = '2'; - *it++ = '1'; - EXPECT_EQ(buffer.size(), 2); - EXPECT_EQ(buffer, "42"); -} - -TEST(IteratorTest, IsOutputIterator) { + *it++ = '4'; + *it++ = '2'; + *it++ = '1'; + EXPECT_EQ(buffer.size(), 2); + EXPECT_EQ(buffer, "42"); +} + +TEST(IteratorTest, IsOutputIterator) { EXPECT_TRUE((fmt::detail::is_output_iterator<char*, char>::value)); EXPECT_FALSE((fmt::detail::is_output_iterator<const char*, char>::value)); EXPECT_FALSE((fmt::detail::is_output_iterator<std::string, char>::value)); - EXPECT_TRUE( + EXPECT_TRUE( (fmt::detail::is_output_iterator<std::back_insert_iterator<std::string>, char>::value)); EXPECT_TRUE( @@ -185,1106 +185,1106 @@ TEST(IteratorTest, IsOutputIterator) { EXPECT_FALSE((fmt::detail::is_output_iterator<std::list<char>::const_iterator, char>::value)); EXPECT_FALSE((fmt::detail::is_output_iterator<uint32_pair, char>::value)); -} - -TEST(MemoryBufferTest, Ctor) { - basic_memory_buffer<char, 123> buffer; - EXPECT_EQ(static_cast<size_t>(0), buffer.size()); - EXPECT_EQ(123u, buffer.capacity()); -} - -static void check_forwarding(mock_allocator<int>& alloc, - allocator_ref<mock_allocator<int>>& ref) { - int mem; - // Check if value_type is properly defined. - allocator_ref<mock_allocator<int>>::value_type* ptr = &mem; - // Check forwarding. - EXPECT_CALL(alloc, allocate(42)).WillOnce(testing::Return(ptr)); - ref.allocate(42); - EXPECT_CALL(alloc, deallocate(ptr, 42)); - ref.deallocate(ptr, 42); -} - -TEST(AllocatorTest, allocator_ref) { - StrictMock<mock_allocator<int>> alloc; - typedef allocator_ref<mock_allocator<int>> test_allocator_ref; - test_allocator_ref ref(&alloc); - // Check if allocator_ref forwards to the underlying allocator. - check_forwarding(alloc, ref); - test_allocator_ref ref2(ref); - check_forwarding(alloc, ref2); - test_allocator_ref ref3; - EXPECT_EQ(nullptr, ref3.get()); - ref3 = ref; - check_forwarding(alloc, ref3); -} - -typedef allocator_ref<std::allocator<char>> TestAllocator; - -static void check_move_buffer( - const char* str, basic_memory_buffer<char, 5, TestAllocator>& buffer) { - std::allocator<char>* alloc = buffer.get_allocator().get(); - basic_memory_buffer<char, 5, TestAllocator> buffer2(std::move(buffer)); - // Move shouldn't destroy the inline content of the first buffer. - EXPECT_EQ(str, std::string(&buffer[0], buffer.size())); - EXPECT_EQ(str, std::string(&buffer2[0], buffer2.size())); - EXPECT_EQ(5u, buffer2.capacity()); - // Move should transfer allocator. - EXPECT_EQ(nullptr, buffer.get_allocator().get()); - EXPECT_EQ(alloc, buffer2.get_allocator().get()); -} - -TEST(MemoryBufferTest, MoveCtorInlineBuffer) { - std::allocator<char> alloc; - basic_memory_buffer<char, 5, TestAllocator> buffer((TestAllocator(&alloc))); - const char test[] = "test"; +} + +TEST(MemoryBufferTest, Ctor) { + basic_memory_buffer<char, 123> buffer; + EXPECT_EQ(static_cast<size_t>(0), buffer.size()); + EXPECT_EQ(123u, buffer.capacity()); +} + +static void check_forwarding(mock_allocator<int>& alloc, + allocator_ref<mock_allocator<int>>& ref) { + int mem; + // Check if value_type is properly defined. + allocator_ref<mock_allocator<int>>::value_type* ptr = &mem; + // Check forwarding. + EXPECT_CALL(alloc, allocate(42)).WillOnce(testing::Return(ptr)); + ref.allocate(42); + EXPECT_CALL(alloc, deallocate(ptr, 42)); + ref.deallocate(ptr, 42); +} + +TEST(AllocatorTest, allocator_ref) { + StrictMock<mock_allocator<int>> alloc; + typedef allocator_ref<mock_allocator<int>> test_allocator_ref; + test_allocator_ref ref(&alloc); + // Check if allocator_ref forwards to the underlying allocator. + check_forwarding(alloc, ref); + test_allocator_ref ref2(ref); + check_forwarding(alloc, ref2); + test_allocator_ref ref3; + EXPECT_EQ(nullptr, ref3.get()); + ref3 = ref; + check_forwarding(alloc, ref3); +} + +typedef allocator_ref<std::allocator<char>> TestAllocator; + +static void check_move_buffer( + const char* str, basic_memory_buffer<char, 5, TestAllocator>& buffer) { + std::allocator<char>* alloc = buffer.get_allocator().get(); + basic_memory_buffer<char, 5, TestAllocator> buffer2(std::move(buffer)); + // Move shouldn't destroy the inline content of the first buffer. + EXPECT_EQ(str, std::string(&buffer[0], buffer.size())); + EXPECT_EQ(str, std::string(&buffer2[0], buffer2.size())); + EXPECT_EQ(5u, buffer2.capacity()); + // Move should transfer allocator. + EXPECT_EQ(nullptr, buffer.get_allocator().get()); + EXPECT_EQ(alloc, buffer2.get_allocator().get()); +} + +TEST(MemoryBufferTest, MoveCtorInlineBuffer) { + std::allocator<char> alloc; + basic_memory_buffer<char, 5, TestAllocator> buffer((TestAllocator(&alloc))); + const char test[] = "test"; buffer.append(string_view(test, 4)); - check_move_buffer("test", buffer); - // Adding one more character fills the inline buffer, but doesn't cause - // dynamic allocation. - buffer.push_back('a'); - check_move_buffer("testa", buffer); -} - -TEST(MemoryBufferTest, MoveCtorDynamicBuffer) { - std::allocator<char> alloc; - basic_memory_buffer<char, 4, TestAllocator> buffer((TestAllocator(&alloc))); - const char test[] = "test"; - buffer.append(test, test + 4); - const char* inline_buffer_ptr = &buffer[0]; - // Adding one more character causes the content to move from the inline to - // a dynamically allocated buffer. - buffer.push_back('a'); - basic_memory_buffer<char, 4, TestAllocator> buffer2(std::move(buffer)); - // Move should rip the guts of the first buffer. - EXPECT_EQ(inline_buffer_ptr, &buffer[0]); - EXPECT_EQ("testa", std::string(&buffer2[0], buffer2.size())); - EXPECT_GT(buffer2.capacity(), 4u); -} - -static void check_move_assign_buffer(const char* str, - basic_memory_buffer<char, 5>& buffer) { - basic_memory_buffer<char, 5> buffer2; - buffer2 = std::move(buffer); - // Move shouldn't destroy the inline content of the first buffer. - EXPECT_EQ(str, std::string(&buffer[0], buffer.size())); - EXPECT_EQ(str, std::string(&buffer2[0], buffer2.size())); - EXPECT_EQ(5u, buffer2.capacity()); -} - -TEST(MemoryBufferTest, MoveAssignment) { - basic_memory_buffer<char, 5> buffer; - const char test[] = "test"; - buffer.append(test, test + 4); - check_move_assign_buffer("test", buffer); - // Adding one more character fills the inline buffer, but doesn't cause - // dynamic allocation. - buffer.push_back('a'); - check_move_assign_buffer("testa", buffer); - const char* inline_buffer_ptr = &buffer[0]; - // Adding one more character causes the content to move from the inline to - // a dynamically allocated buffer. - buffer.push_back('b'); - basic_memory_buffer<char, 5> buffer2; - buffer2 = std::move(buffer); - // Move should rip the guts of the first buffer. - EXPECT_EQ(inline_buffer_ptr, &buffer[0]); - EXPECT_EQ("testab", std::string(&buffer2[0], buffer2.size())); - EXPECT_GT(buffer2.capacity(), 5u); -} - -TEST(MemoryBufferTest, Grow) { - typedef allocator_ref<mock_allocator<int>> Allocator; - mock_allocator<int> alloc; + check_move_buffer("test", buffer); + // Adding one more character fills the inline buffer, but doesn't cause + // dynamic allocation. + buffer.push_back('a'); + check_move_buffer("testa", buffer); +} + +TEST(MemoryBufferTest, MoveCtorDynamicBuffer) { + std::allocator<char> alloc; + basic_memory_buffer<char, 4, TestAllocator> buffer((TestAllocator(&alloc))); + const char test[] = "test"; + buffer.append(test, test + 4); + const char* inline_buffer_ptr = &buffer[0]; + // Adding one more character causes the content to move from the inline to + // a dynamically allocated buffer. + buffer.push_back('a'); + basic_memory_buffer<char, 4, TestAllocator> buffer2(std::move(buffer)); + // Move should rip the guts of the first buffer. + EXPECT_EQ(inline_buffer_ptr, &buffer[0]); + EXPECT_EQ("testa", std::string(&buffer2[0], buffer2.size())); + EXPECT_GT(buffer2.capacity(), 4u); +} + +static void check_move_assign_buffer(const char* str, + basic_memory_buffer<char, 5>& buffer) { + basic_memory_buffer<char, 5> buffer2; + buffer2 = std::move(buffer); + // Move shouldn't destroy the inline content of the first buffer. + EXPECT_EQ(str, std::string(&buffer[0], buffer.size())); + EXPECT_EQ(str, std::string(&buffer2[0], buffer2.size())); + EXPECT_EQ(5u, buffer2.capacity()); +} + +TEST(MemoryBufferTest, MoveAssignment) { + basic_memory_buffer<char, 5> buffer; + const char test[] = "test"; + buffer.append(test, test + 4); + check_move_assign_buffer("test", buffer); + // Adding one more character fills the inline buffer, but doesn't cause + // dynamic allocation. + buffer.push_back('a'); + check_move_assign_buffer("testa", buffer); + const char* inline_buffer_ptr = &buffer[0]; + // Adding one more character causes the content to move from the inline to + // a dynamically allocated buffer. + buffer.push_back('b'); + basic_memory_buffer<char, 5> buffer2; + buffer2 = std::move(buffer); + // Move should rip the guts of the first buffer. + EXPECT_EQ(inline_buffer_ptr, &buffer[0]); + EXPECT_EQ("testab", std::string(&buffer2[0], buffer2.size())); + EXPECT_GT(buffer2.capacity(), 5u); +} + +TEST(MemoryBufferTest, Grow) { + typedef allocator_ref<mock_allocator<int>> Allocator; + mock_allocator<int> alloc; basic_memory_buffer<int, 10, Allocator> buffer((Allocator(&alloc))); - buffer.resize(7); + buffer.resize(7); using fmt::detail::to_unsigned; - for (int i = 0; i < 7; ++i) buffer[to_unsigned(i)] = i * i; - EXPECT_EQ(10u, buffer.capacity()); - int mem[20]; - mem[7] = 0xdead; - EXPECT_CALL(alloc, allocate(20)).WillOnce(Return(mem)); + for (int i = 0; i < 7; ++i) buffer[to_unsigned(i)] = i * i; + EXPECT_EQ(10u, buffer.capacity()); + int mem[20]; + mem[7] = 0xdead; + EXPECT_CALL(alloc, allocate(20)).WillOnce(Return(mem)); buffer.try_reserve(20); - EXPECT_EQ(20u, buffer.capacity()); - // Check if size elements have been copied - for (int i = 0; i < 7; ++i) EXPECT_EQ(i * i, buffer[to_unsigned(i)]); - // and no more than that. - EXPECT_EQ(0xdead, buffer[7]); - EXPECT_CALL(alloc, deallocate(mem, 20)); -} - -TEST(MemoryBufferTest, Allocator) { - typedef allocator_ref<mock_allocator<char>> TestAllocator; - basic_memory_buffer<char, 10, TestAllocator> buffer; - EXPECT_EQ(nullptr, buffer.get_allocator().get()); - StrictMock<mock_allocator<char>> alloc; - char mem; - { - basic_memory_buffer<char, 10, TestAllocator> buffer2( - (TestAllocator(&alloc))); - EXPECT_EQ(&alloc, buffer2.get_allocator().get()); + EXPECT_EQ(20u, buffer.capacity()); + // Check if size elements have been copied + for (int i = 0; i < 7; ++i) EXPECT_EQ(i * i, buffer[to_unsigned(i)]); + // and no more than that. + EXPECT_EQ(0xdead, buffer[7]); + EXPECT_CALL(alloc, deallocate(mem, 20)); +} + +TEST(MemoryBufferTest, Allocator) { + typedef allocator_ref<mock_allocator<char>> TestAllocator; + basic_memory_buffer<char, 10, TestAllocator> buffer; + EXPECT_EQ(nullptr, buffer.get_allocator().get()); + StrictMock<mock_allocator<char>> alloc; + char mem; + { + basic_memory_buffer<char, 10, TestAllocator> buffer2( + (TestAllocator(&alloc))); + EXPECT_EQ(&alloc, buffer2.get_allocator().get()); size_t size = 2 * fmt::inline_buffer_size; - EXPECT_CALL(alloc, allocate(size)).WillOnce(Return(&mem)); - buffer2.reserve(size); - EXPECT_CALL(alloc, deallocate(&mem, size)); - } -} - -TEST(MemoryBufferTest, ExceptionInDeallocate) { - typedef allocator_ref<mock_allocator<char>> TestAllocator; - StrictMock<mock_allocator<char>> alloc; - basic_memory_buffer<char, 10, TestAllocator> buffer((TestAllocator(&alloc))); + EXPECT_CALL(alloc, allocate(size)).WillOnce(Return(&mem)); + buffer2.reserve(size); + EXPECT_CALL(alloc, deallocate(&mem, size)); + } +} + +TEST(MemoryBufferTest, ExceptionInDeallocate) { + typedef allocator_ref<mock_allocator<char>> TestAllocator; + StrictMock<mock_allocator<char>> alloc; + basic_memory_buffer<char, 10, TestAllocator> buffer((TestAllocator(&alloc))); size_t size = 2 * fmt::inline_buffer_size; - std::vector<char> mem(size); - { - EXPECT_CALL(alloc, allocate(size)).WillOnce(Return(&mem[0])); - buffer.resize(size); - std::fill(&buffer[0], &buffer[0] + size, 'x'); - } - std::vector<char> mem2(2 * size); - { - EXPECT_CALL(alloc, allocate(2 * size)).WillOnce(Return(&mem2[0])); - std::exception e; - EXPECT_CALL(alloc, deallocate(&mem[0], size)).WillOnce(testing::Throw(e)); - EXPECT_THROW(buffer.reserve(2 * size), std::exception); - EXPECT_EQ(&mem2[0], &buffer[0]); - // Check that the data has been copied. + std::vector<char> mem(size); + { + EXPECT_CALL(alloc, allocate(size)).WillOnce(Return(&mem[0])); + buffer.resize(size); + std::fill(&buffer[0], &buffer[0] + size, 'x'); + } + std::vector<char> mem2(2 * size); + { + EXPECT_CALL(alloc, allocate(2 * size)).WillOnce(Return(&mem2[0])); + std::exception e; + EXPECT_CALL(alloc, deallocate(&mem[0], size)).WillOnce(testing::Throw(e)); + EXPECT_THROW(buffer.reserve(2 * size), std::exception); + EXPECT_EQ(&mem2[0], &buffer[0]); + // Check that the data has been copied. for (size_t i = 0; i < size; ++i) EXPECT_EQ('x', buffer[i]); - } - EXPECT_CALL(alloc, deallocate(&mem2[0], 2 * size)); -} - -TEST(UtilTest, UTF8ToUTF16) { + } + EXPECT_CALL(alloc, deallocate(&mem2[0], 2 * size)); +} + +TEST(UtilTest, UTF8ToUTF16) { fmt::detail::utf8_to_utf16 u("лошадка"); - EXPECT_EQ(L"\x043B\x043E\x0448\x0430\x0434\x043A\x0430", u.str()); - EXPECT_EQ(7, u.size()); - // U+10437 { DESERET SMALL LETTER YEE } + EXPECT_EQ(L"\x043B\x043E\x0448\x0430\x0434\x043A\x0430", u.str()); + EXPECT_EQ(7, u.size()); + // U+10437 { DESERET SMALL LETTER YEE } EXPECT_EQ(L"\xD801\xDC37", fmt::detail::utf8_to_utf16("𐐷").str()); EXPECT_THROW_MSG(fmt::detail::utf8_to_utf16("\xc3\x28"), std::runtime_error, - "invalid utf8"); + "invalid utf8"); EXPECT_THROW_MSG(fmt::detail::utf8_to_utf16(fmt::string_view("л", 1)), - std::runtime_error, "invalid utf8"); + std::runtime_error, "invalid utf8"); EXPECT_EQ(L"123456", fmt::detail::utf8_to_utf16("123456").str()); -} - -TEST(UtilTest, UTF8ToUTF16EmptyString) { - std::string s = ""; +} + +TEST(UtilTest, UTF8ToUTF16EmptyString) { + std::string s = ""; fmt::detail::utf8_to_utf16 u(s.c_str()); - EXPECT_EQ(L"", u.str()); - EXPECT_EQ(s.size(), u.size()); -} - -TEST(UtilTest, FormatSystemError) { - fmt::memory_buffer message; - fmt::format_system_error(message, EDOM, "test"); - EXPECT_EQ(fmt::format("test: {}", get_system_error(EDOM)), - to_string(message)); - message = fmt::memory_buffer(); - - // Check if std::allocator throws on allocating max size_t / 2 chars. - size_t max_size = max_value<size_t>() / 2; - bool throws_on_alloc = false; - try { - std::allocator<char> alloc; - alloc.deallocate(alloc.allocate(max_size), max_size); - } catch (const std::bad_alloc&) { - throws_on_alloc = true; - } - if (!throws_on_alloc) { - fmt::print("warning: std::allocator allocates {} chars", max_size); - return; - } - fmt::format_system_error(message, EDOM, fmt::string_view(nullptr, max_size)); - EXPECT_EQ(fmt::format("error {}", EDOM), to_string(message)); -} - -TEST(UtilTest, SystemError) { - fmt::system_error e(EDOM, "test"); - EXPECT_EQ(fmt::format("test: {}", get_system_error(EDOM)), e.what()); - EXPECT_EQ(EDOM, e.error_code()); - - fmt::system_error error(0, ""); - try { - throw fmt::system_error(EDOM, "test {}", "error"); - } catch (const fmt::system_error& e) { - error = e; - } - fmt::memory_buffer message; - fmt::format_system_error(message, EDOM, "test error"); - EXPECT_EQ(to_string(message), error.what()); - EXPECT_EQ(EDOM, error.error_code()); -} - -TEST(UtilTest, ReportSystemError) { - fmt::memory_buffer out; - fmt::format_system_error(out, EDOM, "test error"); - out.push_back('\n'); - EXPECT_WRITE(stderr, fmt::report_system_error(EDOM, "test error"), - to_string(out)); -} - -TEST(StringViewTest, Ctor) { - EXPECT_STREQ("abc", string_view("abc").data()); - EXPECT_EQ(3u, string_view("abc").size()); - - EXPECT_STREQ("defg", string_view(std::string("defg")).data()); - EXPECT_EQ(4u, string_view(std::string("defg")).size()); -} - -TEST(FormatToTest, FormatWithoutArgs) { - std::string s; - fmt::format_to(std::back_inserter(s), "test"); - EXPECT_EQ("test", s); -} - -TEST(FormatToTest, Format) { - std::string s; - fmt::format_to(std::back_inserter(s), "part{0}", 1); - EXPECT_EQ("part1", s); - fmt::format_to(std::back_inserter(s), "part{0}", 2); - EXPECT_EQ("part1part2", s); -} - -TEST(FormatToTest, WideString) { - std::vector<wchar_t> buf; - fmt::format_to(std::back_inserter(buf), L"{}{}", 42, L'\0'); - EXPECT_STREQ(buf.data(), L"42"); -} - -TEST(FormatToTest, FormatToMemoryBuffer) { - fmt::basic_memory_buffer<char, 100> buffer; - fmt::format_to(buffer, "{}", "foo"); - EXPECT_EQ("foo", to_string(buffer)); - fmt::wmemory_buffer wbuffer; - fmt::format_to(wbuffer, L"{}", L"foo"); - EXPECT_EQ(L"foo", to_string(wbuffer)); -} - -TEST(FormatterTest, Escape) { - EXPECT_EQ("{", format("{{")); - EXPECT_EQ("before {", format("before {{")); - EXPECT_EQ("{ after", format("{{ after")); - EXPECT_EQ("before { after", format("before {{ after")); - - EXPECT_EQ("}", format("}}")); - EXPECT_EQ("before }", format("before }}")); - EXPECT_EQ("} after", format("}} after")); - EXPECT_EQ("before } after", format("before }} after")); - - EXPECT_EQ("{}", format("{{}}")); - EXPECT_EQ("{42}", format("{{{0}}}", 42)); -} - -TEST(FormatterTest, UnmatchedBraces) { - EXPECT_THROW_MSG(format("{"), format_error, "invalid format string"); - EXPECT_THROW_MSG(format("}"), format_error, "unmatched '}' in format string"); - EXPECT_THROW_MSG(format("{0{}"), format_error, "invalid format string"); -} - -TEST(FormatterTest, NoArgs) { EXPECT_EQ("test", format("test")); } - -TEST(FormatterTest, ArgsInDifferentPositions) { - EXPECT_EQ("42", format("{0}", 42)); - EXPECT_EQ("before 42", format("before {0}", 42)); - EXPECT_EQ("42 after", format("{0} after", 42)); - EXPECT_EQ("before 42 after", format("before {0} after", 42)); - EXPECT_EQ("answer = 42", format("{0} = {1}", "answer", 42)); - EXPECT_EQ("42 is the answer", format("{1} is the {0}", "answer", 42)); - EXPECT_EQ("abracadabra", format("{0}{1}{0}", "abra", "cad")); -} - -TEST(FormatterTest, ArgErrors) { - EXPECT_THROW_MSG(format("{"), format_error, "invalid format string"); - EXPECT_THROW_MSG(format("{?}"), format_error, "invalid format string"); - EXPECT_THROW_MSG(format("{0"), format_error, "invalid format string"); + EXPECT_EQ(L"", u.str()); + EXPECT_EQ(s.size(), u.size()); +} + +TEST(UtilTest, FormatSystemError) { + fmt::memory_buffer message; + fmt::format_system_error(message, EDOM, "test"); + EXPECT_EQ(fmt::format("test: {}", get_system_error(EDOM)), + to_string(message)); + message = fmt::memory_buffer(); + + // Check if std::allocator throws on allocating max size_t / 2 chars. + size_t max_size = max_value<size_t>() / 2; + bool throws_on_alloc = false; + try { + std::allocator<char> alloc; + alloc.deallocate(alloc.allocate(max_size), max_size); + } catch (const std::bad_alloc&) { + throws_on_alloc = true; + } + if (!throws_on_alloc) { + fmt::print("warning: std::allocator allocates {} chars", max_size); + return; + } + fmt::format_system_error(message, EDOM, fmt::string_view(nullptr, max_size)); + EXPECT_EQ(fmt::format("error {}", EDOM), to_string(message)); +} + +TEST(UtilTest, SystemError) { + fmt::system_error e(EDOM, "test"); + EXPECT_EQ(fmt::format("test: {}", get_system_error(EDOM)), e.what()); + EXPECT_EQ(EDOM, e.error_code()); + + fmt::system_error error(0, ""); + try { + throw fmt::system_error(EDOM, "test {}", "error"); + } catch (const fmt::system_error& e) { + error = e; + } + fmt::memory_buffer message; + fmt::format_system_error(message, EDOM, "test error"); + EXPECT_EQ(to_string(message), error.what()); + EXPECT_EQ(EDOM, error.error_code()); +} + +TEST(UtilTest, ReportSystemError) { + fmt::memory_buffer out; + fmt::format_system_error(out, EDOM, "test error"); + out.push_back('\n'); + EXPECT_WRITE(stderr, fmt::report_system_error(EDOM, "test error"), + to_string(out)); +} + +TEST(StringViewTest, Ctor) { + EXPECT_STREQ("abc", string_view("abc").data()); + EXPECT_EQ(3u, string_view("abc").size()); + + EXPECT_STREQ("defg", string_view(std::string("defg")).data()); + EXPECT_EQ(4u, string_view(std::string("defg")).size()); +} + +TEST(FormatToTest, FormatWithoutArgs) { + std::string s; + fmt::format_to(std::back_inserter(s), "test"); + EXPECT_EQ("test", s); +} + +TEST(FormatToTest, Format) { + std::string s; + fmt::format_to(std::back_inserter(s), "part{0}", 1); + EXPECT_EQ("part1", s); + fmt::format_to(std::back_inserter(s), "part{0}", 2); + EXPECT_EQ("part1part2", s); +} + +TEST(FormatToTest, WideString) { + std::vector<wchar_t> buf; + fmt::format_to(std::back_inserter(buf), L"{}{}", 42, L'\0'); + EXPECT_STREQ(buf.data(), L"42"); +} + +TEST(FormatToTest, FormatToMemoryBuffer) { + fmt::basic_memory_buffer<char, 100> buffer; + fmt::format_to(buffer, "{}", "foo"); + EXPECT_EQ("foo", to_string(buffer)); + fmt::wmemory_buffer wbuffer; + fmt::format_to(wbuffer, L"{}", L"foo"); + EXPECT_EQ(L"foo", to_string(wbuffer)); +} + +TEST(FormatterTest, Escape) { + EXPECT_EQ("{", format("{{")); + EXPECT_EQ("before {", format("before {{")); + EXPECT_EQ("{ after", format("{{ after")); + EXPECT_EQ("before { after", format("before {{ after")); + + EXPECT_EQ("}", format("}}")); + EXPECT_EQ("before }", format("before }}")); + EXPECT_EQ("} after", format("}} after")); + EXPECT_EQ("before } after", format("before }} after")); + + EXPECT_EQ("{}", format("{{}}")); + EXPECT_EQ("{42}", format("{{{0}}}", 42)); +} + +TEST(FormatterTest, UnmatchedBraces) { + EXPECT_THROW_MSG(format("{"), format_error, "invalid format string"); + EXPECT_THROW_MSG(format("}"), format_error, "unmatched '}' in format string"); + EXPECT_THROW_MSG(format("{0{}"), format_error, "invalid format string"); +} + +TEST(FormatterTest, NoArgs) { EXPECT_EQ("test", format("test")); } + +TEST(FormatterTest, ArgsInDifferentPositions) { + EXPECT_EQ("42", format("{0}", 42)); + EXPECT_EQ("before 42", format("before {0}", 42)); + EXPECT_EQ("42 after", format("{0} after", 42)); + EXPECT_EQ("before 42 after", format("before {0} after", 42)); + EXPECT_EQ("answer = 42", format("{0} = {1}", "answer", 42)); + EXPECT_EQ("42 is the answer", format("{1} is the {0}", "answer", 42)); + EXPECT_EQ("abracadabra", format("{0}{1}{0}", "abra", "cad")); +} + +TEST(FormatterTest, ArgErrors) { + EXPECT_THROW_MSG(format("{"), format_error, "invalid format string"); + EXPECT_THROW_MSG(format("{?}"), format_error, "invalid format string"); + EXPECT_THROW_MSG(format("{0"), format_error, "invalid format string"); EXPECT_THROW_MSG(format("{0}"), format_error, "argument not found"); - EXPECT_THROW_MSG(format("{00}", 42), format_error, "invalid format string"); - - char format_str[BUFFER_SIZE]; - safe_sprintf(format_str, "{%u", INT_MAX); - EXPECT_THROW_MSG(format(format_str), format_error, "invalid format string"); - safe_sprintf(format_str, "{%u}", INT_MAX); + EXPECT_THROW_MSG(format("{00}", 42), format_error, "invalid format string"); + + char format_str[BUFFER_SIZE]; + safe_sprintf(format_str, "{%u", INT_MAX); + EXPECT_THROW_MSG(format(format_str), format_error, "invalid format string"); + safe_sprintf(format_str, "{%u}", INT_MAX); EXPECT_THROW_MSG(format(format_str), format_error, "argument not found"); - - safe_sprintf(format_str, "{%u", INT_MAX + 1u); - EXPECT_THROW_MSG(format(format_str), format_error, "number is too big"); - safe_sprintf(format_str, "{%u}", INT_MAX + 1u); - EXPECT_THROW_MSG(format(format_str), format_error, "number is too big"); -} - -template <int N> struct TestFormat { - template <typename... Args> - static std::string format(fmt::string_view format_str, const Args&... args) { - return TestFormat<N - 1>::format(format_str, N - 1, args...); - } -}; - -template <> struct TestFormat<0> { - template <typename... Args> - static std::string format(fmt::string_view format_str, const Args&... args) { - return fmt::format(format_str, args...); - } -}; - -TEST(FormatterTest, ManyArgs) { - EXPECT_EQ("19", TestFormat<20>::format("{19}")); - EXPECT_THROW_MSG(TestFormat<20>::format("{20}"), format_error, + + safe_sprintf(format_str, "{%u", INT_MAX + 1u); + EXPECT_THROW_MSG(format(format_str), format_error, "number is too big"); + safe_sprintf(format_str, "{%u}", INT_MAX + 1u); + EXPECT_THROW_MSG(format(format_str), format_error, "number is too big"); +} + +template <int N> struct TestFormat { + template <typename... Args> + static std::string format(fmt::string_view format_str, const Args&... args) { + return TestFormat<N - 1>::format(format_str, N - 1, args...); + } +}; + +template <> struct TestFormat<0> { + template <typename... Args> + static std::string format(fmt::string_view format_str, const Args&... args) { + return fmt::format(format_str, args...); + } +}; + +TEST(FormatterTest, ManyArgs) { + EXPECT_EQ("19", TestFormat<20>::format("{19}")); + EXPECT_THROW_MSG(TestFormat<20>::format("{20}"), format_error, "argument not found"); - EXPECT_THROW_MSG(TestFormat<21>::format("{21}"), format_error, + EXPECT_THROW_MSG(TestFormat<21>::format("{21}"), format_error, "argument not found"); enum { max_packed_args = fmt::detail::max_packed_args }; - std::string format_str = fmt::format("{{{}}}", max_packed_args + 1); - EXPECT_THROW_MSG(TestFormat<max_packed_args>::format(format_str), + std::string format_str = fmt::format("{{{}}}", max_packed_args + 1); + EXPECT_THROW_MSG(TestFormat<max_packed_args>::format(format_str), format_error, "argument not found"); -} - -TEST(FormatterTest, NamedArg) { - EXPECT_EQ("1/a/A", format("{_1}/{a_}/{A_}", fmt::arg("a_", 'a'), - fmt::arg("A_", "A"), fmt::arg("_1", 1))); - EXPECT_EQ(" -42", format("{0:{width}}", -42, fmt::arg("width", 4))); - EXPECT_EQ("st", format("{0:.{precision}}", "str", fmt::arg("precision", 2))); - EXPECT_EQ("1 2", format("{} {two}", 1, fmt::arg("two", 2))); - EXPECT_EQ("42", format("{c}", fmt::arg("a", 0), fmt::arg("b", 0), - fmt::arg("c", 42), fmt::arg("d", 0), fmt::arg("e", 0), - fmt::arg("f", 0), fmt::arg("g", 0), fmt::arg("h", 0), - fmt::arg("i", 0), fmt::arg("j", 0), fmt::arg("k", 0), - fmt::arg("l", 0), fmt::arg("m", 0), fmt::arg("n", 0), - fmt::arg("o", 0), fmt::arg("p", 0))); +} + +TEST(FormatterTest, NamedArg) { + EXPECT_EQ("1/a/A", format("{_1}/{a_}/{A_}", fmt::arg("a_", 'a'), + fmt::arg("A_", "A"), fmt::arg("_1", 1))); + EXPECT_EQ(" -42", format("{0:{width}}", -42, fmt::arg("width", 4))); + EXPECT_EQ("st", format("{0:.{precision}}", "str", fmt::arg("precision", 2))); + EXPECT_EQ("1 2", format("{} {two}", 1, fmt::arg("two", 2))); + EXPECT_EQ("42", format("{c}", fmt::arg("a", 0), fmt::arg("b", 0), + fmt::arg("c", 42), fmt::arg("d", 0), fmt::arg("e", 0), + fmt::arg("f", 0), fmt::arg("g", 0), fmt::arg("h", 0), + fmt::arg("i", 0), fmt::arg("j", 0), fmt::arg("k", 0), + fmt::arg("l", 0), fmt::arg("m", 0), fmt::arg("n", 0), + fmt::arg("o", 0), fmt::arg("p", 0))); EXPECT_THROW_MSG(format("{a}"), format_error, "argument not found"); EXPECT_THROW_MSG(format("{a}", 42), format_error, "argument not found"); -} - -TEST(FormatterTest, AutoArgIndex) { - EXPECT_EQ("abc", format("{}{}{}", 'a', 'b', 'c')); - EXPECT_THROW_MSG(format("{0}{}", 'a', 'b'), format_error, - "cannot switch from manual to automatic argument indexing"); - EXPECT_THROW_MSG(format("{}{0}", 'a', 'b'), format_error, - "cannot switch from automatic to manual argument indexing"); - EXPECT_EQ("1.2", format("{:.{}}", 1.2345, 2)); - EXPECT_THROW_MSG(format("{0}:.{}", 1.2345, 2), format_error, - "cannot switch from manual to automatic argument indexing"); - EXPECT_THROW_MSG(format("{:.{0}}", 1.2345, 2), format_error, - "cannot switch from automatic to manual argument indexing"); +} + +TEST(FormatterTest, AutoArgIndex) { + EXPECT_EQ("abc", format("{}{}{}", 'a', 'b', 'c')); + EXPECT_THROW_MSG(format("{0}{}", 'a', 'b'), format_error, + "cannot switch from manual to automatic argument indexing"); + EXPECT_THROW_MSG(format("{}{0}", 'a', 'b'), format_error, + "cannot switch from automatic to manual argument indexing"); + EXPECT_EQ("1.2", format("{:.{}}", 1.2345, 2)); + EXPECT_THROW_MSG(format("{0}:.{}", 1.2345, 2), format_error, + "cannot switch from manual to automatic argument indexing"); + EXPECT_THROW_MSG(format("{:.{0}}", 1.2345, 2), format_error, + "cannot switch from automatic to manual argument indexing"); EXPECT_THROW_MSG(format("{}"), format_error, "argument not found"); -} - -TEST(FormatterTest, EmptySpecs) { EXPECT_EQ("42", format("{0:}", 42)); } - -TEST(FormatterTest, LeftAlign) { - EXPECT_EQ("42 ", format("{0:<4}", 42)); - EXPECT_EQ("42 ", format("{0:<4o}", 042)); - EXPECT_EQ("42 ", format("{0:<4x}", 0x42)); - EXPECT_EQ("-42 ", format("{0:<5}", -42)); - EXPECT_EQ("42 ", format("{0:<5}", 42u)); - EXPECT_EQ("-42 ", format("{0:<5}", -42l)); - EXPECT_EQ("42 ", format("{0:<5}", 42ul)); - EXPECT_EQ("-42 ", format("{0:<5}", -42ll)); - EXPECT_EQ("42 ", format("{0:<5}", 42ull)); +} + +TEST(FormatterTest, EmptySpecs) { EXPECT_EQ("42", format("{0:}", 42)); } + +TEST(FormatterTest, LeftAlign) { + EXPECT_EQ("42 ", format("{0:<4}", 42)); + EXPECT_EQ("42 ", format("{0:<4o}", 042)); + EXPECT_EQ("42 ", format("{0:<4x}", 0x42)); + EXPECT_EQ("-42 ", format("{0:<5}", -42)); + EXPECT_EQ("42 ", format("{0:<5}", 42u)); + EXPECT_EQ("-42 ", format("{0:<5}", -42l)); + EXPECT_EQ("42 ", format("{0:<5}", 42ul)); + EXPECT_EQ("-42 ", format("{0:<5}", -42ll)); + EXPECT_EQ("42 ", format("{0:<5}", 42ull)); EXPECT_EQ("-42 ", format("{0:<5}", -42.0)); EXPECT_EQ("-42 ", format("{0:<5}", -42.0l)); - EXPECT_EQ("c ", format("{0:<5}", 'c')); - EXPECT_EQ("abc ", format("{0:<5}", "abc")); - EXPECT_EQ("0xface ", format("{0:<8}", reinterpret_cast<void*>(0xface))); -} - -TEST(FormatterTest, RightAlign) { - EXPECT_EQ(" 42", format("{0:>4}", 42)); - EXPECT_EQ(" 42", format("{0:>4o}", 042)); - EXPECT_EQ(" 42", format("{0:>4x}", 0x42)); - EXPECT_EQ(" -42", format("{0:>5}", -42)); - EXPECT_EQ(" 42", format("{0:>5}", 42u)); - EXPECT_EQ(" -42", format("{0:>5}", -42l)); - EXPECT_EQ(" 42", format("{0:>5}", 42ul)); - EXPECT_EQ(" -42", format("{0:>5}", -42ll)); - EXPECT_EQ(" 42", format("{0:>5}", 42ull)); + EXPECT_EQ("c ", format("{0:<5}", 'c')); + EXPECT_EQ("abc ", format("{0:<5}", "abc")); + EXPECT_EQ("0xface ", format("{0:<8}", reinterpret_cast<void*>(0xface))); +} + +TEST(FormatterTest, RightAlign) { + EXPECT_EQ(" 42", format("{0:>4}", 42)); + EXPECT_EQ(" 42", format("{0:>4o}", 042)); + EXPECT_EQ(" 42", format("{0:>4x}", 0x42)); + EXPECT_EQ(" -42", format("{0:>5}", -42)); + EXPECT_EQ(" 42", format("{0:>5}", 42u)); + EXPECT_EQ(" -42", format("{0:>5}", -42l)); + EXPECT_EQ(" 42", format("{0:>5}", 42ul)); + EXPECT_EQ(" -42", format("{0:>5}", -42ll)); + EXPECT_EQ(" 42", format("{0:>5}", 42ull)); EXPECT_EQ(" -42", format("{0:>5}", -42.0)); EXPECT_EQ(" -42", format("{0:>5}", -42.0l)); - EXPECT_EQ(" c", format("{0:>5}", 'c')); - EXPECT_EQ(" abc", format("{0:>5}", "abc")); - EXPECT_EQ(" 0xface", format("{0:>8}", reinterpret_cast<void*>(0xface))); -} - + EXPECT_EQ(" c", format("{0:>5}", 'c')); + EXPECT_EQ(" abc", format("{0:>5}", "abc")); + EXPECT_EQ(" 0xface", format("{0:>8}", reinterpret_cast<void*>(0xface))); +} + #if FMT_DEPRECATED_NUMERIC_ALIGN TEST(FormatterTest, NumericAlign) { EXPECT_EQ("0042", format("{0:=4}", 42)); } -#endif - -TEST(FormatterTest, CenterAlign) { - EXPECT_EQ(" 42 ", format("{0:^5}", 42)); - EXPECT_EQ(" 42 ", format("{0:^5o}", 042)); - EXPECT_EQ(" 42 ", format("{0:^5x}", 0x42)); - EXPECT_EQ(" -42 ", format("{0:^5}", -42)); - EXPECT_EQ(" 42 ", format("{0:^5}", 42u)); - EXPECT_EQ(" -42 ", format("{0:^5}", -42l)); - EXPECT_EQ(" 42 ", format("{0:^5}", 42ul)); - EXPECT_EQ(" -42 ", format("{0:^5}", -42ll)); - EXPECT_EQ(" 42 ", format("{0:^5}", 42ull)); +#endif + +TEST(FormatterTest, CenterAlign) { + EXPECT_EQ(" 42 ", format("{0:^5}", 42)); + EXPECT_EQ(" 42 ", format("{0:^5o}", 042)); + EXPECT_EQ(" 42 ", format("{0:^5x}", 0x42)); + EXPECT_EQ(" -42 ", format("{0:^5}", -42)); + EXPECT_EQ(" 42 ", format("{0:^5}", 42u)); + EXPECT_EQ(" -42 ", format("{0:^5}", -42l)); + EXPECT_EQ(" 42 ", format("{0:^5}", 42ul)); + EXPECT_EQ(" -42 ", format("{0:^5}", -42ll)); + EXPECT_EQ(" 42 ", format("{0:^5}", 42ull)); EXPECT_EQ(" -42 ", format("{0:^5}", -42.0)); EXPECT_EQ(" -42 ", format("{0:^5}", -42.0l)); - EXPECT_EQ(" c ", format("{0:^5}", 'c')); - EXPECT_EQ(" abc ", format("{0:^6}", "abc")); - EXPECT_EQ(" 0xface ", format("{0:^8}", reinterpret_cast<void*>(0xface))); -} - -TEST(FormatterTest, Fill) { - EXPECT_THROW_MSG(format("{0:{<5}", 'c'), format_error, - "invalid fill character '{'"); - EXPECT_THROW_MSG(format("{0:{<5}}", 'c'), format_error, - "invalid fill character '{'"); - EXPECT_EQ("**42", format("{0:*>4}", 42)); - EXPECT_EQ("**-42", format("{0:*>5}", -42)); - EXPECT_EQ("***42", format("{0:*>5}", 42u)); - EXPECT_EQ("**-42", format("{0:*>5}", -42l)); - EXPECT_EQ("***42", format("{0:*>5}", 42ul)); - EXPECT_EQ("**-42", format("{0:*>5}", -42ll)); - EXPECT_EQ("***42", format("{0:*>5}", 42ull)); + EXPECT_EQ(" c ", format("{0:^5}", 'c')); + EXPECT_EQ(" abc ", format("{0:^6}", "abc")); + EXPECT_EQ(" 0xface ", format("{0:^8}", reinterpret_cast<void*>(0xface))); +} + +TEST(FormatterTest, Fill) { + EXPECT_THROW_MSG(format("{0:{<5}", 'c'), format_error, + "invalid fill character '{'"); + EXPECT_THROW_MSG(format("{0:{<5}}", 'c'), format_error, + "invalid fill character '{'"); + EXPECT_EQ("**42", format("{0:*>4}", 42)); + EXPECT_EQ("**-42", format("{0:*>5}", -42)); + EXPECT_EQ("***42", format("{0:*>5}", 42u)); + EXPECT_EQ("**-42", format("{0:*>5}", -42l)); + EXPECT_EQ("***42", format("{0:*>5}", 42ul)); + EXPECT_EQ("**-42", format("{0:*>5}", -42ll)); + EXPECT_EQ("***42", format("{0:*>5}", 42ull)); EXPECT_EQ("**-42", format("{0:*>5}", -42.0)); EXPECT_EQ("**-42", format("{0:*>5}", -42.0l)); - EXPECT_EQ("c****", format("{0:*<5}", 'c')); - EXPECT_EQ("abc**", format("{0:*<5}", "abc")); - EXPECT_EQ("**0xface", format("{0:*>8}", reinterpret_cast<void*>(0xface))); - EXPECT_EQ("foo=", format("{:}=", "foo")); - EXPECT_EQ(std::string("\0\0\0*", 4), format(string_view("{:\0>4}", 6), '*')); - EXPECT_EQ("жж42", format("{0:ж>4}", 42)); - EXPECT_THROW_MSG(format("{:\x80\x80\x80\x80\x80>}", 0), format_error, + EXPECT_EQ("c****", format("{0:*<5}", 'c')); + EXPECT_EQ("abc**", format("{0:*<5}", "abc")); + EXPECT_EQ("**0xface", format("{0:*>8}", reinterpret_cast<void*>(0xface))); + EXPECT_EQ("foo=", format("{:}=", "foo")); + EXPECT_EQ(std::string("\0\0\0*", 4), format(string_view("{:\0>4}", 6), '*')); + EXPECT_EQ("жж42", format("{0:ж>4}", 42)); + EXPECT_THROW_MSG(format("{:\x80\x80\x80\x80\x80>}", 0), format_error, "missing '}' in format string"); -} - -TEST(FormatterTest, PlusSign) { - EXPECT_EQ("+42", format("{0:+}", 42)); - EXPECT_EQ("-42", format("{0:+}", -42)); - EXPECT_EQ("+42", format("{0:+}", 42)); - EXPECT_THROW_MSG(format("{0:+}", 42u), format_error, - "format specifier requires signed argument"); - EXPECT_EQ("+42", format("{0:+}", 42l)); - EXPECT_THROW_MSG(format("{0:+}", 42ul), format_error, - "format specifier requires signed argument"); - EXPECT_EQ("+42", format("{0:+}", 42ll)); - EXPECT_THROW_MSG(format("{0:+}", 42ull), format_error, - "format specifier requires signed argument"); +} + +TEST(FormatterTest, PlusSign) { + EXPECT_EQ("+42", format("{0:+}", 42)); + EXPECT_EQ("-42", format("{0:+}", -42)); + EXPECT_EQ("+42", format("{0:+}", 42)); + EXPECT_THROW_MSG(format("{0:+}", 42u), format_error, + "format specifier requires signed argument"); + EXPECT_EQ("+42", format("{0:+}", 42l)); + EXPECT_THROW_MSG(format("{0:+}", 42ul), format_error, + "format specifier requires signed argument"); + EXPECT_EQ("+42", format("{0:+}", 42ll)); + EXPECT_THROW_MSG(format("{0:+}", 42ull), format_error, + "format specifier requires signed argument"); EXPECT_EQ("+42", format("{0:+}", 42.0)); EXPECT_EQ("+42", format("{0:+}", 42.0l)); - EXPECT_THROW_MSG(format("{0:+", 'c'), format_error, - "missing '}' in format string"); - EXPECT_THROW_MSG(format("{0:+}", 'c'), format_error, - "invalid format specifier for char"); - EXPECT_THROW_MSG(format("{0:+}", "abc"), format_error, - "format specifier requires numeric argument"); - EXPECT_THROW_MSG(format("{0:+}", reinterpret_cast<void*>(0x42)), format_error, - "format specifier requires numeric argument"); -} - -TEST(FormatterTest, MinusSign) { - EXPECT_EQ("42", format("{0:-}", 42)); - EXPECT_EQ("-42", format("{0:-}", -42)); - EXPECT_EQ("42", format("{0:-}", 42)); - EXPECT_THROW_MSG(format("{0:-}", 42u), format_error, - "format specifier requires signed argument"); - EXPECT_EQ("42", format("{0:-}", 42l)); - EXPECT_THROW_MSG(format("{0:-}", 42ul), format_error, - "format specifier requires signed argument"); - EXPECT_EQ("42", format("{0:-}", 42ll)); - EXPECT_THROW_MSG(format("{0:-}", 42ull), format_error, - "format specifier requires signed argument"); + EXPECT_THROW_MSG(format("{0:+", 'c'), format_error, + "missing '}' in format string"); + EXPECT_THROW_MSG(format("{0:+}", 'c'), format_error, + "invalid format specifier for char"); + EXPECT_THROW_MSG(format("{0:+}", "abc"), format_error, + "format specifier requires numeric argument"); + EXPECT_THROW_MSG(format("{0:+}", reinterpret_cast<void*>(0x42)), format_error, + "format specifier requires numeric argument"); +} + +TEST(FormatterTest, MinusSign) { + EXPECT_EQ("42", format("{0:-}", 42)); + EXPECT_EQ("-42", format("{0:-}", -42)); + EXPECT_EQ("42", format("{0:-}", 42)); + EXPECT_THROW_MSG(format("{0:-}", 42u), format_error, + "format specifier requires signed argument"); + EXPECT_EQ("42", format("{0:-}", 42l)); + EXPECT_THROW_MSG(format("{0:-}", 42ul), format_error, + "format specifier requires signed argument"); + EXPECT_EQ("42", format("{0:-}", 42ll)); + EXPECT_THROW_MSG(format("{0:-}", 42ull), format_error, + "format specifier requires signed argument"); EXPECT_EQ("42", format("{0:-}", 42.0)); EXPECT_EQ("42", format("{0:-}", 42.0l)); - EXPECT_THROW_MSG(format("{0:-", 'c'), format_error, - "missing '}' in format string"); - EXPECT_THROW_MSG(format("{0:-}", 'c'), format_error, - "invalid format specifier for char"); - EXPECT_THROW_MSG(format("{0:-}", "abc"), format_error, - "format specifier requires numeric argument"); - EXPECT_THROW_MSG(format("{0:-}", reinterpret_cast<void*>(0x42)), format_error, - "format specifier requires numeric argument"); -} - -TEST(FormatterTest, SpaceSign) { - EXPECT_EQ(" 42", format("{0: }", 42)); - EXPECT_EQ("-42", format("{0: }", -42)); - EXPECT_EQ(" 42", format("{0: }", 42)); - EXPECT_THROW_MSG(format("{0: }", 42u), format_error, - "format specifier requires signed argument"); - EXPECT_EQ(" 42", format("{0: }", 42l)); - EXPECT_THROW_MSG(format("{0: }", 42ul), format_error, - "format specifier requires signed argument"); - EXPECT_EQ(" 42", format("{0: }", 42ll)); - EXPECT_THROW_MSG(format("{0: }", 42ull), format_error, - "format specifier requires signed argument"); + EXPECT_THROW_MSG(format("{0:-", 'c'), format_error, + "missing '}' in format string"); + EXPECT_THROW_MSG(format("{0:-}", 'c'), format_error, + "invalid format specifier for char"); + EXPECT_THROW_MSG(format("{0:-}", "abc"), format_error, + "format specifier requires numeric argument"); + EXPECT_THROW_MSG(format("{0:-}", reinterpret_cast<void*>(0x42)), format_error, + "format specifier requires numeric argument"); +} + +TEST(FormatterTest, SpaceSign) { + EXPECT_EQ(" 42", format("{0: }", 42)); + EXPECT_EQ("-42", format("{0: }", -42)); + EXPECT_EQ(" 42", format("{0: }", 42)); + EXPECT_THROW_MSG(format("{0: }", 42u), format_error, + "format specifier requires signed argument"); + EXPECT_EQ(" 42", format("{0: }", 42l)); + EXPECT_THROW_MSG(format("{0: }", 42ul), format_error, + "format specifier requires signed argument"); + EXPECT_EQ(" 42", format("{0: }", 42ll)); + EXPECT_THROW_MSG(format("{0: }", 42ull), format_error, + "format specifier requires signed argument"); EXPECT_EQ(" 42", format("{0: }", 42.0)); EXPECT_EQ(" 42", format("{0: }", 42.0l)); - EXPECT_THROW_MSG(format("{0: ", 'c'), format_error, - "missing '}' in format string"); - EXPECT_THROW_MSG(format("{0: }", 'c'), format_error, - "invalid format specifier for char"); - EXPECT_THROW_MSG(format("{0: }", "abc"), format_error, - "format specifier requires numeric argument"); - EXPECT_THROW_MSG(format("{0: }", reinterpret_cast<void*>(0x42)), format_error, - "format specifier requires numeric argument"); -} - + EXPECT_THROW_MSG(format("{0: ", 'c'), format_error, + "missing '}' in format string"); + EXPECT_THROW_MSG(format("{0: }", 'c'), format_error, + "invalid format specifier for char"); + EXPECT_THROW_MSG(format("{0: }", "abc"), format_error, + "format specifier requires numeric argument"); + EXPECT_THROW_MSG(format("{0: }", reinterpret_cast<void*>(0x42)), format_error, + "format specifier requires numeric argument"); +} + TEST(FormatterTest, SignNotTruncated) { wchar_t format_str[] = {L'{', L':', '+' | (1 << fmt::detail::num_bits<char>()), L'}', 0}; EXPECT_THROW(format(format_str, 42), format_error); } -TEST(FormatterTest, HashFlag) { - EXPECT_EQ("42", format("{0:#}", 42)); - EXPECT_EQ("-42", format("{0:#}", -42)); - EXPECT_EQ("0b101010", format("{0:#b}", 42)); - EXPECT_EQ("0B101010", format("{0:#B}", 42)); - EXPECT_EQ("-0b101010", format("{0:#b}", -42)); - EXPECT_EQ("0x42", format("{0:#x}", 0x42)); - EXPECT_EQ("0X42", format("{0:#X}", 0x42)); - EXPECT_EQ("-0x42", format("{0:#x}", -0x42)); - EXPECT_EQ("0", format("{0:#o}", 0)); - EXPECT_EQ("042", format("{0:#o}", 042)); - EXPECT_EQ("-042", format("{0:#o}", -042)); - EXPECT_EQ("42", format("{0:#}", 42u)); - EXPECT_EQ("0x42", format("{0:#x}", 0x42u)); - EXPECT_EQ("042", format("{0:#o}", 042u)); - - EXPECT_EQ("-42", format("{0:#}", -42l)); - EXPECT_EQ("0x42", format("{0:#x}", 0x42l)); - EXPECT_EQ("-0x42", format("{0:#x}", -0x42l)); - EXPECT_EQ("042", format("{0:#o}", 042l)); - EXPECT_EQ("-042", format("{0:#o}", -042l)); - EXPECT_EQ("42", format("{0:#}", 42ul)); - EXPECT_EQ("0x42", format("{0:#x}", 0x42ul)); - EXPECT_EQ("042", format("{0:#o}", 042ul)); - - EXPECT_EQ("-42", format("{0:#}", -42ll)); - EXPECT_EQ("0x42", format("{0:#x}", 0x42ll)); - EXPECT_EQ("-0x42", format("{0:#x}", -0x42ll)); - EXPECT_EQ("042", format("{0:#o}", 042ll)); - EXPECT_EQ("-042", format("{0:#o}", -042ll)); - EXPECT_EQ("42", format("{0:#}", 42ull)); - EXPECT_EQ("0x42", format("{0:#x}", 0x42ull)); - EXPECT_EQ("042", format("{0:#o}", 042ull)); - - EXPECT_EQ("-42.0", format("{0:#}", -42.0)); - EXPECT_EQ("-42.0", format("{0:#}", -42.0l)); - EXPECT_EQ("4.e+01", format("{:#.0e}", 42.0)); - EXPECT_EQ("0.", format("{:#.0f}", 0.01)); +TEST(FormatterTest, HashFlag) { + EXPECT_EQ("42", format("{0:#}", 42)); + EXPECT_EQ("-42", format("{0:#}", -42)); + EXPECT_EQ("0b101010", format("{0:#b}", 42)); + EXPECT_EQ("0B101010", format("{0:#B}", 42)); + EXPECT_EQ("-0b101010", format("{0:#b}", -42)); + EXPECT_EQ("0x42", format("{0:#x}", 0x42)); + EXPECT_EQ("0X42", format("{0:#X}", 0x42)); + EXPECT_EQ("-0x42", format("{0:#x}", -0x42)); + EXPECT_EQ("0", format("{0:#o}", 0)); + EXPECT_EQ("042", format("{0:#o}", 042)); + EXPECT_EQ("-042", format("{0:#o}", -042)); + EXPECT_EQ("42", format("{0:#}", 42u)); + EXPECT_EQ("0x42", format("{0:#x}", 0x42u)); + EXPECT_EQ("042", format("{0:#o}", 042u)); + + EXPECT_EQ("-42", format("{0:#}", -42l)); + EXPECT_EQ("0x42", format("{0:#x}", 0x42l)); + EXPECT_EQ("-0x42", format("{0:#x}", -0x42l)); + EXPECT_EQ("042", format("{0:#o}", 042l)); + EXPECT_EQ("-042", format("{0:#o}", -042l)); + EXPECT_EQ("42", format("{0:#}", 42ul)); + EXPECT_EQ("0x42", format("{0:#x}", 0x42ul)); + EXPECT_EQ("042", format("{0:#o}", 042ul)); + + EXPECT_EQ("-42", format("{0:#}", -42ll)); + EXPECT_EQ("0x42", format("{0:#x}", 0x42ll)); + EXPECT_EQ("-0x42", format("{0:#x}", -0x42ll)); + EXPECT_EQ("042", format("{0:#o}", 042ll)); + EXPECT_EQ("-042", format("{0:#o}", -042ll)); + EXPECT_EQ("42", format("{0:#}", 42ull)); + EXPECT_EQ("0x42", format("{0:#x}", 0x42ull)); + EXPECT_EQ("042", format("{0:#o}", 042ull)); + + EXPECT_EQ("-42.0", format("{0:#}", -42.0)); + EXPECT_EQ("-42.0", format("{0:#}", -42.0l)); + EXPECT_EQ("4.e+01", format("{:#.0e}", 42.0)); + EXPECT_EQ("0.", format("{:#.0f}", 0.01)); EXPECT_EQ("0.50", format("{:#.2g}", 0.5)); EXPECT_EQ("0.", format("{:#.0f}", 0.5)); - EXPECT_THROW_MSG(format("{0:#", 'c'), format_error, - "missing '}' in format string"); - EXPECT_THROW_MSG(format("{0:#}", 'c'), format_error, - "invalid format specifier for char"); - EXPECT_THROW_MSG(format("{0:#}", "abc"), format_error, - "format specifier requires numeric argument"); - EXPECT_THROW_MSG(format("{0:#}", reinterpret_cast<void*>(0x42)), format_error, - "format specifier requires numeric argument"); -} - -TEST(FormatterTest, ZeroFlag) { - EXPECT_EQ("42", format("{0:0}", 42)); - EXPECT_EQ("-0042", format("{0:05}", -42)); - EXPECT_EQ("00042", format("{0:05}", 42u)); - EXPECT_EQ("-0042", format("{0:05}", -42l)); - EXPECT_EQ("00042", format("{0:05}", 42ul)); - EXPECT_EQ("-0042", format("{0:05}", -42ll)); - EXPECT_EQ("00042", format("{0:05}", 42ull)); + EXPECT_THROW_MSG(format("{0:#", 'c'), format_error, + "missing '}' in format string"); + EXPECT_THROW_MSG(format("{0:#}", 'c'), format_error, + "invalid format specifier for char"); + EXPECT_THROW_MSG(format("{0:#}", "abc"), format_error, + "format specifier requires numeric argument"); + EXPECT_THROW_MSG(format("{0:#}", reinterpret_cast<void*>(0x42)), format_error, + "format specifier requires numeric argument"); +} + +TEST(FormatterTest, ZeroFlag) { + EXPECT_EQ("42", format("{0:0}", 42)); + EXPECT_EQ("-0042", format("{0:05}", -42)); + EXPECT_EQ("00042", format("{0:05}", 42u)); + EXPECT_EQ("-0042", format("{0:05}", -42l)); + EXPECT_EQ("00042", format("{0:05}", 42ul)); + EXPECT_EQ("-0042", format("{0:05}", -42ll)); + EXPECT_EQ("00042", format("{0:05}", 42ull)); EXPECT_EQ("-000042", format("{0:07}", -42.0)); EXPECT_EQ("-000042", format("{0:07}", -42.0l)); - EXPECT_THROW_MSG(format("{0:0", 'c'), format_error, - "missing '}' in format string"); - EXPECT_THROW_MSG(format("{0:05}", 'c'), format_error, - "invalid format specifier for char"); - EXPECT_THROW_MSG(format("{0:05}", "abc"), format_error, - "format specifier requires numeric argument"); - EXPECT_THROW_MSG(format("{0:05}", reinterpret_cast<void*>(0x42)), - format_error, "format specifier requires numeric argument"); -} - -TEST(FormatterTest, Width) { - char format_str[BUFFER_SIZE]; - safe_sprintf(format_str, "{0:%u", UINT_MAX); - increment(format_str + 3); - EXPECT_THROW_MSG(format(format_str, 0), format_error, "number is too big"); + EXPECT_THROW_MSG(format("{0:0", 'c'), format_error, + "missing '}' in format string"); + EXPECT_THROW_MSG(format("{0:05}", 'c'), format_error, + "invalid format specifier for char"); + EXPECT_THROW_MSG(format("{0:05}", "abc"), format_error, + "format specifier requires numeric argument"); + EXPECT_THROW_MSG(format("{0:05}", reinterpret_cast<void*>(0x42)), + format_error, "format specifier requires numeric argument"); +} + +TEST(FormatterTest, Width) { + char format_str[BUFFER_SIZE]; + safe_sprintf(format_str, "{0:%u", UINT_MAX); + increment(format_str + 3); + EXPECT_THROW_MSG(format(format_str, 0), format_error, "number is too big"); size_t size = std::strlen(format_str); - format_str[size] = '}'; - format_str[size + 1] = 0; - EXPECT_THROW_MSG(format(format_str, 0), format_error, "number is too big"); - - safe_sprintf(format_str, "{0:%u", INT_MAX + 1u); - EXPECT_THROW_MSG(format(format_str, 0), format_error, "number is too big"); - safe_sprintf(format_str, "{0:%u}", INT_MAX + 1u); - EXPECT_THROW_MSG(format(format_str, 0), format_error, "number is too big"); - EXPECT_EQ(" -42", format("{0:4}", -42)); - EXPECT_EQ(" 42", format("{0:5}", 42u)); - EXPECT_EQ(" -42", format("{0:6}", -42l)); - EXPECT_EQ(" 42", format("{0:7}", 42ul)); - EXPECT_EQ(" -42", format("{0:6}", -42ll)); - EXPECT_EQ(" 42", format("{0:7}", 42ull)); - EXPECT_EQ(" -1.23", format("{0:8}", -1.23)); - EXPECT_EQ(" -1.23", format("{0:9}", -1.23l)); - EXPECT_EQ(" 0xcafe", format("{0:10}", reinterpret_cast<void*>(0xcafe))); - EXPECT_EQ("x ", format("{0:11}", 'x')); - EXPECT_EQ("str ", format("{0:12}", "str")); - EXPECT_EQ(fmt::format("{:*^5}", "🤡"), "**🤡**"); -} - -template <typename T> inline T const_check(T value) { return value; } - -TEST(FormatterTest, RuntimeWidth) { - char format_str[BUFFER_SIZE]; - safe_sprintf(format_str, "{0:{%u", UINT_MAX); - increment(format_str + 4); - EXPECT_THROW_MSG(format(format_str, 0), format_error, "number is too big"); + format_str[size] = '}'; + format_str[size + 1] = 0; + EXPECT_THROW_MSG(format(format_str, 0), format_error, "number is too big"); + + safe_sprintf(format_str, "{0:%u", INT_MAX + 1u); + EXPECT_THROW_MSG(format(format_str, 0), format_error, "number is too big"); + safe_sprintf(format_str, "{0:%u}", INT_MAX + 1u); + EXPECT_THROW_MSG(format(format_str, 0), format_error, "number is too big"); + EXPECT_EQ(" -42", format("{0:4}", -42)); + EXPECT_EQ(" 42", format("{0:5}", 42u)); + EXPECT_EQ(" -42", format("{0:6}", -42l)); + EXPECT_EQ(" 42", format("{0:7}", 42ul)); + EXPECT_EQ(" -42", format("{0:6}", -42ll)); + EXPECT_EQ(" 42", format("{0:7}", 42ull)); + EXPECT_EQ(" -1.23", format("{0:8}", -1.23)); + EXPECT_EQ(" -1.23", format("{0:9}", -1.23l)); + EXPECT_EQ(" 0xcafe", format("{0:10}", reinterpret_cast<void*>(0xcafe))); + EXPECT_EQ("x ", format("{0:11}", 'x')); + EXPECT_EQ("str ", format("{0:12}", "str")); + EXPECT_EQ(fmt::format("{:*^5}", "🤡"), "**🤡**"); +} + +template <typename T> inline T const_check(T value) { return value; } + +TEST(FormatterTest, RuntimeWidth) { + char format_str[BUFFER_SIZE]; + safe_sprintf(format_str, "{0:{%u", UINT_MAX); + increment(format_str + 4); + EXPECT_THROW_MSG(format(format_str, 0), format_error, "number is too big"); size_t size = std::strlen(format_str); - format_str[size] = '}'; - format_str[size + 1] = 0; - EXPECT_THROW_MSG(format(format_str, 0), format_error, "number is too big"); - format_str[size + 1] = '}'; - format_str[size + 2] = 0; - EXPECT_THROW_MSG(format(format_str, 0), format_error, "number is too big"); - - EXPECT_THROW_MSG(format("{0:{", 0), format_error, "invalid format string"); - EXPECT_THROW_MSG(format("{0:{}", 0), format_error, - "cannot switch from manual to automatic argument indexing"); - EXPECT_THROW_MSG(format("{0:{?}}", 0), format_error, "invalid format string"); + format_str[size] = '}'; + format_str[size + 1] = 0; + EXPECT_THROW_MSG(format(format_str, 0), format_error, "number is too big"); + format_str[size + 1] = '}'; + format_str[size + 2] = 0; + EXPECT_THROW_MSG(format(format_str, 0), format_error, "number is too big"); + + EXPECT_THROW_MSG(format("{0:{", 0), format_error, "invalid format string"); + EXPECT_THROW_MSG(format("{0:{}", 0), format_error, + "cannot switch from manual to automatic argument indexing"); + EXPECT_THROW_MSG(format("{0:{?}}", 0), format_error, "invalid format string"); EXPECT_THROW_MSG(format("{0:{1}}", 0), format_error, "argument not found"); - - EXPECT_THROW_MSG(format("{0:{0:}}", 0), format_error, - "invalid format string"); - - EXPECT_THROW_MSG(format("{0:{1}}", 0, -1), format_error, "negative width"); - EXPECT_THROW_MSG(format("{0:{1}}", 0, (INT_MAX + 1u)), format_error, - "number is too big"); - EXPECT_THROW_MSG(format("{0:{1}}", 0, -1l), format_error, "negative width"); - if (const_check(sizeof(long) > sizeof(int))) { - long value = INT_MAX; - EXPECT_THROW_MSG(format("{0:{1}}", 0, (value + 1)), format_error, - "number is too big"); - } - EXPECT_THROW_MSG(format("{0:{1}}", 0, (INT_MAX + 1ul)), format_error, - "number is too big"); - - EXPECT_THROW_MSG(format("{0:{1}}", 0, '0'), format_error, - "width is not integer"); - EXPECT_THROW_MSG(format("{0:{1}}", 0, 0.0), format_error, - "width is not integer"); - - EXPECT_EQ(" -42", format("{0:{1}}", -42, 4)); - EXPECT_EQ(" 42", format("{0:{1}}", 42u, 5)); - EXPECT_EQ(" -42", format("{0:{1}}", -42l, 6)); - EXPECT_EQ(" 42", format("{0:{1}}", 42ul, 7)); - EXPECT_EQ(" -42", format("{0:{1}}", -42ll, 6)); - EXPECT_EQ(" 42", format("{0:{1}}", 42ull, 7)); - EXPECT_EQ(" -1.23", format("{0:{1}}", -1.23, 8)); - EXPECT_EQ(" -1.23", format("{0:{1}}", -1.23l, 9)); - EXPECT_EQ(" 0xcafe", - format("{0:{1}}", reinterpret_cast<void*>(0xcafe), 10)); - EXPECT_EQ("x ", format("{0:{1}}", 'x', 11)); - EXPECT_EQ("str ", format("{0:{1}}", "str", 12)); -} - -TEST(FormatterTest, Precision) { - char format_str[BUFFER_SIZE]; - safe_sprintf(format_str, "{0:.%u", UINT_MAX); - increment(format_str + 4); - EXPECT_THROW_MSG(format(format_str, 0), format_error, "number is too big"); + + EXPECT_THROW_MSG(format("{0:{0:}}", 0), format_error, + "invalid format string"); + + EXPECT_THROW_MSG(format("{0:{1}}", 0, -1), format_error, "negative width"); + EXPECT_THROW_MSG(format("{0:{1}}", 0, (INT_MAX + 1u)), format_error, + "number is too big"); + EXPECT_THROW_MSG(format("{0:{1}}", 0, -1l), format_error, "negative width"); + if (const_check(sizeof(long) > sizeof(int))) { + long value = INT_MAX; + EXPECT_THROW_MSG(format("{0:{1}}", 0, (value + 1)), format_error, + "number is too big"); + } + EXPECT_THROW_MSG(format("{0:{1}}", 0, (INT_MAX + 1ul)), format_error, + "number is too big"); + + EXPECT_THROW_MSG(format("{0:{1}}", 0, '0'), format_error, + "width is not integer"); + EXPECT_THROW_MSG(format("{0:{1}}", 0, 0.0), format_error, + "width is not integer"); + + EXPECT_EQ(" -42", format("{0:{1}}", -42, 4)); + EXPECT_EQ(" 42", format("{0:{1}}", 42u, 5)); + EXPECT_EQ(" -42", format("{0:{1}}", -42l, 6)); + EXPECT_EQ(" 42", format("{0:{1}}", 42ul, 7)); + EXPECT_EQ(" -42", format("{0:{1}}", -42ll, 6)); + EXPECT_EQ(" 42", format("{0:{1}}", 42ull, 7)); + EXPECT_EQ(" -1.23", format("{0:{1}}", -1.23, 8)); + EXPECT_EQ(" -1.23", format("{0:{1}}", -1.23l, 9)); + EXPECT_EQ(" 0xcafe", + format("{0:{1}}", reinterpret_cast<void*>(0xcafe), 10)); + EXPECT_EQ("x ", format("{0:{1}}", 'x', 11)); + EXPECT_EQ("str ", format("{0:{1}}", "str", 12)); +} + +TEST(FormatterTest, Precision) { + char format_str[BUFFER_SIZE]; + safe_sprintf(format_str, "{0:.%u", UINT_MAX); + increment(format_str + 4); + EXPECT_THROW_MSG(format(format_str, 0), format_error, "number is too big"); size_t size = std::strlen(format_str); - format_str[size] = '}'; - format_str[size + 1] = 0; - EXPECT_THROW_MSG(format(format_str, 0), format_error, "number is too big"); - - safe_sprintf(format_str, "{0:.%u", INT_MAX + 1u); - EXPECT_THROW_MSG(format(format_str, 0), format_error, "number is too big"); - safe_sprintf(format_str, "{0:.%u}", INT_MAX + 1u); - EXPECT_THROW_MSG(format(format_str, 0), format_error, "number is too big"); - - EXPECT_THROW_MSG(format("{0:.", 0), format_error, - "missing precision specifier"); - EXPECT_THROW_MSG(format("{0:.}", 0), format_error, - "missing precision specifier"); - - EXPECT_THROW_MSG(format("{0:.2", 0), format_error, - "precision not allowed for this argument type"); - EXPECT_THROW_MSG(format("{0:.2}", 42), format_error, - "precision not allowed for this argument type"); - EXPECT_THROW_MSG(format("{0:.2f}", 42), format_error, - "precision not allowed for this argument type"); - EXPECT_THROW_MSG(format("{0:.2}", 42u), format_error, - "precision not allowed for this argument type"); - EXPECT_THROW_MSG(format("{0:.2f}", 42u), format_error, - "precision not allowed for this argument type"); - EXPECT_THROW_MSG(format("{0:.2}", 42l), format_error, - "precision not allowed for this argument type"); - EXPECT_THROW_MSG(format("{0:.2f}", 42l), format_error, - "precision not allowed for this argument type"); - EXPECT_THROW_MSG(format("{0:.2}", 42ul), format_error, - "precision not allowed for this argument type"); - EXPECT_THROW_MSG(format("{0:.2f}", 42ul), format_error, - "precision not allowed for this argument type"); - EXPECT_THROW_MSG(format("{0:.2}", 42ll), format_error, - "precision not allowed for this argument type"); - EXPECT_THROW_MSG(format("{0:.2f}", 42ll), format_error, - "precision not allowed for this argument type"); - EXPECT_THROW_MSG(format("{0:.2}", 42ull), format_error, - "precision not allowed for this argument type"); - EXPECT_THROW_MSG(format("{0:.2f}", 42ull), format_error, - "precision not allowed for this argument type"); - EXPECT_THROW_MSG(format("{0:3.0}", 'x'), format_error, - "precision not allowed for this argument type"); - EXPECT_EQ("1.2", format("{0:.2}", 1.2345)); - EXPECT_EQ("1.2", format("{0:.2}", 1.2345l)); - EXPECT_EQ("1.2e+56", format("{:.2}", 1.234e56)); - EXPECT_EQ("1e+00", format("{:.0e}", 1.0L)); - EXPECT_EQ(" 0.0e+00", format("{:9.1e}", 0.0)); - EXPECT_EQ( - "4.9406564584124654417656879286822137236505980261432476442558568250067550" - "727020875186529983636163599237979656469544571773092665671035593979639877" - "479601078187812630071319031140452784581716784898210368871863605699873072" - "305000638740915356498438731247339727316961514003171538539807412623856559" - "117102665855668676818703956031062493194527159149245532930545654440112748" - "012970999954193198940908041656332452475714786901472678015935523861155013" - "480352649347201937902681071074917033322268447533357208324319361e-324", - format("{:.494}", 4.9406564584124654E-324)); - EXPECT_EQ( - "-0X1.41FE3FFE71C9E000000000000000000000000000000000000000000000000000000" - "000000000000000000000000000000000000000000000000000000000000000000000000" - "000000000000000000000000000000000000000000000000000000000000000000000000" - "000000000000000000000000000000000000000000000000000000000000000000000000" - "000000000000000000000000000000000000000000000000000000000000000000000000" - "000000000000000000000000000000000000000000000000000000000000000000000000" - "000000000000000000000000000000000000000000000000000000000000000000000000" - "000000000000000000000000000000000000000000000000000000000000000000000000" - "000000000000000000000000000000000000000000000000000000000000000000000000" - "000000000000000000000000000000000000000000000000000000000000000000000000" - "000000000000000000000000000000000000000000000000000000000000000000000000" - "000000000000000000000000000000000000000000000000000P+127", - format("{:.838A}", -2.14001164E+38)); - EXPECT_EQ("123.", format("{:#.0f}", 123.0)); - EXPECT_EQ("1.23", format("{:.02f}", 1.234)); - EXPECT_EQ("0.001", format("{:.1g}", 0.001)); + format_str[size] = '}'; + format_str[size + 1] = 0; + EXPECT_THROW_MSG(format(format_str, 0), format_error, "number is too big"); + + safe_sprintf(format_str, "{0:.%u", INT_MAX + 1u); + EXPECT_THROW_MSG(format(format_str, 0), format_error, "number is too big"); + safe_sprintf(format_str, "{0:.%u}", INT_MAX + 1u); + EXPECT_THROW_MSG(format(format_str, 0), format_error, "number is too big"); + + EXPECT_THROW_MSG(format("{0:.", 0), format_error, + "missing precision specifier"); + EXPECT_THROW_MSG(format("{0:.}", 0), format_error, + "missing precision specifier"); + + EXPECT_THROW_MSG(format("{0:.2", 0), format_error, + "precision not allowed for this argument type"); + EXPECT_THROW_MSG(format("{0:.2}", 42), format_error, + "precision not allowed for this argument type"); + EXPECT_THROW_MSG(format("{0:.2f}", 42), format_error, + "precision not allowed for this argument type"); + EXPECT_THROW_MSG(format("{0:.2}", 42u), format_error, + "precision not allowed for this argument type"); + EXPECT_THROW_MSG(format("{0:.2f}", 42u), format_error, + "precision not allowed for this argument type"); + EXPECT_THROW_MSG(format("{0:.2}", 42l), format_error, + "precision not allowed for this argument type"); + EXPECT_THROW_MSG(format("{0:.2f}", 42l), format_error, + "precision not allowed for this argument type"); + EXPECT_THROW_MSG(format("{0:.2}", 42ul), format_error, + "precision not allowed for this argument type"); + EXPECT_THROW_MSG(format("{0:.2f}", 42ul), format_error, + "precision not allowed for this argument type"); + EXPECT_THROW_MSG(format("{0:.2}", 42ll), format_error, + "precision not allowed for this argument type"); + EXPECT_THROW_MSG(format("{0:.2f}", 42ll), format_error, + "precision not allowed for this argument type"); + EXPECT_THROW_MSG(format("{0:.2}", 42ull), format_error, + "precision not allowed for this argument type"); + EXPECT_THROW_MSG(format("{0:.2f}", 42ull), format_error, + "precision not allowed for this argument type"); + EXPECT_THROW_MSG(format("{0:3.0}", 'x'), format_error, + "precision not allowed for this argument type"); + EXPECT_EQ("1.2", format("{0:.2}", 1.2345)); + EXPECT_EQ("1.2", format("{0:.2}", 1.2345l)); + EXPECT_EQ("1.2e+56", format("{:.2}", 1.234e56)); + EXPECT_EQ("1e+00", format("{:.0e}", 1.0L)); + EXPECT_EQ(" 0.0e+00", format("{:9.1e}", 0.0)); + EXPECT_EQ( + "4.9406564584124654417656879286822137236505980261432476442558568250067550" + "727020875186529983636163599237979656469544571773092665671035593979639877" + "479601078187812630071319031140452784581716784898210368871863605699873072" + "305000638740915356498438731247339727316961514003171538539807412623856559" + "117102665855668676818703956031062493194527159149245532930545654440112748" + "012970999954193198940908041656332452475714786901472678015935523861155013" + "480352649347201937902681071074917033322268447533357208324319361e-324", + format("{:.494}", 4.9406564584124654E-324)); + EXPECT_EQ( + "-0X1.41FE3FFE71C9E000000000000000000000000000000000000000000000000000000" + "000000000000000000000000000000000000000000000000000000000000000000000000" + "000000000000000000000000000000000000000000000000000000000000000000000000" + "000000000000000000000000000000000000000000000000000000000000000000000000" + "000000000000000000000000000000000000000000000000000000000000000000000000" + "000000000000000000000000000000000000000000000000000000000000000000000000" + "000000000000000000000000000000000000000000000000000000000000000000000000" + "000000000000000000000000000000000000000000000000000000000000000000000000" + "000000000000000000000000000000000000000000000000000000000000000000000000" + "000000000000000000000000000000000000000000000000000000000000000000000000" + "000000000000000000000000000000000000000000000000000000000000000000000000" + "000000000000000000000000000000000000000000000000000P+127", + format("{:.838A}", -2.14001164E+38)); + EXPECT_EQ("123.", format("{:#.0f}", 123.0)); + EXPECT_EQ("1.23", format("{:.02f}", 1.234)); + EXPECT_EQ("0.001", format("{:.1g}", 0.001)); EXPECT_EQ("1019666400", format("{}", 1019666432.0f)); EXPECT_EQ("1e+01", format("{:.0e}", 9.5)); EXPECT_EQ("1.0e-34", fmt::format("{:.1e}", 1e-34)); - - EXPECT_THROW_MSG(format("{0:.2}", reinterpret_cast<void*>(0xcafe)), - format_error, - "precision not allowed for this argument type"); - EXPECT_THROW_MSG(format("{0:.2f}", reinterpret_cast<void*>(0xcafe)), - format_error, - "precision not allowed for this argument type"); + + EXPECT_THROW_MSG(format("{0:.2}", reinterpret_cast<void*>(0xcafe)), + format_error, + "precision not allowed for this argument type"); + EXPECT_THROW_MSG(format("{0:.2f}", reinterpret_cast<void*>(0xcafe)), + format_error, + "precision not allowed for this argument type"); EXPECT_THROW_MSG(format("{:.{}e}", 42.0, fmt::detail::max_value<int>()), - format_error, "number is too big"); - - EXPECT_EQ("st", format("{0:.2}", "str")); -} - -TEST(FormatterTest, RuntimePrecision) { - char format_str[BUFFER_SIZE]; - safe_sprintf(format_str, "{0:.{%u", UINT_MAX); - increment(format_str + 5); - EXPECT_THROW_MSG(format(format_str, 0), format_error, "number is too big"); + format_error, "number is too big"); + + EXPECT_EQ("st", format("{0:.2}", "str")); +} + +TEST(FormatterTest, RuntimePrecision) { + char format_str[BUFFER_SIZE]; + safe_sprintf(format_str, "{0:.{%u", UINT_MAX); + increment(format_str + 5); + EXPECT_THROW_MSG(format(format_str, 0), format_error, "number is too big"); size_t size = std::strlen(format_str); - format_str[size] = '}'; - format_str[size + 1] = 0; - EXPECT_THROW_MSG(format(format_str, 0), format_error, "number is too big"); - format_str[size + 1] = '}'; - format_str[size + 2] = 0; - EXPECT_THROW_MSG(format(format_str, 0), format_error, "number is too big"); - - EXPECT_THROW_MSG(format("{0:.{", 0), format_error, "invalid format string"); - EXPECT_THROW_MSG(format("{0:.{}", 0), format_error, - "cannot switch from manual to automatic argument indexing"); - EXPECT_THROW_MSG(format("{0:.{?}}", 0), format_error, - "invalid format string"); - EXPECT_THROW_MSG(format("{0:.{1}", 0, 0), format_error, - "precision not allowed for this argument type"); + format_str[size] = '}'; + format_str[size + 1] = 0; + EXPECT_THROW_MSG(format(format_str, 0), format_error, "number is too big"); + format_str[size + 1] = '}'; + format_str[size + 2] = 0; + EXPECT_THROW_MSG(format(format_str, 0), format_error, "number is too big"); + + EXPECT_THROW_MSG(format("{0:.{", 0), format_error, "invalid format string"); + EXPECT_THROW_MSG(format("{0:.{}", 0), format_error, + "cannot switch from manual to automatic argument indexing"); + EXPECT_THROW_MSG(format("{0:.{?}}", 0), format_error, + "invalid format string"); + EXPECT_THROW_MSG(format("{0:.{1}", 0, 0), format_error, + "precision not allowed for this argument type"); EXPECT_THROW_MSG(format("{0:.{1}}", 0), format_error, "argument not found"); - - EXPECT_THROW_MSG(format("{0:.{0:}}", 0), format_error, - "invalid format string"); - - EXPECT_THROW_MSG(format("{0:.{1}}", 0, -1), format_error, - "negative precision"); - EXPECT_THROW_MSG(format("{0:.{1}}", 0, (INT_MAX + 1u)), format_error, - "number is too big"); - EXPECT_THROW_MSG(format("{0:.{1}}", 0, -1l), format_error, - "negative precision"); - if (const_check(sizeof(long) > sizeof(int))) { - long value = INT_MAX; - EXPECT_THROW_MSG(format("{0:.{1}}", 0, (value + 1)), format_error, - "number is too big"); - } - EXPECT_THROW_MSG(format("{0:.{1}}", 0, (INT_MAX + 1ul)), format_error, - "number is too big"); - - EXPECT_THROW_MSG(format("{0:.{1}}", 0, '0'), format_error, - "precision is not integer"); - EXPECT_THROW_MSG(format("{0:.{1}}", 0, 0.0), format_error, - "precision is not integer"); - - EXPECT_THROW_MSG(format("{0:.{1}}", 42, 2), format_error, - "precision not allowed for this argument type"); - EXPECT_THROW_MSG(format("{0:.{1}f}", 42, 2), format_error, - "precision not allowed for this argument type"); - EXPECT_THROW_MSG(format("{0:.{1}}", 42u, 2), format_error, - "precision not allowed for this argument type"); - EXPECT_THROW_MSG(format("{0:.{1}f}", 42u, 2), format_error, - "precision not allowed for this argument type"); - EXPECT_THROW_MSG(format("{0:.{1}}", 42l, 2), format_error, - "precision not allowed for this argument type"); - EXPECT_THROW_MSG(format("{0:.{1}f}", 42l, 2), format_error, - "precision not allowed for this argument type"); - EXPECT_THROW_MSG(format("{0:.{1}}", 42ul, 2), format_error, - "precision not allowed for this argument type"); - EXPECT_THROW_MSG(format("{0:.{1}f}", 42ul, 2), format_error, - "precision not allowed for this argument type"); - EXPECT_THROW_MSG(format("{0:.{1}}", 42ll, 2), format_error, - "precision not allowed for this argument type"); - EXPECT_THROW_MSG(format("{0:.{1}f}", 42ll, 2), format_error, - "precision not allowed for this argument type"); - EXPECT_THROW_MSG(format("{0:.{1}}", 42ull, 2), format_error, - "precision not allowed for this argument type"); - EXPECT_THROW_MSG(format("{0:.{1}f}", 42ull, 2), format_error, - "precision not allowed for this argument type"); - EXPECT_THROW_MSG(format("{0:3.{1}}", 'x', 0), format_error, - "precision not allowed for this argument type"); - EXPECT_EQ("1.2", format("{0:.{1}}", 1.2345, 2)); - EXPECT_EQ("1.2", format("{1:.{0}}", 2, 1.2345l)); - - EXPECT_THROW_MSG(format("{0:.{1}}", reinterpret_cast<void*>(0xcafe), 2), - format_error, - "precision not allowed for this argument type"); - EXPECT_THROW_MSG(format("{0:.{1}f}", reinterpret_cast<void*>(0xcafe), 2), - format_error, - "precision not allowed for this argument type"); - - EXPECT_EQ("st", format("{0:.{1}}", "str", 2)); -} - -template <typename T> -void check_unknown_types(const T& value, const char* types, const char*) { - char format_str[BUFFER_SIZE]; - const char* special = ".0123456789}"; - for (int i = CHAR_MIN; i <= CHAR_MAX; ++i) { - char c = static_cast<char>(i); - if (std::strchr(types, c) || std::strchr(special, c) || !c) continue; - safe_sprintf(format_str, "{0:10%c}", c); - const char* message = "invalid type specifier"; - EXPECT_THROW_MSG(format(format_str, value), format_error, message) - << format_str << " " << message; - } -} - -TEST(BoolTest, FormatBool) { - EXPECT_EQ("true", format("{}", true)); - EXPECT_EQ("false", format("{}", false)); - EXPECT_EQ("1", format("{:d}", true)); - EXPECT_EQ("true ", format("{:5}", true)); - EXPECT_EQ(L"true", format(L"{}", true)); -} - -TEST(FormatterTest, FormatShort) { - short s = 42; - EXPECT_EQ("42", format("{0:d}", s)); - unsigned short us = 42; - EXPECT_EQ("42", format("{0:d}", us)); -} - -TEST(FormatterTest, FormatInt) { - EXPECT_THROW_MSG(format("{0:v", 42), format_error, - "missing '}' in format string"); + + EXPECT_THROW_MSG(format("{0:.{0:}}", 0), format_error, + "invalid format string"); + + EXPECT_THROW_MSG(format("{0:.{1}}", 0, -1), format_error, + "negative precision"); + EXPECT_THROW_MSG(format("{0:.{1}}", 0, (INT_MAX + 1u)), format_error, + "number is too big"); + EXPECT_THROW_MSG(format("{0:.{1}}", 0, -1l), format_error, + "negative precision"); + if (const_check(sizeof(long) > sizeof(int))) { + long value = INT_MAX; + EXPECT_THROW_MSG(format("{0:.{1}}", 0, (value + 1)), format_error, + "number is too big"); + } + EXPECT_THROW_MSG(format("{0:.{1}}", 0, (INT_MAX + 1ul)), format_error, + "number is too big"); + + EXPECT_THROW_MSG(format("{0:.{1}}", 0, '0'), format_error, + "precision is not integer"); + EXPECT_THROW_MSG(format("{0:.{1}}", 0, 0.0), format_error, + "precision is not integer"); + + EXPECT_THROW_MSG(format("{0:.{1}}", 42, 2), format_error, + "precision not allowed for this argument type"); + EXPECT_THROW_MSG(format("{0:.{1}f}", 42, 2), format_error, + "precision not allowed for this argument type"); + EXPECT_THROW_MSG(format("{0:.{1}}", 42u, 2), format_error, + "precision not allowed for this argument type"); + EXPECT_THROW_MSG(format("{0:.{1}f}", 42u, 2), format_error, + "precision not allowed for this argument type"); + EXPECT_THROW_MSG(format("{0:.{1}}", 42l, 2), format_error, + "precision not allowed for this argument type"); + EXPECT_THROW_MSG(format("{0:.{1}f}", 42l, 2), format_error, + "precision not allowed for this argument type"); + EXPECT_THROW_MSG(format("{0:.{1}}", 42ul, 2), format_error, + "precision not allowed for this argument type"); + EXPECT_THROW_MSG(format("{0:.{1}f}", 42ul, 2), format_error, + "precision not allowed for this argument type"); + EXPECT_THROW_MSG(format("{0:.{1}}", 42ll, 2), format_error, + "precision not allowed for this argument type"); + EXPECT_THROW_MSG(format("{0:.{1}f}", 42ll, 2), format_error, + "precision not allowed for this argument type"); + EXPECT_THROW_MSG(format("{0:.{1}}", 42ull, 2), format_error, + "precision not allowed for this argument type"); + EXPECT_THROW_MSG(format("{0:.{1}f}", 42ull, 2), format_error, + "precision not allowed for this argument type"); + EXPECT_THROW_MSG(format("{0:3.{1}}", 'x', 0), format_error, + "precision not allowed for this argument type"); + EXPECT_EQ("1.2", format("{0:.{1}}", 1.2345, 2)); + EXPECT_EQ("1.2", format("{1:.{0}}", 2, 1.2345l)); + + EXPECT_THROW_MSG(format("{0:.{1}}", reinterpret_cast<void*>(0xcafe), 2), + format_error, + "precision not allowed for this argument type"); + EXPECT_THROW_MSG(format("{0:.{1}f}", reinterpret_cast<void*>(0xcafe), 2), + format_error, + "precision not allowed for this argument type"); + + EXPECT_EQ("st", format("{0:.{1}}", "str", 2)); +} + +template <typename T> +void check_unknown_types(const T& value, const char* types, const char*) { + char format_str[BUFFER_SIZE]; + const char* special = ".0123456789}"; + for (int i = CHAR_MIN; i <= CHAR_MAX; ++i) { + char c = static_cast<char>(i); + if (std::strchr(types, c) || std::strchr(special, c) || !c) continue; + safe_sprintf(format_str, "{0:10%c}", c); + const char* message = "invalid type specifier"; + EXPECT_THROW_MSG(format(format_str, value), format_error, message) + << format_str << " " << message; + } +} + +TEST(BoolTest, FormatBool) { + EXPECT_EQ("true", format("{}", true)); + EXPECT_EQ("false", format("{}", false)); + EXPECT_EQ("1", format("{:d}", true)); + EXPECT_EQ("true ", format("{:5}", true)); + EXPECT_EQ(L"true", format(L"{}", true)); +} + +TEST(FormatterTest, FormatShort) { + short s = 42; + EXPECT_EQ("42", format("{0:d}", s)); + unsigned short us = 42; + EXPECT_EQ("42", format("{0:d}", us)); +} + +TEST(FormatterTest, FormatInt) { + EXPECT_THROW_MSG(format("{0:v", 42), format_error, + "missing '}' in format string"); check_unknown_types(42, "bBdoxXnLc", "integer"); EXPECT_EQ("x", format("{:c}", static_cast<int>('x'))); -} - -TEST(FormatterTest, FormatBin) { - EXPECT_EQ("0", format("{0:b}", 0)); - EXPECT_EQ("101010", format("{0:b}", 42)); - EXPECT_EQ("101010", format("{0:b}", 42u)); - EXPECT_EQ("-101010", format("{0:b}", -42)); - EXPECT_EQ("11000000111001", format("{0:b}", 12345)); - EXPECT_EQ("10010001101000101011001111000", format("{0:b}", 0x12345678)); - EXPECT_EQ("10010000101010111100110111101111", format("{0:b}", 0x90ABCDEF)); - EXPECT_EQ("11111111111111111111111111111111", - format("{0:b}", max_value<uint32_t>())); -} - -#if FMT_USE_INT128 -constexpr auto int128_max = static_cast<__int128_t>( - (static_cast<__uint128_t>(1) << ((__SIZEOF_INT128__ * CHAR_BIT) - 1)) - 1); -constexpr auto int128_min = -int128_max - 1; - -constexpr auto uint128_max = ~static_cast<__uint128_t>(0); -#endif - -TEST(FormatterTest, FormatDec) { - EXPECT_EQ("0", format("{0}", 0)); - EXPECT_EQ("42", format("{0}", 42)); - EXPECT_EQ("42", format("{0:d}", 42)); - EXPECT_EQ("42", format("{0}", 42u)); - EXPECT_EQ("-42", format("{0}", -42)); - EXPECT_EQ("12345", format("{0}", 12345)); - EXPECT_EQ("67890", format("{0}", 67890)); -#if FMT_USE_INT128 - EXPECT_EQ("0", format("{0}", static_cast<__int128_t>(0))); - EXPECT_EQ("0", format("{0}", static_cast<__uint128_t>(0))); - EXPECT_EQ("9223372036854775808", - format("{0}", static_cast<__int128_t>(INT64_MAX) + 1)); - EXPECT_EQ("-9223372036854775809", - format("{0}", static_cast<__int128_t>(INT64_MIN) - 1)); - EXPECT_EQ("18446744073709551616", - format("{0}", static_cast<__int128_t>(UINT64_MAX) + 1)); - EXPECT_EQ("170141183460469231731687303715884105727", - format("{0}", int128_max)); - EXPECT_EQ("-170141183460469231731687303715884105728", - format("{0}", int128_min)); - EXPECT_EQ("340282366920938463463374607431768211455", - format("{0}", uint128_max)); -#endif - - char buffer[BUFFER_SIZE]; - safe_sprintf(buffer, "%d", INT_MIN); - EXPECT_EQ(buffer, format("{0}", INT_MIN)); - safe_sprintf(buffer, "%d", INT_MAX); - EXPECT_EQ(buffer, format("{0}", INT_MAX)); - safe_sprintf(buffer, "%u", UINT_MAX); - EXPECT_EQ(buffer, format("{0}", UINT_MAX)); - safe_sprintf(buffer, "%ld", 0 - static_cast<unsigned long>(LONG_MIN)); - EXPECT_EQ(buffer, format("{0}", LONG_MIN)); - safe_sprintf(buffer, "%ld", LONG_MAX); - EXPECT_EQ(buffer, format("{0}", LONG_MAX)); - safe_sprintf(buffer, "%lu", ULONG_MAX); - EXPECT_EQ(buffer, format("{0}", ULONG_MAX)); -} - -TEST(FormatterTest, FormatHex) { - EXPECT_EQ("0", format("{0:x}", 0)); - EXPECT_EQ("42", format("{0:x}", 0x42)); - EXPECT_EQ("42", format("{0:x}", 0x42u)); - EXPECT_EQ("-42", format("{0:x}", -0x42)); - EXPECT_EQ("12345678", format("{0:x}", 0x12345678)); - EXPECT_EQ("90abcdef", format("{0:x}", 0x90abcdef)); - EXPECT_EQ("12345678", format("{0:X}", 0x12345678)); - EXPECT_EQ("90ABCDEF", format("{0:X}", 0x90ABCDEF)); -#if FMT_USE_INT128 - EXPECT_EQ("0", format("{0:x}", static_cast<__int128_t>(0))); - EXPECT_EQ("0", format("{0:x}", static_cast<__uint128_t>(0))); - EXPECT_EQ("8000000000000000", - format("{0:x}", static_cast<__int128_t>(INT64_MAX) + 1)); - EXPECT_EQ("-8000000000000001", - format("{0:x}", static_cast<__int128_t>(INT64_MIN) - 1)); - EXPECT_EQ("10000000000000000", - format("{0:x}", static_cast<__int128_t>(UINT64_MAX) + 1)); - EXPECT_EQ("7fffffffffffffffffffffffffffffff", format("{0:x}", int128_max)); - EXPECT_EQ("-80000000000000000000000000000000", format("{0:x}", int128_min)); - EXPECT_EQ("ffffffffffffffffffffffffffffffff", format("{0:x}", uint128_max)); -#endif - - char buffer[BUFFER_SIZE]; - safe_sprintf(buffer, "-%x", 0 - static_cast<unsigned>(INT_MIN)); - EXPECT_EQ(buffer, format("{0:x}", INT_MIN)); - safe_sprintf(buffer, "%x", INT_MAX); - EXPECT_EQ(buffer, format("{0:x}", INT_MAX)); - safe_sprintf(buffer, "%x", UINT_MAX); - EXPECT_EQ(buffer, format("{0:x}", UINT_MAX)); - safe_sprintf(buffer, "-%lx", 0 - static_cast<unsigned long>(LONG_MIN)); - EXPECT_EQ(buffer, format("{0:x}", LONG_MIN)); - safe_sprintf(buffer, "%lx", LONG_MAX); - EXPECT_EQ(buffer, format("{0:x}", LONG_MAX)); - safe_sprintf(buffer, "%lx", ULONG_MAX); - EXPECT_EQ(buffer, format("{0:x}", ULONG_MAX)); -} - -TEST(FormatterTest, FormatOct) { - EXPECT_EQ("0", format("{0:o}", 0)); - EXPECT_EQ("42", format("{0:o}", 042)); - EXPECT_EQ("42", format("{0:o}", 042u)); - EXPECT_EQ("-42", format("{0:o}", -042)); - EXPECT_EQ("12345670", format("{0:o}", 012345670)); -#if FMT_USE_INT128 - EXPECT_EQ("0", format("{0:o}", static_cast<__int128_t>(0))); - EXPECT_EQ("0", format("{0:o}", static_cast<__uint128_t>(0))); - EXPECT_EQ("1000000000000000000000", - format("{0:o}", static_cast<__int128_t>(INT64_MAX) + 1)); - EXPECT_EQ("-1000000000000000000001", - format("{0:o}", static_cast<__int128_t>(INT64_MIN) - 1)); - EXPECT_EQ("2000000000000000000000", - format("{0:o}", static_cast<__int128_t>(UINT64_MAX) + 1)); - EXPECT_EQ("1777777777777777777777777777777777777777777", - format("{0:o}", int128_max)); - EXPECT_EQ("-2000000000000000000000000000000000000000000", - format("{0:o}", int128_min)); - EXPECT_EQ("3777777777777777777777777777777777777777777", - format("{0:o}", uint128_max)); -#endif - - char buffer[BUFFER_SIZE]; - safe_sprintf(buffer, "-%o", 0 - static_cast<unsigned>(INT_MIN)); - EXPECT_EQ(buffer, format("{0:o}", INT_MIN)); - safe_sprintf(buffer, "%o", INT_MAX); - EXPECT_EQ(buffer, format("{0:o}", INT_MAX)); - safe_sprintf(buffer, "%o", UINT_MAX); - EXPECT_EQ(buffer, format("{0:o}", UINT_MAX)); - safe_sprintf(buffer, "-%lo", 0 - static_cast<unsigned long>(LONG_MIN)); - EXPECT_EQ(buffer, format("{0:o}", LONG_MIN)); - safe_sprintf(buffer, "%lo", LONG_MAX); - EXPECT_EQ(buffer, format("{0:o}", LONG_MAX)); - safe_sprintf(buffer, "%lo", ULONG_MAX); - EXPECT_EQ(buffer, format("{0:o}", ULONG_MAX)); -} - -TEST(FormatterTest, FormatIntLocale) { - EXPECT_EQ("1234", format("{:L}", 1234)); -} - -struct ConvertibleToLongLong { - operator long long() const { return 1LL << 32; } -}; - -TEST(FormatterTest, FormatConvertibleToLongLong) { - EXPECT_EQ("100000000", format("{:x}", ConvertibleToLongLong())); -} - -TEST(FormatterTest, FormatFloat) { +} + +TEST(FormatterTest, FormatBin) { + EXPECT_EQ("0", format("{0:b}", 0)); + EXPECT_EQ("101010", format("{0:b}", 42)); + EXPECT_EQ("101010", format("{0:b}", 42u)); + EXPECT_EQ("-101010", format("{0:b}", -42)); + EXPECT_EQ("11000000111001", format("{0:b}", 12345)); + EXPECT_EQ("10010001101000101011001111000", format("{0:b}", 0x12345678)); + EXPECT_EQ("10010000101010111100110111101111", format("{0:b}", 0x90ABCDEF)); + EXPECT_EQ("11111111111111111111111111111111", + format("{0:b}", max_value<uint32_t>())); +} + +#if FMT_USE_INT128 +constexpr auto int128_max = static_cast<__int128_t>( + (static_cast<__uint128_t>(1) << ((__SIZEOF_INT128__ * CHAR_BIT) - 1)) - 1); +constexpr auto int128_min = -int128_max - 1; + +constexpr auto uint128_max = ~static_cast<__uint128_t>(0); +#endif + +TEST(FormatterTest, FormatDec) { + EXPECT_EQ("0", format("{0}", 0)); + EXPECT_EQ("42", format("{0}", 42)); + EXPECT_EQ("42", format("{0:d}", 42)); + EXPECT_EQ("42", format("{0}", 42u)); + EXPECT_EQ("-42", format("{0}", -42)); + EXPECT_EQ("12345", format("{0}", 12345)); + EXPECT_EQ("67890", format("{0}", 67890)); +#if FMT_USE_INT128 + EXPECT_EQ("0", format("{0}", static_cast<__int128_t>(0))); + EXPECT_EQ("0", format("{0}", static_cast<__uint128_t>(0))); + EXPECT_EQ("9223372036854775808", + format("{0}", static_cast<__int128_t>(INT64_MAX) + 1)); + EXPECT_EQ("-9223372036854775809", + format("{0}", static_cast<__int128_t>(INT64_MIN) - 1)); + EXPECT_EQ("18446744073709551616", + format("{0}", static_cast<__int128_t>(UINT64_MAX) + 1)); + EXPECT_EQ("170141183460469231731687303715884105727", + format("{0}", int128_max)); + EXPECT_EQ("-170141183460469231731687303715884105728", + format("{0}", int128_min)); + EXPECT_EQ("340282366920938463463374607431768211455", + format("{0}", uint128_max)); +#endif + + char buffer[BUFFER_SIZE]; + safe_sprintf(buffer, "%d", INT_MIN); + EXPECT_EQ(buffer, format("{0}", INT_MIN)); + safe_sprintf(buffer, "%d", INT_MAX); + EXPECT_EQ(buffer, format("{0}", INT_MAX)); + safe_sprintf(buffer, "%u", UINT_MAX); + EXPECT_EQ(buffer, format("{0}", UINT_MAX)); + safe_sprintf(buffer, "%ld", 0 - static_cast<unsigned long>(LONG_MIN)); + EXPECT_EQ(buffer, format("{0}", LONG_MIN)); + safe_sprintf(buffer, "%ld", LONG_MAX); + EXPECT_EQ(buffer, format("{0}", LONG_MAX)); + safe_sprintf(buffer, "%lu", ULONG_MAX); + EXPECT_EQ(buffer, format("{0}", ULONG_MAX)); +} + +TEST(FormatterTest, FormatHex) { + EXPECT_EQ("0", format("{0:x}", 0)); + EXPECT_EQ("42", format("{0:x}", 0x42)); + EXPECT_EQ("42", format("{0:x}", 0x42u)); + EXPECT_EQ("-42", format("{0:x}", -0x42)); + EXPECT_EQ("12345678", format("{0:x}", 0x12345678)); + EXPECT_EQ("90abcdef", format("{0:x}", 0x90abcdef)); + EXPECT_EQ("12345678", format("{0:X}", 0x12345678)); + EXPECT_EQ("90ABCDEF", format("{0:X}", 0x90ABCDEF)); +#if FMT_USE_INT128 + EXPECT_EQ("0", format("{0:x}", static_cast<__int128_t>(0))); + EXPECT_EQ("0", format("{0:x}", static_cast<__uint128_t>(0))); + EXPECT_EQ("8000000000000000", + format("{0:x}", static_cast<__int128_t>(INT64_MAX) + 1)); + EXPECT_EQ("-8000000000000001", + format("{0:x}", static_cast<__int128_t>(INT64_MIN) - 1)); + EXPECT_EQ("10000000000000000", + format("{0:x}", static_cast<__int128_t>(UINT64_MAX) + 1)); + EXPECT_EQ("7fffffffffffffffffffffffffffffff", format("{0:x}", int128_max)); + EXPECT_EQ("-80000000000000000000000000000000", format("{0:x}", int128_min)); + EXPECT_EQ("ffffffffffffffffffffffffffffffff", format("{0:x}", uint128_max)); +#endif + + char buffer[BUFFER_SIZE]; + safe_sprintf(buffer, "-%x", 0 - static_cast<unsigned>(INT_MIN)); + EXPECT_EQ(buffer, format("{0:x}", INT_MIN)); + safe_sprintf(buffer, "%x", INT_MAX); + EXPECT_EQ(buffer, format("{0:x}", INT_MAX)); + safe_sprintf(buffer, "%x", UINT_MAX); + EXPECT_EQ(buffer, format("{0:x}", UINT_MAX)); + safe_sprintf(buffer, "-%lx", 0 - static_cast<unsigned long>(LONG_MIN)); + EXPECT_EQ(buffer, format("{0:x}", LONG_MIN)); + safe_sprintf(buffer, "%lx", LONG_MAX); + EXPECT_EQ(buffer, format("{0:x}", LONG_MAX)); + safe_sprintf(buffer, "%lx", ULONG_MAX); + EXPECT_EQ(buffer, format("{0:x}", ULONG_MAX)); +} + +TEST(FormatterTest, FormatOct) { + EXPECT_EQ("0", format("{0:o}", 0)); + EXPECT_EQ("42", format("{0:o}", 042)); + EXPECT_EQ("42", format("{0:o}", 042u)); + EXPECT_EQ("-42", format("{0:o}", -042)); + EXPECT_EQ("12345670", format("{0:o}", 012345670)); +#if FMT_USE_INT128 + EXPECT_EQ("0", format("{0:o}", static_cast<__int128_t>(0))); + EXPECT_EQ("0", format("{0:o}", static_cast<__uint128_t>(0))); + EXPECT_EQ("1000000000000000000000", + format("{0:o}", static_cast<__int128_t>(INT64_MAX) + 1)); + EXPECT_EQ("-1000000000000000000001", + format("{0:o}", static_cast<__int128_t>(INT64_MIN) - 1)); + EXPECT_EQ("2000000000000000000000", + format("{0:o}", static_cast<__int128_t>(UINT64_MAX) + 1)); + EXPECT_EQ("1777777777777777777777777777777777777777777", + format("{0:o}", int128_max)); + EXPECT_EQ("-2000000000000000000000000000000000000000000", + format("{0:o}", int128_min)); + EXPECT_EQ("3777777777777777777777777777777777777777777", + format("{0:o}", uint128_max)); +#endif + + char buffer[BUFFER_SIZE]; + safe_sprintf(buffer, "-%o", 0 - static_cast<unsigned>(INT_MIN)); + EXPECT_EQ(buffer, format("{0:o}", INT_MIN)); + safe_sprintf(buffer, "%o", INT_MAX); + EXPECT_EQ(buffer, format("{0:o}", INT_MAX)); + safe_sprintf(buffer, "%o", UINT_MAX); + EXPECT_EQ(buffer, format("{0:o}", UINT_MAX)); + safe_sprintf(buffer, "-%lo", 0 - static_cast<unsigned long>(LONG_MIN)); + EXPECT_EQ(buffer, format("{0:o}", LONG_MIN)); + safe_sprintf(buffer, "%lo", LONG_MAX); + EXPECT_EQ(buffer, format("{0:o}", LONG_MAX)); + safe_sprintf(buffer, "%lo", ULONG_MAX); + EXPECT_EQ(buffer, format("{0:o}", ULONG_MAX)); +} + +TEST(FormatterTest, FormatIntLocale) { + EXPECT_EQ("1234", format("{:L}", 1234)); +} + +struct ConvertibleToLongLong { + operator long long() const { return 1LL << 32; } +}; + +TEST(FormatterTest, FormatConvertibleToLongLong) { + EXPECT_EQ("100000000", format("{:x}", ConvertibleToLongLong())); +} + +TEST(FormatterTest, FormatFloat) { EXPECT_EQ("0", format("{}", 0.0f)); - EXPECT_EQ("392.500000", format("{0:f}", 392.5f)); -} - -TEST(FormatterTest, FormatDouble) { + EXPECT_EQ("392.500000", format("{0:f}", 392.5f)); +} + +TEST(FormatterTest, FormatDouble) { EXPECT_EQ("0", format("{}", 0.0)); check_unknown_types(1.2, "eEfFgGaAnL%", "double"); EXPECT_EQ("0", format("{:}", 0.0)); - EXPECT_EQ("0.000000", format("{:f}", 0.0)); - EXPECT_EQ("0", format("{:g}", 0.0)); - EXPECT_EQ("392.65", format("{:}", 392.65)); - EXPECT_EQ("392.65", format("{:g}", 392.65)); - EXPECT_EQ("392.65", format("{:G}", 392.65)); + EXPECT_EQ("0.000000", format("{:f}", 0.0)); + EXPECT_EQ("0", format("{:g}", 0.0)); + EXPECT_EQ("392.65", format("{:}", 392.65)); + EXPECT_EQ("392.65", format("{:g}", 392.65)); + EXPECT_EQ("392.65", format("{:G}", 392.65)); EXPECT_EQ("4.9014e+06", format("{:g}", 4.9014e6)); - EXPECT_EQ("392.650000", format("{:f}", 392.65)); - EXPECT_EQ("392.650000", format("{:F}", 392.65)); + EXPECT_EQ("392.650000", format("{:f}", 392.65)); + EXPECT_EQ("392.650000", format("{:F}", 392.65)); EXPECT_EQ("42", format("{:L}", 42.0)); - char buffer[BUFFER_SIZE]; - safe_sprintf(buffer, "%e", 392.65); - EXPECT_EQ(buffer, format("{0:e}", 392.65)); - safe_sprintf(buffer, "%E", 392.65); - EXPECT_EQ(buffer, format("{0:E}", 392.65)); - EXPECT_EQ("+0000392.6", format("{0:+010.4g}", 392.65)); - safe_sprintf(buffer, "%a", -42.0); - EXPECT_EQ(buffer, format("{:a}", -42.0)); - safe_sprintf(buffer, "%A", -42.0); - EXPECT_EQ(buffer, format("{:A}", -42.0)); + char buffer[BUFFER_SIZE]; + safe_sprintf(buffer, "%e", 392.65); + EXPECT_EQ(buffer, format("{0:e}", 392.65)); + safe_sprintf(buffer, "%E", 392.65); + EXPECT_EQ(buffer, format("{0:E}", 392.65)); + EXPECT_EQ("+0000392.6", format("{0:+010.4g}", 392.65)); + safe_sprintf(buffer, "%a", -42.0); + EXPECT_EQ(buffer, format("{:a}", -42.0)); + safe_sprintf(buffer, "%A", -42.0); + EXPECT_EQ(buffer, format("{:A}", -42.0)); EXPECT_EQ("9223372036854775808.000000", format("{:f}", 9223372036854775807.0)); -} - -TEST(FormatterTest, PrecisionRounding) { - EXPECT_EQ("0", format("{:.0f}", 0.0)); - EXPECT_EQ("0", format("{:.0f}", 0.01)); - EXPECT_EQ("0", format("{:.0f}", 0.1)); - EXPECT_EQ("0.000", format("{:.3f}", 0.00049)); - EXPECT_EQ("0.001", format("{:.3f}", 0.0005)); - EXPECT_EQ("0.001", format("{:.3f}", 0.00149)); - EXPECT_EQ("0.002", format("{:.3f}", 0.0015)); - EXPECT_EQ("1.000", format("{:.3f}", 0.9999)); - EXPECT_EQ("0.00123", format("{:.3}", 0.00123)); - EXPECT_EQ("0.1", format("{:.16g}", 0.1)); +} + +TEST(FormatterTest, PrecisionRounding) { + EXPECT_EQ("0", format("{:.0f}", 0.0)); + EXPECT_EQ("0", format("{:.0f}", 0.01)); + EXPECT_EQ("0", format("{:.0f}", 0.1)); + EXPECT_EQ("0.000", format("{:.3f}", 0.00049)); + EXPECT_EQ("0.001", format("{:.3f}", 0.0005)); + EXPECT_EQ("0.001", format("{:.3f}", 0.00149)); + EXPECT_EQ("0.002", format("{:.3f}", 0.0015)); + EXPECT_EQ("1.000", format("{:.3f}", 0.9999)); + EXPECT_EQ("0.00123", format("{:.3}", 0.00123)); + EXPECT_EQ("0.1", format("{:.16g}", 0.1)); EXPECT_EQ("1", fmt::format("{:.0}", 1.0)); EXPECT_EQ("225.51575035152063720", fmt::format("{:.17f}", 225.51575035152064)); @@ -1295,8 +1295,8 @@ TEST(FormatterTest, PrecisionRounding) { // Trigger a rounding error in Grisu by a specially chosen number. EXPECT_EQ("3788512123356.985352", format("{:f}", 3788512123356.985352)); -} - +} + TEST(FormatterTest, PrettifyFloat) { EXPECT_EQ("0.0001", fmt::format("{}", 1e-4)); EXPECT_EQ("1e-05", fmt::format("{}", 1e-5)); @@ -1313,166 +1313,166 @@ TEST(FormatterTest, PrettifyFloat) { EXPECT_EQ("1.3563156e-19", fmt::format("{}", 1.35631564e-19f)); } -TEST(FormatterTest, FormatNaN) { - double nan = std::numeric_limits<double>::quiet_NaN(); - EXPECT_EQ("nan", format("{}", nan)); - EXPECT_EQ("+nan", format("{:+}", nan)); +TEST(FormatterTest, FormatNaN) { + double nan = std::numeric_limits<double>::quiet_NaN(); + EXPECT_EQ("nan", format("{}", nan)); + EXPECT_EQ("+nan", format("{:+}", nan)); if (std::signbit(-nan)) EXPECT_EQ("-nan", format("{}", -nan)); else fmt::print("Warning: compiler doesn't handle negative NaN correctly"); - EXPECT_EQ(" nan", format("{: }", nan)); - EXPECT_EQ("NAN", format("{:F}", nan)); - EXPECT_EQ("nan ", format("{:<7}", nan)); - EXPECT_EQ(" nan ", format("{:^7}", nan)); - EXPECT_EQ(" nan", format("{:>7}", nan)); -} - -TEST(FormatterTest, FormatInfinity) { - double inf = std::numeric_limits<double>::infinity(); - EXPECT_EQ("inf", format("{}", inf)); - EXPECT_EQ("+inf", format("{:+}", inf)); - EXPECT_EQ("-inf", format("{}", -inf)); - EXPECT_EQ(" inf", format("{: }", inf)); - EXPECT_EQ("INF", format("{:F}", inf)); - EXPECT_EQ("inf ", format("{:<7}", inf)); - EXPECT_EQ(" inf ", format("{:^7}", inf)); - EXPECT_EQ(" inf", format("{:>7}", inf)); -} - -TEST(FormatterTest, FormatLongDouble) { + EXPECT_EQ(" nan", format("{: }", nan)); + EXPECT_EQ("NAN", format("{:F}", nan)); + EXPECT_EQ("nan ", format("{:<7}", nan)); + EXPECT_EQ(" nan ", format("{:^7}", nan)); + EXPECT_EQ(" nan", format("{:>7}", nan)); +} + +TEST(FormatterTest, FormatInfinity) { + double inf = std::numeric_limits<double>::infinity(); + EXPECT_EQ("inf", format("{}", inf)); + EXPECT_EQ("+inf", format("{:+}", inf)); + EXPECT_EQ("-inf", format("{}", -inf)); + EXPECT_EQ(" inf", format("{: }", inf)); + EXPECT_EQ("INF", format("{:F}", inf)); + EXPECT_EQ("inf ", format("{:<7}", inf)); + EXPECT_EQ(" inf ", format("{:^7}", inf)); + EXPECT_EQ(" inf", format("{:>7}", inf)); +} + +TEST(FormatterTest, FormatLongDouble) { EXPECT_EQ("0", format("{0:}", 0.0l)); - EXPECT_EQ("0.000000", format("{0:f}", 0.0l)); - EXPECT_EQ("392.65", format("{0:}", 392.65l)); - EXPECT_EQ("392.65", format("{0:g}", 392.65l)); - EXPECT_EQ("392.65", format("{0:G}", 392.65l)); - EXPECT_EQ("392.650000", format("{0:f}", 392.65l)); - EXPECT_EQ("392.650000", format("{0:F}", 392.65l)); - char buffer[BUFFER_SIZE]; - safe_sprintf(buffer, "%Le", 392.65l); - EXPECT_EQ(buffer, format("{0:e}", 392.65l)); - EXPECT_EQ("+0000392.6", format("{0:+010.4g}", 392.64l)); - safe_sprintf(buffer, "%La", 3.31l); - EXPECT_EQ(buffer, format("{:a}", 3.31l)); -} - -TEST(FormatterTest, FormatChar) { + EXPECT_EQ("0.000000", format("{0:f}", 0.0l)); + EXPECT_EQ("392.65", format("{0:}", 392.65l)); + EXPECT_EQ("392.65", format("{0:g}", 392.65l)); + EXPECT_EQ("392.65", format("{0:G}", 392.65l)); + EXPECT_EQ("392.650000", format("{0:f}", 392.65l)); + EXPECT_EQ("392.650000", format("{0:F}", 392.65l)); + char buffer[BUFFER_SIZE]; + safe_sprintf(buffer, "%Le", 392.65l); + EXPECT_EQ(buffer, format("{0:e}", 392.65l)); + EXPECT_EQ("+0000392.6", format("{0:+010.4g}", 392.64l)); + safe_sprintf(buffer, "%La", 3.31l); + EXPECT_EQ(buffer, format("{:a}", 3.31l)); +} + +TEST(FormatterTest, FormatChar) { const char types[] = "cbBdoxXL"; - check_unknown_types('a', types, "char"); - EXPECT_EQ("a", format("{0}", 'a')); - EXPECT_EQ("z", format("{0:c}", 'z')); - EXPECT_EQ(L"a", format(L"{0}", 'a')); - int n = 'x'; - for (const char* type = types + 1; *type; ++type) { - std::string format_str = fmt::format("{{:{}}}", *type); - EXPECT_EQ(fmt::format(format_str, n), fmt::format(format_str, 'x')); - } - EXPECT_EQ(fmt::format("{:02X}", n), fmt::format("{:02X}", 'x')); -} - -TEST(FormatterTest, FormatVolatileChar) { - volatile char c = 'x'; - EXPECT_EQ("x", format("{}", c)); -} - -TEST(FormatterTest, FormatUnsignedChar) { - EXPECT_EQ("42", format("{}", static_cast<unsigned char>(42))); - EXPECT_EQ("42", format("{}", static_cast<uint8_t>(42))); -} - -TEST(FormatterTest, FormatWChar) { - EXPECT_EQ(L"a", format(L"{0}", L'a')); - // This shouldn't compile: - // format("{}", L'a'); -} - -TEST(FormatterTest, FormatCString) { - check_unknown_types("test", "sp", "string"); - EXPECT_EQ("test", format("{0}", "test")); - EXPECT_EQ("test", format("{0:s}", "test")); - char nonconst[] = "nonconst"; - EXPECT_EQ("nonconst", format("{0}", nonconst)); - EXPECT_THROW_MSG(format("{0}", static_cast<const char*>(nullptr)), - format_error, "string pointer is null"); -} - -TEST(FormatterTest, FormatSCharString) { - signed char str[] = "test"; - EXPECT_EQ("test", format("{0:s}", str)); - const signed char* const_str = str; - EXPECT_EQ("test", format("{0:s}", const_str)); -} - -TEST(FormatterTest, FormatUCharString) { - unsigned char str[] = "test"; - EXPECT_EQ("test", format("{0:s}", str)); - const unsigned char* const_str = str; - EXPECT_EQ("test", format("{0:s}", const_str)); - unsigned char* ptr = str; - EXPECT_EQ("test", format("{0:s}", ptr)); -} - -TEST(FormatterTest, FormatPointer) { - check_unknown_types(reinterpret_cast<void*>(0x1234), "p", "pointer"); - EXPECT_EQ("0x0", format("{0}", static_cast<void*>(nullptr))); - EXPECT_EQ("0x1234", format("{0}", reinterpret_cast<void*>(0x1234))); - EXPECT_EQ("0x1234", format("{0:p}", reinterpret_cast<void*>(0x1234))); - EXPECT_EQ("0x" + std::string(sizeof(void*) * CHAR_BIT / 4, 'f'), - format("{0}", reinterpret_cast<void*>(~uintptr_t()))); - EXPECT_EQ("0x1234", format("{}", fmt::ptr(reinterpret_cast<int*>(0x1234)))); - std::unique_ptr<int> up(new int(1)); - EXPECT_EQ(format("{}", fmt::ptr(up.get())), format("{}", fmt::ptr(up))); - std::shared_ptr<int> sp(new int(1)); - EXPECT_EQ(format("{}", fmt::ptr(sp.get())), format("{}", fmt::ptr(sp))); - EXPECT_EQ("0x0", format("{}", nullptr)); -} - -TEST(FormatterTest, FormatString) { - EXPECT_EQ("test", format("{0}", std::string("test"))); -} - -TEST(FormatterTest, FormatStringView) { - EXPECT_EQ("test", format("{}", string_view("test"))); - EXPECT_EQ("", format("{}", string_view())); -} - -#ifdef FMT_USE_STRING_VIEW -struct string_viewable {}; - -FMT_BEGIN_NAMESPACE -template <> struct formatter<string_viewable> : formatter<std::string_view> { - auto format(string_viewable, format_context& ctx) -> decltype(ctx.out()) { - return formatter<std::string_view>::format("foo", ctx); - } -}; -FMT_END_NAMESPACE - -TEST(FormatterTest, FormatStdStringView) { - EXPECT_EQ("test", format("{}", std::string_view("test"))); - EXPECT_EQ("foo", format("{}", string_viewable())); -} - -struct explicitly_convertible_to_std_string_view { - explicit operator std::string_view() const { return "foo"; } -}; - -namespace fmt { -template <> -struct formatter<explicitly_convertible_to_std_string_view> - : formatter<std::string_view> { - auto format(const explicitly_convertible_to_std_string_view& v, - format_context& ctx) -> decltype(ctx.out()) { - return format_to(ctx.out(), "'{}'", std::string_view(v)); - } -}; -} // namespace fmt - -TEST(FormatterTest, FormatExplicitlyConvertibleToStdStringView) { - EXPECT_EQ("'foo'", - fmt::format("{}", explicitly_convertible_to_std_string_view())); -} -#endif - + check_unknown_types('a', types, "char"); + EXPECT_EQ("a", format("{0}", 'a')); + EXPECT_EQ("z", format("{0:c}", 'z')); + EXPECT_EQ(L"a", format(L"{0}", 'a')); + int n = 'x'; + for (const char* type = types + 1; *type; ++type) { + std::string format_str = fmt::format("{{:{}}}", *type); + EXPECT_EQ(fmt::format(format_str, n), fmt::format(format_str, 'x')); + } + EXPECT_EQ(fmt::format("{:02X}", n), fmt::format("{:02X}", 'x')); +} + +TEST(FormatterTest, FormatVolatileChar) { + volatile char c = 'x'; + EXPECT_EQ("x", format("{}", c)); +} + +TEST(FormatterTest, FormatUnsignedChar) { + EXPECT_EQ("42", format("{}", static_cast<unsigned char>(42))); + EXPECT_EQ("42", format("{}", static_cast<uint8_t>(42))); +} + +TEST(FormatterTest, FormatWChar) { + EXPECT_EQ(L"a", format(L"{0}", L'a')); + // This shouldn't compile: + // format("{}", L'a'); +} + +TEST(FormatterTest, FormatCString) { + check_unknown_types("test", "sp", "string"); + EXPECT_EQ("test", format("{0}", "test")); + EXPECT_EQ("test", format("{0:s}", "test")); + char nonconst[] = "nonconst"; + EXPECT_EQ("nonconst", format("{0}", nonconst)); + EXPECT_THROW_MSG(format("{0}", static_cast<const char*>(nullptr)), + format_error, "string pointer is null"); +} + +TEST(FormatterTest, FormatSCharString) { + signed char str[] = "test"; + EXPECT_EQ("test", format("{0:s}", str)); + const signed char* const_str = str; + EXPECT_EQ("test", format("{0:s}", const_str)); +} + +TEST(FormatterTest, FormatUCharString) { + unsigned char str[] = "test"; + EXPECT_EQ("test", format("{0:s}", str)); + const unsigned char* const_str = str; + EXPECT_EQ("test", format("{0:s}", const_str)); + unsigned char* ptr = str; + EXPECT_EQ("test", format("{0:s}", ptr)); +} + +TEST(FormatterTest, FormatPointer) { + check_unknown_types(reinterpret_cast<void*>(0x1234), "p", "pointer"); + EXPECT_EQ("0x0", format("{0}", static_cast<void*>(nullptr))); + EXPECT_EQ("0x1234", format("{0}", reinterpret_cast<void*>(0x1234))); + EXPECT_EQ("0x1234", format("{0:p}", reinterpret_cast<void*>(0x1234))); + EXPECT_EQ("0x" + std::string(sizeof(void*) * CHAR_BIT / 4, 'f'), + format("{0}", reinterpret_cast<void*>(~uintptr_t()))); + EXPECT_EQ("0x1234", format("{}", fmt::ptr(reinterpret_cast<int*>(0x1234)))); + std::unique_ptr<int> up(new int(1)); + EXPECT_EQ(format("{}", fmt::ptr(up.get())), format("{}", fmt::ptr(up))); + std::shared_ptr<int> sp(new int(1)); + EXPECT_EQ(format("{}", fmt::ptr(sp.get())), format("{}", fmt::ptr(sp))); + EXPECT_EQ("0x0", format("{}", nullptr)); +} + +TEST(FormatterTest, FormatString) { + EXPECT_EQ("test", format("{0}", std::string("test"))); +} + +TEST(FormatterTest, FormatStringView) { + EXPECT_EQ("test", format("{}", string_view("test"))); + EXPECT_EQ("", format("{}", string_view())); +} + +#ifdef FMT_USE_STRING_VIEW +struct string_viewable {}; + +FMT_BEGIN_NAMESPACE +template <> struct formatter<string_viewable> : formatter<std::string_view> { + auto format(string_viewable, format_context& ctx) -> decltype(ctx.out()) { + return formatter<std::string_view>::format("foo", ctx); + } +}; +FMT_END_NAMESPACE + +TEST(FormatterTest, FormatStdStringView) { + EXPECT_EQ("test", format("{}", std::string_view("test"))); + EXPECT_EQ("foo", format("{}", string_viewable())); +} + +struct explicitly_convertible_to_std_string_view { + explicit operator std::string_view() const { return "foo"; } +}; + +namespace fmt { +template <> +struct formatter<explicitly_convertible_to_std_string_view> + : formatter<std::string_view> { + auto format(const explicitly_convertible_to_std_string_view& v, + format_context& ctx) -> decltype(ctx.out()) { + return format_to(ctx.out(), "'{}'", std::string_view(v)); + } +}; +} // namespace fmt + +TEST(FormatterTest, FormatExplicitlyConvertibleToStdStringView) { + EXPECT_EQ("'foo'", + fmt::format("{}", explicitly_convertible_to_std_string_view())); +} +#endif + // std::is_constructible is broken in MSVC until version 2015. #if !FMT_MSC_VER || FMT_MSC_VER >= 1900 struct explicitly_convertible_to_wstring_view { @@ -1507,390 +1507,390 @@ TEST(FormatTest, FormatForeignStrings) { EXPECT_EQ(fmt::format(QString(L"{}"), QString(L"42")), L"42"); } -FMT_BEGIN_NAMESPACE -template <> struct formatter<Date> { - template <typename ParseContext> - FMT_CONSTEXPR auto parse(ParseContext& ctx) -> decltype(ctx.begin()) { - auto it = ctx.begin(); +FMT_BEGIN_NAMESPACE +template <> struct formatter<Date> { + template <typename ParseContext> + FMT_CONSTEXPR auto parse(ParseContext& ctx) -> decltype(ctx.begin()) { + auto it = ctx.begin(); if (it != ctx.end() && *it == 'd') ++it; - return it; - } - - auto format(const Date& d, format_context& ctx) -> decltype(ctx.out()) { - format_to(ctx.out(), "{}-{}-{}", d.year(), d.month(), d.day()); - return ctx.out(); - } -}; -FMT_END_NAMESPACE - -TEST(FormatterTest, FormatCustom) { - Date date(2012, 12, 9); - EXPECT_THROW_MSG(fmt::format("{:s}", date), format_error, - "unknown format specifier"); -} - -class Answer {}; - -FMT_BEGIN_NAMESPACE -template <> struct formatter<Answer> : formatter<int> { - template <typename FormatContext> - auto format(Answer, FormatContext& ctx) -> decltype(ctx.out()) { - return formatter<int>::format(42, ctx); - } -}; -FMT_END_NAMESPACE - -TEST(FormatterTest, CustomFormat) { - EXPECT_EQ("42", format("{0}", Answer())); - EXPECT_EQ("0042", format("{:04}", Answer())); -} - -TEST(FormatterTest, CustomFormatTo) { - char buf[10] = {}; - auto end = + return it; + } + + auto format(const Date& d, format_context& ctx) -> decltype(ctx.out()) { + format_to(ctx.out(), "{}-{}-{}", d.year(), d.month(), d.day()); + return ctx.out(); + } +}; +FMT_END_NAMESPACE + +TEST(FormatterTest, FormatCustom) { + Date date(2012, 12, 9); + EXPECT_THROW_MSG(fmt::format("{:s}", date), format_error, + "unknown format specifier"); +} + +class Answer {}; + +FMT_BEGIN_NAMESPACE +template <> struct formatter<Answer> : formatter<int> { + template <typename FormatContext> + auto format(Answer, FormatContext& ctx) -> decltype(ctx.out()) { + return formatter<int>::format(42, ctx); + } +}; +FMT_END_NAMESPACE + +TEST(FormatterTest, CustomFormat) { + EXPECT_EQ("42", format("{0}", Answer())); + EXPECT_EQ("0042", format("{:04}", Answer())); +} + +TEST(FormatterTest, CustomFormatTo) { + char buf[10] = {}; + auto end = &*fmt::format_to(fmt::detail::make_checked(buf, 10), "{}", Answer()); - EXPECT_EQ(end, buf + 2); - EXPECT_STREQ(buf, "42"); -} - -TEST(FormatterTest, WideFormatString) { - EXPECT_EQ(L"42", format(L"{}", 42)); - EXPECT_EQ(L"4.2", format(L"{}", 4.2)); - EXPECT_EQ(L"abc", format(L"{}", L"abc")); - EXPECT_EQ(L"z", format(L"{}", L'z')); + EXPECT_EQ(end, buf + 2); + EXPECT_STREQ(buf, "42"); +} + +TEST(FormatterTest, WideFormatString) { + EXPECT_EQ(L"42", format(L"{}", 42)); + EXPECT_EQ(L"4.2", format(L"{}", 4.2)); + EXPECT_EQ(L"abc", format(L"{}", L"abc")); + EXPECT_EQ(L"z", format(L"{}", L'z')); EXPECT_THROW(fmt::format(L"{:*\x343E}", 42), fmt::format_error); -} - -TEST(FormatterTest, FormatStringFromSpeedTest) { - EXPECT_EQ("1.2340000000:0042:+3.13:str:0x3e8:X:%", - format("{0:0.10f}:{1:04}:{2:+g}:{3}:{4}:{5}:%", 1.234, 42, 3.13, - "str", reinterpret_cast<void*>(1000), 'X')); -} - -TEST(FormatterTest, FormatExamples) { - std::string message = format("The answer is {}", 42); - EXPECT_EQ("The answer is 42", message); - - EXPECT_EQ("42", format("{}", 42)); - EXPECT_EQ("42", format(std::string("{}"), 42)); - - memory_buffer out; - format_to(out, "The answer is {}.", 42); - EXPECT_EQ("The answer is 42.", to_string(out)); - - const char* filename = "nonexistent"; - FILE* ftest = safe_fopen(filename, "r"); - if (ftest) fclose(ftest); - int error_code = errno; - EXPECT_TRUE(ftest == nullptr); - EXPECT_SYSTEM_ERROR( - { - FILE* f = safe_fopen(filename, "r"); - if (!f) - throw fmt::system_error(errno, "Cannot open file '{}'", filename); - fclose(f); - }, - error_code, "Cannot open file 'nonexistent'"); -} - -TEST(FormatterTest, Examples) { - EXPECT_EQ("First, thou shalt count to three", - format("First, thou shalt count to {0}", "three")); - EXPECT_EQ("Bring me a shrubbery", format("Bring me a {}", "shrubbery")); - EXPECT_EQ("From 1 to 3", format("From {} to {}", 1, 3)); - - char buffer[BUFFER_SIZE]; - safe_sprintf(buffer, "%03.2f", -1.2); - EXPECT_EQ(buffer, format("{:03.2f}", -1.2)); - - EXPECT_EQ("a, b, c", format("{0}, {1}, {2}", 'a', 'b', 'c')); - EXPECT_EQ("a, b, c", format("{}, {}, {}", 'a', 'b', 'c')); - EXPECT_EQ("c, b, a", format("{2}, {1}, {0}", 'a', 'b', 'c')); - EXPECT_EQ("abracadabra", format("{0}{1}{0}", "abra", "cad")); - - EXPECT_EQ("left aligned ", format("{:<30}", "left aligned")); - EXPECT_EQ(" right aligned", - format("{:>30}", "right aligned")); - EXPECT_EQ(" centered ", format("{:^30}", "centered")); - EXPECT_EQ("***********centered***********", format("{:*^30}", "centered")); - - EXPECT_EQ("+3.140000; -3.140000", format("{:+f}; {:+f}", 3.14, -3.14)); - EXPECT_EQ(" 3.140000; -3.140000", format("{: f}; {: f}", 3.14, -3.14)); - EXPECT_EQ("3.140000; -3.140000", format("{:-f}; {:-f}", 3.14, -3.14)); - - EXPECT_EQ("int: 42; hex: 2a; oct: 52", - format("int: {0:d}; hex: {0:x}; oct: {0:o}", 42)); - EXPECT_EQ("int: 42; hex: 0x2a; oct: 052", - format("int: {0:d}; hex: {0:#x}; oct: {0:#o}", 42)); - - EXPECT_EQ("The answer is 42", format("The answer is {}", 42)); - EXPECT_THROW_MSG(format("The answer is {:d}", "forty-two"), format_error, - "invalid type specifier"); - - EXPECT_EQ(L"Cyrillic letter \x42e", format(L"Cyrillic letter {}", L'\x42e')); - - EXPECT_WRITE( - stdout, fmt::print("{}", std::numeric_limits<double>::infinity()), "inf"); -} - -TEST(FormatIntTest, Data) { - fmt::format_int format_int(42); - EXPECT_EQ("42", std::string(format_int.data(), format_int.size())); -} - -TEST(FormatIntTest, FormatInt) { - EXPECT_EQ("42", fmt::format_int(42).str()); - EXPECT_EQ(2u, fmt::format_int(42).size()); - EXPECT_EQ("-42", fmt::format_int(-42).str()); - EXPECT_EQ(3u, fmt::format_int(-42).size()); - EXPECT_EQ("42", fmt::format_int(42ul).str()); - EXPECT_EQ("-42", fmt::format_int(-42l).str()); - EXPECT_EQ("42", fmt::format_int(42ull).str()); - EXPECT_EQ("-42", fmt::format_int(-42ll).str()); - std::ostringstream os; - os << max_value<int64_t>(); - EXPECT_EQ(os.str(), fmt::format_int(max_value<int64_t>()).str()); -} - -TEST(FormatTest, Print) { -#if FMT_USE_FCNTL - EXPECT_WRITE(stdout, fmt::print("Don't {}!", "panic"), "Don't panic!"); - EXPECT_WRITE(stderr, fmt::print(stderr, "Don't {}!", "panic"), - "Don't panic!"); -#endif - // Check that the wide print overload compiles. +} + +TEST(FormatterTest, FormatStringFromSpeedTest) { + EXPECT_EQ("1.2340000000:0042:+3.13:str:0x3e8:X:%", + format("{0:0.10f}:{1:04}:{2:+g}:{3}:{4}:{5}:%", 1.234, 42, 3.13, + "str", reinterpret_cast<void*>(1000), 'X')); +} + +TEST(FormatterTest, FormatExamples) { + std::string message = format("The answer is {}", 42); + EXPECT_EQ("The answer is 42", message); + + EXPECT_EQ("42", format("{}", 42)); + EXPECT_EQ("42", format(std::string("{}"), 42)); + + memory_buffer out; + format_to(out, "The answer is {}.", 42); + EXPECT_EQ("The answer is 42.", to_string(out)); + + const char* filename = "nonexistent"; + FILE* ftest = safe_fopen(filename, "r"); + if (ftest) fclose(ftest); + int error_code = errno; + EXPECT_TRUE(ftest == nullptr); + EXPECT_SYSTEM_ERROR( + { + FILE* f = safe_fopen(filename, "r"); + if (!f) + throw fmt::system_error(errno, "Cannot open file '{}'", filename); + fclose(f); + }, + error_code, "Cannot open file 'nonexistent'"); +} + +TEST(FormatterTest, Examples) { + EXPECT_EQ("First, thou shalt count to three", + format("First, thou shalt count to {0}", "three")); + EXPECT_EQ("Bring me a shrubbery", format("Bring me a {}", "shrubbery")); + EXPECT_EQ("From 1 to 3", format("From {} to {}", 1, 3)); + + char buffer[BUFFER_SIZE]; + safe_sprintf(buffer, "%03.2f", -1.2); + EXPECT_EQ(buffer, format("{:03.2f}", -1.2)); + + EXPECT_EQ("a, b, c", format("{0}, {1}, {2}", 'a', 'b', 'c')); + EXPECT_EQ("a, b, c", format("{}, {}, {}", 'a', 'b', 'c')); + EXPECT_EQ("c, b, a", format("{2}, {1}, {0}", 'a', 'b', 'c')); + EXPECT_EQ("abracadabra", format("{0}{1}{0}", "abra", "cad")); + + EXPECT_EQ("left aligned ", format("{:<30}", "left aligned")); + EXPECT_EQ(" right aligned", + format("{:>30}", "right aligned")); + EXPECT_EQ(" centered ", format("{:^30}", "centered")); + EXPECT_EQ("***********centered***********", format("{:*^30}", "centered")); + + EXPECT_EQ("+3.140000; -3.140000", format("{:+f}; {:+f}", 3.14, -3.14)); + EXPECT_EQ(" 3.140000; -3.140000", format("{: f}; {: f}", 3.14, -3.14)); + EXPECT_EQ("3.140000; -3.140000", format("{:-f}; {:-f}", 3.14, -3.14)); + + EXPECT_EQ("int: 42; hex: 2a; oct: 52", + format("int: {0:d}; hex: {0:x}; oct: {0:o}", 42)); + EXPECT_EQ("int: 42; hex: 0x2a; oct: 052", + format("int: {0:d}; hex: {0:#x}; oct: {0:#o}", 42)); + + EXPECT_EQ("The answer is 42", format("The answer is {}", 42)); + EXPECT_THROW_MSG(format("The answer is {:d}", "forty-two"), format_error, + "invalid type specifier"); + + EXPECT_EQ(L"Cyrillic letter \x42e", format(L"Cyrillic letter {}", L'\x42e')); + + EXPECT_WRITE( + stdout, fmt::print("{}", std::numeric_limits<double>::infinity()), "inf"); +} + +TEST(FormatIntTest, Data) { + fmt::format_int format_int(42); + EXPECT_EQ("42", std::string(format_int.data(), format_int.size())); +} + +TEST(FormatIntTest, FormatInt) { + EXPECT_EQ("42", fmt::format_int(42).str()); + EXPECT_EQ(2u, fmt::format_int(42).size()); + EXPECT_EQ("-42", fmt::format_int(-42).str()); + EXPECT_EQ(3u, fmt::format_int(-42).size()); + EXPECT_EQ("42", fmt::format_int(42ul).str()); + EXPECT_EQ("-42", fmt::format_int(-42l).str()); + EXPECT_EQ("42", fmt::format_int(42ull).str()); + EXPECT_EQ("-42", fmt::format_int(-42ll).str()); + std::ostringstream os; + os << max_value<int64_t>(); + EXPECT_EQ(os.str(), fmt::format_int(max_value<int64_t>()).str()); +} + +TEST(FormatTest, Print) { +#if FMT_USE_FCNTL + EXPECT_WRITE(stdout, fmt::print("Don't {}!", "panic"), "Don't panic!"); + EXPECT_WRITE(stderr, fmt::print(stderr, "Don't {}!", "panic"), + "Don't panic!"); +#endif + // Check that the wide print overload compiles. if (fmt::detail::const_check(false)) fmt::print(L"test"); -} - -TEST(FormatTest, Variadic) { - EXPECT_EQ("abc1", format("{}c{}", "ab", 1)); - EXPECT_EQ(L"abc1", format(L"{}c{}", L"ab", 1)); -} - -TEST(FormatTest, Dynamic) { - typedef fmt::format_context ctx; - std::vector<fmt::basic_format_arg<ctx>> args; +} + +TEST(FormatTest, Variadic) { + EXPECT_EQ("abc1", format("{}c{}", "ab", 1)); + EXPECT_EQ(L"abc1", format(L"{}c{}", L"ab", 1)); +} + +TEST(FormatTest, Dynamic) { + typedef fmt::format_context ctx; + std::vector<fmt::basic_format_arg<ctx>> args; args.emplace_back(fmt::detail::make_arg<ctx>(42)); args.emplace_back(fmt::detail::make_arg<ctx>("abc1")); args.emplace_back(fmt::detail::make_arg<ctx>(1.5f)); - - std::string result = fmt::vformat( - "{} and {} and {}", - fmt::basic_format_args<ctx>(args.data(), static_cast<int>(args.size()))); - - EXPECT_EQ("42 and abc1 and 1.5", result); -} - -TEST(FormatTest, Bytes) { - auto s = fmt::format("{:10}", fmt::bytes("ёжик")); - EXPECT_EQ("ёжик ", s); - EXPECT_EQ(10, s.size()); -} - -TEST(FormatTest, JoinArg) { - using fmt::join; - int v1[3] = {1, 2, 3}; - std::vector<float> v2; - v2.push_back(1.2f); - v2.push_back(3.4f); - void* v3[2] = {&v1[0], &v1[1]}; - - EXPECT_EQ("(1, 2, 3)", format("({})", join(v1, v1 + 3, ", "))); - EXPECT_EQ("(1)", format("({})", join(v1, v1 + 1, ", "))); - EXPECT_EQ("()", format("({})", join(v1, v1, ", "))); - EXPECT_EQ("(001, 002, 003)", format("({:03})", join(v1, v1 + 3, ", "))); - EXPECT_EQ("(+01.20, +03.40)", - format("({:+06.2f})", join(v2.begin(), v2.end(), ", "))); - - EXPECT_EQ(L"(1, 2, 3)", format(L"({})", join(v1, v1 + 3, L", "))); - EXPECT_EQ("1, 2, 3", format("{0:{1}}", join(v1, v1 + 3, ", "), 1)); - - EXPECT_EQ(format("{}, {}", v3[0], v3[1]), - format("{}", join(v3, v3 + 2, ", "))); - -#if !FMT_GCC_VERSION || FMT_GCC_VERSION >= 405 - EXPECT_EQ("(1, 2, 3)", format("({})", join(v1, ", "))); - EXPECT_EQ("(+01.20, +03.40)", format("({:+06.2f})", join(v2, ", "))); -#endif -} - -template <typename T> std::string str(const T& value) { - return fmt::format("{}", value); -} - -TEST(StrTest, Convert) { - EXPECT_EQ("42", str(42)); - std::string s = str(Date(2012, 12, 9)); - EXPECT_EQ("2012-12-9", s); -} - -std::string vformat_message(int id, const char* format, fmt::format_args args) { - fmt::memory_buffer buffer; - format_to(buffer, "[{}] ", id); - vformat_to(buffer, format, args); - return to_string(buffer); -} - -template <typename... Args> -std::string format_message(int id, const char* format, const Args&... args) { - auto va = fmt::make_format_args(args...); - return vformat_message(id, format, va); -} - -TEST(FormatTest, FormatMessageExample) { - EXPECT_EQ("[42] something happened", - format_message(42, "{} happened", "something")); -} - -template <typename... Args> -void print_error(const char* file, int line, const char* format, - const Args&... args) { - fmt::print("{}: {}: ", file, line); - fmt::print(format, args...); -} - -TEST(FormatTest, UnpackedArgs) { - EXPECT_EQ("0123456789abcdefg", - fmt::format("{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}", 0, 1, 2, 3, 4, 5, - 6, 7, 8, 9, 'a', 'b', 'c', 'd', 'e', 'f', 'g')); -} - -struct string_like {}; -fmt::string_view to_string_view(string_like) { return "foo"; } - -constexpr char with_null[3] = {'{', '}', '\0'}; -constexpr char no_null[2] = {'{', '}'}; - -TEST(FormatTest, CompileTimeString) { - EXPECT_EQ("42", fmt::format(FMT_STRING("{}"), 42)); - EXPECT_EQ(L"42", fmt::format(FMT_STRING(L"{}"), 42)); - EXPECT_EQ("foo", fmt::format(FMT_STRING("{}"), string_like())); - (void)with_null; - (void)no_null; -#if __cplusplus >= 201703L - EXPECT_EQ("42", fmt::format(FMT_STRING(with_null), 42)); - EXPECT_EQ("42", fmt::format(FMT_STRING(no_null), 42)); -#endif -#if defined(FMT_USE_STRING_VIEW) && __cplusplus >= 201703L - EXPECT_EQ("42", fmt::format(FMT_STRING(std::string_view("{}")), 42)); - EXPECT_EQ(L"42", fmt::format(FMT_STRING(std::wstring_view(L"{}")), 42)); -#endif -} - -TEST(FormatTest, CustomFormatCompileTimeString) { - EXPECT_EQ("42", fmt::format(FMT_STRING("{}"), Answer())); - Answer answer; - EXPECT_EQ("42", fmt::format(FMT_STRING("{}"), answer)); - char buf[10] = {}; - fmt::format_to(buf, FMT_STRING("{}"), answer); - const Answer const_answer = Answer(); - EXPECT_EQ("42", fmt::format(FMT_STRING("{}"), const_answer)); -} - -#if FMT_USE_USER_DEFINED_LITERALS -// Passing user-defined literals directly to EXPECT_EQ causes problems -// with macro argument stringification (#) on some versions of GCC. -// Workaround: Assing the UDL result to a variable before the macro. - -using namespace fmt::literals; - -TEST(LiteralsTest, Format) { - auto udl_format = "{}c{}"_format("ab", 1); - EXPECT_EQ(format("{}c{}", "ab", 1), udl_format); - auto udl_format_w = L"{}c{}"_format(L"ab", 1); - EXPECT_EQ(format(L"{}c{}", L"ab", 1), udl_format_w); -} - -TEST(LiteralsTest, NamedArg) { - auto udl_a = format("{first}{second}{first}{third}", "first"_a = "abra", - "second"_a = "cad", "third"_a = 99); - EXPECT_EQ(format("{first}{second}{first}{third}", fmt::arg("first", "abra"), - fmt::arg("second", "cad"), fmt::arg("third", 99)), - udl_a); - auto udl_a_w = format(L"{first}{second}{first}{third}", L"first"_a = L"abra", - L"second"_a = L"cad", L"third"_a = 99); - EXPECT_EQ( - format(L"{first}{second}{first}{third}", fmt::arg(L"first", L"abra"), - fmt::arg(L"second", L"cad"), fmt::arg(L"third", 99)), - udl_a_w); -} - -TEST(FormatTest, UdlTemplate) { - EXPECT_EQ("foo", "foo"_format()); - EXPECT_EQ(" 42", "{0:10}"_format(42)); -} - -TEST(FormatTest, UdlPassUserDefinedObjectAsLvalue) { - Date date(2015, 10, 21); - EXPECT_EQ("2015-10-21", "{}"_format(date)); -} -#endif // FMT_USE_USER_DEFINED_LITERALS - -enum TestEnum { A }; - -TEST(FormatTest, Enum) { EXPECT_EQ("0", fmt::format("{}", A)); } - -TEST(FormatTest, FormatterNotSpecialized) { - static_assert( - !fmt::has_formatter<fmt::formatter<TestEnum>, fmt::format_context>::value, - ""); -} - -#if FMT_HAS_FEATURE(cxx_strong_enums) -enum big_enum : unsigned long long { big_enum_value = 5000000000ULL }; - -TEST(FormatTest, StrongEnum) { - EXPECT_EQ("5000000000", fmt::format("{}", big_enum_value)); -} -#endif - -TEST(FormatTest, NonNullTerminatedFormatString) { - EXPECT_EQ("42", format(string_view("{}foo", 2), 42)); -} - -struct variant { - enum { INT, STRING } type; - explicit variant(int) : type(INT) {} - explicit variant(const char*) : type(STRING) {} -}; - -FMT_BEGIN_NAMESPACE -template <> struct formatter<variant> : dynamic_formatter<> { - auto format(variant value, format_context& ctx) -> decltype(ctx.out()) { - if (value.type == variant::INT) return dynamic_formatter<>::format(42, ctx); - return dynamic_formatter<>::format("foo", ctx); - } -}; -FMT_END_NAMESPACE - -TEST(FormatTest, DynamicFormatter) { - auto num = variant(42); - auto str = variant("foo"); - EXPECT_EQ("42", format("{:d}", num)); - EXPECT_EQ("foo", format("{:s}", str)); - EXPECT_EQ(" 42 foo ", format("{:{}} {:{}}", num, 3, str, 4)); - EXPECT_THROW_MSG(format("{0:{}}", num), format_error, - "cannot switch from manual to automatic argument indexing"); - EXPECT_THROW_MSG(format("{:{0}}", num), format_error, - "cannot switch from automatic to manual argument indexing"); + + std::string result = fmt::vformat( + "{} and {} and {}", + fmt::basic_format_args<ctx>(args.data(), static_cast<int>(args.size()))); + + EXPECT_EQ("42 and abc1 and 1.5", result); +} + +TEST(FormatTest, Bytes) { + auto s = fmt::format("{:10}", fmt::bytes("ёжик")); + EXPECT_EQ("ёжик ", s); + EXPECT_EQ(10, s.size()); +} + +TEST(FormatTest, JoinArg) { + using fmt::join; + int v1[3] = {1, 2, 3}; + std::vector<float> v2; + v2.push_back(1.2f); + v2.push_back(3.4f); + void* v3[2] = {&v1[0], &v1[1]}; + + EXPECT_EQ("(1, 2, 3)", format("({})", join(v1, v1 + 3, ", "))); + EXPECT_EQ("(1)", format("({})", join(v1, v1 + 1, ", "))); + EXPECT_EQ("()", format("({})", join(v1, v1, ", "))); + EXPECT_EQ("(001, 002, 003)", format("({:03})", join(v1, v1 + 3, ", "))); + EXPECT_EQ("(+01.20, +03.40)", + format("({:+06.2f})", join(v2.begin(), v2.end(), ", "))); + + EXPECT_EQ(L"(1, 2, 3)", format(L"({})", join(v1, v1 + 3, L", "))); + EXPECT_EQ("1, 2, 3", format("{0:{1}}", join(v1, v1 + 3, ", "), 1)); + + EXPECT_EQ(format("{}, {}", v3[0], v3[1]), + format("{}", join(v3, v3 + 2, ", "))); + +#if !FMT_GCC_VERSION || FMT_GCC_VERSION >= 405 + EXPECT_EQ("(1, 2, 3)", format("({})", join(v1, ", "))); + EXPECT_EQ("(+01.20, +03.40)", format("({:+06.2f})", join(v2, ", "))); +#endif +} + +template <typename T> std::string str(const T& value) { + return fmt::format("{}", value); +} + +TEST(StrTest, Convert) { + EXPECT_EQ("42", str(42)); + std::string s = str(Date(2012, 12, 9)); + EXPECT_EQ("2012-12-9", s); +} + +std::string vformat_message(int id, const char* format, fmt::format_args args) { + fmt::memory_buffer buffer; + format_to(buffer, "[{}] ", id); + vformat_to(buffer, format, args); + return to_string(buffer); +} + +template <typename... Args> +std::string format_message(int id, const char* format, const Args&... args) { + auto va = fmt::make_format_args(args...); + return vformat_message(id, format, va); +} + +TEST(FormatTest, FormatMessageExample) { + EXPECT_EQ("[42] something happened", + format_message(42, "{} happened", "something")); +} + +template <typename... Args> +void print_error(const char* file, int line, const char* format, + const Args&... args) { + fmt::print("{}: {}: ", file, line); + fmt::print(format, args...); +} + +TEST(FormatTest, UnpackedArgs) { + EXPECT_EQ("0123456789abcdefg", + fmt::format("{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}", 0, 1, 2, 3, 4, 5, + 6, 7, 8, 9, 'a', 'b', 'c', 'd', 'e', 'f', 'g')); +} + +struct string_like {}; +fmt::string_view to_string_view(string_like) { return "foo"; } + +constexpr char with_null[3] = {'{', '}', '\0'}; +constexpr char no_null[2] = {'{', '}'}; + +TEST(FormatTest, CompileTimeString) { + EXPECT_EQ("42", fmt::format(FMT_STRING("{}"), 42)); + EXPECT_EQ(L"42", fmt::format(FMT_STRING(L"{}"), 42)); + EXPECT_EQ("foo", fmt::format(FMT_STRING("{}"), string_like())); + (void)with_null; + (void)no_null; +#if __cplusplus >= 201703L + EXPECT_EQ("42", fmt::format(FMT_STRING(with_null), 42)); + EXPECT_EQ("42", fmt::format(FMT_STRING(no_null), 42)); +#endif +#if defined(FMT_USE_STRING_VIEW) && __cplusplus >= 201703L + EXPECT_EQ("42", fmt::format(FMT_STRING(std::string_view("{}")), 42)); + EXPECT_EQ(L"42", fmt::format(FMT_STRING(std::wstring_view(L"{}")), 42)); +#endif +} + +TEST(FormatTest, CustomFormatCompileTimeString) { + EXPECT_EQ("42", fmt::format(FMT_STRING("{}"), Answer())); + Answer answer; + EXPECT_EQ("42", fmt::format(FMT_STRING("{}"), answer)); + char buf[10] = {}; + fmt::format_to(buf, FMT_STRING("{}"), answer); + const Answer const_answer = Answer(); + EXPECT_EQ("42", fmt::format(FMT_STRING("{}"), const_answer)); +} + +#if FMT_USE_USER_DEFINED_LITERALS +// Passing user-defined literals directly to EXPECT_EQ causes problems +// with macro argument stringification (#) on some versions of GCC. +// Workaround: Assing the UDL result to a variable before the macro. + +using namespace fmt::literals; + +TEST(LiteralsTest, Format) { + auto udl_format = "{}c{}"_format("ab", 1); + EXPECT_EQ(format("{}c{}", "ab", 1), udl_format); + auto udl_format_w = L"{}c{}"_format(L"ab", 1); + EXPECT_EQ(format(L"{}c{}", L"ab", 1), udl_format_w); +} + +TEST(LiteralsTest, NamedArg) { + auto udl_a = format("{first}{second}{first}{third}", "first"_a = "abra", + "second"_a = "cad", "third"_a = 99); + EXPECT_EQ(format("{first}{second}{first}{third}", fmt::arg("first", "abra"), + fmt::arg("second", "cad"), fmt::arg("third", 99)), + udl_a); + auto udl_a_w = format(L"{first}{second}{first}{third}", L"first"_a = L"abra", + L"second"_a = L"cad", L"third"_a = 99); + EXPECT_EQ( + format(L"{first}{second}{first}{third}", fmt::arg(L"first", L"abra"), + fmt::arg(L"second", L"cad"), fmt::arg(L"third", 99)), + udl_a_w); +} + +TEST(FormatTest, UdlTemplate) { + EXPECT_EQ("foo", "foo"_format()); + EXPECT_EQ(" 42", "{0:10}"_format(42)); +} + +TEST(FormatTest, UdlPassUserDefinedObjectAsLvalue) { + Date date(2015, 10, 21); + EXPECT_EQ("2015-10-21", "{}"_format(date)); +} +#endif // FMT_USE_USER_DEFINED_LITERALS + +enum TestEnum { A }; + +TEST(FormatTest, Enum) { EXPECT_EQ("0", fmt::format("{}", A)); } + +TEST(FormatTest, FormatterNotSpecialized) { + static_assert( + !fmt::has_formatter<fmt::formatter<TestEnum>, fmt::format_context>::value, + ""); +} + +#if FMT_HAS_FEATURE(cxx_strong_enums) +enum big_enum : unsigned long long { big_enum_value = 5000000000ULL }; + +TEST(FormatTest, StrongEnum) { + EXPECT_EQ("5000000000", fmt::format("{}", big_enum_value)); +} +#endif + +TEST(FormatTest, NonNullTerminatedFormatString) { + EXPECT_EQ("42", format(string_view("{}foo", 2), 42)); +} + +struct variant { + enum { INT, STRING } type; + explicit variant(int) : type(INT) {} + explicit variant(const char*) : type(STRING) {} +}; + +FMT_BEGIN_NAMESPACE +template <> struct formatter<variant> : dynamic_formatter<> { + auto format(variant value, format_context& ctx) -> decltype(ctx.out()) { + if (value.type == variant::INT) return dynamic_formatter<>::format(42, ctx); + return dynamic_formatter<>::format("foo", ctx); + } +}; +FMT_END_NAMESPACE + +TEST(FormatTest, DynamicFormatter) { + auto num = variant(42); + auto str = variant("foo"); + EXPECT_EQ("42", format("{:d}", num)); + EXPECT_EQ("foo", format("{:s}", str)); + EXPECT_EQ(" 42 foo ", format("{:{}} {:{}}", num, 3, str, 4)); + EXPECT_THROW_MSG(format("{0:{}}", num), format_error, + "cannot switch from manual to automatic argument indexing"); + EXPECT_THROW_MSG(format("{:{0}}", num), format_error, + "cannot switch from automatic to manual argument indexing"); #if FMT_DEPRECATED_NUMERIC_ALIGN - EXPECT_THROW_MSG(format("{:=}", str), format_error, - "format specifier requires numeric argument"); -#endif - EXPECT_THROW_MSG(format("{:+}", str), format_error, - "format specifier requires numeric argument"); - EXPECT_THROW_MSG(format("{:-}", str), format_error, - "format specifier requires numeric argument"); - EXPECT_THROW_MSG(format("{: }", str), format_error, - "format specifier requires numeric argument"); - EXPECT_THROW_MSG(format("{:#}", str), format_error, - "format specifier requires numeric argument"); - EXPECT_THROW_MSG(format("{:0}", str), format_error, - "format specifier requires numeric argument"); - EXPECT_THROW_MSG(format("{:.2}", num), format_error, - "precision not allowed for this argument type"); -} - + EXPECT_THROW_MSG(format("{:=}", str), format_error, + "format specifier requires numeric argument"); +#endif + EXPECT_THROW_MSG(format("{:+}", str), format_error, + "format specifier requires numeric argument"); + EXPECT_THROW_MSG(format("{:-}", str), format_error, + "format specifier requires numeric argument"); + EXPECT_THROW_MSG(format("{: }", str), format_error, + "format specifier requires numeric argument"); + EXPECT_THROW_MSG(format("{:#}", str), format_error, + "format specifier requires numeric argument"); + EXPECT_THROW_MSG(format("{:0}", str), format_error, + "format specifier requires numeric argument"); + EXPECT_THROW_MSG(format("{:.2}", num), format_error, + "precision not allowed for this argument type"); +} + namespace adl_test { namespace fmt { namespace detail { @@ -1911,58 +1911,58 @@ struct formatter<adl_test::fmt::detail::foo> : formatter<std::string> { }; FMT_END_NAMESPACE -TEST(FormatTest, ToString) { - EXPECT_EQ("42", fmt::to_string(42)); - EXPECT_EQ("0x1234", fmt::to_string(reinterpret_cast<void*>(0x1234))); +TEST(FormatTest, ToString) { + EXPECT_EQ("42", fmt::to_string(42)); + EXPECT_EQ("0x1234", fmt::to_string(reinterpret_cast<void*>(0x1234))); EXPECT_EQ("foo", fmt::to_string(adl_test::fmt::detail::foo())); -} - -TEST(FormatTest, ToWString) { EXPECT_EQ(L"42", fmt::to_wstring(42)); } - -TEST(FormatTest, OutputIterators) { - std::list<char> out; - fmt::format_to(std::back_inserter(out), "{}", 42); - EXPECT_EQ("42", std::string(out.begin(), out.end())); - std::stringstream s; - fmt::format_to(std::ostream_iterator<char>(s), "{}", 42); - EXPECT_EQ("42", s.str()); -} - -TEST(FormatTest, FormattedSize) { - EXPECT_EQ(2u, fmt::formatted_size("{}", 42)); -} - +} + +TEST(FormatTest, ToWString) { EXPECT_EQ(L"42", fmt::to_wstring(42)); } + +TEST(FormatTest, OutputIterators) { + std::list<char> out; + fmt::format_to(std::back_inserter(out), "{}", 42); + EXPECT_EQ("42", std::string(out.begin(), out.end())); + std::stringstream s; + fmt::format_to(std::ostream_iterator<char>(s), "{}", 42); + EXPECT_EQ("42", s.str()); +} + +TEST(FormatTest, FormattedSize) { + EXPECT_EQ(2u, fmt::formatted_size("{}", 42)); +} + TEST(FormatTest, FormatTo) { std::vector<char> v; fmt::format_to(std::back_inserter(v), "{}", "foo"); EXPECT_EQ(string_view(v.data(), v.size()), "foo"); } -TEST(FormatTest, FormatToN) { - char buffer[4]; - buffer[3] = 'x'; - auto result = fmt::format_to_n(buffer, 3, "{}", 12345); - EXPECT_EQ(5u, result.size); - EXPECT_EQ(buffer + 3, result.out); - EXPECT_EQ("123x", fmt::string_view(buffer, 4)); - - result = fmt::format_to_n(buffer, 3, "{:s}", "foobar"); - EXPECT_EQ(6u, result.size); - EXPECT_EQ(buffer + 3, result.out); - EXPECT_EQ("foox", fmt::string_view(buffer, 4)); - - buffer[0] = 'x'; - buffer[1] = 'x'; - buffer[2] = 'x'; - result = fmt::format_to_n(buffer, 3, "{}", 'A'); - EXPECT_EQ(1u, result.size); - EXPECT_EQ(buffer + 1, result.out); - EXPECT_EQ("Axxx", fmt::string_view(buffer, 4)); - - result = fmt::format_to_n(buffer, 3, "{}{} ", 'B', 'C'); - EXPECT_EQ(3u, result.size); - EXPECT_EQ(buffer + 3, result.out); - EXPECT_EQ("BC x", fmt::string_view(buffer, 4)); +TEST(FormatTest, FormatToN) { + char buffer[4]; + buffer[3] = 'x'; + auto result = fmt::format_to_n(buffer, 3, "{}", 12345); + EXPECT_EQ(5u, result.size); + EXPECT_EQ(buffer + 3, result.out); + EXPECT_EQ("123x", fmt::string_view(buffer, 4)); + + result = fmt::format_to_n(buffer, 3, "{:s}", "foobar"); + EXPECT_EQ(6u, result.size); + EXPECT_EQ(buffer + 3, result.out); + EXPECT_EQ("foox", fmt::string_view(buffer, 4)); + + buffer[0] = 'x'; + buffer[1] = 'x'; + buffer[2] = 'x'; + result = fmt::format_to_n(buffer, 3, "{}", 'A'); + EXPECT_EQ(1u, result.size); + EXPECT_EQ(buffer + 1, result.out); + EXPECT_EQ("Axxx", fmt::string_view(buffer, 4)); + + result = fmt::format_to_n(buffer, 3, "{}{} ", 'B', 'C'); + EXPECT_EQ(3u, result.size); + EXPECT_EQ(buffer + 3, result.out); + EXPECT_EQ("BC x", fmt::string_view(buffer, 4)); result = fmt::format_to_n(buffer, 4, "{}", "ABCDE"); EXPECT_EQ(5u, result.size); @@ -1972,503 +1972,503 @@ TEST(FormatTest, FormatToN) { result = fmt::format_to_n(buffer, 3, "{}", std::string(1000, '*')); EXPECT_EQ(1000u, result.size); EXPECT_EQ("***x", fmt::string_view(buffer, 4)); -} - -TEST(FormatTest, WideFormatToN) { - wchar_t buffer[4]; - buffer[3] = L'x'; - auto result = fmt::format_to_n(buffer, 3, L"{}", 12345); - EXPECT_EQ(5u, result.size); - EXPECT_EQ(buffer + 3, result.out); - EXPECT_EQ(L"123x", fmt::wstring_view(buffer, 4)); - buffer[0] = L'x'; - buffer[1] = L'x'; - buffer[2] = L'x'; - result = fmt::format_to_n(buffer, 3, L"{}", L'A'); - EXPECT_EQ(1u, result.size); - EXPECT_EQ(buffer + 1, result.out); - EXPECT_EQ(L"Axxx", fmt::wstring_view(buffer, 4)); - result = fmt::format_to_n(buffer, 3, L"{}{} ", L'B', L'C'); - EXPECT_EQ(3u, result.size); - EXPECT_EQ(buffer + 3, result.out); - EXPECT_EQ(L"BC x", fmt::wstring_view(buffer, 4)); -} - -struct test_output_iterator { - char* data; - - using iterator_category = std::output_iterator_tag; - using value_type = void; - using difference_type = void; - using pointer = void; - using reference = void; - - test_output_iterator& operator++() { - ++data; - return *this; - } - test_output_iterator operator++(int) { - auto tmp = *this; - ++data; - return tmp; - } - char& operator*() { return *data; } -}; - -TEST(FormatTest, FormatToNOutputIterator) { - char buf[10] = {}; - fmt::format_to_n(test_output_iterator{buf}, 10, "{}", 42); - EXPECT_STREQ(buf, "42"); -} - -#if FMT_USE_CONSTEXPR -struct test_arg_id_handler { - enum result { NONE, EMPTY, INDEX, NAME, ERROR }; - result res = NONE; - int index = 0; - string_view name; - - FMT_CONSTEXPR void operator()() { res = EMPTY; } - - FMT_CONSTEXPR void operator()(int i) { - res = INDEX; - index = i; - } - - FMT_CONSTEXPR void operator()(string_view n) { - res = NAME; - name = n; - } - - FMT_CONSTEXPR void on_error(const char*) { res = ERROR; } -}; - -template <size_t N> -FMT_CONSTEXPR test_arg_id_handler parse_arg_id(const char (&s)[N]) { - test_arg_id_handler h; +} + +TEST(FormatTest, WideFormatToN) { + wchar_t buffer[4]; + buffer[3] = L'x'; + auto result = fmt::format_to_n(buffer, 3, L"{}", 12345); + EXPECT_EQ(5u, result.size); + EXPECT_EQ(buffer + 3, result.out); + EXPECT_EQ(L"123x", fmt::wstring_view(buffer, 4)); + buffer[0] = L'x'; + buffer[1] = L'x'; + buffer[2] = L'x'; + result = fmt::format_to_n(buffer, 3, L"{}", L'A'); + EXPECT_EQ(1u, result.size); + EXPECT_EQ(buffer + 1, result.out); + EXPECT_EQ(L"Axxx", fmt::wstring_view(buffer, 4)); + result = fmt::format_to_n(buffer, 3, L"{}{} ", L'B', L'C'); + EXPECT_EQ(3u, result.size); + EXPECT_EQ(buffer + 3, result.out); + EXPECT_EQ(L"BC x", fmt::wstring_view(buffer, 4)); +} + +struct test_output_iterator { + char* data; + + using iterator_category = std::output_iterator_tag; + using value_type = void; + using difference_type = void; + using pointer = void; + using reference = void; + + test_output_iterator& operator++() { + ++data; + return *this; + } + test_output_iterator operator++(int) { + auto tmp = *this; + ++data; + return tmp; + } + char& operator*() { return *data; } +}; + +TEST(FormatTest, FormatToNOutputIterator) { + char buf[10] = {}; + fmt::format_to_n(test_output_iterator{buf}, 10, "{}", 42); + EXPECT_STREQ(buf, "42"); +} + +#if FMT_USE_CONSTEXPR +struct test_arg_id_handler { + enum result { NONE, EMPTY, INDEX, NAME, ERROR }; + result res = NONE; + int index = 0; + string_view name; + + FMT_CONSTEXPR void operator()() { res = EMPTY; } + + FMT_CONSTEXPR void operator()(int i) { + res = INDEX; + index = i; + } + + FMT_CONSTEXPR void operator()(string_view n) { + res = NAME; + name = n; + } + + FMT_CONSTEXPR void on_error(const char*) { res = ERROR; } +}; + +template <size_t N> +FMT_CONSTEXPR test_arg_id_handler parse_arg_id(const char (&s)[N]) { + test_arg_id_handler h; fmt::detail::parse_arg_id(s, s + N, h); - return h; -} - -TEST(FormatTest, ConstexprParseArgID) { - static_assert(parse_arg_id(":").res == test_arg_id_handler::EMPTY, ""); - static_assert(parse_arg_id("}").res == test_arg_id_handler::EMPTY, ""); - static_assert(parse_arg_id("42:").res == test_arg_id_handler::INDEX, ""); - static_assert(parse_arg_id("42:").index == 42, ""); - static_assert(parse_arg_id("foo:").res == test_arg_id_handler::NAME, ""); - static_assert(parse_arg_id("foo:").name.size() == 3, ""); - static_assert(parse_arg_id("!").res == test_arg_id_handler::ERROR, ""); -} - -struct test_format_specs_handler { - enum Result { NONE, PLUS, MINUS, SPACE, HASH, ZERO, ERROR }; - Result res = NONE; - - fmt::align_t align = fmt::align::none; - char fill = 0; - int width = 0; + return h; +} + +TEST(FormatTest, ConstexprParseArgID) { + static_assert(parse_arg_id(":").res == test_arg_id_handler::EMPTY, ""); + static_assert(parse_arg_id("}").res == test_arg_id_handler::EMPTY, ""); + static_assert(parse_arg_id("42:").res == test_arg_id_handler::INDEX, ""); + static_assert(parse_arg_id("42:").index == 42, ""); + static_assert(parse_arg_id("foo:").res == test_arg_id_handler::NAME, ""); + static_assert(parse_arg_id("foo:").name.size() == 3, ""); + static_assert(parse_arg_id("!").res == test_arg_id_handler::ERROR, ""); +} + +struct test_format_specs_handler { + enum Result { NONE, PLUS, MINUS, SPACE, HASH, ZERO, ERROR }; + Result res = NONE; + + fmt::align_t align = fmt::align::none; + char fill = 0; + int width = 0; fmt::detail::arg_ref<char> width_ref; - int precision = 0; + int precision = 0; fmt::detail::arg_ref<char> precision_ref; - char type = 0; - - // Workaround for MSVC2017 bug that results in "expression did not evaluate - // to a constant" with compiler-generated copy ctor. - FMT_CONSTEXPR test_format_specs_handler() {} - FMT_CONSTEXPR test_format_specs_handler( - const test_format_specs_handler& other) - : res(other.res), - align(other.align), - fill(other.fill), - width(other.width), - width_ref(other.width_ref), - precision(other.precision), - precision_ref(other.precision_ref), - type(other.type) {} - - FMT_CONSTEXPR void on_align(fmt::align_t a) { align = a; } - FMT_CONSTEXPR void on_fill(fmt::string_view f) { fill = f[0]; } - FMT_CONSTEXPR void on_plus() { res = PLUS; } - FMT_CONSTEXPR void on_minus() { res = MINUS; } - FMT_CONSTEXPR void on_space() { res = SPACE; } - FMT_CONSTEXPR void on_hash() { res = HASH; } - FMT_CONSTEXPR void on_zero() { res = ZERO; } - - FMT_CONSTEXPR void on_width(int w) { width = w; } + char type = 0; + + // Workaround for MSVC2017 bug that results in "expression did not evaluate + // to a constant" with compiler-generated copy ctor. + FMT_CONSTEXPR test_format_specs_handler() {} + FMT_CONSTEXPR test_format_specs_handler( + const test_format_specs_handler& other) + : res(other.res), + align(other.align), + fill(other.fill), + width(other.width), + width_ref(other.width_ref), + precision(other.precision), + precision_ref(other.precision_ref), + type(other.type) {} + + FMT_CONSTEXPR void on_align(fmt::align_t a) { align = a; } + FMT_CONSTEXPR void on_fill(fmt::string_view f) { fill = f[0]; } + FMT_CONSTEXPR void on_plus() { res = PLUS; } + FMT_CONSTEXPR void on_minus() { res = MINUS; } + FMT_CONSTEXPR void on_space() { res = SPACE; } + FMT_CONSTEXPR void on_hash() { res = HASH; } + FMT_CONSTEXPR void on_zero() { res = ZERO; } + + FMT_CONSTEXPR void on_width(int w) { width = w; } FMT_CONSTEXPR void on_dynamic_width(fmt::detail::auto_id) {} - FMT_CONSTEXPR void on_dynamic_width(int index) { width_ref = index; } - FMT_CONSTEXPR void on_dynamic_width(string_view) {} - - FMT_CONSTEXPR void on_precision(int p) { precision = p; } + FMT_CONSTEXPR void on_dynamic_width(int index) { width_ref = index; } + FMT_CONSTEXPR void on_dynamic_width(string_view) {} + + FMT_CONSTEXPR void on_precision(int p) { precision = p; } FMT_CONSTEXPR void on_dynamic_precision(fmt::detail::auto_id) {} - FMT_CONSTEXPR void on_dynamic_precision(int index) { precision_ref = index; } - FMT_CONSTEXPR void on_dynamic_precision(string_view) {} - - FMT_CONSTEXPR void end_precision() {} - FMT_CONSTEXPR void on_type(char t) { type = t; } - FMT_CONSTEXPR void on_error(const char*) { res = ERROR; } -}; - -template <size_t N> -FMT_CONSTEXPR test_format_specs_handler parse_test_specs(const char (&s)[N]) { - test_format_specs_handler h; + FMT_CONSTEXPR void on_dynamic_precision(int index) { precision_ref = index; } + FMT_CONSTEXPR void on_dynamic_precision(string_view) {} + + FMT_CONSTEXPR void end_precision() {} + FMT_CONSTEXPR void on_type(char t) { type = t; } + FMT_CONSTEXPR void on_error(const char*) { res = ERROR; } +}; + +template <size_t N> +FMT_CONSTEXPR test_format_specs_handler parse_test_specs(const char (&s)[N]) { + test_format_specs_handler h; fmt::detail::parse_format_specs(s, s + N, h); - return h; -} - -TEST(FormatTest, ConstexprParseFormatSpecs) { - typedef test_format_specs_handler handler; - static_assert(parse_test_specs("<").align == fmt::align::left, ""); - static_assert(parse_test_specs("*^").fill == '*', ""); - static_assert(parse_test_specs("+").res == handler::PLUS, ""); - static_assert(parse_test_specs("-").res == handler::MINUS, ""); - static_assert(parse_test_specs(" ").res == handler::SPACE, ""); - static_assert(parse_test_specs("#").res == handler::HASH, ""); - static_assert(parse_test_specs("0").res == handler::ZERO, ""); - static_assert(parse_test_specs("42").width == 42, ""); - static_assert(parse_test_specs("{42}").width_ref.val.index == 42, ""); - static_assert(parse_test_specs(".42").precision == 42, ""); - static_assert(parse_test_specs(".{42}").precision_ref.val.index == 42, ""); - static_assert(parse_test_specs("d").type == 'd', ""); - static_assert(parse_test_specs("{<").res == handler::ERROR, ""); -} - -struct test_parse_context { - typedef char char_type; - - FMT_CONSTEXPR int next_arg_id() { return 11; } - template <typename Id> FMT_CONSTEXPR void check_arg_id(Id) {} - - FMT_CONSTEXPR const char* begin() { return nullptr; } - FMT_CONSTEXPR const char* end() { return nullptr; } - - void on_error(const char*) {} -}; - -struct test_context { - using char_type = char; - using format_arg = fmt::basic_format_arg<test_context>; - using parse_context_type = fmt::format_parse_context; - - template <typename T> struct formatter_type { - typedef fmt::formatter<T, char_type> type; - }; - - template <typename Id> - FMT_CONSTEXPR fmt::basic_format_arg<test_context> arg(Id id) { + return h; +} + +TEST(FormatTest, ConstexprParseFormatSpecs) { + typedef test_format_specs_handler handler; + static_assert(parse_test_specs("<").align == fmt::align::left, ""); + static_assert(parse_test_specs("*^").fill == '*', ""); + static_assert(parse_test_specs("+").res == handler::PLUS, ""); + static_assert(parse_test_specs("-").res == handler::MINUS, ""); + static_assert(parse_test_specs(" ").res == handler::SPACE, ""); + static_assert(parse_test_specs("#").res == handler::HASH, ""); + static_assert(parse_test_specs("0").res == handler::ZERO, ""); + static_assert(parse_test_specs("42").width == 42, ""); + static_assert(parse_test_specs("{42}").width_ref.val.index == 42, ""); + static_assert(parse_test_specs(".42").precision == 42, ""); + static_assert(parse_test_specs(".{42}").precision_ref.val.index == 42, ""); + static_assert(parse_test_specs("d").type == 'd', ""); + static_assert(parse_test_specs("{<").res == handler::ERROR, ""); +} + +struct test_parse_context { + typedef char char_type; + + FMT_CONSTEXPR int next_arg_id() { return 11; } + template <typename Id> FMT_CONSTEXPR void check_arg_id(Id) {} + + FMT_CONSTEXPR const char* begin() { return nullptr; } + FMT_CONSTEXPR const char* end() { return nullptr; } + + void on_error(const char*) {} +}; + +struct test_context { + using char_type = char; + using format_arg = fmt::basic_format_arg<test_context>; + using parse_context_type = fmt::format_parse_context; + + template <typename T> struct formatter_type { + typedef fmt::formatter<T, char_type> type; + }; + + template <typename Id> + FMT_CONSTEXPR fmt::basic_format_arg<test_context> arg(Id id) { return fmt::detail::make_arg<test_context>(id); - } - - void on_error(const char*) {} - - FMT_CONSTEXPR test_context error_handler() { return *this; } -}; - -template <size_t N> -FMT_CONSTEXPR fmt::format_specs parse_specs(const char (&s)[N]) { - auto specs = fmt::format_specs(); - auto parse_ctx = test_parse_context(); - auto ctx = test_context(); + } + + void on_error(const char*) {} + + FMT_CONSTEXPR test_context error_handler() { return *this; } +}; + +template <size_t N> +FMT_CONSTEXPR fmt::format_specs parse_specs(const char (&s)[N]) { + auto specs = fmt::format_specs(); + auto parse_ctx = test_parse_context(); + auto ctx = test_context(); fmt::detail::specs_handler<test_parse_context, test_context> h( - specs, parse_ctx, ctx); - parse_format_specs(s, s + N, h); - return specs; -} - -TEST(FormatTest, ConstexprSpecsHandler) { - static_assert(parse_specs("<").align == fmt::align::left, ""); - static_assert(parse_specs("*^").fill[0] == '*', ""); - static_assert(parse_specs("+").sign == fmt::sign::plus, ""); - static_assert(parse_specs("-").sign == fmt::sign::minus, ""); - static_assert(parse_specs(" ").sign == fmt::sign::space, ""); - static_assert(parse_specs("#").alt, ""); - static_assert(parse_specs("0").align == fmt::align::numeric, ""); - static_assert(parse_specs("42").width == 42, ""); - static_assert(parse_specs("{}").width == 11, ""); - static_assert(parse_specs("{22}").width == 22, ""); - static_assert(parse_specs(".42").precision == 42, ""); - static_assert(parse_specs(".{}").precision == 11, ""); - static_assert(parse_specs(".{22}").precision == 22, ""); - static_assert(parse_specs("d").type == 'd', ""); -} - -template <size_t N> + specs, parse_ctx, ctx); + parse_format_specs(s, s + N, h); + return specs; +} + +TEST(FormatTest, ConstexprSpecsHandler) { + static_assert(parse_specs("<").align == fmt::align::left, ""); + static_assert(parse_specs("*^").fill[0] == '*', ""); + static_assert(parse_specs("+").sign == fmt::sign::plus, ""); + static_assert(parse_specs("-").sign == fmt::sign::minus, ""); + static_assert(parse_specs(" ").sign == fmt::sign::space, ""); + static_assert(parse_specs("#").alt, ""); + static_assert(parse_specs("0").align == fmt::align::numeric, ""); + static_assert(parse_specs("42").width == 42, ""); + static_assert(parse_specs("{}").width == 11, ""); + static_assert(parse_specs("{22}").width == 22, ""); + static_assert(parse_specs(".42").precision == 42, ""); + static_assert(parse_specs(".{}").precision == 11, ""); + static_assert(parse_specs(".{22}").precision == 22, ""); + static_assert(parse_specs("d").type == 'd', ""); +} + +template <size_t N> FMT_CONSTEXPR fmt::detail::dynamic_format_specs<char> parse_dynamic_specs( - const char (&s)[N]) { + const char (&s)[N]) { fmt::detail::dynamic_format_specs<char> specs; - test_parse_context ctx{}; + test_parse_context ctx{}; fmt::detail::dynamic_specs_handler<test_parse_context> h(specs, ctx); - parse_format_specs(s, s + N, h); - return specs; -} - -TEST(FormatTest, ConstexprDynamicSpecsHandler) { - static_assert(parse_dynamic_specs("<").align == fmt::align::left, ""); - static_assert(parse_dynamic_specs("*^").fill[0] == '*', ""); - static_assert(parse_dynamic_specs("+").sign == fmt::sign::plus, ""); - static_assert(parse_dynamic_specs("-").sign == fmt::sign::minus, ""); - static_assert(parse_dynamic_specs(" ").sign == fmt::sign::space, ""); - static_assert(parse_dynamic_specs("#").alt, ""); - static_assert(parse_dynamic_specs("0").align == fmt::align::numeric, ""); - static_assert(parse_dynamic_specs("42").width == 42, ""); - static_assert(parse_dynamic_specs("{}").width_ref.val.index == 11, ""); - static_assert(parse_dynamic_specs("{42}").width_ref.val.index == 42, ""); - static_assert(parse_dynamic_specs(".42").precision == 42, ""); - static_assert(parse_dynamic_specs(".{}").precision_ref.val.index == 11, ""); - static_assert(parse_dynamic_specs(".{42}").precision_ref.val.index == 42, ""); - static_assert(parse_dynamic_specs("d").type == 'd', ""); -} - -template <size_t N> -FMT_CONSTEXPR test_format_specs_handler check_specs(const char (&s)[N]) { + parse_format_specs(s, s + N, h); + return specs; +} + +TEST(FormatTest, ConstexprDynamicSpecsHandler) { + static_assert(parse_dynamic_specs("<").align == fmt::align::left, ""); + static_assert(parse_dynamic_specs("*^").fill[0] == '*', ""); + static_assert(parse_dynamic_specs("+").sign == fmt::sign::plus, ""); + static_assert(parse_dynamic_specs("-").sign == fmt::sign::minus, ""); + static_assert(parse_dynamic_specs(" ").sign == fmt::sign::space, ""); + static_assert(parse_dynamic_specs("#").alt, ""); + static_assert(parse_dynamic_specs("0").align == fmt::align::numeric, ""); + static_assert(parse_dynamic_specs("42").width == 42, ""); + static_assert(parse_dynamic_specs("{}").width_ref.val.index == 11, ""); + static_assert(parse_dynamic_specs("{42}").width_ref.val.index == 42, ""); + static_assert(parse_dynamic_specs(".42").precision == 42, ""); + static_assert(parse_dynamic_specs(".{}").precision_ref.val.index == 11, ""); + static_assert(parse_dynamic_specs(".{42}").precision_ref.val.index == 42, ""); + static_assert(parse_dynamic_specs("d").type == 'd', ""); +} + +template <size_t N> +FMT_CONSTEXPR test_format_specs_handler check_specs(const char (&s)[N]) { fmt::detail::specs_checker<test_format_specs_handler> checker( test_format_specs_handler(), fmt::detail::type::double_type); - parse_format_specs(s, s + N, checker); - return checker; -} - -TEST(FormatTest, ConstexprSpecsChecker) { - typedef test_format_specs_handler handler; - static_assert(check_specs("<").align == fmt::align::left, ""); - static_assert(check_specs("*^").fill == '*', ""); - static_assert(check_specs("+").res == handler::PLUS, ""); - static_assert(check_specs("-").res == handler::MINUS, ""); - static_assert(check_specs(" ").res == handler::SPACE, ""); - static_assert(check_specs("#").res == handler::HASH, ""); - static_assert(check_specs("0").res == handler::ZERO, ""); - static_assert(check_specs("42").width == 42, ""); - static_assert(check_specs("{42}").width_ref.val.index == 42, ""); - static_assert(check_specs(".42").precision == 42, ""); - static_assert(check_specs(".{42}").precision_ref.val.index == 42, ""); - static_assert(check_specs("d").type == 'd', ""); - static_assert(check_specs("{<").res == handler::ERROR, ""); -} - -struct test_format_string_handler { - FMT_CONSTEXPR void on_text(const char*, const char*) {} - + parse_format_specs(s, s + N, checker); + return checker; +} + +TEST(FormatTest, ConstexprSpecsChecker) { + typedef test_format_specs_handler handler; + static_assert(check_specs("<").align == fmt::align::left, ""); + static_assert(check_specs("*^").fill == '*', ""); + static_assert(check_specs("+").res == handler::PLUS, ""); + static_assert(check_specs("-").res == handler::MINUS, ""); + static_assert(check_specs(" ").res == handler::SPACE, ""); + static_assert(check_specs("#").res == handler::HASH, ""); + static_assert(check_specs("0").res == handler::ZERO, ""); + static_assert(check_specs("42").width == 42, ""); + static_assert(check_specs("{42}").width_ref.val.index == 42, ""); + static_assert(check_specs(".42").precision == 42, ""); + static_assert(check_specs(".{42}").precision_ref.val.index == 42, ""); + static_assert(check_specs("d").type == 'd', ""); + static_assert(check_specs("{<").res == handler::ERROR, ""); +} + +struct test_format_string_handler { + FMT_CONSTEXPR void on_text(const char*, const char*) {} + FMT_CONSTEXPR int on_arg_id() { return 0; } - + template <typename T> FMT_CONSTEXPR int on_arg_id(T) { return 0; } - + FMT_CONSTEXPR void on_replacement_field(int, const char*) {} - + FMT_CONSTEXPR const char* on_format_specs(int, const char* begin, const char*) { - return begin; - } - - FMT_CONSTEXPR void on_error(const char*) { error = true; } - - bool error = false; -}; - -template <size_t N> FMT_CONSTEXPR bool parse_string(const char (&s)[N]) { - test_format_string_handler h; + return begin; + } + + FMT_CONSTEXPR void on_error(const char*) { error = true; } + + bool error = false; +}; + +template <size_t N> FMT_CONSTEXPR bool parse_string(const char (&s)[N]) { + test_format_string_handler h; fmt::detail::parse_format_string<true>(fmt::string_view(s, N - 1), h); - return !h.error; -} - -TEST(FormatTest, ConstexprParseFormatString) { - static_assert(parse_string("foo"), ""); - static_assert(!parse_string("}"), ""); - static_assert(parse_string("{}"), ""); - static_assert(parse_string("{42}"), ""); - static_assert(parse_string("{foo}"), ""); - static_assert(parse_string("{:}"), ""); -} - -struct test_error_handler { - const char*& error; - - FMT_CONSTEXPR test_error_handler(const char*& err) : error(err) {} - - FMT_CONSTEXPR test_error_handler(const test_error_handler& other) - : error(other.error) {} - - FMT_CONSTEXPR void on_error(const char* message) { - if (!error) error = message; - } -}; - -FMT_CONSTEXPR size_t len(const char* s) { - size_t len = 0; - while (*s++) ++len; - return len; -} - -FMT_CONSTEXPR bool equal(const char* s1, const char* s2) { - if (!s1 || !s2) return s1 == s2; - while (*s1 && *s1 == *s2) { - ++s1; - ++s2; - } - return *s1 == *s2; -} - -template <typename... Args> -FMT_CONSTEXPR bool test_error(const char* fmt, const char* expected_error) { - const char* actual_error = nullptr; + return !h.error; +} + +TEST(FormatTest, ConstexprParseFormatString) { + static_assert(parse_string("foo"), ""); + static_assert(!parse_string("}"), ""); + static_assert(parse_string("{}"), ""); + static_assert(parse_string("{42}"), ""); + static_assert(parse_string("{foo}"), ""); + static_assert(parse_string("{:}"), ""); +} + +struct test_error_handler { + const char*& error; + + FMT_CONSTEXPR test_error_handler(const char*& err) : error(err) {} + + FMT_CONSTEXPR test_error_handler(const test_error_handler& other) + : error(other.error) {} + + FMT_CONSTEXPR void on_error(const char* message) { + if (!error) error = message; + } +}; + +FMT_CONSTEXPR size_t len(const char* s) { + size_t len = 0; + while (*s++) ++len; + return len; +} + +FMT_CONSTEXPR bool equal(const char* s1, const char* s2) { + if (!s1 || !s2) return s1 == s2; + while (*s1 && *s1 == *s2) { + ++s1; + ++s2; + } + return *s1 == *s2; +} + +template <typename... Args> +FMT_CONSTEXPR bool test_error(const char* fmt, const char* expected_error) { + const char* actual_error = nullptr; string_view s(fmt, len(fmt)); fmt::detail::format_string_checker<char, test_error_handler, Args...> checker( s, test_error_handler(actual_error)); fmt::detail::parse_format_string<true>(s, checker); - return equal(actual_error, expected_error); -} - -# define EXPECT_ERROR_NOARGS(fmt, error) \ - static_assert(test_error(fmt, error), "") -# define EXPECT_ERROR(fmt, error, ...) \ - static_assert(test_error<__VA_ARGS__>(fmt, error), "") - -TEST(FormatTest, FormatStringErrors) { - EXPECT_ERROR_NOARGS("foo", nullptr); - EXPECT_ERROR_NOARGS("}", "unmatched '}' in format string"); - EXPECT_ERROR("{0:s", "unknown format specifier", Date); + return equal(actual_error, expected_error); +} + +# define EXPECT_ERROR_NOARGS(fmt, error) \ + static_assert(test_error(fmt, error), "") +# define EXPECT_ERROR(fmt, error, ...) \ + static_assert(test_error<__VA_ARGS__>(fmt, error), "") + +TEST(FormatTest, FormatStringErrors) { + EXPECT_ERROR_NOARGS("foo", nullptr); + EXPECT_ERROR_NOARGS("}", "unmatched '}' in format string"); + EXPECT_ERROR("{0:s", "unknown format specifier", Date); # if !FMT_MSC_VER || FMT_MSC_VER >= 1916 // This causes an detail compiler error in MSVC2017. - EXPECT_ERROR("{:{<}", "invalid fill character '{'", int); - EXPECT_ERROR("{:10000000000}", "number is too big", int); - EXPECT_ERROR("{:.10000000000}", "number is too big", int); + EXPECT_ERROR("{:{<}", "invalid fill character '{'", int); + EXPECT_ERROR("{:10000000000}", "number is too big", int); + EXPECT_ERROR("{:.10000000000}", "number is too big", int); EXPECT_ERROR_NOARGS("{:x}", "argument not found"); # if FMT_DEPRECATED_NUMERIC_ALIGN - EXPECT_ERROR("{0:=5", "unknown format specifier", int); - EXPECT_ERROR("{:=}", "format specifier requires numeric argument", - const char*); -# endif - EXPECT_ERROR("{:+}", "format specifier requires numeric argument", - const char*); - EXPECT_ERROR("{:-}", "format specifier requires numeric argument", - const char*); - EXPECT_ERROR("{:#}", "format specifier requires numeric argument", - const char*); - EXPECT_ERROR("{: }", "format specifier requires numeric argument", - const char*); - EXPECT_ERROR("{:0}", "format specifier requires numeric argument", - const char*); - EXPECT_ERROR("{:+}", "format specifier requires signed argument", unsigned); - EXPECT_ERROR("{:-}", "format specifier requires signed argument", unsigned); - EXPECT_ERROR("{: }", "format specifier requires signed argument", unsigned); + EXPECT_ERROR("{0:=5", "unknown format specifier", int); + EXPECT_ERROR("{:=}", "format specifier requires numeric argument", + const char*); +# endif + EXPECT_ERROR("{:+}", "format specifier requires numeric argument", + const char*); + EXPECT_ERROR("{:-}", "format specifier requires numeric argument", + const char*); + EXPECT_ERROR("{:#}", "format specifier requires numeric argument", + const char*); + EXPECT_ERROR("{: }", "format specifier requires numeric argument", + const char*); + EXPECT_ERROR("{:0}", "format specifier requires numeric argument", + const char*); + EXPECT_ERROR("{:+}", "format specifier requires signed argument", unsigned); + EXPECT_ERROR("{:-}", "format specifier requires signed argument", unsigned); + EXPECT_ERROR("{: }", "format specifier requires signed argument", unsigned); EXPECT_ERROR("{:{}}", "argument not found", int); EXPECT_ERROR("{:.{}}", "argument not found", double); - EXPECT_ERROR("{:.2}", "precision not allowed for this argument type", int); - EXPECT_ERROR("{:s}", "invalid type specifier", int); - EXPECT_ERROR("{:s}", "invalid type specifier", bool); - EXPECT_ERROR("{:s}", "invalid type specifier", char); - EXPECT_ERROR("{:+}", "invalid format specifier for char", char); - EXPECT_ERROR("{:s}", "invalid type specifier", double); - EXPECT_ERROR("{:d}", "invalid type specifier", const char*); - EXPECT_ERROR("{:d}", "invalid type specifier", std::string); - EXPECT_ERROR("{:s}", "invalid type specifier", void*); -# else - fmt::print("warning: constexpr is broken in this version of MSVC\n"); -# endif - EXPECT_ERROR("{foo", "compile-time checks don't support named arguments", - int); - EXPECT_ERROR_NOARGS("{10000000000}", "number is too big"); - EXPECT_ERROR_NOARGS("{0x}", "invalid format string"); - EXPECT_ERROR_NOARGS("{-}", "invalid format string"); - EXPECT_ERROR("{:{0x}}", "invalid format string", int); - EXPECT_ERROR("{:{-}}", "invalid format string", int); - EXPECT_ERROR("{:.{0x}}", "invalid format string", int); - EXPECT_ERROR("{:.{-}}", "invalid format string", int); - EXPECT_ERROR("{:.x}", "missing precision specifier", int); + EXPECT_ERROR("{:.2}", "precision not allowed for this argument type", int); + EXPECT_ERROR("{:s}", "invalid type specifier", int); + EXPECT_ERROR("{:s}", "invalid type specifier", bool); + EXPECT_ERROR("{:s}", "invalid type specifier", char); + EXPECT_ERROR("{:+}", "invalid format specifier for char", char); + EXPECT_ERROR("{:s}", "invalid type specifier", double); + EXPECT_ERROR("{:d}", "invalid type specifier", const char*); + EXPECT_ERROR("{:d}", "invalid type specifier", std::string); + EXPECT_ERROR("{:s}", "invalid type specifier", void*); +# else + fmt::print("warning: constexpr is broken in this version of MSVC\n"); +# endif + EXPECT_ERROR("{foo", "compile-time checks don't support named arguments", + int); + EXPECT_ERROR_NOARGS("{10000000000}", "number is too big"); + EXPECT_ERROR_NOARGS("{0x}", "invalid format string"); + EXPECT_ERROR_NOARGS("{-}", "invalid format string"); + EXPECT_ERROR("{:{0x}}", "invalid format string", int); + EXPECT_ERROR("{:{-}}", "invalid format string", int); + EXPECT_ERROR("{:.{0x}}", "invalid format string", int); + EXPECT_ERROR("{:.{-}}", "invalid format string", int); + EXPECT_ERROR("{:.x}", "missing precision specifier", int); EXPECT_ERROR_NOARGS("{}", "argument not found"); EXPECT_ERROR("{1}", "argument not found", int); - EXPECT_ERROR("{1}{}", - "cannot switch from manual to automatic argument indexing", int, - int); - EXPECT_ERROR("{}{1}", - "cannot switch from automatic to manual argument indexing", int, - int); -} - -TEST(FormatTest, VFormatTo) { - typedef fmt::format_context context; + EXPECT_ERROR("{1}{}", + "cannot switch from manual to automatic argument indexing", int, + int); + EXPECT_ERROR("{}{1}", + "cannot switch from automatic to manual argument indexing", int, + int); +} + +TEST(FormatTest, VFormatTo) { + typedef fmt::format_context context; fmt::basic_format_arg<context> arg = fmt::detail::make_arg<context>(42); - fmt::basic_format_args<context> args(&arg, 1); - std::string s; - fmt::vformat_to(std::back_inserter(s), "{}", args); - EXPECT_EQ("42", s); - s.clear(); - fmt::vformat_to(std::back_inserter(s), FMT_STRING("{}"), args); - EXPECT_EQ("42", s); - - typedef fmt::wformat_context wcontext; + fmt::basic_format_args<context> args(&arg, 1); + std::string s; + fmt::vformat_to(std::back_inserter(s), "{}", args); + EXPECT_EQ("42", s); + s.clear(); + fmt::vformat_to(std::back_inserter(s), FMT_STRING("{}"), args); + EXPECT_EQ("42", s); + + typedef fmt::wformat_context wcontext; fmt::basic_format_arg<wcontext> warg = fmt::detail::make_arg<wcontext>(42); - fmt::basic_format_args<wcontext> wargs(&warg, 1); - std::wstring w; - fmt::vformat_to(std::back_inserter(w), L"{}", wargs); - EXPECT_EQ(L"42", w); - w.clear(); - fmt::vformat_to(std::back_inserter(w), FMT_STRING(L"{}"), wargs); - EXPECT_EQ(L"42", w); -} - -template <typename T> static std::string FmtToString(const T& t) { - return fmt::format(FMT_STRING("{}"), t); -} - -TEST(FormatTest, FmtStringInTemplate) { - EXPECT_EQ(FmtToString(1), "1"); - EXPECT_EQ(FmtToString(0), "0"); -} - -#endif // FMT_USE_CONSTEXPR - -TEST(FormatTest, CharTraitsIsNotAmbiguous) { + fmt::basic_format_args<wcontext> wargs(&warg, 1); + std::wstring w; + fmt::vformat_to(std::back_inserter(w), L"{}", wargs); + EXPECT_EQ(L"42", w); + w.clear(); + fmt::vformat_to(std::back_inserter(w), FMT_STRING(L"{}"), wargs); + EXPECT_EQ(L"42", w); +} + +template <typename T> static std::string FmtToString(const T& t) { + return fmt::format(FMT_STRING("{}"), t); +} + +TEST(FormatTest, FmtStringInTemplate) { + EXPECT_EQ(FmtToString(1), "1"); + EXPECT_EQ(FmtToString(0), "0"); +} + +#endif // FMT_USE_CONSTEXPR + +TEST(FormatTest, CharTraitsIsNotAmbiguous) { // Test that we don't inject detail names into the std namespace. - using namespace std; - char_traits<char>::char_type c; - (void)c; -#if __cplusplus >= 201103L - std::string s; - auto lval = begin(s); - (void)lval; -#endif -} - + using namespace std; + char_traits<char>::char_type c; + (void)c; +#if __cplusplus >= 201103L + std::string s; + auto lval = begin(s); + (void)lval; +#endif +} + #if __cplusplus > 201103L struct custom_char { - int value; + int value; custom_char() = default; - + template <typename T> constexpr custom_char(T val) : value(static_cast<int>(val)) {} - - operator int() const { return value; } -}; - + + operator int() const { return value; } +}; + int to_ascii(custom_char c) { return c; } -FMT_BEGIN_NAMESPACE +FMT_BEGIN_NAMESPACE template <> struct is_char<custom_char> : std::true_type {}; -FMT_END_NAMESPACE - -TEST(FormatTest, FormatCustomChar) { +FMT_END_NAMESPACE + +TEST(FormatTest, FormatCustomChar) { const custom_char format[] = {'{', '}', 0}; auto result = fmt::format(format, custom_char('x')); - EXPECT_EQ(result.size(), 1); + EXPECT_EQ(result.size(), 1); EXPECT_EQ(result[0], custom_char('x')); -} +} #endif - -// Convert a char8_t string to std::string. Otherwise GTest will insist on -// inserting `char8_t` NTBS into a `char` stream which is disabled by P1423. -template <typename S> std::string from_u8str(const S& str) { - return std::string(str.begin(), str.end()); -} - -TEST(FormatTest, FormatUTF8Precision) { + +// Convert a char8_t string to std::string. Otherwise GTest will insist on +// inserting `char8_t` NTBS into a `char` stream which is disabled by P1423. +template <typename S> std::string from_u8str(const S& str) { + return std::string(str.begin(), str.end()); +} + +TEST(FormatTest, FormatUTF8Precision) { using str_type = std::basic_string<fmt::detail::char8_type>; str_type format(reinterpret_cast<const fmt::detail::char8_type*>(u8"{:.4}")); str_type str(reinterpret_cast<const fmt::detail::char8_type*>( - u8"caf\u00e9s")); // cafés - auto result = fmt::format(format, str); + u8"caf\u00e9s")); // cafés + auto result = fmt::format(format, str); EXPECT_EQ(fmt::detail::count_code_points(result), 4); - EXPECT_EQ(result.size(), 5); - EXPECT_EQ(from_u8str(result), from_u8str(str.substr(0, 5))); -} + EXPECT_EQ(result.size(), 5); + EXPECT_EQ(from_u8str(result), from_u8str(str.substr(0, 5))); +} struct check_back_appender {}; diff --git a/contrib/libs/fmt/test/format-test/ya.make b/contrib/libs/fmt/test/format-test/ya.make index 053554fddf..bc3d7c85c8 100644 --- a/contrib/libs/fmt/test/format-test/ya.make +++ b/contrib/libs/fmt/test/format-test/ya.make @@ -1,39 +1,39 @@ -# Generated by devtools/yamaker. - +# Generated by devtools/yamaker. + GTEST() - + WITHOUT_LICENSE_TEXTS() - + OWNER( orivej g:cpp-contrib ) -LICENSE(MIT) - -ALLOCATOR(J) - -PEERDIR( - contrib/libs/fmt - contrib/libs/fmt/test -) - -NO_COMPILER_WARNINGS() - -NO_UTIL() - -CFLAGS( - -DFMT_LOCALE - -DFMT_SHARED - -DGTEST_HAS_STD_WSTRING=1 - -DGTEST_LANG_CXX11=0 - -D_SILENCE_TR1_NAMESPACE_DEPRECATION_WARNING=1 -) - -SRCDIR(contrib/libs/fmt/test) - -SRCS( - format-test.cc -) - -END() +LICENSE(MIT) + +ALLOCATOR(J) + +PEERDIR( + contrib/libs/fmt + contrib/libs/fmt/test +) + +NO_COMPILER_WARNINGS() + +NO_UTIL() + +CFLAGS( + -DFMT_LOCALE + -DFMT_SHARED + -DGTEST_HAS_STD_WSTRING=1 + -DGTEST_LANG_CXX11=0 + -D_SILENCE_TR1_NAMESPACE_DEPRECATION_WARNING=1 +) + +SRCDIR(contrib/libs/fmt/test) + +SRCS( + format-test.cc +) + +END() diff --git a/contrib/libs/fmt/test/gtest-extra-test.cc b/contrib/libs/fmt/test/gtest-extra-test.cc index 80b3007748..ea728607e8 100644 --- a/contrib/libs/fmt/test/gtest-extra-test.cc +++ b/contrib/libs/fmt/test/gtest-extra-test.cc @@ -1,173 +1,173 @@ -// Formatting library for C++ - tests of custom Google Test assertions -// -// Copyright (c) 2012 - present, Victor Zverovich -// All rights reserved. -// -// For the license information refer to format.h. - -#include "gtest-extra.h" - -#include <gtest/gtest-spi.h> - -#include <algorithm> -#include <cstring> -#include <memory> -#include <stdexcept> - -#if defined(_WIN32) && !defined(__MINGW32__) -# include <crtdbg.h> // for _CrtSetReportMode -#endif // _WIN32 - -#include "util.h" - -namespace { - -// This is used to suppress coverity warnings about untrusted values. -std::string sanitize(const std::string& s) { - std::string result; - for (std::string::const_iterator i = s.begin(), end = s.end(); i != end; ++i) - result.push_back(static_cast<char>(*i & 0xff)); - return result; -} - -// Tests that assertion macros evaluate their arguments exactly once. -class SingleEvaluationTest : public ::testing::Test { - protected: - SingleEvaluationTest() { - p_ = s_; - a_ = 0; - b_ = 0; - } - - static const char* const s_; - static const char* p_; - - static int a_; - static int b_; -}; - -const char* const SingleEvaluationTest::s_ = "01234"; -const char* SingleEvaluationTest::p_; -int SingleEvaluationTest::a_; -int SingleEvaluationTest::b_; - -void do_nothing() {} - -FMT_NORETURN void throw_exception() { throw std::runtime_error("test"); } - -FMT_NORETURN void throw_system_error() { - throw fmt::system_error(EDOM, "test"); -} - -// Tests that when EXPECT_THROW_MSG fails, it evaluates its message argument -// exactly once. -TEST_F(SingleEvaluationTest, FailedEXPECT_THROW_MSG) { - EXPECT_NONFATAL_FAILURE( - EXPECT_THROW_MSG(throw_exception(), std::exception, p_++), "01234"); - EXPECT_EQ(s_ + 1, p_); -} - -// Tests that when EXPECT_SYSTEM_ERROR fails, it evaluates its message argument -// exactly once. -TEST_F(SingleEvaluationTest, FailedEXPECT_SYSTEM_ERROR) { - EXPECT_NONFATAL_FAILURE(EXPECT_SYSTEM_ERROR(throw_system_error(), EDOM, p_++), - "01234"); - EXPECT_EQ(s_ + 1, p_); -} - -// Tests that assertion arguments are evaluated exactly once. -TEST_F(SingleEvaluationTest, ExceptionTests) { - // successful EXPECT_THROW_MSG - EXPECT_THROW_MSG( - { // NOLINT - a_++; - throw_exception(); - }, - std::exception, (b_++, "test")); - EXPECT_EQ(1, a_); - EXPECT_EQ(1, b_); - - // failed EXPECT_THROW_MSG, throws different type - EXPECT_NONFATAL_FAILURE(EXPECT_THROW_MSG( - { // NOLINT - a_++; - throw_exception(); - }, - std::logic_error, (b_++, "test")), - "throws a different type"); - EXPECT_EQ(2, a_); - EXPECT_EQ(2, b_); - - // failed EXPECT_THROW_MSG, throws an exception with different message - EXPECT_NONFATAL_FAILURE(EXPECT_THROW_MSG( - { // NOLINT - a_++; - throw_exception(); - }, - std::exception, (b_++, "other")), - "throws an exception with a different message"); - EXPECT_EQ(3, a_); - EXPECT_EQ(3, b_); - - // failed EXPECT_THROW_MSG, throws nothing - EXPECT_NONFATAL_FAILURE( - EXPECT_THROW_MSG(a_++, std::exception, (b_++, "test")), "throws nothing"); - EXPECT_EQ(4, a_); - EXPECT_EQ(4, b_); -} - -TEST_F(SingleEvaluationTest, SystemErrorTests) { - // successful EXPECT_SYSTEM_ERROR - EXPECT_SYSTEM_ERROR( - { // NOLINT - a_++; - throw_system_error(); - }, - EDOM, (b_++, "test")); - EXPECT_EQ(1, a_); - EXPECT_EQ(1, b_); - - // failed EXPECT_SYSTEM_ERROR, throws different type - EXPECT_NONFATAL_FAILURE(EXPECT_SYSTEM_ERROR( - { // NOLINT - a_++; - throw_exception(); - }, - EDOM, (b_++, "test")), - "throws a different type"); - EXPECT_EQ(2, a_); - EXPECT_EQ(2, b_); - - // failed EXPECT_SYSTEM_ERROR, throws an exception with different message - EXPECT_NONFATAL_FAILURE(EXPECT_SYSTEM_ERROR( - { // NOLINT - a_++; - throw_system_error(); - }, - EDOM, (b_++, "other")), - "throws an exception with a different message"); - EXPECT_EQ(3, a_); - EXPECT_EQ(3, b_); - - // failed EXPECT_SYSTEM_ERROR, throws nothing - EXPECT_NONFATAL_FAILURE(EXPECT_SYSTEM_ERROR(a_++, EDOM, (b_++, "test")), - "throws nothing"); - EXPECT_EQ(4, a_); - EXPECT_EQ(4, b_); -} - -#if FMT_USE_FCNTL -// Tests that when EXPECT_WRITE fails, it evaluates its message argument -// exactly once. -TEST_F(SingleEvaluationTest, FailedEXPECT_WRITE) { - EXPECT_NONFATAL_FAILURE(EXPECT_WRITE(stdout, std::printf("test"), p_++), - "01234"); - EXPECT_EQ(s_ + 1, p_); -} - -// Tests that assertion arguments are evaluated exactly once. -TEST_F(SingleEvaluationTest, WriteTests) { - // successful EXPECT_WRITE +// Formatting library for C++ - tests of custom Google Test assertions +// +// Copyright (c) 2012 - present, Victor Zverovich +// All rights reserved. +// +// For the license information refer to format.h. + +#include "gtest-extra.h" + +#include <gtest/gtest-spi.h> + +#include <algorithm> +#include <cstring> +#include <memory> +#include <stdexcept> + +#if defined(_WIN32) && !defined(__MINGW32__) +# include <crtdbg.h> // for _CrtSetReportMode +#endif // _WIN32 + +#include "util.h" + +namespace { + +// This is used to suppress coverity warnings about untrusted values. +std::string sanitize(const std::string& s) { + std::string result; + for (std::string::const_iterator i = s.begin(), end = s.end(); i != end; ++i) + result.push_back(static_cast<char>(*i & 0xff)); + return result; +} + +// Tests that assertion macros evaluate their arguments exactly once. +class SingleEvaluationTest : public ::testing::Test { + protected: + SingleEvaluationTest() { + p_ = s_; + a_ = 0; + b_ = 0; + } + + static const char* const s_; + static const char* p_; + + static int a_; + static int b_; +}; + +const char* const SingleEvaluationTest::s_ = "01234"; +const char* SingleEvaluationTest::p_; +int SingleEvaluationTest::a_; +int SingleEvaluationTest::b_; + +void do_nothing() {} + +FMT_NORETURN void throw_exception() { throw std::runtime_error("test"); } + +FMT_NORETURN void throw_system_error() { + throw fmt::system_error(EDOM, "test"); +} + +// Tests that when EXPECT_THROW_MSG fails, it evaluates its message argument +// exactly once. +TEST_F(SingleEvaluationTest, FailedEXPECT_THROW_MSG) { + EXPECT_NONFATAL_FAILURE( + EXPECT_THROW_MSG(throw_exception(), std::exception, p_++), "01234"); + EXPECT_EQ(s_ + 1, p_); +} + +// Tests that when EXPECT_SYSTEM_ERROR fails, it evaluates its message argument +// exactly once. +TEST_F(SingleEvaluationTest, FailedEXPECT_SYSTEM_ERROR) { + EXPECT_NONFATAL_FAILURE(EXPECT_SYSTEM_ERROR(throw_system_error(), EDOM, p_++), + "01234"); + EXPECT_EQ(s_ + 1, p_); +} + +// Tests that assertion arguments are evaluated exactly once. +TEST_F(SingleEvaluationTest, ExceptionTests) { + // successful EXPECT_THROW_MSG + EXPECT_THROW_MSG( + { // NOLINT + a_++; + throw_exception(); + }, + std::exception, (b_++, "test")); + EXPECT_EQ(1, a_); + EXPECT_EQ(1, b_); + + // failed EXPECT_THROW_MSG, throws different type + EXPECT_NONFATAL_FAILURE(EXPECT_THROW_MSG( + { // NOLINT + a_++; + throw_exception(); + }, + std::logic_error, (b_++, "test")), + "throws a different type"); + EXPECT_EQ(2, a_); + EXPECT_EQ(2, b_); + + // failed EXPECT_THROW_MSG, throws an exception with different message + EXPECT_NONFATAL_FAILURE(EXPECT_THROW_MSG( + { // NOLINT + a_++; + throw_exception(); + }, + std::exception, (b_++, "other")), + "throws an exception with a different message"); + EXPECT_EQ(3, a_); + EXPECT_EQ(3, b_); + + // failed EXPECT_THROW_MSG, throws nothing + EXPECT_NONFATAL_FAILURE( + EXPECT_THROW_MSG(a_++, std::exception, (b_++, "test")), "throws nothing"); + EXPECT_EQ(4, a_); + EXPECT_EQ(4, b_); +} + +TEST_F(SingleEvaluationTest, SystemErrorTests) { + // successful EXPECT_SYSTEM_ERROR + EXPECT_SYSTEM_ERROR( + { // NOLINT + a_++; + throw_system_error(); + }, + EDOM, (b_++, "test")); + EXPECT_EQ(1, a_); + EXPECT_EQ(1, b_); + + // failed EXPECT_SYSTEM_ERROR, throws different type + EXPECT_NONFATAL_FAILURE(EXPECT_SYSTEM_ERROR( + { // NOLINT + a_++; + throw_exception(); + }, + EDOM, (b_++, "test")), + "throws a different type"); + EXPECT_EQ(2, a_); + EXPECT_EQ(2, b_); + + // failed EXPECT_SYSTEM_ERROR, throws an exception with different message + EXPECT_NONFATAL_FAILURE(EXPECT_SYSTEM_ERROR( + { // NOLINT + a_++; + throw_system_error(); + }, + EDOM, (b_++, "other")), + "throws an exception with a different message"); + EXPECT_EQ(3, a_); + EXPECT_EQ(3, b_); + + // failed EXPECT_SYSTEM_ERROR, throws nothing + EXPECT_NONFATAL_FAILURE(EXPECT_SYSTEM_ERROR(a_++, EDOM, (b_++, "test")), + "throws nothing"); + EXPECT_EQ(4, a_); + EXPECT_EQ(4, b_); +} + +#if FMT_USE_FCNTL +// Tests that when EXPECT_WRITE fails, it evaluates its message argument +// exactly once. +TEST_F(SingleEvaluationTest, FailedEXPECT_WRITE) { + EXPECT_NONFATAL_FAILURE(EXPECT_WRITE(stdout, std::printf("test"), p_++), + "01234"); + EXPECT_EQ(s_ + 1, p_); +} + +// Tests that assertion arguments are evaluated exactly once. +TEST_F(SingleEvaluationTest, WriteTests) { + // successful EXPECT_WRITE EXPECT_WRITE( stdout, { // NOLINT @@ -175,10 +175,10 @@ TEST_F(SingleEvaluationTest, WriteTests) { std::printf("test"); }, (b_++, "test")); - EXPECT_EQ(1, a_); - EXPECT_EQ(1, b_); - - // failed EXPECT_WRITE + EXPECT_EQ(1, a_); + EXPECT_EQ(1, b_); + + // failed EXPECT_WRITE EXPECT_NONFATAL_FAILURE(EXPECT_WRITE( stdout, { // NOLINT @@ -186,240 +186,240 @@ TEST_F(SingleEvaluationTest, WriteTests) { std::printf("test"); }, (b_++, "other")), - "Actual: test"); - EXPECT_EQ(2, a_); - EXPECT_EQ(2, b_); -} - -// Tests EXPECT_WRITE. -TEST(ExpectTest, EXPECT_WRITE) { - EXPECT_WRITE(stdout, do_nothing(), ""); - EXPECT_WRITE(stdout, std::printf("test"), "test"); - EXPECT_WRITE(stderr, std::fprintf(stderr, "test"), "test"); - EXPECT_NONFATAL_FAILURE(EXPECT_WRITE(stdout, std::printf("that"), "this"), - "Expected: this\n" - " Actual: that"); -} - -TEST(StreamingAssertionsTest, EXPECT_WRITE) { - EXPECT_WRITE(stdout, std::printf("test"), "test") << "unexpected failure"; - EXPECT_NONFATAL_FAILURE(EXPECT_WRITE(stdout, std::printf("test"), "other") - << "expected failure", - "expected failure"); -} -#endif // FMT_USE_FCNTL - -// Tests that the compiler will not complain about unreachable code in the -// EXPECT_THROW_MSG macro. -TEST(ExpectThrowTest, DoesNotGenerateUnreachableCodeWarning) { - int n = 0; - using std::runtime_error; - EXPECT_THROW_MSG(throw runtime_error(""), runtime_error, ""); - EXPECT_NONFATAL_FAILURE(EXPECT_THROW_MSG(n++, runtime_error, ""), ""); - EXPECT_NONFATAL_FAILURE(EXPECT_THROW_MSG(throw 1, runtime_error, ""), ""); - EXPECT_NONFATAL_FAILURE( - EXPECT_THROW_MSG(throw runtime_error("a"), runtime_error, "b"), ""); -} - -// Tests that the compiler will not complain about unreachable code in the -// EXPECT_SYSTEM_ERROR macro. -TEST(ExpectSystemErrorTest, DoesNotGenerateUnreachableCodeWarning) { - int n = 0; - EXPECT_SYSTEM_ERROR(throw fmt::system_error(EDOM, "test"), EDOM, "test"); - EXPECT_NONFATAL_FAILURE(EXPECT_SYSTEM_ERROR(n++, EDOM, ""), ""); - EXPECT_NONFATAL_FAILURE(EXPECT_SYSTEM_ERROR(throw 1, EDOM, ""), ""); - EXPECT_NONFATAL_FAILURE( - EXPECT_SYSTEM_ERROR(throw fmt::system_error(EDOM, "aaa"), EDOM, "bbb"), - ""); -} - -TEST(AssertionSyntaxTest, ExceptionAssertionBehavesLikeSingleStatement) { - if (::testing::internal::AlwaysFalse()) - EXPECT_THROW_MSG(do_nothing(), std::exception, ""); - - if (::testing::internal::AlwaysTrue()) - EXPECT_THROW_MSG(throw_exception(), std::exception, "test"); - else - do_nothing(); -} - -TEST(AssertionSyntaxTest, SystemErrorAssertionBehavesLikeSingleStatement) { - if (::testing::internal::AlwaysFalse()) - EXPECT_SYSTEM_ERROR(do_nothing(), EDOM, ""); - - if (::testing::internal::AlwaysTrue()) - EXPECT_SYSTEM_ERROR(throw_system_error(), EDOM, "test"); - else - do_nothing(); -} - -TEST(AssertionSyntaxTest, WriteAssertionBehavesLikeSingleStatement) { - if (::testing::internal::AlwaysFalse()) - EXPECT_WRITE(stdout, std::printf("x"), "x"); - - if (::testing::internal::AlwaysTrue()) - EXPECT_WRITE(stdout, std::printf("x"), "x"); - else - do_nothing(); -} - -// Tests EXPECT_THROW_MSG. -TEST(ExpectTest, EXPECT_THROW_MSG) { - EXPECT_THROW_MSG(throw_exception(), std::exception, "test"); - EXPECT_NONFATAL_FAILURE( - EXPECT_THROW_MSG(throw_exception(), std::logic_error, "test"), - "Expected: throw_exception() throws an exception of " - "type std::logic_error.\n Actual: it throws a different type."); - EXPECT_NONFATAL_FAILURE( - EXPECT_THROW_MSG(do_nothing(), std::exception, "test"), - "Expected: do_nothing() throws an exception of type std::exception.\n" - " Actual: it throws nothing."); - EXPECT_NONFATAL_FAILURE( - EXPECT_THROW_MSG(throw_exception(), std::exception, "other"), - "throw_exception() throws an exception with a different message.\n" - "Expected: other\n" - " Actual: test"); -} - -// Tests EXPECT_SYSTEM_ERROR. -TEST(ExpectTest, EXPECT_SYSTEM_ERROR) { - EXPECT_SYSTEM_ERROR(throw_system_error(), EDOM, "test"); - EXPECT_NONFATAL_FAILURE( - EXPECT_SYSTEM_ERROR(throw_exception(), EDOM, "test"), - "Expected: throw_exception() throws an exception of " - "type fmt::system_error.\n Actual: it throws a different type."); - EXPECT_NONFATAL_FAILURE( - EXPECT_SYSTEM_ERROR(do_nothing(), EDOM, "test"), - "Expected: do_nothing() throws an exception of type fmt::system_error.\n" - " Actual: it throws nothing."); - EXPECT_NONFATAL_FAILURE( - EXPECT_SYSTEM_ERROR(throw_system_error(), EDOM, "other"), - fmt::format( - "throw_system_error() throws an exception with a different message.\n" - "Expected: {}\n" - " Actual: {}", - format_system_error(EDOM, "other"), - format_system_error(EDOM, "test"))); -} - -TEST(StreamingAssertionsTest, EXPECT_THROW_MSG) { - EXPECT_THROW_MSG(throw_exception(), std::exception, "test") - << "unexpected failure"; - EXPECT_NONFATAL_FAILURE( - EXPECT_THROW_MSG(throw_exception(), std::exception, "other") - << "expected failure", - "expected failure"); -} - -TEST(StreamingAssertionsTest, EXPECT_SYSTEM_ERROR) { - EXPECT_SYSTEM_ERROR(throw_system_error(), EDOM, "test") - << "unexpected failure"; - EXPECT_NONFATAL_FAILURE( - EXPECT_SYSTEM_ERROR(throw_system_error(), EDOM, "other") - << "expected failure", - "expected failure"); -} - -TEST(UtilTest, FormatSystemError) { - fmt::memory_buffer out; - fmt::format_system_error(out, EDOM, "test message"); - EXPECT_EQ(to_string(out), format_system_error(EDOM, "test message")); -} - -#if FMT_USE_FCNTL - -using fmt::buffered_file; -using fmt::error_code; -using fmt::file; - -TEST(ErrorCodeTest, Ctor) { - EXPECT_EQ(error_code().get(), 0); - EXPECT_EQ(error_code(42).get(), 42); -} - -TEST(OutputRedirectTest, ScopedRedirect) { - file read_end, write_end; - file::pipe(read_end, write_end); - { - buffered_file file(write_end.fdopen("w")); - std::fprintf(file.get(), "[[["); - { - OutputRedirect redir(file.get()); - std::fprintf(file.get(), "censored"); - } - std::fprintf(file.get(), "]]]"); - } - EXPECT_READ(read_end, "[[[]]]"); -} - -// Test that OutputRedirect handles errors in flush correctly. -TEST(OutputRedirectTest, FlushErrorInCtor) { - file read_end, write_end; - file::pipe(read_end, write_end); - int write_fd = write_end.descriptor(); - file write_copy = write_end.dup(write_fd); - buffered_file f = write_end.fdopen("w"); - // Put a character in a file buffer. - EXPECT_EQ('x', fputc('x', f.get())); - FMT_POSIX(close(write_fd)); - std::unique_ptr<OutputRedirect> redir{nullptr}; - EXPECT_SYSTEM_ERROR_NOASSERT(redir.reset(new OutputRedirect(f.get())), EBADF, - "cannot flush stream"); - redir.reset(nullptr); - write_copy.dup2(write_fd); // "undo" close or dtor will fail -} - -TEST(OutputRedirectTest, DupErrorInCtor) { - buffered_file f = open_buffered_file(); - int fd = (f.fileno)(); - file copy = file::dup(fd); - FMT_POSIX(close(fd)); - std::unique_ptr<OutputRedirect> redir{nullptr}; - EXPECT_SYSTEM_ERROR_NOASSERT( - redir.reset(new OutputRedirect(f.get())), EBADF, - fmt::format("cannot duplicate file descriptor {}", fd)); - copy.dup2(fd); // "undo" close or dtor will fail -} - -TEST(OutputRedirectTest, RestoreAndRead) { - file read_end, write_end; - file::pipe(read_end, write_end); - buffered_file file(write_end.fdopen("w")); - std::fprintf(file.get(), "[[["); - OutputRedirect redir(file.get()); - std::fprintf(file.get(), "censored"); - EXPECT_EQ("censored", sanitize(redir.restore_and_read())); - EXPECT_EQ("", sanitize(redir.restore_and_read())); - std::fprintf(file.get(), "]]]"); - file = buffered_file(); - EXPECT_READ(read_end, "[[[]]]"); -} - -// Test that OutputRedirect handles errors in flush correctly. -TEST(OutputRedirectTest, FlushErrorInRestoreAndRead) { - file read_end, write_end; - file::pipe(read_end, write_end); - int write_fd = write_end.descriptor(); - file write_copy = write_end.dup(write_fd); - buffered_file f = write_end.fdopen("w"); - OutputRedirect redir(f.get()); - // Put a character in a file buffer. - EXPECT_EQ('x', fputc('x', f.get())); - FMT_POSIX(close(write_fd)); - EXPECT_SYSTEM_ERROR_NOASSERT(redir.restore_and_read(), EBADF, - "cannot flush stream"); - write_copy.dup2(write_fd); // "undo" close or dtor will fail -} - -TEST(OutputRedirectTest, ErrorInDtor) { - file read_end, write_end; - file::pipe(read_end, write_end); - int write_fd = write_end.descriptor(); - file write_copy = write_end.dup(write_fd); - buffered_file f = write_end.fdopen("w"); - std::unique_ptr<OutputRedirect> redir(new OutputRedirect(f.get())); - // Put a character in a file buffer. - EXPECT_EQ('x', fputc('x', f.get())); + "Actual: test"); + EXPECT_EQ(2, a_); + EXPECT_EQ(2, b_); +} + +// Tests EXPECT_WRITE. +TEST(ExpectTest, EXPECT_WRITE) { + EXPECT_WRITE(stdout, do_nothing(), ""); + EXPECT_WRITE(stdout, std::printf("test"), "test"); + EXPECT_WRITE(stderr, std::fprintf(stderr, "test"), "test"); + EXPECT_NONFATAL_FAILURE(EXPECT_WRITE(stdout, std::printf("that"), "this"), + "Expected: this\n" + " Actual: that"); +} + +TEST(StreamingAssertionsTest, EXPECT_WRITE) { + EXPECT_WRITE(stdout, std::printf("test"), "test") << "unexpected failure"; + EXPECT_NONFATAL_FAILURE(EXPECT_WRITE(stdout, std::printf("test"), "other") + << "expected failure", + "expected failure"); +} +#endif // FMT_USE_FCNTL + +// Tests that the compiler will not complain about unreachable code in the +// EXPECT_THROW_MSG macro. +TEST(ExpectThrowTest, DoesNotGenerateUnreachableCodeWarning) { + int n = 0; + using std::runtime_error; + EXPECT_THROW_MSG(throw runtime_error(""), runtime_error, ""); + EXPECT_NONFATAL_FAILURE(EXPECT_THROW_MSG(n++, runtime_error, ""), ""); + EXPECT_NONFATAL_FAILURE(EXPECT_THROW_MSG(throw 1, runtime_error, ""), ""); + EXPECT_NONFATAL_FAILURE( + EXPECT_THROW_MSG(throw runtime_error("a"), runtime_error, "b"), ""); +} + +// Tests that the compiler will not complain about unreachable code in the +// EXPECT_SYSTEM_ERROR macro. +TEST(ExpectSystemErrorTest, DoesNotGenerateUnreachableCodeWarning) { + int n = 0; + EXPECT_SYSTEM_ERROR(throw fmt::system_error(EDOM, "test"), EDOM, "test"); + EXPECT_NONFATAL_FAILURE(EXPECT_SYSTEM_ERROR(n++, EDOM, ""), ""); + EXPECT_NONFATAL_FAILURE(EXPECT_SYSTEM_ERROR(throw 1, EDOM, ""), ""); + EXPECT_NONFATAL_FAILURE( + EXPECT_SYSTEM_ERROR(throw fmt::system_error(EDOM, "aaa"), EDOM, "bbb"), + ""); +} + +TEST(AssertionSyntaxTest, ExceptionAssertionBehavesLikeSingleStatement) { + if (::testing::internal::AlwaysFalse()) + EXPECT_THROW_MSG(do_nothing(), std::exception, ""); + + if (::testing::internal::AlwaysTrue()) + EXPECT_THROW_MSG(throw_exception(), std::exception, "test"); + else + do_nothing(); +} + +TEST(AssertionSyntaxTest, SystemErrorAssertionBehavesLikeSingleStatement) { + if (::testing::internal::AlwaysFalse()) + EXPECT_SYSTEM_ERROR(do_nothing(), EDOM, ""); + + if (::testing::internal::AlwaysTrue()) + EXPECT_SYSTEM_ERROR(throw_system_error(), EDOM, "test"); + else + do_nothing(); +} + +TEST(AssertionSyntaxTest, WriteAssertionBehavesLikeSingleStatement) { + if (::testing::internal::AlwaysFalse()) + EXPECT_WRITE(stdout, std::printf("x"), "x"); + + if (::testing::internal::AlwaysTrue()) + EXPECT_WRITE(stdout, std::printf("x"), "x"); + else + do_nothing(); +} + +// Tests EXPECT_THROW_MSG. +TEST(ExpectTest, EXPECT_THROW_MSG) { + EXPECT_THROW_MSG(throw_exception(), std::exception, "test"); + EXPECT_NONFATAL_FAILURE( + EXPECT_THROW_MSG(throw_exception(), std::logic_error, "test"), + "Expected: throw_exception() throws an exception of " + "type std::logic_error.\n Actual: it throws a different type."); + EXPECT_NONFATAL_FAILURE( + EXPECT_THROW_MSG(do_nothing(), std::exception, "test"), + "Expected: do_nothing() throws an exception of type std::exception.\n" + " Actual: it throws nothing."); + EXPECT_NONFATAL_FAILURE( + EXPECT_THROW_MSG(throw_exception(), std::exception, "other"), + "throw_exception() throws an exception with a different message.\n" + "Expected: other\n" + " Actual: test"); +} + +// Tests EXPECT_SYSTEM_ERROR. +TEST(ExpectTest, EXPECT_SYSTEM_ERROR) { + EXPECT_SYSTEM_ERROR(throw_system_error(), EDOM, "test"); + EXPECT_NONFATAL_FAILURE( + EXPECT_SYSTEM_ERROR(throw_exception(), EDOM, "test"), + "Expected: throw_exception() throws an exception of " + "type fmt::system_error.\n Actual: it throws a different type."); + EXPECT_NONFATAL_FAILURE( + EXPECT_SYSTEM_ERROR(do_nothing(), EDOM, "test"), + "Expected: do_nothing() throws an exception of type fmt::system_error.\n" + " Actual: it throws nothing."); + EXPECT_NONFATAL_FAILURE( + EXPECT_SYSTEM_ERROR(throw_system_error(), EDOM, "other"), + fmt::format( + "throw_system_error() throws an exception with a different message.\n" + "Expected: {}\n" + " Actual: {}", + format_system_error(EDOM, "other"), + format_system_error(EDOM, "test"))); +} + +TEST(StreamingAssertionsTest, EXPECT_THROW_MSG) { + EXPECT_THROW_MSG(throw_exception(), std::exception, "test") + << "unexpected failure"; + EXPECT_NONFATAL_FAILURE( + EXPECT_THROW_MSG(throw_exception(), std::exception, "other") + << "expected failure", + "expected failure"); +} + +TEST(StreamingAssertionsTest, EXPECT_SYSTEM_ERROR) { + EXPECT_SYSTEM_ERROR(throw_system_error(), EDOM, "test") + << "unexpected failure"; + EXPECT_NONFATAL_FAILURE( + EXPECT_SYSTEM_ERROR(throw_system_error(), EDOM, "other") + << "expected failure", + "expected failure"); +} + +TEST(UtilTest, FormatSystemError) { + fmt::memory_buffer out; + fmt::format_system_error(out, EDOM, "test message"); + EXPECT_EQ(to_string(out), format_system_error(EDOM, "test message")); +} + +#if FMT_USE_FCNTL + +using fmt::buffered_file; +using fmt::error_code; +using fmt::file; + +TEST(ErrorCodeTest, Ctor) { + EXPECT_EQ(error_code().get(), 0); + EXPECT_EQ(error_code(42).get(), 42); +} + +TEST(OutputRedirectTest, ScopedRedirect) { + file read_end, write_end; + file::pipe(read_end, write_end); + { + buffered_file file(write_end.fdopen("w")); + std::fprintf(file.get(), "[[["); + { + OutputRedirect redir(file.get()); + std::fprintf(file.get(), "censored"); + } + std::fprintf(file.get(), "]]]"); + } + EXPECT_READ(read_end, "[[[]]]"); +} + +// Test that OutputRedirect handles errors in flush correctly. +TEST(OutputRedirectTest, FlushErrorInCtor) { + file read_end, write_end; + file::pipe(read_end, write_end); + int write_fd = write_end.descriptor(); + file write_copy = write_end.dup(write_fd); + buffered_file f = write_end.fdopen("w"); + // Put a character in a file buffer. + EXPECT_EQ('x', fputc('x', f.get())); + FMT_POSIX(close(write_fd)); + std::unique_ptr<OutputRedirect> redir{nullptr}; + EXPECT_SYSTEM_ERROR_NOASSERT(redir.reset(new OutputRedirect(f.get())), EBADF, + "cannot flush stream"); + redir.reset(nullptr); + write_copy.dup2(write_fd); // "undo" close or dtor will fail +} + +TEST(OutputRedirectTest, DupErrorInCtor) { + buffered_file f = open_buffered_file(); + int fd = (f.fileno)(); + file copy = file::dup(fd); + FMT_POSIX(close(fd)); + std::unique_ptr<OutputRedirect> redir{nullptr}; + EXPECT_SYSTEM_ERROR_NOASSERT( + redir.reset(new OutputRedirect(f.get())), EBADF, + fmt::format("cannot duplicate file descriptor {}", fd)); + copy.dup2(fd); // "undo" close or dtor will fail +} + +TEST(OutputRedirectTest, RestoreAndRead) { + file read_end, write_end; + file::pipe(read_end, write_end); + buffered_file file(write_end.fdopen("w")); + std::fprintf(file.get(), "[[["); + OutputRedirect redir(file.get()); + std::fprintf(file.get(), "censored"); + EXPECT_EQ("censored", sanitize(redir.restore_and_read())); + EXPECT_EQ("", sanitize(redir.restore_and_read())); + std::fprintf(file.get(), "]]]"); + file = buffered_file(); + EXPECT_READ(read_end, "[[[]]]"); +} + +// Test that OutputRedirect handles errors in flush correctly. +TEST(OutputRedirectTest, FlushErrorInRestoreAndRead) { + file read_end, write_end; + file::pipe(read_end, write_end); + int write_fd = write_end.descriptor(); + file write_copy = write_end.dup(write_fd); + buffered_file f = write_end.fdopen("w"); + OutputRedirect redir(f.get()); + // Put a character in a file buffer. + EXPECT_EQ('x', fputc('x', f.get())); + FMT_POSIX(close(write_fd)); + EXPECT_SYSTEM_ERROR_NOASSERT(redir.restore_and_read(), EBADF, + "cannot flush stream"); + write_copy.dup2(write_fd); // "undo" close or dtor will fail +} + +TEST(OutputRedirectTest, ErrorInDtor) { + file read_end, write_end; + file::pipe(read_end, write_end); + int write_fd = write_end.descriptor(); + file write_copy = write_end.dup(write_fd); + buffered_file f = write_end.fdopen("w"); + std::unique_ptr<OutputRedirect> redir(new OutputRedirect(f.get())); + // Put a character in a file buffer. + EXPECT_EQ('x', fputc('x', f.get())); EXPECT_WRITE( stderr, { @@ -431,9 +431,9 @@ TEST(OutputRedirectTest, ErrorInDtor) { SUPPRESS_ASSERT(redir.reset(nullptr)); }, format_system_error(EBADF, "cannot flush stream")); - write_copy.dup2(write_fd); // "undo" close or dtor of buffered_file will fail -} - -#endif // FMT_USE_FILE_DESCRIPTORS - -} // namespace + write_copy.dup2(write_fd); // "undo" close or dtor of buffered_file will fail +} + +#endif // FMT_USE_FILE_DESCRIPTORS + +} // namespace diff --git a/contrib/libs/fmt/test/gtest-extra-test/ya.make b/contrib/libs/fmt/test/gtest-extra-test/ya.make index e6953ec539..b8d6cf8316 100644 --- a/contrib/libs/fmt/test/gtest-extra-test/ya.make +++ b/contrib/libs/fmt/test/gtest-extra-test/ya.make @@ -1,37 +1,37 @@ -# Generated by devtools/yamaker. - +# Generated by devtools/yamaker. + GTEST() - + WITHOUT_LICENSE_TEXTS() - + OWNER( orivej g:cpp-contrib ) -LICENSE(MIT) - -PEERDIR( - contrib/libs/fmt - contrib/libs/fmt/test -) - -NO_COMPILER_WARNINGS() - -NO_UTIL() - -CFLAGS( - -DFMT_LOCALE - -DFMT_SHARED - -DGTEST_HAS_STD_WSTRING=1 - -DGTEST_LANG_CXX11=0 - -D_SILENCE_TR1_NAMESPACE_DEPRECATION_WARNING=1 -) - -SRCDIR(contrib/libs/fmt/test) - -SRCS( - gtest-extra-test.cc -) - -END() +LICENSE(MIT) + +PEERDIR( + contrib/libs/fmt + contrib/libs/fmt/test +) + +NO_COMPILER_WARNINGS() + +NO_UTIL() + +CFLAGS( + -DFMT_LOCALE + -DFMT_SHARED + -DGTEST_HAS_STD_WSTRING=1 + -DGTEST_LANG_CXX11=0 + -D_SILENCE_TR1_NAMESPACE_DEPRECATION_WARNING=1 +) + +SRCDIR(contrib/libs/fmt/test) + +SRCS( + gtest-extra-test.cc +) + +END() diff --git a/contrib/libs/fmt/test/gtest-extra.cc b/contrib/libs/fmt/test/gtest-extra.cc index 3f38cbd1e6..58628a8a98 100644 --- a/contrib/libs/fmt/test/gtest-extra.cc +++ b/contrib/libs/fmt/test/gtest-extra.cc @@ -1,87 +1,87 @@ -// Formatting library for C++ - custom Google Test assertions -// -// Copyright (c) 2012 - present, Victor Zverovich -// All rights reserved. -// -// For the license information refer to format.h. - -#include "gtest-extra.h" - -#if FMT_USE_FCNTL - -using fmt::file; - -void OutputRedirect::flush() { -# if EOF != -1 -# error "FMT_RETRY assumes return value of -1 indicating failure" -# endif - int result = 0; - FMT_RETRY(result, fflush(file_)); - if (result != 0) throw fmt::system_error(errno, "cannot flush stream"); -} - -void OutputRedirect::restore() { - if (original_.descriptor() == -1) return; // Already restored. - flush(); - // Restore the original file. - original_.dup2(FMT_POSIX(fileno(file_))); - original_.close(); -} - -OutputRedirect::OutputRedirect(FILE* f) : file_(f) { - flush(); - int fd = FMT_POSIX(fileno(f)); - // Create a file object referring to the original file. - original_ = file::dup(fd); - // Create a pipe. - file write_end; - file::pipe(read_end_, write_end); - // Connect the passed FILE object to the write end of the pipe. - write_end.dup2(fd); -} - -OutputRedirect::~OutputRedirect() FMT_NOEXCEPT { - try { - restore(); - } catch (const std::exception& e) { - std::fputs(e.what(), stderr); - } -} - -std::string OutputRedirect::restore_and_read() { - // Restore output. - restore(); - - // Read everything from the pipe. - std::string content; - if (read_end_.descriptor() == -1) return content; // Already read. - enum { BUFFER_SIZE = 4096 }; - char buffer[BUFFER_SIZE]; +// Formatting library for C++ - custom Google Test assertions +// +// Copyright (c) 2012 - present, Victor Zverovich +// All rights reserved. +// +// For the license information refer to format.h. + +#include "gtest-extra.h" + +#if FMT_USE_FCNTL + +using fmt::file; + +void OutputRedirect::flush() { +# if EOF != -1 +# error "FMT_RETRY assumes return value of -1 indicating failure" +# endif + int result = 0; + FMT_RETRY(result, fflush(file_)); + if (result != 0) throw fmt::system_error(errno, "cannot flush stream"); +} + +void OutputRedirect::restore() { + if (original_.descriptor() == -1) return; // Already restored. + flush(); + // Restore the original file. + original_.dup2(FMT_POSIX(fileno(file_))); + original_.close(); +} + +OutputRedirect::OutputRedirect(FILE* f) : file_(f) { + flush(); + int fd = FMT_POSIX(fileno(f)); + // Create a file object referring to the original file. + original_ = file::dup(fd); + // Create a pipe. + file write_end; + file::pipe(read_end_, write_end); + // Connect the passed FILE object to the write end of the pipe. + write_end.dup2(fd); +} + +OutputRedirect::~OutputRedirect() FMT_NOEXCEPT { + try { + restore(); + } catch (const std::exception& e) { + std::fputs(e.what(), stderr); + } +} + +std::string OutputRedirect::restore_and_read() { + // Restore output. + restore(); + + // Read everything from the pipe. + std::string content; + if (read_end_.descriptor() == -1) return content; // Already read. + enum { BUFFER_SIZE = 4096 }; + char buffer[BUFFER_SIZE]; size_t count = 0; - do { - count = read_end_.read(buffer, BUFFER_SIZE); - content.append(buffer, count); - } while (count != 0); - read_end_.close(); - return content; -} - + do { + count = read_end_.read(buffer, BUFFER_SIZE); + content.append(buffer, count); + } while (count != 0); + read_end_.close(); + return content; +} + std::string read(file& f, size_t count) { - std::string buffer(count, '\0'); + std::string buffer(count, '\0'); size_t n = 0, offset = 0; - do { - n = f.read(&buffer[offset], count - offset); - // We can't read more than size_t bytes since count has type size_t. - offset += n; - } while (offset < count && n != 0); - buffer.resize(offset); - return buffer; -} - -#endif // FMT_USE_FCNTL - -std::string format_system_error(int error_code, fmt::string_view message) { - fmt::memory_buffer out; - format_system_error(out, error_code, message); - return to_string(out); -} + do { + n = f.read(&buffer[offset], count - offset); + // We can't read more than size_t bytes since count has type size_t. + offset += n; + } while (offset < count && n != 0); + buffer.resize(offset); + return buffer; +} + +#endif // FMT_USE_FCNTL + +std::string format_system_error(int error_code, fmt::string_view message) { + fmt::memory_buffer out; + format_system_error(out, error_code, message); + return to_string(out); +} diff --git a/contrib/libs/fmt/test/gtest-extra.h b/contrib/libs/fmt/test/gtest-extra.h index 2b602e65fa..36be158bbb 100644 --- a/contrib/libs/fmt/test/gtest-extra.h +++ b/contrib/libs/fmt/test/gtest-extra.h @@ -1,151 +1,151 @@ -// Formatting library for C++ - custom Google Test assertions -// -// Copyright (c) 2012 - present, Victor Zverovich -// All rights reserved. -// -// For the license information refer to format.h. - -#ifndef FMT_GTEST_EXTRA_H_ -#define FMT_GTEST_EXTRA_H_ - -#include <string> +// Formatting library for C++ - custom Google Test assertions +// +// Copyright (c) 2012 - present, Victor Zverovich +// All rights reserved. +// +// For the license information refer to format.h. + +#ifndef FMT_GTEST_EXTRA_H_ +#define FMT_GTEST_EXTRA_H_ + +#include <string> #include "fmt/os.h" -#include <gmock/gmock.h> - -#define FMT_TEST_THROW_(statement, expected_exception, expected_message, fail) \ - GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ - if (::testing::AssertionResult gtest_ar = ::testing::AssertionSuccess()) { \ - std::string gtest_expected_message = expected_message; \ - bool gtest_caught_expected = false; \ - try { \ - GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \ - } catch (expected_exception const& e) { \ - if (gtest_expected_message != e.what()) { \ - gtest_ar << #statement \ - " throws an exception with a different message.\n" \ - << "Expected: " << gtest_expected_message << "\n" \ - << " Actual: " << e.what(); \ - goto GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__); \ - } \ - gtest_caught_expected = true; \ - } catch (...) { \ - gtest_ar << "Expected: " #statement \ - " throws an exception of type " #expected_exception \ - ".\n Actual: it throws a different type."; \ - goto GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__); \ - } \ - if (!gtest_caught_expected) { \ - gtest_ar << "Expected: " #statement \ - " throws an exception of type " #expected_exception \ - ".\n Actual: it throws nothing."; \ - goto GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__); \ - } \ - } else \ - GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__) \ - : fail(gtest_ar.failure_message()) - -// Tests that the statement throws the expected exception and the exception's -// what() method returns expected message. -#define EXPECT_THROW_MSG(statement, expected_exception, expected_message) \ - FMT_TEST_THROW_(statement, expected_exception, expected_message, \ - GTEST_NONFATAL_FAILURE_) - -std::string format_system_error(int error_code, fmt::string_view message); - -#define EXPECT_SYSTEM_ERROR(statement, error_code, message) \ - EXPECT_THROW_MSG(statement, fmt::system_error, \ - format_system_error(error_code, message)) - -#if FMT_USE_FCNTL - -// Captures file output by redirecting it to a pipe. -// The output it can handle is limited by the pipe capacity. -class OutputRedirect { - private: - FILE* file_; - fmt::file original_; // Original file passed to redirector. - fmt::file read_end_; // Read end of the pipe where the output is redirected. - - GTEST_DISALLOW_COPY_AND_ASSIGN_(OutputRedirect); - - void flush(); - void restore(); - - public: - explicit OutputRedirect(FILE* file); - ~OutputRedirect() FMT_NOEXCEPT; - - // Restores the original file, reads output from the pipe into a string - // and returns it. - std::string restore_and_read(); -}; - -# define FMT_TEST_WRITE_(statement, expected_output, file, fail) \ - GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ - if (::testing::AssertionResult gtest_ar = ::testing::AssertionSuccess()) { \ - std::string gtest_expected_output = expected_output; \ - OutputRedirect gtest_redir(file); \ - GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \ - std::string gtest_output = gtest_redir.restore_and_read(); \ - if (gtest_output != gtest_expected_output) { \ - gtest_ar << #statement " produces different output.\n" \ - << "Expected: " << gtest_expected_output << "\n" \ - << " Actual: " << gtest_output; \ - goto GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__); \ - } \ - } else \ - GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__) \ - : fail(gtest_ar.failure_message()) - -// Tests that the statement writes the expected output to file. -# define EXPECT_WRITE(file, statement, expected_output) \ - FMT_TEST_WRITE_(statement, expected_output, file, GTEST_NONFATAL_FAILURE_) - -# ifdef _MSC_VER +#include <gmock/gmock.h> + +#define FMT_TEST_THROW_(statement, expected_exception, expected_message, fail) \ + GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ + if (::testing::AssertionResult gtest_ar = ::testing::AssertionSuccess()) { \ + std::string gtest_expected_message = expected_message; \ + bool gtest_caught_expected = false; \ + try { \ + GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \ + } catch (expected_exception const& e) { \ + if (gtest_expected_message != e.what()) { \ + gtest_ar << #statement \ + " throws an exception with a different message.\n" \ + << "Expected: " << gtest_expected_message << "\n" \ + << " Actual: " << e.what(); \ + goto GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__); \ + } \ + gtest_caught_expected = true; \ + } catch (...) { \ + gtest_ar << "Expected: " #statement \ + " throws an exception of type " #expected_exception \ + ".\n Actual: it throws a different type."; \ + goto GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__); \ + } \ + if (!gtest_caught_expected) { \ + gtest_ar << "Expected: " #statement \ + " throws an exception of type " #expected_exception \ + ".\n Actual: it throws nothing."; \ + goto GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__); \ + } \ + } else \ + GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__) \ + : fail(gtest_ar.failure_message()) + +// Tests that the statement throws the expected exception and the exception's +// what() method returns expected message. +#define EXPECT_THROW_MSG(statement, expected_exception, expected_message) \ + FMT_TEST_THROW_(statement, expected_exception, expected_message, \ + GTEST_NONFATAL_FAILURE_) + +std::string format_system_error(int error_code, fmt::string_view message); + +#define EXPECT_SYSTEM_ERROR(statement, error_code, message) \ + EXPECT_THROW_MSG(statement, fmt::system_error, \ + format_system_error(error_code, message)) + +#if FMT_USE_FCNTL + +// Captures file output by redirecting it to a pipe. +// The output it can handle is limited by the pipe capacity. +class OutputRedirect { + private: + FILE* file_; + fmt::file original_; // Original file passed to redirector. + fmt::file read_end_; // Read end of the pipe where the output is redirected. + + GTEST_DISALLOW_COPY_AND_ASSIGN_(OutputRedirect); + + void flush(); + void restore(); + + public: + explicit OutputRedirect(FILE* file); + ~OutputRedirect() FMT_NOEXCEPT; + + // Restores the original file, reads output from the pipe into a string + // and returns it. + std::string restore_and_read(); +}; + +# define FMT_TEST_WRITE_(statement, expected_output, file, fail) \ + GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ + if (::testing::AssertionResult gtest_ar = ::testing::AssertionSuccess()) { \ + std::string gtest_expected_output = expected_output; \ + OutputRedirect gtest_redir(file); \ + GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \ + std::string gtest_output = gtest_redir.restore_and_read(); \ + if (gtest_output != gtest_expected_output) { \ + gtest_ar << #statement " produces different output.\n" \ + << "Expected: " << gtest_expected_output << "\n" \ + << " Actual: " << gtest_output; \ + goto GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__); \ + } \ + } else \ + GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__) \ + : fail(gtest_ar.failure_message()) + +// Tests that the statement writes the expected output to file. +# define EXPECT_WRITE(file, statement, expected_output) \ + FMT_TEST_WRITE_(statement, expected_output, file, GTEST_NONFATAL_FAILURE_) + +# ifdef _MSC_VER #include <crtdbg.h> - -// Suppresses Windows assertions on invalid file descriptors, making -// POSIX functions return proper error codes instead of crashing on Windows. -class SuppressAssert { - private: - _invalid_parameter_handler original_handler_; - int original_report_mode_; - - static void handle_invalid_parameter(const wchar_t*, const wchar_t*, - const wchar_t*, unsigned, uintptr_t) {} - - public: - SuppressAssert() - : original_handler_( - _set_invalid_parameter_handler(handle_invalid_parameter)), - original_report_mode_(_CrtSetReportMode(_CRT_ASSERT, 0)) {} - ~SuppressAssert() { - _set_invalid_parameter_handler(original_handler_); - _CrtSetReportMode(_CRT_ASSERT, original_report_mode_); - } -}; - -# define SUPPRESS_ASSERT(statement) \ - { \ - SuppressAssert sa; \ - statement; \ - } -# else -# define SUPPRESS_ASSERT(statement) statement -# endif // _MSC_VER - -# define EXPECT_SYSTEM_ERROR_NOASSERT(statement, error_code, message) \ - EXPECT_SYSTEM_ERROR(SUPPRESS_ASSERT(statement), error_code, message) - -// Attempts to read count characters from a file. + +// Suppresses Windows assertions on invalid file descriptors, making +// POSIX functions return proper error codes instead of crashing on Windows. +class SuppressAssert { + private: + _invalid_parameter_handler original_handler_; + int original_report_mode_; + + static void handle_invalid_parameter(const wchar_t*, const wchar_t*, + const wchar_t*, unsigned, uintptr_t) {} + + public: + SuppressAssert() + : original_handler_( + _set_invalid_parameter_handler(handle_invalid_parameter)), + original_report_mode_(_CrtSetReportMode(_CRT_ASSERT, 0)) {} + ~SuppressAssert() { + _set_invalid_parameter_handler(original_handler_); + _CrtSetReportMode(_CRT_ASSERT, original_report_mode_); + } +}; + +# define SUPPRESS_ASSERT(statement) \ + { \ + SuppressAssert sa; \ + statement; \ + } +# else +# define SUPPRESS_ASSERT(statement) statement +# endif // _MSC_VER + +# define EXPECT_SYSTEM_ERROR_NOASSERT(statement, error_code, message) \ + EXPECT_SYSTEM_ERROR(SUPPRESS_ASSERT(statement), error_code, message) + +// Attempts to read count characters from a file. std::string read(fmt::file& f, size_t count); - -# define EXPECT_READ(file, expected_content) \ + +# define EXPECT_READ(file, expected_content) \ EXPECT_EQ(expected_content, \ read(file, fmt::string_view(expected_content).size())) - -#else + +#else # define EXPECT_WRITE(file, statement, expected_output) \ do { \ (void)(file); \ @@ -153,11 +153,11 @@ std::string read(fmt::file& f, size_t count); (void)(expected_output); \ SUCCEED(); \ } while (false) -#endif // FMT_USE_FCNTL - -template <typename Mock> struct ScopedMock : testing::StrictMock<Mock> { - ScopedMock() { Mock::instance = this; } - ~ScopedMock() { Mock::instance = nullptr; } -}; - -#endif // FMT_GTEST_EXTRA_H_ +#endif // FMT_USE_FCNTL + +template <typename Mock> struct ScopedMock : testing::StrictMock<Mock> { + ScopedMock() { Mock::instance = this; } + ~ScopedMock() { Mock::instance = nullptr; } +}; + +#endif // FMT_GTEST_EXTRA_H_ diff --git a/contrib/libs/fmt/test/header-only-test.cc b/contrib/libs/fmt/test/header-only-test.cc index e38159c83c..674dab993d 100644 --- a/contrib/libs/fmt/test/header-only-test.cc +++ b/contrib/libs/fmt/test/header-only-test.cc @@ -1,3 +1,3 @@ -// Header-only configuration test - -#include "fmt/core.h" +// Header-only configuration test + +#include "fmt/core.h" diff --git a/contrib/libs/fmt/test/header-only-test/ya.make b/contrib/libs/fmt/test/header-only-test/ya.make index de4aa9fa85..cfbc290203 100644 --- a/contrib/libs/fmt/test/header-only-test/ya.make +++ b/contrib/libs/fmt/test/header-only-test/ya.make @@ -1,37 +1,37 @@ -# Generated by devtools/yamaker. - +# Generated by devtools/yamaker. + GTEST() - + WITHOUT_LICENSE_TEXTS() - + OWNER( orivej g:cpp-contrib ) -LICENSE(MIT) - -PEERDIR( +LICENSE(MIT) + +PEERDIR( contrib/libs/fmt - contrib/libs/fmt/test -) - -NO_COMPILER_WARNINGS() - -NO_UTIL() - -CFLAGS( - -DFMT_HEADER_ONLY=1 - -DGTEST_HAS_STD_WSTRING=1 - -DGTEST_LANG_CXX11=0 - -D_SILENCE_TR1_NAMESPACE_DEPRECATION_WARNING=1 -) - -SRCDIR(contrib/libs/fmt/test) - -SRCS( - header-only-test.cc - header-only-test2.cc -) - -END() + contrib/libs/fmt/test +) + +NO_COMPILER_WARNINGS() + +NO_UTIL() + +CFLAGS( + -DFMT_HEADER_ONLY=1 + -DGTEST_HAS_STD_WSTRING=1 + -DGTEST_LANG_CXX11=0 + -D_SILENCE_TR1_NAMESPACE_DEPRECATION_WARNING=1 +) + +SRCDIR(contrib/libs/fmt/test) + +SRCS( + header-only-test.cc + header-only-test2.cc +) + +END() diff --git a/contrib/libs/fmt/test/header-only-test2.cc b/contrib/libs/fmt/test/header-only-test2.cc index 9fbbc9a5b1..ea90b604e4 100644 --- a/contrib/libs/fmt/test/header-only-test2.cc +++ b/contrib/libs/fmt/test/header-only-test2.cc @@ -1,3 +1,3 @@ -// Additional translation unit for the header-only configuration test - -#include "fmt/core.h" +// Additional translation unit for the header-only configuration test + +#include "fmt/core.h" diff --git a/contrib/libs/fmt/test/locale-test.cc b/contrib/libs/fmt/test/locale-test.cc index ef346ab6be..7d776b4290 100644 --- a/contrib/libs/fmt/test/locale-test.cc +++ b/contrib/libs/fmt/test/locale-test.cc @@ -1,102 +1,102 @@ -// Formatting library for C++ - locale tests -// -// Copyright (c) 2012 - present, Victor Zverovich -// All rights reserved. -// -// For the license information refer to format.h. - -#include "fmt/locale.h" +// Formatting library for C++ - locale tests +// +// Copyright (c) 2012 - present, Victor Zverovich +// All rights reserved. +// +// For the license information refer to format.h. + +#include "fmt/locale.h" #include <complex> -#include <gmock/gmock.h> - +#include <gmock/gmock.h> + using fmt::detail::max_value; - -#ifndef FMT_STATIC_THOUSANDS_SEPARATOR -template <typename Char> struct numpunct : std::numpunct<Char> { - protected: - Char do_decimal_point() const FMT_OVERRIDE { return '?'; } - std::string do_grouping() const FMT_OVERRIDE { return "\03"; } - Char do_thousands_sep() const FMT_OVERRIDE { return '~'; } -}; - -template <typename Char> struct no_grouping : std::numpunct<Char> { - protected: - Char do_decimal_point() const FMT_OVERRIDE { return '.'; } - std::string do_grouping() const FMT_OVERRIDE { return ""; } - Char do_thousands_sep() const FMT_OVERRIDE { return ','; } -}; - -template <typename Char> struct special_grouping : std::numpunct<Char> { - protected: - Char do_decimal_point() const FMT_OVERRIDE { return '.'; } - std::string do_grouping() const FMT_OVERRIDE { return "\03\02"; } - Char do_thousands_sep() const FMT_OVERRIDE { return ','; } -}; - -template <typename Char> struct small_grouping : std::numpunct<Char> { - protected: - Char do_decimal_point() const FMT_OVERRIDE { return '.'; } - std::string do_grouping() const FMT_OVERRIDE { return "\01"; } - Char do_thousands_sep() const FMT_OVERRIDE { return ','; } -}; - -TEST(LocaleTest, DoubleDecimalPoint) { - std::locale loc(std::locale(), new numpunct<char>()); + +#ifndef FMT_STATIC_THOUSANDS_SEPARATOR +template <typename Char> struct numpunct : std::numpunct<Char> { + protected: + Char do_decimal_point() const FMT_OVERRIDE { return '?'; } + std::string do_grouping() const FMT_OVERRIDE { return "\03"; } + Char do_thousands_sep() const FMT_OVERRIDE { return '~'; } +}; + +template <typename Char> struct no_grouping : std::numpunct<Char> { + protected: + Char do_decimal_point() const FMT_OVERRIDE { return '.'; } + std::string do_grouping() const FMT_OVERRIDE { return ""; } + Char do_thousands_sep() const FMT_OVERRIDE { return ','; } +}; + +template <typename Char> struct special_grouping : std::numpunct<Char> { + protected: + Char do_decimal_point() const FMT_OVERRIDE { return '.'; } + std::string do_grouping() const FMT_OVERRIDE { return "\03\02"; } + Char do_thousands_sep() const FMT_OVERRIDE { return ','; } +}; + +template <typename Char> struct small_grouping : std::numpunct<Char> { + protected: + Char do_decimal_point() const FMT_OVERRIDE { return '.'; } + std::string do_grouping() const FMT_OVERRIDE { return "\01"; } + Char do_thousands_sep() const FMT_OVERRIDE { return ','; } +}; + +TEST(LocaleTest, DoubleDecimalPoint) { + std::locale loc(std::locale(), new numpunct<char>()); EXPECT_EQ("1?23", fmt::format(loc, "{:L}", 1.23)); -} - -TEST(LocaleTest, Format) { - std::locale loc(std::locale(), new numpunct<char>()); +} + +TEST(LocaleTest, Format) { + std::locale loc(std::locale(), new numpunct<char>()); EXPECT_EQ("1234567", fmt::format(std::locale(), "{:L}", 1234567)); EXPECT_EQ("1~234~567", fmt::format(loc, "{:L}", 1234567)); EXPECT_EQ("-1~234~567", fmt::format(loc, "{:L}", -1234567)); EXPECT_EQ("-256", fmt::format(loc, "{:L}", -256)); - fmt::format_arg_store<fmt::format_context, int> as{1234567}; + fmt::format_arg_store<fmt::format_context, int> as{1234567}; EXPECT_EQ("1~234~567", fmt::vformat(loc, "{:L}", fmt::format_args(as))); - std::string s; + std::string s; fmt::format_to(std::back_inserter(s), loc, "{:L}", 1234567); - EXPECT_EQ("1~234~567", s); - - std::locale no_grouping_loc(std::locale(), new no_grouping<char>()); + EXPECT_EQ("1~234~567", s); + + std::locale no_grouping_loc(std::locale(), new no_grouping<char>()); EXPECT_EQ("1234567", fmt::format(no_grouping_loc, "{:L}", 1234567)); - - std::locale special_grouping_loc(std::locale(), new special_grouping<char>()); + + std::locale special_grouping_loc(std::locale(), new special_grouping<char>()); EXPECT_EQ("1,23,45,678", fmt::format(special_grouping_loc, "{:L}", 12345678)); EXPECT_EQ("12,345", fmt::format(special_grouping_loc, "{:L}", 12345)); - - std::locale small_grouping_loc(std::locale(), new small_grouping<char>()); - EXPECT_EQ("4,2,9,4,9,6,7,2,9,5", + + std::locale small_grouping_loc(std::locale(), new small_grouping<char>()); + EXPECT_EQ("4,2,9,4,9,6,7,2,9,5", fmt::format(small_grouping_loc, "{:L}", max_value<uint32_t>())); -} - +} + TEST(LocaleTest, FormatDetaultAlign) { std::locale special_grouping_loc(std::locale(), new special_grouping<char>()); EXPECT_EQ(" 12,345", fmt::format(special_grouping_loc, "{:8L}", 12345)); } -TEST(LocaleTest, WFormat) { - std::locale loc(std::locale(), new numpunct<wchar_t>()); +TEST(LocaleTest, WFormat) { + std::locale loc(std::locale(), new numpunct<wchar_t>()); EXPECT_EQ(L"1234567", fmt::format(std::locale(), L"{:L}", 1234567)); EXPECT_EQ(L"1~234~567", fmt::format(loc, L"{:L}", 1234567)); - fmt::format_arg_store<fmt::wformat_context, int> as{1234567}; + fmt::format_arg_store<fmt::wformat_context, int> as{1234567}; EXPECT_EQ(L"1~234~567", fmt::vformat(loc, L"{:L}", fmt::wformat_args(as))); EXPECT_EQ(L"1234567", fmt::format(std::locale("C"), L"{:L}", 1234567)); - - std::locale no_grouping_loc(std::locale(), new no_grouping<wchar_t>()); + + std::locale no_grouping_loc(std::locale(), new no_grouping<wchar_t>()); EXPECT_EQ(L"1234567", fmt::format(no_grouping_loc, L"{:L}", 1234567)); - - std::locale special_grouping_loc(std::locale(), - new special_grouping<wchar_t>()); - EXPECT_EQ(L"1,23,45,678", + + std::locale special_grouping_loc(std::locale(), + new special_grouping<wchar_t>()); + EXPECT_EQ(L"1,23,45,678", fmt::format(special_grouping_loc, L"{:L}", 12345678)); - - std::locale small_grouping_loc(std::locale(), new small_grouping<wchar_t>()); - EXPECT_EQ(L"4,2,9,4,9,6,7,2,9,5", + + std::locale small_grouping_loc(std::locale(), new small_grouping<wchar_t>()); + EXPECT_EQ(L"4,2,9,4,9,6,7,2,9,5", fmt::format(small_grouping_loc, L"{:L}", max_value<uint32_t>())); -} - +} + TEST(LocaleTest, DoubleFormatter) { auto loc = std::locale(std::locale(), new special_grouping<char>()); auto f = fmt::formatter<int>(); @@ -157,4 +157,4 @@ TEST(FormatTest, Complex) { EXPECT_EQ(fmt::format("{:8}", std::complex<double>(1, 2)), " (1+2i)"); } -#endif // FMT_STATIC_THOUSANDS_SEPARATOR +#endif // FMT_STATIC_THOUSANDS_SEPARATOR diff --git a/contrib/libs/fmt/test/locale-test/ya.make b/contrib/libs/fmt/test/locale-test/ya.make index 9619d8632c..06a53a939c 100644 --- a/contrib/libs/fmt/test/locale-test/ya.make +++ b/contrib/libs/fmt/test/locale-test/ya.make @@ -1,37 +1,37 @@ -# Generated by devtools/yamaker. - +# Generated by devtools/yamaker. + GTEST() - + WITHOUT_LICENSE_TEXTS() - + OWNER( orivej g:cpp-contrib ) -LICENSE(MIT) - -PEERDIR( - contrib/libs/fmt - contrib/libs/fmt/test -) - -NO_COMPILER_WARNINGS() - -NO_UTIL() - -CFLAGS( - -DFMT_LOCALE - -DFMT_SHARED - -DGTEST_HAS_STD_WSTRING=1 - -DGTEST_LANG_CXX11=0 - -D_SILENCE_TR1_NAMESPACE_DEPRECATION_WARNING=1 -) - -SRCDIR(contrib/libs/fmt/test) - -SRCS( - locale-test.cc -) - -END() +LICENSE(MIT) + +PEERDIR( + contrib/libs/fmt + contrib/libs/fmt/test +) + +NO_COMPILER_WARNINGS() + +NO_UTIL() + +CFLAGS( + -DFMT_LOCALE + -DFMT_SHARED + -DGTEST_HAS_STD_WSTRING=1 + -DGTEST_LANG_CXX11=0 + -D_SILENCE_TR1_NAMESPACE_DEPRECATION_WARNING=1 +) + +SRCDIR(contrib/libs/fmt/test) + +SRCS( + locale-test.cc +) + +END() diff --git a/contrib/libs/fmt/test/mock-allocator.h b/contrib/libs/fmt/test/mock-allocator.h index c946009aa1..dfc13feee7 100644 --- a/contrib/libs/fmt/test/mock-allocator.h +++ b/contrib/libs/fmt/test/mock-allocator.h @@ -1,60 +1,60 @@ -// Formatting library for C++ - mock allocator -// -// Copyright (c) 2012 - present, Victor Zverovich -// All rights reserved. -// -// For the license information refer to format.h. - -#ifndef FMT_MOCK_ALLOCATOR_H_ -#define FMT_MOCK_ALLOCATOR_H_ - -#include "fmt/format.h" -#include <gmock/gmock.h> - -template <typename T> class mock_allocator { - public: - mock_allocator() {} - mock_allocator(const mock_allocator&) {} - typedef T value_type; +// Formatting library for C++ - mock allocator +// +// Copyright (c) 2012 - present, Victor Zverovich +// All rights reserved. +// +// For the license information refer to format.h. + +#ifndef FMT_MOCK_ALLOCATOR_H_ +#define FMT_MOCK_ALLOCATOR_H_ + +#include "fmt/format.h" +#include <gmock/gmock.h> + +template <typename T> class mock_allocator { + public: + mock_allocator() {} + mock_allocator(const mock_allocator&) {} + typedef T value_type; MOCK_METHOD1_T(allocate, T*(size_t n)); MOCK_METHOD2_T(deallocate, void(T* p, size_t n)); -}; - -template <typename Allocator> class allocator_ref { - private: - Allocator* alloc_; - - void move(allocator_ref& other) { - alloc_ = other.alloc_; - other.alloc_ = nullptr; - } - - public: - typedef typename Allocator::value_type value_type; - - explicit allocator_ref(Allocator* alloc = nullptr) : alloc_(alloc) {} - - allocator_ref(const allocator_ref& other) : alloc_(other.alloc_) {} - allocator_ref(allocator_ref&& other) { move(other); } - - allocator_ref& operator=(allocator_ref&& other) { - assert(this != &other); - move(other); - return *this; - } - - allocator_ref& operator=(const allocator_ref& other) { - alloc_ = other.alloc_; - return *this; - } - - public: - Allocator* get() const { return alloc_; } - +}; + +template <typename Allocator> class allocator_ref { + private: + Allocator* alloc_; + + void move(allocator_ref& other) { + alloc_ = other.alloc_; + other.alloc_ = nullptr; + } + + public: + typedef typename Allocator::value_type value_type; + + explicit allocator_ref(Allocator* alloc = nullptr) : alloc_(alloc) {} + + allocator_ref(const allocator_ref& other) : alloc_(other.alloc_) {} + allocator_ref(allocator_ref&& other) { move(other); } + + allocator_ref& operator=(allocator_ref&& other) { + assert(this != &other); + move(other); + return *this; + } + + allocator_ref& operator=(const allocator_ref& other) { + alloc_ = other.alloc_; + return *this; + } + + public: + Allocator* get() const { return alloc_; } + value_type* allocate(size_t n) { - return std::allocator_traits<Allocator>::allocate(*alloc_, n); - } + return std::allocator_traits<Allocator>::allocate(*alloc_, n); + } void deallocate(value_type* p, size_t n) { alloc_->deallocate(p, n); } -}; - -#endif // FMT_MOCK_ALLOCATOR_H_ +}; + +#endif // FMT_MOCK_ALLOCATOR_H_ diff --git a/contrib/libs/fmt/test/os-test.cc b/contrib/libs/fmt/test/os-test.cc index 4e17c5d522..359b5ff8ce 100644 --- a/contrib/libs/fmt/test/os-test.cc +++ b/contrib/libs/fmt/test/os-test.cc @@ -1,243 +1,243 @@ -// Formatting library for C++ - tests of the OS-specific functionality -// -// Copyright (c) 2012 - present, Victor Zverovich -// All rights reserved. -// -// For the license information refer to format.h. - +// Formatting library for C++ - tests of the OS-specific functionality +// +// Copyright (c) 2012 - present, Victor Zverovich +// All rights reserved. +// +// For the license information refer to format.h. + #include "fmt/os.h" -#include <cstdlib> // std::exit -#include <cstring> -#include <memory> - -#include "gtest-extra.h" -#include "util.h" - -#ifdef fileno -# undef fileno -#endif - -using fmt::buffered_file; -using fmt::error_code; - -#ifdef _WIN32 - -# include <windows.h> - -TEST(UtilTest, UTF16ToUTF8) { - std::string s = "ёжик"; +#include <cstdlib> // std::exit +#include <cstring> +#include <memory> + +#include "gtest-extra.h" +#include "util.h" + +#ifdef fileno +# undef fileno +#endif + +using fmt::buffered_file; +using fmt::error_code; + +#ifdef _WIN32 + +# include <windows.h> + +TEST(UtilTest, UTF16ToUTF8) { + std::string s = "ёжик"; fmt::detail::utf16_to_utf8 u(L"\x0451\x0436\x0438\x043A"); - EXPECT_EQ(s, u.str()); - EXPECT_EQ(s.size(), u.size()); -} - -TEST(UtilTest, UTF16ToUTF8EmptyString) { - std::string s = ""; + EXPECT_EQ(s, u.str()); + EXPECT_EQ(s.size(), u.size()); +} + +TEST(UtilTest, UTF16ToUTF8EmptyString) { + std::string s = ""; fmt::detail::utf16_to_utf8 u(L""); - EXPECT_EQ(s, u.str()); - EXPECT_EQ(s.size(), u.size()); -} - -template <typename Converter, typename Char> -void check_utf_conversion_error( - const char* message, - fmt::basic_string_view<Char> str = fmt::basic_string_view<Char>(0, 1)) { - fmt::memory_buffer out; + EXPECT_EQ(s, u.str()); + EXPECT_EQ(s.size(), u.size()); +} + +template <typename Converter, typename Char> +void check_utf_conversion_error( + const char* message, + fmt::basic_string_view<Char> str = fmt::basic_string_view<Char>(0, 1)) { + fmt::memory_buffer out; fmt::detail::format_windows_error(out, ERROR_INVALID_PARAMETER, message); - fmt::system_error error(0, ""); - try { - (Converter)(str); - } catch (const fmt::system_error& e) { - error = e; - } - EXPECT_EQ(ERROR_INVALID_PARAMETER, error.error_code()); - EXPECT_EQ(fmt::to_string(out), error.what()); -} - -TEST(UtilTest, UTF16ToUTF8Error) { + fmt::system_error error(0, ""); + try { + (Converter)(str); + } catch (const fmt::system_error& e) { + error = e; + } + EXPECT_EQ(ERROR_INVALID_PARAMETER, error.error_code()); + EXPECT_EQ(fmt::to_string(out), error.what()); +} + +TEST(UtilTest, UTF16ToUTF8Error) { check_utf_conversion_error<fmt::detail::utf16_to_utf8, wchar_t>( - "cannot convert string from UTF-16 to UTF-8"); -} - -TEST(UtilTest, UTF16ToUTF8Convert) { + "cannot convert string from UTF-16 to UTF-8"); +} + +TEST(UtilTest, UTF16ToUTF8Convert) { fmt::detail::utf16_to_utf8 u; - EXPECT_EQ(ERROR_INVALID_PARAMETER, u.convert(fmt::wstring_view(0, 1))); - EXPECT_EQ(ERROR_INVALID_PARAMETER, - u.convert(fmt::wstring_view(L"foo", INT_MAX + 1u))); -} - -TEST(UtilTest, FormatWindowsError) { - LPWSTR message = 0; - FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | - FORMAT_MESSAGE_IGNORE_INSERTS, - 0, ERROR_FILE_EXISTS, - MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), - reinterpret_cast<LPWSTR>(&message), 0, 0); + EXPECT_EQ(ERROR_INVALID_PARAMETER, u.convert(fmt::wstring_view(0, 1))); + EXPECT_EQ(ERROR_INVALID_PARAMETER, + u.convert(fmt::wstring_view(L"foo", INT_MAX + 1u))); +} + +TEST(UtilTest, FormatWindowsError) { + LPWSTR message = 0; + FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | + FORMAT_MESSAGE_IGNORE_INSERTS, + 0, ERROR_FILE_EXISTS, + MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), + reinterpret_cast<LPWSTR>(&message), 0, 0); fmt::detail::utf16_to_utf8 utf8_message(message); - LocalFree(message); - fmt::memory_buffer actual_message; + LocalFree(message); + fmt::memory_buffer actual_message; fmt::detail::format_windows_error(actual_message, ERROR_FILE_EXISTS, "test"); - EXPECT_EQ(fmt::format("test: {}", utf8_message.str()), - fmt::to_string(actual_message)); - actual_message.resize(0); + EXPECT_EQ(fmt::format("test: {}", utf8_message.str()), + fmt::to_string(actual_message)); + actual_message.resize(0); auto max_size = fmt::detail::max_value<size_t>() / 2; fmt::detail::format_windows_error(actual_message, ERROR_FILE_EXISTS, fmt::string_view(nullptr, max_size)); - EXPECT_EQ(fmt::format("error {}", ERROR_FILE_EXISTS), - fmt::to_string(actual_message)); -} - -TEST(UtilTest, FormatLongWindowsError) { - LPWSTR message = 0; - // this error code is not available on all Windows platforms and - // Windows SDKs, so do not fail the test if the error string cannot - // be retrieved. - const int provisioning_not_allowed = - 0x80284013L /*TBS_E_PROVISIONING_NOT_ALLOWED*/; - if (FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER | - FORMAT_MESSAGE_FROM_SYSTEM | - FORMAT_MESSAGE_IGNORE_INSERTS, - 0, static_cast<DWORD>(provisioning_not_allowed), - MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), - reinterpret_cast<LPWSTR>(&message), 0, 0) == 0) { - return; - } + EXPECT_EQ(fmt::format("error {}", ERROR_FILE_EXISTS), + fmt::to_string(actual_message)); +} + +TEST(UtilTest, FormatLongWindowsError) { + LPWSTR message = 0; + // this error code is not available on all Windows platforms and + // Windows SDKs, so do not fail the test if the error string cannot + // be retrieved. + const int provisioning_not_allowed = + 0x80284013L /*TBS_E_PROVISIONING_NOT_ALLOWED*/; + if (FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER | + FORMAT_MESSAGE_FROM_SYSTEM | + FORMAT_MESSAGE_IGNORE_INSERTS, + 0, static_cast<DWORD>(provisioning_not_allowed), + MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), + reinterpret_cast<LPWSTR>(&message), 0, 0) == 0) { + return; + } fmt::detail::utf16_to_utf8 utf8_message(message); - LocalFree(message); - fmt::memory_buffer actual_message; + LocalFree(message); + fmt::memory_buffer actual_message; fmt::detail::format_windows_error(actual_message, provisioning_not_allowed, "test"); - EXPECT_EQ(fmt::format("test: {}", utf8_message.str()), - fmt::to_string(actual_message)); -} - -TEST(UtilTest, WindowsError) { - fmt::system_error error(0, ""); - try { - throw fmt::windows_error(ERROR_FILE_EXISTS, "test {}", "error"); - } catch (const fmt::system_error& e) { - error = e; - } - fmt::memory_buffer message; + EXPECT_EQ(fmt::format("test: {}", utf8_message.str()), + fmt::to_string(actual_message)); +} + +TEST(UtilTest, WindowsError) { + fmt::system_error error(0, ""); + try { + throw fmt::windows_error(ERROR_FILE_EXISTS, "test {}", "error"); + } catch (const fmt::system_error& e) { + error = e; + } + fmt::memory_buffer message; fmt::detail::format_windows_error(message, ERROR_FILE_EXISTS, "test error"); - EXPECT_EQ(to_string(message), error.what()); - EXPECT_EQ(ERROR_FILE_EXISTS, error.error_code()); -} - -TEST(UtilTest, ReportWindowsError) { - fmt::memory_buffer out; + EXPECT_EQ(to_string(message), error.what()); + EXPECT_EQ(ERROR_FILE_EXISTS, error.error_code()); +} + +TEST(UtilTest, ReportWindowsError) { + fmt::memory_buffer out; fmt::detail::format_windows_error(out, ERROR_FILE_EXISTS, "test error"); - out.push_back('\n'); - EXPECT_WRITE(stderr, - fmt::report_windows_error(ERROR_FILE_EXISTS, "test error"), - fmt::to_string(out)); -} - -#endif // _WIN32 - -#if FMT_USE_FCNTL - -using fmt::file; - -// Checks if the file is open by reading one character from it. -static bool isopen(int fd) { - char buffer; - return FMT_POSIX(read(fd, &buffer, 1)) == 1; -} - -static bool isclosed(int fd) { - char buffer; - std::streamsize result = 0; - SUPPRESS_ASSERT(result = FMT_POSIX(read(fd, &buffer, 1))); - return result == -1 && errno == EBADF; -} - -// Opens a file for reading. -static file open_file() { - file read_end, write_end; - file::pipe(read_end, write_end); - write_end.write(FILE_CONTENT, std::strlen(FILE_CONTENT)); - write_end.close(); - return read_end; -} - -// Attempts to write a string to a file. -static void write(file& f, fmt::string_view s) { + out.push_back('\n'); + EXPECT_WRITE(stderr, + fmt::report_windows_error(ERROR_FILE_EXISTS, "test error"), + fmt::to_string(out)); +} + +#endif // _WIN32 + +#if FMT_USE_FCNTL + +using fmt::file; + +// Checks if the file is open by reading one character from it. +static bool isopen(int fd) { + char buffer; + return FMT_POSIX(read(fd, &buffer, 1)) == 1; +} + +static bool isclosed(int fd) { + char buffer; + std::streamsize result = 0; + SUPPRESS_ASSERT(result = FMT_POSIX(read(fd, &buffer, 1))); + return result == -1 && errno == EBADF; +} + +// Opens a file for reading. +static file open_file() { + file read_end, write_end; + file::pipe(read_end, write_end); + write_end.write(FILE_CONTENT, std::strlen(FILE_CONTENT)); + write_end.close(); + return read_end; +} + +// Attempts to write a string to a file. +static void write(file& f, fmt::string_view s) { size_t num_chars_left = s.size(); - const char* ptr = s.data(); - do { + const char* ptr = s.data(); + do { size_t count = f.write(ptr, num_chars_left); - ptr += count; - // We can't write more than size_t bytes since num_chars_left - // has type size_t. - num_chars_left -= count; - } while (num_chars_left != 0); -} - -TEST(BufferedFileTest, DefaultCtor) { - buffered_file f; - EXPECT_TRUE(f.get() == nullptr); -} - -TEST(BufferedFileTest, MoveCtor) { - buffered_file bf = open_buffered_file(); - FILE* fp = bf.get(); - EXPECT_TRUE(fp != nullptr); - buffered_file bf2(std::move(bf)); - EXPECT_EQ(fp, bf2.get()); - EXPECT_TRUE(bf.get() == nullptr); -} - -TEST(BufferedFileTest, MoveAssignment) { - buffered_file bf = open_buffered_file(); - FILE* fp = bf.get(); - EXPECT_TRUE(fp != nullptr); - buffered_file bf2; - bf2 = std::move(bf); - EXPECT_EQ(fp, bf2.get()); - EXPECT_TRUE(bf.get() == nullptr); -} - -TEST(BufferedFileTest, MoveAssignmentClosesFile) { - buffered_file bf = open_buffered_file(); - buffered_file bf2 = open_buffered_file(); - int old_fd = bf2.fileno(); - bf2 = std::move(bf); - EXPECT_TRUE(isclosed(old_fd)); -} - -TEST(BufferedFileTest, MoveFromTemporaryInCtor) { - FILE* fp = nullptr; - buffered_file f(open_buffered_file(&fp)); - EXPECT_EQ(fp, f.get()); -} - -TEST(BufferedFileTest, MoveFromTemporaryInAssignment) { - FILE* fp = nullptr; - buffered_file f; - f = open_buffered_file(&fp); - EXPECT_EQ(fp, f.get()); -} - -TEST(BufferedFileTest, MoveFromTemporaryInAssignmentClosesFile) { - buffered_file f = open_buffered_file(); - int old_fd = f.fileno(); - f = open_buffered_file(); - EXPECT_TRUE(isclosed(old_fd)); -} - -TEST(BufferedFileTest, CloseFileInDtor) { - int fd = 0; - { - buffered_file f = open_buffered_file(); - fd = f.fileno(); - } - EXPECT_TRUE(isclosed(fd)); -} - -TEST(BufferedFileTest, CloseErrorInDtor) { - std::unique_ptr<buffered_file> f(new buffered_file(open_buffered_file())); + ptr += count; + // We can't write more than size_t bytes since num_chars_left + // has type size_t. + num_chars_left -= count; + } while (num_chars_left != 0); +} + +TEST(BufferedFileTest, DefaultCtor) { + buffered_file f; + EXPECT_TRUE(f.get() == nullptr); +} + +TEST(BufferedFileTest, MoveCtor) { + buffered_file bf = open_buffered_file(); + FILE* fp = bf.get(); + EXPECT_TRUE(fp != nullptr); + buffered_file bf2(std::move(bf)); + EXPECT_EQ(fp, bf2.get()); + EXPECT_TRUE(bf.get() == nullptr); +} + +TEST(BufferedFileTest, MoveAssignment) { + buffered_file bf = open_buffered_file(); + FILE* fp = bf.get(); + EXPECT_TRUE(fp != nullptr); + buffered_file bf2; + bf2 = std::move(bf); + EXPECT_EQ(fp, bf2.get()); + EXPECT_TRUE(bf.get() == nullptr); +} + +TEST(BufferedFileTest, MoveAssignmentClosesFile) { + buffered_file bf = open_buffered_file(); + buffered_file bf2 = open_buffered_file(); + int old_fd = bf2.fileno(); + bf2 = std::move(bf); + EXPECT_TRUE(isclosed(old_fd)); +} + +TEST(BufferedFileTest, MoveFromTemporaryInCtor) { + FILE* fp = nullptr; + buffered_file f(open_buffered_file(&fp)); + EXPECT_EQ(fp, f.get()); +} + +TEST(BufferedFileTest, MoveFromTemporaryInAssignment) { + FILE* fp = nullptr; + buffered_file f; + f = open_buffered_file(&fp); + EXPECT_EQ(fp, f.get()); +} + +TEST(BufferedFileTest, MoveFromTemporaryInAssignmentClosesFile) { + buffered_file f = open_buffered_file(); + int old_fd = f.fileno(); + f = open_buffered_file(); + EXPECT_TRUE(isclosed(old_fd)); +} + +TEST(BufferedFileTest, CloseFileInDtor) { + int fd = 0; + { + buffered_file f = open_buffered_file(); + fd = f.fileno(); + } + EXPECT_TRUE(isclosed(fd)); +} + +TEST(BufferedFileTest, CloseErrorInDtor) { + std::unique_ptr<buffered_file> f(new buffered_file(open_buffered_file())); EXPECT_WRITE( stderr, { @@ -249,44 +249,44 @@ TEST(BufferedFileTest, CloseErrorInDtor) { SUPPRESS_ASSERT(f.reset(nullptr)); }, format_system_error(EBADF, "cannot close file") + "\n"); -} - -TEST(BufferedFileTest, Close) { - buffered_file f = open_buffered_file(); - int fd = f.fileno(); - f.close(); - EXPECT_TRUE(f.get() == nullptr); - EXPECT_TRUE(isclosed(fd)); -} - -TEST(BufferedFileTest, CloseError) { - buffered_file f = open_buffered_file(); - FMT_POSIX(close(f.fileno())); - EXPECT_SYSTEM_ERROR_NOASSERT(f.close(), EBADF, "cannot close file"); - EXPECT_TRUE(f.get() == nullptr); -} - -TEST(BufferedFileTest, Fileno) { - buffered_file f; -# ifndef __COVERITY__ - // fileno on a null FILE pointer either crashes or returns an error. - // Disable Coverity because this is intentional. - EXPECT_DEATH_IF_SUPPORTED( - { - try { - f.fileno(); - } catch (const fmt::system_error&) { - std::exit(1); - } - }, - ""); -# endif - f = open_buffered_file(); - EXPECT_TRUE(f.fileno() != -1); - file copy = file::dup(f.fileno()); - EXPECT_READ(copy, FILE_CONTENT); -} - +} + +TEST(BufferedFileTest, Close) { + buffered_file f = open_buffered_file(); + int fd = f.fileno(); + f.close(); + EXPECT_TRUE(f.get() == nullptr); + EXPECT_TRUE(isclosed(fd)); +} + +TEST(BufferedFileTest, CloseError) { + buffered_file f = open_buffered_file(); + FMT_POSIX(close(f.fileno())); + EXPECT_SYSTEM_ERROR_NOASSERT(f.close(), EBADF, "cannot close file"); + EXPECT_TRUE(f.get() == nullptr); +} + +TEST(BufferedFileTest, Fileno) { + buffered_file f; +# ifndef __COVERITY__ + // fileno on a null FILE pointer either crashes or returns an error. + // Disable Coverity because this is intentional. + EXPECT_DEATH_IF_SUPPORTED( + { + try { + f.fileno(); + } catch (const fmt::system_error&) { + std::exit(1); + } + }, + ""); +# endif + f = open_buffered_file(); + EXPECT_TRUE(f.fileno() != -1); + file copy = file::dup(f.fileno()); + EXPECT_READ(copy, FILE_CONTENT); +} + TEST(OStreamTest, Move) { fmt::ostream out = fmt::output_file("test-file"); fmt::ostream moved(std::move(out)); @@ -319,89 +319,89 @@ TEST(OStreamTest, BufferSize) { EXPECT_READ(in, "foo"); } -TEST(FileTest, DefaultCtor) { - file f; - EXPECT_EQ(-1, f.descriptor()); -} - -TEST(FileTest, OpenBufferedFileInCtor) { - FILE* fp = safe_fopen("test-file", "w"); - std::fputs(FILE_CONTENT, fp); - std::fclose(fp); - file f("test-file", file::RDONLY); - ASSERT_TRUE(isopen(f.descriptor())); -} - -TEST(FileTest, OpenBufferedFileError) { - EXPECT_SYSTEM_ERROR(file("nonexistent", file::RDONLY), ENOENT, - "cannot open file nonexistent"); -} - -TEST(FileTest, MoveCtor) { - file f = open_file(); - int fd = f.descriptor(); - EXPECT_NE(-1, fd); - file f2(std::move(f)); - EXPECT_EQ(fd, f2.descriptor()); - EXPECT_EQ(-1, f.descriptor()); -} - -TEST(FileTest, MoveAssignment) { - file f = open_file(); - int fd = f.descriptor(); - EXPECT_NE(-1, fd); - file f2; - f2 = std::move(f); - EXPECT_EQ(fd, f2.descriptor()); - EXPECT_EQ(-1, f.descriptor()); -} - -TEST(FileTest, MoveAssignmentClosesFile) { - file f = open_file(); - file f2 = open_file(); - int old_fd = f2.descriptor(); - f2 = std::move(f); - EXPECT_TRUE(isclosed(old_fd)); -} - -static file OpenBufferedFile(int& fd) { - file f = open_file(); - fd = f.descriptor(); - return f; -} - -TEST(FileTest, MoveFromTemporaryInCtor) { - int fd = 0xdead; - file f(OpenBufferedFile(fd)); - EXPECT_EQ(fd, f.descriptor()); -} - -TEST(FileTest, MoveFromTemporaryInAssignment) { - int fd = 0xdead; - file f; - f = OpenBufferedFile(fd); - EXPECT_EQ(fd, f.descriptor()); -} - -TEST(FileTest, MoveFromTemporaryInAssignmentClosesFile) { - int fd = 0xdead; - file f = open_file(); - int old_fd = f.descriptor(); - f = OpenBufferedFile(fd); - EXPECT_TRUE(isclosed(old_fd)); -} - -TEST(FileTest, CloseFileInDtor) { - int fd = 0; - { - file f = open_file(); - fd = f.descriptor(); - } - EXPECT_TRUE(isclosed(fd)); -} - -TEST(FileTest, CloseErrorInDtor) { - std::unique_ptr<file> f(new file(open_file())); +TEST(FileTest, DefaultCtor) { + file f; + EXPECT_EQ(-1, f.descriptor()); +} + +TEST(FileTest, OpenBufferedFileInCtor) { + FILE* fp = safe_fopen("test-file", "w"); + std::fputs(FILE_CONTENT, fp); + std::fclose(fp); + file f("test-file", file::RDONLY); + ASSERT_TRUE(isopen(f.descriptor())); +} + +TEST(FileTest, OpenBufferedFileError) { + EXPECT_SYSTEM_ERROR(file("nonexistent", file::RDONLY), ENOENT, + "cannot open file nonexistent"); +} + +TEST(FileTest, MoveCtor) { + file f = open_file(); + int fd = f.descriptor(); + EXPECT_NE(-1, fd); + file f2(std::move(f)); + EXPECT_EQ(fd, f2.descriptor()); + EXPECT_EQ(-1, f.descriptor()); +} + +TEST(FileTest, MoveAssignment) { + file f = open_file(); + int fd = f.descriptor(); + EXPECT_NE(-1, fd); + file f2; + f2 = std::move(f); + EXPECT_EQ(fd, f2.descriptor()); + EXPECT_EQ(-1, f.descriptor()); +} + +TEST(FileTest, MoveAssignmentClosesFile) { + file f = open_file(); + file f2 = open_file(); + int old_fd = f2.descriptor(); + f2 = std::move(f); + EXPECT_TRUE(isclosed(old_fd)); +} + +static file OpenBufferedFile(int& fd) { + file f = open_file(); + fd = f.descriptor(); + return f; +} + +TEST(FileTest, MoveFromTemporaryInCtor) { + int fd = 0xdead; + file f(OpenBufferedFile(fd)); + EXPECT_EQ(fd, f.descriptor()); +} + +TEST(FileTest, MoveFromTemporaryInAssignment) { + int fd = 0xdead; + file f; + f = OpenBufferedFile(fd); + EXPECT_EQ(fd, f.descriptor()); +} + +TEST(FileTest, MoveFromTemporaryInAssignmentClosesFile) { + int fd = 0xdead; + file f = open_file(); + int old_fd = f.descriptor(); + f = OpenBufferedFile(fd); + EXPECT_TRUE(isclosed(old_fd)); +} + +TEST(FileTest, CloseFileInDtor) { + int fd = 0; + { + file f = open_file(); + fd = f.descriptor(); + } + EXPECT_TRUE(isclosed(fd)); +} + +TEST(FileTest, CloseErrorInDtor) { + std::unique_ptr<file> f(new file(open_file())); EXPECT_WRITE( stderr, { @@ -413,120 +413,120 @@ TEST(FileTest, CloseErrorInDtor) { SUPPRESS_ASSERT(f.reset(nullptr)); }, format_system_error(EBADF, "cannot close file") + "\n"); -} - -TEST(FileTest, Close) { - file f = open_file(); - int fd = f.descriptor(); - f.close(); - EXPECT_EQ(-1, f.descriptor()); - EXPECT_TRUE(isclosed(fd)); -} - -TEST(FileTest, CloseError) { - file f = open_file(); - FMT_POSIX(close(f.descriptor())); - EXPECT_SYSTEM_ERROR_NOASSERT(f.close(), EBADF, "cannot close file"); - EXPECT_EQ(-1, f.descriptor()); -} - -TEST(FileTest, Read) { - file f = open_file(); - EXPECT_READ(f, FILE_CONTENT); -} - -TEST(FileTest, ReadError) { - file f("test-file", file::WRONLY); - char buf; - // We intentionally read from a file opened in the write-only mode to - // cause error. - EXPECT_SYSTEM_ERROR(f.read(&buf, 1), EBADF, "cannot read from file"); -} - -TEST(FileTest, Write) { - file read_end, write_end; - file::pipe(read_end, write_end); - write(write_end, "test"); - write_end.close(); - EXPECT_READ(read_end, "test"); -} - -TEST(FileTest, WriteError) { - file f("test-file", file::RDONLY); - // We intentionally write to a file opened in the read-only mode to - // cause error. - EXPECT_SYSTEM_ERROR(f.write(" ", 1), EBADF, "cannot write to file"); -} - -TEST(FileTest, Dup) { - file f = open_file(); - file copy = file::dup(f.descriptor()); - EXPECT_NE(f.descriptor(), copy.descriptor()); - EXPECT_EQ(FILE_CONTENT, read(copy, std::strlen(FILE_CONTENT))); -} - -# ifndef __COVERITY__ -TEST(FileTest, DupError) { - int value = -1; - EXPECT_SYSTEM_ERROR_NOASSERT(file::dup(value), EBADF, - "cannot duplicate file descriptor -1"); -} -# endif - -TEST(FileTest, Dup2) { - file f = open_file(); - file copy = open_file(); - f.dup2(copy.descriptor()); - EXPECT_NE(f.descriptor(), copy.descriptor()); - EXPECT_READ(copy, FILE_CONTENT); -} - -TEST(FileTest, Dup2Error) { - file f = open_file(); - EXPECT_SYSTEM_ERROR_NOASSERT( - f.dup2(-1), EBADF, - fmt::format("cannot duplicate file descriptor {} to -1", f.descriptor())); -} - -TEST(FileTest, Dup2NoExcept) { - file f = open_file(); - file copy = open_file(); - error_code ec; - f.dup2(copy.descriptor(), ec); - EXPECT_EQ(ec.get(), 0); - EXPECT_NE(f.descriptor(), copy.descriptor()); - EXPECT_READ(copy, FILE_CONTENT); -} - -TEST(FileTest, Dup2NoExceptError) { - file f = open_file(); - error_code ec; - SUPPRESS_ASSERT(f.dup2(-1, ec)); - EXPECT_EQ(EBADF, ec.get()); -} - -TEST(FileTest, Pipe) { - file read_end, write_end; - file::pipe(read_end, write_end); - EXPECT_NE(-1, read_end.descriptor()); - EXPECT_NE(-1, write_end.descriptor()); - write(write_end, "test"); - EXPECT_READ(read_end, "test"); -} - -TEST(FileTest, Fdopen) { - file read_end, write_end; - file::pipe(read_end, write_end); - int read_fd = read_end.descriptor(); - EXPECT_EQ(read_fd, FMT_POSIX(fileno(read_end.fdopen("r").get()))); -} - -# ifdef FMT_LOCALE -TEST(LocaleTest, Strtod) { - fmt::locale loc; - const char *start = "4.2", *ptr = start; - EXPECT_EQ(4.2, loc.strtod(ptr)); - EXPECT_EQ(start + 3, ptr); -} -# endif +} + +TEST(FileTest, Close) { + file f = open_file(); + int fd = f.descriptor(); + f.close(); + EXPECT_EQ(-1, f.descriptor()); + EXPECT_TRUE(isclosed(fd)); +} + +TEST(FileTest, CloseError) { + file f = open_file(); + FMT_POSIX(close(f.descriptor())); + EXPECT_SYSTEM_ERROR_NOASSERT(f.close(), EBADF, "cannot close file"); + EXPECT_EQ(-1, f.descriptor()); +} + +TEST(FileTest, Read) { + file f = open_file(); + EXPECT_READ(f, FILE_CONTENT); +} + +TEST(FileTest, ReadError) { + file f("test-file", file::WRONLY); + char buf; + // We intentionally read from a file opened in the write-only mode to + // cause error. + EXPECT_SYSTEM_ERROR(f.read(&buf, 1), EBADF, "cannot read from file"); +} + +TEST(FileTest, Write) { + file read_end, write_end; + file::pipe(read_end, write_end); + write(write_end, "test"); + write_end.close(); + EXPECT_READ(read_end, "test"); +} + +TEST(FileTest, WriteError) { + file f("test-file", file::RDONLY); + // We intentionally write to a file opened in the read-only mode to + // cause error. + EXPECT_SYSTEM_ERROR(f.write(" ", 1), EBADF, "cannot write to file"); +} + +TEST(FileTest, Dup) { + file f = open_file(); + file copy = file::dup(f.descriptor()); + EXPECT_NE(f.descriptor(), copy.descriptor()); + EXPECT_EQ(FILE_CONTENT, read(copy, std::strlen(FILE_CONTENT))); +} + +# ifndef __COVERITY__ +TEST(FileTest, DupError) { + int value = -1; + EXPECT_SYSTEM_ERROR_NOASSERT(file::dup(value), EBADF, + "cannot duplicate file descriptor -1"); +} +# endif + +TEST(FileTest, Dup2) { + file f = open_file(); + file copy = open_file(); + f.dup2(copy.descriptor()); + EXPECT_NE(f.descriptor(), copy.descriptor()); + EXPECT_READ(copy, FILE_CONTENT); +} + +TEST(FileTest, Dup2Error) { + file f = open_file(); + EXPECT_SYSTEM_ERROR_NOASSERT( + f.dup2(-1), EBADF, + fmt::format("cannot duplicate file descriptor {} to -1", f.descriptor())); +} + +TEST(FileTest, Dup2NoExcept) { + file f = open_file(); + file copy = open_file(); + error_code ec; + f.dup2(copy.descriptor(), ec); + EXPECT_EQ(ec.get(), 0); + EXPECT_NE(f.descriptor(), copy.descriptor()); + EXPECT_READ(copy, FILE_CONTENT); +} + +TEST(FileTest, Dup2NoExceptError) { + file f = open_file(); + error_code ec; + SUPPRESS_ASSERT(f.dup2(-1, ec)); + EXPECT_EQ(EBADF, ec.get()); +} + +TEST(FileTest, Pipe) { + file read_end, write_end; + file::pipe(read_end, write_end); + EXPECT_NE(-1, read_end.descriptor()); + EXPECT_NE(-1, write_end.descriptor()); + write(write_end, "test"); + EXPECT_READ(read_end, "test"); +} + +TEST(FileTest, Fdopen) { + file read_end, write_end; + file::pipe(read_end, write_end); + int read_fd = read_end.descriptor(); + EXPECT_EQ(read_fd, FMT_POSIX(fileno(read_end.fdopen("r").get()))); +} + +# ifdef FMT_LOCALE +TEST(LocaleTest, Strtod) { + fmt::locale loc; + const char *start = "4.2", *ptr = start; + EXPECT_EQ(4.2, loc.strtod(ptr)); + EXPECT_EQ(start + 3, ptr); +} +# endif #endif // FMT_USE_FCNTL diff --git a/contrib/libs/fmt/test/os-test/ya.make b/contrib/libs/fmt/test/os-test/ya.make index c0d5749207..34228bb26b 100644 --- a/contrib/libs/fmt/test/os-test/ya.make +++ b/contrib/libs/fmt/test/os-test/ya.make @@ -1,37 +1,37 @@ -# Generated by devtools/yamaker. - +# Generated by devtools/yamaker. + GTEST() - + WITHOUT_LICENSE_TEXTS() - + OWNER( orivej g:cpp-contrib ) -LICENSE(MIT) - -PEERDIR( - contrib/libs/fmt - contrib/libs/fmt/test -) - -NO_COMPILER_WARNINGS() - -NO_UTIL() - -CFLAGS( - -DFMT_LOCALE - -DFMT_SHARED - -DGTEST_HAS_STD_WSTRING=1 - -DGTEST_LANG_CXX11=0 - -D_SILENCE_TR1_NAMESPACE_DEPRECATION_WARNING=1 -) - -SRCDIR(contrib/libs/fmt/test) - -SRCS( - os-test.cc -) - -END() +LICENSE(MIT) + +PEERDIR( + contrib/libs/fmt + contrib/libs/fmt/test +) + +NO_COMPILER_WARNINGS() + +NO_UTIL() + +CFLAGS( + -DFMT_LOCALE + -DFMT_SHARED + -DGTEST_HAS_STD_WSTRING=1 + -DGTEST_LANG_CXX11=0 + -D_SILENCE_TR1_NAMESPACE_DEPRECATION_WARNING=1 +) + +SRCDIR(contrib/libs/fmt/test) + +SRCS( + os-test.cc +) + +END() diff --git a/contrib/libs/fmt/test/ostream-test.cc b/contrib/libs/fmt/test/ostream-test.cc index 7ec8515baf..4cef5a78c4 100644 --- a/contrib/libs/fmt/test/ostream-test.cc +++ b/contrib/libs/fmt/test/ostream-test.cc @@ -1,297 +1,297 @@ -// Formatting library for C++ - std::ostream support tests -// -// Copyright (c) 2012 - present, Victor Zverovich -// All rights reserved. -// -// For the license information refer to format.h. - -#include "fmt/format.h" - -struct test {}; - -// Test that there is no issues with specializations when fmt/ostream.h is -// included after fmt/format.h. -namespace fmt { -template <> struct formatter<test> : formatter<int> { - template <typename FormatContext> - typename FormatContext::iterator format(const test&, FormatContext& ctx) { - return formatter<int>::format(42, ctx); - } -}; -} // namespace fmt - +// Formatting library for C++ - std::ostream support tests +// +// Copyright (c) 2012 - present, Victor Zverovich +// All rights reserved. +// +// For the license information refer to format.h. + +#include "fmt/format.h" + +struct test {}; + +// Test that there is no issues with specializations when fmt/ostream.h is +// included after fmt/format.h. +namespace fmt { +template <> struct formatter<test> : formatter<int> { + template <typename FormatContext> + typename FormatContext::iterator format(const test&, FormatContext& ctx) { + return formatter<int>::format(42, ctx); + } +}; +} // namespace fmt + #include <sstream> -#include "fmt/ostream.h" +#include "fmt/ostream.h" #include "fmt/ranges.h" -#include <gmock/gmock.h> -#include "gtest-extra.h" -#include "util.h" - -using fmt::format; -using fmt::format_error; - -static std::ostream& operator<<(std::ostream& os, const Date& d) { - os << d.year() << '-' << d.month() << '-' << d.day(); - return os; -} - -static std::wostream& operator<<(std::wostream& os, const Date& d) { - os << d.year() << L'-' << d.month() << L'-' << d.day(); - return os; -} - -// Make sure that overloaded comma operators do no harm to is_streamable. -struct type_with_comma_op {}; -template <typename T> void operator,(type_with_comma_op, const T&); -template <typename T> type_with_comma_op operator<<(T&, const Date&); - -enum streamable_enum {}; -static std::ostream& operator<<(std::ostream& os, streamable_enum) { - return os << "streamable_enum"; -} - -static std::wostream& operator<<(std::wostream& os, streamable_enum) { - return os << L"streamable_enum"; -} - -enum unstreamable_enum {}; - -TEST(OStreamTest, Enum) { - EXPECT_EQ("streamable_enum", fmt::format("{}", streamable_enum())); - EXPECT_EQ("0", fmt::format("{}", unstreamable_enum())); - EXPECT_EQ(L"streamable_enum", fmt::format(L"{}", streamable_enum())); - EXPECT_EQ(L"0", fmt::format(L"{}", unstreamable_enum())); -} - +#include <gmock/gmock.h> +#include "gtest-extra.h" +#include "util.h" + +using fmt::format; +using fmt::format_error; + +static std::ostream& operator<<(std::ostream& os, const Date& d) { + os << d.year() << '-' << d.month() << '-' << d.day(); + return os; +} + +static std::wostream& operator<<(std::wostream& os, const Date& d) { + os << d.year() << L'-' << d.month() << L'-' << d.day(); + return os; +} + +// Make sure that overloaded comma operators do no harm to is_streamable. +struct type_with_comma_op {}; +template <typename T> void operator,(type_with_comma_op, const T&); +template <typename T> type_with_comma_op operator<<(T&, const Date&); + +enum streamable_enum {}; +static std::ostream& operator<<(std::ostream& os, streamable_enum) { + return os << "streamable_enum"; +} + +static std::wostream& operator<<(std::wostream& os, streamable_enum) { + return os << L"streamable_enum"; +} + +enum unstreamable_enum {}; + +TEST(OStreamTest, Enum) { + EXPECT_EQ("streamable_enum", fmt::format("{}", streamable_enum())); + EXPECT_EQ("0", fmt::format("{}", unstreamable_enum())); + EXPECT_EQ(L"streamable_enum", fmt::format(L"{}", streamable_enum())); + EXPECT_EQ(L"0", fmt::format(L"{}", unstreamable_enum())); +} + struct test_arg_formatter : fmt::detail::arg_formatter<fmt::format_context::iterator, char> { - fmt::format_parse_context parse_ctx; - test_arg_formatter(fmt::format_context& ctx, fmt::format_specs& s) + fmt::format_parse_context parse_ctx; + test_arg_formatter(fmt::format_context& ctx, fmt::format_specs& s) : fmt::detail::arg_formatter<fmt::format_context::iterator, char>( ctx, &parse_ctx, &s), parse_ctx("") {} -}; - -TEST(OStreamTest, CustomArg) { - fmt::memory_buffer buffer; +}; + +TEST(OStreamTest, CustomArg) { + fmt::memory_buffer buffer; fmt::format_context ctx(fmt::detail::buffer_appender<char>{buffer}, fmt::format_args()); - fmt::format_specs spec; - test_arg_formatter af(ctx, spec); - fmt::visit_format_arg( + fmt::format_specs spec; + test_arg_formatter af(ctx, spec); + fmt::visit_format_arg( af, fmt::detail::make_arg<fmt::format_context>(streamable_enum())); - EXPECT_EQ("streamable_enum", std::string(buffer.data(), buffer.size())); -} - -TEST(OStreamTest, Format) { - EXPECT_EQ("a string", format("{0}", TestString("a string"))); - std::string s = format("The date is {0}", Date(2012, 12, 9)); - EXPECT_EQ("The date is 2012-12-9", s); - Date date(2012, 12, 9); - EXPECT_EQ(L"The date is 2012-12-9", - format(L"The date is {0}", Date(2012, 12, 9))); -} - -TEST(OStreamTest, FormatSpecs) { - EXPECT_EQ("def ", format("{0:<5}", TestString("def"))); - EXPECT_EQ(" def", format("{0:>5}", TestString("def"))); + EXPECT_EQ("streamable_enum", std::string(buffer.data(), buffer.size())); +} + +TEST(OStreamTest, Format) { + EXPECT_EQ("a string", format("{0}", TestString("a string"))); + std::string s = format("The date is {0}", Date(2012, 12, 9)); + EXPECT_EQ("The date is 2012-12-9", s); + Date date(2012, 12, 9); + EXPECT_EQ(L"The date is 2012-12-9", + format(L"The date is {0}", Date(2012, 12, 9))); +} + +TEST(OStreamTest, FormatSpecs) { + EXPECT_EQ("def ", format("{0:<5}", TestString("def"))); + EXPECT_EQ(" def", format("{0:>5}", TestString("def"))); #if FMT_DEPRECATED_NUMERIC_ALIGN - EXPECT_THROW_MSG(format("{0:=5}", TestString("def")), format_error, - "format specifier requires numeric argument"); -#endif - EXPECT_EQ(" def ", format("{0:^5}", TestString("def"))); - EXPECT_EQ("def**", format("{0:*<5}", TestString("def"))); - EXPECT_THROW_MSG(format("{0:+}", TestString()), format_error, - "format specifier requires numeric argument"); - EXPECT_THROW_MSG(format("{0:-}", TestString()), format_error, - "format specifier requires numeric argument"); - EXPECT_THROW_MSG(format("{0: }", TestString()), format_error, - "format specifier requires numeric argument"); - EXPECT_THROW_MSG(format("{0:#}", TestString()), format_error, - "format specifier requires numeric argument"); - EXPECT_THROW_MSG(format("{0:05}", TestString()), format_error, - "format specifier requires numeric argument"); - EXPECT_EQ("test ", format("{0:13}", TestString("test"))); - EXPECT_EQ("test ", format("{0:{1}}", TestString("test"), 13)); - EXPECT_EQ("te", format("{0:.2}", TestString("test"))); - EXPECT_EQ("te", format("{0:.{1}}", TestString("test"), 2)); -} - -struct EmptyTest {}; -static std::ostream& operator<<(std::ostream& os, EmptyTest) { - return os << ""; -} - -TEST(OStreamTest, EmptyCustomOutput) { - EXPECT_EQ("", fmt::format("{}", EmptyTest())); -} - -TEST(OStreamTest, Print) { - std::ostringstream os; - fmt::print(os, "Don't {}!", "panic"); - EXPECT_EQ("Don't panic!", os.str()); - std::wostringstream wos; - fmt::print(wos, L"Don't {}!", L"panic"); - EXPECT_EQ(L"Don't panic!", wos.str()); -} - -TEST(OStreamTest, WriteToOStream) { - std::ostringstream os; - fmt::memory_buffer buffer; - const char* foo = "foo"; - buffer.append(foo, foo + std::strlen(foo)); + EXPECT_THROW_MSG(format("{0:=5}", TestString("def")), format_error, + "format specifier requires numeric argument"); +#endif + EXPECT_EQ(" def ", format("{0:^5}", TestString("def"))); + EXPECT_EQ("def**", format("{0:*<5}", TestString("def"))); + EXPECT_THROW_MSG(format("{0:+}", TestString()), format_error, + "format specifier requires numeric argument"); + EXPECT_THROW_MSG(format("{0:-}", TestString()), format_error, + "format specifier requires numeric argument"); + EXPECT_THROW_MSG(format("{0: }", TestString()), format_error, + "format specifier requires numeric argument"); + EXPECT_THROW_MSG(format("{0:#}", TestString()), format_error, + "format specifier requires numeric argument"); + EXPECT_THROW_MSG(format("{0:05}", TestString()), format_error, + "format specifier requires numeric argument"); + EXPECT_EQ("test ", format("{0:13}", TestString("test"))); + EXPECT_EQ("test ", format("{0:{1}}", TestString("test"), 13)); + EXPECT_EQ("te", format("{0:.2}", TestString("test"))); + EXPECT_EQ("te", format("{0:.{1}}", TestString("test"), 2)); +} + +struct EmptyTest {}; +static std::ostream& operator<<(std::ostream& os, EmptyTest) { + return os << ""; +} + +TEST(OStreamTest, EmptyCustomOutput) { + EXPECT_EQ("", fmt::format("{}", EmptyTest())); +} + +TEST(OStreamTest, Print) { + std::ostringstream os; + fmt::print(os, "Don't {}!", "panic"); + EXPECT_EQ("Don't panic!", os.str()); + std::wostringstream wos; + fmt::print(wos, L"Don't {}!", L"panic"); + EXPECT_EQ(L"Don't panic!", wos.str()); +} + +TEST(OStreamTest, WriteToOStream) { + std::ostringstream os; + fmt::memory_buffer buffer; + const char* foo = "foo"; + buffer.append(foo, foo + std::strlen(foo)); fmt::detail::write_buffer(os, buffer); - EXPECT_EQ("foo", os.str()); -} - -TEST(OStreamTest, WriteToOStreamMaxSize) { + EXPECT_EQ("foo", os.str()); +} + +TEST(OStreamTest, WriteToOStreamMaxSize) { size_t max_size = fmt::detail::max_value<size_t>(); std::streamsize max_streamsize = fmt::detail::max_value<std::streamsize>(); if (max_size <= fmt::detail::to_unsigned(max_streamsize)) return; - + struct test_buffer final : fmt::detail::buffer<char> { explicit test_buffer(size_t size) : fmt::detail::buffer<char>(nullptr, size, size) {} void grow(size_t) {} - } buffer(max_size); - - struct mock_streambuf : std::streambuf { - MOCK_METHOD2(xsputn, std::streamsize(const void* s, std::streamsize n)); - std::streamsize xsputn(const char* s, std::streamsize n) { - const void* v = s; - return xsputn(v, n); - } - } streambuf; - - struct test_ostream : std::ostream { - explicit test_ostream(mock_streambuf& buffer) : std::ostream(&buffer) {} - } os(streambuf); - - testing::InSequence sequence; - const char* data = nullptr; - typedef std::make_unsigned<std::streamsize>::type ustreamsize; - ustreamsize size = max_size; - do { + } buffer(max_size); + + struct mock_streambuf : std::streambuf { + MOCK_METHOD2(xsputn, std::streamsize(const void* s, std::streamsize n)); + std::streamsize xsputn(const char* s, std::streamsize n) { + const void* v = s; + return xsputn(v, n); + } + } streambuf; + + struct test_ostream : std::ostream { + explicit test_ostream(mock_streambuf& buffer) : std::ostream(&buffer) {} + } os(streambuf); + + testing::InSequence sequence; + const char* data = nullptr; + typedef std::make_unsigned<std::streamsize>::type ustreamsize; + ustreamsize size = max_size; + do { auto n = std::min(size, fmt::detail::to_unsigned(max_streamsize)); - EXPECT_CALL(streambuf, xsputn(data, static_cast<std::streamsize>(n))) - .WillOnce(testing::Return(max_streamsize)); - data += n; - size -= n; - } while (size != 0); + EXPECT_CALL(streambuf, xsputn(data, static_cast<std::streamsize>(n))) + .WillOnce(testing::Return(max_streamsize)); + data += n; + size -= n; + } while (size != 0); fmt::detail::write_buffer(os, buffer); -} - -TEST(OStreamTest, Join) { - int v[3] = {1, 2, 3}; - EXPECT_EQ("1, 2, 3", fmt::format("{}", fmt::join(v, v + 3, ", "))); -} - -#if FMT_USE_CONSTEXPR -TEST(OStreamTest, ConstexprString) { - EXPECT_EQ("42", format(FMT_STRING("{}"), std::string("42"))); - EXPECT_EQ("a string", format(FMT_STRING("{0}"), TestString("a string"))); -} -#endif - -namespace fmt_test { -struct ABC {}; - -template <typename Output> Output& operator<<(Output& out, ABC) { - out << "ABC"; - return out; -} -} // namespace fmt_test - -template <typename T> struct TestTemplate {}; - -template <typename T> -std::ostream& operator<<(std::ostream& os, TestTemplate<T>) { - return os << 1; -} - -namespace fmt { -template <typename T> struct formatter<TestTemplate<T>> : formatter<int> { - template <typename FormatContext> - typename FormatContext::iterator format(TestTemplate<T>, FormatContext& ctx) { - return formatter<int>::format(2, ctx); - } -}; -} // namespace fmt - -#if !FMT_GCC_VERSION || FMT_GCC_VERSION >= 407 -TEST(OStreamTest, Template) { - EXPECT_EQ("2", fmt::format("{}", TestTemplate<int>())); -} - -TEST(FormatTest, FormatToN) { - char buffer[4]; - buffer[3] = 'x'; - auto result = fmt::format_to_n(buffer, 3, "{}", fmt_test::ABC()); - EXPECT_EQ(3u, result.size); - EXPECT_EQ(buffer + 3, result.out); - EXPECT_EQ("ABCx", fmt::string_view(buffer, 4)); - result = fmt::format_to_n(buffer, 3, "x{}y", fmt_test::ABC()); - EXPECT_EQ(5u, result.size); - EXPECT_EQ(buffer + 3, result.out); - EXPECT_EQ("xABx", fmt::string_view(buffer, 4)); -} -#endif - -#if FMT_USE_USER_DEFINED_LITERALS -TEST(FormatTest, UDL) { - using namespace fmt::literals; - EXPECT_EQ("{}"_format("test"), "test"); -} -#endif - -template <typename T> struct convertible { - T value; - explicit convertible(const T& val) : value(val) {} - operator T() const { return value; } -}; - -TEST(OStreamTest, DisableBuiltinOStreamOperators) { - EXPECT_EQ("42", fmt::format("{:d}", convertible<unsigned short>(42))); - EXPECT_EQ(L"42", fmt::format(L"{:d}", convertible<unsigned short>(42))); - EXPECT_EQ("foo", fmt::format("{}", convertible<const char*>("foo"))); -} - -struct explicitly_convertible_to_string_like { - template <typename String, - typename = typename std::enable_if<std::is_constructible< +} + +TEST(OStreamTest, Join) { + int v[3] = {1, 2, 3}; + EXPECT_EQ("1, 2, 3", fmt::format("{}", fmt::join(v, v + 3, ", "))); +} + +#if FMT_USE_CONSTEXPR +TEST(OStreamTest, ConstexprString) { + EXPECT_EQ("42", format(FMT_STRING("{}"), std::string("42"))); + EXPECT_EQ("a string", format(FMT_STRING("{0}"), TestString("a string"))); +} +#endif + +namespace fmt_test { +struct ABC {}; + +template <typename Output> Output& operator<<(Output& out, ABC) { + out << "ABC"; + return out; +} +} // namespace fmt_test + +template <typename T> struct TestTemplate {}; + +template <typename T> +std::ostream& operator<<(std::ostream& os, TestTemplate<T>) { + return os << 1; +} + +namespace fmt { +template <typename T> struct formatter<TestTemplate<T>> : formatter<int> { + template <typename FormatContext> + typename FormatContext::iterator format(TestTemplate<T>, FormatContext& ctx) { + return formatter<int>::format(2, ctx); + } +}; +} // namespace fmt + +#if !FMT_GCC_VERSION || FMT_GCC_VERSION >= 407 +TEST(OStreamTest, Template) { + EXPECT_EQ("2", fmt::format("{}", TestTemplate<int>())); +} + +TEST(FormatTest, FormatToN) { + char buffer[4]; + buffer[3] = 'x'; + auto result = fmt::format_to_n(buffer, 3, "{}", fmt_test::ABC()); + EXPECT_EQ(3u, result.size); + EXPECT_EQ(buffer + 3, result.out); + EXPECT_EQ("ABCx", fmt::string_view(buffer, 4)); + result = fmt::format_to_n(buffer, 3, "x{}y", fmt_test::ABC()); + EXPECT_EQ(5u, result.size); + EXPECT_EQ(buffer + 3, result.out); + EXPECT_EQ("xABx", fmt::string_view(buffer, 4)); +} +#endif + +#if FMT_USE_USER_DEFINED_LITERALS +TEST(FormatTest, UDL) { + using namespace fmt::literals; + EXPECT_EQ("{}"_format("test"), "test"); +} +#endif + +template <typename T> struct convertible { + T value; + explicit convertible(const T& val) : value(val) {} + operator T() const { return value; } +}; + +TEST(OStreamTest, DisableBuiltinOStreamOperators) { + EXPECT_EQ("42", fmt::format("{:d}", convertible<unsigned short>(42))); + EXPECT_EQ(L"42", fmt::format(L"{:d}", convertible<unsigned short>(42))); + EXPECT_EQ("foo", fmt::format("{}", convertible<const char*>("foo"))); +} + +struct explicitly_convertible_to_string_like { + template <typename String, + typename = typename std::enable_if<std::is_constructible< String, const char*, size_t>::value>::type> - explicit operator String() const { - return String("foo", 3u); - } -}; - -std::ostream& operator<<(std::ostream& os, - explicitly_convertible_to_string_like) { - return os << "bar"; -} - + explicit operator String() const { + return String("foo", 3u); + } +}; + +std::ostream& operator<<(std::ostream& os, + explicitly_convertible_to_string_like) { + return os << "bar"; +} + TEST(OStreamTest, FormatExplicitlyConvertibleToStringLike) { - EXPECT_EQ("bar", fmt::format("{}", explicitly_convertible_to_string_like())); -} - -#ifdef FMT_USE_STRING_VIEW -struct explicitly_convertible_to_std_string_view { + EXPECT_EQ("bar", fmt::format("{}", explicitly_convertible_to_string_like())); +} + +#ifdef FMT_USE_STRING_VIEW +struct explicitly_convertible_to_std_string_view { explicit operator fmt::detail::std_string_view<char>() const { - return {"foo", 3u}; - } -}; - -std::ostream& operator<<(std::ostream& os, - explicitly_convertible_to_std_string_view) { - return os << "bar"; -} - + return {"foo", 3u}; + } +}; + +std::ostream& operator<<(std::ostream& os, + explicitly_convertible_to_std_string_view) { + return os << "bar"; +} + TEST(OStreamTest, FormatExplicitlyConvertibleToStdStringView) { - EXPECT_EQ("bar", fmt::format("{}", explicitly_convertible_to_string_like())); -} + EXPECT_EQ("bar", fmt::format("{}", explicitly_convertible_to_string_like())); +} #endif // FMT_USE_STRING_VIEW - + struct streamable_and_convertible_to_bool { operator bool() const { return true; } }; diff --git a/contrib/libs/fmt/test/ostream-test/ya.make b/contrib/libs/fmt/test/ostream-test/ya.make index 2356199159..10921b40d1 100644 --- a/contrib/libs/fmt/test/ostream-test/ya.make +++ b/contrib/libs/fmt/test/ostream-test/ya.make @@ -1,37 +1,37 @@ -# Generated by devtools/yamaker. - +# Generated by devtools/yamaker. + GTEST() - + WITHOUT_LICENSE_TEXTS() - + OWNER( orivej g:cpp-contrib ) -LICENSE(MIT) - -PEERDIR( - contrib/libs/fmt - contrib/libs/fmt/test -) - -NO_COMPILER_WARNINGS() - -NO_UTIL() - -CFLAGS( - -DFMT_LOCALE - -DFMT_SHARED - -DGTEST_HAS_STD_WSTRING=1 - -DGTEST_LANG_CXX11=0 - -D_SILENCE_TR1_NAMESPACE_DEPRECATION_WARNING=1 -) - -SRCDIR(contrib/libs/fmt/test) - -SRCS( - ostream-test.cc -) - -END() +LICENSE(MIT) + +PEERDIR( + contrib/libs/fmt + contrib/libs/fmt/test +) + +NO_COMPILER_WARNINGS() + +NO_UTIL() + +CFLAGS( + -DFMT_LOCALE + -DFMT_SHARED + -DGTEST_HAS_STD_WSTRING=1 + -DGTEST_LANG_CXX11=0 + -D_SILENCE_TR1_NAMESPACE_DEPRECATION_WARNING=1 +) + +SRCDIR(contrib/libs/fmt/test) + +SRCS( + ostream-test.cc +) + +END() diff --git a/contrib/libs/fmt/test/posix-mock-test.cc b/contrib/libs/fmt/test/posix-mock-test.cc index 54f6ab7971..0ea1b9c6d5 100644 --- a/contrib/libs/fmt/test/posix-mock-test.cc +++ b/contrib/libs/fmt/test/posix-mock-test.cc @@ -1,558 +1,558 @@ -// Tests of the C++ interface to POSIX functions that require mocks -// -// Copyright (c) 2012 - present, Victor Zverovich -// All rights reserved. -// -// For the license information refer to format.h. - -// Disable bogus MSVC warnings. -#ifndef _CRT_SECURE_NO_WARNINGS -# define _CRT_SECURE_NO_WARNINGS -#endif - -#include "posix-mock.h" - -#include <errno.h> -#include <fcntl.h> - -#include <climits> -#include <memory> - -#include "../src/os.cc" - -#ifdef _WIN32 -# include <io.h> -# undef max -# undef ERROR -#endif - -#include <gmock/gmock.h> -#include "gtest-extra.h" -#include "util.h" - -using fmt::buffered_file; -using fmt::error_code; - -using testing::_; -using testing::Return; -using testing::StrEq; - -namespace { -int open_count; -int close_count; -int dup_count; -int dup2_count; -int fdopen_count; -int read_count; -int write_count; -int pipe_count; -int fopen_count; -int fclose_count; -int fileno_count; +// Tests of the C++ interface to POSIX functions that require mocks +// +// Copyright (c) 2012 - present, Victor Zverovich +// All rights reserved. +// +// For the license information refer to format.h. + +// Disable bogus MSVC warnings. +#ifndef _CRT_SECURE_NO_WARNINGS +# define _CRT_SECURE_NO_WARNINGS +#endif + +#include "posix-mock.h" + +#include <errno.h> +#include <fcntl.h> + +#include <climits> +#include <memory> + +#include "../src/os.cc" + +#ifdef _WIN32 +# include <io.h> +# undef max +# undef ERROR +#endif + +#include <gmock/gmock.h> +#include "gtest-extra.h" +#include "util.h" + +using fmt::buffered_file; +using fmt::error_code; + +using testing::_; +using testing::Return; +using testing::StrEq; + +namespace { +int open_count; +int close_count; +int dup_count; +int dup2_count; +int fdopen_count; +int read_count; +int write_count; +int pipe_count; +int fopen_count; +int fclose_count; +int fileno_count; size_t read_nbyte; size_t write_nbyte; -bool sysconf_error; - -enum { NONE, MAX_SIZE, ERROR } fstat_sim; -} // namespace - -#define EMULATE_EINTR(func, error_result) \ - if (func##_count != 0) { \ - if (func##_count++ != 3) { \ - errno = EINTR; \ - return error_result; \ - } \ - } - -#ifndef _MSC_VER -int test::open(const char* path, int oflag, int mode) { - EMULATE_EINTR(open, -1); - return ::open(path, oflag, mode); -} -#else -errno_t test::sopen_s(int* pfh, const char* filename, int oflag, int shflag, - int pmode) { - EMULATE_EINTR(open, EINTR); - return _sopen_s(pfh, filename, oflag, shflag, pmode); -} -#endif - -#ifndef _WIN32 - -long test::sysconf(int name) { - long result = ::sysconf(name); - if (!sysconf_error) return result; - // Simulate an error. - errno = EINVAL; - return -1; -} - -static off_t max_file_size() { return std::numeric_limits<off_t>::max(); } - -int test::fstat(int fd, struct stat* buf) { - int result = ::fstat(fd, buf); - if (fstat_sim == MAX_SIZE) buf->st_size = max_file_size(); - return result; -} - -#else - -static LONGLONG max_file_size() { return std::numeric_limits<LONGLONG>::max(); } - -DWORD test::GetFileSize(HANDLE hFile, LPDWORD lpFileSizeHigh) { - if (fstat_sim == ERROR) { - SetLastError(ERROR_ACCESS_DENIED); - return INVALID_FILE_SIZE; - } - if (fstat_sim == MAX_SIZE) { - DWORD max = std::numeric_limits<DWORD>::max(); - *lpFileSizeHigh = max >> 1; - return max; - } - return ::GetFileSize(hFile, lpFileSizeHigh); -} - -#endif - -int test::close(int fildes) { - // Close the file first because close shouldn't be retried. - int result = ::FMT_POSIX(close(fildes)); - EMULATE_EINTR(close, -1); - return result; -} - -int test::dup(int fildes) { - EMULATE_EINTR(dup, -1); - return ::FMT_POSIX(dup(fildes)); -} - -int test::dup2(int fildes, int fildes2) { - EMULATE_EINTR(dup2, -1); - return ::FMT_POSIX(dup2(fildes, fildes2)); -} - -FILE* test::fdopen(int fildes, const char* mode) { - EMULATE_EINTR(fdopen, nullptr); - return ::FMT_POSIX(fdopen(fildes, mode)); -} - -test::ssize_t test::read(int fildes, void* buf, test::size_t nbyte) { - read_nbyte = nbyte; - EMULATE_EINTR(read, -1); - return ::FMT_POSIX(read(fildes, buf, nbyte)); -} - -test::ssize_t test::write(int fildes, const void* buf, test::size_t nbyte) { - write_nbyte = nbyte; - EMULATE_EINTR(write, -1); - return ::FMT_POSIX(write(fildes, buf, nbyte)); -} - -#ifndef _WIN32 -int test::pipe(int fildes[2]) { - EMULATE_EINTR(pipe, -1); - return ::pipe(fildes); -} -#else -int test::pipe(int* pfds, unsigned psize, int textmode) { - EMULATE_EINTR(pipe, -1); - return _pipe(pfds, psize, textmode); -} -#endif - -FILE* test::fopen(const char* filename, const char* mode) { - EMULATE_EINTR(fopen, nullptr); - return ::fopen(filename, mode); -} - -int test::fclose(FILE* stream) { - EMULATE_EINTR(fclose, EOF); - return ::fclose(stream); -} - -int(test::fileno)(FILE* stream) { - EMULATE_EINTR(fileno, -1); -#ifdef fileno - return FMT_POSIX(fileno(stream)); -#else - return ::FMT_POSIX(fileno(stream)); -#endif -} - -#ifndef _WIN32 -# define EXPECT_RETRY(statement, func, message) \ - func##_count = 1; \ - statement; \ - EXPECT_EQ(4, func##_count); \ - func##_count = 0; -# define EXPECT_EQ_POSIX(expected, actual) EXPECT_EQ(expected, actual) -#else -# define EXPECT_RETRY(statement, func, message) \ - func##_count = 1; \ - EXPECT_SYSTEM_ERROR(statement, EINTR, message); \ - func##_count = 0; -# define EXPECT_EQ_POSIX(expected, actual) -#endif - -static void write_file(fmt::cstring_view filename, fmt::string_view content) { - fmt::buffered_file f(filename, "w"); - f.print("{}", content); -} - -#if FMT_USE_FCNTL -using fmt::file; - -TEST(UtilTest, GetPageSize) { -# ifdef _WIN32 - SYSTEM_INFO si = {}; - GetSystemInfo(&si); - EXPECT_EQ(si.dwPageSize, fmt::getpagesize()); -# else - EXPECT_EQ(sysconf(_SC_PAGESIZE), fmt::getpagesize()); - sysconf_error = true; - EXPECT_SYSTEM_ERROR(fmt::getpagesize(), EINVAL, - "cannot get memory page size"); - sysconf_error = false; -# endif -} - -TEST(FileTest, OpenRetry) { - write_file("temp", "there must be something here"); - std::unique_ptr<file> f{nullptr}; - EXPECT_RETRY(f.reset(new file("temp", file::RDONLY)), open, - "cannot open file temp"); -# ifndef _WIN32 - char c = 0; - f->read(&c, 1); -# endif -} - -TEST(FileTest, CloseNoRetryInDtor) { - file read_end, write_end; - file::pipe(read_end, write_end); - std::unique_ptr<file> f(new file(std::move(read_end))); - int saved_close_count = 0; - EXPECT_WRITE( - stderr, - { - close_count = 1; - f.reset(nullptr); - saved_close_count = close_count; - close_count = 0; - }, - format_system_error(EINTR, "cannot close file") + "\n"); - EXPECT_EQ(2, saved_close_count); -} - -TEST(FileTest, CloseNoRetry) { - file read_end, write_end; - file::pipe(read_end, write_end); - close_count = 1; - EXPECT_SYSTEM_ERROR(read_end.close(), EINTR, "cannot close file"); - EXPECT_EQ(2, close_count); - close_count = 0; -} - -TEST(FileTest, Size) { - std::string content = "top secret, destroy before reading"; - write_file("temp", content); - file f("temp", file::RDONLY); - EXPECT_GE(f.size(), 0); - EXPECT_EQ(content.size(), static_cast<unsigned long long>(f.size())); -# ifdef _WIN32 - fmt::memory_buffer message; +bool sysconf_error; + +enum { NONE, MAX_SIZE, ERROR } fstat_sim; +} // namespace + +#define EMULATE_EINTR(func, error_result) \ + if (func##_count != 0) { \ + if (func##_count++ != 3) { \ + errno = EINTR; \ + return error_result; \ + } \ + } + +#ifndef _MSC_VER +int test::open(const char* path, int oflag, int mode) { + EMULATE_EINTR(open, -1); + return ::open(path, oflag, mode); +} +#else +errno_t test::sopen_s(int* pfh, const char* filename, int oflag, int shflag, + int pmode) { + EMULATE_EINTR(open, EINTR); + return _sopen_s(pfh, filename, oflag, shflag, pmode); +} +#endif + +#ifndef _WIN32 + +long test::sysconf(int name) { + long result = ::sysconf(name); + if (!sysconf_error) return result; + // Simulate an error. + errno = EINVAL; + return -1; +} + +static off_t max_file_size() { return std::numeric_limits<off_t>::max(); } + +int test::fstat(int fd, struct stat* buf) { + int result = ::fstat(fd, buf); + if (fstat_sim == MAX_SIZE) buf->st_size = max_file_size(); + return result; +} + +#else + +static LONGLONG max_file_size() { return std::numeric_limits<LONGLONG>::max(); } + +DWORD test::GetFileSize(HANDLE hFile, LPDWORD lpFileSizeHigh) { + if (fstat_sim == ERROR) { + SetLastError(ERROR_ACCESS_DENIED); + return INVALID_FILE_SIZE; + } + if (fstat_sim == MAX_SIZE) { + DWORD max = std::numeric_limits<DWORD>::max(); + *lpFileSizeHigh = max >> 1; + return max; + } + return ::GetFileSize(hFile, lpFileSizeHigh); +} + +#endif + +int test::close(int fildes) { + // Close the file first because close shouldn't be retried. + int result = ::FMT_POSIX(close(fildes)); + EMULATE_EINTR(close, -1); + return result; +} + +int test::dup(int fildes) { + EMULATE_EINTR(dup, -1); + return ::FMT_POSIX(dup(fildes)); +} + +int test::dup2(int fildes, int fildes2) { + EMULATE_EINTR(dup2, -1); + return ::FMT_POSIX(dup2(fildes, fildes2)); +} + +FILE* test::fdopen(int fildes, const char* mode) { + EMULATE_EINTR(fdopen, nullptr); + return ::FMT_POSIX(fdopen(fildes, mode)); +} + +test::ssize_t test::read(int fildes, void* buf, test::size_t nbyte) { + read_nbyte = nbyte; + EMULATE_EINTR(read, -1); + return ::FMT_POSIX(read(fildes, buf, nbyte)); +} + +test::ssize_t test::write(int fildes, const void* buf, test::size_t nbyte) { + write_nbyte = nbyte; + EMULATE_EINTR(write, -1); + return ::FMT_POSIX(write(fildes, buf, nbyte)); +} + +#ifndef _WIN32 +int test::pipe(int fildes[2]) { + EMULATE_EINTR(pipe, -1); + return ::pipe(fildes); +} +#else +int test::pipe(int* pfds, unsigned psize, int textmode) { + EMULATE_EINTR(pipe, -1); + return _pipe(pfds, psize, textmode); +} +#endif + +FILE* test::fopen(const char* filename, const char* mode) { + EMULATE_EINTR(fopen, nullptr); + return ::fopen(filename, mode); +} + +int test::fclose(FILE* stream) { + EMULATE_EINTR(fclose, EOF); + return ::fclose(stream); +} + +int(test::fileno)(FILE* stream) { + EMULATE_EINTR(fileno, -1); +#ifdef fileno + return FMT_POSIX(fileno(stream)); +#else + return ::FMT_POSIX(fileno(stream)); +#endif +} + +#ifndef _WIN32 +# define EXPECT_RETRY(statement, func, message) \ + func##_count = 1; \ + statement; \ + EXPECT_EQ(4, func##_count); \ + func##_count = 0; +# define EXPECT_EQ_POSIX(expected, actual) EXPECT_EQ(expected, actual) +#else +# define EXPECT_RETRY(statement, func, message) \ + func##_count = 1; \ + EXPECT_SYSTEM_ERROR(statement, EINTR, message); \ + func##_count = 0; +# define EXPECT_EQ_POSIX(expected, actual) +#endif + +static void write_file(fmt::cstring_view filename, fmt::string_view content) { + fmt::buffered_file f(filename, "w"); + f.print("{}", content); +} + +#if FMT_USE_FCNTL +using fmt::file; + +TEST(UtilTest, GetPageSize) { +# ifdef _WIN32 + SYSTEM_INFO si = {}; + GetSystemInfo(&si); + EXPECT_EQ(si.dwPageSize, fmt::getpagesize()); +# else + EXPECT_EQ(sysconf(_SC_PAGESIZE), fmt::getpagesize()); + sysconf_error = true; + EXPECT_SYSTEM_ERROR(fmt::getpagesize(), EINVAL, + "cannot get memory page size"); + sysconf_error = false; +# endif +} + +TEST(FileTest, OpenRetry) { + write_file("temp", "there must be something here"); + std::unique_ptr<file> f{nullptr}; + EXPECT_RETRY(f.reset(new file("temp", file::RDONLY)), open, + "cannot open file temp"); +# ifndef _WIN32 + char c = 0; + f->read(&c, 1); +# endif +} + +TEST(FileTest, CloseNoRetryInDtor) { + file read_end, write_end; + file::pipe(read_end, write_end); + std::unique_ptr<file> f(new file(std::move(read_end))); + int saved_close_count = 0; + EXPECT_WRITE( + stderr, + { + close_count = 1; + f.reset(nullptr); + saved_close_count = close_count; + close_count = 0; + }, + format_system_error(EINTR, "cannot close file") + "\n"); + EXPECT_EQ(2, saved_close_count); +} + +TEST(FileTest, CloseNoRetry) { + file read_end, write_end; + file::pipe(read_end, write_end); + close_count = 1; + EXPECT_SYSTEM_ERROR(read_end.close(), EINTR, "cannot close file"); + EXPECT_EQ(2, close_count); + close_count = 0; +} + +TEST(FileTest, Size) { + std::string content = "top secret, destroy before reading"; + write_file("temp", content); + file f("temp", file::RDONLY); + EXPECT_GE(f.size(), 0); + EXPECT_EQ(content.size(), static_cast<unsigned long long>(f.size())); +# ifdef _WIN32 + fmt::memory_buffer message; fmt::detail::format_windows_error(message, ERROR_ACCESS_DENIED, "cannot get file size"); - fstat_sim = ERROR; - EXPECT_THROW_MSG(f.size(), fmt::windows_error, fmt::to_string(message)); - fstat_sim = NONE; -# else - f.close(); - EXPECT_SYSTEM_ERROR(f.size(), EBADF, "cannot get file attributes"); -# endif -} - -TEST(FileTest, MaxSize) { - write_file("temp", ""); - file f("temp", file::RDONLY); - fstat_sim = MAX_SIZE; - EXPECT_GE(f.size(), 0); - EXPECT_EQ(max_file_size(), f.size()); - fstat_sim = NONE; -} - -TEST(FileTest, ReadRetry) { - file read_end, write_end; - file::pipe(read_end, write_end); - enum { SIZE = 4 }; - write_end.write("test", SIZE); - write_end.close(); - char buffer[SIZE]; + fstat_sim = ERROR; + EXPECT_THROW_MSG(f.size(), fmt::windows_error, fmt::to_string(message)); + fstat_sim = NONE; +# else + f.close(); + EXPECT_SYSTEM_ERROR(f.size(), EBADF, "cannot get file attributes"); +# endif +} + +TEST(FileTest, MaxSize) { + write_file("temp", ""); + file f("temp", file::RDONLY); + fstat_sim = MAX_SIZE; + EXPECT_GE(f.size(), 0); + EXPECT_EQ(max_file_size(), f.size()); + fstat_sim = NONE; +} + +TEST(FileTest, ReadRetry) { + file read_end, write_end; + file::pipe(read_end, write_end); + enum { SIZE = 4 }; + write_end.write("test", SIZE); + write_end.close(); + char buffer[SIZE]; size_t count = 0; - EXPECT_RETRY(count = read_end.read(buffer, SIZE), read, - "cannot read from file"); - EXPECT_EQ_POSIX(static_cast<std::streamsize>(SIZE), count); -} - -TEST(FileTest, WriteRetry) { - file read_end, write_end; - file::pipe(read_end, write_end); - enum { SIZE = 4 }; + EXPECT_RETRY(count = read_end.read(buffer, SIZE), read, + "cannot read from file"); + EXPECT_EQ_POSIX(static_cast<std::streamsize>(SIZE), count); +} + +TEST(FileTest, WriteRetry) { + file read_end, write_end; + file::pipe(read_end, write_end); + enum { SIZE = 4 }; size_t count = 0; - EXPECT_RETRY(count = write_end.write("test", SIZE), write, - "cannot write to file"); - write_end.close(); -# ifndef _WIN32 - EXPECT_EQ(static_cast<std::streamsize>(SIZE), count); - char buffer[SIZE + 1]; - read_end.read(buffer, SIZE); - buffer[SIZE] = '\0'; - EXPECT_STREQ("test", buffer); -# endif -} - -# ifdef _WIN32 -TEST(FileTest, ConvertReadCount) { - file read_end, write_end; - file::pipe(read_end, write_end); - char c; + EXPECT_RETRY(count = write_end.write("test", SIZE), write, + "cannot write to file"); + write_end.close(); +# ifndef _WIN32 + EXPECT_EQ(static_cast<std::streamsize>(SIZE), count); + char buffer[SIZE + 1]; + read_end.read(buffer, SIZE); + buffer[SIZE] = '\0'; + EXPECT_STREQ("test", buffer); +# endif +} + +# ifdef _WIN32 +TEST(FileTest, ConvertReadCount) { + file read_end, write_end; + file::pipe(read_end, write_end); + char c; size_t size = UINT_MAX; if (sizeof(unsigned) != sizeof(size_t)) ++size; - read_count = 1; - read_nbyte = 0; - EXPECT_THROW(read_end.read(&c, size), fmt::system_error); - read_count = 0; - EXPECT_EQ(UINT_MAX, read_nbyte); -} - -TEST(FileTest, ConvertWriteCount) { - file read_end, write_end; - file::pipe(read_end, write_end); - char c; + read_count = 1; + read_nbyte = 0; + EXPECT_THROW(read_end.read(&c, size), fmt::system_error); + read_count = 0; + EXPECT_EQ(UINT_MAX, read_nbyte); +} + +TEST(FileTest, ConvertWriteCount) { + file read_end, write_end; + file::pipe(read_end, write_end); + char c; size_t size = UINT_MAX; if (sizeof(unsigned) != sizeof(size_t)) ++size; - write_count = 1; - write_nbyte = 0; - EXPECT_THROW(write_end.write(&c, size), fmt::system_error); - write_count = 0; - EXPECT_EQ(UINT_MAX, write_nbyte); -} -# endif - -TEST(FileTest, DupNoRetry) { - int stdout_fd = FMT_POSIX(fileno(stdout)); - dup_count = 1; - EXPECT_SYSTEM_ERROR( - file::dup(stdout_fd), EINTR, - fmt::format("cannot duplicate file descriptor {}", stdout_fd)); - dup_count = 0; -} - -TEST(FileTest, Dup2Retry) { - int stdout_fd = FMT_POSIX(fileno(stdout)); - file f1 = file::dup(stdout_fd), f2 = file::dup(stdout_fd); - EXPECT_RETRY(f1.dup2(f2.descriptor()), dup2, - fmt::format("cannot duplicate file descriptor {} to {}", - f1.descriptor(), f2.descriptor())); -} - -TEST(FileTest, Dup2NoExceptRetry) { - int stdout_fd = FMT_POSIX(fileno(stdout)); - file f1 = file::dup(stdout_fd), f2 = file::dup(stdout_fd); - error_code ec; - dup2_count = 1; - f1.dup2(f2.descriptor(), ec); -# ifndef _WIN32 - EXPECT_EQ(4, dup2_count); -# else - EXPECT_EQ(EINTR, ec.get()); -# endif - dup2_count = 0; -} - -TEST(FileTest, PipeNoRetry) { - file read_end, write_end; - pipe_count = 1; - EXPECT_SYSTEM_ERROR(file::pipe(read_end, write_end), EINTR, - "cannot create pipe"); - pipe_count = 0; -} - -TEST(FileTest, FdopenNoRetry) { - file read_end, write_end; - file::pipe(read_end, write_end); - fdopen_count = 1; - EXPECT_SYSTEM_ERROR(read_end.fdopen("r"), EINTR, - "cannot associate stream with file descriptor"); - fdopen_count = 0; -} - -TEST(BufferedFileTest, OpenRetry) { - write_file("temp", "there must be something here"); - std::unique_ptr<buffered_file> f{nullptr}; - EXPECT_RETRY(f.reset(new buffered_file("temp", "r")), fopen, - "cannot open file temp"); -# ifndef _WIN32 - char c = 0; - if (fread(&c, 1, 1, f->get()) < 1) - throw fmt::system_error(errno, "fread failed"); -# endif -} - -TEST(BufferedFileTest, CloseNoRetryInDtor) { - file read_end, write_end; - file::pipe(read_end, write_end); - std::unique_ptr<buffered_file> f(new buffered_file(read_end.fdopen("r"))); - int saved_fclose_count = 0; - EXPECT_WRITE( - stderr, - { - fclose_count = 1; - f.reset(nullptr); - saved_fclose_count = fclose_count; - fclose_count = 0; - }, - format_system_error(EINTR, "cannot close file") + "\n"); - EXPECT_EQ(2, saved_fclose_count); -} - -TEST(BufferedFileTest, CloseNoRetry) { - file read_end, write_end; - file::pipe(read_end, write_end); - buffered_file f = read_end.fdopen("r"); - fclose_count = 1; - EXPECT_SYSTEM_ERROR(f.close(), EINTR, "cannot close file"); - EXPECT_EQ(2, fclose_count); - fclose_count = 0; -} - -TEST(BufferedFileTest, FilenoNoRetry) { - file read_end, write_end; - file::pipe(read_end, write_end); - buffered_file f = read_end.fdopen("r"); - fileno_count = 1; - EXPECT_SYSTEM_ERROR((f.fileno)(), EINTR, "cannot get file descriptor"); - EXPECT_EQ(2, fileno_count); - fileno_count = 0; -} -#endif // FMT_USE_FCNTL - -struct test_mock { - static test_mock* instance; -} * test_mock::instance; - -TEST(ScopedMock, Scope) { - { - ScopedMock<test_mock> mock; - EXPECT_EQ(&mock, test_mock::instance); - test_mock& copy = mock; - static_cast<void>(copy); - } - EXPECT_EQ(nullptr, test_mock::instance); -} - -#if defined(FMT_LOCALE) && !defined(_LIBCPP_VERSION) - -typedef fmt::locale::type locale_type; - -struct locale_mock { - static locale_mock* instance; - MOCK_METHOD3(newlocale, locale_type(int category_mask, const char* locale, - locale_type base)); - MOCK_METHOD1(freelocale, void(locale_type locale)); - - MOCK_METHOD3(strtod_l, - double(const char* nptr, char** endptr, locale_type locale)); -} * locale_mock::instance; - -# ifdef _MSC_VER -# pragma warning(push) -# pragma warning(disable : 4273) -# ifdef __clang__ -# pragma clang diagnostic push -# pragma clang diagnostic ignored "-Winconsistent-dllimport" -# endif - -_locale_t _create_locale(int category, const char* locale) { - return locale_mock::instance->newlocale(category, locale, 0); -} - -void _free_locale(_locale_t locale) { - locale_mock::instance->freelocale(locale); -} - -double _strtod_l(const char* nptr, char** endptr, _locale_t locale) { - return locale_mock::instance->strtod_l(nptr, endptr, locale); -} -# ifdef __clang__ -# pragma clang diagnostic pop -# endif -# pragma warning(pop) -# endif - -# if defined(__THROW) && FMT_GCC_VERSION > 0 && FMT_GCC_VERSION <= 408 -# define FMT_LOCALE_THROW __THROW -# else -# define FMT_LOCALE_THROW -# endif - -# if defined(__APPLE__) || \ - (defined(__FreeBSD__) && __FreeBSD_version < 1200002) -typedef int FreeLocaleResult; -# else -typedef void FreeLocaleResult; -# endif - -FreeLocaleResult freelocale(locale_type locale) FMT_LOCALE_THROW { - locale_mock::instance->freelocale(locale); - return FreeLocaleResult(); -} - -double strtod_l(const char* nptr, char** endptr, - locale_type locale) FMT_LOCALE_THROW { - return locale_mock::instance->strtod_l(nptr, endptr, locale); -} - -# undef FMT_LOCALE_THROW - -# if !defined(_WIN32) || defined(_LIBCPP_VERSION) -locale_t test::newlocale(int category_mask, const char* locale, locale_t base) { - return locale_mock::instance->newlocale(category_mask, locale, base); -} - -TEST(LocaleTest, LocaleMock) { - ScopedMock<locale_mock> mock; - locale_type locale = reinterpret_cast<locale_type>(11); - EXPECT_CALL(mock, newlocale(222, StrEq("foo"), locale)); - FMT_SYSTEM(newlocale(222, "foo", locale)); -} -# endif - -TEST(LocaleTest, Locale) { -# ifndef LC_NUMERIC_MASK - enum { LC_NUMERIC_MASK = LC_NUMERIC }; -# endif - ScopedMock<locale_mock> mock; - locale_type impl = reinterpret_cast<locale_type>(42); - EXPECT_CALL(mock, newlocale(LC_NUMERIC_MASK, StrEq("C"), nullptr)) - .WillOnce(Return(impl)); - EXPECT_CALL(mock, freelocale(impl)); - fmt::locale loc; - EXPECT_EQ(impl, loc.get()); -} - -TEST(LocaleTest, Strtod) { - ScopedMock<locale_mock> mock; - EXPECT_CALL(mock, newlocale(_, _, _)) - .WillOnce(Return(reinterpret_cast<locale_type>(42))); - EXPECT_CALL(mock, freelocale(_)); - fmt::locale loc; - const char* str = "4.2"; - char end = 'x'; - EXPECT_CALL(mock, strtod_l(str, _, loc.get())) - .WillOnce(testing::DoAll(testing::SetArgPointee<1>(&end), Return(777))); - EXPECT_EQ(777, loc.strtod(str)); - EXPECT_EQ(&end, str); -} - -#endif // FMT_LOCALE + write_count = 1; + write_nbyte = 0; + EXPECT_THROW(write_end.write(&c, size), fmt::system_error); + write_count = 0; + EXPECT_EQ(UINT_MAX, write_nbyte); +} +# endif + +TEST(FileTest, DupNoRetry) { + int stdout_fd = FMT_POSIX(fileno(stdout)); + dup_count = 1; + EXPECT_SYSTEM_ERROR( + file::dup(stdout_fd), EINTR, + fmt::format("cannot duplicate file descriptor {}", stdout_fd)); + dup_count = 0; +} + +TEST(FileTest, Dup2Retry) { + int stdout_fd = FMT_POSIX(fileno(stdout)); + file f1 = file::dup(stdout_fd), f2 = file::dup(stdout_fd); + EXPECT_RETRY(f1.dup2(f2.descriptor()), dup2, + fmt::format("cannot duplicate file descriptor {} to {}", + f1.descriptor(), f2.descriptor())); +} + +TEST(FileTest, Dup2NoExceptRetry) { + int stdout_fd = FMT_POSIX(fileno(stdout)); + file f1 = file::dup(stdout_fd), f2 = file::dup(stdout_fd); + error_code ec; + dup2_count = 1; + f1.dup2(f2.descriptor(), ec); +# ifndef _WIN32 + EXPECT_EQ(4, dup2_count); +# else + EXPECT_EQ(EINTR, ec.get()); +# endif + dup2_count = 0; +} + +TEST(FileTest, PipeNoRetry) { + file read_end, write_end; + pipe_count = 1; + EXPECT_SYSTEM_ERROR(file::pipe(read_end, write_end), EINTR, + "cannot create pipe"); + pipe_count = 0; +} + +TEST(FileTest, FdopenNoRetry) { + file read_end, write_end; + file::pipe(read_end, write_end); + fdopen_count = 1; + EXPECT_SYSTEM_ERROR(read_end.fdopen("r"), EINTR, + "cannot associate stream with file descriptor"); + fdopen_count = 0; +} + +TEST(BufferedFileTest, OpenRetry) { + write_file("temp", "there must be something here"); + std::unique_ptr<buffered_file> f{nullptr}; + EXPECT_RETRY(f.reset(new buffered_file("temp", "r")), fopen, + "cannot open file temp"); +# ifndef _WIN32 + char c = 0; + if (fread(&c, 1, 1, f->get()) < 1) + throw fmt::system_error(errno, "fread failed"); +# endif +} + +TEST(BufferedFileTest, CloseNoRetryInDtor) { + file read_end, write_end; + file::pipe(read_end, write_end); + std::unique_ptr<buffered_file> f(new buffered_file(read_end.fdopen("r"))); + int saved_fclose_count = 0; + EXPECT_WRITE( + stderr, + { + fclose_count = 1; + f.reset(nullptr); + saved_fclose_count = fclose_count; + fclose_count = 0; + }, + format_system_error(EINTR, "cannot close file") + "\n"); + EXPECT_EQ(2, saved_fclose_count); +} + +TEST(BufferedFileTest, CloseNoRetry) { + file read_end, write_end; + file::pipe(read_end, write_end); + buffered_file f = read_end.fdopen("r"); + fclose_count = 1; + EXPECT_SYSTEM_ERROR(f.close(), EINTR, "cannot close file"); + EXPECT_EQ(2, fclose_count); + fclose_count = 0; +} + +TEST(BufferedFileTest, FilenoNoRetry) { + file read_end, write_end; + file::pipe(read_end, write_end); + buffered_file f = read_end.fdopen("r"); + fileno_count = 1; + EXPECT_SYSTEM_ERROR((f.fileno)(), EINTR, "cannot get file descriptor"); + EXPECT_EQ(2, fileno_count); + fileno_count = 0; +} +#endif // FMT_USE_FCNTL + +struct test_mock { + static test_mock* instance; +} * test_mock::instance; + +TEST(ScopedMock, Scope) { + { + ScopedMock<test_mock> mock; + EXPECT_EQ(&mock, test_mock::instance); + test_mock& copy = mock; + static_cast<void>(copy); + } + EXPECT_EQ(nullptr, test_mock::instance); +} + +#if defined(FMT_LOCALE) && !defined(_LIBCPP_VERSION) + +typedef fmt::locale::type locale_type; + +struct locale_mock { + static locale_mock* instance; + MOCK_METHOD3(newlocale, locale_type(int category_mask, const char* locale, + locale_type base)); + MOCK_METHOD1(freelocale, void(locale_type locale)); + + MOCK_METHOD3(strtod_l, + double(const char* nptr, char** endptr, locale_type locale)); +} * locale_mock::instance; + +# ifdef _MSC_VER +# pragma warning(push) +# pragma warning(disable : 4273) +# ifdef __clang__ +# pragma clang diagnostic push +# pragma clang diagnostic ignored "-Winconsistent-dllimport" +# endif + +_locale_t _create_locale(int category, const char* locale) { + return locale_mock::instance->newlocale(category, locale, 0); +} + +void _free_locale(_locale_t locale) { + locale_mock::instance->freelocale(locale); +} + +double _strtod_l(const char* nptr, char** endptr, _locale_t locale) { + return locale_mock::instance->strtod_l(nptr, endptr, locale); +} +# ifdef __clang__ +# pragma clang diagnostic pop +# endif +# pragma warning(pop) +# endif + +# if defined(__THROW) && FMT_GCC_VERSION > 0 && FMT_GCC_VERSION <= 408 +# define FMT_LOCALE_THROW __THROW +# else +# define FMT_LOCALE_THROW +# endif + +# if defined(__APPLE__) || \ + (defined(__FreeBSD__) && __FreeBSD_version < 1200002) +typedef int FreeLocaleResult; +# else +typedef void FreeLocaleResult; +# endif + +FreeLocaleResult freelocale(locale_type locale) FMT_LOCALE_THROW { + locale_mock::instance->freelocale(locale); + return FreeLocaleResult(); +} + +double strtod_l(const char* nptr, char** endptr, + locale_type locale) FMT_LOCALE_THROW { + return locale_mock::instance->strtod_l(nptr, endptr, locale); +} + +# undef FMT_LOCALE_THROW + +# if !defined(_WIN32) || defined(_LIBCPP_VERSION) +locale_t test::newlocale(int category_mask, const char* locale, locale_t base) { + return locale_mock::instance->newlocale(category_mask, locale, base); +} + +TEST(LocaleTest, LocaleMock) { + ScopedMock<locale_mock> mock; + locale_type locale = reinterpret_cast<locale_type>(11); + EXPECT_CALL(mock, newlocale(222, StrEq("foo"), locale)); + FMT_SYSTEM(newlocale(222, "foo", locale)); +} +# endif + +TEST(LocaleTest, Locale) { +# ifndef LC_NUMERIC_MASK + enum { LC_NUMERIC_MASK = LC_NUMERIC }; +# endif + ScopedMock<locale_mock> mock; + locale_type impl = reinterpret_cast<locale_type>(42); + EXPECT_CALL(mock, newlocale(LC_NUMERIC_MASK, StrEq("C"), nullptr)) + .WillOnce(Return(impl)); + EXPECT_CALL(mock, freelocale(impl)); + fmt::locale loc; + EXPECT_EQ(impl, loc.get()); +} + +TEST(LocaleTest, Strtod) { + ScopedMock<locale_mock> mock; + EXPECT_CALL(mock, newlocale(_, _, _)) + .WillOnce(Return(reinterpret_cast<locale_type>(42))); + EXPECT_CALL(mock, freelocale(_)); + fmt::locale loc; + const char* str = "4.2"; + char end = 'x'; + EXPECT_CALL(mock, strtod_l(str, _, loc.get())) + .WillOnce(testing::DoAll(testing::SetArgPointee<1>(&end), Return(777))); + EXPECT_EQ(777, loc.strtod(str)); + EXPECT_EQ(&end, str); +} + +#endif // FMT_LOCALE diff --git a/contrib/libs/fmt/test/posix-mock-test/ya.make b/contrib/libs/fmt/test/posix-mock-test/ya.make index 1da082bd78..d1a55e5200 100644 --- a/contrib/libs/fmt/test/posix-mock-test/ya.make +++ b/contrib/libs/fmt/test/posix-mock-test/ya.make @@ -1,38 +1,38 @@ -# Generated by devtools/yamaker. - +# Generated by devtools/yamaker. + GTEST() - + WITHOUT_LICENSE_TEXTS() - + OWNER( orivej g:cpp-contrib ) -LICENSE(MIT) - +LICENSE(MIT) + ADDINCL( contrib/libs/fmt/include ) - -NO_COMPILER_WARNINGS() - -NO_UTIL() - -CFLAGS( - -DFMT_LOCALE - -DGTEST_HAS_STD_WSTRING=1 - -DGTEST_LANG_CXX11=0 - -D_SILENCE_TR1_NAMESPACE_DEPRECATION_WARNING=1 -) - -SRCDIR(contrib/libs/fmt) - -SRCS( - src/format.cc - test/gtest-extra.cc - test/posix-mock-test.cc - test/util.cc -) - -END() + +NO_COMPILER_WARNINGS() + +NO_UTIL() + +CFLAGS( + -DFMT_LOCALE + -DGTEST_HAS_STD_WSTRING=1 + -DGTEST_LANG_CXX11=0 + -D_SILENCE_TR1_NAMESPACE_DEPRECATION_WARNING=1 +) + +SRCDIR(contrib/libs/fmt) + +SRCS( + src/format.cc + test/gtest-extra.cc + test/posix-mock-test.cc + test/util.cc +) + +END() diff --git a/contrib/libs/fmt/test/posix-mock.h b/contrib/libs/fmt/test/posix-mock.h index 22f305cbf7..1f204263c6 100644 --- a/contrib/libs/fmt/test/posix-mock.h +++ b/contrib/libs/fmt/test/posix-mock.h @@ -1,78 +1,78 @@ -// Formatting library for C++ - mocks of POSIX functions -// -// Copyright (c) 2012 - present, Victor Zverovich -// All rights reserved. -// -// For the license information refer to format.h. - -#ifndef FMT_POSIX_TEST_H -#define FMT_POSIX_TEST_H - -#include <errno.h> -#include <locale.h> -#include <stdio.h> -#ifdef __APPLE__ -# include <xlocale.h> -#endif - -#ifdef _WIN32 -# include <windows.h> -# include <locale> // for libc++ locale_win32.h -#else -# include <sys/param.h> // for FreeBSD version -# include <sys/types.h> // for ssize_t -#endif - -#ifndef _MSC_VER -struct stat; -#endif - -namespace test { - -#ifndef _MSC_VER -// Size type for read and write. -typedef size_t size_t; -typedef ssize_t ssize_t; -int open(const char* path, int oflag, int mode); -int fstat(int fd, struct stat* buf); -#else -typedef unsigned size_t; -typedef int ssize_t; -errno_t sopen_s(int* pfh, const char* filename, int oflag, int shflag, - int pmode); -#endif - -#ifndef _WIN32 -long sysconf(int name); -#else -DWORD GetFileSize(HANDLE hFile, LPDWORD lpFileSizeHigh); -#endif - -int close(int fildes); - -int dup(int fildes); -int dup2(int fildes, int fildes2); - -FILE* fdopen(int fildes, const char* mode); - -ssize_t read(int fildes, void* buf, size_t nbyte); -ssize_t write(int fildes, const void* buf, size_t nbyte); - -#ifndef _WIN32 -int pipe(int fildes[2]); -#else -int pipe(int* pfds, unsigned psize, int textmode); -#endif - -FILE* fopen(const char* filename, const char* mode); -int fclose(FILE* stream); -int(fileno)(FILE* stream); - -#if defined(FMT_LOCALE) && (!defined(_WIN32) || defined(_LIBCPP_VERSION)) -locale_t newlocale(int category_mask, const char* locale, locale_t base); -#endif -} // namespace test - -#define FMT_SYSTEM(call) test::call - -#endif // FMT_POSIX_TEST_H +// Formatting library for C++ - mocks of POSIX functions +// +// Copyright (c) 2012 - present, Victor Zverovich +// All rights reserved. +// +// For the license information refer to format.h. + +#ifndef FMT_POSIX_TEST_H +#define FMT_POSIX_TEST_H + +#include <errno.h> +#include <locale.h> +#include <stdio.h> +#ifdef __APPLE__ +# include <xlocale.h> +#endif + +#ifdef _WIN32 +# include <windows.h> +# include <locale> // for libc++ locale_win32.h +#else +# include <sys/param.h> // for FreeBSD version +# include <sys/types.h> // for ssize_t +#endif + +#ifndef _MSC_VER +struct stat; +#endif + +namespace test { + +#ifndef _MSC_VER +// Size type for read and write. +typedef size_t size_t; +typedef ssize_t ssize_t; +int open(const char* path, int oflag, int mode); +int fstat(int fd, struct stat* buf); +#else +typedef unsigned size_t; +typedef int ssize_t; +errno_t sopen_s(int* pfh, const char* filename, int oflag, int shflag, + int pmode); +#endif + +#ifndef _WIN32 +long sysconf(int name); +#else +DWORD GetFileSize(HANDLE hFile, LPDWORD lpFileSizeHigh); +#endif + +int close(int fildes); + +int dup(int fildes); +int dup2(int fildes, int fildes2); + +FILE* fdopen(int fildes, const char* mode); + +ssize_t read(int fildes, void* buf, size_t nbyte); +ssize_t write(int fildes, const void* buf, size_t nbyte); + +#ifndef _WIN32 +int pipe(int fildes[2]); +#else +int pipe(int* pfds, unsigned psize, int textmode); +#endif + +FILE* fopen(const char* filename, const char* mode); +int fclose(FILE* stream); +int(fileno)(FILE* stream); + +#if defined(FMT_LOCALE) && (!defined(_WIN32) || defined(_LIBCPP_VERSION)) +locale_t newlocale(int category_mask, const char* locale, locale_t base); +#endif +} // namespace test + +#define FMT_SYSTEM(call) test::call + +#endif // FMT_POSIX_TEST_H diff --git a/contrib/libs/fmt/test/printf-test.cc b/contrib/libs/fmt/test/printf-test.cc index c9e1dfa6a2..ccd72dcd75 100644 --- a/contrib/libs/fmt/test/printf-test.cc +++ b/contrib/libs/fmt/test/printf-test.cc @@ -1,159 +1,159 @@ -// Formatting library for C++ - printf tests -// -// Copyright (c) 2012 - present, Victor Zverovich -// All rights reserved. -// -// For the license information refer to format.h. - -#include "fmt/printf.h" - -#include <cctype> -#include <climits> -#include <cstring> - -#include "fmt/core.h" -#include "gtest-extra.h" -#include "util.h" - -using fmt::format; -using fmt::format_error; +// Formatting library for C++ - printf tests +// +// Copyright (c) 2012 - present, Victor Zverovich +// All rights reserved. +// +// For the license information refer to format.h. + +#include "fmt/printf.h" + +#include <cctype> +#include <climits> +#include <cstring> + +#include "fmt/core.h" +#include "gtest-extra.h" +#include "util.h" + +using fmt::format; +using fmt::format_error; using fmt::detail::max_value; - -const unsigned BIG_NUM = INT_MAX + 1u; - -// Makes format string argument positional. -static std::string make_positional(fmt::string_view format) { - std::string s(format.data(), format.size()); - s.replace(s.find('%'), 1, "%1$"); - return s; -} - -static std::wstring make_positional(fmt::wstring_view format) { - std::wstring s(format.data(), format.size()); - s.replace(s.find(L'%'), 1, L"%1$"); - return s; -} - -// A wrapper around fmt::sprintf to workaround bogus warnings about invalid -// format strings in MSVC. -template <typename... Args> -std::string test_sprintf(fmt::string_view format, const Args&... args) { - return fmt::sprintf(format, args...); -} -template <typename... Args> -std::wstring test_sprintf(fmt::wstring_view format, const Args&... args) { - return fmt::sprintf(format, args...); -} - -#define EXPECT_PRINTF(expected_output, format, arg) \ - EXPECT_EQ(expected_output, test_sprintf(format, arg)) \ - << "format: " << format; \ - EXPECT_EQ(expected_output, fmt::sprintf(make_positional(format), arg)) - -TEST(PrintfTest, NoArgs) { - EXPECT_EQ("test", test_sprintf("test")); - EXPECT_EQ(L"test", fmt::sprintf(L"test")); -} - -TEST(PrintfTest, Escape) { - EXPECT_EQ("%", test_sprintf("%%")); - EXPECT_EQ("before %", test_sprintf("before %%")); - EXPECT_EQ("% after", test_sprintf("%% after")); - EXPECT_EQ("before % after", test_sprintf("before %% after")); - EXPECT_EQ("%s", test_sprintf("%%s")); - EXPECT_EQ(L"%", fmt::sprintf(L"%%")); - EXPECT_EQ(L"before %", fmt::sprintf(L"before %%")); - EXPECT_EQ(L"% after", fmt::sprintf(L"%% after")); - EXPECT_EQ(L"before % after", fmt::sprintf(L"before %% after")); - EXPECT_EQ(L"%s", fmt::sprintf(L"%%s")); -} - -TEST(PrintfTest, PositionalArgs) { - EXPECT_EQ("42", test_sprintf("%1$d", 42)); - EXPECT_EQ("before 42", test_sprintf("before %1$d", 42)); - EXPECT_EQ("42 after", test_sprintf("%1$d after", 42)); - EXPECT_EQ("before 42 after", test_sprintf("before %1$d after", 42)); - EXPECT_EQ("answer = 42", test_sprintf("%1$s = %2$d", "answer", 42)); - EXPECT_EQ("42 is the answer", test_sprintf("%2$d is the %1$s", "answer", 42)); - EXPECT_EQ("abracadabra", test_sprintf("%1$s%2$s%1$s", "abra", "cad")); -} - -TEST(PrintfTest, AutomaticArgIndexing) { - EXPECT_EQ("abc", test_sprintf("%c%c%c", 'a', 'b', 'c')); -} - -TEST(PrintfTest, NumberIsTooBigInArgIndex) { - EXPECT_THROW_MSG(test_sprintf(format("%{}$", BIG_NUM)), format_error, - "number is too big"); - EXPECT_THROW_MSG(test_sprintf(format("%{}$d", BIG_NUM)), format_error, - "number is too big"); -} - -TEST(PrintfTest, SwitchArgIndexing) { - EXPECT_THROW_MSG(test_sprintf("%1$d%", 1, 2), format_error, - "cannot switch from manual to automatic argument indexing"); - EXPECT_THROW_MSG(test_sprintf(format("%1$d%{}d", BIG_NUM), 1, 2), - format_error, "number is too big"); - EXPECT_THROW_MSG(test_sprintf("%1$d%d", 1, 2), format_error, - "cannot switch from manual to automatic argument indexing"); - - EXPECT_THROW_MSG(test_sprintf("%d%1$", 1, 2), format_error, - "cannot switch from automatic to manual argument indexing"); - EXPECT_THROW_MSG(test_sprintf(format("%d%{}$d", BIG_NUM), 1, 2), format_error, - "number is too big"); - EXPECT_THROW_MSG(test_sprintf("%d%1$d", 1, 2), format_error, - "cannot switch from automatic to manual argument indexing"); - - // Indexing errors override width errors. - EXPECT_THROW_MSG(test_sprintf(format("%d%1${}d", BIG_NUM), 1, 2), - format_error, "number is too big"); - EXPECT_THROW_MSG(test_sprintf(format("%1$d%{}d", BIG_NUM), 1, 2), - format_error, "number is too big"); -} - -TEST(PrintfTest, InvalidArgIndex) { - EXPECT_THROW_MSG(test_sprintf("%0$d", 42), format_error, + +const unsigned BIG_NUM = INT_MAX + 1u; + +// Makes format string argument positional. +static std::string make_positional(fmt::string_view format) { + std::string s(format.data(), format.size()); + s.replace(s.find('%'), 1, "%1$"); + return s; +} + +static std::wstring make_positional(fmt::wstring_view format) { + std::wstring s(format.data(), format.size()); + s.replace(s.find(L'%'), 1, L"%1$"); + return s; +} + +// A wrapper around fmt::sprintf to workaround bogus warnings about invalid +// format strings in MSVC. +template <typename... Args> +std::string test_sprintf(fmt::string_view format, const Args&... args) { + return fmt::sprintf(format, args...); +} +template <typename... Args> +std::wstring test_sprintf(fmt::wstring_view format, const Args&... args) { + return fmt::sprintf(format, args...); +} + +#define EXPECT_PRINTF(expected_output, format, arg) \ + EXPECT_EQ(expected_output, test_sprintf(format, arg)) \ + << "format: " << format; \ + EXPECT_EQ(expected_output, fmt::sprintf(make_positional(format), arg)) + +TEST(PrintfTest, NoArgs) { + EXPECT_EQ("test", test_sprintf("test")); + EXPECT_EQ(L"test", fmt::sprintf(L"test")); +} + +TEST(PrintfTest, Escape) { + EXPECT_EQ("%", test_sprintf("%%")); + EXPECT_EQ("before %", test_sprintf("before %%")); + EXPECT_EQ("% after", test_sprintf("%% after")); + EXPECT_EQ("before % after", test_sprintf("before %% after")); + EXPECT_EQ("%s", test_sprintf("%%s")); + EXPECT_EQ(L"%", fmt::sprintf(L"%%")); + EXPECT_EQ(L"before %", fmt::sprintf(L"before %%")); + EXPECT_EQ(L"% after", fmt::sprintf(L"%% after")); + EXPECT_EQ(L"before % after", fmt::sprintf(L"before %% after")); + EXPECT_EQ(L"%s", fmt::sprintf(L"%%s")); +} + +TEST(PrintfTest, PositionalArgs) { + EXPECT_EQ("42", test_sprintf("%1$d", 42)); + EXPECT_EQ("before 42", test_sprintf("before %1$d", 42)); + EXPECT_EQ("42 after", test_sprintf("%1$d after", 42)); + EXPECT_EQ("before 42 after", test_sprintf("before %1$d after", 42)); + EXPECT_EQ("answer = 42", test_sprintf("%1$s = %2$d", "answer", 42)); + EXPECT_EQ("42 is the answer", test_sprintf("%2$d is the %1$s", "answer", 42)); + EXPECT_EQ("abracadabra", test_sprintf("%1$s%2$s%1$s", "abra", "cad")); +} + +TEST(PrintfTest, AutomaticArgIndexing) { + EXPECT_EQ("abc", test_sprintf("%c%c%c", 'a', 'b', 'c')); +} + +TEST(PrintfTest, NumberIsTooBigInArgIndex) { + EXPECT_THROW_MSG(test_sprintf(format("%{}$", BIG_NUM)), format_error, + "number is too big"); + EXPECT_THROW_MSG(test_sprintf(format("%{}$d", BIG_NUM)), format_error, + "number is too big"); +} + +TEST(PrintfTest, SwitchArgIndexing) { + EXPECT_THROW_MSG(test_sprintf("%1$d%", 1, 2), format_error, + "cannot switch from manual to automatic argument indexing"); + EXPECT_THROW_MSG(test_sprintf(format("%1$d%{}d", BIG_NUM), 1, 2), + format_error, "number is too big"); + EXPECT_THROW_MSG(test_sprintf("%1$d%d", 1, 2), format_error, + "cannot switch from manual to automatic argument indexing"); + + EXPECT_THROW_MSG(test_sprintf("%d%1$", 1, 2), format_error, + "cannot switch from automatic to manual argument indexing"); + EXPECT_THROW_MSG(test_sprintf(format("%d%{}$d", BIG_NUM), 1, 2), format_error, + "number is too big"); + EXPECT_THROW_MSG(test_sprintf("%d%1$d", 1, 2), format_error, + "cannot switch from automatic to manual argument indexing"); + + // Indexing errors override width errors. + EXPECT_THROW_MSG(test_sprintf(format("%d%1${}d", BIG_NUM), 1, 2), + format_error, "number is too big"); + EXPECT_THROW_MSG(test_sprintf(format("%1$d%{}d", BIG_NUM), 1, 2), + format_error, "number is too big"); +} + +TEST(PrintfTest, InvalidArgIndex) { + EXPECT_THROW_MSG(test_sprintf("%0$d", 42), format_error, "argument not found"); - EXPECT_THROW_MSG(test_sprintf("%2$d", 42), format_error, + EXPECT_THROW_MSG(test_sprintf("%2$d", 42), format_error, "argument not found"); - EXPECT_THROW_MSG(test_sprintf(format("%{}$d", INT_MAX), 42), format_error, + EXPECT_THROW_MSG(test_sprintf(format("%{}$d", INT_MAX), 42), format_error, "argument not found"); - + EXPECT_THROW_MSG(test_sprintf("%2$", 42), format_error, "argument not found"); - EXPECT_THROW_MSG(test_sprintf(format("%{}$d", BIG_NUM), 42), format_error, - "number is too big"); -} - -TEST(PrintfTest, DefaultAlignRight) { - EXPECT_PRINTF(" 42", "%5d", 42); - EXPECT_PRINTF(" abc", "%5s", "abc"); -} - -TEST(PrintfTest, ZeroFlag) { - EXPECT_PRINTF("00042", "%05d", 42); - EXPECT_PRINTF("-0042", "%05d", -42); - - EXPECT_PRINTF("00042", "%05d", 42); - EXPECT_PRINTF("-0042", "%05d", -42); - EXPECT_PRINTF("-004.2", "%06g", -4.2); - - EXPECT_PRINTF("+00042", "%00+6d", 42); - + EXPECT_THROW_MSG(test_sprintf(format("%{}$d", BIG_NUM), 42), format_error, + "number is too big"); +} + +TEST(PrintfTest, DefaultAlignRight) { + EXPECT_PRINTF(" 42", "%5d", 42); + EXPECT_PRINTF(" abc", "%5s", "abc"); +} + +TEST(PrintfTest, ZeroFlag) { + EXPECT_PRINTF("00042", "%05d", 42); + EXPECT_PRINTF("-0042", "%05d", -42); + + EXPECT_PRINTF("00042", "%05d", 42); + EXPECT_PRINTF("-0042", "%05d", -42); + EXPECT_PRINTF("-004.2", "%06g", -4.2); + + EXPECT_PRINTF("+00042", "%00+6d", 42); + EXPECT_PRINTF(" 42", "%05.d", 42); EXPECT_PRINTF(" 0042", "%05.4d", 42); - // '0' flag is ignored for non-numeric types. + // '0' flag is ignored for non-numeric types. EXPECT_PRINTF(" x", "%05c", 'x'); -} - -TEST(PrintfTest, PlusFlag) { - EXPECT_PRINTF("+42", "%+d", 42); - EXPECT_PRINTF("-42", "%+d", -42); - EXPECT_PRINTF("+0042", "%+05d", 42); - EXPECT_PRINTF("+0042", "%0++5d", 42); - - // '+' flag is ignored for non-numeric types. - EXPECT_PRINTF("x", "%+c", 'x'); +} + +TEST(PrintfTest, PlusFlag) { + EXPECT_PRINTF("+42", "%+d", 42); + EXPECT_PRINTF("-42", "%+d", -42); + EXPECT_PRINTF("+0042", "%+05d", 42); + EXPECT_PRINTF("+0042", "%0++5d", 42); + + // '+' flag is ignored for non-numeric types. + EXPECT_PRINTF("x", "%+c", 'x'); // '+' flag wins over space flag EXPECT_PRINTF("+42", "%+ d", 42); @@ -166,11 +166,11 @@ TEST(PrintfTest, PlusFlag) { // '+' flag and space flag are both ignored for non-numeric types. EXPECT_PRINTF("x", "%+ c", 'x'); EXPECT_PRINTF("x", "% +c", 'x'); -} - -TEST(PrintfTest, MinusFlag) { - EXPECT_PRINTF("abc ", "%-5s", "abc"); - EXPECT_PRINTF("abc ", "%0--5s", "abc"); +} + +TEST(PrintfTest, MinusFlag) { + EXPECT_PRINTF("abc ", "%-5s", "abc"); + EXPECT_PRINTF("abc ", "%0--5s", "abc"); EXPECT_PRINTF("7 ", "%-5d", 7); EXPECT_PRINTF("97 ", "%-5hhi", 'a'); @@ -186,443 +186,443 @@ TEST(PrintfTest, MinusFlag) { // '-' and space flag don't interfere EXPECT_PRINTF(" 42", "%- d", 42); -} - -TEST(PrintfTest, SpaceFlag) { - EXPECT_PRINTF(" 42", "% d", 42); - EXPECT_PRINTF("-42", "% d", -42); - EXPECT_PRINTF(" 0042", "% 05d", 42); - EXPECT_PRINTF(" 0042", "%0 5d", 42); - - // ' ' flag is ignored for non-numeric types. - EXPECT_PRINTF("x", "% c", 'x'); -} - -TEST(PrintfTest, HashFlag) { - EXPECT_PRINTF("042", "%#o", 042); - EXPECT_PRINTF(fmt::format("0{:o}", static_cast<unsigned>(-042)), "%#o", -042); - EXPECT_PRINTF("0", "%#o", 0); - - EXPECT_PRINTF("0x42", "%#x", 0x42); - EXPECT_PRINTF("0X42", "%#X", 0x42); - EXPECT_PRINTF(fmt::format("0x{:x}", static_cast<unsigned>(-0x42)), "%#x", - -0x42); - EXPECT_PRINTF("0", "%#x", 0); - - EXPECT_PRINTF("0x0042", "%#06x", 0x42); - EXPECT_PRINTF("0x0042", "%0##6x", 0x42); - - EXPECT_PRINTF("-42.000000", "%#f", -42.0); - EXPECT_PRINTF("-42.000000", "%#F", -42.0); - - char buffer[BUFFER_SIZE]; - safe_sprintf(buffer, "%#e", -42.0); - EXPECT_PRINTF(buffer, "%#e", -42.0); - safe_sprintf(buffer, "%#E", -42.0); - EXPECT_PRINTF(buffer, "%#E", -42.0); - - EXPECT_PRINTF("-42.0000", "%#g", -42.0); - EXPECT_PRINTF("-42.0000", "%#G", -42.0); - - safe_sprintf(buffer, "%#a", 16.0); - EXPECT_PRINTF(buffer, "%#a", 16.0); - safe_sprintf(buffer, "%#A", 16.0); - EXPECT_PRINTF(buffer, "%#A", 16.0); - - // '#' flag is ignored for non-numeric types. - EXPECT_PRINTF("x", "%#c", 'x'); -} - -TEST(PrintfTest, Width) { - EXPECT_PRINTF(" abc", "%5s", "abc"); - - // Width cannot be specified twice. - EXPECT_THROW_MSG(test_sprintf("%5-5d", 42), format_error, - "invalid type specifier"); - - EXPECT_THROW_MSG(test_sprintf(format("%{}d", BIG_NUM), 42), format_error, - "number is too big"); - EXPECT_THROW_MSG(test_sprintf(format("%1${}d", BIG_NUM), 42), format_error, - "number is too big"); -} - -TEST(PrintfTest, DynamicWidth) { - EXPECT_EQ(" 42", test_sprintf("%*d", 5, 42)); - EXPECT_EQ("42 ", test_sprintf("%*d", -5, 42)); - EXPECT_THROW_MSG(test_sprintf("%*d", 5.0, 42), format_error, - "width is not integer"); +} + +TEST(PrintfTest, SpaceFlag) { + EXPECT_PRINTF(" 42", "% d", 42); + EXPECT_PRINTF("-42", "% d", -42); + EXPECT_PRINTF(" 0042", "% 05d", 42); + EXPECT_PRINTF(" 0042", "%0 5d", 42); + + // ' ' flag is ignored for non-numeric types. + EXPECT_PRINTF("x", "% c", 'x'); +} + +TEST(PrintfTest, HashFlag) { + EXPECT_PRINTF("042", "%#o", 042); + EXPECT_PRINTF(fmt::format("0{:o}", static_cast<unsigned>(-042)), "%#o", -042); + EXPECT_PRINTF("0", "%#o", 0); + + EXPECT_PRINTF("0x42", "%#x", 0x42); + EXPECT_PRINTF("0X42", "%#X", 0x42); + EXPECT_PRINTF(fmt::format("0x{:x}", static_cast<unsigned>(-0x42)), "%#x", + -0x42); + EXPECT_PRINTF("0", "%#x", 0); + + EXPECT_PRINTF("0x0042", "%#06x", 0x42); + EXPECT_PRINTF("0x0042", "%0##6x", 0x42); + + EXPECT_PRINTF("-42.000000", "%#f", -42.0); + EXPECT_PRINTF("-42.000000", "%#F", -42.0); + + char buffer[BUFFER_SIZE]; + safe_sprintf(buffer, "%#e", -42.0); + EXPECT_PRINTF(buffer, "%#e", -42.0); + safe_sprintf(buffer, "%#E", -42.0); + EXPECT_PRINTF(buffer, "%#E", -42.0); + + EXPECT_PRINTF("-42.0000", "%#g", -42.0); + EXPECT_PRINTF("-42.0000", "%#G", -42.0); + + safe_sprintf(buffer, "%#a", 16.0); + EXPECT_PRINTF(buffer, "%#a", 16.0); + safe_sprintf(buffer, "%#A", 16.0); + EXPECT_PRINTF(buffer, "%#A", 16.0); + + // '#' flag is ignored for non-numeric types. + EXPECT_PRINTF("x", "%#c", 'x'); +} + +TEST(PrintfTest, Width) { + EXPECT_PRINTF(" abc", "%5s", "abc"); + + // Width cannot be specified twice. + EXPECT_THROW_MSG(test_sprintf("%5-5d", 42), format_error, + "invalid type specifier"); + + EXPECT_THROW_MSG(test_sprintf(format("%{}d", BIG_NUM), 42), format_error, + "number is too big"); + EXPECT_THROW_MSG(test_sprintf(format("%1${}d", BIG_NUM), 42), format_error, + "number is too big"); +} + +TEST(PrintfTest, DynamicWidth) { + EXPECT_EQ(" 42", test_sprintf("%*d", 5, 42)); + EXPECT_EQ("42 ", test_sprintf("%*d", -5, 42)); + EXPECT_THROW_MSG(test_sprintf("%*d", 5.0, 42), format_error, + "width is not integer"); EXPECT_THROW_MSG(test_sprintf("%*d"), format_error, "argument not found"); - EXPECT_THROW_MSG(test_sprintf("%*d", BIG_NUM, 42), format_error, - "number is too big"); -} - -TEST(PrintfTest, IntPrecision) { - EXPECT_PRINTF("00042", "%.5d", 42); - EXPECT_PRINTF("-00042", "%.5d", -42); - EXPECT_PRINTF("00042", "%.5x", 0x42); - EXPECT_PRINTF("0x00042", "%#.5x", 0x42); - EXPECT_PRINTF("00042", "%.5o", 042); - EXPECT_PRINTF("00042", "%#.5o", 042); - - EXPECT_PRINTF(" 00042", "%7.5d", 42); - EXPECT_PRINTF(" 00042", "%7.5x", 0x42); - EXPECT_PRINTF(" 0x00042", "%#10.5x", 0x42); - EXPECT_PRINTF(" 00042", "%7.5o", 042); - EXPECT_PRINTF(" 00042", "%#10.5o", 042); - - EXPECT_PRINTF("00042 ", "%-7.5d", 42); - EXPECT_PRINTF("00042 ", "%-7.5x", 0x42); - EXPECT_PRINTF("0x00042 ", "%-#10.5x", 0x42); - EXPECT_PRINTF("00042 ", "%-7.5o", 042); - EXPECT_PRINTF("00042 ", "%-#10.5o", 042); -} - -TEST(PrintfTest, FloatPrecision) { - char buffer[BUFFER_SIZE]; - safe_sprintf(buffer, "%.3e", 1234.5678); - EXPECT_PRINTF(buffer, "%.3e", 1234.5678); - EXPECT_PRINTF("1234.568", "%.3f", 1234.5678); - EXPECT_PRINTF("1.23e+03", "%.3g", 1234.5678); - safe_sprintf(buffer, "%.3a", 1234.5678); - EXPECT_PRINTF(buffer, "%.3a", 1234.5678); -} - + EXPECT_THROW_MSG(test_sprintf("%*d", BIG_NUM, 42), format_error, + "number is too big"); +} + +TEST(PrintfTest, IntPrecision) { + EXPECT_PRINTF("00042", "%.5d", 42); + EXPECT_PRINTF("-00042", "%.5d", -42); + EXPECT_PRINTF("00042", "%.5x", 0x42); + EXPECT_PRINTF("0x00042", "%#.5x", 0x42); + EXPECT_PRINTF("00042", "%.5o", 042); + EXPECT_PRINTF("00042", "%#.5o", 042); + + EXPECT_PRINTF(" 00042", "%7.5d", 42); + EXPECT_PRINTF(" 00042", "%7.5x", 0x42); + EXPECT_PRINTF(" 0x00042", "%#10.5x", 0x42); + EXPECT_PRINTF(" 00042", "%7.5o", 042); + EXPECT_PRINTF(" 00042", "%#10.5o", 042); + + EXPECT_PRINTF("00042 ", "%-7.5d", 42); + EXPECT_PRINTF("00042 ", "%-7.5x", 0x42); + EXPECT_PRINTF("0x00042 ", "%-#10.5x", 0x42); + EXPECT_PRINTF("00042 ", "%-7.5o", 042); + EXPECT_PRINTF("00042 ", "%-#10.5o", 042); +} + +TEST(PrintfTest, FloatPrecision) { + char buffer[BUFFER_SIZE]; + safe_sprintf(buffer, "%.3e", 1234.5678); + EXPECT_PRINTF(buffer, "%.3e", 1234.5678); + EXPECT_PRINTF("1234.568", "%.3f", 1234.5678); + EXPECT_PRINTF("1.23e+03", "%.3g", 1234.5678); + safe_sprintf(buffer, "%.3a", 1234.5678); + EXPECT_PRINTF(buffer, "%.3a", 1234.5678); +} + TEST(PrintfTest, StringPrecision) { char test[] = {'H', 'e', 'l', 'l', 'o'}; EXPECT_EQ(fmt::sprintf("%.4s", test), "Hell"); } -TEST(PrintfTest, IgnorePrecisionForNonNumericArg) { - EXPECT_PRINTF("abc", "%.5s", "abc"); -} - -TEST(PrintfTest, DynamicPrecision) { - EXPECT_EQ("00042", test_sprintf("%.*d", 5, 42)); - EXPECT_EQ("42", test_sprintf("%.*d", -5, 42)); - EXPECT_THROW_MSG(test_sprintf("%.*d", 5.0, 42), format_error, - "precision is not integer"); +TEST(PrintfTest, IgnorePrecisionForNonNumericArg) { + EXPECT_PRINTF("abc", "%.5s", "abc"); +} + +TEST(PrintfTest, DynamicPrecision) { + EXPECT_EQ("00042", test_sprintf("%.*d", 5, 42)); + EXPECT_EQ("42", test_sprintf("%.*d", -5, 42)); + EXPECT_THROW_MSG(test_sprintf("%.*d", 5.0, 42), format_error, + "precision is not integer"); EXPECT_THROW_MSG(test_sprintf("%.*d"), format_error, "argument not found"); - EXPECT_THROW_MSG(test_sprintf("%.*d", BIG_NUM, 42), format_error, - "number is too big"); - if (sizeof(long long) != sizeof(int)) { - long long prec = static_cast<long long>(INT_MIN) - 1; - EXPECT_THROW_MSG(test_sprintf("%.*d", prec, 42), format_error, - "number is too big"); - } -} - -template <typename T> struct make_signed { typedef T type; }; - -#define SPECIALIZE_MAKE_SIGNED(T, S) \ - template <> struct make_signed<T> { typedef S type; } - -SPECIALIZE_MAKE_SIGNED(char, signed char); -SPECIALIZE_MAKE_SIGNED(unsigned char, signed char); -SPECIALIZE_MAKE_SIGNED(unsigned short, short); -SPECIALIZE_MAKE_SIGNED(unsigned, int); -SPECIALIZE_MAKE_SIGNED(unsigned long, long); -SPECIALIZE_MAKE_SIGNED(unsigned long long, long long); - -// Test length format specifier ``length_spec``. -template <typename T, typename U> -void TestLength(const char* length_spec, U value) { - long long signed_value = 0; - unsigned long long unsigned_value = 0; - // Apply integer promotion to the argument. - unsigned long long max = max_value<U>(); + EXPECT_THROW_MSG(test_sprintf("%.*d", BIG_NUM, 42), format_error, + "number is too big"); + if (sizeof(long long) != sizeof(int)) { + long long prec = static_cast<long long>(INT_MIN) - 1; + EXPECT_THROW_MSG(test_sprintf("%.*d", prec, 42), format_error, + "number is too big"); + } +} + +template <typename T> struct make_signed { typedef T type; }; + +#define SPECIALIZE_MAKE_SIGNED(T, S) \ + template <> struct make_signed<T> { typedef S type; } + +SPECIALIZE_MAKE_SIGNED(char, signed char); +SPECIALIZE_MAKE_SIGNED(unsigned char, signed char); +SPECIALIZE_MAKE_SIGNED(unsigned short, short); +SPECIALIZE_MAKE_SIGNED(unsigned, int); +SPECIALIZE_MAKE_SIGNED(unsigned long, long); +SPECIALIZE_MAKE_SIGNED(unsigned long long, long long); + +// Test length format specifier ``length_spec``. +template <typename T, typename U> +void TestLength(const char* length_spec, U value) { + long long signed_value = 0; + unsigned long long unsigned_value = 0; + // Apply integer promotion to the argument. + unsigned long long max = max_value<U>(); using fmt::detail::const_check; - if (const_check(max <= static_cast<unsigned>(max_value<int>()))) { - signed_value = static_cast<int>(value); - unsigned_value = static_cast<unsigned long long>(value); - } else if (const_check(max <= max_value<unsigned>())) { - signed_value = static_cast<unsigned>(value); - unsigned_value = static_cast<unsigned long long>(value); - } - if (sizeof(U) <= sizeof(int) && sizeof(int) < sizeof(T)) { - signed_value = static_cast<long long>(value); - unsigned_value = static_cast<unsigned long long>( - static_cast<typename std::make_unsigned<unsigned>::type>(value)); - } else { - signed_value = static_cast<typename make_signed<T>::type>(value); - unsigned_value = static_cast<typename std::make_unsigned<T>::type>(value); - } - std::ostringstream os; - os << signed_value; - EXPECT_PRINTF(os.str(), fmt::format("%{}d", length_spec), value); - EXPECT_PRINTF(os.str(), fmt::format("%{}i", length_spec), value); - os.str(""); - os << unsigned_value; - EXPECT_PRINTF(os.str(), fmt::format("%{}u", length_spec), value); - os.str(""); - os << std::oct << unsigned_value; - EXPECT_PRINTF(os.str(), fmt::format("%{}o", length_spec), value); - os.str(""); - os << std::hex << unsigned_value; - EXPECT_PRINTF(os.str(), fmt::format("%{}x", length_spec), value); - os.str(""); - os << std::hex << std::uppercase << unsigned_value; - EXPECT_PRINTF(os.str(), fmt::format("%{}X", length_spec), value); -} - -template <typename T> void TestLength(const char* length_spec) { - T min = std::numeric_limits<T>::min(), max = max_value<T>(); - TestLength<T>(length_spec, 42); - TestLength<T>(length_spec, -42); - TestLength<T>(length_spec, min); - TestLength<T>(length_spec, max); - long long long_long_min = std::numeric_limits<long long>::min(); - if (static_cast<long long>(min) > long_long_min) - TestLength<T>(length_spec, static_cast<long long>(min) - 1); - unsigned long long long_long_max = max_value<long long>(); - if (static_cast<unsigned long long>(max) < long_long_max) - TestLength<T>(length_spec, static_cast<long long>(max) + 1); - TestLength<T>(length_spec, std::numeric_limits<short>::min()); - TestLength<T>(length_spec, max_value<unsigned short>()); - TestLength<T>(length_spec, std::numeric_limits<int>::min()); - TestLength<T>(length_spec, max_value<int>()); - TestLength<T>(length_spec, std::numeric_limits<unsigned>::min()); - TestLength<T>(length_spec, max_value<unsigned>()); - TestLength<T>(length_spec, std::numeric_limits<long long>::min()); - TestLength<T>(length_spec, max_value<long long>()); - TestLength<T>(length_spec, std::numeric_limits<unsigned long long>::min()); - TestLength<T>(length_spec, max_value<unsigned long long>()); -} - -TEST(PrintfTest, Length) { - TestLength<char>("hh"); - TestLength<signed char>("hh"); - TestLength<unsigned char>("hh"); - TestLength<short>("h"); - TestLength<unsigned short>("h"); - TestLength<long>("l"); - TestLength<unsigned long>("l"); - TestLength<long long>("ll"); - TestLength<unsigned long long>("ll"); - TestLength<intmax_t>("j"); + if (const_check(max <= static_cast<unsigned>(max_value<int>()))) { + signed_value = static_cast<int>(value); + unsigned_value = static_cast<unsigned long long>(value); + } else if (const_check(max <= max_value<unsigned>())) { + signed_value = static_cast<unsigned>(value); + unsigned_value = static_cast<unsigned long long>(value); + } + if (sizeof(U) <= sizeof(int) && sizeof(int) < sizeof(T)) { + signed_value = static_cast<long long>(value); + unsigned_value = static_cast<unsigned long long>( + static_cast<typename std::make_unsigned<unsigned>::type>(value)); + } else { + signed_value = static_cast<typename make_signed<T>::type>(value); + unsigned_value = static_cast<typename std::make_unsigned<T>::type>(value); + } + std::ostringstream os; + os << signed_value; + EXPECT_PRINTF(os.str(), fmt::format("%{}d", length_spec), value); + EXPECT_PRINTF(os.str(), fmt::format("%{}i", length_spec), value); + os.str(""); + os << unsigned_value; + EXPECT_PRINTF(os.str(), fmt::format("%{}u", length_spec), value); + os.str(""); + os << std::oct << unsigned_value; + EXPECT_PRINTF(os.str(), fmt::format("%{}o", length_spec), value); + os.str(""); + os << std::hex << unsigned_value; + EXPECT_PRINTF(os.str(), fmt::format("%{}x", length_spec), value); + os.str(""); + os << std::hex << std::uppercase << unsigned_value; + EXPECT_PRINTF(os.str(), fmt::format("%{}X", length_spec), value); +} + +template <typename T> void TestLength(const char* length_spec) { + T min = std::numeric_limits<T>::min(), max = max_value<T>(); + TestLength<T>(length_spec, 42); + TestLength<T>(length_spec, -42); + TestLength<T>(length_spec, min); + TestLength<T>(length_spec, max); + long long long_long_min = std::numeric_limits<long long>::min(); + if (static_cast<long long>(min) > long_long_min) + TestLength<T>(length_spec, static_cast<long long>(min) - 1); + unsigned long long long_long_max = max_value<long long>(); + if (static_cast<unsigned long long>(max) < long_long_max) + TestLength<T>(length_spec, static_cast<long long>(max) + 1); + TestLength<T>(length_spec, std::numeric_limits<short>::min()); + TestLength<T>(length_spec, max_value<unsigned short>()); + TestLength<T>(length_spec, std::numeric_limits<int>::min()); + TestLength<T>(length_spec, max_value<int>()); + TestLength<T>(length_spec, std::numeric_limits<unsigned>::min()); + TestLength<T>(length_spec, max_value<unsigned>()); + TestLength<T>(length_spec, std::numeric_limits<long long>::min()); + TestLength<T>(length_spec, max_value<long long>()); + TestLength<T>(length_spec, std::numeric_limits<unsigned long long>::min()); + TestLength<T>(length_spec, max_value<unsigned long long>()); +} + +TEST(PrintfTest, Length) { + TestLength<char>("hh"); + TestLength<signed char>("hh"); + TestLength<unsigned char>("hh"); + TestLength<short>("h"); + TestLength<unsigned short>("h"); + TestLength<long>("l"); + TestLength<unsigned long>("l"); + TestLength<long long>("ll"); + TestLength<unsigned long long>("ll"); + TestLength<intmax_t>("j"); TestLength<size_t>("z"); - TestLength<std::ptrdiff_t>("t"); - long double max = max_value<long double>(); - EXPECT_PRINTF(fmt::format("{:.6}", max), "%g", max); - EXPECT_PRINTF(fmt::format("{:.6}", max), "%Lg", max); -} - -TEST(PrintfTest, Bool) { - EXPECT_PRINTF("1", "%d", true); - EXPECT_PRINTF("true", "%s", true); -} - -TEST(PrintfTest, Int) { - EXPECT_PRINTF("-42", "%d", -42); - EXPECT_PRINTF("-42", "%i", -42); - unsigned u = 0 - 42u; - EXPECT_PRINTF(fmt::format("{}", u), "%u", -42); - EXPECT_PRINTF(fmt::format("{:o}", u), "%o", -42); - EXPECT_PRINTF(fmt::format("{:x}", u), "%x", -42); - EXPECT_PRINTF(fmt::format("{:X}", u), "%X", -42); -} - -TEST(PrintfTest, long_long) { - // fmt::printf allows passing long long arguments to %d without length - // specifiers. - long long max = max_value<long long>(); - EXPECT_PRINTF(fmt::format("{}", max), "%d", max); -} - -TEST(PrintfTest, Float) { - EXPECT_PRINTF("392.650000", "%f", 392.65); - EXPECT_PRINTF("392.65", "%.2f", 392.65); - EXPECT_PRINTF("392.6", "%.1f", 392.65); - EXPECT_PRINTF("393", "%.f", 392.65); - EXPECT_PRINTF("392.650000", "%F", 392.65); - char buffer[BUFFER_SIZE]; - safe_sprintf(buffer, "%e", 392.65); - EXPECT_PRINTF(buffer, "%e", 392.65); - safe_sprintf(buffer, "%E", 392.65); - EXPECT_PRINTF(buffer, "%E", 392.65); - EXPECT_PRINTF("392.65", "%g", 392.65); - EXPECT_PRINTF("392.65", "%G", 392.65); - EXPECT_PRINTF("392", "%g", 392.0); - EXPECT_PRINTF("392", "%G", 392.0); - EXPECT_PRINTF("4.56e-07", "%g", 0.000000456); - safe_sprintf(buffer, "%a", -392.65); - EXPECT_EQ(buffer, format("{:a}", -392.65)); - safe_sprintf(buffer, "%A", -392.65); - EXPECT_EQ(buffer, format("{:A}", -392.65)); -} - -TEST(PrintfTest, Inf) { - double inf = std::numeric_limits<double>::infinity(); - for (const char* type = "fega"; *type; ++type) { - EXPECT_PRINTF("inf", fmt::format("%{}", *type), inf); - char upper = static_cast<char>(std::toupper(*type)); - EXPECT_PRINTF("INF", fmt::format("%{}", upper), inf); - } -} - -TEST(PrintfTest, Char) { - EXPECT_PRINTF("x", "%c", 'x'); - int max = max_value<int>(); - EXPECT_PRINTF(fmt::format("{}", static_cast<char>(max)), "%c", max); - // EXPECT_PRINTF("x", "%lc", L'x'); - EXPECT_PRINTF(L"x", L"%c", L'x'); - EXPECT_PRINTF(fmt::format(L"{}", static_cast<wchar_t>(max)), L"%c", max); -} - -TEST(PrintfTest, String) { - EXPECT_PRINTF("abc", "%s", "abc"); - const char* null_str = nullptr; - EXPECT_PRINTF("(null)", "%s", null_str); - EXPECT_PRINTF(" (null)", "%10s", null_str); - EXPECT_PRINTF(L"abc", L"%s", L"abc"); - const wchar_t* null_wstr = nullptr; - EXPECT_PRINTF(L"(null)", L"%s", null_wstr); - EXPECT_PRINTF(L" (null)", L"%10s", null_wstr); -} - -TEST(PrintfTest, UCharString) { - unsigned char str[] = "test"; - unsigned char* pstr = str; - EXPECT_EQ("test", fmt::sprintf("%s", pstr)); -} - -TEST(PrintfTest, Pointer) { - int n; - void* p = &n; - EXPECT_PRINTF(fmt::format("{}", p), "%p", p); - p = nullptr; - EXPECT_PRINTF("(nil)", "%p", p); - EXPECT_PRINTF(" (nil)", "%10p", p); - const char* s = "test"; - EXPECT_PRINTF(fmt::format("{:p}", s), "%p", s); - const char* null_str = nullptr; - EXPECT_PRINTF("(nil)", "%p", null_str); - - p = &n; - EXPECT_PRINTF(fmt::format(L"{}", p), L"%p", p); - p = nullptr; - EXPECT_PRINTF(L"(nil)", L"%p", p); - EXPECT_PRINTF(L" (nil)", L"%10p", p); - const wchar_t* w = L"test"; - EXPECT_PRINTF(fmt::format(L"{:p}", w), L"%p", w); - const wchar_t* null_wstr = nullptr; - EXPECT_PRINTF(L"(nil)", L"%p", null_wstr); -} - -TEST(PrintfTest, Location) { - // TODO: test %n -} - -enum test_enum { answer = 42 }; - -TEST(PrintfTest, Enum) { - EXPECT_PRINTF("42", "%d", answer); - volatile test_enum volatile_enum = answer; - EXPECT_PRINTF("42", "%d", volatile_enum); -} - -#if FMT_USE_FCNTL -TEST(PrintfTest, Examples) { - const char* weekday = "Thursday"; - const char* month = "August"; - int day = 21; - EXPECT_WRITE(stdout, fmt::printf("%1$s, %3$d %2$s", weekday, month, day), - "Thursday, 21 August"); -} - -TEST(PrintfTest, PrintfError) { - fmt::file read_end, write_end; - fmt::file::pipe(read_end, write_end); - int result = fmt::fprintf(read_end.fdopen("r").get(), "test"); - EXPECT_LT(result, 0); -} -#endif - -TEST(PrintfTest, WideString) { EXPECT_EQ(L"abc", fmt::sprintf(L"%s", L"abc")); } - -TEST(PrintfTest, PrintfCustom) { - EXPECT_EQ("abc", test_sprintf("%s", TestString("abc"))); -} - -TEST(PrintfTest, OStream) { - std::ostringstream os; - int ret = fmt::fprintf(os, "Don't %s!", "panic"); - EXPECT_EQ("Don't panic!", os.str()); - EXPECT_EQ(12, ret); -} - -TEST(PrintfTest, VPrintf) { - fmt::format_arg_store<fmt::printf_context, int> as{42}; - fmt::basic_format_args<fmt::printf_context> args(as); - EXPECT_EQ(fmt::vsprintf("%d", args), "42"); - EXPECT_WRITE(stdout, fmt::vprintf("%d", args), "42"); - EXPECT_WRITE(stdout, fmt::vfprintf(stdout, "%d", args), "42"); - EXPECT_WRITE(stdout, fmt::vfprintf(std::cout, "%d", args), "42"); -} - -template <typename... Args> -void check_format_string_regression(fmt::string_view s, const Args&... args) { - fmt::sprintf(s, args...); -} - -TEST(PrintfTest, CheckFormatStringRegression) { - check_format_string_regression("%c%s", 'x', ""); -} - -TEST(PrintfTest, FixedLargeExponent) { - EXPECT_EQ("1000000000000000000000", fmt::sprintf("%.*f", -13, 1e21)); -} - -TEST(PrintfTest, VSPrintfMakeArgsExample) { - fmt::format_arg_store<fmt::printf_context, int, const char*> as{42, - "something"}; - fmt::basic_format_args<fmt::printf_context> args(as); - EXPECT_EQ("[42] something happened", fmt::vsprintf("[%d] %s happened", args)); - auto as2 = fmt::make_printf_args(42, "something"); - fmt::basic_format_args<fmt::printf_context> args2(as2); - EXPECT_EQ("[42] something happened", - fmt::vsprintf("[%d] %s happened", args2)); - // The older gcc versions can't cast the return value. -#if !defined(__GNUC__) || (__GNUC__ > 4) - EXPECT_EQ("[42] something happened", - fmt::vsprintf("[%d] %s happened", - {fmt::make_printf_args(42, "something")})); -#endif -} - -TEST(PrintfTest, VSPrintfMakeWArgsExample) { - fmt::format_arg_store<fmt::wprintf_context, int, const wchar_t*> as{ - 42, L"something"}; - fmt::basic_format_args<fmt::wprintf_context> args(as); - EXPECT_EQ(L"[42] something happened", - fmt::vsprintf(L"[%d] %s happened", args)); - auto as2 = fmt::make_wprintf_args(42, L"something"); - fmt::basic_format_args<fmt::wprintf_context> args2(as2); - EXPECT_EQ(L"[42] something happened", - fmt::vsprintf(L"[%d] %s happened", args2)); - // the older gcc versions can't cast the return value -#if !defined(__GNUC__) || (__GNUC__ > 4) - EXPECT_EQ(L"[42] something happened", - fmt::vsprintf(L"[%d] %s happened", - {fmt::make_wprintf_args(42, L"something")})); -#endif -} - + TestLength<std::ptrdiff_t>("t"); + long double max = max_value<long double>(); + EXPECT_PRINTF(fmt::format("{:.6}", max), "%g", max); + EXPECT_PRINTF(fmt::format("{:.6}", max), "%Lg", max); +} + +TEST(PrintfTest, Bool) { + EXPECT_PRINTF("1", "%d", true); + EXPECT_PRINTF("true", "%s", true); +} + +TEST(PrintfTest, Int) { + EXPECT_PRINTF("-42", "%d", -42); + EXPECT_PRINTF("-42", "%i", -42); + unsigned u = 0 - 42u; + EXPECT_PRINTF(fmt::format("{}", u), "%u", -42); + EXPECT_PRINTF(fmt::format("{:o}", u), "%o", -42); + EXPECT_PRINTF(fmt::format("{:x}", u), "%x", -42); + EXPECT_PRINTF(fmt::format("{:X}", u), "%X", -42); +} + +TEST(PrintfTest, long_long) { + // fmt::printf allows passing long long arguments to %d without length + // specifiers. + long long max = max_value<long long>(); + EXPECT_PRINTF(fmt::format("{}", max), "%d", max); +} + +TEST(PrintfTest, Float) { + EXPECT_PRINTF("392.650000", "%f", 392.65); + EXPECT_PRINTF("392.65", "%.2f", 392.65); + EXPECT_PRINTF("392.6", "%.1f", 392.65); + EXPECT_PRINTF("393", "%.f", 392.65); + EXPECT_PRINTF("392.650000", "%F", 392.65); + char buffer[BUFFER_SIZE]; + safe_sprintf(buffer, "%e", 392.65); + EXPECT_PRINTF(buffer, "%e", 392.65); + safe_sprintf(buffer, "%E", 392.65); + EXPECT_PRINTF(buffer, "%E", 392.65); + EXPECT_PRINTF("392.65", "%g", 392.65); + EXPECT_PRINTF("392.65", "%G", 392.65); + EXPECT_PRINTF("392", "%g", 392.0); + EXPECT_PRINTF("392", "%G", 392.0); + EXPECT_PRINTF("4.56e-07", "%g", 0.000000456); + safe_sprintf(buffer, "%a", -392.65); + EXPECT_EQ(buffer, format("{:a}", -392.65)); + safe_sprintf(buffer, "%A", -392.65); + EXPECT_EQ(buffer, format("{:A}", -392.65)); +} + +TEST(PrintfTest, Inf) { + double inf = std::numeric_limits<double>::infinity(); + for (const char* type = "fega"; *type; ++type) { + EXPECT_PRINTF("inf", fmt::format("%{}", *type), inf); + char upper = static_cast<char>(std::toupper(*type)); + EXPECT_PRINTF("INF", fmt::format("%{}", upper), inf); + } +} + +TEST(PrintfTest, Char) { + EXPECT_PRINTF("x", "%c", 'x'); + int max = max_value<int>(); + EXPECT_PRINTF(fmt::format("{}", static_cast<char>(max)), "%c", max); + // EXPECT_PRINTF("x", "%lc", L'x'); + EXPECT_PRINTF(L"x", L"%c", L'x'); + EXPECT_PRINTF(fmt::format(L"{}", static_cast<wchar_t>(max)), L"%c", max); +} + +TEST(PrintfTest, String) { + EXPECT_PRINTF("abc", "%s", "abc"); + const char* null_str = nullptr; + EXPECT_PRINTF("(null)", "%s", null_str); + EXPECT_PRINTF(" (null)", "%10s", null_str); + EXPECT_PRINTF(L"abc", L"%s", L"abc"); + const wchar_t* null_wstr = nullptr; + EXPECT_PRINTF(L"(null)", L"%s", null_wstr); + EXPECT_PRINTF(L" (null)", L"%10s", null_wstr); +} + +TEST(PrintfTest, UCharString) { + unsigned char str[] = "test"; + unsigned char* pstr = str; + EXPECT_EQ("test", fmt::sprintf("%s", pstr)); +} + +TEST(PrintfTest, Pointer) { + int n; + void* p = &n; + EXPECT_PRINTF(fmt::format("{}", p), "%p", p); + p = nullptr; + EXPECT_PRINTF("(nil)", "%p", p); + EXPECT_PRINTF(" (nil)", "%10p", p); + const char* s = "test"; + EXPECT_PRINTF(fmt::format("{:p}", s), "%p", s); + const char* null_str = nullptr; + EXPECT_PRINTF("(nil)", "%p", null_str); + + p = &n; + EXPECT_PRINTF(fmt::format(L"{}", p), L"%p", p); + p = nullptr; + EXPECT_PRINTF(L"(nil)", L"%p", p); + EXPECT_PRINTF(L" (nil)", L"%10p", p); + const wchar_t* w = L"test"; + EXPECT_PRINTF(fmt::format(L"{:p}", w), L"%p", w); + const wchar_t* null_wstr = nullptr; + EXPECT_PRINTF(L"(nil)", L"%p", null_wstr); +} + +TEST(PrintfTest, Location) { + // TODO: test %n +} + +enum test_enum { answer = 42 }; + +TEST(PrintfTest, Enum) { + EXPECT_PRINTF("42", "%d", answer); + volatile test_enum volatile_enum = answer; + EXPECT_PRINTF("42", "%d", volatile_enum); +} + +#if FMT_USE_FCNTL +TEST(PrintfTest, Examples) { + const char* weekday = "Thursday"; + const char* month = "August"; + int day = 21; + EXPECT_WRITE(stdout, fmt::printf("%1$s, %3$d %2$s", weekday, month, day), + "Thursday, 21 August"); +} + +TEST(PrintfTest, PrintfError) { + fmt::file read_end, write_end; + fmt::file::pipe(read_end, write_end); + int result = fmt::fprintf(read_end.fdopen("r").get(), "test"); + EXPECT_LT(result, 0); +} +#endif + +TEST(PrintfTest, WideString) { EXPECT_EQ(L"abc", fmt::sprintf(L"%s", L"abc")); } + +TEST(PrintfTest, PrintfCustom) { + EXPECT_EQ("abc", test_sprintf("%s", TestString("abc"))); +} + +TEST(PrintfTest, OStream) { + std::ostringstream os; + int ret = fmt::fprintf(os, "Don't %s!", "panic"); + EXPECT_EQ("Don't panic!", os.str()); + EXPECT_EQ(12, ret); +} + +TEST(PrintfTest, VPrintf) { + fmt::format_arg_store<fmt::printf_context, int> as{42}; + fmt::basic_format_args<fmt::printf_context> args(as); + EXPECT_EQ(fmt::vsprintf("%d", args), "42"); + EXPECT_WRITE(stdout, fmt::vprintf("%d", args), "42"); + EXPECT_WRITE(stdout, fmt::vfprintf(stdout, "%d", args), "42"); + EXPECT_WRITE(stdout, fmt::vfprintf(std::cout, "%d", args), "42"); +} + +template <typename... Args> +void check_format_string_regression(fmt::string_view s, const Args&... args) { + fmt::sprintf(s, args...); +} + +TEST(PrintfTest, CheckFormatStringRegression) { + check_format_string_regression("%c%s", 'x', ""); +} + +TEST(PrintfTest, FixedLargeExponent) { + EXPECT_EQ("1000000000000000000000", fmt::sprintf("%.*f", -13, 1e21)); +} + +TEST(PrintfTest, VSPrintfMakeArgsExample) { + fmt::format_arg_store<fmt::printf_context, int, const char*> as{42, + "something"}; + fmt::basic_format_args<fmt::printf_context> args(as); + EXPECT_EQ("[42] something happened", fmt::vsprintf("[%d] %s happened", args)); + auto as2 = fmt::make_printf_args(42, "something"); + fmt::basic_format_args<fmt::printf_context> args2(as2); + EXPECT_EQ("[42] something happened", + fmt::vsprintf("[%d] %s happened", args2)); + // The older gcc versions can't cast the return value. +#if !defined(__GNUC__) || (__GNUC__ > 4) + EXPECT_EQ("[42] something happened", + fmt::vsprintf("[%d] %s happened", + {fmt::make_printf_args(42, "something")})); +#endif +} + +TEST(PrintfTest, VSPrintfMakeWArgsExample) { + fmt::format_arg_store<fmt::wprintf_context, int, const wchar_t*> as{ + 42, L"something"}; + fmt::basic_format_args<fmt::wprintf_context> args(as); + EXPECT_EQ(L"[42] something happened", + fmt::vsprintf(L"[%d] %s happened", args)); + auto as2 = fmt::make_wprintf_args(42, L"something"); + fmt::basic_format_args<fmt::wprintf_context> args2(as2); + EXPECT_EQ(L"[42] something happened", + fmt::vsprintf(L"[%d] %s happened", args2)); + // the older gcc versions can't cast the return value +#if !defined(__GNUC__) || (__GNUC__ > 4) + EXPECT_EQ(L"[42] something happened", + fmt::vsprintf(L"[%d] %s happened", + {fmt::make_wprintf_args(42, L"something")})); +#endif +} + TEST(PrintfTest, PrintfDetermineOutputSize) { using backit = std::back_insert_iterator<std::vector<char>>; using truncated_printf_context = fmt::basic_printf_context<fmt::detail::truncating_iterator<backit>, char>; - + auto v = std::vector<char>{}; auto it = std::back_inserter(v); - + const auto format_string = "%s"; const auto format_arg = "Hello"; const auto expected_size = fmt::sprintf(format_string, format_arg).size(); - + EXPECT_EQ((truncated_printf_context( fmt::detail::truncating_iterator<backit>(it, 0), format_string, fmt::make_format_args<truncated_printf_context>(format_arg)) .format() .count()), expected_size); -} +} diff --git a/contrib/libs/fmt/test/printf-test/ya.make b/contrib/libs/fmt/test/printf-test/ya.make index 4c27379ea4..ec264a6c81 100644 --- a/contrib/libs/fmt/test/printf-test/ya.make +++ b/contrib/libs/fmt/test/printf-test/ya.make @@ -1,37 +1,37 @@ -# Generated by devtools/yamaker. - +# Generated by devtools/yamaker. + GTEST() - + WITHOUT_LICENSE_TEXTS() - + OWNER( orivej g:cpp-contrib ) -LICENSE(MIT) - -PEERDIR( - contrib/libs/fmt - contrib/libs/fmt/test -) - -NO_COMPILER_WARNINGS() - -NO_UTIL() - -CFLAGS( - -DFMT_LOCALE - -DFMT_SHARED - -DGTEST_HAS_STD_WSTRING=1 - -DGTEST_LANG_CXX11=0 - -D_SILENCE_TR1_NAMESPACE_DEPRECATION_WARNING=1 -) - -SRCDIR(contrib/libs/fmt/test) - -SRCS( - printf-test.cc -) - -END() +LICENSE(MIT) + +PEERDIR( + contrib/libs/fmt + contrib/libs/fmt/test +) + +NO_COMPILER_WARNINGS() + +NO_UTIL() + +CFLAGS( + -DFMT_LOCALE + -DFMT_SHARED + -DGTEST_HAS_STD_WSTRING=1 + -DGTEST_LANG_CXX11=0 + -D_SILENCE_TR1_NAMESPACE_DEPRECATION_WARNING=1 +) + +SRCDIR(contrib/libs/fmt/test) + +SRCS( + printf-test.cc +) + +END() diff --git a/contrib/libs/fmt/test/ranges-test.cc b/contrib/libs/fmt/test/ranges-test.cc index a45ea55f25..394f7b81be 100644 --- a/contrib/libs/fmt/test/ranges-test.cc +++ b/contrib/libs/fmt/test/ranges-test.cc @@ -1,144 +1,144 @@ -// Formatting library for C++ - the core API -// -// Copyright (c) 2012 - present, Victor Zverovich -// All rights reserved. -// -// For the license information refer to format.h. -// -// Copyright (c) 2018 - present, Remotion (Igor Schulz) -// All Rights Reserved -// {fmt} support for ranges, containers and types tuple interface. - -#include "fmt/ranges.h" - -#include <gtest/gtest.h> - -// Check if 'if constexpr' is supported. -#if (__cplusplus > 201402L) || \ - (defined(_MSVC_LANG) && _MSVC_LANG > 201402L && _MSC_VER >= 1910) - -# include <array> -# include <map> -# include <string> -# include <vector> - -TEST(RangesTest, FormatVector) { - std::vector<int32_t> iv{1, 2, 3, 5, 7, 11}; - auto ivf = fmt::format("{}", iv); - EXPECT_EQ("{1, 2, 3, 5, 7, 11}", ivf); -} - -TEST(RangesTest, FormatVector2) { - std::vector<std::vector<int32_t>> ivv{{1, 2}, {3, 5}, {7, 11}}; - auto ivf = fmt::format("{}", ivv); - EXPECT_EQ("{{1, 2}, {3, 5}, {7, 11}}", ivf); -} - -TEST(RangesTest, FormatMap) { - std::map<std::string, int32_t> simap{{"one", 1}, {"two", 2}}; - EXPECT_EQ("{(\"one\", 1), (\"two\", 2)}", fmt::format("{}", simap)); -} - -TEST(RangesTest, FormatPair) { - std::pair<int64_t, float> pa1{42, 1.5f}; - EXPECT_EQ("(42, 1.5)", fmt::format("{}", pa1)); -} - -TEST(RangesTest, FormatTuple) { - std::tuple<int64_t, float, std::string, char> t{42, 1.5f, "this is tuple", - 'i'}; - EXPECT_EQ("(42, 1.5, \"this is tuple\", 'i')", fmt::format("{}", t)); - EXPECT_EQ("()", fmt::format("{}", std::tuple<>())); -} - -TEST(RangesTest, JoinTuple) { - // Value tuple args - std::tuple<char, int, float> t1 = std::make_tuple('a', 1, 2.0f); +// Formatting library for C++ - the core API +// +// Copyright (c) 2012 - present, Victor Zverovich +// All rights reserved. +// +// For the license information refer to format.h. +// +// Copyright (c) 2018 - present, Remotion (Igor Schulz) +// All Rights Reserved +// {fmt} support for ranges, containers and types tuple interface. + +#include "fmt/ranges.h" + +#include <gtest/gtest.h> + +// Check if 'if constexpr' is supported. +#if (__cplusplus > 201402L) || \ + (defined(_MSVC_LANG) && _MSVC_LANG > 201402L && _MSC_VER >= 1910) + +# include <array> +# include <map> +# include <string> +# include <vector> + +TEST(RangesTest, FormatVector) { + std::vector<int32_t> iv{1, 2, 3, 5, 7, 11}; + auto ivf = fmt::format("{}", iv); + EXPECT_EQ("{1, 2, 3, 5, 7, 11}", ivf); +} + +TEST(RangesTest, FormatVector2) { + std::vector<std::vector<int32_t>> ivv{{1, 2}, {3, 5}, {7, 11}}; + auto ivf = fmt::format("{}", ivv); + EXPECT_EQ("{{1, 2}, {3, 5}, {7, 11}}", ivf); +} + +TEST(RangesTest, FormatMap) { + std::map<std::string, int32_t> simap{{"one", 1}, {"two", 2}}; + EXPECT_EQ("{(\"one\", 1), (\"two\", 2)}", fmt::format("{}", simap)); +} + +TEST(RangesTest, FormatPair) { + std::pair<int64_t, float> pa1{42, 1.5f}; + EXPECT_EQ("(42, 1.5)", fmt::format("{}", pa1)); +} + +TEST(RangesTest, FormatTuple) { + std::tuple<int64_t, float, std::string, char> t{42, 1.5f, "this is tuple", + 'i'}; + EXPECT_EQ("(42, 1.5, \"this is tuple\", 'i')", fmt::format("{}", t)); + EXPECT_EQ("()", fmt::format("{}", std::tuple<>())); +} + +TEST(RangesTest, JoinTuple) { + // Value tuple args + std::tuple<char, int, float> t1 = std::make_tuple('a', 1, 2.0f); EXPECT_EQ("(a, 1, 2)", fmt::format("({})", fmt::join(t1, ", "))); - - // Testing lvalue tuple args - int x = 4; - std::tuple<char, int&> t2{'b', x}; - EXPECT_EQ("b + 4", fmt::format("{}", fmt::join(t2, " + "))); - - // Empty tuple - std::tuple<> t3; - EXPECT_EQ("", fmt::format("{}", fmt::join(t3, "|"))); - - // Single element tuple - std::tuple<float> t4{4.0f}; + + // Testing lvalue tuple args + int x = 4; + std::tuple<char, int&> t2{'b', x}; + EXPECT_EQ("b + 4", fmt::format("{}", fmt::join(t2, " + "))); + + // Empty tuple + std::tuple<> t3; + EXPECT_EQ("", fmt::format("{}", fmt::join(t3, "|"))); + + // Single element tuple + std::tuple<float> t4{4.0f}; EXPECT_EQ("4", fmt::format("{}", fmt::join(t4, "/"))); -} - -TEST(RangesTest, JoinInitializerList) { - EXPECT_EQ("1, 2, 3", fmt::format("{}", fmt::join({1, 2, 3}, ", "))); - EXPECT_EQ("fmt rocks !", - fmt::format("{}", fmt::join({"fmt", "rocks", "!"}, " "))); -} - -struct my_struct { - int32_t i; - std::string str; // can throw +} + +TEST(RangesTest, JoinInitializerList) { + EXPECT_EQ("1, 2, 3", fmt::format("{}", fmt::join({1, 2, 3}, ", "))); + EXPECT_EQ("fmt rocks !", + fmt::format("{}", fmt::join({"fmt", "rocks", "!"}, " "))); +} + +struct my_struct { + int32_t i; + std::string str; // can throw template <size_t N> decltype(auto) get() const noexcept { - if constexpr (N == 0) - return i; - else if constexpr (N == 1) - return fmt::string_view{str}; - } -}; - + if constexpr (N == 0) + return i; + else if constexpr (N == 1) + return fmt::string_view{str}; + } +}; + template <size_t N> decltype(auto) get(const my_struct& s) noexcept { - return s.get<N>(); -} - -namespace std { - + return s.get<N>(); +} + +namespace std { + template <> struct tuple_size<my_struct> : std::integral_constant<size_t, 2> {}; - + template <size_t N> struct tuple_element<N, my_struct> { - using type = decltype(std::declval<my_struct>().get<N>()); -}; - -} // namespace std - -TEST(RangesTest, FormatStruct) { - my_struct mst{13, "my struct"}; - EXPECT_EQ("(13, \"my struct\")", fmt::format("{}", mst)); -} - -TEST(RangesTest, FormatTo) { - char buf[10]; - auto end = fmt::format_to(buf, "{}", std::vector{1, 2, 3}); - *end = '\0'; - EXPECT_STREQ(buf, "{1, 2, 3}"); -} - -struct path_like { - const path_like* begin() const; - const path_like* end() const; - - operator std::string() const; -}; - -TEST(RangesTest, PathLike) { - EXPECT_FALSE((fmt::is_range<path_like, char>::value)); -} - -#endif // (__cplusplus > 201402L) || (defined(_MSVC_LANG) && _MSVC_LANG > - // 201402L && _MSC_VER >= 1910) - -#ifdef FMT_USE_STRING_VIEW -struct string_like { - const char* begin(); - const char* end(); - explicit operator fmt::string_view() const { return "foo"; } - explicit operator std::string_view() const { return "foo"; } -}; - -TEST(RangesTest, FormatStringLike) { - EXPECT_EQ("foo", fmt::format("{}", string_like())); -} -#endif // FMT_USE_STRING_VIEW + using type = decltype(std::declval<my_struct>().get<N>()); +}; + +} // namespace std + +TEST(RangesTest, FormatStruct) { + my_struct mst{13, "my struct"}; + EXPECT_EQ("(13, \"my struct\")", fmt::format("{}", mst)); +} + +TEST(RangesTest, FormatTo) { + char buf[10]; + auto end = fmt::format_to(buf, "{}", std::vector{1, 2, 3}); + *end = '\0'; + EXPECT_STREQ(buf, "{1, 2, 3}"); +} + +struct path_like { + const path_like* begin() const; + const path_like* end() const; + + operator std::string() const; +}; + +TEST(RangesTest, PathLike) { + EXPECT_FALSE((fmt::is_range<path_like, char>::value)); +} + +#endif // (__cplusplus > 201402L) || (defined(_MSVC_LANG) && _MSVC_LANG > + // 201402L && _MSC_VER >= 1910) + +#ifdef FMT_USE_STRING_VIEW +struct string_like { + const char* begin(); + const char* end(); + explicit operator fmt::string_view() const { return "foo"; } + explicit operator std::string_view() const { return "foo"; } +}; + +TEST(RangesTest, FormatStringLike) { + EXPECT_EQ("foo", fmt::format("{}", string_like())); +} +#endif // FMT_USE_STRING_VIEW struct zstring_sentinel {}; diff --git a/contrib/libs/fmt/test/ranges-test/ya.make b/contrib/libs/fmt/test/ranges-test/ya.make index 194968c38b..6856e12893 100644 --- a/contrib/libs/fmt/test/ranges-test/ya.make +++ b/contrib/libs/fmt/test/ranges-test/ya.make @@ -1,37 +1,37 @@ -# Generated by devtools/yamaker. - +# Generated by devtools/yamaker. + GTEST() - + WITHOUT_LICENSE_TEXTS() - + OWNER( orivej g:cpp-contrib ) -LICENSE(MIT) - -PEERDIR( - contrib/libs/fmt - contrib/libs/fmt/test -) - -NO_COMPILER_WARNINGS() - -NO_UTIL() - -CFLAGS( - -DFMT_LOCALE - -DFMT_SHARED - -DGTEST_HAS_STD_WSTRING=1 - -DGTEST_LANG_CXX11=0 - -D_SILENCE_TR1_NAMESPACE_DEPRECATION_WARNING=1 -) - -SRCDIR(contrib/libs/fmt/test) - -SRCS( - ranges-test.cc -) - -END() +LICENSE(MIT) + +PEERDIR( + contrib/libs/fmt + contrib/libs/fmt/test +) + +NO_COMPILER_WARNINGS() + +NO_UTIL() + +CFLAGS( + -DFMT_LOCALE + -DFMT_SHARED + -DGTEST_HAS_STD_WSTRING=1 + -DGTEST_LANG_CXX11=0 + -D_SILENCE_TR1_NAMESPACE_DEPRECATION_WARNING=1 +) + +SRCDIR(contrib/libs/fmt/test) + +SRCS( + ranges-test.cc +) + +END() diff --git a/contrib/libs/fmt/test/scan-test.cc b/contrib/libs/fmt/test/scan-test.cc index 3542cdc2cb..90c0edef9b 100644 --- a/contrib/libs/fmt/test/scan-test.cc +++ b/contrib/libs/fmt/test/scan-test.cc @@ -1,116 +1,116 @@ -// Formatting library for C++ - scanning API test -// -// Copyright (c) 2019 - present, Victor Zverovich -// All rights reserved. -// -// For the license information refer to format.h. - +// Formatting library for C++ - scanning API test +// +// Copyright (c) 2019 - present, Victor Zverovich +// All rights reserved. +// +// For the license information refer to format.h. + #include "scan.h" -#include <time.h> - -#include <climits> - -#include <gmock/gmock.h> -#include "gtest-extra.h" - -TEST(ScanTest, ReadText) { - fmt::string_view s = "foo"; - auto end = fmt::scan(s, "foo"); - EXPECT_EQ(end, s.end()); - EXPECT_THROW_MSG(fmt::scan("fob", "foo"), fmt::format_error, "invalid input"); -} - -TEST(ScanTest, ReadInt) { - int n = 0; - fmt::scan("42", "{}", n); - EXPECT_EQ(n, 42); - fmt::scan("-42", "{}", n); - EXPECT_EQ(n, -42); -} - -TEST(ScanTest, ReadLongLong) { - long long n = 0; - fmt::scan("42", "{}", n); - EXPECT_EQ(n, 42); - fmt::scan("-42", "{}", n); - EXPECT_EQ(n, -42); -} - -TEST(ScanTest, ReadUInt) { - unsigned n = 0; - fmt::scan("42", "{}", n); - EXPECT_EQ(n, 42); - EXPECT_THROW_MSG(fmt::scan("-42", "{}", n), fmt::format_error, - "invalid input"); -} - -TEST(ScanTest, ReadULongLong) { - unsigned long long n = 0; - fmt::scan("42", "{}", n); - EXPECT_EQ(n, 42); - EXPECT_THROW_MSG(fmt::scan("-42", "{}", n), fmt::format_error, - "invalid input"); -} - -TEST(ScanTest, ReadString) { - std::string s; - fmt::scan("foo", "{}", s); - EXPECT_EQ(s, "foo"); -} - -TEST(ScanTest, ReadStringView) { - fmt::string_view s; - fmt::scan("foo", "{}", s); - EXPECT_EQ(s, "foo"); -} - -#ifndef _WIN32 -namespace fmt { -template <> struct scanner<tm> { - std::string format; - - scan_parse_context::iterator parse(scan_parse_context& ctx) { - auto it = ctx.begin(); - if (it != ctx.end() && *it == ':') ++it; - auto end = it; - while (end != ctx.end() && *end != '}') ++end; +#include <time.h> + +#include <climits> + +#include <gmock/gmock.h> +#include "gtest-extra.h" + +TEST(ScanTest, ReadText) { + fmt::string_view s = "foo"; + auto end = fmt::scan(s, "foo"); + EXPECT_EQ(end, s.end()); + EXPECT_THROW_MSG(fmt::scan("fob", "foo"), fmt::format_error, "invalid input"); +} + +TEST(ScanTest, ReadInt) { + int n = 0; + fmt::scan("42", "{}", n); + EXPECT_EQ(n, 42); + fmt::scan("-42", "{}", n); + EXPECT_EQ(n, -42); +} + +TEST(ScanTest, ReadLongLong) { + long long n = 0; + fmt::scan("42", "{}", n); + EXPECT_EQ(n, 42); + fmt::scan("-42", "{}", n); + EXPECT_EQ(n, -42); +} + +TEST(ScanTest, ReadUInt) { + unsigned n = 0; + fmt::scan("42", "{}", n); + EXPECT_EQ(n, 42); + EXPECT_THROW_MSG(fmt::scan("-42", "{}", n), fmt::format_error, + "invalid input"); +} + +TEST(ScanTest, ReadULongLong) { + unsigned long long n = 0; + fmt::scan("42", "{}", n); + EXPECT_EQ(n, 42); + EXPECT_THROW_MSG(fmt::scan("-42", "{}", n), fmt::format_error, + "invalid input"); +} + +TEST(ScanTest, ReadString) { + std::string s; + fmt::scan("foo", "{}", s); + EXPECT_EQ(s, "foo"); +} + +TEST(ScanTest, ReadStringView) { + fmt::string_view s; + fmt::scan("foo", "{}", s); + EXPECT_EQ(s, "foo"); +} + +#ifndef _WIN32 +namespace fmt { +template <> struct scanner<tm> { + std::string format; + + scan_parse_context::iterator parse(scan_parse_context& ctx) { + auto it = ctx.begin(); + if (it != ctx.end() && *it == ':') ++it; + auto end = it; + while (end != ctx.end() && *end != '}') ++end; format.reserve(detail::to_unsigned(end - it + 1)); - format.append(it, end); - format.push_back('\0'); - return end; - } - - template <class ScanContext> - typename ScanContext::iterator scan(tm& t, ScanContext& ctx) { - auto result = strptime(ctx.begin(), format.c_str(), &t); - if (!result) throw format_error("failed to parse time"); - return result; - } -}; -} // namespace fmt - -TEST(ScanTest, ReadCustom) { - const char* input = "Date: 1985-10-25"; - auto t = tm(); - fmt::scan(input, "Date: {0:%Y-%m-%d}", t); - EXPECT_EQ(t.tm_year, 85); - EXPECT_EQ(t.tm_mon, 9); - EXPECT_EQ(t.tm_mday, 25); -} -#endif - -TEST(ScanTest, InvalidFormat) { - EXPECT_THROW_MSG(fmt::scan("", "{}"), fmt::format_error, - "argument index out of range"); - EXPECT_THROW_MSG(fmt::scan("", "{"), fmt::format_error, - "invalid format string"); -} - -TEST(ScanTest, Example) { - std::string key; - int value; - fmt::scan("answer = 42", "{} = {}", key, value); - EXPECT_EQ(key, "answer"); - EXPECT_EQ(value, 42); -} + format.append(it, end); + format.push_back('\0'); + return end; + } + + template <class ScanContext> + typename ScanContext::iterator scan(tm& t, ScanContext& ctx) { + auto result = strptime(ctx.begin(), format.c_str(), &t); + if (!result) throw format_error("failed to parse time"); + return result; + } +}; +} // namespace fmt + +TEST(ScanTest, ReadCustom) { + const char* input = "Date: 1985-10-25"; + auto t = tm(); + fmt::scan(input, "Date: {0:%Y-%m-%d}", t); + EXPECT_EQ(t.tm_year, 85); + EXPECT_EQ(t.tm_mon, 9); + EXPECT_EQ(t.tm_mday, 25); +} +#endif + +TEST(ScanTest, InvalidFormat) { + EXPECT_THROW_MSG(fmt::scan("", "{}"), fmt::format_error, + "argument index out of range"); + EXPECT_THROW_MSG(fmt::scan("", "{"), fmt::format_error, + "invalid format string"); +} + +TEST(ScanTest, Example) { + std::string key; + int value; + fmt::scan("answer = 42", "{} = {}", key, value); + EXPECT_EQ(key, "answer"); + EXPECT_EQ(value, 42); +} diff --git a/contrib/libs/fmt/test/scan-test/ya.make b/contrib/libs/fmt/test/scan-test/ya.make index d8219e04b9..2a3a49bd9a 100644 --- a/contrib/libs/fmt/test/scan-test/ya.make +++ b/contrib/libs/fmt/test/scan-test/ya.make @@ -1,37 +1,37 @@ -# Generated by devtools/yamaker. - +# Generated by devtools/yamaker. + GTEST() - + WITHOUT_LICENSE_TEXTS() - + OWNER( orivej g:cpp-contrib ) -LICENSE(MIT) - -PEERDIR( - contrib/libs/fmt - contrib/libs/fmt/test -) - -NO_COMPILER_WARNINGS() - -NO_UTIL() - -CFLAGS( - -DFMT_LOCALE - -DFMT_SHARED - -DGTEST_HAS_STD_WSTRING=1 - -DGTEST_LANG_CXX11=0 - -D_SILENCE_TR1_NAMESPACE_DEPRECATION_WARNING=1 -) - -SRCDIR(contrib/libs/fmt/test) - -SRCS( - scan-test.cc -) - -END() +LICENSE(MIT) + +PEERDIR( + contrib/libs/fmt + contrib/libs/fmt/test +) + +NO_COMPILER_WARNINGS() + +NO_UTIL() + +CFLAGS( + -DFMT_LOCALE + -DFMT_SHARED + -DGTEST_HAS_STD_WSTRING=1 + -DGTEST_LANG_CXX11=0 + -D_SILENCE_TR1_NAMESPACE_DEPRECATION_WARNING=1 +) + +SRCDIR(contrib/libs/fmt/test) + +SRCS( + scan-test.cc +) + +END() diff --git a/contrib/libs/fmt/test/scan.h b/contrib/libs/fmt/test/scan.h index c4faf54863..de82067a49 100644 --- a/contrib/libs/fmt/test/scan.h +++ b/contrib/libs/fmt/test/scan.h @@ -1,238 +1,238 @@ -// Formatting library for C++ - scanning API proof of concept -// -// Copyright (c) 2019 - present, Victor Zverovich -// All rights reserved. -// -// For the license information refer to format.h. - -#include <array> -#include <cassert> -#include <climits> - -#include "fmt/format.h" - -FMT_BEGIN_NAMESPACE -template <typename T, typename Char = char> struct scanner { - // A deleted default constructor indicates a disabled scanner. - scanner() = delete; -}; - -class scan_parse_context { - private: - string_view format_; - - public: - using iterator = string_view::iterator; - - explicit FMT_CONSTEXPR scan_parse_context(string_view format) - : format_(format) {} - - FMT_CONSTEXPR iterator begin() const { return format_.begin(); } - FMT_CONSTEXPR iterator end() const { return format_.end(); } - - void advance_to(iterator it) { +// Formatting library for C++ - scanning API proof of concept +// +// Copyright (c) 2019 - present, Victor Zverovich +// All rights reserved. +// +// For the license information refer to format.h. + +#include <array> +#include <cassert> +#include <climits> + +#include "fmt/format.h" + +FMT_BEGIN_NAMESPACE +template <typename T, typename Char = char> struct scanner { + // A deleted default constructor indicates a disabled scanner. + scanner() = delete; +}; + +class scan_parse_context { + private: + string_view format_; + + public: + using iterator = string_view::iterator; + + explicit FMT_CONSTEXPR scan_parse_context(string_view format) + : format_(format) {} + + FMT_CONSTEXPR iterator begin() const { return format_.begin(); } + FMT_CONSTEXPR iterator end() const { return format_.end(); } + + void advance_to(iterator it) { format_.remove_prefix(detail::to_unsigned(it - begin())); - } -}; - -struct scan_context { - private: - string_view input_; - - public: - using iterator = const char*; - - explicit scan_context(string_view input) : input_(input) {} - - iterator begin() const { return input_.data(); } - iterator end() const { return begin() + input_.size(); } - - void advance_to(iterator it) { + } +}; + +struct scan_context { + private: + string_view input_; + + public: + using iterator = const char*; + + explicit scan_context(string_view input) : input_(input) {} + + iterator begin() const { return input_.data(); } + iterator end() const { return begin() + input_.size(); } + + void advance_to(iterator it) { input_.remove_prefix(detail::to_unsigned(it - begin())); - } -}; - + } +}; + namespace detail { -enum class scan_type { - none_type, - int_type, - uint_type, - long_long_type, - ulong_long_type, - string_type, - string_view_type, - custom_type -}; - -struct custom_scan_arg { - void* value; - void (*scan)(void* arg, scan_parse_context& parse_ctx, scan_context& ctx); -}; - -class scan_arg { - public: - scan_type type; - union { - int* int_value; - unsigned* uint_value; - long long* long_long_value; - unsigned long long* ulong_long_value; - std::string* string; - fmt::string_view* string_view; - custom_scan_arg custom; - // TODO: more types - }; - - scan_arg() : type(scan_type::none_type) {} - scan_arg(int& value) : type(scan_type::int_type), int_value(&value) {} - scan_arg(unsigned& value) : type(scan_type::uint_type), uint_value(&value) {} - scan_arg(long long& value) - : type(scan_type::long_long_type), long_long_value(&value) {} - scan_arg(unsigned long long& value) - : type(scan_type::ulong_long_type), ulong_long_value(&value) {} - scan_arg(std::string& value) : type(scan_type::string_type), string(&value) {} - scan_arg(fmt::string_view& value) - : type(scan_type::string_view_type), string_view(&value) {} - template <typename T> scan_arg(T& value) : type(scan_type::custom_type) { - custom.value = &value; - custom.scan = scan_custom_arg<T>; - } - - private: - template <typename T> - static void scan_custom_arg(void* arg, scan_parse_context& parse_ctx, - scan_context& ctx) { - scanner<T> s; - parse_ctx.advance_to(s.parse(parse_ctx)); - ctx.advance_to(s.scan(*static_cast<T*>(arg), ctx)); - } -}; +enum class scan_type { + none_type, + int_type, + uint_type, + long_long_type, + ulong_long_type, + string_type, + string_view_type, + custom_type +}; + +struct custom_scan_arg { + void* value; + void (*scan)(void* arg, scan_parse_context& parse_ctx, scan_context& ctx); +}; + +class scan_arg { + public: + scan_type type; + union { + int* int_value; + unsigned* uint_value; + long long* long_long_value; + unsigned long long* ulong_long_value; + std::string* string; + fmt::string_view* string_view; + custom_scan_arg custom; + // TODO: more types + }; + + scan_arg() : type(scan_type::none_type) {} + scan_arg(int& value) : type(scan_type::int_type), int_value(&value) {} + scan_arg(unsigned& value) : type(scan_type::uint_type), uint_value(&value) {} + scan_arg(long long& value) + : type(scan_type::long_long_type), long_long_value(&value) {} + scan_arg(unsigned long long& value) + : type(scan_type::ulong_long_type), ulong_long_value(&value) {} + scan_arg(std::string& value) : type(scan_type::string_type), string(&value) {} + scan_arg(fmt::string_view& value) + : type(scan_type::string_view_type), string_view(&value) {} + template <typename T> scan_arg(T& value) : type(scan_type::custom_type) { + custom.value = &value; + custom.scan = scan_custom_arg<T>; + } + + private: + template <typename T> + static void scan_custom_arg(void* arg, scan_parse_context& parse_ctx, + scan_context& ctx) { + scanner<T> s; + parse_ctx.advance_to(s.parse(parse_ctx)); + ctx.advance_to(s.scan(*static_cast<T*>(arg), ctx)); + } +}; } // namespace detail - -struct scan_args { - int size; + +struct scan_args { + int size; const detail::scan_arg* data; - - template <size_t N> + + template <size_t N> scan_args(const std::array<detail::scan_arg, N>& store) - : size(N), data(store.data()) { - static_assert(N < INT_MAX, "too many arguments"); - } -}; - + : size(N), data(store.data()) { + static_assert(N < INT_MAX, "too many arguments"); + } +}; + namespace detail { - -struct scan_handler : error_handler { - private: - scan_parse_context parse_ctx_; - scan_context scan_ctx_; - scan_args args_; - int next_arg_id_; - scan_arg arg_; - - template <typename T = unsigned> T read_uint() { - T value = 0; - auto it = scan_ctx_.begin(), end = scan_ctx_.end(); - while (it != end) { - char c = *it++; - if (c < '0' || c > '9') on_error("invalid input"); - // TODO: check overflow - value = value * 10 + static_cast<unsigned>(c - '0'); - } - scan_ctx_.advance_to(it); - return value; - } - - template <typename T = int> T read_int() { - auto it = scan_ctx_.begin(), end = scan_ctx_.end(); - bool negative = it != end && *it == '-'; - if (negative) ++it; - scan_ctx_.advance_to(it); - const auto value = read_uint<typename std::make_unsigned<T>::type>(); - if (negative) return -static_cast<T>(value); - return static_cast<T>(value); - } - - public: - scan_handler(string_view format, string_view input, scan_args args) - : parse_ctx_(format), scan_ctx_(input), args_(args), next_arg_id_(0) {} - - const char* pos() const { return scan_ctx_.begin(); } - - void on_text(const char* begin, const char* end) { - auto size = to_unsigned(end - begin); - auto it = scan_ctx_.begin(); - if (it + size > scan_ctx_.end() || - !std::equal(begin, end, make_checked(it, size))) { - on_error("invalid input"); - } - scan_ctx_.advance_to(it + size); - } - + +struct scan_handler : error_handler { + private: + scan_parse_context parse_ctx_; + scan_context scan_ctx_; + scan_args args_; + int next_arg_id_; + scan_arg arg_; + + template <typename T = unsigned> T read_uint() { + T value = 0; + auto it = scan_ctx_.begin(), end = scan_ctx_.end(); + while (it != end) { + char c = *it++; + if (c < '0' || c > '9') on_error("invalid input"); + // TODO: check overflow + value = value * 10 + static_cast<unsigned>(c - '0'); + } + scan_ctx_.advance_to(it); + return value; + } + + template <typename T = int> T read_int() { + auto it = scan_ctx_.begin(), end = scan_ctx_.end(); + bool negative = it != end && *it == '-'; + if (negative) ++it; + scan_ctx_.advance_to(it); + const auto value = read_uint<typename std::make_unsigned<T>::type>(); + if (negative) return -static_cast<T>(value); + return static_cast<T>(value); + } + + public: + scan_handler(string_view format, string_view input, scan_args args) + : parse_ctx_(format), scan_ctx_(input), args_(args), next_arg_id_(0) {} + + const char* pos() const { return scan_ctx_.begin(); } + + void on_text(const char* begin, const char* end) { + auto size = to_unsigned(end - begin); + auto it = scan_ctx_.begin(); + if (it + size > scan_ctx_.end() || + !std::equal(begin, end, make_checked(it, size))) { + on_error("invalid input"); + } + scan_ctx_.advance_to(it + size); + } + int on_arg_id() { return on_arg_id(next_arg_id_++); } int on_arg_id(int id) { - if (id >= args_.size) on_error("argument index out of range"); - arg_ = args_.data[id]; + if (id >= args_.size) on_error("argument index out of range"); + arg_ = args_.data[id]; return id; - } + } int on_arg_id(string_view) { return on_error("invalid format"), 0; } - + void on_replacement_field(int, const char*) { - auto it = scan_ctx_.begin(), end = scan_ctx_.end(); - switch (arg_.type) { - case scan_type::int_type: - *arg_.int_value = read_int(); - break; - case scan_type::uint_type: - *arg_.uint_value = read_uint(); - break; - case scan_type::long_long_type: - *arg_.long_long_value = read_int<long long>(); - break; - case scan_type::ulong_long_type: - *arg_.ulong_long_value = read_uint<unsigned long long>(); - break; - case scan_type::string_type: - while (it != end && *it != ' ') arg_.string->push_back(*it++); - scan_ctx_.advance_to(it); - break; - case scan_type::string_view_type: { - auto s = it; - while (it != end && *it != ' ') ++it; - *arg_.string_view = fmt::string_view(s, to_unsigned(it - s)); - scan_ctx_.advance_to(it); - break; - } - case scan_type::none_type: - case scan_type::custom_type: - assert(false); - } - } - + auto it = scan_ctx_.begin(), end = scan_ctx_.end(); + switch (arg_.type) { + case scan_type::int_type: + *arg_.int_value = read_int(); + break; + case scan_type::uint_type: + *arg_.uint_value = read_uint(); + break; + case scan_type::long_long_type: + *arg_.long_long_value = read_int<long long>(); + break; + case scan_type::ulong_long_type: + *arg_.ulong_long_value = read_uint<unsigned long long>(); + break; + case scan_type::string_type: + while (it != end && *it != ' ') arg_.string->push_back(*it++); + scan_ctx_.advance_to(it); + break; + case scan_type::string_view_type: { + auto s = it; + while (it != end && *it != ' ') ++it; + *arg_.string_view = fmt::string_view(s, to_unsigned(it - s)); + scan_ctx_.advance_to(it); + break; + } + case scan_type::none_type: + case scan_type::custom_type: + assert(false); + } + } + const char* on_format_specs(int, const char* begin, const char*) { - if (arg_.type != scan_type::custom_type) return begin; - parse_ctx_.advance_to(begin); - arg_.custom.scan(arg_.custom.value, parse_ctx_, scan_ctx_); - return parse_ctx_.begin(); - } -}; + if (arg_.type != scan_type::custom_type) return begin; + parse_ctx_.advance_to(begin); + arg_.custom.scan(arg_.custom.value, parse_ctx_, scan_ctx_); + return parse_ctx_.begin(); + } +}; } // namespace detail - -template <typename... Args> + +template <typename... Args> std::array<detail::scan_arg, sizeof...(Args)> make_scan_args(Args&... args) { - return {{args...}}; -} - -string_view::iterator vscan(string_view input, string_view format_str, - scan_args args) { + return {{args...}}; +} + +string_view::iterator vscan(string_view input, string_view format_str, + scan_args args) { detail::scan_handler h(format_str, input, args); detail::parse_format_string<false>(format_str, h); - return input.begin() + (h.pos() - &*input.begin()); -} - -template <typename... Args> -string_view::iterator scan(string_view input, string_view format_str, - Args&... args) { - return vscan(input, format_str, make_scan_args(args...)); -} -FMT_END_NAMESPACE + return input.begin() + (h.pos() - &*input.begin()); +} + +template <typename... Args> +string_view::iterator scan(string_view input, string_view format_str, + Args&... args) { + return vscan(input, format_str, make_scan_args(args...)); +} +FMT_END_NAMESPACE diff --git a/contrib/libs/fmt/test/test-assert.h b/contrib/libs/fmt/test/test-assert.h index 0eb7215ee4..f9df580539 100644 --- a/contrib/libs/fmt/test/test-assert.h +++ b/contrib/libs/fmt/test/test-assert.h @@ -1,32 +1,32 @@ -// Formatting library for C++ - test version of FMT_ASSERT -// -// Copyright (c) 2012 - present, Victor Zverovich -// All rights reserved. -// -// For the license information refer to format.h. - -#ifndef FMT_TEST_ASSERT_H_ -#define FMT_TEST_ASSERT_H_ - -#include <stdexcept> - -#include <gtest/gtest.h> - -class assertion_failure : public std::logic_error { - public: - explicit assertion_failure(const char* message) : std::logic_error(message) {} - - private: - virtual void avoid_weak_vtable(); -}; - -void assertion_failure::avoid_weak_vtable() {} - -#define FMT_ASSERT(condition, message) \ - if (!(condition)) throw assertion_failure(message); - -// Expects an assertion failure. -#define EXPECT_ASSERT(stmt, message) \ - FMT_TEST_THROW_(stmt, assertion_failure, message, GTEST_NONFATAL_FAILURE_) - -#endif // FMT_TEST_ASSERT_H_ +// Formatting library for C++ - test version of FMT_ASSERT +// +// Copyright (c) 2012 - present, Victor Zverovich +// All rights reserved. +// +// For the license information refer to format.h. + +#ifndef FMT_TEST_ASSERT_H_ +#define FMT_TEST_ASSERT_H_ + +#include <stdexcept> + +#include <gtest/gtest.h> + +class assertion_failure : public std::logic_error { + public: + explicit assertion_failure(const char* message) : std::logic_error(message) {} + + private: + virtual void avoid_weak_vtable(); +}; + +void assertion_failure::avoid_weak_vtable() {} + +#define FMT_ASSERT(condition, message) \ + if (!(condition)) throw assertion_failure(message); + +// Expects an assertion failure. +#define EXPECT_ASSERT(stmt, message) \ + FMT_TEST_THROW_(stmt, assertion_failure, message, GTEST_NONFATAL_FAILURE_) + +#endif // FMT_TEST_ASSERT_H_ diff --git a/contrib/libs/fmt/test/util.cc b/contrib/libs/fmt/test/util.cc index 116e8a3a0a..d08dcbdcbf 100644 --- a/contrib/libs/fmt/test/util.cc +++ b/contrib/libs/fmt/test/util.cc @@ -1,50 +1,50 @@ -// Formatting library for C++ - test utilities -// -// Copyright (c) 2012 - present, Victor Zverovich -// All rights reserved. -// -// For the license information refer to format.h. - -#include "util.h" +// Formatting library for C++ - test utilities +// +// Copyright (c) 2012 - present, Victor Zverovich +// All rights reserved. +// +// For the license information refer to format.h. -#include <cstring> - -void increment(char* s) { - for (int i = static_cast<int>(std::strlen(s)) - 1; i >= 0; --i) { - if (s[i] != '9') { - ++s[i]; - break; - } - s[i] = '0'; - } -} - -std::string get_system_error(int error_code) { -#if defined(__MINGW32__) || !defined(_WIN32) - return strerror(error_code); -#else - enum { BUFFER_SIZE = 200 }; - char buffer[BUFFER_SIZE]; - if (strerror_s(buffer, BUFFER_SIZE, error_code)) - throw std::exception("strerror_s failed"); - return buffer; -#endif -} - -const char* const FILE_CONTENT = "Don't panic!"; - -fmt::buffered_file open_buffered_file(FILE** fp) { -#if FMT_USE_FCNTL - fmt::file read_end, write_end; - fmt::file::pipe(read_end, write_end); - write_end.write(FILE_CONTENT, std::strlen(FILE_CONTENT)); - write_end.close(); - fmt::buffered_file f = read_end.fdopen("r"); - if (fp) *fp = f.get(); -#else - fmt::buffered_file f("test-file", "w"); - fputs(FILE_CONTENT, f.get()); - if (fp) *fp = f.get(); -#endif - return f; -} +#include "util.h" + +#include <cstring> + +void increment(char* s) { + for (int i = static_cast<int>(std::strlen(s)) - 1; i >= 0; --i) { + if (s[i] != '9') { + ++s[i]; + break; + } + s[i] = '0'; + } +} + +std::string get_system_error(int error_code) { +#if defined(__MINGW32__) || !defined(_WIN32) + return strerror(error_code); +#else + enum { BUFFER_SIZE = 200 }; + char buffer[BUFFER_SIZE]; + if (strerror_s(buffer, BUFFER_SIZE, error_code)) + throw std::exception("strerror_s failed"); + return buffer; +#endif +} + +const char* const FILE_CONTENT = "Don't panic!"; + +fmt::buffered_file open_buffered_file(FILE** fp) { +#if FMT_USE_FCNTL + fmt::file read_end, write_end; + fmt::file::pipe(read_end, write_end); + write_end.write(FILE_CONTENT, std::strlen(FILE_CONTENT)); + write_end.close(); + fmt::buffered_file f = read_end.fdopen("r"); + if (fp) *fp = f.get(); +#else + fmt::buffered_file f("test-file", "w"); + fputs(FILE_CONTENT, f.get()); + if (fp) *fp = f.get(); +#endif + return f; +} diff --git a/contrib/libs/fmt/test/util.h b/contrib/libs/fmt/test/util.h index ad3b999d38..24a5f4e34b 100644 --- a/contrib/libs/fmt/test/util.h +++ b/contrib/libs/fmt/test/util.h @@ -1,84 +1,84 @@ -// Formatting library for C++ - test utilities -// -// Copyright (c) 2012 - present, Victor Zverovich -// All rights reserved. -// -// For the license information refer to format.h. - -#include <cstdarg> -#include <cstdio> -#include <string> - -#include "fmt/os.h" - -enum { BUFFER_SIZE = 256 }; - -#ifdef _MSC_VER -# define FMT_VSNPRINTF vsprintf_s -#else -# define FMT_VSNPRINTF vsnprintf -#endif - +// Formatting library for C++ - test utilities +// +// Copyright (c) 2012 - present, Victor Zverovich +// All rights reserved. +// +// For the license information refer to format.h. + +#include <cstdarg> +#include <cstdio> +#include <string> + +#include "fmt/os.h" + +enum { BUFFER_SIZE = 256 }; + +#ifdef _MSC_VER +# define FMT_VSNPRINTF vsprintf_s +#else +# define FMT_VSNPRINTF vsnprintf +#endif + template <size_t SIZE> -void safe_sprintf(char (&buffer)[SIZE], const char* format, ...) { - std::va_list args; - va_start(args, format); - FMT_VSNPRINTF(buffer, SIZE, format, args); - va_end(args); -} - -// Increment a number in a string. -void increment(char* s); - -std::string get_system_error(int error_code); - -extern const char* const FILE_CONTENT; - -// Opens a buffered file for reading. -fmt::buffered_file open_buffered_file(FILE** fp = nullptr); - -inline FILE* safe_fopen(const char* filename, const char* mode) { -#if defined(_WIN32) && !defined(__MINGW32__) - // Fix MSVC warning about "unsafe" fopen. - FILE* f = 0; - errno = fopen_s(&f, filename, mode); - return f; -#else - return std::fopen(filename, mode); -#endif -} - -template <typename Char> class BasicTestString { - private: - std::basic_string<Char> value_; - - static const Char EMPTY[]; - - public: - explicit BasicTestString(const Char* value = EMPTY) : value_(value) {} - - const std::basic_string<Char>& value() const { return value_; } -}; - -template <typename Char> const Char BasicTestString<Char>::EMPTY[] = {0}; - -typedef BasicTestString<char> TestString; -typedef BasicTestString<wchar_t> TestWString; - -template <typename Char> -std::basic_ostream<Char>& operator<<(std::basic_ostream<Char>& os, - const BasicTestString<Char>& s) { - os << s.value(); - return os; -} - -class Date { - int year_, month_, day_; - - public: - Date(int year, int month, int day) : year_(year), month_(month), day_(day) {} - - int year() const { return year_; } - int month() const { return month_; } - int day() const { return day_; } -}; +void safe_sprintf(char (&buffer)[SIZE], const char* format, ...) { + std::va_list args; + va_start(args, format); + FMT_VSNPRINTF(buffer, SIZE, format, args); + va_end(args); +} + +// Increment a number in a string. +void increment(char* s); + +std::string get_system_error(int error_code); + +extern const char* const FILE_CONTENT; + +// Opens a buffered file for reading. +fmt::buffered_file open_buffered_file(FILE** fp = nullptr); + +inline FILE* safe_fopen(const char* filename, const char* mode) { +#if defined(_WIN32) && !defined(__MINGW32__) + // Fix MSVC warning about "unsafe" fopen. + FILE* f = 0; + errno = fopen_s(&f, filename, mode); + return f; +#else + return std::fopen(filename, mode); +#endif +} + +template <typename Char> class BasicTestString { + private: + std::basic_string<Char> value_; + + static const Char EMPTY[]; + + public: + explicit BasicTestString(const Char* value = EMPTY) : value_(value) {} + + const std::basic_string<Char>& value() const { return value_; } +}; + +template <typename Char> const Char BasicTestString<Char>::EMPTY[] = {0}; + +typedef BasicTestString<char> TestString; +typedef BasicTestString<wchar_t> TestWString; + +template <typename Char> +std::basic_ostream<Char>& operator<<(std::basic_ostream<Char>& os, + const BasicTestString<Char>& s) { + os << s.value(); + return os; +} + +class Date { + int year_, month_, day_; + + public: + Date(int year, int month, int day) : year_(year), month_(month), day_(day) {} + + int year() const { return year_; } + int month() const { return month_; } + int day() const { return day_; } +}; diff --git a/contrib/libs/fmt/test/ya.make b/contrib/libs/fmt/test/ya.make index afba712c09..8db82d6c1e 100644 --- a/contrib/libs/fmt/test/ya.make +++ b/contrib/libs/fmt/test/ya.make @@ -1,9 +1,9 @@ -# Generated by devtools/yamaker. - -LIBRARY() - +# Generated by devtools/yamaker. + +LIBRARY() + WITHOUT_LICENSE_TEXTS() - + OWNER( orivej g:cpp-contrib @@ -11,45 +11,45 @@ OWNER( LICENSE(MIT) -PEERDIR( +PEERDIR( contrib/libs/fmt contrib/restricted/googletest/googlemock -) - -NO_COMPILER_WARNINGS() - -NO_UTIL() - -CFLAGS( - -DFMT_LOCALE - -DFMT_SHARED - -DGTEST_HAS_STD_WSTRING=1 - -DGTEST_LANG_CXX11=0 - -D_SILENCE_TR1_NAMESPACE_DEPRECATION_WARNING=1 -) - -SRCS( - gtest-extra.cc - util.cc -) - -END() - -RECURSE( - assert-test - chrono-test - color-test - compile-test - core-test - format-impl-test - format-test - gtest-extra-test - header-only-test - locale-test - os-test - ostream-test - posix-mock-test - printf-test - ranges-test - scan-test -) +) + +NO_COMPILER_WARNINGS() + +NO_UTIL() + +CFLAGS( + -DFMT_LOCALE + -DFMT_SHARED + -DGTEST_HAS_STD_WSTRING=1 + -DGTEST_LANG_CXX11=0 + -D_SILENCE_TR1_NAMESPACE_DEPRECATION_WARNING=1 +) + +SRCS( + gtest-extra.cc + util.cc +) + +END() + +RECURSE( + assert-test + chrono-test + color-test + compile-test + core-test + format-impl-test + format-test + gtest-extra-test + header-only-test + locale-test + os-test + ostream-test + posix-mock-test + printf-test + ranges-test + scan-test +) diff --git a/contrib/libs/fmt/ya.make b/contrib/libs/fmt/ya.make index 289c312a69..6222739350 100644 --- a/contrib/libs/fmt/ya.make +++ b/contrib/libs/fmt/ya.make @@ -1,44 +1,44 @@ -# Generated by devtools/yamaker from nixpkgs 980c4c3c2f664ccc5002f7fd6e08059cf1f00e75. - -LIBRARY() - +# Generated by devtools/yamaker from nixpkgs 980c4c3c2f664ccc5002f7fd6e08059cf1f00e75. + +LIBRARY() + OWNER( orivej g:cpp-contrib ) - + VERSION(7.1.3) - -ORIGINAL_SOURCE(https://github.com/fmtlib/fmt/archive/7.1.3.tar.gz) - + +ORIGINAL_SOURCE(https://github.com/fmtlib/fmt/archive/7.1.3.tar.gz) + LICENSE( Apache-2.0 WITH LLVM-exception AND MIT AND Public-Domain AND Python-2.0 -) - +) + LICENSE_TEXTS(.yandex_meta/licenses.list.txt) ADDINCL( GLOBAL contrib/libs/fmt/include ) -NO_COMPILER_WARNINGS() - -NO_UTIL() - +NO_COMPILER_WARNINGS() + +NO_UTIL() + CFLAGS( GLOBAL -DFMT_EXPORT ) - -SRCS( - src/format.cc - src/os.cc -) - -END() - -RECURSE( - test -) + +SRCS( + src/format.cc + src/os.cc +) + +END() + +RECURSE( + test +) |