From 0066ad2d3879f4604b3a2644128cf5d447e54eef Mon Sep 17 00:00:00 2001 From: MerryMage Date: Wed, 22 Apr 2020 21:00:18 +0100 Subject: [PATCH] Squashed 'externals/fmt/' changes from 3e75ad982..9e554999c 9e554999c Update version b34d92b05 Bump version d39ece187 Make rst2md runnable and update changelog fe2d715ff Update changelog 27b306701 Update changelog 68837079a Update changelog c98b202eb Update changelog 587a7f663 Update changelog and docs 84e5170c9 Update changelog and deprecate visit 130e412b6 Update changelog and docs 0bbdca5b8 Fix conversion warnings (#989) 77a724480 Implement fill/align/width for strftime-like formatting 3e01376e0 Implement fill/align/width parsing in chrono formatter 1f92f8a9d Remove noexcept 8668639ae Get rid of null_terminating_iterator in format 93fd473b8 Add support for builtin terminal colors. (#974) 61ad543c3 Windows .sln filename changed from FORMAT to FMT 7f7504b3f Clean up docs 37f599b1a Fix docs 8c2e15aed Make printf work in search (#164) de71db6d4 Fix asan error (#977) b180b3915 Fix default formatting 24594c747 Disable printing the reset escape code when no style modifiers where applied. (#973) b0f222471 Implement default chrono formatting 749276072 Add file stream support for stylized text printing. (#967) f54f3d0fb Move chrono-specific code to a separate header bf1f1c73e Fix time test b6bc6ec24 Add default ctor and fix use of constexpr macros in text_style acfa95d4a Workaround a bug in MSVC's strftime (#965) 628f83058 More chrono formatting aa3b5aba4 Implement locale-specific minute formatting 639de2175 Workaround more MSVC bugs 3242ddf7b Fix warnings bd1104046 Workaround a bug in MSVC 81b5c4a5f Add experimental emphasis support (#961) 7c4eb0fbe Fix warnings in time.h 2d624218b Fix another warning b31680990 Fix a warning b10ccb83e Add rpclib to projects 0497875ff Stop the orgy of casts 37dc495b9 Simplify MSVC workaround 2ff4996d0 Fix ambiguous complier error C2666 in vs2017.The '+' opeator may cause ambiguity.Avoid implicit conversion. 77656c672 Fix sign-conversion warnings reported by Clang7 ea5e4790b Fix formatting 86681c4bb Update README.rst e867768ee Do not override user provided compile flag 0c7f5c3ca Update README.rst e7e2ab107 Make return type of basic_format_args::max_size() consistent. 29352af36 Update README.rst 68214bd90 More time formatting bcf3fcd67 Clean up bit fiddling for argument packing 9dcf127fa Workaround a bogus MSVC warning b8b06e3e1 Fix conversion warnings in Grisu 322b2594e Implement more time specifiers 0835f1ba3 Use full paths for fmt.pc.in a084495d7 Add Ceph to projects fa1d4dbcf Fix warnings 2b2cfdac1 Update docs 99744f8f8 Suppress unfixable warning f5fe84923 Specialize formatter for chrono durations a5a9805a9 First stub at the datetime format parser 645c76a9a Fix dummy warnings fecb2d6f0 Eliminate msvc compiler warnings (#931) 64690d3a9 Add context_base::arg() 01640f44c Fully qualify dummy_int (#941) e37d6a984 add make_printf_args and make_wprintf_args functions (#934) 982ee5c69 parse_context -> format_parse_context b7b854855 thousands_sep -> thousands_sep_impl (#939) 00a8cc832 Fix formatting 33fbb3a7e Fix remaining linker errors. bd6121596 Disable fmt-impl-test in windows + shared lib. 702b3d161 Fix link error in windows with shared library. 9d4ef9435 Install pdb files. 6c95fb356 Default Context to format_context 16b78ee62 fix incompatibilities with c++2a mode in clang 19e008876 More locale support f2ee98810 Improve locale support 1385050e2 More formatter tests 03c1b110a Fix gcc 4.4 build cc805c616 Test enabled formatters e01579231 Disallow leading zeros in arg-id 34030deca Cleanup warning flags 6b26e3f2d Manifest & Gradle comment d286c9775 Update for Gradle build d951f6dfe Get latest Gradle (ver. 4.10.2) a23d59247 Fix check_format_string (#925) 36161284e Update docs 38f355d87 Revert "find sphinx-build before calling build.py" 324eac1aa Make locales work with any character type bdda4d603 Simplify compile-time strings 5ee1a4bc8 check for property 'mutable iterator' and SFINAE on it 2dea780fb change type naming and fix sfinae bug b98e8301d add non-char support for compile-time format check ccd3e8bbf Make is_constructible public (#918) 437315380 Update usage.rst 73cfd8f32 Fix colored print ec384302d additional test for print with background color 0a96c032b Parameterize v*printf on string type (#920) 61e6d2e38 Fix core version of vformat_to ea4010d70 Merge has_to_string_view into is_string 486fff597 Add sprintf_format instantiations and remove syntactic noise 1e3dcbba8 fix: 'format_to_n' compiles 'std::back_inserter' arguments f0328f8e3 Use char_traits::length in string_view ctor (#914) 895fb9845 Disallow gcc 4.4 failures 20c708bf6 Fix build on gcc 4.4 9d0c9c4bb cmake: output share/fmt.pc 2d2326a76 Fix compilation with older gcc 1ec027230 Get rid of FMT_UNION 2c81c851b Adapt any string-like type to be used by {fmt} just like the standard string types already supported. The adaption is totally non-intrusive. 846c644e8 Workeround broken sprintf in MSVC 13d472bd8 Compute output size for grisu b71d3fe7a Remove use_grisu 847abb6f8 Fix test dda47c946 Merge min_digits and max_digits 292462215 Fix naming of basic_format_specs members bda5f9a55 Replace grisu2_specs with core_format_specs b1ca608ba Remove unused empty_spec e8efdef8d Avoid extra copy 98f1c1fe8 Remove unused code 50b18a3c1 Integrate Grisu 699297520 Implement Grisu rounding 4bb76ef0c Remove redundant definition of print ddd7caf38 Fix locale-dependent formatting (#905) 10e03e695 use found python executable for launching sphinx-build 07200f445 find sphinx-build before calling build.py 08a65c228 Workaround broken constexpr in MSVC2017 167f8fe32 Fix a typo in api.rst 57983423c Remove signbit workaround 7bebb3e12 Clarify overload resolution in docs 939fbe556 Remove basic_fixed_buffer. 61f81a071 minor documentation corrections f27defc63 Parameterize printf functions on the type of the format string. 6a685571d Make 'std::*::basic_string_view' a valid argument type for 'format_str' parameters. 87a0408c6 Fix ostream.h build 2b5acad4a Remove redundant size argument to write_padded 655ce5338 is_format_string -> is_string fea712abb Parameterize ostream functions on the type of the format string. f16a118e8 Fix non-matching char types. 041bf83d9 Improve fmt::format readability 229903239 Document how to write a formatter for a type hierarchy f5480635c visit -> visit_format_arg cdf3fa08d Put related code together in fmt/core.h 38325248e Count width in code points (#628) deb901b9e Parameterize core functions on the type of the format string. 0f98de301 Update docs c797708fc Workaround strlen being non-constexpr in ARM toolchain 49b4c1e9d Update docs 63a87beba Add to_string_view 4e0c31465 checked_format_args -> checked_args c3538a1ee Simplify variadic functions further 2d7d0835d Simplify variadic functions 3f4cfa6c6 Implement UTF-8 string support f8027414f Impelement char8_t support 76a47d41c Cleanup the use of FMT_CHAR 267fdc7a1 Parameterize core functions on the type of the format string. 5bced1242 Parameterize more functions on string type 674999c52 fix vs2017 warning fmt::v5::localtime 'not all control paths return a value'. e4fea22d1 Make char8_t a strongly-typed enum 66992e90d Clarify that writing to memory_buffer appends (#877) e864acfdb Fix compilation with intel compilers (ICC/ICPC) v14.0 4cf21f58b constrain templated format_to on proper format string type. d7f17613f Fix compilation on platforms with exotic double (#878) e4ca37ccf Parameterize format_to on string type (#880) d66fa2216 Reduce syntactic noise 48e6dcd0f Implement workarounds for gcc 4.4 0ea3221d3 Remove is_named_arg and add FMT_CHAR 73c53d783 Parameterize 'printf(rgb color, ...)' and 'vprint_rgb(rgb color, ...)' on the type of the format string. d41be23ac Simplify string_view detection 2def9e4c8 Remove FMT_DTOR_NOEXCEPT ff6e46ed9 More cleanup 715f2b4c0 Remove require_wchar and internalize no_formatter_error ec0cdc46f Workaround Windows slowness git-subtree-dir: externals/fmt git-subtree-split: 9e554999ce02cf86fcdfe74fe740c4fe3f5a56d5 --- .gitignore | 1 + .travis.yml | 71 +- CMakeLists.txt | 46 +- ChangeLog.rst | 236 ++++++ README.rst | 37 +- doc/api.rst | 63 +- doc/build.py | 6 +- doc/index.rst | 4 +- doc/usage.rst | 9 +- include/fmt/chrono.h | 452 ++++++++++ include/fmt/color.h | 407 +++++++-- include/fmt/core.h | 900 ++++++++++---------- include/fmt/format-inl.h | 548 +++++++----- include/fmt/format.h | 1467 +++++++++++++++------------------ include/fmt/locale.h | 77 ++ include/fmt/ostream.h | 20 +- include/fmt/posix.h | 4 +- include/fmt/printf.h | 367 ++++++--- include/fmt/time.h | 38 +- src/format.cc | 26 +- support/AndroidManifest.xml | 2 +- support/build.gradle | 27 +- support/cmake/fmt.pc.in | 11 + support/rst2md.py | 10 +- test/CMakeLists.txt | 13 +- test/chrono-test.cc | 185 +++++ test/core-test.cc | 167 +++- test/custom-formatter-test.cc | 4 +- test/format-impl-test.cc | 56 +- test/format-test.cc | 322 ++++---- test/gtest-extra-test.cc | 12 +- test/gtest-extra.h | 2 +- test/locale-test.cc | 34 + test/mock-allocator.h | 4 +- test/ostream-test.cc | 9 +- test/posix-mock-test.cc | 16 +- test/posix-test.cc | 24 +- test/printf-test.cc | 179 ++-- test/ranges-test.cc | 3 +- test/time-test.cc | 15 +- test/util.h | 2 +- 41 files changed, 3817 insertions(+), 2059 deletions(-) create mode 100644 include/fmt/chrono.h create mode 100644 include/fmt/locale.h create mode 100644 support/cmake/fmt.pc.in mode change 100644 => 100755 support/rst2md.py create mode 100644 test/chrono-test.cc create mode 100644 test/locale-test.cc diff --git a/.gitignore b/.gitignore index 1e6172fe..694f8f8f 100644 --- a/.gitignore +++ b/.gitignore @@ -31,3 +31,4 @@ CMakeFiles FMT.build Makefile run-msbuild.bat +fmt.pc diff --git a/.travis.yml b/.travis.yml index cbc024d7..da50ae67 100644 --- a/.travis.yml +++ b/.travis.yml @@ -84,42 +84,41 @@ matrix: sources: - ubuntu-toolchain-r-test # Android -# - language: android -# android: -# addons: -# apt: -# update: true -# components: -# - tools -# - platform-tools -# - android-21 -# - sys-img-armeabi-v7a-android-21 -# env: -# - ANDROID=true -# before_install: -# - git submodule update --init --recursive -# - sudo apt-get install wget unzip tree -# install: -# # Accept SDK Licenses + Install NDK -# - yes | sdkmanager --update > /dev/null 2>&1 -# - sdkmanager ndk-bundle > /dev/null 2>&1 -# # Download Gradle 4.3.1 -# - wget https://services.gradle.org/distributions/gradle-4.3.1-bin.zip -# - mkdir -p gradle -# - unzip -q -d ./gradle gradle-4.3.1-bin.zip -# - export GRADLE=${TRAVIS_BUILD_DIR}/gradle/gradle-4.3.1/bin/gradle -# before_script: -# - bash $GRADLE --version -# - cd ./support -# script: -# - bash $GRADLE clean assemble -# after_success: -# - cd ${TRAVIS_BUILD_DIR} -# - tree ./libs - allow_failures: - # Errors - - env: COMPILER=g++-4.4 BUILD=Debug STANDARD=11 - compiler: gcc + - language: android + addons: + apt: + update: true + sources: + - ubuntu-toolchain-r-test + packages: + - wget + - unzip + - tree + android: + components: + - tools + - platform-tools + - android-21 + env: + - ANDROID=true + before_install: + # Download/Install Gradle + - wget https://services.gradle.org/distributions/gradle-4.10.2-bin.zip + - mkdir -p gradle + - unzip -q -d ./gradle gradle-4.10.2-bin.zip + - export GRADLE=gradle/gradle-4.10.2/bin/gradle + - bash $GRADLE --version + install: + # Accept SDK Licenses + Install NDK + - yes | sdkmanager --update > /dev/null 2>&1 + - sdkmanager ndk-bundle > /dev/null 2>&1 + before_script: + - pushd ./support + script: + - bash ../$GRADLE clean assemble + after_success: + - popd; + - tree ./libs before_script: - if [[ "${TRAVIS_OS_NAME}" == "linux" ]]; then export CXX=${COMPILER}; fi diff --git a/CMakeLists.txt b/CMakeLists.txt index f872e3c9..ce9dbf95 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -68,16 +68,17 @@ include(CheckCXXCompilerFlag) if (CMAKE_CXX_COMPILER_ID MATCHES "GNU") set(PEDANTIC_COMPILE_FLAGS -pedantic-errors -Wall -Wextra -pedantic - -Wold-style-cast -Wfloat-equal -Wlogical-op -Wundef - -Wredundant-decls -Wshadow -Wwrite-strings -Wpointer-arith + -Wold-style-cast -Wundef + -Wredundant-decls -Wwrite-strings -Wpointer-arith -Wcast-qual -Wformat=2 -Wmissing-include-dirs -Wcast-align -Wnon-virtual-dtor -Wctor-dtor-privacy -Wdisabled-optimization -Winvalid-pch -Woverloaded-virtual - -Wno-ctor-dtor-privacy -Wno-dangling-else -Wno-float-equal - -Wno-format-nonliteral -Wno-sign-conversion -Wno-shadow) + -Wconversion + -Wno-ctor-dtor-privacy -Wno-format-nonliteral -Wno-shadow) if (NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 4.6) - set(PEDANTIC_COMPILE_FLAGS ${PEDANTIC_COMPILE_FLAGS} -Wnoexcept) + set(PEDANTIC_COMPILE_FLAGS ${PEDANTIC_COMPILE_FLAGS} -Wnoexcept + -Wno-dangling-else -Wno-unused-local-typedefs) endif () if (NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 5.0) set(PEDANTIC_COMPILE_FLAGS ${PEDANTIC_COMPILE_FLAGS} -Wdouble-promotion @@ -88,29 +89,17 @@ if (CMAKE_CXX_COMPILER_ID MATCHES "GNU") set(PEDANTIC_COMPILE_FLAGS ${PEDANTIC_COMPILE_FLAGS} -Wshift-overflow=2 -Wnull-dereference -Wduplicated-cond) endif () - set(WERROR_FLAG -Werror) endif () if (CMAKE_CXX_COMPILER_ID MATCHES "Clang") - set(PEDANTIC_COMPILE_FLAGS -Weverything -Wpedantic - -Wno-weak-vtables -Wno-padded -Wno-gnu-statement-expression - -Wno-c++98-compat -Wno-c++98-compat-pedantic -Wno-reserved-id-macro - -Wno-global-constructors -Wno-disabled-macro-expansion - -Wno-switch-enum -Wno-documentation-unknown-command - -Wno-unused-member-function - -Wno-format-nonliteral -Wno-missing-noreturn -Wno-undefined-func-template - -Wno-shadow -Wno-sign-conversion -Wno-used-but-marked-unused - -Wno-covered-switch-default -Wno-missing-prototypes - -Wno-missing-variable-declarations -Wno-double-promotion) - - set(WERROR_FLAG -Werror) - - check_cxx_compiler_flag(-Wno-zero-as-null-pointer-constant HAS_NULLPTR_WARNING) + set(PEDANTIC_COMPILE_FLAGS -Wall -Wextra -pedantic -Wconversion -Wno-sign-conversion) + check_cxx_compiler_flag(-Wzero-as-null-pointer-constant HAS_NULLPTR_WARNING) if (HAS_NULLPTR_WARNING) set(PEDANTIC_COMPILE_FLAGS ${PEDANTIC_COMPILE_FLAGS} - -Wno-zero-as-null-pointer-constant) + -Wzero-as-null-pointer-constant) endif () + set(WERROR_FLAG -Werror) endif () if (MSVC) @@ -150,8 +139,8 @@ function(add_headers VAR) endfunction() # Define the fmt library, its includes and the needed defines. -add_headers(FMT_HEADERS color.h core.h format.h format-inl.h ostream.h printf.h - time.h ranges.h) +add_headers(FMT_HEADERS chrono.h color.h core.h format.h format-inl.h locale.h + ostream.h printf.h time.h ranges.h) set(FMT_SOURCES src/format.cc) if (HAVE_OPEN) add_headers(FMT_HEADERS posix.h) @@ -202,6 +191,7 @@ if (FMT_INSTALL) "Installation directory for cmake files, relative to ${CMAKE_INSTALL_PREFIX}.") set(version_config ${PROJECT_BINARY_DIR}/fmt-config-version.cmake) set(project_config ${PROJECT_BINARY_DIR}/fmt-config.cmake) + set(pkgconfig ${PROJECT_BINARY_DIR}/fmt.pc) set(targets_export_name fmt-targets) set (INSTALL_TARGETS fmt) @@ -215,11 +205,18 @@ if (FMT_INSTALL) set(FMT_INC_DIR ${CMAKE_INSTALL_INCLUDEDIR}/fmt CACHE STRING "Installation directory for include files, relative to ${CMAKE_INSTALL_PREFIX}.") + set(FMT_PKGCONFIG_DIR "${CMAKE_INSTALL_PREFIX}/share/pkgconfig" CACHE PATH + "Installation directory for pkgconfig (.pc) files, relative to ${CMAKE_INSTALL_PREFIX}.") + # Generate the version, config and target files into the build directory. write_basic_package_version_file( ${version_config} VERSION ${FMT_VERSION} COMPATIBILITY AnyNewerVersion) + configure_file( + "${PROJECT_SOURCE_DIR}/support/cmake/fmt.pc.in" + "${pkgconfig}" + @ONLY) configure_package_config_file( ${PROJECT_SOURCE_DIR}/support/cmake/fmt-config.cmake.in ${project_config} @@ -239,7 +236,10 @@ if (FMT_INSTALL) # Install the library and headers. install(TARGETS ${INSTALL_TARGETS} EXPORT ${targets_export_name} DESTINATION ${FMT_LIB_DIR}) + + install(FILES $ DESTINATION ${FMT_LIB_DIR} OPTIONAL) install(FILES ${FMT_HEADERS} DESTINATION ${FMT_INC_DIR}) + install(FILES "${pkgconfig}" DESTINATION "${FMT_PKGCONFIG_DIR}") endif () if (FMT_DOC) diff --git a/ChangeLog.rst b/ChangeLog.rst index e158e458..72f09d7a 100644 --- a/ChangeLog.rst +++ b/ChangeLog.rst @@ -1,3 +1,239 @@ +5.3.0 - 2018-12-28 +------------------ + +* Introduced experimental chrono formatting support: + + .. code:: c++ + + #include + + 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 `_, + `#967 `_, + `#973 `_): + + .. code:: c++ + + #include + + 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) `_. + +* Added support for 4-bit terminal colors + (`#968 `_, + `#974 `_) + + .. code:: c++ + + #include + + 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) `_. + +* Parameterized formatting functions on the type of the format string + (`#880 `_, + `#881 `_, + `#883 `_, + `#885 `_, + `#897 `_, + `#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) `_. + +* Made ``std::string_view`` work as a format string + (`#898 `_): + + .. code:: c++ + + auto message = fmt::format(std::string_view("The answer is {}."), 42); + + Thanks `@DanielaE (Daniela Engert) `_. + +* Added wide string support to compile-time format string checks + (`#924 `_): + + .. code:: c++ + + print(fmt(L"{:f}"), 42); // compile-time error: invalid type specifier + + Thanks `@XZiar `_. + +* Made colored print functions work with wide strings + (`#867 `_): + + .. code:: c++ + + #include + + int main() { + print(fg(fmt::color::red), L"{}\n", 42); + } + + Thanks `@DanielaE (Daniela Engert) `_. + +* Introduced experimental Unicode support + (`#628 `_, + `#891 `_): + + .. code:: c++ + + using namespace fmt::literals; + auto s = fmt::format("{:*^5}"_u, "🤡"_u); // s == "**🤡**"_u + +* Improved locale support: + + .. code:: c++ + + #include + + struct numpunct : std::numpunct { + 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 `_): + Thanks `@DanielaE (Daniela Engert) `_. + +* Added ``make_printf_args`` and ``make_wprintf_args`` functions + (`#934 `_). + Thanks `@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 `_, + `#902 `_). + Thanks `@superfunc (hollywood programmer) `_. + +* 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 `_). + +* Improved documentation + (`#164 `_, + `#877 `_, + `#901 `_, + `#906 `_, + `#979 `_). + Thanks `@kookjr (Mathew Cucuzella) `_, + `@DarkDimius (Dmitry Petrashko) `_, + `@HecticSerenity `_. + +* Added pkgconfig support which makes it easier to consume the library from + meson and other build systems + (`#916 `_). + Thanks `@colemickens (Cole Mickens) `_. + +* Various build improvements + (`#909 `_, + `#926 `_, + `#937 `_, + `#953 `_, + `#959 `_). + Thanks `@tchaikov (Kefu Chai) `_, + `@luncliff (Park DongHa) `_, + `@AndreasSchoenle (Andreas Schönle) `_, + `@hotwatermorning `_, + `@Zefz (JohanJansen) `_. + +* Improved ``string_view`` construction performance + (`#914 `_). + Thanks `@gabime (Gabi Melman) `_. + +* Fixed non-matching char types + (`#895 `_). + Thanks `@DanielaE (Daniela Engert) `_. + +* Fixed ``format_to_n`` with ``std::back_insert_iterator`` + (`#913 `_). + Thanks `@DanielaE (Daniela Engert) `_. + +* Fixed locale-dependent formatting + (`#905 `_). + +* Fixed various compiler warnings and errors + (`#882 `_, + `#886 `_, + `#933 `_, + `#941 `_, + `#931 `_, + `#943 `_, + `#954 `_, + `#956 `_, + `#962 `_, + `#965 `_, + `#977 `_, + `#983 `_, + `#989 `_). + Thanks `@Luthaf (Guillaume Fraux) `_, + `@stevenhoving (Steven Hoving) `_, + `@christinaa (Kristina Brooks) `_, + `@lgritz (Larry Gritz) `_, + `@DanielaE (Daniela Engert) `_, + `@0x8000-0000 (Sign Bit) `_, + `@liuping1997 `_. + 5.2.1 - 2018-09-21 ------------------ diff --git a/README.rst b/README.rst index bd634a4a..3e43b308 100644 --- a/README.rst +++ b/README.rst @@ -30,7 +30,7 @@ Features of `str.format `_ in Python. * Safe `printf implementation - `_ including + `_ including the POSIX extension for positional arguments. * Support for user-defined types. * High speed: performance of the format API is close to that of glibc's `printf @@ -126,7 +126,7 @@ Formatting of user-defined types is supported via a simple template auto format(const date &d, FormatContext &ctx) { - return format_to(ctx.begin(), "{}-{}-{}", d.year, d.month, d.day); + return format_to(ctx.out(), "{}-{}-{}", d.year, d.month, d.day); } }; @@ -153,19 +153,27 @@ which take arbitrary arguments (`godbolt `_): report_error("file not found: {}", path); Note that ``vreport_error`` is not parameterized on argument types which can -improve compile times and reduce code size compared to fully parameterized version. +improve compile times and reduce code size compared to fully parameterized +version. Projects using this library --------------------------- -* `0 A.D. `_: A free, open-source, cross-platform real-time strategy game +* `0 A.D. `_: A free, open-source, cross-platform real-time + strategy game * `AMPL/MP `_: An open-source library for mathematical programming -* `AvioBook `_: A comprehensive aircraft operations suite +* `AvioBook `_: A comprehensive aircraft + operations suite + +* `Celestia `_: Real-time 3D visualization of space -* `CUAUV `_: Cornell University's autonomous underwater vehicle +* `Ceph `_: A scalable distributed storage system + +* `CUAUV `_: Cornell University's autonomous underwater + vehicle * `HarpyWar/pvpgn `_: Player vs Player Gaming Network with tweaks @@ -200,7 +208,11 @@ Projects using this library * `readpe `_: Read Portable Executable -* `redis-cerberus `_: A Redis cluster proxy +* `redis-cerberus `_: A Redis cluster + proxy + +* `rpclib `_: A modern C++ msgpack-RPC server and client + library * `Saddy `_: Small crossplatform 2D graphic engine @@ -208,11 +220,11 @@ Projects using this library * `Salesforce Analytics Cloud `_: Business intelligence software -* `Scylla `_: A Cassandra-compatible NoSQL data store that can handle - 1 million transactions per second on a single server +* `Scylla `_: A Cassandra-compatible NoSQL data store + that can handle 1 million transactions per second on a single server -* `Seastar `_: An advanced, open-source C++ framework for - high-performance server applications on modern hardware +* `Seastar `_: An advanced, open-source C++ + framework for high-performance server applications on modern hardware * `spdlog `_: Super fast C++ logging library @@ -220,7 +232,8 @@ Projects using this library * `Touch Surgery `_: Surgery simulator -* `TrinityCore `_: Open-source MMORPG framework +* `TrinityCore `_: Open-source + MMORPG framework `More... `_ diff --git a/doc/api.rst b/doc/api.rst index 5ecaaa46..33a4f6d2 100644 --- a/doc/api.rst +++ b/doc/api.rst @@ -26,30 +26,29 @@ Core API and a lightweight subset of formatting functions. The following functions use :ref:`format string syntax ` -imilar to that of Python's `str.format +similar to that of Python's `str.format `_. They take *format_str* and *args* as arguments. *format_str* is a format string that contains literal text and replacement fields surrounded by braces ``{}``. The fields are replaced with formatted -arguments in the resulting string. +arguments in the resulting string. A function taking *format_str* doesn't +participate in an overload resolution if the latter is not a string. *args* is an argument list representing objects to be formatted. .. _format: -.. doxygenfunction:: format(const String&, const Args&...) -.. doxygenfunction:: vformat(const String&, basic_format_args::type>) +.. doxygenfunction:: format(const S&, const Args&...) +.. doxygenfunction:: vformat(const S&, basic_format_args::type>) .. _print: -.. doxygenfunction:: print(string_view, const Args&...) +.. doxygenfunction:: print(const S&, const Args&...) .. doxygenfunction:: vprint(string_view, format_args) -.. doxygenfunction:: print(std::FILE *, string_view, const Args&...) +.. doxygenfunction:: print(std::FILE *, const S&, const Args&...) .. doxygenfunction:: vprint(std::FILE *, string_view, format_args) - -.. doxygenfunction:: print(std::FILE *, wstring_view, const Args&...) .. doxygenfunction:: vprint(std::FILE *, wstring_view, wformat_args) Named arguments @@ -149,6 +148,35 @@ You can also reuse existing formatters, for example:: } }; +You can also write a formatter for a hierarchy of classes:: + + #include + #include + + struct A { + virtual ~A() {} + virtual std::string name() const { return "A"; } + }; + + struct B : A { + virtual std::string name() const { return "B"; } + }; + + template + struct fmt::formatter::value, char>> : + fmt::formatter { + template + auto format(const A& a, FormatCtx& ctx) { + return fmt::formatter::format(a.name(), ctx); + } + }; + + int main() { + B b; + A& a = b; + fmt::print("{}", a); // prints "B" + } + This section shows how to define a custom format function for a user-defined type. The next section describes how to get ``fmt`` to use a conventional stream output ``operator<<`` when one is defined for a user-defined type. @@ -156,7 +184,7 @@ output ``operator<<`` when one is defined for a user-defined type. Output iterator support ----------------------- -.. doxygenfunction:: fmt::format_to(OutputIt, string_view, const Args&...) +.. doxygenfunction:: fmt::format_to(OutputIt, const S&, const Args&...) .. doxygenfunction:: fmt::format_to_n(OutputIt, std::size_t, string_view, const Args&...) .. doxygenstruct:: fmt::format_to_n_result :members: @@ -173,12 +201,16 @@ The following user-defined literals are defined in ``fmt/format.h``. Utilities --------- +.. doxygentypedef:: fmt::char_t + .. doxygenfunction:: fmt::formatted_size(string_view, const Args&...) .. doxygenfunction:: fmt::to_string(const T&) .. doxygenfunction:: fmt::to_wstring(const T&) +.. doxygenfunction:: fmt::to_string_view(basic_string_view) + .. doxygenclass:: fmt::basic_memory_buffer :protected-members: :members: @@ -248,7 +280,8 @@ custom argument formatter class:: // with the ``x`` format specifier. class custom_arg_formatter : public arg_formatter { public: - custom_arg_formatter(fmt::format_context &ctx, fmt::format_specs &spec) + custom_arg_formatter(fmt::format_context &ctx, + fmt::format_specs *spec = nullptr) : arg_formatter(ctx, spec) {} using arg_formatter::operator(); @@ -319,7 +352,7 @@ user-defined types that have overloaded ``operator<<``:: std::string s = fmt::format("The date is {}", date(2012, 12, 9)); // s == "The date is 2012-12-9" -.. doxygenfunction:: print(std::ostream&, string_view, const Args&...) +.. doxygenfunction:: print(std::basic_ostream>&, const S&, const Args&...) .. _printf-api: @@ -333,10 +366,10 @@ the POSIX extension for positional arguments. Unlike their standard counterparts, the ``fmt`` functions are type-safe and throw an exception if an argument type doesn't match its format specification. -.. doxygenfunction:: printf(string_view, const Args&...) +.. doxygenfunction:: printf(const S&, const Args&...) -.. doxygenfunction:: fprintf(std::FILE *, string_view, const Args&...) +.. doxygenfunction:: fprintf(std::FILE *, const S&, const Args&...) -.. doxygenfunction:: fprintf(std::ostream&, string_view, const Args&...) +.. doxygenfunction:: fprintf(std::basic_ostream>&, const S&, const Args&...) -.. doxygenfunction:: sprintf(string_view, const Args&...) +.. doxygenfunction:: sprintf(const S&, const Args&...) diff --git a/doc/build.py b/doc/build.py index 5947e465..924563f0 100755 --- a/doc/build.py +++ b/doc/build.py @@ -6,7 +6,7 @@ import errno, os, shutil, sys, tempfile from subprocess import check_call, check_output, CalledProcessError, Popen, PIPE from distutils.version import LooseVersion -versions = ['1.0.0', '1.1.0', '2.0.0', '3.0.2', '4.0.0', '4.1.0', '5.0.0', '5.1.0', '5.2.0', '5.2.1'] +versions = ['1.0.0', '1.1.0', '2.0.0', '3.0.2', '4.0.0', '4.1.0', '5.0.0', '5.1.0', '5.2.0', '5.2.1', '5.3.0'] def pip_install(package, commit=None, **kwargs): "Install package using pip." @@ -89,10 +89,12 @@ def build_docs(version='dev', **kwargs): FMT_USE_VARIADIC_TEMPLATES=1 \ FMT_USE_RVALUE_REFERENCES=1 \ FMT_USE_USER_DEFINED_LITERALS=1 \ + FMT_USE_ALIAS_TEMPLATES=1 \ FMT_API= \ "FMT_BEGIN_NAMESPACE=namespace fmt {{" \ "FMT_END_NAMESPACE=}}" \ - "FMT_STRING_ALIAS=1" + "FMT_STRING_ALIAS=1" \ + "FMT_ENABLE_IF_T(B, T)=T" EXCLUDE_SYMBOLS = fmt::internal::* StringValue write_str '''.format(include_dir, doxyxml_dir).encode('UTF-8')) if p.returncode != 0: diff --git a/doc/index.rst b/doc/index.rst index 17d6b4bb..a8dc05e5 100644 --- a/doc/index.rst +++ b/doc/index.rst @@ -40,7 +40,7 @@ The ``fmt::format`` function returns a string "The answer is 42.". You can use format_to(out, "For a moment, {} happened.", "nothing"); out.data(); // returns a pointer to the formatted data -The ``fmt::print`` function performs formatting and writes the result to a file: +The ``fmt::print`` function performs formatting and writes the result to a stream: .. code:: c++ @@ -94,7 +94,7 @@ Safety The library is fully type safe, automatic memory management prevents buffer overflow, errors in format strings are reported using exceptions or at compile -tim. For example, the code +time. For example, the code .. code:: c++ diff --git a/doc/usage.rst b/doc/usage.rst index 4d39882c..2b9777c6 100644 --- a/doc/usage.rst +++ b/doc/usage.rst @@ -45,7 +45,7 @@ You can control generation of the make ``test`` target with the ``FMT_TEST`` CMake option. This can be useful if you include fmt as a subdirectory in your project but don't want to add fmt's tests to your ``test`` target. -If you use Windows and have Visual Studio installed, a :file:`FORMAT.sln` +If you use Windows and have Visual Studio installed, a :file:`FMT.sln` file and several :file:`.vcproj` files will be created. You can then build them using Visual Studio or msbuild. @@ -74,7 +74,12 @@ or to exclude it from ``make``, ``make all``, or ``cmake --build .``. -Settting up your target to use a header-only version of ``fmt`` is equaly easy:: +You can detect and use an installed version of {fmt} as follows:: + + find_package(fmt) + target_link_libraries( fmt::fmt) + +Setting up your target to use a header-only version of ``fmt`` is equaly easy:: target_link_libraries( PRIVATE fmt-header-only) diff --git a/include/fmt/chrono.h b/include/fmt/chrono.h new file mode 100644 index 00000000..209cdc25 --- /dev/null +++ b/include/fmt/chrono.h @@ -0,0 +1,452 @@ +// 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 "format.h" +#include "locale.h" + +#include +#include +#include +#include + +FMT_BEGIN_NAMESPACE + +namespace internal{ + +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 +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) + 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 'z': + handler.on_utc_offset(); + break; + case 'Z': + handler.on_tz_name(); + break; + // Alternative representation: + case 'E': { + if (ptr == end) + 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: + throw format_error("invalid format"); + } + break; + } + case 'O': + if (ptr == end) + 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: + throw format_error("invalid format"); + } + break; + default: + throw format_error("invalid format"); + } + begin = ptr; + } + if (begin != ptr) + handler.on_text(begin, ptr); + return ptr; +} + +struct chrono_format_checker { + void report_no_date() { throw format_error("no date"); } + + template + void on_text(const Char *, const Char *) {} + void on_abbr_weekday() { report_no_date(); } + void on_full_weekday() { report_no_date(); } + void on_dec0_weekday(numeric_system) { report_no_date(); } + void on_dec1_weekday(numeric_system) { report_no_date(); } + void on_abbr_month() { report_no_date(); } + 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) {} + void on_datetime(numeric_system) { report_no_date(); } + void on_loc_date(numeric_system) { report_no_date(); } + void on_loc_time(numeric_system) { report_no_date(); } + void on_us_date() { report_no_date(); } + 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_utc_offset() { report_no_date(); } + void on_tz_name() { report_no_date(); } +}; + +template +inline int to_int(Int value) { + FMT_ASSERT(value >= (std::numeric_limits::min)() && + value <= (std::numeric_limits::max)(), "invalid value"); + return static_cast(value); +} + +template +struct chrono_formatter { + FormatContext &context; + OutputIt out; + std::chrono::seconds s; + std::chrono::milliseconds ms; + + typedef typename FormatContext::char_type char_type; + + explicit chrono_formatter(FormatContext &ctx, OutputIt o) + : context(ctx), out(o) {} + + int hour() const { return to_int((s.count() / 3600) % 24); } + + int hour12() const { + auto hour = to_int((s.count() / 3600) % 12); + return hour > 0 ? hour : 12; + } + + int minute() const { return to_int((s.count() / 60) % 60); } + int second() const { return to_int(s.count() % 60); } + + std::tm time() const { + auto time = std::tm(); + time.tm_hour = hour(); + time.tm_min = minute(); + time.tm_sec = second(); + return time; + } + + void write(int value, int width) { + typedef typename int_traits::main_type main_type; + main_type n = to_unsigned(value); + int num_digits = internal::count_digits(n); + if (width > num_digits) + out = std::fill_n(out, width - num_digits, '0'); + out = format_decimal(out, n, num_digits); + } + + void format_localized(const tm &time, const char *format) { + auto locale = context.locale().template get(); + auto &facet = std::use_facet>(locale); + std::basic_ostringstream os; + os.imbue(locale); + facet.put(os, os, ' ', &time, format, format + std::strlen(format)); + 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 (ns == numeric_system::standard) + return write(hour(), 2); + auto time = tm(); + time.tm_hour = hour(); + format_localized(time, "%OH"); + } + + void on_12_hour(numeric_system ns) { + if (ns == numeric_system::standard) + return write(hour12(), 2); + auto time = tm(); + time.tm_hour = hour(); + format_localized(time, "%OI"); + } + + void on_minute(numeric_system ns) { + if (ns == numeric_system::standard) + return write(minute(), 2); + auto time = tm(); + time.tm_min = minute(); + format_localized(time, "%OM"); + } + + void on_second(numeric_system ns) { + if (ns == numeric_system::standard) { + write(second(), 2); + if (ms != std::chrono::milliseconds(0)) { + *out++ = '.'; + write(to_int(ms.count()), 3); + } + return; + } + auto time = tm(); + time.tm_sec = second(); + format_localized(time, "%OS"); + } + + void on_12_hour_time() { format_localized(time(), "%r"); } + + void on_24_hour_time() { + write(hour(), 2); + *out++ = ':'; + write(minute(), 2); + } + + void on_iso_time() { + on_24_hour_time(); + *out++ = ':'; + write(second(), 2); + } + + void on_am_pm() { format_localized(time(), "%p"); } +}; +} // namespace internal + +template FMT_CONSTEXPR const char *get_units() { + return FMT_NULL; +} +template <> FMT_CONSTEXPR const char *get_units() { return "as"; } +template <> FMT_CONSTEXPR const char *get_units() { return "fs"; } +template <> FMT_CONSTEXPR const char *get_units() { return "ps"; } +template <> FMT_CONSTEXPR const char *get_units() { return "ns"; } +template <> FMT_CONSTEXPR const char *get_units() { return "µs"; } +template <> FMT_CONSTEXPR const char *get_units() { return "ms"; } +template <> FMT_CONSTEXPR const char *get_units() { return "cs"; } +template <> FMT_CONSTEXPR const char *get_units() { return "ds"; } +template <> FMT_CONSTEXPR const char *get_units>() { return "s"; } +template <> FMT_CONSTEXPR const char *get_units() { return "das"; } +template <> FMT_CONSTEXPR const char *get_units() { return "hs"; } +template <> FMT_CONSTEXPR const char *get_units() { return "ks"; } +template <> FMT_CONSTEXPR const char *get_units() { return "Ms"; } +template <> FMT_CONSTEXPR const char *get_units() { return "Gs"; } +template <> FMT_CONSTEXPR const char *get_units() { return "Ts"; } +template <> FMT_CONSTEXPR const char *get_units() { return "Ps"; } +template <> FMT_CONSTEXPR const char *get_units() { return "Es"; } +template <> FMT_CONSTEXPR const char *get_units>() { + return "m"; +} +template <> FMT_CONSTEXPR const char *get_units>() { + return "h"; +} + +template +struct formatter, Char> { + private: + align_spec spec; + internal::arg_ref width_ref; + mutable basic_string_view format_str; + typedef std::chrono::duration duration; + + struct spec_handler { + formatter &f; + basic_parse_context &context; + + typedef internal::arg_ref arg_ref_type; + + template + 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(internal::auto_id) { + return arg_ref_type(context.next_arg_id()); + } + + void on_error(const char *msg) { throw format_error(msg); } + void on_fill(Char fill) { f.spec.fill_ = fill; } + void on_align(alignment align) { f.spec.align_ = align; } + void on_width(unsigned width) { f.spec.width_ = width; } + + template + void on_dynamic_width(Id arg_id) { + f.width_ref = make_arg_ref(arg_id); + } + }; + + public: + formatter() : spec() {} + + FMT_CONSTEXPR auto parse(basic_parse_context &ctx) + -> decltype(ctx.begin()) { + auto begin = ctx.begin(), end = ctx.end(); + if (begin == end) return begin; + spec_handler handler{*this, ctx}; + begin = internal::parse_align(begin, end, handler); + if (begin == end) return begin; + begin = internal::parse_width(begin, end, handler); + end = parse_chrono_format(begin, end, internal::chrono_format_checker()); + format_str = basic_string_view(&*begin, internal::to_unsigned(end - begin)); + return end; + } + + template + auto format(const duration &d, FormatContext &ctx) + -> decltype(ctx.out()) { + auto begin = format_str.begin(), end = format_str.end(); + memory_buffer buf; + typedef output_range range; + basic_writer w(range(ctx.out())); + if (begin == end || *begin == '}') { + if (const char *unit = get_units()) + format_to(buf, "{}{}", d.count(), unit); + else if (Period::den == 1) + format_to(buf, "{}[{}]s", d.count(), Period::num); + else + format_to(buf, "{}[{}/{}]s", d.count(), Period::num, Period::den); + internal::handle_dynamic_spec( + spec.width_, width_ref, ctx); + } else { + auto out = std::back_inserter(buf); + internal::chrono_formatter f(ctx, out); + f.s = std::chrono::duration_cast(d); + f.ms = std::chrono::duration_cast(d - f.s); + parse_chrono_format(begin, end, f); + } + w.write(buf.data(), buf.size(), spec); + return w.out(); + } +}; + +FMT_END_NAMESPACE + +#endif // FMT_CHRONO_H_ diff --git a/include/fmt/color.h b/include/fmt/color.h index 4973976a..5db861c9 100644 --- a/include/fmt/color.h +++ b/include/fmt/color.h @@ -47,7 +47,6 @@ inline void vprint_colored(color c, wstring_view format, wformat_args args) { #else -// Experimental color support. enum class color : uint32_t { alice_blue = 0xF0F8FF, // rgb(240,248,255) antique_white = 0xFAEBD7, // rgb(250,235,215) @@ -189,9 +188,35 @@ enum class color : uint32_t { 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) + 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 terminal_color + +enum class emphasis : uint8_t { + bold = 1, + italic = 1 << 1, + underline = 1 << 2, + strikethrough = 1 << 3 +}; // enum class emphasis + // rgb is a struct for red, green and blue colors. // We use rgb as name because some editors will show it as color direct in the // editor. @@ -209,66 +234,340 @@ struct rgb { uint8_t b; }; -void vprint_rgb(rgb fd, string_view format, format_args args); -void vprint_rgb(rgb fd, rgb bg, string_view format, format_args args); - -/** - Formats a string and prints it to stdout using ANSI escape sequences to - specify foreground color 'fd'. - Example: - fmt::print(fmt::color::red, "Elapsed time: {0:.2f} seconds", 1.23); - */ -template -inline void print(rgb fd, string_view format_str, const Args & ... args) { - vprint_rgb(fd, format_str, make_format_args(args...)); -} - -/** - Formats a string and prints it to stdout using ANSI escape sequences to - specify foreground color 'fd' and background color 'bg'. - Example: - fmt::print(fmt::color::red, fmt::color::black, - "Elapsed time: {0:.2f} seconds", 1.23); - */ -template -inline void print(rgb fd, rgb bg, string_view format_str, - const Args & ... args) { - vprint_rgb(fd, bg, format_str, make_format_args(args...)); -} namespace internal { -FMT_CONSTEXPR void to_esc(uint8_t c, char out[], int offset) { - out[offset + 0] = static_cast('0' + c / 100); - out[offset + 1] = static_cast('0' + c / 10 % 10); - out[offset + 2] = static_cast('0' + c % 10); -} + +// 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(rgb_color); + } + FMT_CONSTEXPR color_type(rgb rgb_color) FMT_NOEXCEPT + : is_rgb(true), value{} { + value.rgb_color = (static_cast(rgb_color.r) << 16) + | (static_cast(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(term_color); + } + bool is_rgb; + union color_union { + uint8_t term_color; + uint32_t rgb_color; + } value; +}; } // namespace internal -inline void vprint_rgb(rgb fd, string_view format, format_args args) { - char escape_fd[] = "\x1b[38;2;000;000;000m"; - internal::to_esc(fd.r, escape_fd, 7); - internal::to_esc(fd.g, escape_fd, 11); - internal::to_esc(fd.b, escape_fd, 15); +// 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) {} - std::fputs(escape_fd, stdout); - vprint(format, args); - std::fputs(internal::data::RESET_COLOR, stdout); + 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) + 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) + throw format_error("can't OR a terminal color"); + background_color.value.rgb_color |= rhs.background_color.value.rgb_color; + } + + ems = static_cast(static_cast(ems) | + static_cast(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) + 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) + throw format_error("can't AND a terminal color"); + background_color.value.rgb_color &= rhs.background_color.value.rgb_color; + } + + ems = static_cast(static_cast(ems) & + static_cast(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(ems) != 0; + } + FMT_CONSTEXPR internal::color_type get_foreground() const FMT_NOEXCEPT { + assert(has_foreground() && "no foreground specified for this style"); + return foreground_color; + } + FMT_CONSTEXPR internal::color_type get_background() const FMT_NOEXCEPT { + assert(has_background() && "no background specified for this style"); + return background_color; + } + FMT_CONSTEXPR emphasis get_emphasis() const FMT_NOEXCEPT { + assert(has_emphasis() && "no emphasis specified for this style"); + return ems; + } + +private: + FMT_CONSTEXPR text_style(bool is_foreground, + internal::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; + } + } + + friend FMT_CONSTEXPR_DECL text_style fg(internal::color_type foreground) + FMT_NOEXCEPT; + friend FMT_CONSTEXPR_DECL text_style bg(internal::color_type background) + FMT_NOEXCEPT; + + internal::color_type foreground_color; + internal::color_type background_color; + bool set_foreground_color; + bool set_background_color; + emphasis ems; +}; + +FMT_CONSTEXPR text_style fg(internal::color_type foreground) FMT_NOEXCEPT { + return text_style(/*is_foreground=*/true, foreground); } -inline void vprint_rgb(rgb fd, rgb bg, string_view format, format_args args) { - char escape_fd[] = "\x1b[38;2;000;000;000m"; // foreground color - char escape_bg[] = "\x1b[48;2;000;000;000m"; // background color - internal::to_esc(fd.r, escape_fd, 7); - internal::to_esc(fd.g, escape_fd, 11); - internal::to_esc(fd.b, escape_fd, 15); +FMT_CONSTEXPR text_style bg(internal::color_type background) FMT_NOEXCEPT { + return text_style(/*is_foreground=*/false, background); +} - internal::to_esc(bg.r, escape_bg, 7); - internal::to_esc(bg.g, escape_bg, 11); - internal::to_esc(bg.b, escape_bg, 15); +FMT_CONSTEXPR text_style operator|(emphasis lhs, emphasis rhs) FMT_NOEXCEPT { + return text_style(lhs) | rhs; +} - std::fputs(escape_fd, stdout); - std::fputs(escape_bg, stdout); - vprint(format, args); - std::fputs(internal::data::RESET_COLOR, stdout); +namespace internal { + +template +struct ansi_color_escape { + FMT_CONSTEXPR ansi_color_escape(internal::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) { + bool is_background = esc == internal::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; + + std::size_t index = 0; + buffer[index++] = static_cast('\x1b'); + buffer[index++] = static_cast('['); + + if (value >= 100u) { + buffer[index++] = static_cast('1'); + value %= 100u; + } + buffer[index++] = static_cast('0' + value / 10u); + buffer[index++] = static_cast('0' + value % 10u); + + buffer[index++] = static_cast('m'); + buffer[index++] = static_cast('\0'); + return; + } + + for (int i = 0; i < 7; i++) { + buffer[i] = static_cast(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(0); + } + FMT_CONSTEXPR ansi_color_escape(emphasis em) FMT_NOEXCEPT { + uint8_t em_codes[4] = {}; + uint8_t em_bits = static_cast(em); + if (em_bits & static_cast(emphasis::bold)) + em_codes[0] = 1; + if (em_bits & static_cast(emphasis::italic)) + em_codes[1] = 3; + if (em_bits & static_cast(emphasis::underline)) + em_codes[2] = 4; + if (em_bits & static_cast(emphasis::strikethrough)) + em_codes[3] = 9; + + std::size_t index = 0; + for (int i = 0; i < 4; ++i) { + if (!em_codes[i]) + continue; + buffer[index++] = static_cast('\x1b'); + buffer[index++] = static_cast('['); + buffer[index++] = static_cast('0' + em_codes[i]); + buffer[index++] = static_cast('m'); + } + buffer[index++] = static_cast(0); + } + FMT_CONSTEXPR operator const Char *() const FMT_NOEXCEPT { return 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('0' + c / 100); + out[1] = static_cast('0' + c / 10 % 10); + out[2] = static_cast('0' + c % 10); + out[3] = static_cast(delimiter); + } +}; + +template +FMT_CONSTEXPR ansi_color_escape +make_foreground_color(internal::color_type foreground) FMT_NOEXCEPT { + return ansi_color_escape(foreground, internal::data::FOREGROUND_COLOR); +} + +template +FMT_CONSTEXPR ansi_color_escape +make_background_color(internal::color_type background) FMT_NOEXCEPT { + return ansi_color_escape(background, internal::data::BACKGROUND_COLOR); +} + +template +FMT_CONSTEXPR ansi_color_escape +make_emphasis(emphasis em) FMT_NOEXCEPT { + return ansi_color_escape(em); +} + +template +inline void fputs(const Char *chars, FILE *stream) FMT_NOEXCEPT { + std::fputs(chars, stream); +} + +template <> +inline void fputs(const wchar_t *chars, FILE *stream) FMT_NOEXCEPT { + std::fputws(chars, stream); +} + +template +inline void reset_color(FILE *stream) FMT_NOEXCEPT { + fputs(internal::data::RESET_COLOR, stream); +} + +template <> +inline void reset_color(FILE *stream) FMT_NOEXCEPT { + fputs(internal::data::WRESET_COLOR, stream); +} + +// The following specialiazation disables using std::FILE as a character type, +// which is needed because or else +// fmt::print(stderr, fmt::emphasis::bold, ""); +// would take stderr (a std::FILE *) as the format string. +template <> +struct is_string : std::false_type {}; +template <> +struct is_string : std::false_type {}; +} // namespace internal + +template < + typename S, typename Char = typename internal::char_t::type> +void vprint(std::FILE *f, const text_style &ts, const S &format, + basic_format_args::type> args) { + bool has_style = false; + if (ts.has_emphasis()) { + has_style = true; + internal::fputs( + internal::make_emphasis(ts.get_emphasis()), f); + } + if (ts.has_foreground()) { + has_style = true; + internal::fputs( + internal::make_foreground_color(ts.get_foreground()), f); + } + if (ts.has_background()) { + has_style = true; + internal::fputs( + internal::make_background_color(ts.get_background()), f); + } + vprint(f, format, args); + if (has_style) { + internal::reset_color(f); + } +} + +/** + 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); + */ +template +typename std::enable_if::value>::type print( + std::FILE *f, const text_style &ts, const String &format_str, + const Args &... args) { + internal::check_format_string(format_str); + typedef typename internal::char_t::type char_t; + typedef typename buffer_context::type context_t; + format_arg_store as{args...}; + vprint(f, ts, format_str, basic_format_args(as)); +} + +/** + 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 std::enable_if::value>::type print( + const text_style &ts, const String &format_str, + const Args &... args) { + return print(stdout, ts, format_str, args...); } #endif diff --git a/include/fmt/core.h b/include/fmt/core.h index 5912afef..50b79351 100644 --- a/include/fmt/core.h +++ b/include/fmt/core.h @@ -16,7 +16,7 @@ #include // The fmt library version in the form major * 10000 + minor * 100 + patch. -#define FMT_VERSION 50201 +#define FMT_VERSION 50300 #ifdef __has_feature # define FMT_HAS_FEATURE(x) __has_feature(x) @@ -25,7 +25,7 @@ #endif #if defined(__has_include) && !defined(__INTELLISENSE__) && \ - (!defined(__INTEL_COMPILER) || __INTEL_COMPILER >= 1600) + !(defined(__INTEL_COMPILER) && __INTEL_COMPILER < 1600) # define FMT_HAS_INCLUDE(x) __has_include(x) #else # define FMT_HAS_INCLUDE(x) 0 @@ -72,7 +72,7 @@ #ifndef FMT_USE_CONSTEXPR11 # define FMT_USE_CONSTEXPR11 \ - (FMT_MSC_VER >= 1900 || FMT_GCC_VERSION >= 406 || FMT_USE_CONSTEXPR) + (FMT_USE_CONSTEXPR || FMT_GCC_VERSION >= 406 || FMT_MSC_VER >= 1900) #endif #if FMT_USE_CONSTEXPR11 # define FMT_CONSTEXPR11 constexpr @@ -89,9 +89,12 @@ # endif #endif -#if FMT_HAS_FEATURE(cxx_explicit_conversions) || FMT_MSC_VER >= 1800 +#if FMT_HAS_FEATURE(cxx_explicit_conversions) || \ + FMT_GCC_VERSION >= 405 || FMT_MSC_VER >= 1800 +# define FMT_USE_EXPLICIT 1 # define FMT_EXPLICIT explicit #else +# define FMT_USE_EXPLICIT 0 # define FMT_EXPLICIT #endif @@ -104,25 +107,18 @@ # define FMT_NULL NULL # endif #endif - #ifndef FMT_USE_NULLPTR # define FMT_USE_NULLPTR 0 #endif -#if FMT_HAS_CPP_ATTRIBUTE(noreturn) -# define FMT_NORETURN [[noreturn]] -#else -# define FMT_NORETURN -#endif - // Check if exceptions are disabled. -#if defined(__GNUC__) && !defined(__EXCEPTIONS) -# define FMT_EXCEPTIONS 0 -#elif FMT_MSC_VER && !_HAS_EXCEPTIONS -# define FMT_EXCEPTIONS 0 -#endif #ifndef FMT_EXCEPTIONS -# define FMT_EXCEPTIONS 1 +# 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). @@ -147,14 +143,6 @@ # endif #endif -// This is needed because GCC still uses throw() in its headers when exceptions -// are disabled. -#if FMT_GCC_VERSION -# define FMT_DTOR_NOEXCEPT FMT_DETECTED_NOEXCEPT -#else -# define FMT_DTOR_NOEXCEPT FMT_NOEXCEPT -#endif - #ifndef FMT_BEGIN_NAMESPACE # if FMT_HAS_FEATURE(cxx_inline_namespaces) || FMT_GCC_VERSION >= 404 || \ FMT_MSC_VER >= 1900 @@ -187,11 +175,10 @@ (__cplusplus > 201402L || defined(_LIBCPP_VERSION))) || \ (defined(_MSVC_LANG) && _MSVC_LANG > 201402L && _MSC_VER >= 1910) # include -# define FMT_USE_STD_STRING_VIEW -#elif (FMT_HAS_INCLUDE() && \ - __cplusplus >= 201402L) +# define FMT_STRING_VIEW std::basic_string_view +#elif FMT_HAS_INCLUDE() && __cplusplus >= 201402L # include -# define FMT_USE_EXPERIMENTAL_STRING_VIEW +# define FMT_STRING_VIEW std::experimental::basic_string_view #endif // std::result_of is defined in in gcc 4.4. @@ -223,149 +210,6 @@ FMT_CONSTEXPR typename std::make_unsigned::type to_unsigned(Int value) { return static_cast::type>(value); } -// A constexpr std::char_traits::length replacement for pre-C++17. -template -FMT_CONSTEXPR size_t length(const Char *s) { - const Char *start = s; - while (*s) ++s; - return s - start; -} -#if FMT_GCC_VERSION -FMT_CONSTEXPR size_t length(const char *s) { return std::strlen(s); } -#endif -} // namespace internal - -/** - 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 -class basic_string_view { - private: - const Char *data_; - size_t size_; - - public: - typedef Char char_type; - typedef const Char *iterator; - - // Standard basic_string_view type. -#if defined(FMT_USE_STD_STRING_VIEW) - typedef std::basic_string_view type; -#elif defined(FMT_USE_EXPERIMENTAL_STRING_VIEW) - typedef std::experimental::basic_string_view type; -#else - struct type { - const char *data() const { return FMT_NULL; } - size_t size() const { return 0; } - }; -#endif - - FMT_CONSTEXPR basic_string_view() FMT_NOEXCEPT : data_(FMT_NULL), size_(0) {} - - /** Constructs a string reference object from a C string and a size. */ - FMT_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::length``. - \endrst - */ - FMT_CONSTEXPR basic_string_view(const Char *s) - : data_(s), size_(internal::length(s)) {} - - /** Constructs a string reference from a ``std::basic_string`` object. */ - template - FMT_CONSTEXPR basic_string_view( - const std::basic_string &s) FMT_NOEXCEPT - : data_(s.data()), size_(s.size()) {} - - FMT_CONSTEXPR basic_string_view(type s) FMT_NOEXCEPT - : data_(s.data()), size_(s.size()) {} - - /** Returns a pointer to the string data. */ - FMT_CONSTEXPR const Char *data() const { return data_; } - - /** Returns the string size. */ - FMT_CONSTEXPR size_t size() const { return size_; } - - FMT_CONSTEXPR iterator begin() const { return data_; } - FMT_CONSTEXPR iterator end() const { return data_ + size_; } - - 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::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; - } -}; - -typedef basic_string_view string_view; -typedef basic_string_view wstring_view; - -template -class basic_format_arg; - -template -class basic_format_args; - -template -struct no_formatter_error : std::false_type {}; - -// A formatter for objects of type T. -template -struct formatter { - static_assert(no_formatter_error::value, - "don't know how to format the type, include fmt/ostream.h if it provides " - "an operator<< that should be used"); - - // The following functions are not defined intentionally. - template - typename ParseContext::iterator parse(ParseContext &); - template - auto format(const T &val, FormatContext &ctx) -> decltype(ctx.out()); -}; - -template -struct convert_to_int { - enum { - value = !std::is_arithmetic::value && std::is_convertible::value - }; -}; - -namespace internal { - /** A contiguous memory buffer with an optional growing ability. */ template class basic_buffer { @@ -464,6 +308,17 @@ class container_buffer : public basic_buffer { : basic_buffer(c.size()), container_(c) {} }; +// Extracts a reference to the container from back_insert_iterator. +template +inline Container &get_container(std::back_insert_iterator it) { + typedef std::back_insert_iterator bi_iterator; + struct accessor: bi_iterator { + accessor(bi_iterator iter) : bi_iterator(iter) {} + using bi_iterator::container; + }; + return *accessor(it).container; +} + struct error_handler { FMT_CONSTEXPR error_handler() {} FMT_CONSTEXPR error_handler(const error_handler &) {} @@ -472,16 +327,199 @@ struct error_handler { FMT_API void on_error(const char *message); }; -// Formatting of wide characters and strings into a narrow output is disallowed: -// fmt::format("{}", L"test"); // error -// To fix this, use a wide format string: -// fmt::format(L"{}", L"test"); +template +struct no_formatter_error : std::false_type {}; +} // namespace internal + +#if FMT_GCC_VERSION && FMT_GCC_VERSION < 405 +template +struct is_constructible: std::false_type {}; +#else +template +struct is_constructible : std::is_constructible {}; +#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 -inline void require_wchar() { - static_assert( - std::is_same::value, - "formatting of wide characters into a narrow output is disallowed"); -} +class basic_string_view { + private: + const Char *data_; + size_t size_; + + public: + typedef Char char_type; + typedef const Char *iterator; + + FMT_CONSTEXPR basic_string_view() FMT_NOEXCEPT : data_(FMT_NULL), size_(0) {} + + /** Constructs a string reference object from a C string and a size. */ + FMT_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::length``. + \endrst + */ + basic_string_view(const Char *s) + : data_(s), size_(std::char_traits::length(s)) {} + + /** Constructs a string reference from a ``std::basic_string`` object. */ + template + FMT_CONSTEXPR basic_string_view( + const std::basic_string &s) FMT_NOEXCEPT + : data_(s.data()), size_(s.size()) {} + +#ifdef FMT_STRING_VIEW + FMT_CONSTEXPR basic_string_view(FMT_STRING_VIEW s) FMT_NOEXCEPT + : data_(s.data()), size_(s.size()) {} +#endif + + /** Returns a pointer to the string data. */ + FMT_CONSTEXPR const Char *data() const { return data_; } + + /** Returns the string size. */ + FMT_CONSTEXPR size_t size() const { return size_; } + + FMT_CONSTEXPR iterator begin() const { return data_; } + FMT_CONSTEXPR iterator end() const { return data_ + size_; } + + 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::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; + } +}; + +typedef basic_string_view string_view; +typedef basic_string_view wstring_view; + +/** + \rst + The function ``to_string_view`` adapts non-intrusively any kind of string or + string-like type if the user provides a (possibly templated) overload of + ``to_string_view`` which takes an instance of the string class + ``StringType`` and returns a ``fmt::basic_string_view``. + The conversion function must live in the very same namespace as + ``StringType`` to be picked up by ADL. Non-templated string types + like f.e. QString must return a ``basic_string_view`` with a fixed matching + char type. + + **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 +inline basic_string_view + to_string_view(basic_string_view s) { return s; } + +template +inline basic_string_view + to_string_view(const std::basic_string &s) { return s; } + +template +inline basic_string_view to_string_view(const Char *s) { return s; } + +#ifdef FMT_STRING_VIEW +template +inline basic_string_view + to_string_view(FMT_STRING_VIEW s) { return s; } +#endif + +// 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("{}"), 42). +struct compile_string {}; + +template +struct is_compile_string : std::is_base_of {}; + +template < + typename S, + typename Enable = typename std::enable_if::value>::type> +FMT_CONSTEXPR basic_string_view + to_string_view(const S &s) { return s; } + +template +class basic_format_arg; + +template +class basic_format_args; + +// A formatter for objects of type T. +template +struct formatter { + static_assert(internal::no_formatter_error::value, + "don't know how to format the type, include fmt/ostream.h if it provides " + "an operator<< that should be used"); + + // The following functions are not defined intentionally. + template + typename ParseContext::iterator parse(ParseContext &); + template + auto format(const T &val, FormatContext &ctx) -> decltype(ctx.out()); +}; + +template +struct convert_to_int: std::integral_constant< + bool, !std::is_arithmetic::value && std::is_convertible::value> {}; + +namespace internal { + +struct dummy_string_view { typedef void char_type; }; +dummy_string_view to_string_view(...); +using fmt::v5::to_string_view; + +// Specifies whether S is a string type convertible to fmt::basic_string_view. +template +struct is_string : std::integral_constant()))>::value> {}; + +template +struct char_t { + typedef decltype(to_string_view(declval())) result; + typedef typename result::char_type type; +}; template struct named_arg_base; @@ -489,12 +527,6 @@ struct named_arg_base; template struct named_arg; -template -struct is_named_arg : std::false_type {}; - -template -struct is_named_arg> : std::true_type {}; - enum type { none_type, named_arg_type, // Integer types should go first, @@ -639,15 +671,17 @@ FMT_MAKE_VALUE_SAME(long_long_type, long long) FMT_MAKE_VALUE_SAME(ulong_long_type, unsigned long long) FMT_MAKE_VALUE(int_type, signed char, int) FMT_MAKE_VALUE(uint_type, unsigned char, unsigned) -FMT_MAKE_VALUE(char_type, char, int) -#if !defined(_MSC_VER) || defined(_NATIVE_WCHAR_T_DEFINED) +// This doesn't use FMT_MAKE_VALUE because of ambiguity in gcc 4.4. +template +FMT_CONSTEXPR typename std::enable_if< + std::is_same::value, + init>::type make_value(Char val) { return val; } + template -inline init make_value(wchar_t val) { - require_wchar(); - return static_cast(val); -} -#endif +FMT_CONSTEXPR typename std::enable_if< + !std::is_same::value, + init>::type make_value(char val) { return val; } FMT_MAKE_VALUE(double_type, float, double) FMT_MAKE_VALUE_SAME(double_type, double) @@ -695,15 +729,17 @@ inline typename std::enable_if< template inline typename std::enable_if< - std::is_constructible, T>::value, + is_constructible, T>::value && + !internal::is_string::value, init, string_type>>::type make_value(const T &val) { return basic_string_view(val); } template inline typename std::enable_if< - !convert_to_int::value && + !convert_to_int::value && !std::is_same::value && !std::is_convertible>::value && - !std::is_constructible, T>::value, + !is_constructible, T>::value && + !internal::is_string::value, // Implicit conversion to std::string is not handled here because it's // unsafe: https://github.com/fmtlib/fmt/issues/729 init>::type @@ -717,8 +753,21 @@ init return static_cast(&val); } +template +FMT_CONSTEXPR11 typename std::enable_if< + internal::is_string::value, + init, string_type>>::type + make_value(const S &val) { + // Handle adapted strings. + static_assert(std::is_same< + typename C::char_type, typename internal::char_t::type>::value, + "mismatch between char-types of context and argument"); + return to_string_view(val); +} + // Maximum number of arguments with packed types. enum { max_packed_args = 15 }; +enum : unsigned long long { is_unpacked_bit = 1ull << 63 }; template class arg_map; @@ -738,7 +787,7 @@ class basic_format_arg { template friend FMT_CONSTEXPR typename internal::result_of::type - visit(Visitor &&vis, const basic_format_arg &arg); + visit_format_arg(Visitor &&vis, const basic_format_arg &arg); friend class basic_format_args; friend class internal::arg_map; @@ -779,7 +828,7 @@ struct monostate {}; */ template FMT_CONSTEXPR typename internal::result_of::type - visit(Visitor &&vis, const basic_format_arg &arg) { + visit_format_arg(Visitor &&vis, const basic_format_arg &arg) { typedef typename Context::char_type char_type; switch (arg.type_) { case internal::none_type: @@ -816,6 +865,13 @@ FMT_CONSTEXPR typename internal::result_of::type return vis(monostate()); } +// DEPRECATED! +template +FMT_CONSTEXPR typename internal::result_of::type + visit(Visitor &&vis, const basic_format_arg &arg) { + return visit_format_arg(std::forward(vis), arg); +} + // Parsing context consisting of a format string range being parsed and an // argument counter for automatic indexing. template @@ -866,6 +922,10 @@ class basic_parse_context : private ErrorHandler { FMT_CONSTEXPR ErrorHandler error_handler() const { return *this; } }; +typedef basic_parse_context format_parse_context; +typedef basic_parse_context wformat_parse_context; + +// DEPRECATED! typedef basic_parse_context parse_context; typedef basic_parse_context wparse_context; @@ -904,10 +964,26 @@ class arg_map { if (it->name == name) return it->arg; } - return basic_format_arg(); + return {}; } }; +// A type-erased reference to an std::locale to avoid heavy include. +class locale_ref { + private: + const void *locale_; // A type-erased pointer to std::locale. + friend class locale; + + public: + locale_ref() : locale_(FMT_NULL) {} + + template + explicit locale_ref(const Locale &loc); + + template + Locale get() const; +}; + template class context_base { public: @@ -917,14 +993,16 @@ class context_base { basic_parse_context parse_context_; iterator out_; basic_format_args args_; + locale_ref loc_; protected: typedef Char char_type; typedef basic_format_arg format_arg; context_base(OutputIt out, basic_string_view format_str, - basic_format_args ctx_args) - : parse_context_(format_str), out_(out), args_(ctx_args) {} + basic_format_args ctx_args, + locale_ref loc = locale_ref()) + : parse_context_(format_str), out_(out), args_(ctx_args), loc_(loc) {} // Returns the argument with specified index. format_arg do_get_arg(unsigned arg_id) { @@ -942,9 +1020,9 @@ class context_base { } public: - basic_parse_context &parse_context() { - return parse_context_; - } + basic_parse_context &parse_context() { return parse_context_; } + basic_format_args args() const { return args_; } // DEPRECATED! + basic_format_arg arg(unsigned id) const { return args_.get(id); } internal::error_handler error_handler() { return parse_context_.error_handler(); @@ -959,74 +1037,9 @@ class context_base { // Advances the begin iterator to ``it``. void advance_to(iterator it) { out_ = it; } - basic_format_args args() const { return args_; } + locale_ref locale() { return loc_; } }; -// Extracts a reference to the container from back_insert_iterator. -template -inline Container &get_container(std::back_insert_iterator it) { - typedef std::back_insert_iterator bi_iterator; - struct accessor: bi_iterator { - accessor(bi_iterator iter) : bi_iterator(iter) {} - using bi_iterator::container; - }; - return *accessor(it).container; -} -} // namespace internal - -// Formatting context. -template -class basic_format_context : - public internal::context_base< - OutputIt, basic_format_context, Char> { - public: - /** The character type for the output. */ - typedef Char char_type; - - // using formatter_type = formatter; - template - struct formatter_type { typedef formatter type; }; - - private: - internal::arg_map map_; - - basic_format_context(const basic_format_context &) = delete; - void operator=(const basic_format_context &) = delete; - - typedef internal::context_base base; - typedef typename base::format_arg format_arg; - using base::get_arg; - - public: - using typename base::iterator; - - /** - 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_string_view format_str, - basic_format_args ctx_args) - : base(out, format_str, ctx_args) {} - - format_arg next_arg() { - return this->do_get_arg(this->parse_context().next_arg_id()); - } - format_arg get_arg(unsigned arg_id) { return this->do_get_arg(arg_id); } - - // Checks if manual indexing is used and returns the argument with the - // specified name. - format_arg get_arg(basic_string_view name); -}; - -template -struct buffer_context { - typedef basic_format_context< - std::back_insert_iterator>, Char> type; -}; -typedef buffer_context::type format_context; -typedef buffer_context::type wformat_context; - -namespace internal { template struct get_type { typedef decltype(make_value( @@ -1063,6 +1076,59 @@ inline typename std::enable_if>::type } } // namespace internal +// Formatting context. +template +class basic_format_context : + public internal::context_base< + OutputIt, basic_format_context, Char> { + public: + /** The character type for the output. */ + typedef Char char_type; + + // using formatter_type = formatter; + template + struct formatter_type { typedef formatter type; }; + + private: + internal::arg_map map_; + + basic_format_context(const basic_format_context &) = delete; + void operator=(const basic_format_context &) = delete; + + typedef internal::context_base base; + typedef typename base::format_arg format_arg; + using base::get_arg; + + public: + using typename base::iterator; + + /** + 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_string_view format_str, + basic_format_args ctx_args, + internal::locale_ref loc = internal::locale_ref()) + : base(out, format_str, ctx_args, loc) {} + + format_arg next_arg() { + return this->do_get_arg(this->parse_context().next_arg_id()); + } + format_arg get_arg(unsigned arg_id) { return this->do_get_arg(arg_id); } + + // Checks if manual indexing is used and returns the argument with the + // specified name. + format_arg get_arg(basic_string_view name); +}; + +template +struct buffer_context { + typedef basic_format_context< + std::back_insert_iterator>, Char> type; +}; +typedef buffer_context::type format_context; +typedef buffer_context::type wformat_context; + /** \rst An array of references to arguments. It can be implicitly converted into @@ -1088,17 +1154,17 @@ class format_arg_store { friend class basic_format_args; - static FMT_CONSTEXPR11 long long get_types() { + static FMT_CONSTEXPR11 unsigned long long get_types() { return IS_PACKED ? - static_cast(internal::get_types()) : - -static_cast(NUM_ARGS); + internal::get_types() : + internal::is_unpacked_bit | NUM_ARGS; } public: #if FMT_USE_CONSTEXPR11 - static FMT_CONSTEXPR11 long long TYPES = get_types(); + static FMT_CONSTEXPR11 unsigned long long TYPES = get_types(); #else - static const long long TYPES; + static const unsigned long long TYPES; #endif #if (FMT_GCC_VERSION && FMT_GCC_VERSION <= 405) || \ @@ -1117,7 +1183,8 @@ class format_arg_store { #if !FMT_USE_CONSTEXPR11 template -const long long format_arg_store::TYPES = get_types(); +const unsigned long long format_arg_store::TYPES = + get_types(); #endif /** @@ -1127,17 +1194,9 @@ const long long format_arg_store::TYPES = get_types(); can be omitted in which case it defaults to `~fmt::context`. \endrst */ -template +template inline format_arg_store - make_format_args(const Args & ... args) { - return format_arg_store(args...); -} - -template -inline format_arg_store - make_format_args(const Args & ... args) { - return format_arg_store(args...); -} + make_format_args(const Args &... args) { return {args...}; } /** Formatting arguments. */ template @@ -1160,11 +1219,12 @@ class basic_format_args { const format_arg *args_; }; + bool is_packed() const { return (types_ & internal::is_unpacked_bit) == 0; } + typename internal::type type(unsigned index) const { unsigned shift = index * 4; - unsigned long long mask = 0xf; return static_cast( - (types_ & (mask << shift)) >> shift); + (types_ & (0xfull << shift)) >> shift); } friend class internal::arg_map; @@ -1174,10 +1234,8 @@ class basic_format_args { format_arg do_get(size_type index) const { format_arg arg; - long long signed_types = static_cast(types_); - if (signed_types < 0) { - unsigned long long num_args = - static_cast(-signed_types); + if (!is_packed()) { + auto num_args = max_size(); if (index < num_args) arg = args_[index]; return arg; @@ -1212,7 +1270,7 @@ class basic_format_args { \endrst */ basic_format_args(const format_arg *args, size_type count) - : types_(-static_cast(count)) { + : types_(internal::is_unpacked_bit | count) { set_data(args); } @@ -1224,34 +1282,52 @@ class basic_format_args { return arg; } - unsigned max_size() const { - long long signed_types = static_cast(types_); - return static_cast( - signed_types < 0 ? - -signed_types : static_cast(internal::max_packed_args)); + size_type max_size() const { + unsigned long long max_packed = internal::max_packed_args; + return static_cast( + is_packed() ? max_packed : types_ & ~internal::is_unpacked_bit); } }; /** An alias to ``basic_format_args``. */ // It is a separate type rather than a typedef to make symbols readable. -struct format_args: basic_format_args { +struct format_args : basic_format_args { template - format_args(Args && ... arg) + format_args(Args &&... arg) : basic_format_args(std::forward(arg)...) {} }; struct wformat_args : basic_format_args { template - wformat_args(Args && ... arg) + wformat_args(Args &&... arg) : basic_format_args(std::forward(arg)...) {} }; +#define FMT_ENABLE_IF_T(B, T) typename std::enable_if::type + +#ifndef FMT_USE_ALIAS_TEMPLATES +# define FMT_USE_ALIAS_TEMPLATES FMT_HAS_FEATURE(cxx_alias_templates) +#endif +#if FMT_USE_ALIAS_TEMPLATES +/** String's character type. */ +template +using char_t = FMT_ENABLE_IF_T( + internal::is_string::value, typename internal::char_t::type); +#define FMT_CHAR(S) fmt::char_t +#else +template +struct char_t : std::enable_if< + internal::is_string::value, typename internal::char_t::type> {}; +#define FMT_CHAR(S) typename char_t::type +#endif + namespace internal { template struct named_arg_base { basic_string_view name; // Serialized value. - mutable char data[sizeof(basic_format_arg)]; + mutable char data[ + sizeof(basic_format_arg::type>)]; named_arg_base(basic_string_view nm) : name(nm) {} @@ -1270,6 +1346,36 @@ struct named_arg : named_arg_base { named_arg(basic_string_view name, const T &val) : named_arg_base(name), value(val) {} }; + +template +inline typename std::enable_if::value>::type + check_format_string(const S &) {} +template +typename std::enable_if::value>::type + check_format_string(S); + +template +struct checked_args : format_arg_store< + typename buffer_context::type, Args...> { + typedef typename buffer_context::type context; + + checked_args(const S &format_str, const Args &... args): + format_arg_store(args...) { + internal::check_format_string(format_str); + } + + basic_format_args operator*() const { return *this; } +}; + +template +std::basic_string vformat( + basic_string_view format_str, + basic_format_args::type> args); + +template +typename buffer_context::type::iterator vformat_to( + internal::basic_buffer &buf, basic_string_view format_str, + basic_format_args::type> args); } /** @@ -1283,142 +1389,55 @@ struct named_arg : named_arg_base { */ template inline internal::named_arg arg(string_view name, const T &arg) { - return internal::named_arg(name, arg); + return {name, arg}; } template inline internal::named_arg arg(wstring_view name, const T &arg) { - return internal::named_arg(name, arg); + return {name, arg}; } -// This function template is deleted intentionally to disable nested named -// arguments as in ``format("{}", arg("a", arg("b", 42)))``. +// Disable nested named arguments, e.g. ``arg("a", arg("b", 42))``. template void arg(S, internal::named_arg) = delete; -// 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("{}"), 42). -struct compile_string {}; - -namespace internal { -// If S is a format string type, format_string_traints::char_type gives its -// character type. -template -struct format_string_traits { - private: - // Use constructability as a way to detect if format_string_traits is - // specialized because other methods are broken on MSVC2013. - format_string_traits(); -}; - -template -struct format_string_traits_base { typedef Char char_type; }; - -template -struct format_string_traits : format_string_traits_base {}; - -template -struct format_string_traits : format_string_traits_base {}; - -template -struct format_string_traits : format_string_traits_base {}; - -template -struct format_string_traits : format_string_traits_base {}; - -template -struct format_string_traits> : - format_string_traits_base {}; - -template -struct format_string_traits< - S, typename std::enable_if, S>::value>::type> : - format_string_traits_base {}; - -template -struct is_format_string : - std::integral_constant< - bool, std::is_constructible>::value> {}; - -template -struct is_compile_string : - std::integral_constant::value> {}; - -template -inline typename std::enable_if::value>::type - check_format_string(const S &) {} -template -typename std::enable_if::value>::type - check_format_string(S); - -template -std::basic_string vformat( - basic_string_view format_str, - basic_format_args::type> args); -} // namespace internal - -format_context::iterator vformat_to( - internal::buffer &buf, string_view format_str, format_args args); -wformat_context::iterator vformat_to( - internal::wbuffer &buf, wstring_view format_str, wformat_args args); - template -struct is_contiguous : std::false_type {}; +struct is_contiguous: std::false_type {}; template -struct is_contiguous> : std::true_type {}; +struct is_contiguous >: std::true_type {}; template -struct is_contiguous> : std::true_type {}; +struct is_contiguous >: std::true_type {}; /** Formats a string and writes the output to ``out``. */ -template +template typename std::enable_if< - is_contiguous::value, std::back_insert_iterator>::type - vformat_to(std::back_insert_iterator out, - string_view format_str, format_args args) { + is_contiguous::value, std::back_insert_iterator>::type + vformat_to( + std::back_insert_iterator out, + const S &format_str, + basic_format_args::type> args) { internal::container_buffer buf(internal::get_container(out)); - vformat_to(buf, format_str, args); + internal::vformat_to(buf, to_string_view(format_str), args); return out; } -template -typename std::enable_if< - is_contiguous::value, std::back_insert_iterator>::type - vformat_to(std::back_insert_iterator out, - wstring_view format_str, wformat_args args) { - internal::container_buffer buf(internal::get_container(out)); - vformat_to(buf, format_str, args); - return out; -} - -template +template inline typename std::enable_if< - is_contiguous::value, std::back_insert_iterator>::type - format_to(std::back_insert_iterator out, - string_view format_str, const Args & ... args) { - format_arg_store as{args...}; - return vformat_to(out, format_str, as); + is_contiguous::value && internal::is_string::value, + std::back_insert_iterator>::type + format_to(std::back_insert_iterator out, const S &format_str, + const Args &... args) { + internal::checked_args ca(format_str, args...); + return vformat_to(out, to_string_view(format_str), *ca); } -template -inline typename std::enable_if< - is_contiguous::value, std::back_insert_iterator>::type - format_to(std::back_insert_iterator out, - wstring_view format_str, const Args & ... args) { - return vformat_to(out, format_str, - make_format_args(args...)); -} - -template < - typename String, - typename Char = typename internal::format_string_traits::char_type> +template inline std::basic_string vformat( - const String &format_str, + const S &format_str, basic_format_args::type> args) { - // Convert format string to string_view to reduce the number of overloads. - return internal::vformat(basic_string_view(format_str), args); + return internal::vformat(to_string_view(format_str), args); } /** @@ -1431,19 +1450,12 @@ inline std::basic_string vformat( std::string message = fmt::format("The answer is {}", 42); \endrst */ -template -inline std::basic_string< - typename internal::format_string_traits::char_type> - format(const String &format_str, const Args & ... args) { - internal::check_format_string(format_str); - // This should be just - // return vformat(format_str, make_format_args(args...)); - // but gcc has trouble optimizing the latter, so break it down. - typedef typename internal::format_string_traits::char_type char_t; - typedef typename buffer_context::type context_t; - format_arg_store as{args...}; +template +inline std::basic_string format( + const S &format_str, const Args &... args) { return internal::vformat( - basic_string_view(format_str), basic_format_args(as)); + to_string_view(format_str), + *internal::checked_args(format_str, args...)); } FMT_API void vprint(std::FILE *f, string_view format_str, format_args args); @@ -1451,27 +1463,20 @@ FMT_API void vprint(std::FILE *f, wstring_view format_str, wformat_args args); /** \rst - Prints formatted data to the file *f*. + Prints formatted data to the file *f*. For wide format strings, + *f* should be in wide-oriented mode set via ``fwide(f, 1)`` or + ``_setmode(_fileno(f), _O_U8TEXT)`` on Windows. **Example**:: fmt::print(stderr, "Don't {}!", "panic"); \endrst */ -template -inline void print(std::FILE *f, string_view format_str, const Args & ... args) { - format_arg_store as(args...); - vprint(f, format_str, as); -} -/** - Prints formatted data to the file *f* which should be in wide-oriented mode - set via ``fwide(f, 1)`` or ``_setmode(_fileno(f), _O_U8TEXT)`` on Windows. - */ -template -inline void print(std::FILE *f, wstring_view format_str, - const Args & ... args) { - format_arg_store as(args...); - vprint(f, format_str, as); +template +inline FMT_ENABLE_IF_T(internal::is_string::value, void) + print(std::FILE *f, const S &format_str, const Args &... args) { + vprint(f, to_string_view(format_str), + internal::checked_args(format_str, args...)); } FMT_API void vprint(string_view format_str, format_args args); @@ -1486,16 +1491,11 @@ FMT_API void vprint(wstring_view format_str, wformat_args args); fmt::print("Elapsed time: {0:.2f} seconds", 1.23); \endrst */ -template -inline void print(string_view format_str, const Args & ... args) { - format_arg_store as{args...}; - vprint(format_str, as); -} - -template -inline void print(wstring_view format_str, const Args & ... args) { - format_arg_store as(args...); - vprint(format_str, as); +template +inline FMT_ENABLE_IF_T(internal::is_string::value, void) + print(const S &format_str, const Args &... args) { + vprint(to_string_view(format_str), + internal::checked_args(format_str, args...)); } FMT_END_NAMESPACE diff --git a/include/fmt/format-inl.h b/include/fmt/format-inl.h index 56c4d581..552c9430 100644 --- a/include/fmt/format-inl.h +++ b/include/fmt/format-inl.h @@ -136,12 +136,14 @@ int safe_strerror( ERANGE : result; } +#if !FMT_MSC_VER // Fallback to strerror if strerror_r and strerror_s are not available. int fallback(internal::null<>) { errno = 0; buffer_ = strerror(error_code_); return errno; } +#endif public: dispatcher(int err_code, char *&buf, std::size_t buf_size) @@ -170,7 +172,7 @@ void format_error_code(internal::buffer &out, int error_code, abs_value = 0 - abs_value; ++error_code_size; } - error_code_size += internal::count_digits(abs_value); + error_code_size += internal::to_unsigned(internal::count_digits(abs_value)); writer w(out); if (message.size() <= inline_buffer_size - error_code_size) { w.write(message); @@ -192,34 +194,39 @@ void report_error(FormatFunc func, int error_code, } } // namespace -#if !defined(FMT_STATIC_THOUSANDS_SEPARATOR) -class locale { - private: - std::locale locale_; - - public: - explicit locale(std::locale loc = std::locale()) : locale_(loc) {} - std::locale get() { return locale_; } -}; - -FMT_FUNC size_t internal::count_code_points(u8string_view s) { +FMT_FUNC size_t internal::count_code_points(basic_string_view s) { const char8_t *data = s.data(); - int num_code_points = 0; + size_t num_code_points = 0; for (size_t i = 0, size = s.size(); i != size; ++i) { - if ((data[i].value & 0xc0) != 0x80) + if ((data[i] & 0xc0) != 0x80) ++num_code_points; } return num_code_points; } +#if !defined(FMT_STATIC_THOUSANDS_SEPARATOR) +namespace internal { + +template +locale_ref::locale_ref(const Locale &loc) : locale_(&loc) { + static_assert(std::is_same::value, ""); +} + +template +Locale locale_ref::get() const { + static_assert(std::is_same::value, ""); + return locale_ ? *static_cast(locale_) : std::locale(); +} + template -FMT_FUNC Char internal::thousands_sep(locale_provider *lp) { - std::locale loc = lp ? lp->locale().get() : std::locale(); - return std::use_facet>(loc).thousands_sep(); +FMT_FUNC Char thousands_sep_impl(locale_ref loc) { + return std::use_facet >( + loc.get()).thousands_sep(); +} } #else template -FMT_FUNC Char internal::thousands_sep(locale_provider *lp) { +FMT_FUNC Char internal::thousands_sep_impl(locale_ref) { return FMT_STATIC_THOUSANDS_SEPARATOR; } #endif @@ -236,19 +243,19 @@ FMT_FUNC void system_error::init( namespace internal { template int char_traits::format_float( - char *buffer, std::size_t size, const char *format, int precision, T value) { + char *buf, std::size_t size, const char *format, int precision, T value) { return precision < 0 ? - FMT_SNPRINTF(buffer, size, format, value) : - FMT_SNPRINTF(buffer, size, format, precision, value); + FMT_SNPRINTF(buf, size, format, value) : + FMT_SNPRINTF(buf, size, format, precision, value); } template int char_traits::format_float( - wchar_t *buffer, std::size_t size, const wchar_t *format, int precision, + wchar_t *buf, std::size_t size, const wchar_t *format, int precision, T value) { return precision < 0 ? - FMT_SWPRINTF(buffer, size, format, value) : - FMT_SWPRINTF(buffer, size, format, precision, value); + FMT_SWPRINTF(buf, size, format, value) : + FMT_SWPRINTF(buf, size, format, precision, value); } template @@ -337,6 +344,8 @@ const int16_t basic_data::POW10_EXPONENTS[] = { 827, 853, 880, 907, 933, 960, 986, 1013, 1039, 1066 }; +template const char basic_data::FOREGROUND_COLOR[] = "\x1b[38;2;"; +template const char basic_data::BACKGROUND_COLOR[] = "\x1b[48;2;"; template const char basic_data::RESET_COLOR[] = "\x1b[0m"; template const wchar_t basic_data::WRESET_COLOR[] = L"\x1b[0m"; @@ -363,7 +372,7 @@ class fp { sizeof(significand_type) * char_size; fp(): f(0), e(0) {} - fp(uint64_t f, int e): f(f), e(e) {} + 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. @@ -454,19 +463,28 @@ FMT_FUNC fp get_cached_power(int min_exponent, int &pow10_exponent) { return fp(data::POW10_SIGNIFICANDS[index], data::POW10_EXPONENTS[index]); } +FMT_FUNC bool grisu2_round( + char *buf, int &size, int max_digits, uint64_t delta, + uint64_t remainder, uint64_t exp, uint64_t diff, int &exp10) { + while (remainder < diff && delta - remainder >= exp && + (remainder + exp < diff || diff - remainder > remainder + exp - diff)) { + --buf[size - 1]; + remainder += exp; + } + if (size > max_digits) { + --size; + ++exp10; + if (buf[size] >= '5') + return false; + } + return true; +} + // Generates output using Grisu2 digit-gen algorithm. -FMT_FUNC void grisu2_gen_digits( - const fp &scaled_value, const fp &scaled_upper, uint64_t delta, - char *buffer, size_t &size, int &dec_exp) { - internal::fp one(1ull << -scaled_upper.e, scaled_upper.e); - // hi (p1 in Grisu) contains the most significant digits of scaled_upper. - // hi = floor(scaled_upper / one). - uint32_t hi = static_cast(scaled_upper.f >> -one.e); - // lo (p2 in Grisu) contains the least significants digits of scaled_upper. - // lo = scaled_upper mod 1. - uint64_t lo = scaled_upper.f & (one.f - 1); - size = 0; - auto exp = count_digits(hi); // kappa in Grisu. +FMT_FUNC bool grisu2_gen_digits( + char *buf, int &size, uint32_t hi, uint64_t lo, int &exp, + uint64_t delta, const fp &one, const fp &diff, int max_digits) { + // Generate digits for the most significant part (hi). while (exp > 0) { uint32_t digit = 0; // This optimization by miloyip reduces the number of integer divisions by @@ -486,148 +504,32 @@ FMT_FUNC void grisu2_gen_digits( FMT_ASSERT(false, "invalid number of digits"); } if (digit != 0 || size != 0) - buffer[size++] = static_cast('0' + digit); + buf[size++] = static_cast('0' + digit); --exp; uint64_t remainder = (static_cast(hi) << -one.e) + lo; - if (remainder <= delta) { - dec_exp += exp; - // TODO: use scaled_value - (void)scaled_value; - return; + if (remainder <= delta || size > max_digits) { + return grisu2_round( + buf, size, max_digits, delta, remainder, + static_cast(data::POWERS_OF_10_32[exp]) << -one.e, + diff.f, exp); } } + // Generate digits for the least significant part (lo). for (;;) { lo *= 10; delta *= 10; char digit = static_cast(lo >> -one.e); if (digit != 0 || size != 0) - buffer[size++] = static_cast('0' + digit); + buf[size++] = static_cast('0' + digit); lo &= one.f - 1; --exp; - if (lo < delta) { - dec_exp += exp; - return; + if (lo < delta || size > max_digits) { + return grisu2_round(buf, size, max_digits, delta, lo, one.f, + diff.f * data::POWERS_OF_10_32[-exp], exp); } } } -FMT_FUNC void grisu2_format_positive(double value, char *buffer, size_t &size, - int &dec_exp) { - FMT_ASSERT(value > 0, "value is nonpositive"); - fp fp_value(value); - fp lower, upper; // w^- and w^+ in the Grisu paper. - fp_value.compute_boundaries(lower, upper); - // Find a cached power of 10 close to 1 / upper. - const int min_exp = -60; // alpha in Grisu. - auto dec_pow = get_cached_power( // \tilde{c}_{-k} in Grisu. - min_exp - (upper.e + fp::significand_size), dec_exp); - dec_exp = -dec_exp; - fp_value.normalize(); - fp scaled_value = fp_value * dec_pow; - fp scaled_lower = lower * dec_pow; // \tilde{M}^- in Grisu. - fp scaled_upper = upper * dec_pow; // \tilde{M}^+ in Grisu. - ++scaled_lower.f; // \tilde{M}^- + 1 ulp -> M^-_{\uparrow}. - --scaled_upper.f; // \tilde{M}^+ - 1 ulp -> M^+_{\downarrow}. - uint64_t delta = scaled_upper.f - scaled_lower.f; - grisu2_gen_digits(scaled_value, scaled_upper, delta, buffer, size, dec_exp); -} - -FMT_FUNC void round(char *buffer, size_t &size, int &exp, - int digits_to_remove) { - size -= to_unsigned(digits_to_remove); - exp += digits_to_remove; - int digit = buffer[size] - '0'; - // TODO: proper rounding and carry - if (digit > 5 || (digit == 5 && (digits_to_remove > 1 || - (buffer[size - 1] - '0') % 2) != 0)) { - ++buffer[size - 1]; - } -} - -// Writes the exponent exp in the form "[+-]d{1,3}" to buffer. -FMT_FUNC char *write_exponent(char *buffer, int exp) { - FMT_ASSERT(-1000 < exp && exp < 1000, "exponent out of range"); - if (exp < 0) { - *buffer++ = '-'; - exp = -exp; - } else { - *buffer++ = '+'; - } - if (exp >= 100) { - *buffer++ = static_cast('0' + exp / 100); - exp %= 100; - const char *d = data::DIGITS + exp * 2; - *buffer++ = d[0]; - *buffer++ = d[1]; - } else { - const char *d = data::DIGITS + exp * 2; - *buffer++ = d[0]; - *buffer++ = d[1]; - } - return buffer; -} - -FMT_FUNC void format_exp_notation( - char *buffer, size_t &size, int exp, int precision, bool upper) { - // Insert a decimal point after the first digit and add an exponent. - std::memmove(buffer + 2, buffer + 1, size - 1); - buffer[1] = '.'; - exp += static_cast(size) - 1; - int num_digits = precision - static_cast(size) + 1; - if (num_digits > 0) { - std::uninitialized_fill_n(buffer + size + 1, num_digits, '0'); - size += to_unsigned(num_digits); - } else if (num_digits < 0) { - round(buffer, size, exp, -num_digits); - } - char *p = buffer + size + 1; - *p++ = upper ? 'E' : 'e'; - size = to_unsigned(write_exponent(p, exp) - buffer); -} - -// Prettifies the output of the Grisu2 algorithm. -// The number is given as v = buffer * 10^exp. -FMT_FUNC void grisu2_prettify(char *buffer, size_t &size, int exp, - int precision, bool upper) { - // pow(10, full_exp - 1) <= v <= pow(10, full_exp). - int int_size = static_cast(size); - int full_exp = int_size + exp; - const int exp_threshold = 21; - if (int_size <= full_exp && full_exp <= exp_threshold) { - // 1234e7 -> 12340000000[.0+] - std::uninitialized_fill_n(buffer + int_size, full_exp - int_size, '0'); - char *p = buffer + full_exp; - if (precision > 0) { - *p++ = '.'; - std::uninitialized_fill_n(p, precision, '0'); - p += precision; - } - size = to_unsigned(p - buffer); - } else if (0 < full_exp && full_exp <= exp_threshold) { - // 1234e-2 -> 12.34[0+] - int fractional_size = -exp; - std::memmove(buffer + full_exp + 1, buffer + full_exp, - to_unsigned(fractional_size)); - buffer[full_exp] = '.'; - int num_zeros = precision - fractional_size; - if (num_zeros > 0) { - std::uninitialized_fill_n(buffer + size + 1, num_zeros, '0'); - size += to_unsigned(num_zeros); - } - ++size; - } else if (-6 < full_exp && full_exp <= 0) { - // 1234e-6 -> 0.001234 - int offset = 2 - full_exp; - std::memmove(buffer + offset, buffer, size); - buffer[0] = '0'; - buffer[1] = '.'; - std::uninitialized_fill_n(buffer + 2, -full_exp, '0'); - size = to_unsigned(int_size + offset); - } else { - format_exp_notation(buffer, size, exp, precision, upper); - } -} - #if FMT_CLANG_VERSION # define FMT_FALLTHROUGH [[clang::fallthrough]]; #elif FMT_GCC_VERSION >= 700 @@ -636,58 +538,270 @@ FMT_FUNC void grisu2_prettify(char *buffer, size_t &size, int exp, # define FMT_FALLTHROUGH #endif -// Formats a nonnegative value using Grisu2 algorithm. Grisu2 doesn't give any -// guarantees on the shortness of the result. -FMT_FUNC void grisu2_format(double value, char *buffer, size_t &size, char type, - int precision, bool write_decimal_point) { - FMT_ASSERT(value >= 0, "value is negative"); - int dec_exp = 0; // K in Grisu. - if (value > 0) { - grisu2_format_positive(value, buffer, size, dec_exp); +struct gen_digits_params { + int num_digits; + bool fixed; + bool upper; + bool trailing_zeros; +}; + +struct prettify_handler { + char *data; + ptrdiff_t size; + buffer &buf; + + explicit prettify_handler(buffer &b, ptrdiff_t n) + : data(b.data()), size(n), buf(b) {} + ~prettify_handler() { + assert(buf.size() >= to_unsigned(size)); + buf.resize(to_unsigned(size)); + } + + template + void insert(ptrdiff_t pos, ptrdiff_t n, F f) { + std::memmove(data + pos + n, data + pos, to_unsigned(size - pos)); + f(data + pos); + size += n; + } + + void insert(ptrdiff_t pos, char c) { + std::memmove(data + pos + 1, data + pos, to_unsigned(size - pos)); + data[pos] = c; + ++size; + } + + void append(ptrdiff_t n, char c) { + std::uninitialized_fill_n(data + size, n, c); + size += n; + } + + void append(char c) { data[size++] = c; } + + void remove_trailing(char c) { + while (data[size - 1] == c) --size; + } +}; + +// Writes the exponent exp in the form "[+-]d{2,3}" to buffer. +template +FMT_FUNC void write_exponent(int exp, Handler &&h) { + FMT_ASSERT(-1000 < exp && exp < 1000, "exponent out of range"); + if (exp < 0) { + h.append('-'); + exp = -exp; } else { - *buffer = '0'; - size = 1; + h.append('+'); } - const int default_precision = 6; - if (precision < 0) - precision = default_precision; - bool upper = false; - switch (type) { - case 'G': - upper = true; - FMT_FALLTHROUGH - case '\0': case 'g': { - int digits_to_remove = static_cast(size) - precision; - if (digits_to_remove > 0) { - round(buffer, size, dec_exp, digits_to_remove); - // Remove trailing zeros. - while (size > 0 && buffer[size - 1] == '0') { - --size; - ++dec_exp; - } - } - precision = 0; - break; + if (exp >= 100) { + h.append(static_cast('0' + exp / 100)); + exp %= 100; + const char *d = data::DIGITS + exp * 2; + h.append(d[0]); + h.append(d[1]); + } else { + const char *d = data::DIGITS + exp * 2; + h.append(d[0]); + h.append(d[1]); } - case 'F': - upper = true; - FMT_FALLTHROUGH - case 'f': { - int digits_to_remove = -dec_exp - precision; - if (digits_to_remove > 0) { - if (digits_to_remove >= static_cast(size)) - digits_to_remove = static_cast(size) - 1; - round(buffer, size, dec_exp, digits_to_remove); - } - break; +} + +struct fill { + size_t n; + void operator()(char *buf) const { + buf[0] = '0'; + buf[1] = '.'; + std::uninitialized_fill_n(buf + 2, n, '0'); } - case 'e': case 'E': - format_exp_notation(buffer, size, dec_exp, precision, type == 'E'); +}; + +// The number is given as v = f * pow(10, exp), where f has size digits. +template +FMT_FUNC void grisu2_prettify(const gen_digits_params ¶ms, + int size, int exp, Handler &&handler) { + if (!params.fixed) { + // Insert a decimal point after the first digit and add an exponent. + handler.insert(1, '.'); + exp += size - 1; + if (size < params.num_digits) + handler.append(params.num_digits - size, '0'); + handler.append(params.upper ? 'E' : 'e'); + write_exponent(exp, handler); return; } - if (write_decimal_point && precision < 1) - precision = 1; - grisu2_prettify(buffer, size, dec_exp, precision, upper); + // pow(10, full_exp - 1) <= v <= pow(10, full_exp). + int full_exp = size + exp; + const int exp_threshold = 21; + if (size <= full_exp && full_exp <= exp_threshold) { + // 1234e7 -> 12340000000[.0+] + handler.append(full_exp - size, '0'); + int num_zeros = params.num_digits - full_exp; + if (num_zeros > 0 && params.trailing_zeros) { + handler.append('.'); + handler.append(num_zeros, '0'); + } + } else if (full_exp > 0) { + // 1234e-2 -> 12.34[0+] + handler.insert(full_exp, '.'); + if (!params.trailing_zeros) { + // Remove trailing zeros. + handler.remove_trailing('0'); + } else if (params.num_digits > size) { + // Add trailing zeros. + ptrdiff_t num_zeros = params.num_digits - size; + handler.append(num_zeros, '0'); + } + } else { + // 1234e-6 -> 0.001234 + handler.insert(0, 2 - full_exp, fill{to_unsigned(-full_exp)}); + } +} + +struct char_counter { + ptrdiff_t size; + + template + void insert(ptrdiff_t, ptrdiff_t n, F) { size += n; } + void insert(ptrdiff_t, char) { ++size; } + void append(ptrdiff_t n, char) { size += n; } + void append(char) { ++size; } + void remove_trailing(char) {} +}; + +// Converts format specifiers into parameters for digit generation and computes +// output buffer size for a number in the range [pow(10, exp - 1), pow(10, exp) +// or 0 if exp == 1. +FMT_FUNC gen_digits_params process_specs(const core_format_specs &specs, + int exp, buffer &buf) { + auto params = gen_digits_params(); + int num_digits = specs.precision >= 0 ? specs.precision : 6; + switch (specs.type) { + case 'G': + params.upper = true; + FMT_FALLTHROUGH + case '\0': case 'g': + params.trailing_zeros = (specs.flags & HASH_FLAG) != 0; + if (-4 <= exp && exp < num_digits + 1) { + params.fixed = true; + if (!specs.type && params.trailing_zeros && exp >= 0) + num_digits = exp + 1; + } + break; + case 'F': + params.upper = true; + FMT_FALLTHROUGH + case 'f': { + params.fixed = true; + params.trailing_zeros = true; + int adjusted_min_digits = num_digits + exp; + if (adjusted_min_digits > 0) + num_digits = adjusted_min_digits; + break; + } + case 'E': + params.upper = true; + FMT_FALLTHROUGH + case 'e': + ++num_digits; + break; + } + params.num_digits = num_digits; + char_counter counter{num_digits}; + grisu2_prettify(params, params.num_digits, exp - num_digits, counter); + buf.resize(to_unsigned(counter.size)); + return params; +} + +template +FMT_FUNC typename std::enable_if::type + grisu2_format(Double value, buffer &buf, core_format_specs specs) { + FMT_ASSERT(value >= 0, "value is negative"); + if (value == 0) { + gen_digits_params params = process_specs(specs, 1, buf); + const size_t size = 1; + buf[0] = '0'; + grisu2_prettify(params, size, 0, prettify_handler(buf, size)); + return true; + } + + fp fp_value(value); + fp lower, upper; // w^- and w^+ in the Grisu paper. + fp_value.compute_boundaries(lower, upper); + + // Find a cached power of 10 close to 1 / upper and use it to scale upper. + const int min_exp = -60; // alpha in Grisu. + int cached_exp = 0; // K in Grisu. + auto cached_pow = get_cached_power( // \tilde{c}_{-k} in Grisu. + min_exp - (upper.e + fp::significand_size), cached_exp); + cached_exp = -cached_exp; + upper = upper * cached_pow; // \tilde{M}^+ in Grisu. + --upper.f; // \tilde{M}^+ - 1 ulp -> M^+_{\downarrow}. + fp one(1ull << -upper.e, upper.e); + // hi (p1 in Grisu) contains the most significant digits of scaled_upper. + // hi = floor(upper / one). + uint32_t hi = static_cast(upper.f >> -one.e); + int exp = count_digits(hi); // kappa in Grisu. + gen_digits_params params = process_specs(specs, cached_exp + exp, buf); + fp_value.normalize(); + fp scaled_value = fp_value * cached_pow; + lower = lower * cached_pow; // \tilde{M}^- in Grisu. + ++lower.f; // \tilde{M}^- + 1 ulp -> M^-_{\uparrow}. + uint64_t delta = upper.f - lower.f; + fp diff = upper - scaled_value; // wp_w in Grisu. + // lo (p2 in Grisu) contains the least significants digits of scaled_upper. + // lo = supper % one. + uint64_t lo = upper.f & (one.f - 1); + int size = 0; + if (!grisu2_gen_digits(buf.data(), size, hi, lo, exp, delta, one, diff, + params.num_digits)) { + buf.clear(); + return false; + } + grisu2_prettify(params, size, cached_exp + exp, prettify_handler(buf, size)); + return true; +} + +template +void sprintf_format(Double value, internal::buffer &buf, + core_format_specs spec) { + // Buffer capacity must be non-zero, otherwise MSVC's vsnprintf_s will fail. + FMT_ASSERT(buf.capacity() != 0, "empty buffer"); + + // Build format string. + enum { MAX_FORMAT_SIZE = 10}; // longest format: %#-*.*Lg + char format[MAX_FORMAT_SIZE]; + char *format_ptr = format; + *format_ptr++ = '%'; + if (spec.has(HASH_FLAG)) + *format_ptr++ = '#'; + if (spec.precision >= 0) { + *format_ptr++ = '.'; + *format_ptr++ = '*'; + } + if (std::is_same::value) + *format_ptr++ = 'L'; + *format_ptr++ = spec.type; + *format_ptr = '\0'; + + // Format using snprintf. + char *start = FMT_NULL; + for (;;) { + std::size_t buffer_size = buf.capacity(); + start = &buf[0]; + int result = internal::char_traits::format_float( + start, buffer_size, format, spec.precision, value); + if (result >= 0) { + unsigned n = internal::to_unsigned(result); + if (n < buf.capacity()) { + buf.resize(n); + break; // The buffer is large enough - continue with formatting. + } + buf.reserve(n + 1); + } else { + // If result is negative we ask to increase the capacity by at least 1, + // but as std::vector, the buffer grows exponentially. + buf.reserve(buf.capacity() + 1); + } + } } } // namespace internal @@ -812,11 +926,6 @@ FMT_FUNC void format_system_error( format_error_code(out, error_code, message); } -template -void basic_fixed_buffer::grow(std::size_t) { - FMT_THROW(std::runtime_error("buffer overflow")); -} - FMT_FUNC void internal::error_handler::on_error(const char *message) { FMT_THROW(format_error(message)); } @@ -835,13 +944,14 @@ FMT_FUNC void report_windows_error( FMT_FUNC void vprint(std::FILE *f, string_view format_str, format_args args) { memory_buffer buffer; - vformat_to(buffer, format_str, args); + internal::vformat_to(buffer, format_str, + basic_format_args::type>(args)); std::fwrite(buffer.data(), 1, buffer.size(), f); } FMT_FUNC void vprint(std::FILE *f, wstring_view format_str, wformat_args args) { wmemory_buffer buffer; - vformat_to(buffer, format_str, args); + internal::vformat_to(buffer, format_str, args); std::fwrite(buffer.data(), sizeof(wchar_t), buffer.size(), f); } @@ -853,10 +963,6 @@ FMT_FUNC void vprint(wstring_view format_str, wformat_args args) { vprint(stdout, format_str, args); } -#if !defined(FMT_STATIC_THOUSANDS_SEPARATOR) -FMT_FUNC locale locale_provider::locale() { return fmt::locale(); } -#endif - FMT_END_NAMESPACE #ifdef _MSC_VER diff --git a/include/fmt/format.h b/include/fmt/format.h index 9f522f39..1bb24a52 100644 --- a/include/fmt/format.h +++ b/include/fmt/format.h @@ -66,9 +66,9 @@ // many valid cases. # pragma GCC diagnostic ignored "-Wshadow" -// Disable the warning about implicit conversions that may change the sign of -// an integer; silencing it otherwise would require many explicit casts. -# pragma GCC diagnostic ignored "-Wsign-conversion" +// Disable the warning about nonliteral format strings because we construct +// them dynamically when falling back to snprintf for FP formatting. +# pragma GCC diagnostic ignored "-Wformat-nonliteral" #endif # if FMT_CLANG_VERSION @@ -163,6 +163,7 @@ FMT_END_NAMESPACE #ifndef FMT_USE_GRISU # define FMT_USE_GRISU 0 +//# define FMT_USE_GRISU std::numeric_limits::is_iec559 #endif // __builtin_clz is broken in clang with Microsoft CodeGen: @@ -177,14 +178,6 @@ FMT_END_NAMESPACE # endif #endif -// A workaround for gcc 4.4 that doesn't support union members with ctors. -#if (FMT_GCC_VERSION && FMT_GCC_VERSION <= 404) || \ - (FMT_MSC_VER && FMT_MSC_VER <= 1800) -# define FMT_UNION struct -#else -# define FMT_UNION union -#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. @@ -278,24 +271,13 @@ struct dummy_int { }; typedef std::numeric_limits fputil; -// Dummy implementations of system functions such as signbit and ecvt called -// if the latter are not available. -inline dummy_int signbit(...) { return dummy_int(); } -inline dummy_int _ecvt_s(...) { return dummy_int(); } +// Dummy implementations of system functions called if the latter are not +// available. inline dummy_int isinf(...) { return dummy_int(); } inline dummy_int _finite(...) { return dummy_int(); } inline dummy_int isnan(...) { return dummy_int(); } inline dummy_int _isnan(...) { return dummy_int(); } -inline bool use_grisu() { - return FMT_USE_GRISU && std::numeric_limits::is_iec559; -} - -// Formats value using Grisu2 algorithm: -// https://www.cs.tufts.edu/~nr/cs257/archive/florian-loitsch/printf.pdf -FMT_API void grisu2_format(double value, char *buffer, size_t &size, char type, - int precision, bool write_decimal_point); - template typename Allocator::value_type *allocate(Allocator& alloc, std::size_t n) { #if __cplusplus >= 201103L || FMT_MSC_VER >= 1700 @@ -316,7 +298,7 @@ namespace std { // Standard permits specialization of std::numeric_limits. This specialization // is used to resolve ambiguity between isinf and std::isinf in glibc: // https://gcc.gnu.org/bugzilla/show_bug.cgi?id=48891 -// and the same for isnan and signbit. +// and the same for isnan. template <> class numeric_limits : public std::numeric_limits { @@ -327,7 +309,7 @@ class numeric_limits : using namespace fmt::internal; // The resolution "priority" is: // isinf macro > std::isinf > ::isinf > fmt::internal::isinf - if (const_check(sizeof(isinf(x)) != sizeof(dummy_int))) + if (const_check(sizeof(isinf(x)) != sizeof(fmt::internal::dummy_int))) return isinf(x) != 0; return !_finite(static_cast(x)); } @@ -340,19 +322,6 @@ class numeric_limits : return isnan(x) != 0; return _isnan(static_cast(x)) != 0; } - - // Portable version of signbit. - static bool isnegative(double x) { - using namespace fmt::internal; - if (const_check(sizeof(signbit(x)) != sizeof(fmt::internal::dummy_int))) - return signbit(x) != 0; - if (x < 0) return true; - if (!isnotanumber(x)) return false; - int dec = 0, sign = 0; - char buffer[2]; // The buffer size must be >= 2 or _ecvt_s will fail. - _ecvt_s(buffer, sizeof(buffer), x, 0, &dec, &sign); - return sign != 0; - } }; } // namespace std @@ -431,48 +400,32 @@ void basic_buffer::append(const U *begin, const U *end) { } } // namespace internal +// C++20 feature test, since r346892 Clang considers char8_t a fundamental +// type in this mode. If this is the case __cpp_char8_t will be defined. +#if !defined(__cpp_char8_t) // A UTF-8 code unit type. -struct char8_t { - char value; - FMT_CONSTEXPR explicit operator bool() const FMT_NOEXCEPT { - return value != 0; - } -}; +enum char8_t: unsigned char {}; +#endif // A UTF-8 string view. class u8string_view : public basic_string_view { - private: - typedef basic_string_view base; - public: - using basic_string_view::basic_string_view; - using basic_string_view::char_type; + typedef char8_t char_type; - u8string_view(const char *s) - : base(reinterpret_cast(s)) {} - - u8string_view(const char *s, size_t count) FMT_NOEXCEPT - : base(reinterpret_cast(s), count) {} + u8string_view(const char *s): + basic_string_view(reinterpret_cast(s)) {} + u8string_view(const char *s, size_t count) FMT_NOEXCEPT: + basic_string_view(reinterpret_cast(s), count) {} }; #if FMT_USE_USER_DEFINED_LITERALS inline namespace literals { inline u8string_view operator"" _u(const char *s, std::size_t n) { - return u8string_view(s, n); + return {s, n}; } } #endif -// A wrapper around std::locale used to reduce compile times since -// is very heavy. -class locale; - -class locale_provider { - public: - virtual ~locale_provider() {} - virtual fmt::locale locale(); -}; - // The number of characters to store in the basic_memory_buffer object itself // to avoid dynamic memory allocation. enum { inline_buffer_size = 500 }; @@ -497,7 +450,7 @@ enum { inline_buffer_size = 500 }; fmt::memory_buffer out; format_to(out, "The answer is {}.", 42); - This will write the following output to the ``out`` object: + This will append the following output to the ``out`` object: .. code-block:: none @@ -522,6 +475,9 @@ class basic_memory_buffer: private Allocator, public internal::basic_buffer { void grow(std::size_t size) FMT_OVERRIDE; public: + typedef T value_type; + typedef const T &const_reference; + explicit basic_memory_buffer(const Allocator &alloc = Allocator()) : Allocator(alloc) { this->set(store_, SIZE); @@ -597,43 +553,6 @@ void basic_memory_buffer::grow(std::size_t size) { typedef basic_memory_buffer memory_buffer; typedef basic_memory_buffer wmemory_buffer; -/** - \rst - A fixed-size memory buffer. For a dynamically growing buffer use - :class:`fmt::basic_memory_buffer`. - - Trying to increase the buffer size past the initial capacity will throw - ``std::runtime_error``. - \endrst - */ -template -class basic_fixed_buffer : public internal::basic_buffer { - public: - /** - \rst - Constructs a :class:`fmt::basic_fixed_buffer` object for *array* of the - given size. - \endrst - */ - basic_fixed_buffer(Char *array, std::size_t size) { - this->set(array, size); - } - - /** - \rst - Constructs a :class:`fmt::basic_fixed_buffer` object for *array* of the - size known at compile time. - \endrst - */ - template - explicit basic_fixed_buffer(Char (&array)[SIZE]) { - this->set(array, SIZE); - } - - protected: - FMT_API void grow(std::size_t size) FMT_OVERRIDE; -}; - namespace internal { template @@ -690,98 +609,6 @@ class null_terminating_iterator; template FMT_CONSTEXPR_DECL const Char *pointer_from(null_terminating_iterator it); -// An iterator that produces a null terminator on *end. This simplifies parsing -// and allows comparing the performance of processing a null-terminated string -// vs string_view. -template -class null_terminating_iterator { - public: - typedef std::ptrdiff_t difference_type; - typedef Char value_type; - typedef const Char* pointer; - typedef const Char& reference; - typedef std::random_access_iterator_tag iterator_category; - - null_terminating_iterator() : ptr_(0), end_(0) {} - - FMT_CONSTEXPR null_terminating_iterator(const Char *ptr, const Char *end) - : ptr_(ptr), end_(end) {} - - template - FMT_CONSTEXPR explicit null_terminating_iterator(const Range &r) - : ptr_(r.begin()), end_(r.end()) {} - - FMT_CONSTEXPR null_terminating_iterator &operator=(const Char *ptr) { - assert(ptr <= end_); - ptr_ = ptr; - return *this; - } - - FMT_CONSTEXPR Char operator*() const { - return ptr_ != end_ ? *ptr_ : 0; - } - - FMT_CONSTEXPR null_terminating_iterator operator++() { - ++ptr_; - return *this; - } - - FMT_CONSTEXPR null_terminating_iterator operator++(int) { - null_terminating_iterator result(*this); - ++ptr_; - return result; - } - - FMT_CONSTEXPR null_terminating_iterator operator--() { - --ptr_; - return *this; - } - - FMT_CONSTEXPR null_terminating_iterator operator+(difference_type n) { - return null_terminating_iterator(ptr_ + n, end_); - } - - FMT_CONSTEXPR null_terminating_iterator operator-(difference_type n) { - return null_terminating_iterator(ptr_ - n, end_); - } - - FMT_CONSTEXPR null_terminating_iterator operator+=(difference_type n) { - ptr_ += n; - return *this; - } - - FMT_CONSTEXPR difference_type operator-( - null_terminating_iterator other) const { - return ptr_ - other.ptr_; - } - - FMT_CONSTEXPR bool operator!=(null_terminating_iterator other) const { - return ptr_ != other.ptr_; - } - - bool operator>=(null_terminating_iterator other) const { - return ptr_ >= other.ptr_; - } - - // This should be a friend specialization pointer_from but the latter - // doesn't compile by gcc 5.1 due to a compiler bug. - template - friend FMT_CONSTEXPR_DECL const CharT *pointer_from( - null_terminating_iterator it); - - private: - const Char *ptr_; - const Char *end_; -}; - -template -FMT_CONSTEXPR const T *pointer_from(const T *p) { return p; } - -template -FMT_CONSTEXPR const Char *pointer_from(null_terminating_iterator it) { - return it.ptr_; -} - // An output iterator that counts the number of objects written to it and // discards them. template @@ -816,35 +643,49 @@ class counting_iterator { T &operator*() const { return blackhole_; } }; -// An output iterator that truncates the output and counts the number of objects -// written to it. template -class truncating_iterator { - private: - typedef std::iterator_traits traits; - +class truncating_iterator_base { + protected: OutputIt out_; std::size_t limit_; std::size_t count_; - mutable typename traits::value_type blackhole_; + + truncating_iterator_base(OutputIt out, std::size_t limit) + : out_(out), limit_(limit), count_(0) {} public: typedef std::output_iterator_tag iterator_category; - typedef typename traits::value_type value_type; - typedef typename traits::difference_type difference_type; - typedef typename traits::pointer pointer; - typedef typename traits::reference reference; - typedef truncating_iterator _Unchecked_type; // Mark iterator as checked. - - truncating_iterator(OutputIt out, std::size_t limit) - : out_(out), limit_(limit), count_(0) {} + typedef void difference_type; + typedef void pointer; + typedef void reference; + typedef truncating_iterator_base _Unchecked_type; // Mark iterator as checked. OutputIt base() const { return out_; } std::size_t count() const { return count_; } +}; + +// An output iterator that truncates the output and counts the number of objects +// written to it. +template ::value_type>::type> +class truncating_iterator; + +template +class truncating_iterator: + public truncating_iterator_base { + typedef std::iterator_traits traits; + + mutable typename traits::value_type blackhole_; + + public: + typedef typename traits::value_type value_type; + + truncating_iterator(OutputIt out, std::size_t limit) + : truncating_iterator_base(out, limit) {} truncating_iterator& operator++() { - if (count_++ < limit_) - ++out_; + if (this->count_++ < this->limit_) + ++this->out_; return *this; } @@ -854,7 +695,29 @@ class truncating_iterator { return it; } - reference operator*() const { return count_ < limit_ ? *out_ : blackhole_; } + value_type& operator*() const { + return this->count_ < this->limit_ ? *this->out_ : blackhole_; + } +}; + +template +class truncating_iterator: + public truncating_iterator_base { + public: + typedef typename OutputIt::container_type::value_type value_type; + + truncating_iterator(OutputIt out, std::size_t limit) + : truncating_iterator_base(out, limit) {} + + truncating_iterator& operator=(value_type 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; } }; // Returns true if value is negative, false otherwise. @@ -888,6 +751,8 @@ struct FMT_API basic_data { static const uint64_t POW10_SIGNIFICANDS[]; static const int16_t POW10_EXPONENTS[]; static const char DIGITS[]; + static const char FOREGROUND_COLOR[]; + static const char BACKGROUND_COLOR[]; static const char RESET_COLOR[]; static const wchar_t WRESET_COLOR[]; }; @@ -901,16 +766,16 @@ typedef basic_data<> 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 unsigned count_digits(uint64_t n) { +inline int count_digits(uint64_t n) { // Based on http://graphics.stanford.edu/~seander/bithacks.html#IntegerLog10 // and the benchmark https://github.com/localvoid/cxx-benchmark-count-digits. int t = (64 - FMT_BUILTIN_CLZLL(n | 1)) * 1233 >> 12; - return to_unsigned(t) - (n < data::ZERO_OR_POWERS_OF_10_64[t]) + 1; + return t - (n < data::ZERO_OR_POWERS_OF_10_64[t]) + 1; } #else // Fallback version of count_digits used when __builtin_clz is not available. -inline unsigned count_digits(uint64_t n) { - unsigned count = 1; +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 @@ -925,8 +790,33 @@ inline unsigned count_digits(uint64_t n) { } #endif +template +inline size_t count_code_points(basic_string_view s) { return s.size(); } + // Counts the number of code points in a UTF-8 string. -FMT_API size_t count_code_points(u8string_view s); +FMT_API size_t count_code_points(basic_string_view s); + +inline char8_t to_char8_t(char c) { return static_cast(c); } + +template +struct needs_conversion: std::integral_constant::value_type, char>::value && + std::is_same::value> {}; + +template +typename std::enable_if< + !needs_conversion::value, OutputIt>::type + copy_str(InputIt begin, InputIt end, OutputIt it) { + return std::copy(begin, end, it); +} + +template +typename std::enable_if< + needs_conversion::value, OutputIt>::type + copy_str(InputIt begin, InputIt end, OutputIt it) { + return std::transform(begin, end, it, to_char8_t); +} #if FMT_HAS_CPP_ATTRIBUTE(always_inline) # define FMT_ALWAYS_INLINE __attribute__((always_inline)) @@ -1006,9 +896,9 @@ class decimal_formatter_null : public decimal_formatter { #ifdef FMT_BUILTIN_CLZ // Optional version of count_digits for better performance on 32-bit platforms. -inline unsigned count_digits(uint32_t n) { +inline int count_digits(uint32_t n) { int t = (32 - FMT_BUILTIN_CLZ(n | 1)) * 1233 >> 12; - return to_unsigned(t) - (n < data::ZERO_OR_POWERS_OF_10_32[t]) + 1; + return t - (n < data::ZERO_OR_POWERS_OF_10_32[t]) + 1; } #endif @@ -1018,6 +908,8 @@ struct no_thousands_sep { template void operator()(Char *) {} + + enum { size = 0 }; }; // A functor that adds a thousands separator. @@ -1042,17 +934,30 @@ class add_thousands_sep { std::uninitialized_copy(sep_.data(), sep_.data() + sep_.size(), internal::make_checked(buffer, sep_.size())); } + + enum { size = 1 }; }; template -FMT_API Char thousands_sep(locale_provider *lp); +FMT_API Char thousands_sep_impl(locale_ref loc); + +template +inline Char thousands_sep(locale_ref loc) { + return Char(thousands_sep_impl(loc)); +} + +template <> +inline wchar_t thousands_sep(locale_ref loc) { + return thousands_sep_impl(loc); +} // Formats a decimal unsigned integer value writing into buffer. // thousands_sep is a functor that is called after writing each char to // add a thousands separator if necessary. template -inline Char *format_decimal(Char *buffer, UInt value, unsigned num_digits, +inline Char *format_decimal(Char *buffer, UInt value, int num_digits, ThousandsSep thousands_sep) { + FMT_ASSERT(num_digits >= 0, "invalid digit count"); buffer += num_digits; Char *end = buffer; while (value >= 100) { @@ -1061,58 +966,63 @@ inline Char *format_decimal(Char *buffer, UInt value, unsigned num_digits, // "Three Optimization Tips for C++". See speed-test for a comparison. unsigned index = static_cast((value % 100) * 2); value /= 100; - *--buffer = data::DIGITS[index + 1]; + *--buffer = static_cast(data::DIGITS[index + 1]); thousands_sep(buffer); - *--buffer = data::DIGITS[index]; + *--buffer = static_cast(data::DIGITS[index]); thousands_sep(buffer); } if (value < 10) { - *--buffer = static_cast('0' + value); + *--buffer = static_cast('0' + value); return end; } unsigned index = static_cast(value * 2); - *--buffer = data::DIGITS[index + 1]; + *--buffer = static_cast(data::DIGITS[index + 1]); thousands_sep(buffer); - *--buffer = data::DIGITS[index]; + *--buffer = static_cast(data::DIGITS[index]); return end; } -template +template inline Iterator format_decimal( - Iterator out, UInt value, unsigned num_digits, ThousandsSep sep) { + Iterator out, UInt value, int num_digits, ThousandsSep sep) { + FMT_ASSERT(num_digits >= 0, "invalid digit count"); typedef typename ThousandsSep::char_type char_type; - // Buffer should be large enough to hold all digits (digits10 + 1) and null. - char_type buffer[std::numeric_limits::digits10 + 2]; - format_decimal(buffer, value, num_digits, sep); - return std::copy_n(buffer, num_digits, out); + // Buffer should be large enough to hold all digits (<= digits10 + 1). + enum { max_size = std::numeric_limits::digits10 + 1 }; + FMT_ASSERT(ThousandsSep::size <= 1, "invalid separator"); + char_type buffer[max_size + max_size / 3]; + auto end = format_decimal(buffer, value, num_digits, sep); + return internal::copy_str(buffer, end, out); } -template -inline It format_decimal(It out, UInt value, unsigned num_digits) { - return format_decimal(out, value, num_digits, no_thousands_sep()); +template +inline It format_decimal(It out, UInt value, int num_digits) { + return format_decimal(out, value, num_digits, no_thousands_sep()); } template -inline Char *format_uint(Char *buffer, UInt value, unsigned num_digits, +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" : "0123456789abcdef"; unsigned digit = (value & ((1 << BASE_BITS) - 1)); - *--buffer = BASE_BITS < 4 ? static_cast('0' + digit) : digits[digit]; + *--buffer = static_cast(BASE_BITS < 4 ? static_cast('0' + digit) + : digits[digit]); } while ((value >>= BASE_BITS) != 0); return end; } -template -inline It format_uint(It out, UInt value, unsigned num_digits, +template +inline It format_uint(It out, UInt value, int num_digits, bool upper = false) { // Buffer should be large enough to hold all digits (digits / BASE_BITS + 1) // and null. char buffer[std::numeric_limits::digits / BASE_BITS + 2]; format_uint(buffer, value, num_digits, upper); - return std::copy_n(buffer, num_digits, out); + return internal::copy_str(buffer, buffer + num_digits, out); } #ifndef _WIN32 @@ -1171,72 +1081,35 @@ enum alignment { }; // Flags. -enum {SIGN_FLAG = 1, PLUS_FLAG = 2, MINUS_FLAG = 4, HASH_FLAG = 8}; - -enum format_spec_tag {fill_tag, align_tag, width_tag, type_tag}; - -// Format specifier. -template -class format_spec { - private: - T value_; - - public: - typedef T value_type; - - explicit format_spec(T value) : value_(value) {} - - T value() const { return value_; } -}; - -// template -// typedef format_spec fill_spec; -template -class fill_spec : public format_spec { - public: - explicit fill_spec(Char value) : format_spec(value) {} -}; - -typedef format_spec width_spec; -typedef format_spec type_spec; - -// An empty format specifier. -struct empty_spec {}; +enum { SIGN_FLAG = 1, PLUS_FLAG = 2, MINUS_FLAG = 4, HASH_FLAG = 8 }; // An alignment specifier. -struct align_spec : empty_spec { +struct align_spec { unsigned width_; // Fill is always wchar_t and cast to char if necessary to avoid having // two specialization of AlignSpec and its subclasses. wchar_t fill_; alignment align_; - FMT_CONSTEXPR align_spec( - unsigned width, wchar_t fill, alignment align = ALIGN_DEFAULT) - : width_(width), fill_(fill), align_(align) {} - + FMT_CONSTEXPR align_spec() : width_(0), fill_(' '), align_(ALIGN_DEFAULT) {} FMT_CONSTEXPR unsigned width() const { return width_; } FMT_CONSTEXPR wchar_t fill() const { return fill_; } FMT_CONSTEXPR alignment align() const { return align_; } +}; - int precision() const { return -1; } +struct core_format_specs { + int precision; + uint_least8_t flags; + char type; + + FMT_CONSTEXPR core_format_specs() : precision(-1), flags(0), type(0) {} + FMT_CONSTEXPR bool has(unsigned f) const { return (flags & f) != 0; } }; // Format specifiers. template -class basic_format_specs : public align_spec { - public: - unsigned flags_; - int precision_; - Char type_; - - FMT_CONSTEXPR basic_format_specs( - unsigned width = 0, char type = 0, wchar_t fill = ' ') - : align_spec(width, fill), flags_(0), precision_(-1), type_(type) {} - - FMT_CONSTEXPR bool flag(unsigned f) const { return (flags_ & f) != 0; } - FMT_CONSTEXPR int precision() const { return precision_; } - FMT_CONSTEXPR Char type() const { return type_; } +struct basic_format_specs : align_spec, core_format_specs { + FMT_CONSTEXPR basic_format_specs() {} }; typedef basic_format_specs format_specs; @@ -1251,13 +1124,20 @@ FMT_CONSTEXPR unsigned basic_parse_context::next_arg_id() { namespace internal { -template -struct format_string_traits< - S, typename std::enable_if::value>::type>: - format_string_traits_base {}; +// Formats value using Grisu2 algorithm: +// https://www.cs.tufts.edu/~nr/cs257/archive/florian-loitsch/printf.pdf +template +FMT_API typename std::enable_if::type + grisu2_format(Double value, buffer &buf, core_format_specs); +template +inline typename std::enable_if::type + grisu2_format(Double, buffer &, core_format_specs) { return false; } -template -FMT_CONSTEXPR void handle_int_type_spec(Char spec, Handler &&handler) { +template +void sprintf_format(Double, internal::buffer &, core_format_specs); + +template +FMT_CONSTEXPR void handle_int_type_spec(char spec, Handler &&handler) { switch (spec) { case 0: case 'd': handler.on_dec(); @@ -1279,8 +1159,8 @@ FMT_CONSTEXPR void handle_int_type_spec(Char spec, Handler &&handler) { } } -template -FMT_CONSTEXPR void handle_float_type_spec(Char spec, Handler &&handler) { +template +FMT_CONSTEXPR void handle_float_type_spec(char spec, Handler &&handler) { switch (spec) { case 0: case 'g': case 'G': handler.on_general(); @@ -1304,8 +1184,8 @@ template FMT_CONSTEXPR void handle_char_specs( const basic_format_specs *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->flag(~0u) != 0) + if (specs->type && specs->type != 'c') return handler.on_int(); + if (specs->align() == ALIGN_NUMERIC || specs->flags != 0) handler.on_error("invalid format specifier for char"); handler.on_char(); } @@ -1364,13 +1244,13 @@ class float_type_checker : private ErrorHandler { } }; -template +template class char_specs_checker : public ErrorHandler { private: - CharType type_; + char type_; public: - FMT_CONSTEXPR char_specs_checker(CharType type, ErrorHandler eh) + FMT_CONSTEXPR char_specs_checker(char type, ErrorHandler eh) : ErrorHandler(eh), type_(type) {} FMT_CONSTEXPR void on_int() { @@ -1394,8 +1274,7 @@ void arg_map::init(const basic_format_args &args) { if (map_) return; map_ = new entry[args.max_size()]; - bool use_values = args.type(max_packed_args - 1) == internal::none_type; - if (use_values) { + if (args.is_packed()) { for (unsigned i = 0;/*nothing*/; ++i) { internal::type arg_type = args.type(i); switch (arg_type) { @@ -1436,21 +1315,25 @@ class arg_formatter_base { struct char_writer { char_type value; + + size_t size() const { return 1; } + size_t width() const { return 1; } + template void operator()(It &&it) const { *it++ = value; } }; void write_char(char_type value) { if (specs_) - writer_.write_padded(1, *specs_, char_writer{value}); + writer_.write_padded(*specs_, char_writer{value}); else writer_.write(value); } void write_pointer(const void *p) { format_specs specs = specs_ ? *specs_ : format_specs(); - specs.flags_ = HASH_FLAG; - specs.type_ = 'x'; + specs.flags = HASH_FLAG; + specs.type = 'x'; writer_.write_int(reinterpret_cast(p), specs); } @@ -1461,7 +1344,7 @@ class arg_formatter_base { void write(bool value) { string_view sv(value ? "true" : "false"); - specs_ ? writer_.write_str(sv, *specs_) : writer_.write(sv); + specs_ ? writer_.write(sv, *specs_) : writer_.write(sv); } void write(const char_type *value) { @@ -1469,11 +1352,12 @@ class arg_formatter_base { FMT_THROW(format_error("string pointer is null")); auto length = std::char_traits::length(value); basic_string_view sv(value, length); - specs_ ? writer_.write_str(sv, *specs_) : writer_.write(sv); + specs_ ? writer_.write(sv, *specs_) : writer_.write(sv); } public: - arg_formatter_base(Range r, format_specs *s): writer_(r), specs_(s) {} + arg_formatter_base(Range r, format_specs *s, locale_ref loc) + : writer_(r, loc), specs_(s) {} iterator operator()(monostate) { FMT_ASSERT(false, "invalid argument type"); @@ -1481,12 +1365,13 @@ class arg_formatter_base { } template - typename std::enable_if::value, iterator>::type - operator()(T value) { + typename std::enable_if< + std::is_integral::value || std::is_same::value, + iterator>::type operator()(T value) { // MSVC2013 fails to compile separate overloads for bool and char_type so // use std::is_same instead. if (std::is_same::value) { - if (specs_ && specs_->type_) + if (specs_ && specs_->type) return (*this)(value ? 1 : 0); write(value != 0); } else if (std::is_same::value) { @@ -1535,15 +1420,15 @@ class arg_formatter_base { iterator operator()(const char_type *value) { if (!specs_) return write(value), out(); internal::handle_cstring_type_spec( - specs_->type_, cstring_spec_handler(*this, value)); + specs_->type, cstring_spec_handler(*this, value)); return out(); } iterator operator()(basic_string_view value) { if (specs_) { internal::check_string_type_spec( - specs_->type_, internal::error_handler()); - writer_.write_str(value, *specs_); + specs_->type, internal::error_handler()); + writer_.write(value, *specs_); } else { writer_.write(value); } @@ -1552,7 +1437,7 @@ class arg_formatter_base { iterator operator()(const void *value) { if (specs_) - check_pointer_type_spec(specs_->type_, internal::error_handler()); + check_pointer_type_spec(specs_->type, internal::error_handler()); write_pointer(value); return out(); } @@ -1563,40 +1448,16 @@ FMT_CONSTEXPR bool is_name_start(Char c) { return ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z') || '_' == c; } -// DEPRECATED: Parses the input as an unsigned integer. This function assumes -// that the first character is a digit and presence of a non-digit character at -// the end. -// it: an iterator pointing to the beginning of the input range. -template -FMT_CONSTEXPR unsigned parse_nonnegative_int(Iterator &it, ErrorHandler &&eh) { - assert('0' <= *it && *it <= '9'); - unsigned value = 0; - // Convert to unsigned to prevent a warning. - unsigned max_int = (std::numeric_limits::max)(); - unsigned big = max_int / 10; - do { - // Check for overflow. - if (value > big) { - value = max_int + 1; - break; - } - value = value * 10 + unsigned(*it - '0'); - // Workaround for MSVC "setup_exception stack overflow" error: - auto next = it; - ++next; - it = next; - } while ('0' <= *it && *it <= '9'); - if (value > max_int) - eh.on_error("number is too big"); - return value; -} - // 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 FMT_CONSTEXPR unsigned parse_nonnegative_int( const Char *&begin, const Char *end, ErrorHandler &&eh) { assert(begin != end && '0' <= *begin && *begin <= '9'); + if (*begin == '0') { + ++begin; + return 0; + } unsigned value = 0; // Convert to unsigned to prevent a warning. unsigned max_int = (std::numeric_limits::max)(); @@ -1607,7 +1468,8 @@ FMT_CONSTEXPR unsigned parse_nonnegative_int( value = max_int + 1; break; } - value = value * 10 + unsigned(*begin++ - '0'); + 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"); @@ -1695,14 +1557,14 @@ class specs_setter { explicit FMT_CONSTEXPR specs_setter(basic_format_specs &specs): specs_(specs) {} - FMT_CONSTEXPR specs_setter(const specs_setter &other) : specs_(other.specs_) {} + FMT_CONSTEXPR specs_setter(const specs_setter &other): specs_(other.specs_) {} FMT_CONSTEXPR void on_align(alignment align) { specs_.align_ = align; } FMT_CONSTEXPR void on_fill(Char fill) { specs_.fill_ = fill; } - FMT_CONSTEXPR void on_plus() { specs_.flags_ |= SIGN_FLAG | PLUS_FLAG; } - FMT_CONSTEXPR void on_minus() { specs_.flags_ |= MINUS_FLAG; } - FMT_CONSTEXPR void on_space() { specs_.flags_ |= SIGN_FLAG; } - FMT_CONSTEXPR void on_hash() { specs_.flags_ |= HASH_FLAG; } + FMT_CONSTEXPR void on_plus() { specs_.flags |= SIGN_FLAG | PLUS_FLAG; } + FMT_CONSTEXPR void on_minus() { specs_.flags |= MINUS_FLAG; } + FMT_CONSTEXPR void on_space() { specs_.flags |= SIGN_FLAG; } + FMT_CONSTEXPR void on_hash() { specs_.flags |= HASH_FLAG; } FMT_CONSTEXPR void on_zero() { specs_.align_ = ALIGN_NUMERIC; @@ -1711,11 +1573,13 @@ class specs_setter { FMT_CONSTEXPR void on_width(unsigned width) { specs_.width_ = width; } FMT_CONSTEXPR void on_precision(unsigned precision) { - specs_.precision_ = static_cast(precision); + specs_.precision = static_cast(precision); } FMT_CONSTEXPR void end_precision() {} - FMT_CONSTEXPR void on_type(Char type) { specs_.type_ = type; } + FMT_CONSTEXPR void on_type(Char type) { + specs_.type = static_cast(type); + } protected: basic_format_specs &specs_; @@ -1789,8 +1653,9 @@ template