Snap for 5933730 from 7502de07f20e3162e7e3cf3fa33a69a8fb937cc1 to simpleperf-release
Change-Id: I61c853ad6d048c8c926d7aaef544c56cf3d9510f
diff --git a/.clang-format b/.clang-format
new file mode 100644
index 0000000..df55d34
--- /dev/null
+++ b/.clang-format
@@ -0,0 +1,8 @@
+# Run manually to reformat a file:
+# clang-format -i --style=file <file>
+Language: Cpp
+BasedOnStyle: Google
+IndentPPDirectives: AfterHash
+IndentCaseLabels: false
+AlwaysBreakTemplateDeclarations: false
+DerivePointerAlignment: false
diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md
new file mode 100644
index 0000000..548e30f
--- /dev/null
+++ b/.github/pull_request_template.md
@@ -0,0 +1,6 @@
+<!-- Please read the contribution guidelines before submitting a pull request. -->
+<!-- By submitting this pull request, you agree that your contributions are licensed under the {fmt} license,
+ and agree to future changes to the licensing. -->
+<!-- If you're a first-time contributor, please acknowledge it by leaving the statement below. -->
+
+I agree that my contributions are licensed under the {fmt} license, and agree to future changes to the licensing.
diff --git a/.travis.yml b/.travis.yml
index da50ae6..27a83c1 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -7,7 +7,6 @@
git:
depth: 1
-
env:
global:
- secure: |-
@@ -39,6 +38,26 @@
- ubuntu-toolchain-r-test
packages:
- g++-6
+ # g++ 8 on Linux with C++17
+ - env: COMPILER=g++-8 BUILD=Debug STANDARD=17
+ compiler: gcc
+ addons:
+ apt:
+ update: true
+ sources:
+ - ubuntu-toolchain-r-test
+ packages:
+ - g++-8
+ - env: COMPILER=g++-8 BUILD=Release STANDARD=17
+ compiler: gcc
+ addons:
+ apt:
+ update: true
+ sources:
+ - ubuntu-toolchain-r-test
+ packages:
+ - g++-8
+
# Apple clang on OS X with C++14
- env: BUILD=Debug STANDARD=14
compiler: clang
@@ -46,8 +65,8 @@
- env: BUILD=Release STANDARD=14
compiler: clang
os: osx
- # clang 6.0 on Linux with C++14
- - env: COMPILER=clang++-6.0 BUILD=Debug STANDARD=14
+ # clang 6.0 on Linux with C++14 (builds the fuzzers as well)
+ - env: COMPILER=clang++-6.0 BUILD=Debug STANDARD=14 ENABLE_FUZZING=1
compiler: clang
addons:
apt:
@@ -73,41 +92,33 @@
# g++ 4.8 on Linux with C++11
- env: COMPILER=g++-4.8 BUILD=Debug STANDARD=11
compiler: gcc
- # g++ 4.4 on Linux with C++11
- - env: COMPILER=g++-4.4 BUILD=Debug STANDARD=11
- compiler: gcc
- addons:
- apt:
- update: true
- packages:
- - g++-4.4
- sources:
- - ubuntu-toolchain-r-test
- # Android
- - language: android
+ - name: Android NDK (Gradle)
+ language: android
addons:
apt:
update: true
sources:
- ubuntu-toolchain-r-test
packages:
- - wget
- - unzip
+ - ninja-build
+ - curl
- tree
android:
components:
- tools
- platform-tools
- - android-21
- env:
- - ANDROID=true
+ - android-25 # 7.0
+ - android-27 # 8.1
+ - android-28 # 9.0
+ - build-tools-28.0.3
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 Gradle from https://sdkman.io/
+ - curl -s "https://get.sdkman.io" | bash > /dev/null
+ - source "$HOME/.sdkman/bin/sdkman-init.sh"
+ - sdk version
+ - sdk install gradle
+ - sdk use gradle
+ - gradle --version
install:
# Accept SDK Licenses + Install NDK
- yes | sdkmanager --update > /dev/null 2>&1
@@ -115,7 +126,8 @@
before_script:
- pushd ./support
script:
- - bash ../$GRADLE clean assemble
+ - gradle clean
+ - gradle assemble
after_success:
- popd;
- tree ./libs
diff --git a/CMakeLists.txt b/CMakeLists.txt
index ce9dbf9..6e08aa5 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -27,21 +27,23 @@
# Set the default CMAKE_BUILD_TYPE to Release.
# This should be done before the project command since the latter can set
# CMAKE_BUILD_TYPE itself (it does so for nmake).
-if (NOT CMAKE_BUILD_TYPE)
+if (MASTER_PROJECT AND NOT CMAKE_BUILD_TYPE)
join(doc "Choose the type of build, options are: None(CMAKE_CXX_FLAGS or "
"CMAKE_C_FLAGS used) Debug Release RelWithDebInfo MinSizeRel.")
set(CMAKE_BUILD_TYPE Release CACHE STRING ${doc})
endif ()
option(FMT_PEDANTIC "Enable extra warnings and expensive tests." OFF)
-option(FMT_WERROR "Halt the compilation with an error on compiler warnings." OFF)
+option(FMT_WERROR "Halt the compilation with an error on compiler warnings."
+ OFF)
# Options that control generation of various targets.
option(FMT_DOC "Generate the doc target." ${MASTER_PROJECT})
option(FMT_INSTALL "Generate the install target." ${MASTER_PROJECT})
option(FMT_TEST "Generate the test target." ${MASTER_PROJECT})
+option(FMT_FUZZ "Generate the fuzz target." OFF)
-project(FMT)
+project(FMT CXX)
# Get version from core.h
file(READ include/fmt/core.h core_h)
@@ -66,6 +68,8 @@
include(cxx14)
include(CheckCXXCompilerFlag)
+set(FMT_REQUIRED_FEATURES cxx_auto_type cxx_variadic_templates)
+
if (CMAKE_CXX_COMPILER_ID MATCHES "GNU")
set(PEDANTIC_COMPILE_FLAGS -pedantic-errors -Wall -Wextra -pedantic
-Wold-style-cast -Wundef
@@ -93,7 +97,8 @@
endif ()
if (CMAKE_CXX_COMPILER_ID MATCHES "Clang")
- set(PEDANTIC_COMPILE_FLAGS -Wall -Wextra -pedantic -Wconversion -Wno-sign-conversion)
+ 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}
@@ -123,11 +128,18 @@
${CMAKE_MAKE_PROGRAM} -p:FrameworkPathOverride=\"${netfxpath}\" %*")
endif ()
+set(strtod_l_headers stdlib.h)
+if (APPLE)
+ set(strtod_l_headers ${strtod_l_headers} xlocale.h)
+endif ()
+
include(CheckSymbolExists)
if (WIN32)
check_symbol_exists(open io.h HAVE_OPEN)
+ check_symbol_exists(_strtod_l "${strtod_l_headers}" HAVE_STRTOD_L)
else ()
check_symbol_exists(open fcntl.h HAVE_OPEN)
+ check_symbol_exists(strtod_l "${strtod_l_headers}" HAVE_STRTOD_L)
endif ()
function(add_headers VAR)
@@ -139,8 +151,9 @@
endfunction()
# Define the fmt library, its includes and the needed defines.
-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)
+add_headers(FMT_HEADERS chrono.h color.h compile.h core.h format.h format-inl.h
+ locale.h ostream.h printf.h ranges.h
+ safe-duration-cast.h)
set(FMT_SOURCES src/format.cc)
if (HAVE_OPEN)
add_headers(FMT_HEADERS posix.h)
@@ -150,6 +163,10 @@
add_library(fmt ${FMT_SOURCES} ${FMT_HEADERS} README.rst ChangeLog.rst)
add_library(fmt::fmt ALIAS fmt)
+if (HAVE_STRTOD_L)
+ target_compile_definitions(fmt PUBLIC FMT_LOCALE)
+endif ()
+
if (FMT_WERROR)
target_compile_options(fmt PRIVATE ${WERROR_FLAG})
endif ()
@@ -157,6 +174,8 @@
target_compile_options(fmt PRIVATE ${PEDANTIC_COMPILE_FLAGS})
endif ()
+target_compile_features(fmt INTERFACE ${FMT_REQUIRED_FEATURES})
+
target_include_directories(fmt PUBLIC
$<BUILD_INTERFACE:${PROJECT_SOURCE_DIR}/include>
$<INSTALL_INTERFACE:include>)
@@ -173,12 +192,17 @@
endif ()
target_compile_definitions(fmt PRIVATE FMT_EXPORT INTERFACE FMT_SHARED)
endif ()
+if (FMT_SAFE_DURATION_CAST)
+ target_compile_definitions(fmt PUBLIC FMT_SAFE_DURATION_CAST)
+endif()
add_library(fmt-header-only INTERFACE)
add_library(fmt::fmt-header-only ALIAS fmt-header-only)
target_compile_definitions(fmt-header-only INTERFACE FMT_HEADER_ONLY=1)
+target_compile_features(fmt-header-only INTERFACE ${FMT_REQUIRED_FEATURES})
+
target_include_directories(fmt-header-only INTERFACE
$<BUILD_INTERFACE:${PROJECT_SOURCE_DIR}/include>
$<INSTALL_INTERFACE:include>)
@@ -188,7 +212,7 @@
include(GNUInstallDirs)
include(CMakePackageConfigHelpers)
set(FMT_CMAKE_DIR ${CMAKE_INSTALL_LIBDIR}/cmake/fmt CACHE STRING
- "Installation directory for cmake files, relative to ${CMAKE_INSTALL_PREFIX}.")
+ "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)
@@ -205,8 +229,8 @@
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}.")
+ set(FMT_PKGCONFIG_DIR ${CMAKE_INSTALL_LIBDIR}/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(
@@ -237,7 +261,8 @@
install(TARGETS ${INSTALL_TARGETS} EXPORT ${targets_export_name}
DESTINATION ${FMT_LIB_DIR})
- install(FILES $<TARGET_PDB_FILE:${INSTALL_TARGETS}> DESTINATION ${FMT_LIB_DIR} OPTIONAL)
+ install(FILES $<TARGET_PDB_FILE:${INSTALL_TARGETS}>
+ DESTINATION ${FMT_LIB_DIR} OPTIONAL)
install(FILES ${FMT_HEADERS} DESTINATION ${FMT_INC_DIR})
install(FILES "${pkgconfig}" DESTINATION "${FMT_PKGCONFIG_DIR}")
endif ()
@@ -251,6 +276,11 @@
add_subdirectory(test)
endif ()
+# Control fuzzing independent of the unit tests.
+if (FMT_FUZZ)
+ add_subdirectory(test/fuzzing)
+endif ()
+
set(gitignore ${PROJECT_SOURCE_DIR}/.gitignore)
if (MASTER_PROJECT AND EXISTS ${gitignore})
# Get the list of ignored files from .gitignore.
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
new file mode 100644
index 0000000..3532bd1
--- /dev/null
+++ b/CONTRIBUTING.md
@@ -0,0 +1,17 @@
+Contributing to {fmt}
+=====================
+
+By submitting a pull request or a patch, you represent that you have the right
+to license your contribution to the {fmt} project owners and the community,
+agree that your contributions are licensed under the {fmt} license, and agree
+to future changes to the licensing.
+
+All C++ code must adhere to [Google C++ Style Guide](
+https://google.github.io/styleguide/cppguide.html) with the following
+exceptions:
+
+* Exceptions are permitted
+* snake_case should be used instead of UpperCamelCase for function and type
+ names
+
+Thanks for contributing!
diff --git a/CONTRIBUTING.rst b/CONTRIBUTING.rst
deleted file mode 100644
index 899b646..0000000
--- a/CONTRIBUTING.rst
+++ /dev/null
@@ -1,12 +0,0 @@
-Contributing to fmt
-===================
-
-All C++ code must adhere to `Google C++ Style Guide
-<https://google.github.io/styleguide/cppguide.html>`_ with the following
-exceptions:
-
-* Exceptions are permitted
-* snake_case should be used instead of UpperCamelCase for function and type
- names
-
-Thanks for contributing!
diff --git a/ChangeLog.rst b/ChangeLog.rst
index 72f09d7..33a4003 100644
--- a/ChangeLog.rst
+++ b/ChangeLog.rst
@@ -1,3 +1,399 @@
+6.0.0 - 2019-08-26
+------------------
+
+* Switched to the `MIT license
+ <https://github.com/fmtlib/fmt/blob/5a4b24613ba16cc689977c3b5bd8274a3ba1dd1f/LICENSE.rst>`_
+ with an optional exception that allows distributing binary code without
+ attribution.
+
+* Floating-point formatting is now locale-independent by default:
+
+ .. code:: c++
+
+ #include <locale>
+ #include <fmt/core.h>
+
+ int main() {
+ std::locale::global(std::locale("ru_RU.UTF-8"));
+ fmt::print("value = {}", 4.2);
+ }
+
+ prints "value = 4.2" regardless of the locale.
+
+ For locale-specific formatting use the ``n`` specifier:
+
+ .. code:: c++
+
+ std::locale::global(std::locale("ru_RU.UTF-8"));
+ fmt::print("value = {:n}", 4.2);
+
+ prints "value = 4,2".
+
+* Added an experimental Grisu floating-point formatting algorithm
+ implementation (disabled by default). To enable it compile with the
+ ``FMT_USE_GRISU`` macro defined to 1:
+
+ .. code:: c++
+
+ #define FMT_USE_GRISU 1
+ #include <fmt/format.h>
+
+ auto s = fmt::format("{}", 4.2); // formats 4.2 using Grisu
+
+ With Grisu enabled, {fmt} is 13x faster than ``std::ostringstream`` (libc++)
+ and 10x faster than ``sprintf`` on `dtoa-benchmark
+ <https://github.com/fmtlib/dtoa-benchmark>`_ (`full results
+ <https://fmt.dev/unknown_mac64_clang10.0.html>`_):
+
+ .. image:: https://user-images.githubusercontent.com/576385/
+ 54883977-9fe8c000-4e28-11e9-8bde-272d122e7c52.jpg
+
+* Separated formatting and parsing contexts for consistency with
+ `C++20 std::format <http://eel.is/c++draft/format>`_, removing the
+ undocumented ``basic_format_context::parse_context()`` function.
+
+* Added `oss-fuzz <https://github.com/google/oss-fuzz>`_ support
+ (`#1199 <https://github.com/fmtlib/fmt/pull/1199>`_).
+ Thanks `@pauldreik (Paul Dreik) <https://github.com/pauldreik>`_.
+
+* ``formatter`` specializations now always take precedence over ``operator<<``
+ (`#952 <https://github.com/fmtlib/fmt/issues/952>`_):
+
+ .. code:: c++
+
+ #include <iostream>
+ #include <fmt/ostream.h>
+
+ struct S {};
+
+ std::ostream& operator<<(std::ostream& os, S) {
+ return os << 1;
+ }
+
+ template <>
+ struct fmt::formatter<S> : fmt::formatter<int> {
+ auto format(S, format_context& ctx) {
+ return formatter<int>::format(2, ctx);
+ }
+ };
+
+ int main() {
+ std::cout << S() << "\n"; // prints 1 using operator<<
+ fmt::print("{}\n", S()); // prints 2 using formatter
+ }
+
+* Introduced the experimental ``fmt::compile`` function that does format string
+ compilation (`#618 <https://github.com/fmtlib/fmt/issues/618>`_,
+ `#1169 <https://github.com/fmtlib/fmt/issues/1169>`_,
+ `#1171 <https://github.com/fmtlib/fmt/pull/1171>`_):
+
+ .. code:: c++
+
+ #include <fmt/compile.h>
+
+ auto f = fmt::compile<int>("{}");
+ std::string s = fmt::format(f, 42); // can be called multiple times to format
+ // different values
+ // s == "42"
+
+ It moves the cost of parsing a format string outside of the format function
+ which can be beneficial when identically formatting many objects of the same
+ types. Thanks `@stryku (Mateusz Janek) <https://github.com/stryku>`_.
+
+* Added the ``%`` format specifier that formats floating-point values as
+ percentages (`#1060 <https://github.com/fmtlib/fmt/pull/1060>`_,
+ `#1069 <https://github.com/fmtlib/fmt/pull/1069>`_,
+ `#1071 <https://github.com/fmtlib/fmt/pull/1071>`_):
+
+ .. code:: c++
+
+ auto s = fmt::format("{:.1%}", 0.42); // s == "42.0%"
+
+ Thanks `@gawain-bolton (Gawain Bolton) <https://github.com/gawain-bolton>`_.
+
+* Implemented precision for floating-point durations
+ (`#1004 <https://github.com/fmtlib/fmt/issues/1004>`_,
+ `#1012 <https://github.com/fmtlib/fmt/pull/1012>`_):
+
+ .. code:: c++
+
+ auto s = fmt::format("{:.1}", std::chrono::duration<double>(1.234));
+ // s == 1.2s
+
+ Thanks `@DanielaE (Daniela Engert) <https://github.com/DanielaE>`_.
+
+* Implemented ``chrono`` format specifiers ``%Q`` and ``%q`` that give the value
+ and the unit respectively (`#1019 <https://github.com/fmtlib/fmt/pull/1019>`_):
+
+ .. code:: c++
+
+ auto value = fmt::format("{:%Q}", 42s); // value == "42"
+ auto unit = fmt::format("{:%q}", 42s); // unit == "s"
+
+ Thanks `@DanielaE (Daniela Engert) <https://github.com/DanielaE>`_.
+
+* Fixed handling of dynamic width in chrono formatter:
+
+ .. code:: c++
+
+ auto s = fmt::format("{0:{1}%H:%M:%S}", std::chrono::seconds(12345), 12);
+ // ^ width argument index ^ width
+ // s == "03:25:45 "
+
+ Thanks Howard Hinnant.
+
+* Removed deprecated ``fmt/time.h``. Use ``fmt/chrono.h`` instead.
+
+* Added ``fmt::format`` and ``fmt::vformat`` overloads that take ``text_style``
+ (`#993 <https://github.com/fmtlib/fmt/issues/993>`_,
+ `#994 <https://github.com/fmtlib/fmt/pull/994>`_):
+
+ .. code:: c++
+
+ #include <fmt/color.h>
+
+ std::string message = fmt::format(fmt::emphasis::bold | fg(fmt::color::red),
+ "The answer is {}.", 42);
+
+ Thanks `@Naios (Denis Blank) <https://github.com/Naios>`_.
+
+* Removed the deprecated color API (``print_colored``). Use the new API, namely
+ ``print`` overloads that take ``text_style`` instead.
+
+* Made ``std::unique_ptr`` and ``std::shared_ptr`` formattable as pointers via
+ ``fmt::ptr`` (`#1121 <https://github.com/fmtlib/fmt/pull/1121>`_):
+
+ .. code:: c++
+
+ std::unique_ptr<int> p = ...;
+ fmt::print("{}", fmt::ptr(p)); // prints p as a pointer
+
+ Thanks `@sighingnow (Tao He) <https://github.com/sighingnow>`_.
+
+* Made ``print`` and ``vprint`` report I/O errors
+ (`#1098 <https://github.com/fmtlib/fmt/issues/1098>`_,
+ `#1099 <https://github.com/fmtlib/fmt/pull/1099>`_).
+ Thanks `@BillyDonahue (Billy Donahue) <https://github.com/BillyDonahue>`_.
+
+* Marked deprecated APIs with the ``[[deprecated]]`` attribute and removed
+ internal uses of deprecated APIs
+ (`#1022 <https://github.com/fmtlib/fmt/pull/1022>`_).
+ Thanks `@eliaskosunen (Elias Kosunen) <https://github.com/eliaskosunen>`_.
+
+* Modernized the codebase using more C++11 features and removing workarounds.
+ Most importantly, ``buffer_context`` is now an alias template, so
+ use ``buffer_context<T>`` instead of ``buffer_context<T>::type``.
+
+* ``formatter`` specializations now always take precedence over implicit
+ conversions to ``int`` and the undocumented ``convert_to_int`` trait
+ is now deprecated.
+
+* Moved the undocumented ``basic_writer``, ``writer``, and ``wwriter`` types
+ to the ``internal`` namespace.
+
+* Removed deprecated ``basic_format_context::begin()``. Use ``out()`` instead.
+
+* Disallowed passing the result of ``join`` as an lvalue to prevent misuse.
+
+* Refactored the undocumented structs that represent parsed format specifiers
+ to simplify the API and allow multibyte fill.
+
+* Moved SFINAE to template parameters to reduce symbol sizes.
+
+* Switched to ``fputws`` for writing wide strings so that it's no longer
+ required to call ``_setmode`` on Windows
+ (`#1229 <https://github.com/fmtlib/fmt/issues/1229>`_,
+ `#1243 <https://github.com/fmtlib/fmt/pull/1243>`_).
+ Thanks `@jackoalan (Jack Andersen) <https://github.com/jackoalan>`_.
+
+* Improved literal-based API
+ (`#1254 <https://github.com/fmtlib/fmt/pull/1254>`_).
+ Thanks `@sylveon (Charles Milette) <https://github.com/sylveon>`_.
+
+* Added support for exotic platforms without ``uintptr_t`` such as IBM i
+ (AS/400) which has 128-bit pointers and only 64-bit integers
+ (`#1059 <https://github.com/fmtlib/fmt/issues/1059>`_).
+
+* Added `Sublime Text syntax highlighting config
+ <https://github.com/fmtlib/fmt/blob/master/support/C%2B%2B.sublime-syntax>`_
+ (`#1037 <https://github.com/fmtlib/fmt/issues/1037>`_).
+ Thanks `@Kronuz (Germán Méndez Bravo) <https://github.com/Kronuz>`_.
+
+* Added the ``FMT_ENFORCE_COMPILE_STRING`` macro to enforce the use of
+ compile-time format strings
+ (`#1231 <https://github.com/fmtlib/fmt/pull/1231>`_).
+ Thanks `@jackoalan (Jack Andersen) <https://github.com/jackoalan>`_.
+
+* Stopped setting ``CMAKE_BUILD_TYPE`` if {fmt} is a subproject
+ (`#1081 <https://github.com/fmtlib/fmt/issues/1081>`_).
+
+* Various build improvements
+ (`#1039 <https://github.com/fmtlib/fmt/pull/1039>`_,
+ `#1078 <https://github.com/fmtlib/fmt/pull/1078>`_,
+ `#1091 <https://github.com/fmtlib/fmt/pull/1091>`_,
+ `#1103 <https://github.com/fmtlib/fmt/pull/1103>`_,
+ `#1177 <https://github.com/fmtlib/fmt/pull/1177>`_).
+ Thanks `@luncliff (Park DongHa) <https://github.com/luncliff>`_,
+ `@jasonszang (Jason Shuo Zang) <https://github.com/jasonszang>`_,
+ `@olafhering (Olaf Hering) <https://github.com/olafhering>`_,
+ `@Lecetem <https://github.com/Lectem>`_,
+ `@pauldreik (Paul Dreik) <https://github.com/pauldreik>`_.
+
+* Improved documentation
+ (`#1049 <https://github.com/fmtlib/fmt/issues/1049>`_,
+ `#1051 <https://github.com/fmtlib/fmt/pull/1051>`_,
+ `#1083 <https://github.com/fmtlib/fmt/pull/1083>`_,
+ `#1113 <https://github.com/fmtlib/fmt/pull/1113>`_,
+ `#1114 <https://github.com/fmtlib/fmt/pull/1114>`_,
+ `#1146 <https://github.com/fmtlib/fmt/issues/1146>`_,
+ `#1180 <https://github.com/fmtlib/fmt/issues/1180>`_,
+ `#1250 <https://github.com/fmtlib/fmt/pull/1250>`_,
+ `#1252 <https://github.com/fmtlib/fmt/pull/1252>`_,
+ `#1265 <https://github.com/fmtlib/fmt/pull/1265>`_).
+ Thanks `@mikelui (Michael Lui) <https://github.com/mikelui>`_,
+ `@foonathan (Jonathan Müller) <https://github.com/foonathan>`_,
+ `@BillyDonahue (Billy Donahue) <https://github.com/BillyDonahue>`_,
+ `@jwakely (Jonathan Wakely) <https://github.com/jwakely>`_,
+ `@kaisbe (Kais Ben Salah) <https://github.com/kaisbe>`_,
+ `@sdebionne (Samuel Debionne) <https://github.com/sdebionne>`_.
+
+* Fixed ambiguous formatter specialization in ``fmt/ranges.h``
+ (`#1123 <https://github.com/fmtlib/fmt/issues/1123>`_).
+
+* Fixed formatting of a non-empty ``std::filesystem::path`` which is an
+ infinitely deep range of its components
+ (`#1268 <https://github.com/fmtlib/fmt/issues/1268>`_).
+
+* Fixed handling of general output iterators when formatting characters
+ (`#1056 <https://github.com/fmtlib/fmt/issues/1056>`_,
+ `#1058 <https://github.com/fmtlib/fmt/pull/1058>`_).
+ Thanks `@abolz (Alexander Bolz) <https://github.com/abolz>`_.
+
+* Fixed handling of output iterators in ``formatter`` specialization for
+ ranges (`#1064 <https://github.com/fmtlib/fmt/issues/1064>`_).
+
+* Fixed handling of exotic character types
+ (`#1188 <https://github.com/fmtlib/fmt/issues/1188>`_).
+
+* Made chrono formatting work with exceptions disabled
+ (`#1062 <https://github.com/fmtlib/fmt/issues/1062>`_).
+
+* Fixed DLL visibility issues
+ (`#1134 <https://github.com/fmtlib/fmt/pull/1134>`_,
+ `#1147 <https://github.com/fmtlib/fmt/pull/1147>`_).
+ Thanks `@denchat <https://github.com/denchat>`_.
+
+* Disabled the use of UDL template extension on GCC 9
+ (`#1148 <https://github.com/fmtlib/fmt/issues/1148>`_).
+
+* Removed misplaced ``format`` compile-time checks from ``printf``
+ (`#1173 <https://github.com/fmtlib/fmt/issues/1173>`_).
+
+* Fixed issues in the experimental floating-point formatter
+ (`#1072 <https://github.com/fmtlib/fmt/issues/1072>`_,
+ `#1129 <https://github.com/fmtlib/fmt/issues/1129>`_,
+ `#1153 <https://github.com/fmtlib/fmt/issues/1153>`_,
+ `#1155 <https://github.com/fmtlib/fmt/pull/1155>`_,
+ `#1210 <https://github.com/fmtlib/fmt/issues/1210>`_,
+ `#1222 <https://github.com/fmtlib/fmt/issues/1222>`_).
+ Thanks `@alabuzhev (Alex Alabuzhev) <https://github.com/alabuzhev>`_.
+
+* Fixed bugs discovered by fuzzing or during fuzzing integation
+ (`#1124 <https://github.com/fmtlib/fmt/issues/1124>`_,
+ `#1127 <https://github.com/fmtlib/fmt/issues/1127>`_,
+ `#1132 <https://github.com/fmtlib/fmt/issues/1132>`_,
+ `#1135 <https://github.com/fmtlib/fmt/pull/1135>`_,
+ `#1136 <https://github.com/fmtlib/fmt/issues/1136>`_,
+ `#1141 <https://github.com/fmtlib/fmt/issues/1141>`_,
+ `#1142 <https://github.com/fmtlib/fmt/issues/1142>`_,
+ `#1178 <https://github.com/fmtlib/fmt/issues/1178>`_,
+ `#1179 <https://github.com/fmtlib/fmt/issues/1179>`_,
+ `#1194 <https://github.com/fmtlib/fmt/issues/1194>`_).
+ Thanks `@pauldreik (Paul Dreik) <https://github.com/pauldreik>`_.
+
+* Fixed building tests on FreeBSD and Hurd
+ (`#1043 <https://github.com/fmtlib/fmt/issues/1043>`_).
+ Thanks `@jackyf (Eugene V. Lyubimkin) <https://github.com/jackyf>`_.
+
+* Fixed various warnings and compilation issues
+ (`#998 <https://github.com/fmtlib/fmt/pull/998>`_,
+ `#1006 <https://github.com/fmtlib/fmt/pull/1006>`_,
+ `#1008 <https://github.com/fmtlib/fmt/issues/1008>`_,
+ `#1011 <https://github.com/fmtlib/fmt/issues/1011>`_,
+ `#1025 <https://github.com/fmtlib/fmt/issues/1025>`_,
+ `#1027 <https://github.com/fmtlib/fmt/pull/1027>`_,
+ `#1028 <https://github.com/fmtlib/fmt/pull/1028>`_,
+ `#1029 <https://github.com/fmtlib/fmt/pull/1029>`_,
+ `#1030 <https://github.com/fmtlib/fmt/pull/1030>`_,
+ `#1031 <https://github.com/fmtlib/fmt/pull/1031>`_,
+ `#1054 <https://github.com/fmtlib/fmt/pull/1054>`_,
+ `#1063 <https://github.com/fmtlib/fmt/issues/1063>`_,
+ `#1068 <https://github.com/fmtlib/fmt/pull/1068>`_,
+ `#1074 <https://github.com/fmtlib/fmt/pull/1074>`_,
+ `#1075 <https://github.com/fmtlib/fmt/pull/1075>`_,
+ `#1079 <https://github.com/fmtlib/fmt/pull/1079>`_,
+ `#1086 <https://github.com/fmtlib/fmt/pull/1086>`_,
+ `#1088 <https://github.com/fmtlib/fmt/issues/1088>`_,
+ `#1089 <https://github.com/fmtlib/fmt/pull/1089>`_,
+ `#1094 <https://github.com/fmtlib/fmt/pull/1094>`_,
+ `#1101 <https://github.com/fmtlib/fmt/issues/1101>`_,
+ `#1102 <https://github.com/fmtlib/fmt/pull/1102>`_,
+ `#1105 <https://github.com/fmtlib/fmt/issues/1105>`_,
+ `#1107 <https://github.com/fmtlib/fmt/pull/1107>`_,
+ `#1115 <https://github.com/fmtlib/fmt/issues/1115>`_,
+ `#1117 <https://github.com/fmtlib/fmt/issues/1117>`_,
+ `#1118 <https://github.com/fmtlib/fmt/issues/1118>`_,
+ `#1120 <https://github.com/fmtlib/fmt/issues/1120>`_,
+ `#1123 <https://github.com/fmtlib/fmt/issues/1123>`_,
+ `#1139 <https://github.com/fmtlib/fmt/pull/1139>`_,
+ `#1140 <https://github.com/fmtlib/fmt/issues/1140>`_,
+ `#1143 <https://github.com/fmtlib/fmt/issues/1143>`_,
+ `#1144 <https://github.com/fmtlib/fmt/pull/1144>`_,
+ `#1150 <https://github.com/fmtlib/fmt/pull/1150>`_,
+ `#1151 <https://github.com/fmtlib/fmt/pull/1151>`_,
+ `#1152 <https://github.com/fmtlib/fmt/issues/1152>`_,
+ `#1154 <https://github.com/fmtlib/fmt/issues/1154>`_,
+ `#1156 <https://github.com/fmtlib/fmt/issues/1156>`_,
+ `#1159 <https://github.com/fmtlib/fmt/pull/1159>`_,
+ `#1175 <https://github.com/fmtlib/fmt/issues/1175>`_,
+ `#1181 <https://github.com/fmtlib/fmt/issues/1181>`_,
+ `#1186 <https://github.com/fmtlib/fmt/issues/1186>`_,
+ `#1187 <https://github.com/fmtlib/fmt/pull/1187>`_,
+ `#1191 <https://github.com/fmtlib/fmt/pull/1191>`_,
+ `#1197 <https://github.com/fmtlib/fmt/issues/1197>`_,
+ `#1200 <https://github.com/fmtlib/fmt/issues/1200>`_,
+ `#1203 <https://github.com/fmtlib/fmt/issues/1203>`_,
+ `#1205 <https://github.com/fmtlib/fmt/issues/1205>`_,
+ `#1206 <https://github.com/fmtlib/fmt/pull/1206>`_,
+ `#1213 <https://github.com/fmtlib/fmt/issues/1213>`_,
+ `#1214 <https://github.com/fmtlib/fmt/issues/1214>`_,
+ `#1217 <https://github.com/fmtlib/fmt/pull/1217>`_,
+ `#1228 <https://github.com/fmtlib/fmt/issues/1228>`_,
+ `#1230 <https://github.com/fmtlib/fmt/pull/1230>`_,
+ `#1232 <https://github.com/fmtlib/fmt/issues/1232>`_,
+ `#1235 <https://github.com/fmtlib/fmt/pull/1235>`_,
+ `#1236 <https://github.com/fmtlib/fmt/pull/1236>`_,
+ `#1240 <https://github.com/fmtlib/fmt/issues/1240>`_).
+ Thanks `@DanielaE (Daniela Engert) <https://github.com/DanielaE>`_,
+ `@mwinterb <https://github.com/mwinterb>`_,
+ `@eliaskosunen (Elias Kosunen) <https://github.com/eliaskosunen>`_,
+ `@morinmorin <https://github.com/morinmorin>`_,
+ `@ricco19 (Brian Ricciardelli) <https://github.com/ricco19>`_,
+ `@waywardmonkeys (Bruce Mitchener) <https://github.com/waywardmonkeys>`_,
+ `@chronoxor (Ivan Shynkarenka) <https://github.com/chronoxor>`_,
+ `@remyabel <https://github.com/remyabel>`_,
+ `@pauldreik (Paul Dreik) <https://github.com/pauldreik>`_,
+ `@gsjaardema (Greg Sjaardema) <https://github.com/gsjaardema>`_,
+ `@rcane (Ronny Krüger) <https://github.com/rcane>`_,
+ `@mocabe <https://github.com/mocabe>`_,
+ `@denchat <https://github.com/denchat>`_,
+ `@cjdb (Christopher Di Bella) <https://github.com/cjdb>`_,
+ `@HazardyKnusperkeks (Björn Schäpers) <https://github.com/HazardyKnusperkeks>`_,
+ `@vedranmiletic (Vedran Miletić) <https://github.com/vedranmiletic>`_,
+ `@jackoalan (Jack Andersen) <https://github.com/jackoalan>`_,
+ `@DaanDeMeyer (Daan De Meyer) <https://github.com/DaanDeMeyer>`_,
+ `@starkmapper (Mark Stapper) <https://github.com/starkmapper>`_.
+
5.3.0 - 2018-12-28
------------------
@@ -142,7 +538,7 @@
// s == "1~234~567"
* Constrained formatting functions on proper iterator types
- (`#921 <https://github.com/fmtlib/fmt/pull/921>`_):
+ (`#921 <https://github.com/fmtlib/fmt/pull/921>`_).
Thanks `@DanielaE (Daniela Engert) <https://github.com/DanielaE>`_.
* Added ``make_printf_args`` and ``make_wprintf_args`` functions
@@ -386,7 +782,7 @@
``color`` enum) is now deprecated.
(`#762 <https://github.com/fmtlib/fmt/issues/762>`_
`#767 <https://github.com/fmtlib/fmt/pull/767>`_).
- thanks `@remotion (remo) <https://github.com/remotion>`_.
+ thanks `@Remotion (Remo) <https://github.com/Remotion>`_.
* Added quotes to strings in ranges and tuples
(`#766 <https://github.com/fmtlib/fmt/pull/766>`_).
@@ -467,7 +863,7 @@
* Implemented ``constexpr`` parsing of format strings and `compile-time format
string checks
- <http://fmtlib.net/dev/api.html#compile-time-format-string-checks>`_. For
+ <https://fmt.dev/dev/api.html#compile-time-format-string-checks>`_. For
example
.. code:: c++
@@ -528,7 +924,7 @@
throw format_error("invalid specifier");
* Added `iterator support
- <http://fmtlib.net/dev/api.html#output-iterator-support>`_:
+ <https://fmt.dev/dev/api.html#output-iterator-support>`_:
.. code:: c++
@@ -539,7 +935,7 @@
fmt::format_to(std::back_inserter(out), "{}", 42);
* Added the `format_to_n
- <http://fmtlib.net/dev/api.html#_CPPv2N3fmt11format_to_nE8OutputItNSt6size_tE11string_viewDpRK4Args>`_
+ <https://fmt.dev/dev/api.html#_CPPv2N3fmt11format_to_nE8OutputItNSt6size_tE11string_viewDpRK4Args>`_
function that restricts the output to the specified number of characters
(`#298 <https://github.com/fmtlib/fmt/issues/298>`_):
@@ -550,7 +946,7 @@
// out == "1234" (without terminating '\0')
* Added the `formatted_size
- <http://fmtlib.net/dev/api.html#_CPPv2N3fmt14formatted_sizeE11string_viewDpRK4Args>`_
+ <https://fmt.dev/dev/api.html#_CPPv2N3fmt14formatted_sizeE11string_viewDpRK4Args>`_
function for computing the output size:
.. code:: c++
@@ -560,7 +956,7 @@
auto size = fmt::formatted_size("{}", 12345); // size == 5
* Improved compile times by reducing dependencies on standard headers and
- providing a lightweight `core API <http://fmtlib.net/dev/api.html#core-api>`_:
+ providing a lightweight `core API <https://fmt.dev/dev/api.html#core-api>`_:
.. code:: c++
@@ -572,7 +968,7 @@
<https://github.com/fmtlib/fmt#compile-time-and-code-bloat>`_.
* Added the `make_format_args
- <http://fmtlib.net/dev/api.html#_CPPv2N3fmt16make_format_argsEDpRK4Args>`_
+ <https://fmt.dev/dev/api.html#_CPPv2N3fmt16make_format_argsEDpRK4Args>`_
function for capturing formatting arguments:
.. code:: c++
@@ -654,7 +1050,7 @@
fmt::format("{} {two}", 1, fmt::arg("two", 2));
* Removed the write API in favor of the `format API
- <http://fmtlib.net/dev/api.html#format-api>`_ with compile-time handling of
+ <https://fmt.dev/dev/api.html#format-api>`_ with compile-time handling of
format strings.
* Disallowed formatting of multibyte strings into a wide character target
@@ -1057,7 +1453,7 @@
3.0.1 - 2016-11-01
------------------
-* Fixed handling of thousands seperator
+* Fixed handling of thousands separator
(`#353 <https://github.com/fmtlib/fmt/issues/353>`_).
* Fixed handling of ``unsigned char`` strings
@@ -1115,10 +1511,10 @@
Including ``format.h`` from the ``cppformat`` directory is deprecated
but works via a proxy header which will be removed in the next major version.
- The documentation is now available at http://fmtlib.net.
+ The documentation is now available at https://fmt.dev.
* Added support for `strftime <http://en.cppreference.com/w/cpp/chrono/c/strftime>`_-like
- `date and time formatting <http://fmtlib.net/3.0.0/api.html#date-and-time-formatting>`_
+ `date and time formatting <https://fmt.dev/3.0.0/api.html#date-and-time-formatting>`_
(`#283 <https://github.com/fmtlib/fmt/issues/283>`_):
.. code:: c++
@@ -1150,7 +1546,7 @@
// s == "The date is 2012-12-9"
* Added support for `custom argument formatters
- <http://fmtlib.net/3.0.0/api.html#argument-formatters>`_
+ <https://fmt.dev/3.0.0/api.html#argument-formatters>`_
(`#235 <https://github.com/fmtlib/fmt/issues/235>`_).
* Added support for locale-specific integer formatting with the ``n`` specifier
@@ -1530,7 +1926,7 @@
* Added `Building the documentation
- <http://fmtlib.net/2.0.0/usage.html#building-the-documentation>`_
+ <https://fmt.dev/2.0.0/usage.html#building-the-documentation>`_
section to the documentation.
* Documentation build script is now compatible with Python 3 and newer pip versions.
diff --git a/LICENSE.rst b/LICENSE.rst
index eb6be65..f0ec3db 100644
--- a/LICENSE.rst
+++ b/LICENSE.rst
@@ -1,23 +1,27 @@
-Copyright (c) 2012 - 2016, Victor Zverovich
+Copyright (c) 2012 - present, Victor Zverovich
-All rights reserved.
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of this software and associated documentation files (the
+"Software"), to deal in the Software without restriction, including
+without limitation the rights to use, copy, modify, merge, publish,
+distribute, sublicense, and/or sell copies of the Software, and to
+permit persons to whom the Software is furnished to do so, subject to
+the following conditions:
-Redistribution and use in source and binary forms, with or without
-modification, are permitted provided that the following conditions are met:
+The above copyright notice and this permission notice shall be
+included in all copies or substantial portions of the Software.
-1. Redistributions of source code must retain the above copyright notice, this
- list of conditions and the following disclaimer.
-2. Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following disclaimer in the documentation
- and/or other materials provided with the distribution.
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
-ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
-WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
-DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
-ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
-(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
-LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
-ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
-SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+--- Optional exception to the license ---
+
+As an exception, if, as a result of your compiling your source code, portions
+of this Software are embedded into a machine-executable object form of such
+source code, you may redistribute such embedded portions in such object form
+without including the above copyright and permission notices.
diff --git a/METADATA b/METADATA
index 81de786..157fb95 100644
--- a/METADATA
+++ b/METADATA
@@ -1,8 +1,5 @@
name: "fmtlib"
-description:
- "{fmt} is an open-source formatting library for C++. It can be used as a "
- "safe and fast alternative to (s)printf and iostreams."
-
+description: "{fmt} is an open-source formatting library for C++. It can be used as a safe and fast alternative to (s)printf and iostreams."
third_party {
url {
type: HOMEPAGE
@@ -12,6 +9,10 @@
type: GIT
value: "https://github.com/fmtlib/fmt.git"
}
- version: "5.3.0"
- last_upgrade_date { year: 2019 month: 6 day: 11 }
+ version: "6.0.0"
+ last_upgrade_date {
+ year: 2019
+ month: 8
+ day: 26
+ }
}
diff --git a/README.rst b/README.rst
index 3e43b30..f08b22f 100644
--- a/README.rst
+++ b/README.rst
@@ -6,37 +6,34 @@
.. image:: https://ci.appveyor.com/api/projects/status/ehjkiefde6gucy1v
:target: https://ci.appveyor.com/project/vitaut/fmt
-
-.. image:: https://badges.gitter.im/Join%20Chat.svg
- :alt: Join the chat at https://gitter.im/fmtlib/fmt
- :target: https://gitter.im/fmtlib/fmt
+
+.. image:: https://img.shields.io/badge/stackoverflow-fmt-blue.svg
+ :alt: Ask questions at StackOverflow with the tag fmt
+ :target: http://stackoverflow.com/questions/tagged/fmt
**{fmt}** is an open-source formatting library for C++.
-It can be used as a safe and fast alternative to (s)printf and IOStreams.
+It can be used as a safe and fast alternative to (s)printf and iostreams.
-`Documentation <http://fmtlib.net/latest/>`__
+`Documentation <https://fmt.dev/latest/>`__
-This is a development branch that implements the C++ standards proposal `P0645
-Text Formatting <http://fmtlib.net/Text%20Formatting.html>`__.
-Released versions are available from the `Releases page
-<https://github.com/fmtlib/fmt/releases>`__.
+Q&A: ask questions on `StackOverflow with the tag fmt <http://stackoverflow.com/questions/tagged/fmt>`_.
Features
--------
-* Replacement-based `format API <http://fmtlib.net/dev/api.html>`_ with
+* Replacement-based `format API <https://fmt.dev/dev/api.html>`_ with
positional arguments for localization.
-* `Format string syntax <http://fmtlib.net/dev/syntax.html>`_ similar to the one
+* `Format string syntax <https://fmt.dev/dev/syntax.html>`_ similar to the one
of `str.format <https://docs.python.org/2/library/stdtypes.html#str.format>`_
in Python.
* Safe `printf implementation
- <http://fmtlib.net/latest/api.html#printf-formatting>`_ including
+ <https://fmt.dev/latest/api.html#printf-formatting>`_ including
the POSIX extension for positional arguments.
+* Implementation of `C++20 std::format <https://fmt.dev/Text%20Formatting.html>`__.
* Support for user-defined types.
-* High speed: performance of the format API is close to that of glibc's `printf
- <http://en.cppreference.com/w/cpp/io/c/fprintf>`_ and better than the
- performance of IOStreams. See `Speed tests`_ and
- `Fast integer to string conversion in C++
+* High performance: faster than common standard library implementations of
+ `printf <http://en.cppreference.com/w/cpp/io/c/fprintf>`_ and
+ iostreams. See `Speed tests`_ and `Fast integer to string conversion in C++
<http://zverovich.net/2013/09/07/integer-to-string-conversion-in-cplusplus.html>`_.
* Small code size both in terms of source code (the minimum configuration
consists of just three header files, ``core.h``, ``format.h`` and
@@ -49,33 +46,33 @@
* Ease of use: small self-contained code base, no external dependencies,
permissive BSD `license
<https://github.com/fmtlib/fmt/blob/master/LICENSE.rst>`_
-* `Portability <http://fmtlib.net/latest/index.html#portability>`_ with
+* `Portability <https://fmt.dev/latest/index.html#portability>`_ with
consistent output across platforms and support for older compilers.
* Clean warning-free codebase even on high warning levels
(``-Wall -Wextra -pedantic``).
* Support for wide strings.
* Optional header-only configuration enabled with the ``FMT_HEADER_ONLY`` macro.
-See the `documentation <http://fmtlib.net/latest/>`_ for more details.
+See the `documentation <https://fmt.dev/latest/>`_ for more details.
Examples
--------
-This prints ``Hello, world!`` to stdout:
+Print ``Hello, world!`` to ``stdout``:
.. code:: c++
- fmt::print("Hello, {}!", "world"); // uses Python-like format string syntax
- fmt::printf("Hello, %s!", "world"); // uses printf format string syntax
+ fmt::print("Hello, {}!", "world"); // Python-like format string syntax
+ fmt::printf("Hello, %s!", "world"); // printf format string syntax
-Arguments can be accessed by position and arguments' indices can be repeated:
+Format a string and use positional arguments:
.. code:: c++
- std::string s = fmt::format("{0}{1}{0}", "abra", "cad");
- // s == "abracadabra"
+ std::string s = fmt::format("I'd rather be {1} than {0}.", "right", "happy");
+ // s == "I'd rather be happy than right."
-Format strings can be checked at compile time:
+Check a format string at compile time:
.. code:: c++
@@ -98,7 +95,7 @@
context_.on_error("argument index out of range");
^
-{fmt} can be used as a safe portable replacement for ``itoa``
+Use {fmt} as a safe portable replacement for ``itoa``
(`godbolt <https://godbolt.org/g/NXmpU4>`_):
.. code:: c++
@@ -106,10 +103,10 @@
fmt::memory_buffer buf;
format_to(buf, "{}", 42); // replaces itoa(42, buffer, 10)
format_to(buf, "{:x}", 42); // replaces itoa(42, buffer, 16)
- // access the string using to_string(buf) or buf.data()
+ // access the string with to_string(buf) or buf.data()
-Formatting of user-defined types is supported via a simple
-`extension API <http://fmtlib.net/latest/api.html#formatting-user-defined-types>`_:
+Format objects of user-defined types via a simple `extension API
+<https://fmt.dev/latest/api.html#formatting-user-defined-types>`_:
.. code:: c++
@@ -133,9 +130,9 @@
std::string s = fmt::format("The date is {}", date{2012, 12, 9});
// s == "The date is 2012-12-9"
-You can create your own functions similar to `format
-<http://fmtlib.net/latest/api.html#format>`_ and
-`print <http://fmtlib.net/latest/api.html#print>`_
+Create your own functions similar to `format
+<https://fmt.dev/latest/api.html#format>`_ and
+`print <https://fmt.dev/latest/api.html#print>`_
which take arbitrary arguments (`godbolt <https://godbolt.org/g/MHjHVf>`_):
.. code:: c++
@@ -153,9 +150,118 @@
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
+improve compile times and reduce code size compared to a fully parameterized
version.
+Benchmarks
+----------
+
+Speed tests
+~~~~~~~~~~~
+
+================= ============= ===========
+Library Method Run Time, s
+================= ============= ===========
+libc printf 1.01
+libc++ std::ostream 3.04
+{fmt} 1632f72 fmt::print 0.86
+tinyformat 2.0.1 tfm::printf 3.23
+Boost Format 1.67 boost::format 7.98
+Folly Format folly::format 2.23
+================= ============= ===========
+
+{fmt} is the fastest of the benchmarked methods, ~17% faster than ``printf``.
+
+The above results were generated by building ``tinyformat_test.cpp`` on macOS
+10.14.3 with ``clang++ -O3 -DSPEED_TEST -DHAVE_FORMAT``, and taking the best of
+three runs. In the test, the format string ``"%0.10f:%04d:%+g:%s:%p:%c:%%\n"``
+or equivalent is filled 2,000,000 times with output sent to ``/dev/null``; for
+further details refer to the `source
+<https://github.com/fmtlib/format-benchmark/blob/master/tinyformat_test.cpp>`_.
+
+{fmt} is 10x faster than ``std::ostringstream`` and ``sprintf`` on floating-point
+formatting (`dtoa-benchmark <https://github.com/fmtlib/dtoa-benchmark>`_)
+and as fast as `double-conversion <https://github.com/google/double-conversion>`_:
+
+.. image:: https://user-images.githubusercontent.com/576385/54883977-9fe8c000-4e28-11e9-8bde-272d122e7c52.jpg
+ :target: https://fmt.dev/unknown_mac64_clang10.0.html
+
+Compile time and code bloat
+~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+The script `bloat-test.py
+<https://github.com/fmtlib/format-benchmark/blob/master/bloat-test.py>`_
+from `format-benchmark <https://github.com/fmtlib/format-benchmark>`_
+tests compile time and code bloat for nontrivial projects.
+It generates 100 translation units and uses ``printf()`` or its alternative
+five times in each to simulate a medium sized project. The resulting
+executable size and compile time (Apple LLVM version 8.1.0 (clang-802.0.42),
+macOS Sierra, best of three) is shown in the following tables.
+
+**Optimized build (-O3)**
+
+============= =============== ==================== ==================
+Method Compile Time, s Executable size, KiB Stripped size, KiB
+============= =============== ==================== ==================
+printf 2.6 29 26
+printf+string 16.4 29 26
+iostreams 31.1 59 55
+{fmt} 19.0 37 34
+tinyformat 44.0 103 97
+Boost Format 91.9 226 203
+Folly Format 115.7 101 88
+============= =============== ==================== ==================
+
+As you can see, {fmt} has 60% less overhead in terms of resulting binary code
+size compared to iostreams and comes pretty close to ``printf``. Boost Format
+and Folly Format have the largest overheads.
+
+``printf+string`` is the same as ``printf`` but with extra ``<string>``
+include to measure the overhead of the latter.
+
+**Non-optimized build**
+
+============= =============== ==================== ==================
+Method Compile Time, s Executable size, KiB Stripped size, KiB
+============= =============== ==================== ==================
+printf 2.2 33 30
+printf+string 16.0 33 30
+iostreams 28.3 56 52
+{fmt} 18.2 59 50
+tinyformat 32.6 88 82
+Boost Format 54.1 365 303
+Folly Format 79.9 445 430
+============= =============== ==================== ==================
+
+``libc``, ``lib(std)c++`` and ``libfmt`` are all linked as shared libraries to
+compare formatting function overhead only. Boost Format and tinyformat are
+header-only libraries so they don't provide any linkage options.
+
+Running the tests
+~~~~~~~~~~~~~~~~~
+
+Please refer to `Building the library`__ for the instructions on how to build
+the library and run the unit tests.
+
+__ https://fmt.dev/latest/usage.html#building-the-library
+
+Benchmarks reside in a separate repository,
+`format-benchmarks <https://github.com/fmtlib/format-benchmark>`_,
+so to run the benchmarks you first need to clone this repository and
+generate Makefiles with CMake::
+
+ $ git clone --recursive https://github.com/fmtlib/format-benchmark.git
+ $ cd format-benchmark
+ $ cmake .
+
+Then you can run the speed test::
+
+ $ make speed-test
+
+or the bloat test::
+
+ $ make bloat-test
+
Projects using this library
---------------------------
@@ -194,6 +300,8 @@
* `FiveM <https://fivem.net/>`_: a modification framework for GTA V
+* `MongoDB <https://mongodb.com/>`_: Distributed document database
+
* `MongoDB Smasher <https://github.com/duckie/mongo_smasher>`_: A small tool to
generate randomized datasets
@@ -247,28 +355,28 @@
So why yet another formatting library?
There are plenty of methods for doing this task, from standard ones like
-the printf family of function and IOStreams to Boost Format library and
-FastFormat. The reason for creating a new library is that every existing
+the printf family of function and iostreams to Boost Format and FastFormat
+libraries. The reason for creating a new library is that every existing
solution that I found either had serious issues or didn't provide
all the features I needed.
-Printf
+printf
~~~~~~
-The good thing about printf is that it is pretty fast and readily available
+The good thing about ``printf`` is that it is pretty fast and readily available
being a part of the C standard library. The main drawback is that it
-doesn't support user-defined types. Printf also has safety issues although
-they are mostly solved with `__attribute__ ((format (printf, ...))
+doesn't support user-defined types. ``printf`` also has safety issues although
+they are somewhat mitigated with `__attribute__ ((format (printf, ...))
<http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html>`_ in GCC.
There is a POSIX extension that adds positional arguments required for
`i18n <https://en.wikipedia.org/wiki/Internationalization_and_localization>`_
-to printf but it is not a part of C99 and may not be available on some
+to ``printf`` but it is not a part of C99 and may not be available on some
platforms.
-IOStreams
+iostreams
~~~~~~~~~
-The main issue with IOStreams is best illustrated with an example:
+The main issue with iostreams is best illustrated with an example:
.. code:: c++
@@ -280,21 +388,20 @@
printf("%.2f\n", 1.23456);
-Matthew Wilson, the author of FastFormat, referred to this situation with
-IOStreams as "chevron hell". IOStreams doesn't support positional arguments
-by design.
+Matthew Wilson, the author of FastFormat, called this "chevron hell". iostreams
+don't support positional arguments by design.
-The good part is that IOStreams supports user-defined types and is safe
-although error reporting is awkward.
+The good part is that iostreams support user-defined types and are safe although
+error handling is awkward.
-Boost Format library
-~~~~~~~~~~~~~~~~~~~~
+Boost Format
+~~~~~~~~~~~~
-This is a very powerful library which supports both printf-like format
-strings and positional arguments. Its main drawback is performance.
-According to various benchmarks it is much slower than other methods
-considered here. Boost Format also has excessive build times and severe
-code bloat issues (see `Benchmarks`_).
+This is a very powerful library which supports both ``printf``-like format
+strings and positional arguments. Its main drawback is performance. According to
+various benchmarks it is much slower than other methods considered here. Boost
+Format also has excessive build times and severe code bloat issues (see
+`Benchmarks`_).
FastFormat
~~~~~~~~~~
@@ -315,139 +422,27 @@
Loki SafeFormat
~~~~~~~~~~~~~~~
-SafeFormat is a formatting library which uses printf-like format strings
-and is type safe. It doesn't support user-defined types or positional
-arguments. It makes unconventional use of ``operator()`` for passing
-format arguments.
+SafeFormat is a formatting library which uses ``printf``-like format strings and
+is type safe. It doesn't support user-defined types or positional arguments and
+makes unconventional use of ``operator()`` for passing format arguments.
Tinyformat
~~~~~~~~~~
-This library supports printf-like format strings and is very small and
-fast. Unfortunately it doesn't support positional arguments and wrapping
-it in C++98 is somewhat difficult. Also its performance and code compactness
-are limited by IOStreams.
+This library supports ``printf``-like format strings and is very small .
+It doesn't support positional arguments and wrapping it in C++98 is somewhat
+difficult. Tinyformat relies on iostreams which limits its performance.
Boost Spirit.Karma
~~~~~~~~~~~~~~~~~~
-This is not really a formatting library but I decided to include it here
-for completeness. As IOStreams it suffers from the problem of mixing
-verbatim text with arguments. The library is pretty fast, but slower
-on integer formatting than ``fmt::Writer`` on Karma's own benchmark,
+This is not really a formatting library but I decided to include it here for
+completeness. As iostreams, it suffers from the problem of mixing verbatim text
+with arguments. The library is pretty fast, but slower on integer formatting
+than ``fmt::format_int`` on Karma's own benchmark,
see `Fast integer to string conversion in C++
<http://zverovich.net/2013/09/07/integer-to-string-conversion-in-cplusplus.html>`_.
-Benchmarks
-----------
-
-Speed tests
-~~~~~~~~~~~
-
-The following speed tests results were generated by building
-``tinyformat_test.cpp`` on Ubuntu GNU/Linux 14.04.1 with
-``g++-4.8.2 -O3 -DSPEED_TEST -DHAVE_FORMAT``, and taking the best of three
-runs. In the test, the format string ``"%0.10f:%04d:%+g:%s:%p:%c:%%\n"`` or
-equivalent is filled 2000000 times with output sent to ``/dev/null``; for
-further details see the `source
-<https://github.com/fmtlib/format-benchmark/blob/master/tinyformat_test.cpp>`_.
-
-================= ============= ===========
-Library Method Run Time, s
-================= ============= ===========
-libc printf 1.35
-libc++ std::ostream 3.42
-fmt 534bff7 fmt::print 1.56
-tinyformat 2.0.1 tfm::printf 3.73
-Boost Format 1.54 boost::format 8.44
-Folly Format folly::format 2.54
-================= ============= ===========
-
-As you can see ``boost::format`` is much slower than the alternative methods; this
-is confirmed by `other tests <http://accu.org/index.php/journals/1539>`_.
-Tinyformat is quite good coming close to IOStreams. Unfortunately tinyformat
-cannot be faster than the IOStreams because it uses them internally.
-Performance of fmt is close to that of printf, being `faster than printf on integer
-formatting <http://zverovich.net/2013/09/07/integer-to-string-conversion-in-cplusplus.html>`_,
-but slower on floating-point formatting which dominates this benchmark.
-
-Compile time and code bloat
-~~~~~~~~~~~~~~~~~~~~~~~~~~~
-
-The script `bloat-test.py
-<https://github.com/fmtlib/format-benchmark/blob/master/bloat-test.py>`_
-from `format-benchmark <https://github.com/fmtlib/format-benchmark>`_
-tests compile time and code bloat for nontrivial projects.
-It generates 100 translation units and uses ``printf()`` or its alternative
-five times in each to simulate a medium sized project. The resulting
-executable size and compile time (Apple LLVM version 8.1.0 (clang-802.0.42),
-macOS Sierra, best of three) is shown in the following tables.
-
-**Optimized build (-O3)**
-
-============= =============== ==================== ==================
-Method Compile Time, s Executable size, KiB Stripped size, KiB
-============= =============== ==================== ==================
-printf 2.6 29 26
-printf+string 16.4 29 26
-IOStreams 31.1 59 55
-fmt 19.0 37 34
-tinyformat 44.0 103 97
-Boost Format 91.9 226 203
-Folly Format 115.7 101 88
-============= =============== ==================== ==================
-
-As you can see, fmt has 60% less overhead in terms of resulting binary code
-size compared to IOStreams and comes pretty close to ``printf``. Boost Format
-and Folly Format have the largest overheads.
-
-``printf+string`` is the same as ``printf`` but with extra ``<string>``
-include to measure the overhead of the latter.
-
-**Non-optimized build**
-
-============= =============== ==================== ==================
-Method Compile Time, s Executable size, KiB Stripped size, KiB
-============= =============== ==================== ==================
-printf 2.2 33 30
-printf+string 16.0 33 30
-IOStreams 28.3 56 52
-fmt 18.2 59 50
-tinyformat 32.6 88 82
-Boost Format 54.1 365 303
-Folly Format 79.9 445 430
-============= =============== ==================== ==================
-
-``libc``, ``lib(std)c++`` and ``libfmt`` are all linked as shared
-libraries to compare formatting function overhead only. Boost Format
-and tinyformat are header-only libraries so they don't provide any
-linkage options.
-
-Running the tests
-~~~~~~~~~~~~~~~~~
-
-Please refer to `Building the library`__ for the instructions on how to build
-the library and run the unit tests.
-
-__ http://fmtlib.net/latest/usage.html#building-the-library
-
-Benchmarks reside in a separate repository,
-`format-benchmarks <https://github.com/fmtlib/format-benchmark>`_,
-so to run the benchmarks you first need to clone this repository and
-generate Makefiles with CMake::
-
- $ git clone --recursive https://github.com/fmtlib/format-benchmark.git
- $ cd format-benchmark
- $ cmake .
-
-Then you can run the speed test::
-
- $ make speed-test
-
-or the bloat test::
-
- $ make bloat-test
-
FAQ
---
@@ -474,11 +469,11 @@
License
-------
-fmt is distributed under the BSD `license
+{fmt} is distributed under the BSD `license
<https://github.com/fmtlib/fmt/blob/master/LICENSE.rst>`_.
The `Format String Syntax
-<http://fmtlib.net/latest/syntax.html>`_
+<https://fmt.dev/latest/syntax.html>`_
section in the documentation is based on the one from Python `string module
documentation <https://docs.python.org/3/library/string.html#module-string>`_
adapted for the current library. For this reason the documentation is
@@ -490,7 +485,7 @@
Acknowledgments
---------------
-The fmt library is maintained by Victor Zverovich (`vitaut
+The {fmt} library is maintained by Victor Zverovich (`vitaut
<https://github.com/vitaut>`_) and Jonathan Müller (`foonathan
<https://github.com/foonathan>`_) with contributions from many other people.
See `Contributors <https://github.com/fmtlib/fmt/graphs/contributors>`_ and
diff --git a/doc/CMakeLists.txt b/doc/CMakeLists.txt
index c16427a..f3dae60 100644
--- a/doc/CMakeLists.txt
+++ b/doc/CMakeLists.txt
@@ -6,7 +6,7 @@
add_custom_target(doc
COMMAND ${CMAKE_CURRENT_SOURCE_DIR}/build.py ${FMT_VERSION}
- SOURCES api.rst syntax.rst build.py conf.py _templates/layout.html)
+ SOURCES api.rst syntax.rst usage.rst build.py conf.py _templates/layout.html)
install(DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/html/
DESTINATION share/doc/fmt OPTIONAL)
diff --git a/doc/_templates/layout.html b/doc/_templates/layout.html
index 0ac2dec..ed19bcd 100644
--- a/doc/_templates/layout.html
+++ b/doc/_templates/layout.html
@@ -58,7 +58,7 @@
<span class="caret"></span></a>
<ul class="dropdown-menu" role="menu">
{% for v in versions.split(',') %}
- <li><a href="http://fmtlib.net/{{v}}">{{v}}</a></li>
+ <li><a href="https://fmt.dev/{{v}}">{{v}}</a></li>
{% endfor %}
</ul>
</li>
diff --git a/doc/api.rst b/doc/api.rst
index 33a4f6d..b5adf4b 100644
--- a/doc/api.rst
+++ b/doc/api.rst
@@ -10,7 +10,7 @@
facilities and a lightweight subset of formatting functions
* :ref:`fmt/format.h <format-api>`: the full format API providing compile-time
format string checks, output iterator and user-defined type support
-* :ref:`fmt/time.h <time-api>`: date and time formatting
+* :ref:`fmt/chrono.h <chrono-api>`: date and time formatting
* :ref:`fmt/ostream.h <ostream-api>`: ``std::ostream`` support
* :ref:`fmt/printf.h <printf-api>`: ``printf`` formatting
@@ -39,24 +39,26 @@
.. _format:
-.. doxygenfunction:: format(const S&, const Args&...)
-.. doxygenfunction:: vformat(const S&, basic_format_args<typename buffer_context<Char>::type>)
+.. doxygenfunction:: format(const S&, Args&&...)
+.. doxygenfunction:: vformat(const S&, basic_format_args<buffer_context<Char>>)
.. _print:
-.. doxygenfunction:: print(const S&, const Args&...)
+.. doxygenfunction:: print(const S&, Args&&...)
.. doxygenfunction:: vprint(string_view, format_args)
-.. doxygenfunction:: print(std::FILE *, const S&, const Args&...)
+.. doxygenfunction:: print(std::FILE *, const S&, Args&&...)
.. doxygenfunction:: vprint(std::FILE *, string_view, format_args)
.. doxygenfunction:: vprint(std::FILE *, wstring_view, wformat_args)
-Named arguments
+Named Arguments
---------------
-.. doxygenfunction:: fmt::arg(string_view, const T&)
+.. doxygenfunction:: fmt::arg(const S&, const T&)
-Argument lists
+Named arguments are not supported in compile-time checks at the moment.
+
+Argument Lists
--------------
.. doxygenfunction:: fmt::make_format_args(const Args&...)
@@ -89,12 +91,13 @@
``fmt/format.h`` defines the full format API providing compile-time format
string checks, output iterator and user-defined type support.
-Compile-time format string checks
+Compile-time Format String Checks
---------------------------------
+.. doxygendefine:: FMT_STRING
.. doxygendefine:: fmt
-Formatting user-defined types
+Formatting User-defined Types
-----------------------------
To make a user-defined type formattable, specialize the ``formatter<T>`` struct
@@ -112,7 +115,7 @@
template <typename FormatContext>
auto format(const point &p, FormatContext &ctx) {
- return format_to(ctx.begin(), "({:.1f}, {:.1f})", p.x, p.y);
+ return format_to(ctx.out(), "({:.1f}, {:.1f})", p.x, p.y);
}
};
}
@@ -126,7 +129,7 @@
In the example above the ``formatter<point>::parse`` function ignores the
contents of the format string referred to by ``ctx.begin()`` so the object will
always be formatted in the same way. See ``formatter<tm>::parse`` in
-:file:`fmt/time.h` for an advanced example of how to parse the format string and
+:file:`fmt/chrono.h` for an advanced example of how to parse the format string and
customize the formatted output.
You can also reuse existing formatters, for example::
@@ -177,15 +180,11 @@
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.
-
-Output iterator support
+Output Iterator Support
-----------------------
-.. doxygenfunction:: fmt::format_to(OutputIt, const S&, const Args&...)
-.. doxygenfunction:: fmt::format_to_n(OutputIt, std::size_t, string_view, const Args&...)
+.. doxygenfunction:: fmt::format_to(OutputIt, const S&, Args&&...)
+.. doxygenfunction:: fmt::format_to_n(OutputIt, std::size_t, string_view, Args&&...)
.. doxygenstruct:: fmt::format_to_n_result
:members:
@@ -201,6 +200,8 @@
Utilities
---------
+.. doxygenstruct:: fmt::is_char
+
.. doxygentypedef:: fmt::char_t
.. doxygenfunction:: fmt::formatted_size(string_view, const Args&...)
@@ -209,13 +210,17 @@
.. doxygenfunction:: fmt::to_wstring(const T&)
-.. doxygenfunction:: fmt::to_string_view(basic_string_view<Char>)
+.. doxygenfunction:: fmt::to_string_view(const Char *)
+
+.. doxygenfunction:: fmt::join(const Range&, string_view)
+
+.. doxygenfunction:: fmt::join(It, It, string_view)
.. doxygenclass:: fmt::basic_memory_buffer
:protected-members:
:members:
-System errors
+System Errors
-------------
fmt does not use ``errno`` to communicate errors to the user, but it may call
@@ -232,7 +237,7 @@
.. _formatstrings:
-Custom allocators
+Custom Allocators
-----------------
The {fmt} library supports custom dynamic memory allocators.
@@ -267,7 +272,7 @@
the default allocator. Also floating-point formatting falls back on ``sprintf``
which may do allocations.
-Custom formatting of built-in types
+Custom Formatting of Built-in Types
-----------------------------------
It is possible to change the way arguments are formatted by providing a
@@ -311,16 +316,16 @@
.. doxygenclass:: fmt::arg_formatter
:members:
-.. _time-api:
+.. _chrono-api:
-Date and time formatting
+Date and Time Formatting
========================
The library supports `strftime
<http://en.cppreference.com/w/cpp/chrono/c/strftime>`_-like date and time
formatting::
- #include <fmt/time.h>
+ #include <fmt/chrono.h>
std::time_t t = std::time(nullptr);
// Prints "The date is 2016-04-29." (with the current date)
@@ -331,7 +336,7 @@
.. _ostream-api:
-``std::ostream`` support
+``std::ostream`` Support
========================
``fmt/ostream.h`` provides ``std::ostream`` support including formatting of
@@ -352,11 +357,11 @@
std::string s = fmt::format("The date is {}", date(2012, 12, 9));
// s == "The date is 2012-12-9"
-.. doxygenfunction:: print(std::basic_ostream<fmt::char_t<S>>&, const S&, const Args&...)
+.. doxygenfunction:: print(std::basic_ostream<Char>&, const S&, Args&&...)
.. _printf-api:
-``printf`` formatting
+``printf`` Formatting
=====================
The header ``fmt/printf.h`` provides ``printf``-like formatting functionality.
@@ -370,6 +375,6 @@
.. doxygenfunction:: fprintf(std::FILE *, const S&, const Args&...)
-.. doxygenfunction:: fprintf(std::basic_ostream<fmt::char_t<S>>&, const S&, const Args&...)
+.. doxygenfunction:: fprintf(std::basic_ostream<Char>&, const S&, const Args&...)
.. doxygenfunction:: sprintf(const S&, const Args&...)
diff --git a/doc/build.py b/doc/build.py
index 924563f..fb4f546 100755
--- a/doc/build.py
+++ b/doc/build.py
@@ -6,7 +6,7 @@
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', '5.3.0']
+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', '6.0.0']
def pip_install(package, commit=None, **kwargs):
"Install package using pip."
@@ -94,7 +94,7 @@
"FMT_BEGIN_NAMESPACE=namespace fmt {{" \
"FMT_END_NAMESPACE=}}" \
"FMT_STRING_ALIAS=1" \
- "FMT_ENABLE_IF_T(B, T)=T"
+ "FMT_ENABLE_IF(B)="
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 a8dc05e..9480ff6 100644
--- a/doc/index.rst
+++ b/doc/index.rst
@@ -109,7 +109,8 @@
format(fmt("The answer is {:d}"), "forty-two");
reports a compile-time error for the same reason on compilers that support
-relaxed ``constexpr``.
+relaxed ``constexpr``. See `here <api.html#c.fmt>`_ for how to enable
+compile-time checks.
The following code
@@ -129,7 +130,7 @@
which is represented by ``L'\x42e'`` if we use Unicode) which is rarely what is
needed.
-Compact binary code
+Compact Binary Code
-------------------
The library is designed to produce compact per-call compiled code. For example
@@ -174,8 +175,9 @@
* decltype
* trailing return types
* deleted functions
+* alias templates
-These are available since GCC 4.4, Clang 2.9 and MSVC 18.0 (2013). For older
+These are available since GCC 4.8, Clang 3.0 and MSVC 19.0 (2015). For older
compilers use fmt `version 4.x
<https://github.com/fmtlib/fmt/releases/tag/4.1.0>`_ which continues to be
maintained and only requires C++98.
diff --git a/doc/syntax.rst b/doc/syntax.rst
index fc27c5e..a6bddf6 100644
--- a/doc/syntax.rst
+++ b/doc/syntax.rst
@@ -244,7 +244,7 @@
| | notation using the letter 'e' to indicate the exponent. |
+---------+----------------------------------------------------------+
| ``'E'`` | Exponent notation. Same as ``'e'`` except it uses an |
-| | upper-case 'E' as the separator character. |
+| | upper-case ``'E'`` as the separator character. |
+---------+----------------------------------------------------------+
| ``'f'`` | Fixed point. Displays the number as a fixed-point |
| | number. |
@@ -264,10 +264,15 @@
| | ``'E'`` if the number gets too large. The |
| | representations of infinity and NaN are uppercased, too. |
+---------+----------------------------------------------------------+
-| none | The same as ``'g'``. |
+| ``'%'`` | Fixed point as a percentage. This is similar to ``'f'``, |
+| | but the argument is multiplied by 100 and a percent sign |
+| | ``%`` is appended. |
+---------+----------------------------------------------------------+
-
-Floating-point formatting is locale-dependent.
+| none | Similar to ``'g'``, except that fixed-point notation, |
+| | when used, has at least one digit past the decimal |
+| | point. The default precision is as high as needed to |
+| | represent the particular value. |
++---------+----------------------------------------------------------+
.. ifconfig:: False
@@ -303,7 +308,7 @@
.. _formatexamples:
-Format examples
+Format Examples
===============
This section contains examples of the format syntax and comparison with
@@ -357,6 +362,13 @@
format("{:-f}; {:-f}", 3.14, -3.14); // show only the minus -- same as '{:f}; {:f}'
// Result: "3.140000; -3.140000"
+As a percentage::
+
+ format("{0:f} or {0:%}", .635);
+ // Result: "0.635000 or 63.500000%"
+ format("{:*^{}.{}%}", 1., 15, 2); // With fill, dynamic width and dynamic precision.
+ // Result: "****100.00%****"
+
Replacing ``%x`` and ``%o`` and converting the value to different bases::
format("int: {0:d}; hex: {0:x}; oct: {0:o}; bin: {0:b}", 42);
@@ -412,4 +424,3 @@
9 9 11 1001
10 A 12 1010
11 B 13 1011
-
diff --git a/doc/usage.rst b/doc/usage.rst
index 2b9777c..e71629c 100644
--- a/doc/usage.rst
+++ b/doc/usage.rst
@@ -2,21 +2,15 @@
Usage
*****
-To use the fmt library, add :file:`format.h` and :file:`format.cc` from
-a `release archive <https://github.com/fmtlib/fmt/releases/latest>`_
-or the `Git repository <https://github.com/fmtlib/fmt>`_ to your project.
+To use the {fmt} library, add :file:`fmt/core.h`, :file:`fmt/format.h`,
+:file:`fmt/format-inl.h`, :file:`src/format.cc` and optionally other headers
+from a `release archive <https://github.com/fmtlib/fmt/releases/latest>`_ or
+the `Git repository <https://github.com/fmtlib/fmt>`_ to your project.
Alternatively, you can :ref:`build the library with CMake <building>`.
-If you are using Visual C++ with precompiled headers, you might need to add
-the line ::
-
- #include "stdafx.h"
-
-before other includes in :file:`format.cc`.
-
.. _building:
-Building the library
+Building the Library
====================
The included `CMake build script`__ can be used to build the fmt
@@ -31,7 +25,7 @@
mkdir build # Create a directory to hold the build output.
cd build
- cmake <path/to/fmt> # Generate native build scripts.
+ cmake .. # Generate native build scripts.
where :file:`{<path/to/fmt>}` is a path to the ``fmt`` repository.
@@ -58,8 +52,14 @@
__ http://en.wikipedia.org/wiki/Library_%28computing%29#Shared_libraries
-Header-only usage with CMake
-============================
+Installing the Library
+======================
+
+After building the library you can install it on a Unix-like system by running
+:command:`sudo make install`.
+
+Usage with CMake
+================
You can add the ``fmt`` library directory into your project and include it in
your ``CMakeLists.txt`` file::
@@ -79,11 +79,11 @@
find_package(fmt)
target_link_libraries(<your-target> fmt::fmt)
-Setting up your target to use a header-only version of ``fmt`` is equaly easy::
+Setting up your target to use a header-only version of ``fmt`` is equally easy::
- target_link_libraries(<your-target> PRIVATE fmt-header-only)
+ target_link_libraries(<your-target> PRIVATE fmt::fmt-header-only)
-Building the documentation
+Building the Documentation
==========================
To build the documentation you need the following software installed on your
diff --git a/include/fmt/chrono.h b/include/fmt/chrono.h
index 209cdc2..57ce9ef 100644
--- a/include/fmt/chrono.h
+++ b/include/fmt/chrono.h
@@ -16,9 +16,181 @@
#include <locale>
#include <sstream>
+// enable safe chrono durations, unless explicitly disabled
+#ifndef FMT_SAFE_DURATION_CAST
+# define FMT_SAFE_DURATION_CAST 1
+#endif
+
+#if FMT_SAFE_DURATION_CAST
+# include "safe-duration-cast.h"
+#endif
+
FMT_BEGIN_NAMESPACE
-namespace internal{
+// Prevents expansion of a preceding token as a function-style macro.
+// Usage: f FMT_NOMACRO()
+#define FMT_NOMACRO
+
+namespace internal {
+inline null<> localtime_r FMT_NOMACRO(...) { return null<>(); }
+inline null<> localtime_s(...) { return null<>(); }
+inline null<> gmtime_r(...) { return null<>(); }
+inline null<> gmtime_s(...) { return null<>(); }
+} // namespace internal
+
+// Thread-safe replacement for std::localtime
+inline std::tm localtime(std::time_t time) {
+ struct dispatcher {
+ std::time_t time_;
+ std::tm tm_;
+
+ dispatcher(std::time_t t) : time_(t) {}
+
+ bool run() {
+ using namespace fmt::internal;
+ return handle(localtime_r(&time_, &tm_));
+ }
+
+ bool handle(std::tm* tm) { return tm != nullptr; }
+
+ bool handle(internal::null<>) {
+ using namespace fmt::internal;
+ return fallback(localtime_s(&tm_, &time_));
+ }
+
+ bool fallback(int res) { return res == 0; }
+
+#if !FMT_MSC_VER
+ bool fallback(internal::null<>) {
+ using namespace fmt::internal;
+ std::tm* tm = std::localtime(&time_);
+ if (tm) tm_ = *tm;
+ return tm != nullptr;
+ }
+#endif
+ };
+ dispatcher lt(time);
+ // Too big time values may be unsupported.
+ if (!lt.run()) FMT_THROW(format_error("time_t value out of range"));
+ return lt.tm_;
+}
+
+// Thread-safe replacement for std::gmtime
+inline std::tm gmtime(std::time_t time) {
+ struct dispatcher {
+ std::time_t time_;
+ std::tm tm_;
+
+ dispatcher(std::time_t t) : time_(t) {}
+
+ bool run() {
+ using namespace fmt::internal;
+ return handle(gmtime_r(&time_, &tm_));
+ }
+
+ bool handle(std::tm* tm) { return tm != nullptr; }
+
+ bool handle(internal::null<>) {
+ using namespace fmt::internal;
+ return fallback(gmtime_s(&tm_, &time_));
+ }
+
+ bool fallback(int res) { return res == 0; }
+
+#if !FMT_MSC_VER
+ bool fallback(internal::null<>) {
+ std::tm* tm = std::gmtime(&time_);
+ if (tm) tm_ = *tm;
+ return tm != nullptr;
+ }
+#endif
+ };
+ dispatcher gt(time);
+ // Too big time values may be unsupported.
+ if (!gt.run()) FMT_THROW(format_error("time_t value out of range"));
+ return gt.tm_;
+}
+
+namespace internal {
+inline std::size_t strftime(char* str, std::size_t count, const char* format,
+ const std::tm* time) {
+ return std::strftime(str, count, format, time);
+}
+
+inline std::size_t strftime(wchar_t* str, std::size_t count,
+ const wchar_t* format, const std::tm* time) {
+ return std::wcsftime(str, count, format, time);
+}
+} // namespace internal
+
+template <typename Char> struct formatter<std::tm, Char> {
+ template <typename ParseContext>
+ auto parse(ParseContext& ctx) -> decltype(ctx.begin()) {
+ auto it = ctx.begin();
+ if (it != ctx.end() && *it == ':') ++it;
+ auto end = it;
+ while (end != ctx.end() && *end != '}') ++end;
+ tm_format.reserve(internal::to_unsigned(end - it + 1));
+ tm_format.append(it, end);
+ tm_format.push_back('\0');
+ return end;
+ }
+
+ template <typename FormatContext>
+ auto format(const std::tm& tm, FormatContext& ctx) -> decltype(ctx.out()) {
+ basic_memory_buffer<Char> buf;
+ std::size_t start = buf.size();
+ for (;;) {
+ std::size_t size = buf.capacity() - start;
+ std::size_t count =
+ internal::strftime(&buf[start], size, &tm_format[0], &tm);
+ if (count != 0) {
+ buf.resize(start + count);
+ break;
+ }
+ if (size >= tm_format.size() * 256) {
+ // If the buffer is 256 times larger than the format string, assume
+ // that `strftime` gives an empty result. There doesn't seem to be a
+ // better way to distinguish the two cases:
+ // https://github.com/fmtlib/fmt/issues/367
+ break;
+ }
+ const std::size_t MIN_GROWTH = 10;
+ buf.reserve(buf.capacity() + (size > MIN_GROWTH ? size : MIN_GROWTH));
+ }
+ return std::copy(buf.begin(), buf.end(), ctx.out());
+ }
+
+ basic_memory_buffer<Char> tm_format;
+};
+
+namespace internal {
+template <typename Period> FMT_CONSTEXPR const char* get_units() {
+ return nullptr;
+}
+template <> FMT_CONSTEXPR const char* get_units<std::atto>() { return "as"; }
+template <> FMT_CONSTEXPR const char* get_units<std::femto>() { return "fs"; }
+template <> FMT_CONSTEXPR const char* get_units<std::pico>() { return "ps"; }
+template <> FMT_CONSTEXPR const char* get_units<std::nano>() { return "ns"; }
+template <> FMT_CONSTEXPR const char* get_units<std::micro>() { return "µs"; }
+template <> FMT_CONSTEXPR const char* get_units<std::milli>() { return "ms"; }
+template <> FMT_CONSTEXPR const char* get_units<std::centi>() { return "cs"; }
+template <> FMT_CONSTEXPR const char* get_units<std::deci>() { return "ds"; }
+template <> FMT_CONSTEXPR const char* get_units<std::ratio<1>>() { return "s"; }
+template <> FMT_CONSTEXPR const char* get_units<std::deca>() { return "das"; }
+template <> FMT_CONSTEXPR const char* get_units<std::hecto>() { return "hs"; }
+template <> FMT_CONSTEXPR const char* get_units<std::kilo>() { return "ks"; }
+template <> FMT_CONSTEXPR const char* get_units<std::mega>() { return "Ms"; }
+template <> FMT_CONSTEXPR const char* get_units<std::giga>() { return "Gs"; }
+template <> FMT_CONSTEXPR const char* get_units<std::tera>() { return "Ts"; }
+template <> FMT_CONSTEXPR const char* get_units<std::peta>() { return "Ps"; }
+template <> FMT_CONSTEXPR const char* get_units<std::exa>() { return "Es"; }
+template <> FMT_CONSTEXPR const char* get_units<std::ratio<60>>() {
+ return "m";
+}
+template <> FMT_CONSTEXPR const char* get_units<std::ratio<3600>>() {
+ return "h";
+}
enum class numeric_system {
standard,
@@ -28,8 +200,9 @@
// Parses a put_time-like format string and invokes handler actions.
template <typename Char, typename Handler>
-FMT_CONSTEXPR const Char *parse_chrono_format(
- const Char *begin, const Char *end, Handler &&handler) {
+FMT_CONSTEXPR const Char* parse_chrono_format(const Char* begin,
+ const Char* end,
+ Handler&& handler) {
auto ptr = begin;
while (ptr != end) {
auto c = *ptr;
@@ -38,11 +211,9 @@
++ptr;
continue;
}
- if (begin != ptr)
- handler.on_text(begin, ptr);
- ++ptr; // consume '%'
- if (ptr == end)
- throw format_error("invalid format");
+ if (begin != ptr) handler.on_text(begin, ptr);
+ ++ptr; // consume '%'
+ if (ptr == end) FMT_THROW(format_error("invalid format"));
c = *ptr++;
switch (c) {
case '%':
@@ -119,6 +290,12 @@
case 'p':
handler.on_am_pm();
break;
+ case 'Q':
+ handler.on_duration_value();
+ break;
+ case 'q':
+ handler.on_duration_unit();
+ break;
case 'z':
handler.on_utc_offset();
break;
@@ -127,8 +304,7 @@
break;
// Alternative representation:
case 'E': {
- if (ptr == end)
- throw format_error("invalid format");
+ if (ptr == end) FMT_THROW(format_error("invalid format"));
c = *ptr++;
switch (c) {
case 'c':
@@ -141,13 +317,12 @@
handler.on_loc_time(numeric_system::alternative);
break;
default:
- throw format_error("invalid format");
+ FMT_THROW(format_error("invalid format"));
}
break;
}
case 'O':
- if (ptr == end)
- throw format_error("invalid format");
+ if (ptr == end) FMT_THROW(format_error("invalid format"));
c = *ptr++;
switch (c) {
case 'w':
@@ -169,96 +344,259 @@
handler.on_second(numeric_system::alternative);
break;
default:
- throw format_error("invalid format");
+ FMT_THROW(format_error("invalid format"));
}
break;
default:
- throw format_error("invalid format");
+ FMT_THROW(format_error("invalid format"));
}
begin = ptr;
}
- if (begin != ptr)
- handler.on_text(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"); }
+ FMT_NORETURN void report_no_date() { FMT_THROW(format_error("no date")); }
- template <typename Char>
- 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(); }
+ template <typename Char> void on_text(const Char*, const Char*) {}
+ FMT_NORETURN void on_abbr_weekday() { report_no_date(); }
+ FMT_NORETURN void on_full_weekday() { report_no_date(); }
+ FMT_NORETURN void on_dec0_weekday(numeric_system) { report_no_date(); }
+ FMT_NORETURN void on_dec1_weekday(numeric_system) { report_no_date(); }
+ FMT_NORETURN void on_abbr_month() { report_no_date(); }
+ FMT_NORETURN void on_full_month() { report_no_date(); }
void on_24_hour(numeric_system) {}
void on_12_hour(numeric_system) {}
void on_minute(numeric_system) {}
void on_second(numeric_system) {}
- 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(); }
+ FMT_NORETURN void on_datetime(numeric_system) { report_no_date(); }
+ FMT_NORETURN void on_loc_date(numeric_system) { report_no_date(); }
+ FMT_NORETURN void on_loc_time(numeric_system) { report_no_date(); }
+ FMT_NORETURN void on_us_date() { report_no_date(); }
+ FMT_NORETURN void on_iso_date() { report_no_date(); }
void on_12_hour_time() {}
void on_24_hour_time() {}
void on_iso_time() {}
void on_am_pm() {}
- void on_utc_offset() { report_no_date(); }
- void on_tz_name() { report_no_date(); }
+ void on_duration_value() {}
+ void on_duration_unit() {}
+ FMT_NORETURN void on_utc_offset() { report_no_date(); }
+ FMT_NORETURN void on_tz_name() { report_no_date(); }
};
-template <typename Int>
-inline int to_int(Int value) {
- FMT_ASSERT(value >= (std::numeric_limits<int>::min)() &&
- value <= (std::numeric_limits<int>::max)(), "invalid value");
+template <typename T, FMT_ENABLE_IF(std::is_integral<T>::value)>
+inline bool isnan(T) {
+ return false;
+}
+template <typename T, FMT_ENABLE_IF(std::is_floating_point<T>::value)>
+inline bool isnan(T value) {
+ return std::isnan(value);
+}
+
+template <typename T, FMT_ENABLE_IF(std::is_integral<T>::value)>
+inline bool isfinite(T) {
+ return true;
+}
+template <typename T, FMT_ENABLE_IF(std::is_floating_point<T>::value)>
+inline bool isfinite(T value) {
+ return std::isfinite(value);
+}
+
+// Convers value to int and checks that it's in the range [0, upper).
+template <typename T, FMT_ENABLE_IF(std::is_integral<T>::value)>
+inline int to_nonnegative_int(T value, int upper) {
+ FMT_ASSERT(value >= 0 && value <= upper, "invalid value");
+ (void)upper;
+ return static_cast<int>(value);
+}
+template <typename T, FMT_ENABLE_IF(!std::is_integral<T>::value)>
+inline int to_nonnegative_int(T value, int upper) {
+ FMT_ASSERT(
+ std::isnan(value) || (value >= 0 && value <= static_cast<T>(upper)),
+ "invalid value");
+ (void)upper;
return static_cast<int>(value);
}
-template <typename FormatContext, typename OutputIt>
+template <typename T, FMT_ENABLE_IF(std::is_integral<T>::value)>
+inline T mod(T x, int y) {
+ return x % y;
+}
+template <typename T, FMT_ENABLE_IF(std::is_floating_point<T>::value)>
+inline T mod(T x, int y) {
+ return std::fmod(x, static_cast<T>(y));
+}
+
+// If T is an integral type, maps T to its unsigned counterpart, otherwise
+// leaves it unchanged (unlike std::make_unsigned).
+template <typename T, bool INTEGRAL = std::is_integral<T>::value>
+struct make_unsigned_or_unchanged {
+ using type = T;
+};
+
+template <typename T> struct make_unsigned_or_unchanged<T, true> {
+ using type = typename std::make_unsigned<T>::type;
+};
+
+#if FMT_SAFE_DURATION_CAST
+// throwing version of safe_duration_cast
+template <typename To, typename FromRep, typename FromPeriod>
+To fmt_safe_duration_cast(std::chrono::duration<FromRep, FromPeriod> from) {
+ int ec;
+ To to = safe_duration_cast::safe_duration_cast<To>(from, ec);
+ if (ec) FMT_THROW(format_error("cannot format duration"));
+ return to;
+}
+#endif
+
+template <typename Rep, typename Period,
+ FMT_ENABLE_IF(std::is_integral<Rep>::value)>
+inline std::chrono::duration<Rep, std::milli> get_milliseconds(
+ std::chrono::duration<Rep, Period> d) {
+ // this may overflow and/or the result may not fit in the
+ // target type.
+#if FMT_SAFE_DURATION_CAST
+ using CommonSecondsType =
+ typename std::common_type<decltype(d), std::chrono::seconds>::type;
+ const auto d_as_common = fmt_safe_duration_cast<CommonSecondsType>(d);
+ const auto d_as_whole_seconds =
+ fmt_safe_duration_cast<std::chrono::seconds>(d_as_common);
+ // this conversion should be nonproblematic
+ const auto diff = d_as_common - d_as_whole_seconds;
+ const auto ms =
+ fmt_safe_duration_cast<std::chrono::duration<Rep, std::milli>>(diff);
+ return ms;
+#else
+ auto s = std::chrono::duration_cast<std::chrono::seconds>(d);
+ return std::chrono::duration_cast<std::chrono::milliseconds>(d - s);
+#endif
+}
+
+template <typename Rep, typename Period,
+ FMT_ENABLE_IF(std::is_floating_point<Rep>::value)>
+inline std::chrono::duration<Rep, std::milli> get_milliseconds(
+ std::chrono::duration<Rep, Period> d) {
+ using common_type = typename std::common_type<Rep, std::intmax_t>::type;
+ auto ms = mod(d.count() * static_cast<common_type>(Period::num) /
+ static_cast<common_type>(Period::den) * 1000,
+ 1000);
+ return std::chrono::duration<Rep, std::milli>(static_cast<Rep>(ms));
+}
+
+template <typename Rep, typename OutputIt>
+OutputIt format_chrono_duration_value(OutputIt out, Rep val, int precision) {
+ if (precision >= 0) return format_to(out, "{:.{}f}", val, precision);
+ return format_to(out, std::is_floating_point<Rep>::value ? "{:g}" : "{}",
+ val);
+}
+
+template <typename Period, typename OutputIt>
+static OutputIt format_chrono_duration_unit(OutputIt out) {
+ if (const char* unit = get_units<Period>()) return format_to(out, "{}", unit);
+ if (Period::den == 1) return format_to(out, "[{}]s", Period::num);
+ return format_to(out, "[{}/{}]s", Period::num, Period::den);
+}
+
+template <typename FormatContext, typename OutputIt, typename Rep,
+ typename Period>
struct chrono_formatter {
- FormatContext &context;
+ FormatContext& context;
OutputIt out;
- std::chrono::seconds s;
- std::chrono::milliseconds ms;
+ int precision;
+ // rep is unsigned to avoid overflow.
+ using rep =
+ conditional_t<std::is_integral<Rep>::value && sizeof(Rep) < sizeof(int),
+ unsigned, typename make_unsigned_or_unchanged<Rep>::type>;
+ rep val;
+ using seconds = std::chrono::duration<rep>;
+ seconds s;
+ using milliseconds = std::chrono::duration<rep, std::milli>;
+ bool negative;
- typedef typename FormatContext::char_type char_type;
+ using char_type = typename FormatContext::char_type;
- explicit chrono_formatter(FormatContext &ctx, OutputIt o)
- : context(ctx), out(o) {}
+ explicit chrono_formatter(FormatContext& ctx, OutputIt o,
+ std::chrono::duration<Rep, Period> d)
+ : context(ctx), out(o), val(d.count()), negative(false) {
+ if (d.count() < 0) {
+ val = 0 - val;
+ negative = true;
+ }
- 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;
+ // this may overflow and/or the result may not fit in the
+ // target type.
+#if FMT_SAFE_DURATION_CAST
+ // might need checked conversion (rep!=Rep)
+ auto tmpval = std::chrono::duration<rep, Period>(val);
+ s = fmt_safe_duration_cast<seconds>(tmpval);
+#else
+ s = std::chrono::duration_cast<seconds>(
+ std::chrono::duration<rep, Period>(val));
+#endif
}
- int minute() const { return to_int((s.count() / 60) % 60); }
- int second() const { return to_int(s.count() % 60); }
+ // returns true if nan or inf, writes to out.
+ bool handle_nan_inf() {
+ if (isfinite(val)) {
+ return false;
+ }
+ if (isnan(val)) {
+ write_nan();
+ return true;
+ }
+ // must be +-inf
+ if (val > 0) {
+ write_pinf();
+ } else {
+ write_ninf();
+ }
+ return true;
+ }
+
+ Rep hour() const { return static_cast<Rep>(mod((s.count() / 3600), 24)); }
+
+ Rep hour12() const {
+ Rep hour = static_cast<Rep>(mod((s.count() / 3600), 12));
+ return hour <= 0 ? 12 : hour;
+ }
+
+ Rep minute() const { return static_cast<Rep>(mod((s.count() / 60), 60)); }
+ Rep second() const { return static_cast<Rep>(mod(s.count(), 60)); }
std::tm time() const {
auto time = std::tm();
- time.tm_hour = hour();
- time.tm_min = minute();
- time.tm_sec = second();
+ time.tm_hour = to_nonnegative_int(hour(), 24);
+ time.tm_min = to_nonnegative_int(minute(), 60);
+ time.tm_sec = to_nonnegative_int(second(), 60);
return time;
}
- void write(int value, int width) {
- typedef typename int_traits<int>::main_type main_type;
- main_type n = to_unsigned(value);
+ void write_sign() {
+ if (negative) {
+ *out++ = '-';
+ negative = false;
+ }
+ }
+
+ void write(Rep value, int width) {
+ write_sign();
+ if (isnan(value)) return write_nan();
+ uint32_or_64_t<int> n = to_unsigned(
+ to_nonnegative_int(value, (std::numeric_limits<int>::max)()));
int num_digits = internal::count_digits(n);
- if (width > num_digits)
- out = std::fill_n(out, width - num_digits, '0');
+ if (width > num_digits) out = std::fill_n(out, width - num_digits, '0');
out = format_decimal<char_type>(out, n, num_digits);
}
- void format_localized(const tm &time, const char *format) {
+ void write_nan() { std::copy_n("nan", 3, out); }
+ void write_pinf() { std::copy_n("inf", 3, out); }
+ void write_ninf() { std::copy_n("-inf", 4, out); }
+
+ void format_localized(const tm& time, const char* format) {
+ if (isnan(val)) return write_nan();
auto locale = context.locale().template get<std::locale>();
- auto &facet = std::use_facet<std::time_put<char_type>>(locale);
+ auto& facet = std::use_facet<std::time_put<char_type>>(locale);
std::basic_ostringstream<char_type> os;
os.imbue(locale);
facet.put(os, os, ' ', &time, format, format + std::strlen(format));
@@ -266,7 +604,7 @@
std::copy(str.begin(), str.end(), out);
}
- void on_text(const char_type *begin, const char_type *end) {
+ void on_text(const char_type* begin, const char_type* end) {
std::copy(begin, end, out);
}
@@ -286,46 +624,70 @@
void on_tz_name() {}
void on_24_hour(numeric_system ns) {
- if (ns == numeric_system::standard)
- return write(hour(), 2);
+ if (handle_nan_inf()) return;
+
+ if (ns == numeric_system::standard) return write(hour(), 2);
auto time = tm();
- time.tm_hour = hour();
+ time.tm_hour = to_nonnegative_int(hour(), 24);
format_localized(time, "%OH");
}
void on_12_hour(numeric_system ns) {
- if (ns == numeric_system::standard)
- return write(hour12(), 2);
+ if (handle_nan_inf()) return;
+
+ if (ns == numeric_system::standard) return write(hour12(), 2);
auto time = tm();
- time.tm_hour = hour();
+ time.tm_hour = to_nonnegative_int(hour12(), 12);
format_localized(time, "%OI");
}
void on_minute(numeric_system ns) {
- if (ns == numeric_system::standard)
- return write(minute(), 2);
+ if (handle_nan_inf()) return;
+
+ if (ns == numeric_system::standard) return write(minute(), 2);
auto time = tm();
- time.tm_min = minute();
+ time.tm_min = to_nonnegative_int(minute(), 60);
format_localized(time, "%OM");
}
void on_second(numeric_system ns) {
+ if (handle_nan_inf()) return;
+
if (ns == numeric_system::standard) {
write(second(), 2);
+#if FMT_SAFE_DURATION_CAST
+ // convert rep->Rep
+ using duration_rep = std::chrono::duration<rep, Period>;
+ using duration_Rep = std::chrono::duration<Rep, Period>;
+ auto tmpval = fmt_safe_duration_cast<duration_Rep>(duration_rep{val});
+#else
+ auto tmpval = std::chrono::duration<Rep, Period>(val);
+#endif
+ auto ms = get_milliseconds(tmpval);
if (ms != std::chrono::milliseconds(0)) {
*out++ = '.';
- write(to_int(ms.count()), 3);
+ write(ms.count(), 3);
}
return;
}
auto time = tm();
- time.tm_sec = second();
+ time.tm_sec = to_nonnegative_int(second(), 60);
format_localized(time, "%OS");
}
- void on_12_hour_time() { format_localized(time(), "%r"); }
+ void on_12_hour_time() {
+ if (handle_nan_inf()) return;
+
+ format_localized(time(), "%r");
+ }
void on_24_hour_time() {
+ if (handle_nan_inf()) {
+ *out++ = ':';
+ handle_nan_inf();
+ return;
+ }
+
write(hour(), 2);
*out++ = ':';
write(minute(), 2);
@@ -334,115 +696,130 @@
void on_iso_time() {
on_24_hour_time();
*out++ = ':';
+ if (handle_nan_inf()) return;
write(second(), 2);
}
- void on_am_pm() { format_localized(time(), "%p"); }
+ void on_am_pm() {
+ if (handle_nan_inf()) return;
+ format_localized(time(), "%p");
+ }
+
+ void on_duration_value() {
+ if (handle_nan_inf()) return;
+ write_sign();
+ out = format_chrono_duration_value(out, val, precision);
+ }
+
+ void on_duration_unit() { out = format_chrono_duration_unit<Period>(out); }
};
} // namespace internal
-template <typename Period> FMT_CONSTEXPR const char *get_units() {
- return FMT_NULL;
-}
-template <> FMT_CONSTEXPR const char *get_units<std::atto>() { return "as"; }
-template <> FMT_CONSTEXPR const char *get_units<std::femto>() { return "fs"; }
-template <> FMT_CONSTEXPR const char *get_units<std::pico>() { return "ps"; }
-template <> FMT_CONSTEXPR const char *get_units<std::nano>() { return "ns"; }
-template <> FMT_CONSTEXPR const char *get_units<std::micro>() { return "µs"; }
-template <> FMT_CONSTEXPR const char *get_units<std::milli>() { return "ms"; }
-template <> FMT_CONSTEXPR const char *get_units<std::centi>() { return "cs"; }
-template <> FMT_CONSTEXPR const char *get_units<std::deci>() { return "ds"; }
-template <> FMT_CONSTEXPR const char *get_units<std::ratio<1>>() { return "s"; }
-template <> FMT_CONSTEXPR const char *get_units<std::deca>() { return "das"; }
-template <> FMT_CONSTEXPR const char *get_units<std::hecto>() { return "hs"; }
-template <> FMT_CONSTEXPR const char *get_units<std::kilo>() { return "ks"; }
-template <> FMT_CONSTEXPR const char *get_units<std::mega>() { return "Ms"; }
-template <> FMT_CONSTEXPR const char *get_units<std::giga>() { return "Gs"; }
-template <> FMT_CONSTEXPR const char *get_units<std::tera>() { return "Ts"; }
-template <> FMT_CONSTEXPR const char *get_units<std::peta>() { return "Ps"; }
-template <> FMT_CONSTEXPR const char *get_units<std::exa>() { return "Es"; }
-template <> FMT_CONSTEXPR const char *get_units<std::ratio<60>>() {
- return "m";
-}
-template <> FMT_CONSTEXPR const char *get_units<std::ratio<3600>>() {
- return "h";
-}
-
template <typename Rep, typename Period, typename Char>
struct formatter<std::chrono::duration<Rep, Period>, Char> {
private:
- align_spec spec;
- internal::arg_ref<Char> width_ref;
+ basic_format_specs<Char> specs;
+ int precision;
+ using arg_ref_type = internal::arg_ref<Char>;
+ arg_ref_type width_ref;
+ arg_ref_type precision_ref;
mutable basic_string_view<Char> format_str;
- typedef std::chrono::duration<Rep, Period> duration;
+ using duration = std::chrono::duration<Rep, Period>;
struct spec_handler {
- formatter &f;
- basic_parse_context<Char> &context;
+ formatter& f;
+ basic_parse_context<Char>& context;
+ basic_string_view<Char> format_str;
- typedef internal::arg_ref<Char> arg_ref_type;
-
- template <typename Id>
- FMT_CONSTEXPR arg_ref_type make_arg_ref(Id arg_id) {
+ template <typename Id> FMT_CONSTEXPR arg_ref_type make_arg_ref(Id arg_id) {
context.check_arg_id(arg_id);
return arg_ref_type(arg_id);
}
+ FMT_CONSTEXPR arg_ref_type make_arg_ref(basic_string_view<Char> arg_id) {
+ context.check_arg_id(arg_id);
+ const auto str_val = internal::string_view_metadata(format_str, arg_id);
+ return arg_ref_type(str_val);
+ }
+
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; }
+ void on_error(const char* msg) { FMT_THROW(format_error(msg)); }
+ void on_fill(Char fill) { f.specs.fill[0] = fill; }
+ void on_align(align_t align) { f.specs.align = align; }
+ void on_width(unsigned width) { f.specs.width = width; }
+ void on_precision(unsigned precision) { f.precision = precision; }
+ void end_precision() {}
- template <typename Id>
- void on_dynamic_width(Id arg_id) {
+ template <typename Id> void on_dynamic_width(Id arg_id) {
f.width_ref = make_arg_ref(arg_id);
}
+
+ template <typename Id> void on_dynamic_precision(Id arg_id) {
+ f.precision_ref = make_arg_ref(arg_id);
+ }
};
- public:
- formatter() : spec() {}
+ using iterator = typename basic_parse_context<Char>::iterator;
+ struct parse_range {
+ iterator begin;
+ iterator end;
+ };
- FMT_CONSTEXPR auto parse(basic_parse_context<Char> &ctx)
- -> decltype(ctx.begin()) {
+ FMT_CONSTEXPR parse_range do_parse(basic_parse_context<Char>& ctx) {
auto begin = ctx.begin(), end = ctx.end();
- if (begin == end) return begin;
- spec_handler handler{*this, ctx};
+ if (begin == end || *begin == '}') return {begin, begin};
+ spec_handler handler{*this, ctx, format_str};
begin = internal::parse_align(begin, end, handler);
- if (begin == end) return begin;
+ if (begin == end) return {begin, begin};
begin = internal::parse_width(begin, end, handler);
+ if (begin == end) return {begin, begin};
+ if (*begin == '.') {
+ if (std::is_floating_point<Rep>::value)
+ begin = internal::parse_precision(begin, end, handler);
+ else
+ handler.on_error("precision not allowed for this argument type");
+ }
end = parse_chrono_format(begin, end, internal::chrono_format_checker());
- format_str = basic_string_view<Char>(&*begin, internal::to_unsigned(end - begin));
- return end;
+ return {begin, end};
+ }
+
+ public:
+ formatter() : precision(-1) {}
+
+ FMT_CONSTEXPR auto parse(basic_parse_context<Char>& ctx)
+ -> decltype(ctx.begin()) {
+ auto range = do_parse(ctx);
+ format_str = basic_string_view<Char>(
+ &*range.begin, internal::to_unsigned(range.end - range.begin));
+ return range.end;
}
template <typename FormatContext>
- auto format(const duration &d, FormatContext &ctx)
- -> decltype(ctx.out()) {
+ 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<decltype(ctx.out()), Char> range;
- basic_writer<range> w(range(ctx.out()));
+ // As a possible future optimization, we could avoid extra copying if width
+ // is not specified.
+ basic_memory_buffer<Char> buf;
+ auto out = std::back_inserter(buf);
+ using range = internal::output_range<decltype(ctx.out()), Char>;
+ internal::basic_writer<range> w(range(ctx.out()));
+ internal::handle_dynamic_spec<internal::width_checker>(
+ specs.width, width_ref, ctx, format_str.begin());
+ internal::handle_dynamic_spec<internal::precision_checker>(
+ precision, precision_ref, ctx, format_str.begin());
if (begin == end || *begin == '}') {
- if (const char *unit = get_units<Period>())
- 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<internal::width_checker>(
- spec.width_, width_ref, ctx);
+ out = internal::format_chrono_duration_value(out, d.count(), precision);
+ internal::format_chrono_duration_unit<Period>(out);
} else {
- auto out = std::back_inserter(buf);
- internal::chrono_formatter<FormatContext, decltype(out)> f(ctx, out);
- f.s = std::chrono::duration_cast<std::chrono::seconds>(d);
- f.ms = std::chrono::duration_cast<std::chrono::milliseconds>(d - f.s);
+ internal::chrono_formatter<FormatContext, decltype(out), Rep, Period> f(
+ ctx, out, d);
+ f.precision = precision;
parse_chrono_format(begin, end, f);
}
- w.write(buf.data(), buf.size(), spec);
+ w.write(buf.data(), buf.size(), specs);
return w.out();
}
};
diff --git a/include/fmt/color.h b/include/fmt/color.h
index 5db861c..d9d3155 100644
--- a/include/fmt/color.h
+++ b/include/fmt/color.h
@@ -12,184 +12,149 @@
FMT_BEGIN_NAMESPACE
-#ifdef FMT_DEPRECATED_COLORS
-
-// color and (v)print_colored are deprecated.
-enum color { black, red, green, yellow, blue, magenta, cyan, white };
-FMT_API void vprint_colored(color c, string_view format, format_args args);
-FMT_API void vprint_colored(color c, wstring_view format, wformat_args args);
-template <typename... Args>
-inline void print_colored(color c, string_view format_str,
- const Args & ... args) {
- vprint_colored(c, format_str, make_format_args(args...));
-}
-template <typename... Args>
-inline void print_colored(color c, wstring_view format_str,
- const Args & ... args) {
- vprint_colored(c, format_str, make_format_args<wformat_context>(args...));
-}
-
-inline void vprint_colored(color c, string_view format, format_args args) {
- char escape[] = "\x1b[30m";
- escape[3] = static_cast<char>('0' + c);
- std::fputs(escape, stdout);
- vprint(format, args);
- std::fputs(internal::data::RESET_COLOR, stdout);
-}
-
-inline void vprint_colored(color c, wstring_view format, wformat_args args) {
- wchar_t escape[] = L"\x1b[30m";
- escape[3] = static_cast<wchar_t>('0' + c);
- std::fputws(escape, stdout);
- vprint(format, args);
- std::fputws(internal::data::WRESET_COLOR, stdout);
-}
-
-#else
-
enum class color : uint32_t {
- alice_blue = 0xF0F8FF, // rgb(240,248,255)
- antique_white = 0xFAEBD7, // rgb(250,235,215)
- aqua = 0x00FFFF, // rgb(0,255,255)
- aquamarine = 0x7FFFD4, // rgb(127,255,212)
- azure = 0xF0FFFF, // rgb(240,255,255)
- beige = 0xF5F5DC, // rgb(245,245,220)
- bisque = 0xFFE4C4, // rgb(255,228,196)
- black = 0x000000, // rgb(0,0,0)
- blanched_almond = 0xFFEBCD, // rgb(255,235,205)
- blue = 0x0000FF, // rgb(0,0,255)
- blue_violet = 0x8A2BE2, // rgb(138,43,226)
- brown = 0xA52A2A, // rgb(165,42,42)
- burly_wood = 0xDEB887, // rgb(222,184,135)
- cadet_blue = 0x5F9EA0, // rgb(95,158,160)
- chartreuse = 0x7FFF00, // rgb(127,255,0)
- chocolate = 0xD2691E, // rgb(210,105,30)
- coral = 0xFF7F50, // rgb(255,127,80)
- cornflower_blue = 0x6495ED, // rgb(100,149,237)
- cornsilk = 0xFFF8DC, // rgb(255,248,220)
- crimson = 0xDC143C, // rgb(220,20,60)
- cyan = 0x00FFFF, // rgb(0,255,255)
- dark_blue = 0x00008B, // rgb(0,0,139)
- dark_cyan = 0x008B8B, // rgb(0,139,139)
- dark_golden_rod = 0xB8860B, // rgb(184,134,11)
- dark_gray = 0xA9A9A9, // rgb(169,169,169)
- dark_green = 0x006400, // rgb(0,100,0)
- dark_khaki = 0xBDB76B, // rgb(189,183,107)
- dark_magenta = 0x8B008B, // rgb(139,0,139)
- dark_olive_green = 0x556B2F, // rgb(85,107,47)
- dark_orange = 0xFF8C00, // rgb(255,140,0)
- dark_orchid = 0x9932CC, // rgb(153,50,204)
- dark_red = 0x8B0000, // rgb(139,0,0)
- dark_salmon = 0xE9967A, // rgb(233,150,122)
- dark_sea_green = 0x8FBC8F, // rgb(143,188,143)
- dark_slate_blue = 0x483D8B, // rgb(72,61,139)
- dark_slate_gray = 0x2F4F4F, // rgb(47,79,79)
- dark_turquoise = 0x00CED1, // rgb(0,206,209)
- dark_violet = 0x9400D3, // rgb(148,0,211)
- deep_pink = 0xFF1493, // rgb(255,20,147)
- deep_sky_blue = 0x00BFFF, // rgb(0,191,255)
- dim_gray = 0x696969, // rgb(105,105,105)
- dodger_blue = 0x1E90FF, // rgb(30,144,255)
- fire_brick = 0xB22222, // rgb(178,34,34)
- floral_white = 0xFFFAF0, // rgb(255,250,240)
- forest_green = 0x228B22, // rgb(34,139,34)
- fuchsia = 0xFF00FF, // rgb(255,0,255)
- gainsboro = 0xDCDCDC, // rgb(220,220,220)
- ghost_white = 0xF8F8FF, // rgb(248,248,255)
- gold = 0xFFD700, // rgb(255,215,0)
- golden_rod = 0xDAA520, // rgb(218,165,32)
- gray = 0x808080, // rgb(128,128,128)
- green = 0x008000, // rgb(0,128,0)
- green_yellow = 0xADFF2F, // rgb(173,255,47)
- honey_dew = 0xF0FFF0, // rgb(240,255,240)
- hot_pink = 0xFF69B4, // rgb(255,105,180)
- indian_red = 0xCD5C5C, // rgb(205,92,92)
- indigo = 0x4B0082, // rgb(75,0,130)
- ivory = 0xFFFFF0, // rgb(255,255,240)
- khaki = 0xF0E68C, // rgb(240,230,140)
- lavender = 0xE6E6FA, // rgb(230,230,250)
- lavender_blush = 0xFFF0F5, // rgb(255,240,245)
- lawn_green = 0x7CFC00, // rgb(124,252,0)
- lemon_chiffon = 0xFFFACD, // rgb(255,250,205)
- light_blue = 0xADD8E6, // rgb(173,216,230)
- light_coral = 0xF08080, // rgb(240,128,128)
- light_cyan = 0xE0FFFF, // rgb(224,255,255)
- light_golden_rod_yellow = 0xFAFAD2, // rgb(250,250,210)
- light_gray = 0xD3D3D3, // rgb(211,211,211)
- light_green = 0x90EE90, // rgb(144,238,144)
- light_pink = 0xFFB6C1, // rgb(255,182,193)
- light_salmon = 0xFFA07A, // rgb(255,160,122)
- light_sea_green = 0x20B2AA, // rgb(32,178,170)
- light_sky_blue = 0x87CEFA, // rgb(135,206,250)
- light_slate_gray = 0x778899, // rgb(119,136,153)
- light_steel_blue = 0xB0C4DE, // rgb(176,196,222)
- light_yellow = 0xFFFFE0, // rgb(255,255,224)
- lime = 0x00FF00, // rgb(0,255,0)
- lime_green = 0x32CD32, // rgb(50,205,50)
- linen = 0xFAF0E6, // rgb(250,240,230)
- magenta = 0xFF00FF, // rgb(255,0,255)
- maroon = 0x800000, // rgb(128,0,0)
- medium_aquamarine = 0x66CDAA, // rgb(102,205,170)
- medium_blue = 0x0000CD, // rgb(0,0,205)
- medium_orchid = 0xBA55D3, // rgb(186,85,211)
- medium_purple = 0x9370DB, // rgb(147,112,219)
- medium_sea_green = 0x3CB371, // rgb(60,179,113)
- medium_slate_blue = 0x7B68EE, // rgb(123,104,238)
- medium_spring_green = 0x00FA9A, // rgb(0,250,154)
- medium_turquoise = 0x48D1CC, // rgb(72,209,204)
- medium_violet_red = 0xC71585, // rgb(199,21,133)
- midnight_blue = 0x191970, // rgb(25,25,112)
- mint_cream = 0xF5FFFA, // rgb(245,255,250)
- misty_rose = 0xFFE4E1, // rgb(255,228,225)
- moccasin = 0xFFE4B5, // rgb(255,228,181)
- navajo_white = 0xFFDEAD, // rgb(255,222,173)
- navy = 0x000080, // rgb(0,0,128)
- old_lace = 0xFDF5E6, // rgb(253,245,230)
- olive = 0x808000, // rgb(128,128,0)
- olive_drab = 0x6B8E23, // rgb(107,142,35)
- orange = 0xFFA500, // rgb(255,165,0)
- orange_red = 0xFF4500, // rgb(255,69,0)
- orchid = 0xDA70D6, // rgb(218,112,214)
- pale_golden_rod = 0xEEE8AA, // rgb(238,232,170)
- pale_green = 0x98FB98, // rgb(152,251,152)
- pale_turquoise = 0xAFEEEE, // rgb(175,238,238)
- pale_violet_red = 0xDB7093, // rgb(219,112,147)
- papaya_whip = 0xFFEFD5, // rgb(255,239,213)
- peach_puff = 0xFFDAB9, // rgb(255,218,185)
- peru = 0xCD853F, // rgb(205,133,63)
- pink = 0xFFC0CB, // rgb(255,192,203)
- plum = 0xDDA0DD, // rgb(221,160,221)
- powder_blue = 0xB0E0E6, // rgb(176,224,230)
- purple = 0x800080, // rgb(128,0,128)
- rebecca_purple = 0x663399, // rgb(102,51,153)
- red = 0xFF0000, // rgb(255,0,0)
- rosy_brown = 0xBC8F8F, // rgb(188,143,143)
- royal_blue = 0x4169E1, // rgb(65,105,225)
- saddle_brown = 0x8B4513, // rgb(139,69,19)
- salmon = 0xFA8072, // rgb(250,128,114)
- sandy_brown = 0xF4A460, // rgb(244,164,96)
- sea_green = 0x2E8B57, // rgb(46,139,87)
- sea_shell = 0xFFF5EE, // rgb(255,245,238)
- sienna = 0xA0522D, // rgb(160,82,45)
- silver = 0xC0C0C0, // rgb(192,192,192)
- sky_blue = 0x87CEEB, // rgb(135,206,235)
- slate_blue = 0x6A5ACD, // rgb(106,90,205)
- slate_gray = 0x708090, // rgb(112,128,144)
- snow = 0xFFFAFA, // rgb(255,250,250)
- spring_green = 0x00FF7F, // rgb(0,255,127)
- steel_blue = 0x4682B4, // rgb(70,130,180)
- tan = 0xD2B48C, // rgb(210,180,140)
- teal = 0x008080, // rgb(0,128,128)
- thistle = 0xD8BFD8, // rgb(216,191,216)
- tomato = 0xFF6347, // rgb(255,99,71)
- turquoise = 0x40E0D0, // rgb(64,224,208)
- violet = 0xEE82EE, // rgb(238,130,238)
- wheat = 0xF5DEB3, // rgb(245,222,179)
- white = 0xFFFFFF, // rgb(255,255,255)
- white_smoke = 0xF5F5F5, // rgb(245,245,245)
- yellow = 0xFFFF00, // rgb(255,255,0)
- yellow_green = 0x9ACD32 // rgb(154,205,50)
-}; // enum class color
+ alice_blue = 0xF0F8FF, // rgb(240,248,255)
+ antique_white = 0xFAEBD7, // rgb(250,235,215)
+ aqua = 0x00FFFF, // rgb(0,255,255)
+ aquamarine = 0x7FFFD4, // rgb(127,255,212)
+ azure = 0xF0FFFF, // rgb(240,255,255)
+ beige = 0xF5F5DC, // rgb(245,245,220)
+ bisque = 0xFFE4C4, // rgb(255,228,196)
+ black = 0x000000, // rgb(0,0,0)
+ blanched_almond = 0xFFEBCD, // rgb(255,235,205)
+ blue = 0x0000FF, // rgb(0,0,255)
+ blue_violet = 0x8A2BE2, // rgb(138,43,226)
+ brown = 0xA52A2A, // rgb(165,42,42)
+ burly_wood = 0xDEB887, // rgb(222,184,135)
+ cadet_blue = 0x5F9EA0, // rgb(95,158,160)
+ chartreuse = 0x7FFF00, // rgb(127,255,0)
+ chocolate = 0xD2691E, // rgb(210,105,30)
+ coral = 0xFF7F50, // rgb(255,127,80)
+ cornflower_blue = 0x6495ED, // rgb(100,149,237)
+ cornsilk = 0xFFF8DC, // rgb(255,248,220)
+ crimson = 0xDC143C, // rgb(220,20,60)
+ cyan = 0x00FFFF, // rgb(0,255,255)
+ dark_blue = 0x00008B, // rgb(0,0,139)
+ dark_cyan = 0x008B8B, // rgb(0,139,139)
+ dark_golden_rod = 0xB8860B, // rgb(184,134,11)
+ dark_gray = 0xA9A9A9, // rgb(169,169,169)
+ dark_green = 0x006400, // rgb(0,100,0)
+ dark_khaki = 0xBDB76B, // rgb(189,183,107)
+ dark_magenta = 0x8B008B, // rgb(139,0,139)
+ dark_olive_green = 0x556B2F, // rgb(85,107,47)
+ dark_orange = 0xFF8C00, // rgb(255,140,0)
+ dark_orchid = 0x9932CC, // rgb(153,50,204)
+ dark_red = 0x8B0000, // rgb(139,0,0)
+ dark_salmon = 0xE9967A, // rgb(233,150,122)
+ dark_sea_green = 0x8FBC8F, // rgb(143,188,143)
+ dark_slate_blue = 0x483D8B, // rgb(72,61,139)
+ dark_slate_gray = 0x2F4F4F, // rgb(47,79,79)
+ dark_turquoise = 0x00CED1, // rgb(0,206,209)
+ dark_violet = 0x9400D3, // rgb(148,0,211)
+ deep_pink = 0xFF1493, // rgb(255,20,147)
+ deep_sky_blue = 0x00BFFF, // rgb(0,191,255)
+ dim_gray = 0x696969, // rgb(105,105,105)
+ dodger_blue = 0x1E90FF, // rgb(30,144,255)
+ fire_brick = 0xB22222, // rgb(178,34,34)
+ floral_white = 0xFFFAF0, // rgb(255,250,240)
+ forest_green = 0x228B22, // rgb(34,139,34)
+ fuchsia = 0xFF00FF, // rgb(255,0,255)
+ gainsboro = 0xDCDCDC, // rgb(220,220,220)
+ ghost_white = 0xF8F8FF, // rgb(248,248,255)
+ gold = 0xFFD700, // rgb(255,215,0)
+ golden_rod = 0xDAA520, // rgb(218,165,32)
+ gray = 0x808080, // rgb(128,128,128)
+ green = 0x008000, // rgb(0,128,0)
+ green_yellow = 0xADFF2F, // rgb(173,255,47)
+ honey_dew = 0xF0FFF0, // rgb(240,255,240)
+ hot_pink = 0xFF69B4, // rgb(255,105,180)
+ indian_red = 0xCD5C5C, // rgb(205,92,92)
+ indigo = 0x4B0082, // rgb(75,0,130)
+ ivory = 0xFFFFF0, // rgb(255,255,240)
+ khaki = 0xF0E68C, // rgb(240,230,140)
+ lavender = 0xE6E6FA, // rgb(230,230,250)
+ lavender_blush = 0xFFF0F5, // rgb(255,240,245)
+ lawn_green = 0x7CFC00, // rgb(124,252,0)
+ lemon_chiffon = 0xFFFACD, // rgb(255,250,205)
+ light_blue = 0xADD8E6, // rgb(173,216,230)
+ light_coral = 0xF08080, // rgb(240,128,128)
+ light_cyan = 0xE0FFFF, // rgb(224,255,255)
+ light_golden_rod_yellow = 0xFAFAD2, // rgb(250,250,210)
+ light_gray = 0xD3D3D3, // rgb(211,211,211)
+ light_green = 0x90EE90, // rgb(144,238,144)
+ light_pink = 0xFFB6C1, // rgb(255,182,193)
+ light_salmon = 0xFFA07A, // rgb(255,160,122)
+ light_sea_green = 0x20B2AA, // rgb(32,178,170)
+ light_sky_blue = 0x87CEFA, // rgb(135,206,250)
+ light_slate_gray = 0x778899, // rgb(119,136,153)
+ light_steel_blue = 0xB0C4DE, // rgb(176,196,222)
+ light_yellow = 0xFFFFE0, // rgb(255,255,224)
+ lime = 0x00FF00, // rgb(0,255,0)
+ lime_green = 0x32CD32, // rgb(50,205,50)
+ linen = 0xFAF0E6, // rgb(250,240,230)
+ magenta = 0xFF00FF, // rgb(255,0,255)
+ maroon = 0x800000, // rgb(128,0,0)
+ medium_aquamarine = 0x66CDAA, // rgb(102,205,170)
+ medium_blue = 0x0000CD, // rgb(0,0,205)
+ medium_orchid = 0xBA55D3, // rgb(186,85,211)
+ medium_purple = 0x9370DB, // rgb(147,112,219)
+ medium_sea_green = 0x3CB371, // rgb(60,179,113)
+ medium_slate_blue = 0x7B68EE, // rgb(123,104,238)
+ medium_spring_green = 0x00FA9A, // rgb(0,250,154)
+ medium_turquoise = 0x48D1CC, // rgb(72,209,204)
+ medium_violet_red = 0xC71585, // rgb(199,21,133)
+ midnight_blue = 0x191970, // rgb(25,25,112)
+ mint_cream = 0xF5FFFA, // rgb(245,255,250)
+ misty_rose = 0xFFE4E1, // rgb(255,228,225)
+ moccasin = 0xFFE4B5, // rgb(255,228,181)
+ navajo_white = 0xFFDEAD, // rgb(255,222,173)
+ navy = 0x000080, // rgb(0,0,128)
+ old_lace = 0xFDF5E6, // rgb(253,245,230)
+ olive = 0x808000, // rgb(128,128,0)
+ olive_drab = 0x6B8E23, // rgb(107,142,35)
+ orange = 0xFFA500, // rgb(255,165,0)
+ orange_red = 0xFF4500, // rgb(255,69,0)
+ orchid = 0xDA70D6, // rgb(218,112,214)
+ pale_golden_rod = 0xEEE8AA, // rgb(238,232,170)
+ pale_green = 0x98FB98, // rgb(152,251,152)
+ pale_turquoise = 0xAFEEEE, // rgb(175,238,238)
+ pale_violet_red = 0xDB7093, // rgb(219,112,147)
+ papaya_whip = 0xFFEFD5, // rgb(255,239,213)
+ peach_puff = 0xFFDAB9, // rgb(255,218,185)
+ peru = 0xCD853F, // rgb(205,133,63)
+ pink = 0xFFC0CB, // rgb(255,192,203)
+ plum = 0xDDA0DD, // rgb(221,160,221)
+ powder_blue = 0xB0E0E6, // rgb(176,224,230)
+ purple = 0x800080, // rgb(128,0,128)
+ rebecca_purple = 0x663399, // rgb(102,51,153)
+ red = 0xFF0000, // rgb(255,0,0)
+ rosy_brown = 0xBC8F8F, // rgb(188,143,143)
+ royal_blue = 0x4169E1, // rgb(65,105,225)
+ saddle_brown = 0x8B4513, // rgb(139,69,19)
+ salmon = 0xFA8072, // rgb(250,128,114)
+ sandy_brown = 0xF4A460, // rgb(244,164,96)
+ sea_green = 0x2E8B57, // rgb(46,139,87)
+ sea_shell = 0xFFF5EE, // rgb(255,245,238)
+ sienna = 0xA0522D, // rgb(160,82,45)
+ silver = 0xC0C0C0, // rgb(192,192,192)
+ sky_blue = 0x87CEEB, // rgb(135,206,235)
+ slate_blue = 0x6A5ACD, // rgb(106,90,205)
+ slate_gray = 0x708090, // rgb(112,128,144)
+ snow = 0xFFFAFA, // rgb(255,250,250)
+ spring_green = 0x00FF7F, // rgb(0,255,127)
+ steel_blue = 0x4682B4, // rgb(70,130,180)
+ tan = 0xD2B48C, // rgb(210,180,140)
+ teal = 0x008080, // rgb(0,128,128)
+ thistle = 0xD8BFD8, // rgb(216,191,216)
+ tomato = 0xFF6347, // rgb(255,99,71)
+ turquoise = 0x40E0D0, // rgb(64,224,208)
+ violet = 0xEE82EE, // rgb(238,130,238)
+ wheat = 0xF5DEB3, // rgb(245,222,179)
+ white = 0xFFFFFF, // rgb(255,255,255)
+ white_smoke = 0xF5F5F5, // rgb(245,245,245)
+ yellow = 0xFFFF00, // rgb(255,255,0)
+ yellow_green = 0x9ACD32 // rgb(154,205,50)
+}; // enum class color
enum class terminal_color : uint8_t {
black = 30,
@@ -208,27 +173,26 @@
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.
+// Using the name "rgb" makes some editors show the color in a tooltip.
struct rgb {
- FMT_CONSTEXPR_DECL rgb() : r(0), g(0), b(0) {}
- FMT_CONSTEXPR_DECL rgb(uint8_t r_, uint8_t g_, uint8_t b_)
- : r(r_), g(g_), b(b_) {}
- FMT_CONSTEXPR_DECL rgb(uint32_t hex)
- : r((hex >> 16) & 0xFF), g((hex >> 8) & 0xFF), b((hex) & 0xFF) {}
- FMT_CONSTEXPR_DECL rgb(color hex)
- : r((uint32_t(hex) >> 16) & 0xFF), g((uint32_t(hex) >> 8) & 0xFF),
- b(uint32_t(hex) & 0xFF) {}
+ FMT_CONSTEXPR rgb() : r(0), g(0), b(0) {}
+ FMT_CONSTEXPR rgb(uint8_t r_, uint8_t g_, uint8_t b_) : r(r_), g(g_), b(b_) {}
+ FMT_CONSTEXPR rgb(uint32_t hex)
+ : r((hex >> 16) & 0xFF), g((hex >> 8) & 0xFF), b(hex & 0xFF) {}
+ FMT_CONSTEXPR rgb(color hex)
+ : r((uint32_t(hex) >> 16) & 0xFF),
+ g((uint32_t(hex) >> 8) & 0xFF),
+ b(uint32_t(hex) & 0xFF) {}
uint8_t r;
uint8_t g;
uint8_t b;
@@ -238,19 +202,17 @@
// 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{} {
+ FMT_CONSTEXPR color_type() FMT_NOEXCEPT : is_rgb(), value{} {}
+ FMT_CONSTEXPR color_type(color rgb_color) FMT_NOEXCEPT : is_rgb(true),
+ value{} {
value.rgb_color = static_cast<uint32_t>(rgb_color);
}
- FMT_CONSTEXPR color_type(rgb rgb_color) FMT_NOEXCEPT
- : is_rgb(true), value{} {
- value.rgb_color = (static_cast<uint32_t>(rgb_color.r) << 16)
- | (static_cast<uint32_t>(rgb_color.g) << 8) | rgb_color.b;
+ FMT_CONSTEXPR color_type(rgb rgb_color) FMT_NOEXCEPT : is_rgb(true), value{} {
+ value.rgb_color = (static_cast<uint32_t>(rgb_color.r) << 16) |
+ (static_cast<uint32_t>(rgb_color.g) << 8) | rgb_color.b;
}
- FMT_CONSTEXPR color_type(terminal_color term_color) FMT_NOEXCEPT
- : is_rgb(), value{} {
+ FMT_CONSTEXPR color_type(terminal_color term_color) FMT_NOEXCEPT : is_rgb(),
+ value{} {
value.term_color = static_cast<uint8_t>(term_color);
}
bool is_rgb;
@@ -259,21 +221,23 @@
uint32_t rgb_color;
} value;
};
-} // namespace internal
+} // namespace internal
// 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) {}
+ : set_foreground_color(),
+ set_background_color(),
+ ems(em) {}
- FMT_CONSTEXPR text_style &operator|=(const text_style &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 OR a terminal color");
+ FMT_THROW(format_error("can't OR a terminal color"));
foreground_color.value.rgb_color |= rhs.foreground_color.value.rgb_color;
}
@@ -282,7 +246,7 @@
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");
+ FMT_THROW(format_error("can't OR a terminal color"));
background_color.value.rgb_color |= rhs.background_color.value.rgb_color;
}
@@ -291,18 +255,18 @@
return *this;
}
- friend FMT_CONSTEXPR
- text_style operator|(text_style lhs, const text_style &rhs) {
+ 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) {
+ 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");
+ FMT_THROW(format_error("can't AND a terminal color"));
foreground_color.value.rgb_color &= rhs.foreground_color.value.rgb_color;
}
@@ -311,7 +275,7 @@
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");
+ FMT_THROW(format_error("can't AND a terminal color"));
background_color.value.rgb_color &= rhs.background_color.value.rgb_color;
}
@@ -320,8 +284,8 @@
return *this;
}
- friend FMT_CONSTEXPR
- text_style operator&(text_style lhs, const text_style &rhs) {
+ friend FMT_CONSTEXPR text_style operator&(text_style lhs,
+ const text_style& rhs) {
return lhs &= rhs;
}
@@ -347,20 +311,20 @@
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;
- }
- }
+ 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;
@@ -388,19 +352,17 @@
namespace internal {
-template <typename Char>
-struct ansi_color_escape {
+template <typename Char> struct ansi_color_escape {
FMT_CONSTEXPR ansi_color_escape(internal::color_type text_color,
- const char * esc) FMT_NOEXCEPT {
+ 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;
+ 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;
+ if (is_background) value += 10u;
std::size_t index = 0;
buffer[index++] = static_cast<Char>('\x1b');
@@ -422,7 +384,7 @@
buffer[i] = static_cast<Char>(esc[i]);
}
rgb color(text_color.value.rgb_color);
- to_esc(color.r, buffer + 7, ';');
+ to_esc(color.r, buffer + 7, ';');
to_esc(color.g, buffer + 11, ';');
to_esc(color.b, buffer + 15, 'm');
buffer[19] = static_cast<Char>(0);
@@ -430,19 +392,15 @@
FMT_CONSTEXPR ansi_color_escape(emphasis em) FMT_NOEXCEPT {
uint8_t em_codes[4] = {};
uint8_t em_bits = static_cast<uint8_t>(em);
- if (em_bits & static_cast<uint8_t>(emphasis::bold))
- em_codes[0] = 1;
- if (em_bits & static_cast<uint8_t>(emphasis::italic))
- em_codes[1] = 3;
- if (em_bits & static_cast<uint8_t>(emphasis::underline))
- em_codes[2] = 4;
+ if (em_bits & static_cast<uint8_t>(emphasis::bold)) em_codes[0] = 1;
+ if (em_bits & static_cast<uint8_t>(emphasis::italic)) em_codes[1] = 3;
+ if (em_bits & static_cast<uint8_t>(emphasis::underline)) em_codes[2] = 4;
if (em_bits & static_cast<uint8_t>(emphasis::strikethrough))
em_codes[3] = 9;
std::size_t index = 0;
for (int i = 0; i < 4; ++i) {
- if (!em_codes[i])
- continue;
+ if (!em_codes[i]) continue;
buffer[index++] = static_cast<Char>('\x1b');
buffer[index++] = static_cast<Char>('[');
buffer[index++] = static_cast<Char>('0' + em_codes[i]);
@@ -450,12 +408,17 @@
}
buffer[index++] = static_cast<Char>(0);
}
- FMT_CONSTEXPR operator const Char *() const FMT_NOEXCEPT { return buffer; }
+ FMT_CONSTEXPR operator const Char*() const FMT_NOEXCEPT { return buffer; }
-private:
+ FMT_CONSTEXPR const Char* begin() const FMT_NOEXCEPT { return buffer; }
+ FMT_CONSTEXPR const Char* end() const FMT_NOEXCEPT {
+ return buffer + std::strlen(buffer);
+ }
+
+ private:
Char buffer[7u + 3u * 4u + 1u];
- static FMT_CONSTEXPR void to_esc(uint8_t c, Char *out,
+ static FMT_CONSTEXPR void to_esc(uint8_t c, Char* out,
char delimiter) FMT_NOEXCEPT {
out[0] = static_cast<Char>('0' + c / 100);
out[1] = static_cast<Char>('0' + c / 10 % 10);
@@ -465,67 +428,90 @@
};
template <typename Char>
-FMT_CONSTEXPR ansi_color_escape<Char>
-make_foreground_color(internal::color_type foreground) FMT_NOEXCEPT {
- return ansi_color_escape<Char>(foreground, internal::data::FOREGROUND_COLOR);
+FMT_CONSTEXPR ansi_color_escape<Char> make_foreground_color(
+ internal::color_type foreground) FMT_NOEXCEPT {
+ return ansi_color_escape<Char>(foreground, internal::data::foreground_color);
}
template <typename Char>
-FMT_CONSTEXPR ansi_color_escape<Char>
-make_background_color(internal::color_type background) FMT_NOEXCEPT {
- return ansi_color_escape<Char>(background, internal::data::BACKGROUND_COLOR);
+FMT_CONSTEXPR ansi_color_escape<Char> make_background_color(
+ internal::color_type background) FMT_NOEXCEPT {
+ return ansi_color_escape<Char>(background, internal::data::background_color);
}
template <typename Char>
-FMT_CONSTEXPR ansi_color_escape<Char>
-make_emphasis(emphasis em) FMT_NOEXCEPT {
+FMT_CONSTEXPR ansi_color_escape<Char> make_emphasis(emphasis em) FMT_NOEXCEPT {
return ansi_color_escape<Char>(em);
}
template <typename Char>
-inline void fputs(const Char *chars, FILE *stream) FMT_NOEXCEPT {
+inline void fputs(const Char* chars, FILE* stream) FMT_NOEXCEPT {
std::fputs(chars, stream);
}
template <>
-inline void fputs<wchar_t>(const wchar_t *chars, FILE *stream) FMT_NOEXCEPT {
+inline void fputs<wchar_t>(const wchar_t* chars, FILE* stream) FMT_NOEXCEPT {
std::fputws(chars, stream);
}
+template <typename Char> inline void reset_color(FILE* stream) FMT_NOEXCEPT {
+ fputs(internal::data::reset_color, stream);
+}
+
+template <> inline void reset_color<wchar_t>(FILE* stream) FMT_NOEXCEPT {
+ fputs(internal::data::wreset_color, stream);
+}
+
template <typename Char>
-inline void reset_color(FILE *stream) FMT_NOEXCEPT {
- fputs(internal::data::RESET_COLOR, stream);
+inline void reset_color(basic_memory_buffer<Char>& buffer) FMT_NOEXCEPT {
+ const char* begin = data::reset_color;
+ const char* end = begin + sizeof(data::reset_color) - 1;
+ buffer.append(begin, end);
}
-template <>
-inline void reset_color<wchar_t>(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::FILE *> : std::false_type {};
-template <>
-struct is_string<const std::FILE *> : std::false_type {};
-} // namespace internal
-
-template <
- typename S, typename Char = typename internal::char_t<S>::type>
-void vprint(std::FILE *f, const text_style &ts, const S &format,
- basic_format_args<typename buffer_context<Char>::type> args) {
+template <typename Char>
+std::basic_string<Char> vformat(const text_style& ts,
+ basic_string_view<Char> format_str,
+ basic_format_args<buffer_context<Char> > args) {
+ basic_memory_buffer<Char> buffer;
bool has_style = false;
if (ts.has_emphasis()) {
has_style = true;
- internal::fputs<Char>(
- internal::make_emphasis<Char>(ts.get_emphasis()), f);
+ ansi_color_escape<Char> escape = make_emphasis<Char>(ts.get_emphasis());
+ buffer.append(escape.begin(), escape.end());
+ }
+ if (ts.has_foreground()) {
+ has_style = true;
+ ansi_color_escape<Char> escape =
+ make_foreground_color<Char>(ts.get_foreground());
+ buffer.append(escape.begin(), escape.end());
+ }
+ if (ts.has_background()) {
+ has_style = true;
+ ansi_color_escape<Char> escape =
+ make_background_color<Char>(ts.get_background());
+ buffer.append(escape.begin(), escape.end());
+ }
+ internal::vformat_to(buffer, format_str, args);
+ if (has_style) {
+ reset_color<Char>(buffer);
+ }
+ return fmt::to_string(buffer);
+}
+} // namespace internal
+
+template <typename S, typename Char = char_t<S> >
+void vprint(std::FILE* f, const text_style& ts, const S& format,
+ basic_format_args<buffer_context<Char> > args) {
+ bool has_style = false;
+ if (ts.has_emphasis()) {
+ has_style = true;
+ internal::fputs<Char>(internal::make_emphasis<Char>(ts.get_emphasis()), f);
}
if (ts.has_foreground()) {
has_style = true;
internal::fputs<Char>(
- internal::make_foreground_color<Char>(ts.get_foreground()), f);
+ internal::make_foreground_color<Char>(ts.get_foreground()), f);
}
if (ts.has_background()) {
has_style = true;
@@ -545,15 +531,14 @@
fmt::print(fmt::emphasis::bold | fg(fmt::color::red),
"Elapsed time: {0:.2f} seconds", 1.23);
*/
-template <typename String, typename... Args>
-typename std::enable_if<internal::is_string<String>::value>::type print(
- std::FILE *f, const text_style &ts, const String &format_str,
- const Args &... args) {
+template <typename S, typename... Args,
+ FMT_ENABLE_IF(internal::is_string<S>::value)>
+void print(std::FILE* f, const text_style& ts, const S& format_str,
+ const Args&... args) {
internal::check_format_string<Args...>(format_str);
- typedef typename internal::char_t<String>::type char_t;
- typedef typename buffer_context<char_t>::type context_t;
- format_arg_store<context_t, Args...> as{args...};
- vprint(f, ts, format_str, basic_format_args<context_t>(as));
+ using context = buffer_context<char_t<S> >;
+ format_arg_store<context, Args...> as{args...};
+ vprint(f, ts, format_str, basic_format_args<context>(as));
}
/**
@@ -563,14 +548,37 @@
fmt::print(fmt::emphasis::bold | fg(fmt::color::red),
"Elapsed time: {0:.2f} seconds", 1.23);
*/
-template <typename String, typename... Args>
-typename std::enable_if<internal::is_string<String>::value>::type print(
- const text_style &ts, const String &format_str,
- const Args &... args) {
+template <typename S, typename... Args,
+ FMT_ENABLE_IF(internal::is_string<S>::value)>
+void print(const text_style& ts, const S& format_str, const Args&... args) {
return print(stdout, ts, format_str, args...);
}
-#endif
+template <typename S, typename Char = char_t<S> >
+inline std::basic_string<Char> vformat(
+ const text_style& ts, const S& format_str,
+ basic_format_args<buffer_context<Char> > args) {
+ return internal::vformat(ts, to_string_view(format_str), args);
+}
+
+/**
+ \rst
+ Formats arguments and returns the result as a string using ANSI
+ escape sequences to specify text formatting.
+
+ **Example**::
+
+ #include <fmt/color.h>
+ std::string message = fmt::format(fmt::emphasis::bold | fg(fmt::color::red),
+ "The answer is {}", 42);
+ \endrst
+*/
+template <typename S, typename... Args, typename Char = char_t<S> >
+inline std::basic_string<Char> format(const text_style& ts, const S& format_str,
+ const Args&... args) {
+ return internal::vformat(ts, to_string_view(format_str),
+ {internal::make_args_checked(format_str, args...)});
+}
FMT_END_NAMESPACE
diff --git a/include/fmt/compile.h b/include/fmt/compile.h
new file mode 100644
index 0000000..82625bb
--- /dev/null
+++ b/include/fmt/compile.h
@@ -0,0 +1,466 @@
+// Formatting library for C++ - experimental format string compilation
+//
+// Copyright (c) 2012 - present, Victor Zverovich and fmt contributors
+// All rights reserved.
+//
+// For the license information refer to format.h.
+
+#ifndef FMT_COMPILE_H_
+#define FMT_COMPILE_H_
+
+#include <vector>
+#include "format.h"
+
+FMT_BEGIN_NAMESPACE
+namespace internal {
+
+template <typename Char> struct format_part {
+ public:
+ struct named_argument_id {
+ FMT_CONSTEXPR named_argument_id(internal::string_view_metadata id)
+ : id(id) {}
+ internal::string_view_metadata id;
+ };
+
+ struct argument_id {
+ FMT_CONSTEXPR argument_id() : argument_id(0u) {}
+
+ FMT_CONSTEXPR argument_id(unsigned id)
+ : which(which_arg_id::index), val(id) {}
+
+ FMT_CONSTEXPR argument_id(internal::string_view_metadata id)
+ : which(which_arg_id::named_index), val(id) {}
+
+ enum class which_arg_id { index, named_index };
+
+ which_arg_id which;
+
+ union value {
+ FMT_CONSTEXPR value() : index(0u) {}
+ FMT_CONSTEXPR value(unsigned id) : index(id) {}
+ FMT_CONSTEXPR value(internal::string_view_metadata id)
+ : named_index(id) {}
+
+ unsigned index;
+ internal::string_view_metadata named_index;
+ } val;
+ };
+
+ struct specification {
+ FMT_CONSTEXPR specification() : arg_id(0u) {}
+ FMT_CONSTEXPR specification(unsigned id) : arg_id(id) {}
+
+ FMT_CONSTEXPR specification(internal::string_view_metadata id)
+ : arg_id(id) {}
+
+ argument_id arg_id;
+ internal::dynamic_format_specs<Char> parsed_specs;
+ };
+
+ FMT_CONSTEXPR format_part()
+ : which(kind::argument_id), end_of_argument_id(0u), val(0u) {}
+
+ FMT_CONSTEXPR format_part(internal::string_view_metadata text)
+ : which(kind::text), end_of_argument_id(0u), val(text) {}
+
+ FMT_CONSTEXPR format_part(unsigned id)
+ : which(kind::argument_id), end_of_argument_id(0u), val(id) {}
+
+ FMT_CONSTEXPR format_part(named_argument_id arg_id)
+ : which(kind::named_argument_id), end_of_argument_id(0u), val(arg_id) {}
+
+ FMT_CONSTEXPR format_part(specification spec)
+ : which(kind::specification), end_of_argument_id(0u), val(spec) {}
+
+ enum class kind { argument_id, named_argument_id, text, specification };
+
+ kind which;
+ std::size_t end_of_argument_id;
+ union value {
+ FMT_CONSTEXPR value() : arg_id(0u) {}
+ FMT_CONSTEXPR value(unsigned id) : arg_id(id) {}
+ FMT_CONSTEXPR value(named_argument_id named_id)
+ : named_arg_id(named_id.id) {}
+ FMT_CONSTEXPR value(internal::string_view_metadata t) : text(t) {}
+ FMT_CONSTEXPR value(specification s) : spec(s) {}
+ unsigned arg_id;
+ internal::string_view_metadata named_arg_id;
+ internal::string_view_metadata text;
+ specification spec;
+ } val;
+};
+
+template <typename Char, typename PartsContainer>
+class format_preparation_handler : public internal::error_handler {
+ private:
+ using part = format_part<Char>;
+
+ public:
+ using iterator = typename basic_string_view<Char>::iterator;
+
+ FMT_CONSTEXPR format_preparation_handler(basic_string_view<Char> format,
+ PartsContainer& parts)
+ : parts_(parts), format_(format), parse_context_(format) {}
+
+ FMT_CONSTEXPR void on_text(const Char* begin, const Char* end) {
+ if (begin == end) return;
+ const auto offset = begin - format_.data();
+ const auto size = end - begin;
+ parts_.push_back(part(string_view_metadata(offset, size)));
+ }
+
+ FMT_CONSTEXPR void on_arg_id() {
+ parts_.push_back(part(parse_context_.next_arg_id()));
+ }
+
+ FMT_CONSTEXPR void on_arg_id(unsigned id) {
+ parse_context_.check_arg_id(id);
+ parts_.push_back(part(id));
+ }
+
+ FMT_CONSTEXPR void on_arg_id(basic_string_view<Char> id) {
+ const auto view = string_view_metadata(format_, id);
+ const auto arg_id = typename part::named_argument_id(view);
+ parts_.push_back(part(arg_id));
+ }
+
+ FMT_CONSTEXPR void on_replacement_field(const Char* ptr) {
+ parts_.back().end_of_argument_id = ptr - format_.begin();
+ }
+
+ FMT_CONSTEXPR const Char* on_format_specs(const Char* begin,
+ const Char* end) {
+ const auto specs_offset = to_unsigned(begin - format_.begin());
+
+ using parse_context = basic_parse_context<Char>;
+ internal::dynamic_format_specs<Char> parsed_specs;
+ dynamic_specs_handler<parse_context> handler(parsed_specs, parse_context_);
+ begin = parse_format_specs(begin, end, handler);
+
+ if (*begin != '}') on_error("missing '}' in format string");
+
+ auto& last_part = parts_.back();
+ auto specs = last_part.which == part::kind::argument_id
+ ? typename part::specification(last_part.val.arg_id)
+ : typename part::specification(last_part.val.named_arg_id);
+ specs.parsed_specs = parsed_specs;
+ last_part = part(specs);
+ last_part.end_of_argument_id = specs_offset;
+ return begin;
+ }
+
+ private:
+ PartsContainer& parts_;
+ basic_string_view<Char> format_;
+ basic_parse_context<Char> parse_context_;
+};
+
+template <typename Format, typename PreparedPartsProvider, typename... Args>
+class prepared_format {
+ public:
+ using char_type = char_t<Format>;
+ using format_part_t = format_part<char_type>;
+
+ constexpr prepared_format(Format f)
+ : format_(std::move(f)), parts_provider_(to_string_view(format_)) {}
+
+ prepared_format() = delete;
+
+ using context = buffer_context<char_type>;
+
+ template <typename Range, typename Context>
+ auto vformat_to(Range out, basic_format_args<Context> args) const ->
+ typename Context::iterator {
+ const auto format_view = internal::to_string_view(format_);
+ basic_parse_context<char_type> parse_ctx(format_view);
+ Context ctx(out.begin(), args);
+
+ const auto& parts = parts_provider_.parts();
+ for (auto part_it = parts.begin(); part_it != parts.end(); ++part_it) {
+ const auto& part = *part_it;
+ const auto& value = part.val;
+
+ switch (part.which) {
+ case format_part_t::kind::text: {
+ const auto text = value.text.to_view(format_view.data());
+ auto output = ctx.out();
+ auto&& it = internal::reserve(output, text.size());
+ it = std::copy_n(text.begin(), text.size(), it);
+ ctx.advance_to(output);
+ } break;
+
+ case format_part_t::kind::argument_id: {
+ advance_parse_context_to_specification(parse_ctx, part);
+ format_arg<Range>(parse_ctx, ctx, value.arg_id);
+ } break;
+
+ case format_part_t::kind::named_argument_id: {
+ advance_parse_context_to_specification(parse_ctx, part);
+ const auto named_arg_id =
+ value.named_arg_id.to_view(format_view.data());
+ format_arg<Range>(parse_ctx, ctx, named_arg_id);
+ } break;
+ case format_part_t::kind::specification: {
+ const auto& arg_id_value = value.spec.arg_id.val;
+ const auto arg = value.spec.arg_id.which ==
+ format_part_t::argument_id::which_arg_id::index
+ ? ctx.arg(arg_id_value.index)
+ : ctx.arg(arg_id_value.named_index.to_view(
+ to_string_view(format_).data()));
+
+ auto specs = value.spec.parsed_specs;
+
+ handle_dynamic_spec<internal::width_checker>(
+ specs.width, specs.width_ref, ctx, format_view.begin());
+ handle_dynamic_spec<internal::precision_checker>(
+ specs.precision, specs.precision_ref, ctx, format_view.begin());
+
+ check_prepared_specs(specs, arg.type());
+ advance_parse_context_to_specification(parse_ctx, part);
+ ctx.advance_to(
+ visit_format_arg(arg_formatter<Range>(ctx, nullptr, &specs), arg));
+ } break;
+ }
+ }
+
+ return ctx.out();
+ }
+
+ private:
+ void advance_parse_context_to_specification(
+ basic_parse_context<char_type>& parse_ctx,
+ const format_part_t& part) const {
+ const auto view = to_string_view(format_);
+ const auto specification_begin = view.data() + part.end_of_argument_id;
+ advance_to(parse_ctx, specification_begin);
+ }
+
+ template <typename Range, typename Context, typename Id>
+ void format_arg(basic_parse_context<char_type>& parse_ctx, Context& ctx,
+ Id arg_id) const {
+ parse_ctx.check_arg_id(arg_id);
+ const auto stopped_at =
+ visit_format_arg(arg_formatter<Range>(ctx), ctx.arg(arg_id));
+ ctx.advance_to(stopped_at);
+ }
+
+ template <typename Char>
+ void check_prepared_specs(const basic_format_specs<Char>& specs,
+ internal::type arg_type) const {
+ internal::error_handler h;
+ numeric_specs_checker<internal::error_handler> checker(h, arg_type);
+ if (specs.align == align::numeric) checker.require_numeric_argument();
+ if (specs.sign != sign::none) checker.check_sign();
+ if (specs.alt) checker.require_numeric_argument();
+ if (specs.precision >= 0) checker.check_precision();
+ }
+
+ private:
+ Format format_;
+ PreparedPartsProvider parts_provider_;
+};
+
+template <typename Char> struct part_counter {
+ unsigned num_parts = 0;
+
+ FMT_CONSTEXPR void on_text(const Char* begin, const Char* end) {
+ if (begin != end) ++num_parts;
+ }
+
+ FMT_CONSTEXPR void on_arg_id() { ++num_parts; }
+ FMT_CONSTEXPR void on_arg_id(unsigned) { ++num_parts; }
+ FMT_CONSTEXPR void on_arg_id(basic_string_view<Char>) { ++num_parts; }
+
+ FMT_CONSTEXPR void on_replacement_field(const Char*) {}
+
+ FMT_CONSTEXPR const Char* on_format_specs(const Char* begin,
+ const Char* end) {
+ // Find the matching brace.
+ unsigned braces_counter = 0;
+ for (; begin != end; ++begin) {
+ if (*begin == '{') {
+ ++braces_counter;
+ } else if (*begin == '}') {
+ if (braces_counter == 0u) break;
+ --braces_counter;
+ }
+ }
+ return begin;
+ }
+
+ FMT_CONSTEXPR void on_error(const char*) {}
+};
+
+template <typename Format> class compiletime_prepared_parts_type_provider {
+ private:
+ using char_type = char_t<Format>;
+
+ static FMT_CONSTEXPR unsigned count_parts() {
+ FMT_CONSTEXPR_DECL const auto text = to_string_view(Format{});
+ part_counter<char_type> counter;
+ internal::parse_format_string</*IS_CONSTEXPR=*/true>(text, counter);
+ return counter.num_parts;
+ }
+
+// Workaround for old compilers. Compiletime parts preparation will not be
+// performed with them anyway.
+#if FMT_USE_CONSTEXPR
+ static FMT_CONSTEXPR_DECL const unsigned number_of_format_parts =
+ compiletime_prepared_parts_type_provider::count_parts();
+#else
+ static const unsigned number_of_format_parts = 0u;
+#endif
+
+ public:
+ template <unsigned N> struct format_parts_array {
+ using value_type = format_part<char_type>;
+
+ FMT_CONSTEXPR format_parts_array() : arr{} {}
+
+ FMT_CONSTEXPR value_type& operator[](unsigned ind) { return arr[ind]; }
+
+ FMT_CONSTEXPR const value_type* begin() const { return arr; }
+ FMT_CONSTEXPR const value_type* end() const { return begin() + N; }
+
+ private:
+ value_type arr[N];
+ };
+
+ struct empty {
+ // Parts preparator will search for it
+ using value_type = format_part<char_type>;
+ };
+
+ using type = conditional_t<number_of_format_parts != 0,
+ format_parts_array<number_of_format_parts>, empty>;
+};
+
+template <typename Parts> class compiletime_prepared_parts_collector {
+ private:
+ using format_part = typename Parts::value_type;
+
+ public:
+ FMT_CONSTEXPR explicit compiletime_prepared_parts_collector(Parts& parts)
+ : parts_{parts}, counter_{0u} {}
+
+ FMT_CONSTEXPR void push_back(format_part part) { parts_[counter_++] = part; }
+
+ FMT_CONSTEXPR format_part& back() { return parts_[counter_ - 1]; }
+
+ private:
+ Parts& parts_;
+ unsigned counter_;
+};
+
+template <typename PartsContainer, typename Char>
+FMT_CONSTEXPR PartsContainer prepare_parts(basic_string_view<Char> format) {
+ PartsContainer parts;
+ internal::parse_format_string</*IS_CONSTEXPR=*/false>(
+ format, format_preparation_handler<Char, PartsContainer>(format, parts));
+ return parts;
+}
+
+template <typename PartsContainer, typename Char>
+FMT_CONSTEXPR PartsContainer
+prepare_compiletime_parts(basic_string_view<Char> format) {
+ using collector = compiletime_prepared_parts_collector<PartsContainer>;
+
+ PartsContainer parts;
+ collector c(parts);
+ internal::parse_format_string</*IS_CONSTEXPR=*/true>(
+ format, format_preparation_handler<Char, collector>(format, c));
+ return parts;
+}
+
+template <typename PartsContainer> class runtime_parts_provider {
+ public:
+ runtime_parts_provider() = delete;
+ template <typename Char>
+ runtime_parts_provider(basic_string_view<Char> format)
+ : parts_(prepare_parts<PartsContainer>(format)) {}
+
+ const PartsContainer& parts() const { return parts_; }
+
+ private:
+ PartsContainer parts_;
+};
+
+template <typename Format, typename PartsContainer>
+struct compiletime_parts_provider {
+ compiletime_parts_provider() = delete;
+ template <typename Char>
+ FMT_CONSTEXPR compiletime_parts_provider(basic_string_view<Char>) {}
+
+ const PartsContainer& parts() const {
+ static FMT_CONSTEXPR_DECL const PartsContainer prepared_parts =
+ prepare_compiletime_parts<PartsContainer>(
+ internal::to_string_view(Format{}));
+
+ return prepared_parts;
+ }
+};
+} // namespace internal
+
+#if FMT_USE_CONSTEXPR
+template <typename... Args, typename S,
+ FMT_ENABLE_IF(is_compile_string<S>::value)>
+FMT_CONSTEXPR auto compile(S format_str) -> internal::prepared_format<
+ S,
+ internal::compiletime_parts_provider<
+ S,
+ typename internal::compiletime_prepared_parts_type_provider<S>::type>,
+ Args...> {
+ return format_str;
+}
+#endif
+
+template <typename... Args, typename Char, size_t N>
+auto compile(const Char (&format_str)[N]) -> internal::prepared_format<
+ std::basic_string<Char>,
+ internal::runtime_parts_provider<std::vector<internal::format_part<Char>>>,
+ Args...> {
+ return std::basic_string<Char>(format_str, N - 1);
+}
+
+template <typename CompiledFormat, typename... Args,
+ typename Char = typename CompiledFormat::char_type>
+std::basic_string<Char> format(const CompiledFormat& cf, const Args&... args) {
+ basic_memory_buffer<Char> buffer;
+ using range = internal::buffer_range<Char>;
+ using context = buffer_context<Char>;
+ cf.template vformat_to<range, context>(range(buffer),
+ {make_format_args<context>(args...)});
+ return to_string(buffer);
+}
+
+template <typename OutputIt, typename CompiledFormat, typename... Args>
+OutputIt format_to(OutputIt out, const CompiledFormat& cf,
+ const Args&... args) {
+ using char_type = typename CompiledFormat::char_type;
+ using range = internal::output_range<OutputIt, char_type>;
+ using context = format_context_t<OutputIt, char_type>;
+ return cf.template vformat_to<range, context>(
+ range(out), {make_format_args<context>(args...)});
+}
+
+template <typename OutputIt, typename CompiledFormat, typename... Args,
+ FMT_ENABLE_IF(internal::is_output_iterator<OutputIt>::value)>
+format_to_n_result<OutputIt> format_to_n(OutputIt out, size_t n,
+ const CompiledFormat& cf,
+ const Args&... args) {
+ auto it =
+ format_to(internal::truncating_iterator<OutputIt>(out, n), cf, args...);
+ return {it.base(), it.count()};
+}
+
+template <typename CompiledFormat, typename... Args>
+std::size_t formatted_size(const CompiledFormat& cf, const Args&... args) {
+ return fmt::format_to(
+ internal::counting_iterator<typename CompiledFormat::char_type>(),
+ cf, args...)
+ .count();
+}
+
+FMT_END_NAMESPACE
+
+#endif // FMT_COMPILE_H_
diff --git a/include/fmt/core.h b/include/fmt/core.h
index 50b7935..bcce2f5 100644
--- a/include/fmt/core.h
+++ b/include/fmt/core.h
@@ -16,192 +16,211 @@
#include <type_traits>
// The fmt library version in the form major * 10000 + minor * 100 + patch.
-#define FMT_VERSION 50300
+#define FMT_VERSION 60000
#ifdef __has_feature
-# define FMT_HAS_FEATURE(x) __has_feature(x)
+# define FMT_HAS_FEATURE(x) __has_feature(x)
#else
-# define FMT_HAS_FEATURE(x) 0
+# define FMT_HAS_FEATURE(x) 0
#endif
#if defined(__has_include) && !defined(__INTELLISENSE__) && \
!(defined(__INTEL_COMPILER) && __INTEL_COMPILER < 1600)
-# define FMT_HAS_INCLUDE(x) __has_include(x)
+# define FMT_HAS_INCLUDE(x) __has_include(x)
#else
-# define FMT_HAS_INCLUDE(x) 0
+# define FMT_HAS_INCLUDE(x) 0
#endif
#ifdef __has_cpp_attribute
-# define FMT_HAS_CPP_ATTRIBUTE(x) __has_cpp_attribute(x)
+# define FMT_HAS_CPP_ATTRIBUTE(x) __has_cpp_attribute(x)
#else
-# define FMT_HAS_CPP_ATTRIBUTE(x) 0
+# define FMT_HAS_CPP_ATTRIBUTE(x) 0
#endif
#if defined(__GNUC__) && !defined(__clang__)
-# define FMT_GCC_VERSION (__GNUC__ * 100 + __GNUC_MINOR__)
+# define FMT_GCC_VERSION (__GNUC__ * 100 + __GNUC_MINOR__)
#else
-# define FMT_GCC_VERSION 0
+# define FMT_GCC_VERSION 0
#endif
#if __cplusplus >= 201103L || defined(__GXX_EXPERIMENTAL_CXX0X__)
-# define FMT_HAS_GXX_CXX11 FMT_GCC_VERSION
+# define FMT_HAS_GXX_CXX11 FMT_GCC_VERSION
#else
-# define FMT_HAS_GXX_CXX11 0
+# define FMT_HAS_GXX_CXX11 0
#endif
#ifdef _MSC_VER
-# define FMT_MSC_VER _MSC_VER
+# define FMT_MSC_VER _MSC_VER
#else
-# define FMT_MSC_VER 0
+# define FMT_MSC_VER 0
#endif
// Check if relaxed C++14 constexpr is supported.
// GCC doesn't allow throw in constexpr until version 6 (bug 67371).
#ifndef FMT_USE_CONSTEXPR
-# define FMT_USE_CONSTEXPR \
- (FMT_HAS_FEATURE(cxx_relaxed_constexpr) || FMT_MSC_VER >= 1910 || \
- (FMT_GCC_VERSION >= 600 && __cplusplus >= 201402L))
+# define FMT_USE_CONSTEXPR \
+ (FMT_HAS_FEATURE(cxx_relaxed_constexpr) || FMT_MSC_VER >= 1910 || \
+ (FMT_GCC_VERSION >= 600 && __cplusplus >= 201402L))
#endif
#if FMT_USE_CONSTEXPR
-# define FMT_CONSTEXPR constexpr
-# define FMT_CONSTEXPR_DECL constexpr
+# define FMT_CONSTEXPR constexpr
+# define FMT_CONSTEXPR_DECL constexpr
#else
-# define FMT_CONSTEXPR inline
-# define FMT_CONSTEXPR_DECL
-#endif
-
-#ifndef FMT_USE_CONSTEXPR11
-# define FMT_USE_CONSTEXPR11 \
- (FMT_USE_CONSTEXPR || FMT_GCC_VERSION >= 406 || FMT_MSC_VER >= 1900)
-#endif
-#if FMT_USE_CONSTEXPR11
-# define FMT_CONSTEXPR11 constexpr
-#else
-# define FMT_CONSTEXPR11
+# define FMT_CONSTEXPR inline
+# define FMT_CONSTEXPR_DECL
#endif
#ifndef FMT_OVERRIDE
-# if FMT_HAS_FEATURE(cxx_override) || \
- (FMT_GCC_VERSION >= 408 && FMT_HAS_GXX_CXX11) || FMT_MSC_VER >= 1900
-# define FMT_OVERRIDE override
-# else
-# define FMT_OVERRIDE
-# endif
-#endif
-
-#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
-
-#ifndef FMT_NULL
-# if FMT_HAS_FEATURE(cxx_nullptr) || \
- (FMT_GCC_VERSION >= 408 && FMT_HAS_GXX_CXX11) || FMT_MSC_VER >= 1600
-# define FMT_NULL nullptr
-# define FMT_USE_NULLPTR 1
-# else
-# define FMT_NULL NULL
-# endif
-#endif
-#ifndef FMT_USE_NULLPTR
-# define FMT_USE_NULLPTR 0
+# if FMT_HAS_FEATURE(cxx_override) || \
+ (FMT_GCC_VERSION >= 408 && FMT_HAS_GXX_CXX11) || FMT_MSC_VER >= 1900
+# define FMT_OVERRIDE override
+# else
+# define FMT_OVERRIDE
+# endif
#endif
// Check if exceptions are disabled.
#ifndef FMT_EXCEPTIONS
-# if (defined(__GNUC__) && !defined(__EXCEPTIONS)) || \
- FMT_MSC_VER && !_HAS_EXCEPTIONS
-# define FMT_EXCEPTIONS 0
-# else
-# define FMT_EXCEPTIONS 1
-# endif
+# if (defined(__GNUC__) && !defined(__EXCEPTIONS)) || \
+ FMT_MSC_VER && !_HAS_EXCEPTIONS
+# define FMT_EXCEPTIONS 0
+# else
+# define FMT_EXCEPTIONS 1
+# endif
#endif
// Define FMT_USE_NOEXCEPT to make fmt use noexcept (C++11 feature).
#ifndef FMT_USE_NOEXCEPT
-# define FMT_USE_NOEXCEPT 0
+# define FMT_USE_NOEXCEPT 0
#endif
#if FMT_USE_NOEXCEPT || FMT_HAS_FEATURE(cxx_noexcept) || \
(FMT_GCC_VERSION >= 408 && FMT_HAS_GXX_CXX11) || FMT_MSC_VER >= 1900
-# define FMT_DETECTED_NOEXCEPT noexcept
-# define FMT_HAS_CXX11_NOEXCEPT 1
+# define FMT_DETECTED_NOEXCEPT noexcept
+# define FMT_HAS_CXX11_NOEXCEPT 1
#else
-# define FMT_DETECTED_NOEXCEPT throw()
-# define FMT_HAS_CXX11_NOEXCEPT 0
+# define FMT_DETECTED_NOEXCEPT throw()
+# define FMT_HAS_CXX11_NOEXCEPT 0
#endif
#ifndef FMT_NOEXCEPT
-# if FMT_EXCEPTIONS || FMT_HAS_CXX11_NOEXCEPT
-# define FMT_NOEXCEPT FMT_DETECTED_NOEXCEPT
-# else
-# define FMT_NOEXCEPT
-# endif
+# if FMT_EXCEPTIONS || FMT_HAS_CXX11_NOEXCEPT
+# define FMT_NOEXCEPT FMT_DETECTED_NOEXCEPT
+# else
+# define FMT_NOEXCEPT
+# endif
+#endif
+
+// [[noreturn]] is disabled on MSVC because of bogus unreachable code warnings.
+#if FMT_EXCEPTIONS && FMT_HAS_CPP_ATTRIBUTE(noreturn) && !FMT_MSC_VER
+# define FMT_NORETURN [[noreturn]]
+#else
+# define FMT_NORETURN
+#endif
+
+#ifndef FMT_DEPRECATED
+# if (FMT_HAS_CPP_ATTRIBUTE(deprecated) && __cplusplus >= 201402L) || \
+ FMT_MSC_VER >= 1900
+# define FMT_DEPRECATED [[deprecated]]
+# else
+# if defined(__GNUC__) || defined(__clang__)
+# define FMT_DEPRECATED __attribute__((deprecated))
+# elif FMT_MSC_VER
+# define FMT_DEPRECATED __declspec(deprecated)
+# else
+# define FMT_DEPRECATED /* deprecated */
+# endif
+# endif
#endif
#ifndef FMT_BEGIN_NAMESPACE
-# if FMT_HAS_FEATURE(cxx_inline_namespaces) || FMT_GCC_VERSION >= 404 || \
- FMT_MSC_VER >= 1900
-# define FMT_INLINE_NAMESPACE inline namespace
-# define FMT_END_NAMESPACE }}
-# else
-# define FMT_INLINE_NAMESPACE namespace
-# define FMT_END_NAMESPACE } using namespace v5; }
-# endif
-# define FMT_BEGIN_NAMESPACE namespace fmt { FMT_INLINE_NAMESPACE v5 {
+# if FMT_HAS_FEATURE(cxx_inline_namespaces) || FMT_GCC_VERSION >= 404 || \
+ FMT_MSC_VER >= 1900
+# define FMT_INLINE_NAMESPACE inline namespace
+# define FMT_END_NAMESPACE \
+ } \
+ }
+# else
+# define FMT_INLINE_NAMESPACE namespace
+# define FMT_END_NAMESPACE \
+ } \
+ using namespace v6; \
+ }
+# endif
+# define FMT_BEGIN_NAMESPACE \
+ namespace fmt { \
+ FMT_INLINE_NAMESPACE v6 {
#endif
#if !defined(FMT_HEADER_ONLY) && defined(_WIN32)
-# ifdef FMT_EXPORT
-# define FMT_API __declspec(dllexport)
-# elif defined(FMT_SHARED)
-# define FMT_API __declspec(dllimport)
-# endif
+# ifdef FMT_EXPORT
+# define FMT_API __declspec(dllexport)
+# elif defined(FMT_SHARED)
+# define FMT_API __declspec(dllimport)
+# define FMT_EXTERN_TEMPLATE_API FMT_API
+# endif
#endif
#ifndef FMT_API
-# define FMT_API
+# define FMT_API
+#endif
+#ifndef FMT_EXTERN_TEMPLATE_API
+# define FMT_EXTERN_TEMPLATE_API
+#endif
+
+#ifndef FMT_HEADER_ONLY
+# define FMT_EXTERN extern
+#else
+# define FMT_EXTERN
#endif
#ifndef FMT_ASSERT
-# define FMT_ASSERT(condition, message) assert((condition) && message)
+# define FMT_ASSERT(condition, message) assert((condition) && message)
#endif
// libc++ supports string_view in pre-c++17.
-#if (FMT_HAS_INCLUDE(<string_view>) && \
- (__cplusplus > 201402L || defined(_LIBCPP_VERSION))) || \
+#if (FMT_HAS_INCLUDE(<string_view>) && \
+ (__cplusplus > 201402L || defined(_LIBCPP_VERSION))) || \
(defined(_MSVC_LANG) && _MSVC_LANG > 201402L && _MSC_VER >= 1910)
-# include <string_view>
-# define FMT_STRING_VIEW std::basic_string_view
-#elif FMT_HAS_INCLUDE(<experimental/string_view>) && __cplusplus >= 201402L
-# include <experimental/string_view>
-# define FMT_STRING_VIEW std::experimental::basic_string_view
-#endif
-
-// std::result_of is defined in <functional> in gcc 4.4.
-#if FMT_GCC_VERSION && FMT_GCC_VERSION <= 404
-# include <functional>
+# include <string_view>
+# define FMT_USE_STRING_VIEW
+#elif FMT_HAS_INCLUDE("experimental/string_view") && __cplusplus >= 201402L
+# include <experimental/string_view>
+# define FMT_USE_EXPERIMENTAL_STRING_VIEW
#endif
FMT_BEGIN_NAMESPACE
+
+// Implementations of enable_if_t and other types for pre-C++14 systems.
+template <bool B, class T = void>
+using enable_if_t = typename std::enable_if<B, T>::type;
+template <bool B, class T, class F>
+using conditional_t = typename std::conditional<B, T, F>::type;
+template <bool B> using bool_constant = std::integral_constant<bool, B>;
+template <typename T>
+using remove_reference_t = typename std::remove_reference<T>::type;
+template <typename T>
+using remove_const_t = typename std::remove_const<T>::type;
+
+struct monostate {};
+
+// An enable_if helper to be used in template parameters which results in much
+// shorter symbols: https://godbolt.org/z/sWw4vP. Extra parentheses are needed
+// to workaround a bug in MSVC 2019 (see #1140 and #1186).
+#define FMT_ENABLE_IF(...) enable_if_t<(__VA_ARGS__), int> = 0
+
namespace internal {
-// An implementation of declval for pre-C++11 compilers such as gcc 4.
-template <typename T>
-typename std::add_rvalue_reference<T>::type declval() FMT_NOEXCEPT;
+// A workaround for gcc 4.8 to make void_t work in a SFINAE context.
+template <typename... Ts> struct void_t_impl { using type = void; };
-template <typename>
-struct result_of;
-
-template <typename F, typename... Args>
-struct result_of<F(Args...)> {
- // A workaround for gcc 4.4 that doesn't allow F to be a reference.
- typedef typename std::result_of<
- typename std::remove_reference<F>::type(Args...)>::type type;
-};
+#if defined(FMT_USE_STRING_VIEW)
+template <typename Char> using std_string_view = std::basic_string_view<Char>;
+#elif defined(FMT_USE_EXPERIMENTAL_STRING_VIEW)
+template <typename Char>
+using std_string_view = std::experimental::basic_string_view<Char>;
+#else
+template <typename T> struct std_string_view {};
+#endif
// Casts nonnegative integer to unsigned.
template <typename Int>
@@ -209,135 +228,10 @@
FMT_ASSERT(value >= 0, "negative value");
return static_cast<typename std::make_unsigned<Int>::type>(value);
}
-
-/** A contiguous memory buffer with an optional growing ability. */
-template <typename T>
-class basic_buffer {
- private:
- basic_buffer(const basic_buffer &) = delete;
- void operator=(const basic_buffer &) = delete;
-
- T *ptr_;
- std::size_t size_;
- std::size_t capacity_;
-
- protected:
- // Don't initialize ptr_ since it is not accessed to save a few cycles.
- basic_buffer(std::size_t sz) FMT_NOEXCEPT: size_(sz), capacity_(sz) {}
-
- basic_buffer(T *p = FMT_NULL, std::size_t sz = 0, std::size_t cap = 0)
- FMT_NOEXCEPT: ptr_(p), size_(sz), capacity_(cap) {}
-
- /** Sets the buffer data and capacity. */
- void set(T *buf_data, std::size_t buf_capacity) FMT_NOEXCEPT {
- ptr_ = buf_data;
- capacity_ = buf_capacity;
- }
-
- /** Increases the buffer capacity to hold at least *capacity* elements. */
- virtual void grow(std::size_t capacity) = 0;
-
- public:
- typedef T value_type;
- typedef const T &const_reference;
-
- virtual ~basic_buffer() {}
-
- T *begin() FMT_NOEXCEPT { return ptr_; }
- T *end() FMT_NOEXCEPT { return ptr_ + size_; }
-
- /** Returns the size of this buffer. */
- std::size_t size() const FMT_NOEXCEPT { return size_; }
-
- /** Returns the capacity of this buffer. */
- std::size_t capacity() const FMT_NOEXCEPT { return capacity_; }
-
- /** Returns a pointer to the buffer data. */
- T *data() FMT_NOEXCEPT { return ptr_; }
-
- /** Returns a pointer to the buffer data. */
- const T *data() const FMT_NOEXCEPT { return ptr_; }
-
- /**
- Resizes the buffer. If T is a POD type new elements may not be initialized.
- */
- void resize(std::size_t new_size) {
- reserve(new_size);
- size_ = new_size;
- }
-
- /** Clears this buffer. */
- void clear() { size_ = 0; }
-
- /** Reserves space to store at least *capacity* elements. */
- void reserve(std::size_t new_capacity) {
- if (new_capacity > capacity_)
- grow(new_capacity);
- }
-
- void push_back(const T &value) {
- reserve(size_ + 1);
- ptr_[size_++] = value;
- }
-
- /** Appends data to the end of the buffer. */
- template <typename U>
- void append(const U *begin, const U *end);
-
- T &operator[](std::size_t index) { return ptr_[index]; }
- const T &operator[](std::size_t index) const { return ptr_[index]; }
-};
-
-typedef basic_buffer<char> buffer;
-typedef basic_buffer<wchar_t> wbuffer;
-
-// A container-backed buffer.
-template <typename Container>
-class container_buffer : public basic_buffer<typename Container::value_type> {
- private:
- Container &container_;
-
- protected:
- void grow(std::size_t capacity) FMT_OVERRIDE {
- container_.resize(capacity);
- this->set(&container_[0], capacity);
- }
-
- public:
- explicit container_buffer(Container &c)
- : basic_buffer<typename Container::value_type>(c.size()), container_(c) {}
-};
-
-// Extracts a reference to the container from back_insert_iterator.
-template <typename Container>
-inline Container &get_container(std::back_insert_iterator<Container> it) {
- typedef std::back_insert_iterator<Container> 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 &) {}
-
- // This function is intentionally not constexpr to give a compile-time error.
- FMT_API void on_error(const char *message);
-};
-
-template <typename T>
-struct no_formatter_error : std::false_type {};
} // namespace internal
-#if FMT_GCC_VERSION && FMT_GCC_VERSION < 405
-template <typename... T>
-struct is_constructible: std::false_type {};
-#else
-template <typename... T>
-struct is_constructible : std::is_constructible<T...> {};
-#endif
+template <typename... Ts>
+using void_t = typename internal::void_t_impl<Ts...>::type;
/**
An implementation of ``std::basic_string_view`` for pre-C++17. It provides a
@@ -346,21 +240,21 @@
compiled with a different ``-std`` option than the client code (which is not
recommended).
*/
-template <typename Char>
-class basic_string_view {
+template <typename Char> class basic_string_view {
private:
- const Char *data_;
+ const Char* data_;
size_t size_;
public:
- typedef Char char_type;
- typedef const Char *iterator;
+ using char_type = Char;
+ using iterator = const Char*;
- FMT_CONSTEXPR basic_string_view() FMT_NOEXCEPT : data_(FMT_NULL), size_(0) {}
+ FMT_CONSTEXPR basic_string_view() FMT_NOEXCEPT : data_(nullptr), 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) {}
+ FMT_CONSTEXPR basic_string_view(const Char* s, size_t count) FMT_NOEXCEPT
+ : data_(s),
+ size_(count) {}
/**
\rst
@@ -368,22 +262,23 @@
the size with ``std::char_traits<Char>::length``.
\endrst
*/
- basic_string_view(const Char *s)
- : data_(s), size_(std::char_traits<Char>::length(s)) {}
+ basic_string_view(const Char* s)
+ : data_(s), size_(std::char_traits<Char>::length(s)) {}
/** Constructs a string reference from a ``std::basic_string`` object. */
template <typename Alloc>
- FMT_CONSTEXPR basic_string_view(
- const std::basic_string<Char, Alloc> &s) FMT_NOEXCEPT
- : data_(s.data()), size_(s.size()) {}
+ FMT_CONSTEXPR basic_string_view(const std::basic_string<Char, Alloc>& s)
+ FMT_NOEXCEPT : data_(s.data()),
+ size_(s.size()) {}
-#ifdef FMT_STRING_VIEW
- FMT_CONSTEXPR basic_string_view(FMT_STRING_VIEW<Char> s) FMT_NOEXCEPT
- : data_(s.data()), size_(s.size()) {}
-#endif
+ template <
+ typename S,
+ FMT_ENABLE_IF(std::is_same<S, internal::std_string_view<Char>>::value)>
+ FMT_CONSTEXPR basic_string_view(S s) FMT_NOEXCEPT : data_(s.data()),
+ size_(s.size()) {}
/** Returns a pointer to the string data. */
- FMT_CONSTEXPR const Char *data() const { return data_; }
+ FMT_CONSTEXPR const Char* data() const { return data_; }
/** Returns the string size. */
FMT_CONSTEXPR size_t size() const { return size_; }
@@ -425,47 +320,60 @@
}
};
-typedef basic_string_view<char> string_view;
-typedef basic_string_view<wchar_t> wstring_view;
+using string_view = basic_string_view<char>;
+using wstring_view = basic_string_view<wchar_t>;
+
+#ifndef __cpp_char8_t
+// A UTF-8 code unit type.
+enum char8_t : unsigned char {};
+#endif
+
+/** Specifies if ``T`` is a character type. Can be specialized by users. */
+template <typename T> struct is_char : std::false_type {};
+template <> struct is_char<char> : std::true_type {};
+template <> struct is_char<wchar_t> : std::true_type {};
+template <> struct is_char<char8_t> : std::true_type {};
+template <> struct is_char<char16_t> : std::true_type {};
+template <> struct is_char<char32_t> : std::true_type {};
/**
\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<Char>`` and returns a ``fmt::basic_string_view<Char>``.
- The conversion function must live in the very same namespace as
- ``StringType<Char>`` 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.
+ Returns a string view of `s`. In order to add custom string type support to
+ {fmt} provide an overload of `to_string_view` for it in the same namespace as
+ the type for the argument-dependent lookup to work.
**Example**::
namespace my_ns {
- inline string_view to_string_view(const my_string &s) {
+ inline string_view to_string_view(const my_string& s) {
return {s.data(), s.length()};
}
}
-
std::string message = fmt::format(my_string("The answer is {}"), 42);
\endrst
*/
-template <typename Char>
-inline basic_string_view<Char>
- to_string_view(basic_string_view<Char> s) { return s; }
+template <typename Char, FMT_ENABLE_IF(is_char<Char>::value)>
+inline basic_string_view<Char> to_string_view(const Char* s) {
+ return s;
+}
+
+template <typename Char, typename Traits, typename Allocator>
+inline basic_string_view<Char> to_string_view(
+ const std::basic_string<Char, Traits, Allocator>& s) {
+ return {s.data(), s.size()};
+}
template <typename Char>
-inline basic_string_view<Char>
- to_string_view(const std::basic_string<Char> &s) { return s; }
+inline basic_string_view<Char> to_string_view(basic_string_view<Char> s) {
+ return s;
+}
-template <typename Char>
-inline basic_string_view<Char> to_string_view(const Char *s) { return s; }
-
-#ifdef FMT_STRING_VIEW
-template <typename Char>
-inline basic_string_view<Char>
- to_string_view(FMT_STRING_VIEW<Char> s) { return s; }
-#endif
+template <typename Char,
+ FMT_ENABLE_IF(!std::is_empty<internal::std_string_view<Char>>::value)>
+inline basic_string_view<Char> to_string_view(
+ internal::std_string_view<Char> s) {
+ return s;
+}
// A base class for compile-time strings. It is defined in the fmt namespace to
// make formatting functions visible via ADL, e.g. format(fmt("{}"), 42).
@@ -474,403 +382,39 @@
template <typename S>
struct is_compile_string : std::is_base_of<compile_string, S> {};
-template <
- typename S,
- typename Enable = typename std::enable_if<is_compile_string<S>::value>::type>
-FMT_CONSTEXPR basic_string_view<typename S::char_type>
- to_string_view(const S &s) { return s; }
-
-template <typename Context>
-class basic_format_arg;
-
-template <typename Context>
-class basic_format_args;
-
-// A formatter for objects of type T.
-template <typename T, typename Char = char, typename Enable = void>
-struct formatter {
- static_assert(internal::no_formatter_error<T>::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>
- typename ParseContext::iterator parse(ParseContext &);
- template <typename FormatContext>
- auto format(const T &val, FormatContext &ctx) -> decltype(ctx.out());
-};
-
-template <typename T, typename Char, typename Enable = void>
-struct convert_to_int: std::integral_constant<
- bool, !std::is_arithmetic<T>::value && std::is_convertible<T, int>::value> {};
+template <typename S, FMT_ENABLE_IF(is_compile_string<S>::value)>
+constexpr basic_string_view<typename S::char_type> to_string_view(const S& s) {
+ return s;
+}
namespace internal {
-
-struct dummy_string_view { typedef void char_type; };
-dummy_string_view to_string_view(...);
-using fmt::v5::to_string_view;
+void to_string_view(...);
+using fmt::v6::to_string_view;
// Specifies whether S is a string type convertible to fmt::basic_string_view.
+// It should be a constexpr function but MSVC 2017 fails to compile it in
+// enable_if and MSVC 2015 fails to compile it as an alias template.
template <typename S>
-struct is_string : std::integral_constant<bool, !std::is_same<
- dummy_string_view, decltype(to_string_view(declval<S>()))>::value> {};
-
-template <typename S>
-struct char_t {
- typedef decltype(to_string_view(declval<S>())) result;
- typedef typename result::char_type type;
+struct is_string : std::is_class<decltype(to_string_view(std::declval<S>()))> {
};
-template <typename Char>
-struct named_arg_base;
-
-template <typename T, typename Char>
-struct named_arg;
-
-enum type {
- none_type, named_arg_type,
- // Integer types should go first,
- int_type, uint_type, long_long_type, ulong_long_type, bool_type, char_type,
- last_integer_type = char_type,
- // followed by floating-point types.
- double_type, long_double_type, last_numeric_type = long_double_type,
- cstring_type, string_type, pointer_type, custom_type
+template <typename S, typename = void> struct char_t_impl {};
+template <typename S> struct char_t_impl<S, enable_if_t<is_string<S>::value>> {
+ using result = decltype(to_string_view(std::declval<S>()));
+ using type = typename result::char_type;
};
-FMT_CONSTEXPR bool is_integral(type t) {
- FMT_ASSERT(t != internal::named_arg_type, "invalid argument type");
- return t > internal::none_type && t <= internal::last_integer_type;
-}
+struct error_handler {
+ FMT_CONSTEXPR error_handler() {}
+ FMT_CONSTEXPR error_handler(const error_handler&) {}
-FMT_CONSTEXPR bool is_arithmetic(type t) {
- FMT_ASSERT(t != internal::named_arg_type, "invalid argument type");
- return t > internal::none_type && t <= internal::last_numeric_type;
-}
-
-template <typename Char>
-struct string_value {
- const Char *value;
- std::size_t size;
+ // This function is intentionally not constexpr to give a compile-time error.
+ FMT_NORETURN FMT_API void on_error(const char* message);
};
-
-template <typename Context>
-struct custom_value {
- const void *value;
- void (*format)(const void *arg, Context &ctx);
-};
-
-// A formatting argument value.
-template <typename Context>
-class value {
- public:
- typedef typename Context::char_type char_type;
-
- union {
- int int_value;
- unsigned uint_value;
- long long long_long_value;
- unsigned long long ulong_long_value;
- double double_value;
- long double long_double_value;
- const void *pointer;
- string_value<char_type> string;
- string_value<signed char> sstring;
- string_value<unsigned char> ustring;
- custom_value<Context> custom;
- };
-
- FMT_CONSTEXPR value(int val = 0) : int_value(val) {}
- value(unsigned val) { uint_value = val; }
- value(long long val) { long_long_value = val; }
- value(unsigned long long val) { ulong_long_value = val; }
- value(double val) { double_value = val; }
- value(long double val) { long_double_value = val; }
- value(const char_type *val) { string.value = val; }
- value(const signed char *val) {
- static_assert(std::is_same<char, char_type>::value,
- "incompatible string types");
- sstring.value = val;
- }
- value(const unsigned char *val) {
- static_assert(std::is_same<char, char_type>::value,
- "incompatible string types");
- ustring.value = val;
- }
- value(basic_string_view<char_type> val) {
- string.value = val.data();
- string.size = val.size();
- }
- value(const void *val) { pointer = val; }
-
- template <typename T>
- explicit value(const T &val) {
- custom.value = &val;
- custom.format = &format_custom_arg<T>;
- }
-
- const named_arg_base<char_type> &as_named_arg() {
- return *static_cast<const named_arg_base<char_type>*>(pointer);
- }
-
- private:
- // Formats an argument of a custom type, such as a user-defined class.
- template <typename T>
- static void format_custom_arg(const void *arg, Context &ctx) {
- // Get the formatter type through the context to allow different contexts
- // have different extension points, e.g. `formatter<T>` for `format` and
- // `printf_formatter<T>` for `printf`.
- typename Context::template formatter_type<T>::type f;
- auto &&parse_ctx = ctx.parse_context();
- parse_ctx.advance_to(f.parse(parse_ctx));
- ctx.advance_to(f.format(*static_cast<const T*>(arg), ctx));
- }
-};
-
-// Value initializer used to delay conversion to value and reduce memory churn.
-template <typename Context, typename T, type TYPE>
-struct init {
- T val;
- static const type type_tag = TYPE;
-
- FMT_CONSTEXPR init(const T &v) : val(v) {}
- FMT_CONSTEXPR operator value<Context>() const { return value<Context>(val); }
-};
-
-template <typename Context, typename T>
-FMT_CONSTEXPR basic_format_arg<Context> make_arg(const T &value);
-
-#define FMT_MAKE_VALUE(TAG, ArgType, ValueType) \
- template <typename C> \
- FMT_CONSTEXPR init<C, ValueType, TAG> make_value(ArgType val) { \
- return static_cast<ValueType>(val); \
- }
-
-#define FMT_MAKE_VALUE_SAME(TAG, Type) \
- template <typename C> \
- FMT_CONSTEXPR init<C, Type, TAG> make_value(Type val) { return val; }
-
-FMT_MAKE_VALUE(bool_type, bool, int)
-FMT_MAKE_VALUE(int_type, short, int)
-FMT_MAKE_VALUE(uint_type, unsigned short, unsigned)
-FMT_MAKE_VALUE_SAME(int_type, int)
-FMT_MAKE_VALUE_SAME(uint_type, unsigned)
-
-// To minimize the number of types we need to deal with, long is translated
-// either to int or to long long depending on its size.
-typedef std::conditional<sizeof(long) == sizeof(int), int, long long>::type
- long_type;
-FMT_MAKE_VALUE(
- (sizeof(long) == sizeof(int) ? int_type : long_long_type), long, long_type)
-typedef std::conditional<sizeof(unsigned long) == sizeof(unsigned),
- unsigned, unsigned long long>::type ulong_type;
-FMT_MAKE_VALUE(
- (sizeof(unsigned long) == sizeof(unsigned) ? uint_type : ulong_long_type),
- unsigned long, ulong_type)
-
-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)
-
-// This doesn't use FMT_MAKE_VALUE because of ambiguity in gcc 4.4.
-template <typename C, typename Char>
-FMT_CONSTEXPR typename std::enable_if<
- std::is_same<typename C::char_type, Char>::value,
- init<C, int, char_type>>::type make_value(Char val) { return val; }
-
-template <typename C>
-FMT_CONSTEXPR typename std::enable_if<
- !std::is_same<typename C::char_type, char>::value,
- init<C, int, char_type>>::type make_value(char val) { return val; }
-
-FMT_MAKE_VALUE(double_type, float, double)
-FMT_MAKE_VALUE_SAME(double_type, double)
-FMT_MAKE_VALUE_SAME(long_double_type, long double)
-
-// Formatting of wide strings into a narrow buffer and multibyte strings
-// into a wide buffer is disallowed (https://github.com/fmtlib/fmt/pull/606).
-FMT_MAKE_VALUE(cstring_type, typename C::char_type*,
- const typename C::char_type*)
-FMT_MAKE_VALUE(cstring_type, const typename C::char_type*,
- const typename C::char_type*)
-
-FMT_MAKE_VALUE(cstring_type, signed char*, const signed char*)
-FMT_MAKE_VALUE_SAME(cstring_type, const signed char*)
-FMT_MAKE_VALUE(cstring_type, unsigned char*, const unsigned char*)
-FMT_MAKE_VALUE_SAME(cstring_type, const unsigned char*)
-FMT_MAKE_VALUE_SAME(string_type, basic_string_view<typename C::char_type>)
-FMT_MAKE_VALUE(string_type,
- typename basic_string_view<typename C::char_type>::type,
- basic_string_view<typename C::char_type>)
-FMT_MAKE_VALUE(string_type, const std::basic_string<typename C::char_type>&,
- basic_string_view<typename C::char_type>)
-FMT_MAKE_VALUE(pointer_type, void*, const void*)
-FMT_MAKE_VALUE_SAME(pointer_type, const void*)
-
-#if FMT_USE_NULLPTR
-FMT_MAKE_VALUE(pointer_type, std::nullptr_t, const void*)
-#endif
-
-// Formatting of arbitrary pointers is disallowed. If you want to output a
-// pointer cast it to "void *" or "const void *". In particular, this forbids
-// formatting of "[const] volatile char *" which is printed as bool by
-// iostreams.
-template <typename C, typename T>
-typename std::enable_if<!std::is_same<T, typename C::char_type>::value>::type
- make_value(const T *) {
- static_assert(!sizeof(T), "formatting of non-void pointers is disallowed");
-}
-
-template <typename C, typename T>
-inline typename std::enable_if<
- std::is_enum<T>::value && convert_to_int<T, typename C::char_type>::value,
- init<C, int, int_type>>::type
- make_value(const T &val) { return static_cast<int>(val); }
-
-template <typename C, typename T, typename Char = typename C::char_type>
-inline typename std::enable_if<
- is_constructible<basic_string_view<Char>, T>::value &&
- !internal::is_string<T>::value,
- init<C, basic_string_view<Char>, string_type>>::type
- make_value(const T &val) { return basic_string_view<Char>(val); }
-
-template <typename C, typename T, typename Char = typename C::char_type>
-inline typename std::enable_if<
- !convert_to_int<T, Char>::value && !std::is_same<T, Char>::value &&
- !std::is_convertible<T, basic_string_view<Char>>::value &&
- !is_constructible<basic_string_view<Char>, T>::value &&
- !internal::is_string<T>::value,
- // Implicit conversion to std::string is not handled here because it's
- // unsafe: https://github.com/fmtlib/fmt/issues/729
- init<C, const T &, custom_type>>::type
- make_value(const T &val) { return val; }
-
-template <typename C, typename T>
-init<C, const void*, named_arg_type>
- make_value(const named_arg<T, typename C::char_type> &val) {
- basic_format_arg<C> arg = make_arg<C>(val.value);
- std::memcpy(val.data, &arg, sizeof(arg));
- return static_cast<const void*>(&val);
-}
-
-template <typename C, typename S>
-FMT_CONSTEXPR11 typename std::enable_if<
- internal::is_string<S>::value,
- init<C, basic_string_view<typename C::char_type>, string_type>>::type
- make_value(const S &val) {
- // Handle adapted strings.
- static_assert(std::is_same<
- typename C::char_type, typename internal::char_t<S>::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 <typename Context>
-class arg_map;
} // namespace internal
-// A formatting argument. It is a trivially copyable/constructible type to
-// allow storage in basic_memory_buffer.
-template <typename Context>
-class basic_format_arg {
- private:
- internal::value<Context> value_;
- internal::type type_;
-
- template <typename ContextType, typename T>
- friend FMT_CONSTEXPR basic_format_arg<ContextType>
- internal::make_arg(const T &value);
-
- template <typename Visitor, typename Ctx>
- friend FMT_CONSTEXPR typename internal::result_of<Visitor(int)>::type
- visit_format_arg(Visitor &&vis, const basic_format_arg<Ctx> &arg);
-
- friend class basic_format_args<Context>;
- friend class internal::arg_map<Context>;
-
- typedef typename Context::char_type char_type;
-
- public:
- class handle {
- public:
- explicit handle(internal::custom_value<Context> custom): custom_(custom) {}
-
- void format(Context &ctx) const { custom_.format(custom_.value, ctx); }
-
- private:
- internal::custom_value<Context> custom_;
- };
-
- FMT_CONSTEXPR basic_format_arg() : type_(internal::none_type) {}
-
- FMT_EXPLICIT operator bool() const FMT_NOEXCEPT {
- return type_ != internal::none_type;
- }
-
- internal::type type() const { return type_; }
-
- bool is_integral() const { return internal::is_integral(type_); }
- bool is_arithmetic() const { return internal::is_arithmetic(type_); }
-};
-
-struct monostate {};
-
-/**
- \rst
- Visits an argument dispatching to the appropriate visit method based on
- the argument type. For example, if the argument type is ``double`` then
- ``vis(value)`` will be called with the value of type ``double``.
- \endrst
- */
-template <typename Visitor, typename Context>
-FMT_CONSTEXPR typename internal::result_of<Visitor(int)>::type
- visit_format_arg(Visitor &&vis, const basic_format_arg<Context> &arg) {
- typedef typename Context::char_type char_type;
- switch (arg.type_) {
- case internal::none_type:
- break;
- case internal::named_arg_type:
- FMT_ASSERT(false, "invalid argument type");
- break;
- case internal::int_type:
- return vis(arg.value_.int_value);
- case internal::uint_type:
- return vis(arg.value_.uint_value);
- case internal::long_long_type:
- return vis(arg.value_.long_long_value);
- case internal::ulong_long_type:
- return vis(arg.value_.ulong_long_value);
- case internal::bool_type:
- return vis(arg.value_.int_value != 0);
- case internal::char_type:
- return vis(static_cast<char_type>(arg.value_.int_value));
- case internal::double_type:
- return vis(arg.value_.double_value);
- case internal::long_double_type:
- return vis(arg.value_.long_double_value);
- case internal::cstring_type:
- return vis(arg.value_.string.value);
- case internal::string_type:
- return vis(basic_string_view<char_type>(
- arg.value_.string.value, arg.value_.string.size));
- case internal::pointer_type:
- return vis(arg.value_.pointer);
- case internal::custom_type:
- return vis(typename basic_format_arg<Context>::handle(arg.value_.custom));
- }
- return vis(monostate());
-}
-
-// DEPRECATED!
-template <typename Visitor, typename Context>
-FMT_CONSTEXPR typename internal::result_of<Visitor(int)>::type
- visit(Visitor &&vis, const basic_format_arg<Context> &arg) {
- return visit_format_arg(std::forward<Visitor>(vis), arg);
-}
+/** String's character type. */
+template <typename S> using char_t = typename internal::char_t_impl<S>::type;
// Parsing context consisting of a format string range being parsed and an
// argument counter for automatic indexing.
@@ -881,12 +425,12 @@
int next_arg_id_;
public:
- typedef Char char_type;
- typedef typename basic_string_view<Char>::iterator iterator;
+ using char_type = Char;
+ using iterator = typename basic_string_view<Char>::iterator;
- explicit FMT_CONSTEXPR basic_parse_context(
- basic_string_view<Char> format_str, ErrorHandler eh = ErrorHandler())
- : ErrorHandler(eh), format_str_(format_str), next_arg_id_(0) {}
+ explicit FMT_CONSTEXPR basic_parse_context(basic_string_view<Char> format_str,
+ ErrorHandler eh = ErrorHandler())
+ : ErrorHandler(eh), format_str_(format_str), next_arg_id_(0) {}
// Returns an iterator to the beginning of the format string range being
// parsed.
@@ -903,9 +447,13 @@
}
// Returns the next argument index.
- FMT_CONSTEXPR unsigned next_arg_id();
+ FMT_CONSTEXPR int next_arg_id() {
+ if (next_arg_id_ >= 0) return next_arg_id_++;
+ on_error("cannot switch from manual to automatic argument indexing");
+ return 0;
+ }
- FMT_CONSTEXPR bool check_arg_id(unsigned) {
+ FMT_CONSTEXPR bool check_arg_id(int) {
if (next_arg_id_ > 0) {
on_error("cannot switch from automatic to manual argument indexing");
return false;
@@ -913,56 +461,521 @@
next_arg_id_ = -1;
return true;
}
- void check_arg_id(basic_string_view<Char>) {}
- FMT_CONSTEXPR void on_error(const char *message) {
+ FMT_CONSTEXPR void check_arg_id(basic_string_view<Char>) {}
+
+ FMT_CONSTEXPR void on_error(const char* message) {
ErrorHandler::on_error(message);
}
FMT_CONSTEXPR ErrorHandler error_handler() const { return *this; }
};
-typedef basic_parse_context<char> format_parse_context;
-typedef basic_parse_context<wchar_t> wformat_parse_context;
+using format_parse_context = basic_parse_context<char>;
+using wformat_parse_context = basic_parse_context<wchar_t>;
-// DEPRECATED!
-typedef basic_parse_context<char> parse_context;
-typedef basic_parse_context<wchar_t> wparse_context;
+using parse_context FMT_DEPRECATED = basic_parse_context<char>;
+using wparse_context FMT_DEPRECATED = basic_parse_context<wchar_t>;
+
+template <typename Context> class basic_format_arg;
+template <typename Context> class basic_format_args;
+
+// A formatter for objects of type T.
+template <typename T, typename Char = char, typename Enable = void>
+struct formatter {
+ // A deleted default constructor indicates a disabled formatter.
+ formatter() = delete;
+};
+
+template <typename T, typename Char, typename Enable = void>
+struct FMT_DEPRECATED convert_to_int
+ : bool_constant<!std::is_arithmetic<T>::value &&
+ std::is_convertible<T, int>::value> {};
+
+namespace internal {
+
+// Specifies if T has an enabled formatter specialization. A type can be
+// formattable even if it doesn't have a formatter e.g. via a conversion.
+template <typename T, typename Context>
+using has_formatter =
+ std::is_constructible<typename Context::template formatter_type<T>>;
+
+/** A contiguous memory buffer with an optional growing ability. */
+template <typename T> class buffer {
+ private:
+ buffer(const buffer&) = delete;
+ void operator=(const buffer&) = delete;
+
+ T* ptr_;
+ std::size_t size_;
+ std::size_t capacity_;
+
+ protected:
+ // Don't initialize ptr_ since it is not accessed to save a few cycles.
+ buffer(std::size_t sz) FMT_NOEXCEPT : size_(sz), capacity_(sz) {}
+
+ buffer(T* p = nullptr, std::size_t sz = 0, std::size_t cap = 0) FMT_NOEXCEPT
+ : ptr_(p),
+ size_(sz),
+ capacity_(cap) {}
+
+ /** Sets the buffer data and capacity. */
+ void set(T* buf_data, std::size_t buf_capacity) FMT_NOEXCEPT {
+ ptr_ = buf_data;
+ capacity_ = buf_capacity;
+ }
+
+ /** Increases the buffer capacity to hold at least *capacity* elements. */
+ virtual void grow(std::size_t capacity) = 0;
+
+ public:
+ using value_type = T;
+ using const_reference = const T&;
+
+ virtual ~buffer() {}
+
+ T* begin() FMT_NOEXCEPT { return ptr_; }
+ T* end() FMT_NOEXCEPT { return ptr_ + size_; }
+
+ /** Returns the size of this buffer. */
+ std::size_t size() const FMT_NOEXCEPT { return size_; }
+
+ /** Returns the capacity of this buffer. */
+ std::size_t capacity() const FMT_NOEXCEPT { return capacity_; }
+
+ /** Returns a pointer to the buffer data. */
+ T* data() FMT_NOEXCEPT { return ptr_; }
+
+ /** Returns a pointer to the buffer data. */
+ const T* data() const FMT_NOEXCEPT { return ptr_; }
+
+ /**
+ Resizes the buffer. If T is a POD type new elements may not be initialized.
+ */
+ void resize(std::size_t new_size) {
+ reserve(new_size);
+ size_ = new_size;
+ }
+
+ /** Clears this buffer. */
+ void clear() { size_ = 0; }
+
+ /** Reserves space to store at least *capacity* elements. */
+ void reserve(std::size_t new_capacity) {
+ if (new_capacity > capacity_) grow(new_capacity);
+ }
+
+ void push_back(const T& value) {
+ reserve(size_ + 1);
+ ptr_[size_++] = value;
+ }
+
+ /** Appends data to the end of the buffer. */
+ template <typename U> void append(const U* begin, const U* end);
+
+ T& operator[](std::size_t index) { return ptr_[index]; }
+ const T& operator[](std::size_t index) const { return ptr_[index]; }
+};
+
+// A container-backed buffer.
+template <typename Container>
+class container_buffer : public buffer<typename Container::value_type> {
+ private:
+ Container& container_;
+
+ protected:
+ void grow(std::size_t capacity) FMT_OVERRIDE {
+ container_.resize(capacity);
+ this->set(&container_[0], capacity);
+ }
+
+ public:
+ explicit container_buffer(Container& c)
+ : buffer<typename Container::value_type>(c.size()), container_(c) {}
+};
+
+// Extracts a reference to the container from back_insert_iterator.
+template <typename Container>
+inline Container& get_container(std::back_insert_iterator<Container> it) {
+ using bi_iterator = std::back_insert_iterator<Container>;
+ struct accessor : bi_iterator {
+ accessor(bi_iterator iter) : bi_iterator(iter) {}
+ using bi_iterator::container;
+ };
+ return *accessor(it).container;
+}
+
+template <typename T, typename Char = char, typename Enable = void>
+struct fallback_formatter {
+ fallback_formatter() = delete;
+};
+
+// Specifies if T has an enabled fallback_formatter specialization.
+template <typename T, typename Context>
+using has_fallback_formatter =
+ std::is_constructible<fallback_formatter<T, typename Context::char_type>>;
+
+template <typename Char> struct named_arg_base;
+template <typename T, typename Char> struct named_arg;
+
+enum type {
+ none_type,
+ named_arg_type,
+ // Integer types should go first,
+ int_type,
+ uint_type,
+ long_long_type,
+ ulong_long_type,
+ bool_type,
+ char_type,
+ last_integer_type = char_type,
+ // followed by floating-point types.
+ double_type,
+ long_double_type,
+ last_numeric_type = long_double_type,
+ cstring_type,
+ string_type,
+ pointer_type,
+ custom_type
+};
+
+// Maps core type T to the corresponding type enum constant.
+template <typename T, typename Char>
+struct type_constant : std::integral_constant<type, custom_type> {};
+
+#define FMT_TYPE_CONSTANT(Type, constant) \
+ template <typename Char> \
+ struct type_constant<Type, Char> : std::integral_constant<type, constant> {}
+
+FMT_TYPE_CONSTANT(const named_arg_base<Char>&, named_arg_type);
+FMT_TYPE_CONSTANT(int, int_type);
+FMT_TYPE_CONSTANT(unsigned, uint_type);
+FMT_TYPE_CONSTANT(long long, long_long_type);
+FMT_TYPE_CONSTANT(unsigned long long, ulong_long_type);
+FMT_TYPE_CONSTANT(bool, bool_type);
+FMT_TYPE_CONSTANT(Char, char_type);
+FMT_TYPE_CONSTANT(double, double_type);
+FMT_TYPE_CONSTANT(long double, long_double_type);
+FMT_TYPE_CONSTANT(const Char*, cstring_type);
+FMT_TYPE_CONSTANT(basic_string_view<Char>, string_type);
+FMT_TYPE_CONSTANT(const void*, pointer_type);
+
+FMT_CONSTEXPR bool is_integral(type t) {
+ FMT_ASSERT(t != named_arg_type, "invalid argument type");
+ return t > none_type && t <= last_integer_type;
+}
+
+FMT_CONSTEXPR bool is_arithmetic(type t) {
+ FMT_ASSERT(t != named_arg_type, "invalid argument type");
+ return t > none_type && t <= last_numeric_type;
+}
+
+template <typename Char> struct string_value {
+ const Char* data;
+ std::size_t size;
+};
+
+template <typename Context> struct custom_value {
+ using parse_context = basic_parse_context<typename Context::char_type>;
+ const void* value;
+ void (*format)(const void* arg, parse_context& parse_ctx, Context& ctx);
+};
+
+// A formatting argument value.
+template <typename Context> class value {
+ public:
+ using char_type = typename Context::char_type;
+
+ union {
+ int int_value;
+ unsigned uint_value;
+ long long long_long_value;
+ unsigned long long ulong_long_value;
+ bool bool_value;
+ char_type char_value;
+ double double_value;
+ long double long_double_value;
+ const void* pointer;
+ string_value<char_type> string;
+ custom_value<Context> custom;
+ const named_arg_base<char_type>* named_arg;
+ };
+
+ FMT_CONSTEXPR value(int val = 0) : int_value(val) {}
+ FMT_CONSTEXPR value(unsigned val) : uint_value(val) {}
+ value(long long val) : long_long_value(val) {}
+ value(unsigned long long val) : ulong_long_value(val) {}
+ value(double val) : double_value(val) {}
+ value(long double val) : long_double_value(val) {}
+ value(bool val) : bool_value(val) {}
+ value(char_type val) : char_value(val) {}
+ value(const char_type* val) { string.data = val; }
+ value(basic_string_view<char_type> val) {
+ string.data = val.data();
+ string.size = val.size();
+ }
+ value(const void* val) : pointer(val) {}
+
+ template <typename T> value(const T& val) {
+ custom.value = &val;
+ // Get the formatter type through the context to allow different contexts
+ // have different extension points, e.g. `formatter<T>` for `format` and
+ // `printf_formatter<T>` for `printf`.
+ custom.format = format_custom_arg<
+ T, conditional_t<has_formatter<T, Context>::value,
+ typename Context::template formatter_type<T>,
+ fallback_formatter<T, char_type>>>;
+ }
+
+ value(const named_arg_base<char_type>& val) { named_arg = &val; }
+
+ private:
+ // Formats an argument of a custom type, such as a user-defined class.
+ template <typename T, typename Formatter>
+ static void format_custom_arg(const void* arg,
+ basic_parse_context<char_type>& parse_ctx,
+ Context& ctx) {
+ Formatter f;
+ parse_ctx.advance_to(f.parse(parse_ctx));
+ ctx.advance_to(f.format(*static_cast<const T*>(arg), ctx));
+ }
+};
+
+template <typename Context, typename T>
+FMT_CONSTEXPR basic_format_arg<Context> make_arg(const T& value);
+
+// To minimize the number of types we need to deal with, long is translated
+// either to int or to long long depending on its size.
+enum { long_short = sizeof(long) == sizeof(int) };
+using long_type = conditional_t<long_short, int, long long>;
+using ulong_type = conditional_t<long_short, unsigned, unsigned long long>;
+
+// Maps formatting arguments to core types.
+template <typename Context> struct arg_mapper {
+ using char_type = typename Context::char_type;
+
+ FMT_CONSTEXPR int map(signed char val) { return val; }
+ FMT_CONSTEXPR unsigned map(unsigned char val) { return val; }
+ FMT_CONSTEXPR int map(short val) { return val; }
+ FMT_CONSTEXPR unsigned map(unsigned short val) { return val; }
+ FMT_CONSTEXPR int map(int val) { return val; }
+ FMT_CONSTEXPR unsigned map(unsigned val) { return val; }
+ FMT_CONSTEXPR long_type map(long val) { return val; }
+ FMT_CONSTEXPR ulong_type map(unsigned long val) { return val; }
+ FMT_CONSTEXPR long long map(long long val) { return val; }
+ FMT_CONSTEXPR unsigned long long map(unsigned long long val) { return val; }
+ FMT_CONSTEXPR bool map(bool val) { return val; }
+
+ template <typename T, FMT_ENABLE_IF(is_char<T>::value)>
+ FMT_CONSTEXPR char_type map(T val) {
+ static_assert(
+ std::is_same<T, char>::value || std::is_same<T, char_type>::value,
+ "mixing character types is disallowed");
+ return val;
+ }
+
+ FMT_CONSTEXPR double map(float val) { return static_cast<double>(val); }
+ FMT_CONSTEXPR double map(double val) { return val; }
+ FMT_CONSTEXPR long double map(long double val) { return val; }
+
+ FMT_CONSTEXPR const char_type* map(char_type* val) { return val; }
+ FMT_CONSTEXPR const char_type* map(const char_type* val) { return val; }
+ template <typename T, FMT_ENABLE_IF(is_string<T>::value)>
+ FMT_CONSTEXPR basic_string_view<char_type> map(const T& val) {
+ static_assert(std::is_same<char_type, char_t<T>>::value,
+ "mixing character types is disallowed");
+ return to_string_view(val);
+ }
+ template <typename T,
+ FMT_ENABLE_IF(
+ std::is_constructible<basic_string_view<char_type>, T>::value &&
+ !is_string<T>::value)>
+ FMT_CONSTEXPR basic_string_view<char_type> map(const T& val) {
+ return basic_string_view<char_type>(val);
+ }
+ FMT_CONSTEXPR const char* map(const signed char* val) {
+ static_assert(std::is_same<char_type, char>::value, "invalid string type");
+ return reinterpret_cast<const char*>(val);
+ }
+ FMT_CONSTEXPR const char* map(const unsigned char* val) {
+ static_assert(std::is_same<char_type, char>::value, "invalid string type");
+ return reinterpret_cast<const char*>(val);
+ }
+
+ FMT_CONSTEXPR const void* map(void* val) { return val; }
+ FMT_CONSTEXPR const void* map(const void* val) { return val; }
+ FMT_CONSTEXPR const void* map(std::nullptr_t val) { return val; }
+ template <typename T> FMT_CONSTEXPR int map(const T*) {
+ // Formatting of arbitrary pointers is disallowed. If you want to output
+ // a pointer cast it to "void *" or "const void *". In particular, this
+ // forbids formatting of "[const] volatile char *" which is printed as bool
+ // by iostreams.
+ static_assert(!sizeof(T), "formatting of non-void pointers is disallowed");
+ return 0;
+ }
+
+ template <typename T,
+ FMT_ENABLE_IF(std::is_enum<T>::value &&
+ !has_formatter<T, Context>::value &&
+ !has_fallback_formatter<T, Context>::value)>
+ FMT_CONSTEXPR int map(const T& val) {
+ return static_cast<int>(val);
+ }
+ template <typename T,
+ FMT_ENABLE_IF(!is_string<T>::value && !is_char<T>::value &&
+ (has_formatter<T, Context>::value ||
+ has_fallback_formatter<T, Context>::value))>
+ FMT_CONSTEXPR const T& map(const T& val) {
+ return val;
+ }
+
+ template <typename T>
+ FMT_CONSTEXPR const named_arg_base<char_type>& map(
+ const named_arg<T, char_type>& val) {
+ auto arg = make_arg<Context>(val.value);
+ std::memcpy(val.data, &arg, sizeof(arg));
+ return val;
+ }
+};
+
+// A type constant after applying arg_mapper<Context>.
+template <typename T, typename Context>
+using mapped_type_constant =
+ type_constant<decltype(arg_mapper<Context>().map(std::declval<T>())),
+ typename Context::char_type>;
+
+// Maximum number of arguments with packed types.
+enum { max_packed_args = 15 };
+enum : unsigned long long { is_unpacked_bit = 1ull << 63 };
+
+template <typename Context> class arg_map;
+} // namespace internal
+
+// A formatting argument. It is a trivially copyable/constructible type to
+// allow storage in basic_memory_buffer.
+template <typename Context> class basic_format_arg {
+ private:
+ internal::value<Context> value_;
+ internal::type type_;
+
+ template <typename ContextType, typename T>
+ friend FMT_CONSTEXPR basic_format_arg<ContextType> internal::make_arg(
+ const T& value);
+
+ template <typename Visitor, typename Ctx>
+ friend FMT_CONSTEXPR auto visit_format_arg(Visitor&& vis,
+ const basic_format_arg<Ctx>& arg)
+ -> decltype(vis(0));
+
+ friend class basic_format_args<Context>;
+ friend class internal::arg_map<Context>;
+
+ using char_type = typename Context::char_type;
+
+ public:
+ class handle {
+ public:
+ explicit handle(internal::custom_value<Context> custom) : custom_(custom) {}
+
+ void format(basic_parse_context<char_type>& parse_ctx, Context& ctx) const {
+ custom_.format(custom_.value, parse_ctx, ctx);
+ }
+
+ private:
+ internal::custom_value<Context> custom_;
+ };
+
+ FMT_CONSTEXPR basic_format_arg() : type_(internal::none_type) {}
+
+ FMT_CONSTEXPR explicit operator bool() const FMT_NOEXCEPT {
+ return type_ != internal::none_type;
+ }
+
+ internal::type type() const { return type_; }
+
+ bool is_integral() const { return internal::is_integral(type_); }
+ bool is_arithmetic() const { return internal::is_arithmetic(type_); }
+};
+
+/**
+ \rst
+ Visits an argument dispatching to the appropriate visit method based on
+ the argument type. For example, if the argument type is ``double`` then
+ ``vis(value)`` will be called with the value of type ``double``.
+ \endrst
+ */
+template <typename Visitor, typename Context>
+FMT_CONSTEXPR auto visit_format_arg(Visitor&& vis,
+ const basic_format_arg<Context>& arg)
+ -> decltype(vis(0)) {
+ using char_type = typename Context::char_type;
+ switch (arg.type_) {
+ case internal::none_type:
+ break;
+ case internal::named_arg_type:
+ FMT_ASSERT(false, "invalid argument type");
+ break;
+ case internal::int_type:
+ return vis(arg.value_.int_value);
+ case internal::uint_type:
+ return vis(arg.value_.uint_value);
+ case internal::long_long_type:
+ return vis(arg.value_.long_long_value);
+ case internal::ulong_long_type:
+ return vis(arg.value_.ulong_long_value);
+ case internal::bool_type:
+ return vis(arg.value_.bool_value);
+ case internal::char_type:
+ return vis(arg.value_.char_value);
+ case internal::double_type:
+ return vis(arg.value_.double_value);
+ case internal::long_double_type:
+ return vis(arg.value_.long_double_value);
+ case internal::cstring_type:
+ return vis(arg.value_.string.data);
+ case internal::string_type:
+ return vis(basic_string_view<char_type>(arg.value_.string.data,
+ arg.value_.string.size));
+ case internal::pointer_type:
+ return vis(arg.value_.pointer);
+ case internal::custom_type:
+ return vis(typename basic_format_arg<Context>::handle(arg.value_.custom));
+ }
+ return vis(monostate());
+}
namespace internal {
// A map from argument names to their values for named arguments.
-template <typename Context>
-class arg_map {
+template <typename Context> class arg_map {
private:
- arg_map(const arg_map &) = delete;
- void operator=(const arg_map &) = delete;
+ arg_map(const arg_map&) = delete;
+ void operator=(const arg_map&) = delete;
- typedef typename Context::char_type char_type;
+ using char_type = typename Context::char_type;
struct entry {
basic_string_view<char_type> name;
basic_format_arg<Context> arg;
};
- entry *map_;
+ entry* map_;
unsigned size_;
void push_back(value<Context> val) {
- const internal::named_arg_base<char_type> &named = val.as_named_arg();
- map_[size_] = entry{named.name, named.template deserialize<Context>()};
+ const auto& named = *val.named_arg;
+ map_[size_] = {named.name, named.template deserialize<Context>()};
++size_;
}
public:
- arg_map() : map_(FMT_NULL), size_(0) {}
- void init(const basic_format_args<Context> &args);
- ~arg_map() { delete [] map_; }
+ arg_map() : map_(nullptr), size_(0) {}
+ void init(const basic_format_args<Context>& args);
+ ~arg_map() { delete[] map_; }
basic_format_arg<Context> find(basic_string_view<char_type> name) const {
// The list is unsorted, so just return the first matching name.
for (entry *it = map_, *end = map_ + size_; it != end; ++it) {
- if (it->name == name)
- return it->arg;
+ if (it->name == name) return it->arg;
}
return {};
}
@@ -971,163 +984,97 @@
// A type-erased reference to an std::locale to avoid heavy <locale> include.
class locale_ref {
private:
- const void *locale_; // A type-erased pointer to std::locale.
- friend class locale;
+ const void* locale_; // A type-erased pointer to std::locale.
public:
- locale_ref() : locale_(FMT_NULL) {}
+ locale_ref() : locale_(nullptr) {}
+ template <typename Locale> explicit locale_ref(const Locale& loc);
- template <typename Locale>
- explicit locale_ref(const Locale &loc);
-
- template <typename Locale>
- Locale get() const;
+ template <typename Locale> Locale get() const;
};
-template <typename OutputIt, typename Context, typename Char>
-class context_base {
- public:
- typedef OutputIt iterator;
-
- private:
- basic_parse_context<Char> parse_context_;
- iterator out_;
- basic_format_args<Context> args_;
- locale_ref loc_;
-
- protected:
- typedef Char char_type;
- typedef basic_format_arg<Context> format_arg;
-
- context_base(OutputIt out, basic_string_view<char_type> format_str,
- basic_format_args<Context> 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) {
- format_arg arg = args_.get(arg_id);
- if (!arg)
- parse_context_.on_error("argument index out of range");
- return arg;
- }
-
- // Checks if manual indexing is used and returns the argument with
- // specified index.
- format_arg get_arg(unsigned arg_id) {
- return this->parse_context().check_arg_id(arg_id) ?
- this->do_get_arg(arg_id) : format_arg();
- }
-
- public:
- basic_parse_context<char_type> &parse_context() { return parse_context_; }
- basic_format_args<Context> args() const { return args_; } // DEPRECATED!
- basic_format_arg<Context> arg(unsigned id) const { return args_.get(id); }
-
- internal::error_handler error_handler() {
- return parse_context_.error_handler();
- }
-
- void on_error(const char *message) { parse_context_.on_error(message); }
-
- // Returns an iterator to the beginning of the output range.
- iterator out() { return out_; }
- iterator begin() { return out_; } // deprecated
-
- // Advances the begin iterator to ``it``.
- void advance_to(iterator it) { out_ = it; }
-
- locale_ref locale() { return loc_; }
-};
-
-template <typename Context, typename T>
-struct get_type {
- typedef decltype(make_value<Context>(
- declval<typename std::decay<T>::type&>())) value_type;
- static const type value = value_type::type_tag;
-};
-
-template <typename Context>
-FMT_CONSTEXPR11 unsigned long long get_types() { return 0; }
+template <typename> constexpr unsigned long long encode_types() { return 0; }
template <typename Context, typename Arg, typename... Args>
-FMT_CONSTEXPR11 unsigned long long get_types() {
- return get_type<Context, Arg>::value | (get_types<Context, Args...>() << 4);
+constexpr unsigned long long encode_types() {
+ return mapped_type_constant<Arg, Context>::value |
+ (encode_types<Context, Args...>() << 4);
}
template <typename Context, typename T>
-FMT_CONSTEXPR basic_format_arg<Context> make_arg(const T &value) {
+FMT_CONSTEXPR basic_format_arg<Context> make_arg(const T& value) {
basic_format_arg<Context> arg;
- arg.type_ = get_type<Context, T>::value;
- arg.value_ = make_value<Context>(value);
+ arg.type_ = mapped_type_constant<T, Context>::value;
+ arg.value_ = arg_mapper<Context>().map(value);
return arg;
}
-template <bool IS_PACKED, typename Context, typename T>
-inline typename std::enable_if<IS_PACKED, value<Context>>::type
- make_arg(const T &value) {
- return make_value<Context>(value);
+template <bool IS_PACKED, typename Context, typename T,
+ FMT_ENABLE_IF(IS_PACKED)>
+inline value<Context> make_arg(const T& val) {
+ return arg_mapper<Context>().map(val);
}
-template <bool IS_PACKED, typename Context, typename T>
-inline typename std::enable_if<!IS_PACKED, basic_format_arg<Context>>::type
- make_arg(const T &value) {
+template <bool IS_PACKED, typename Context, typename T,
+ FMT_ENABLE_IF(!IS_PACKED)>
+inline basic_format_arg<Context> make_arg(const T& value) {
return make_arg<Context>(value);
}
} // namespace internal
// Formatting context.
-template <typename OutputIt, typename Char>
-class basic_format_context :
- public internal::context_base<
- OutputIt, basic_format_context<OutputIt, Char>, Char> {
+template <typename OutputIt, typename Char> class basic_format_context {
public:
/** The character type for the output. */
- typedef Char char_type;
-
- // using formatter_type = formatter<T, char_type>;
- template <typename T>
- struct formatter_type { typedef formatter<T, char_type> type; };
+ using char_type = Char;
private:
+ OutputIt out_;
+ basic_format_args<basic_format_context> args_;
internal::arg_map<basic_format_context> map_;
+ internal::locale_ref loc_;
- basic_format_context(const basic_format_context &) = delete;
- void operator=(const basic_format_context &) = delete;
-
- typedef internal::context_base<OutputIt, basic_format_context, Char> base;
- typedef typename base::format_arg format_arg;
- using base::get_arg;
+ basic_format_context(const basic_format_context&) = delete;
+ void operator=(const basic_format_context&) = delete;
public:
- using typename base::iterator;
+ using iterator = OutputIt;
+ using format_arg = basic_format_arg<basic_format_context>;
+ template <typename T> using formatter_type = formatter<T, char_type>;
/**
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<char_type> format_str,
+ basic_format_context(OutputIt out,
basic_format_args<basic_format_context> ctx_args,
internal::locale_ref loc = internal::locale_ref())
- : base(out, format_str, ctx_args, loc) {}
+ : out_(out), args_(ctx_args), loc_(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); }
+ format_arg arg(int id) const { return args_.get(id); }
// Checks if manual indexing is used and returns the argument with the
// specified name.
- format_arg get_arg(basic_string_view<char_type> name);
+ format_arg arg(basic_string_view<char_type> name);
+
+ internal::error_handler error_handler() { return {}; }
+ void on_error(const char* message) { error_handler().on_error(message); }
+
+ // Returns an iterator to the beginning of the output range.
+ iterator out() { return out_; }
+
+ // Advances the begin iterator to ``it``.
+ void advance_to(iterator it) { out_ = it; }
+
+ internal::locale_ref locale() { return loc_; }
};
template <typename Char>
-struct buffer_context {
- typedef basic_format_context<
- std::back_insert_iterator<internal::basic_buffer<Char>>, Char> type;
-};
-typedef buffer_context<char>::type format_context;
-typedef buffer_context<wchar_t>::type wformat_context;
+using buffer_context =
+ basic_format_context<std::back_insert_iterator<internal::buffer<Char>>,
+ Char>;
+using format_context = buffer_context<char>;
+using wformat_context = buffer_context<wchar_t>;
/**
\rst
@@ -1136,74 +1083,48 @@
such as `~fmt::vformat`.
\endrst
*/
-template <typename Context, typename ...Args>
-class format_arg_store {
+template <typename Context, typename... Args> class format_arg_store {
private:
- static const size_t NUM_ARGS = sizeof...(Args);
+ static const size_t num_args = sizeof...(Args);
+ static const bool is_packed = num_args < internal::max_packed_args;
- // Packed is a macro on MinGW so use IS_PACKED instead.
- static const bool IS_PACKED = NUM_ARGS < internal::max_packed_args;
-
- typedef typename std::conditional<IS_PACKED,
- internal::value<Context>, basic_format_arg<Context>>::type value_type;
+ using value_type = conditional_t<is_packed, internal::value<Context>,
+ basic_format_arg<Context>>;
// If the arguments are not packed, add one more element to mark the end.
- static const size_t DATA_SIZE =
- NUM_ARGS + (IS_PACKED && NUM_ARGS != 0 ? 0 : 1);
- value_type data_[DATA_SIZE];
+ value_type data_[num_args + (num_args == 0 ? 1 : 0)];
friend class basic_format_args<Context>;
- static FMT_CONSTEXPR11 unsigned long long get_types() {
- return IS_PACKED ?
- internal::get_types<Context, Args...>() :
- internal::is_unpacked_bit | NUM_ARGS;
- }
-
public:
-#if FMT_USE_CONSTEXPR11
- static FMT_CONSTEXPR11 unsigned long long TYPES = get_types();
-#else
- static const unsigned long long TYPES;
-#endif
+ static constexpr unsigned long long types =
+ is_packed ? internal::encode_types<Context, Args...>()
+ : internal::is_unpacked_bit | num_args;
+ FMT_DEPRECATED static constexpr unsigned long long TYPES = types;
-#if (FMT_GCC_VERSION && FMT_GCC_VERSION <= 405) || \
- (FMT_MSC_VER && FMT_MSC_VER <= 1800)
- // Workaround array initialization issues in gcc <= 4.5 and MSVC <= 2013.
- format_arg_store(const Args &... args) {
- value_type init[DATA_SIZE] =
- {internal::make_arg<IS_PACKED, Context>(args)...};
- std::memcpy(data_, init, sizeof(init));
- }
-#else
- format_arg_store(const Args &... args)
- : data_{internal::make_arg<IS_PACKED, Context>(args)...} {}
-#endif
+ format_arg_store(const Args&... args)
+ : data_{internal::make_arg<is_packed, Context>(args)...} {}
};
-#if !FMT_USE_CONSTEXPR11
-template <typename Context, typename ...Args>
-const unsigned long long format_arg_store<Context, Args...>::TYPES =
- get_types();
-#endif
-
/**
\rst
Constructs an `~fmt::format_arg_store` object that contains references to
arguments and can be implicitly converted to `~fmt::format_args`. `Context`
can be omitted in which case it defaults to `~fmt::context`.
+ See `~fmt::arg` for lifetime considerations.
\endrst
*/
-template <typename Context = format_context, typename ...Args>
-inline format_arg_store<Context, Args...>
- make_format_args(const Args &... args) { return {args...}; }
+template <typename Context = format_context, typename... Args>
+inline format_arg_store<Context, Args...> make_format_args(
+ const Args&... args) {
+ return {args...};
+}
/** Formatting arguments. */
-template <typename Context>
-class basic_format_args {
+template <typename Context> class basic_format_args {
public:
- typedef unsigned size_type;
- typedef basic_format_arg<Context> format_arg;
+ using size_type = int;
+ using format_arg = basic_format_arg<Context>;
private:
// To reduce compiled code size per formatting function call, types of first
@@ -1215,37 +1136,33 @@
// This is done to reduce compiled code size as storing larger objects
// may require more code (at least on x86-64) even if the same amount of
// data is actually copied to stack. It saves ~10% on the bloat test.
- const internal::value<Context> *values_;
- const format_arg *args_;
+ const internal::value<Context>* values_;
+ 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;
- return static_cast<typename internal::type>(
- (types_ & (0xfull << shift)) >> shift);
+ internal::type type(int index) const {
+ int shift = index * 4;
+ return static_cast<internal::type>((types_ & (0xfull << shift)) >> shift);
}
friend class internal::arg_map<Context>;
- void set_data(const internal::value<Context> *values) { values_ = values; }
- void set_data(const format_arg *args) { args_ = args; }
+ void set_data(const internal::value<Context>* values) { values_ = values; }
+ void set_data(const format_arg* args) { args_ = args; }
- format_arg do_get(size_type index) const {
+ format_arg do_get(int index) const {
format_arg arg;
if (!is_packed()) {
auto num_args = max_size();
- if (index < num_args)
- arg = args_[index];
+ if (index < num_args) arg = args_[index];
return arg;
}
- if (index > internal::max_packed_args)
- return arg;
+ if (index > internal::max_packed_args) return arg;
arg.type_ = type(index);
- if (arg.type_ == internal::none_type)
- return arg;
- internal::value<Context> &val = arg.value_;
+ if (arg.type_ == internal::none_type) return arg;
+ internal::value<Context>& val = arg.value_;
val = values_[index];
return arg;
}
@@ -1259,8 +1176,8 @@
\endrst
*/
template <typename... Args>
- basic_format_args(const format_arg_store<Context, Args...> &store)
- : types_(static_cast<unsigned long long>(store.TYPES)) {
+ basic_format_args(const format_arg_store<Context, Args...>& store)
+ : types_(static_cast<unsigned long long>(store.types)) {
set_data(store.data_);
}
@@ -1269,131 +1186,133 @@
Constructs a `basic_format_args` object from a dynamic set of arguments.
\endrst
*/
- basic_format_args(const format_arg *args, size_type count)
- : types_(internal::is_unpacked_bit | count) {
+ basic_format_args(const format_arg* args, int count)
+ : types_(internal::is_unpacked_bit | internal::to_unsigned(count)) {
set_data(args);
}
/** Returns the argument at specified index. */
- format_arg get(size_type index) const {
+ format_arg get(int index) const {
format_arg arg = do_get(index);
if (arg.type_ == internal::named_arg_type)
- arg = arg.value_.as_named_arg().template deserialize<Context>();
+ arg = arg.value_.named_arg->template deserialize<Context>();
return arg;
}
- size_type max_size() const {
+ int max_size() const {
unsigned long long max_packed = internal::max_packed_args;
- return static_cast<size_type>(
- is_packed() ? max_packed : types_ & ~internal::is_unpacked_bit);
+ return static_cast<int>(is_packed() ? max_packed
+ : types_ & ~internal::is_unpacked_bit);
}
};
/** An alias to ``basic_format_args<context>``. */
-// It is a separate type rather than a typedef to make symbols readable.
+// It is a separate type rather than an alias to make symbols readable.
struct format_args : basic_format_args<format_context> {
- template <typename ...Args>
- format_args(Args &&... arg)
- : basic_format_args<format_context>(std::forward<Args>(arg)...) {}
+ template <typename... Args>
+ format_args(Args&&... args)
+ : basic_format_args<format_context>(std::forward<Args>(args)...) {}
};
struct wformat_args : basic_format_args<wformat_context> {
- template <typename ...Args>
- wformat_args(Args &&... arg)
- : basic_format_args<wformat_context>(std::forward<Args>(arg)...) {}
+ template <typename... Args>
+ wformat_args(Args&&... args)
+ : basic_format_args<wformat_context>(std::forward<Args>(args)...) {}
};
-#define FMT_ENABLE_IF_T(B, T) typename std::enable_if<B, T>::type
+template <typename Container> struct is_contiguous : std::false_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 <typename S>
-using char_t = FMT_ENABLE_IF_T(
- internal::is_string<S>::value, typename internal::char_t<S>::type);
-#define FMT_CHAR(S) fmt::char_t<S>
-#else
-template <typename S>
-struct char_t : std::enable_if<
- internal::is_string<S>::value, typename internal::char_t<S>::type> {};
-#define FMT_CHAR(S) typename char_t<S>::type
-#endif
+template <typename Char>
+struct is_contiguous<std::basic_string<Char>> : std::true_type {};
+
+template <typename Char>
+struct is_contiguous<internal::buffer<Char>> : std::true_type {};
namespace internal {
-template <typename Char>
-struct named_arg_base {
+
+template <typename OutputIt>
+struct is_contiguous_back_insert_iterator : std::false_type {};
+template <typename Container>
+struct is_contiguous_back_insert_iterator<std::back_insert_iterator<Container>>
+ : is_contiguous<Container> {};
+
+template <typename Char> struct named_arg_base {
basic_string_view<Char> name;
// Serialized value<context>.
- mutable char data[
- sizeof(basic_format_arg<typename buffer_context<Char>::type>)];
+ mutable char data[sizeof(basic_format_arg<buffer_context<Char>>)];
named_arg_base(basic_string_view<Char> nm) : name(nm) {}
- template <typename Context>
- basic_format_arg<Context> deserialize() const {
+ template <typename Context> basic_format_arg<Context> deserialize() const {
basic_format_arg<Context> arg;
std::memcpy(&arg, data, sizeof(basic_format_arg<Context>));
return arg;
}
};
-template <typename T, typename Char>
-struct named_arg : named_arg_base<Char> {
- const T &value;
+template <typename T, typename Char> struct named_arg : named_arg_base<Char> {
+ const T& value;
- named_arg(basic_string_view<Char> name, const T &val)
- : named_arg_base<Char>(name), value(val) {}
+ named_arg(basic_string_view<Char> name, const T& val)
+ : named_arg_base<Char>(name), value(val) {}
};
-template <typename... Args, typename S>
-inline typename std::enable_if<!is_compile_string<S>::value>::type
- check_format_string(const S &) {}
-template <typename... Args, typename S>
-typename std::enable_if<is_compile_string<S>::value>::type
- check_format_string(S);
-
-template <typename S, typename... Args>
-struct checked_args : format_arg_store<
- typename buffer_context<FMT_CHAR(S)>::type, Args...> {
- typedef typename buffer_context<FMT_CHAR(S)>::type context;
-
- checked_args(const S &format_str, const Args &... args):
- format_arg_store<context, Args...>(args...) {
- internal::check_format_string<Args...>(format_str);
- }
-
- basic_format_args<context> operator*() const { return *this; }
-};
-
-template <typename Char>
-std::basic_string<Char> vformat(
- basic_string_view<Char> format_str,
- basic_format_args<typename buffer_context<Char>::type> args);
-
-template <typename Char>
-typename buffer_context<Char>::type::iterator vformat_to(
- internal::basic_buffer<Char> &buf, basic_string_view<Char> format_str,
- basic_format_args<typename buffer_context<Char>::type> args);
+template <typename..., typename S, FMT_ENABLE_IF(!is_compile_string<S>::value)>
+inline void check_format_string(const S&) {
+#if defined(FMT_ENFORCE_COMPILE_STRING)
+ static_assert(is_compile_string<S>::value,
+ "FMT_ENFORCE_COMPILE_STRING requires all format strings to "
+ "utilize FMT_STRING() or fmt().");
+#endif
}
+template <typename..., typename S, FMT_ENABLE_IF(is_compile_string<S>::value)>
+void check_format_string(S);
+
+struct view {};
+template <bool...> struct bool_pack;
+template <bool... Args>
+using all_true =
+ std::is_same<bool_pack<Args..., true>, bool_pack<true, Args...>>;
+
+template <typename... Args, typename S, typename Char = char_t<S>>
+inline format_arg_store<buffer_context<Char>, remove_reference_t<Args>...>
+make_args_checked(const S& format_str,
+ const remove_reference_t<Args>&... args) {
+ static_assert(all_true<(!std::is_base_of<view, remove_reference_t<Args>>() ||
+ !std::is_reference<Args>())...>::value,
+ "passing views as lvalues is disallowed");
+ check_format_string<remove_const_t<remove_reference_t<Args>>...>(format_str);
+ return {args...};
+}
+
+template <typename Char>
+std::basic_string<Char> vformat(basic_string_view<Char> format_str,
+ basic_format_args<buffer_context<Char>> args);
+
+template <typename Char>
+typename buffer_context<Char>::iterator vformat_to(
+ buffer<Char>& buf, basic_string_view<Char> format_str,
+ basic_format_args<buffer_context<Char>> args);
+} // namespace internal
/**
\rst
Returns a named argument to be used in a formatting function.
+ The named argument holds a reference and does not extend the lifetime
+ of its arguments.
+ Consequently, a dangling reference can accidentally be created.
+ The user should take care to only pass this function temporaries when
+ the named argument is itself a temporary, as per the following example.
+
**Example**::
fmt::print("Elapsed time: {s:.2f} seconds", fmt::arg("s", 1.23));
\endrst
*/
-template <typename T>
-inline internal::named_arg<T, char> arg(string_view name, const T &arg) {
- return {name, arg};
-}
-
-template <typename T>
-inline internal::named_arg<T, wchar_t> arg(wstring_view name, const T &arg) {
+template <typename S, typename T, typename Char = char_t<S>>
+inline internal::named_arg<T, Char> arg(const S& name, const T& arg) {
+ static_assert(internal::is_string<S>::value, "");
return {name, arg};
}
@@ -1401,42 +1320,34 @@
template <typename S, typename T, typename Char>
void arg(S, internal::named_arg<T, Char>) = delete;
-template <typename Container>
-struct is_contiguous: std::false_type {};
-
-template <typename Char>
-struct is_contiguous<std::basic_string<Char> >: std::true_type {};
-
-template <typename Char>
-struct is_contiguous<internal::basic_buffer<Char> >: std::true_type {};
-
/** Formats a string and writes the output to ``out``. */
-template <typename Container, typename S>
-typename std::enable_if<
- is_contiguous<Container>::value, std::back_insert_iterator<Container>>::type
- vformat_to(
- std::back_insert_iterator<Container> out,
- const S &format_str,
- basic_format_args<typename buffer_context<FMT_CHAR(S)>::type> args) {
- internal::container_buffer<Container> buf(internal::get_container(out));
+// GCC 8 and earlier cannot handle std::back_insert_iterator<Container> with
+// vformat_to<ArgFormatter>(...) overload, so SFINAE on iterator type instead.
+template <typename OutputIt, typename S, typename Char = char_t<S>,
+ FMT_ENABLE_IF(
+ internal::is_contiguous_back_insert_iterator<OutputIt>::value)>
+OutputIt vformat_to(OutputIt out, const S& format_str,
+ basic_format_args<buffer_context<Char>> args) {
+ using container = remove_reference_t<decltype(internal::get_container(out))>;
+ internal::container_buffer<container> buf((internal::get_container(out)));
internal::vformat_to(buf, to_string_view(format_str), args);
return out;
}
-template <typename Container, typename S, typename... Args>
-inline typename std::enable_if<
- is_contiguous<Container>::value && internal::is_string<S>::value,
- std::back_insert_iterator<Container>>::type
- format_to(std::back_insert_iterator<Container> out, const S &format_str,
- const Args &... args) {
- internal::checked_args<S, Args...> ca(format_str, args...);
- return vformat_to(out, to_string_view(format_str), *ca);
+template <typename Container, typename S, typename... Args,
+ FMT_ENABLE_IF(
+ is_contiguous<Container>::value&& internal::is_string<S>::value)>
+inline std::back_insert_iterator<Container> format_to(
+ std::back_insert_iterator<Container> out, const S& format_str,
+ Args&&... args) {
+ return vformat_to(
+ out, to_string_view(format_str),
+ {internal::make_args_checked<Args...>(format_str, args...)});
}
-template <typename S, typename Char = FMT_CHAR(S)>
+template <typename S, typename Char = char_t<S>>
inline std::basic_string<Char> vformat(
- const S &format_str,
- basic_format_args<typename buffer_context<Char>::type> args) {
+ const S& format_str, basic_format_args<buffer_context<Char>> args) {
return internal::vformat(to_string_view(format_str), args);
}
@@ -1450,16 +1361,17 @@
std::string message = fmt::format("The answer is {}", 42);
\endrst
*/
-template <typename S, typename... Args>
-inline std::basic_string<FMT_CHAR(S)> format(
- const S &format_str, const Args &... args) {
+// Pass char_t as a default template parameter instead of using
+// std::basic_string<char_t<S>> to reduce the symbol size.
+template <typename S, typename... Args, typename Char = char_t<S>>
+inline std::basic_string<Char> format(const S& format_str, Args&&... args) {
return internal::vformat(
- to_string_view(format_str),
- *internal::checked_args<S, Args...>(format_str, args...));
+ to_string_view(format_str),
+ {internal::make_args_checked<Args...>(format_str, args...)});
}
-FMT_API void vprint(std::FILE *f, string_view format_str, format_args args);
-FMT_API void vprint(std::FILE *f, wstring_view format_str, wformat_args args);
+FMT_API void vprint(std::FILE* f, string_view format_str, format_args args);
+FMT_API void vprint(std::FILE* f, wstring_view format_str, wformat_args args);
/**
\rst
@@ -1472,11 +1384,11 @@
fmt::print(stderr, "Don't {}!", "panic");
\endrst
*/
-template <typename S, typename... Args>
-inline FMT_ENABLE_IF_T(internal::is_string<S>::value, void)
- print(std::FILE *f, const S &format_str, const Args &... args) {
+template <typename S, typename... Args,
+ FMT_ENABLE_IF(internal::is_string<S>::value)>
+inline void print(std::FILE* f, const S& format_str, Args&&... args) {
vprint(f, to_string_view(format_str),
- internal::checked_args<S, Args...>(format_str, args...));
+ internal::make_args_checked<Args...>(format_str, args...));
}
FMT_API void vprint(string_view format_str, format_args args);
@@ -1491,11 +1403,11 @@
fmt::print("Elapsed time: {0:.2f} seconds", 1.23);
\endrst
*/
-template <typename S, typename... Args>
-inline FMT_ENABLE_IF_T(internal::is_string<S>::value, void)
- print(const S &format_str, const Args &... args) {
+template <typename S, typename... Args,
+ FMT_ENABLE_IF(internal::is_string<S>::value)>
+inline void print(const S& format_str, Args&&... args) {
vprint(to_string_view(format_str),
- internal::checked_args<S, Args...>(format_str, args...));
+ internal::make_args_checked<Args...>(format_str, args...));
}
FMT_END_NAMESPACE
diff --git a/include/fmt/format-inl.h b/include/fmt/format-inl.h
index 552c943..147062f 100644
--- a/include/fmt/format-inl.h
+++ b/include/fmt/format-inl.h
@@ -19,73 +19,67 @@
#include <cstdarg>
#include <cstddef> // for std::ptrdiff_t
#include <cstring> // for std::memmove
+#include <cwchar>
#if !defined(FMT_STATIC_THOUSANDS_SEPARATOR)
-# include <locale>
+# include <locale>
#endif
#if FMT_USE_WINDOWS_H
-# if !defined(FMT_HEADER_ONLY) && !defined(WIN32_LEAN_AND_MEAN)
-# define WIN32_LEAN_AND_MEAN
-# endif
-# if defined(NOMINMAX) || defined(FMT_WIN_MINMAX)
-# include <windows.h>
-# else
-# define NOMINMAX
-# include <windows.h>
-# undef NOMINMAX
-# endif
+# if !defined(FMT_HEADER_ONLY) && !defined(WIN32_LEAN_AND_MEAN)
+# define WIN32_LEAN_AND_MEAN
+# endif
+# if defined(NOMINMAX) || defined(FMT_WIN_MINMAX)
+# include <windows.h>
+# else
+# define NOMINMAX
+# include <windows.h>
+# undef NOMINMAX
+# endif
#endif
#if FMT_EXCEPTIONS
-# define FMT_TRY try
-# define FMT_CATCH(x) catch (x)
+# define FMT_TRY try
+# define FMT_CATCH(x) catch (x)
#else
-# define FMT_TRY if (true)
-# define FMT_CATCH(x) if (false)
+# define FMT_TRY if (true)
+# define FMT_CATCH(x) if (false)
#endif
#ifdef _MSC_VER
-# pragma warning(push)
-# pragma warning(disable: 4127) // conditional expression is constant
-# pragma warning(disable: 4702) // unreachable code
+# pragma warning(push)
+# pragma warning(disable : 4127) // conditional expression is constant
+# pragma warning(disable : 4702) // unreachable code
// Disable deprecation warning for strerror. The latter is not called but
// MSVC fails to detect it.
-# pragma warning(disable: 4996)
+# pragma warning(disable : 4996)
#endif
// Dummy implementations of strerror_r and strerror_s called if corresponding
// system functions are not available.
-inline fmt::internal::null<> strerror_r(int, char *, ...) {
+inline fmt::internal::null<> strerror_r(int, char*, ...) {
return fmt::internal::null<>();
}
-inline fmt::internal::null<> strerror_s(char *, std::size_t, ...) {
+inline fmt::internal::null<> strerror_s(char*, std::size_t, ...) {
return fmt::internal::null<>();
}
FMT_BEGIN_NAMESPACE
-
-namespace {
+namespace internal {
#ifndef _MSC_VER
-# define FMT_SNPRINTF snprintf
+# define FMT_SNPRINTF snprintf
#else // _MSC_VER
-inline int fmt_snprintf(char *buffer, size_t size, const char *format, ...) {
+inline int fmt_snprintf(char* buffer, size_t size, const char* format, ...) {
va_list args;
va_start(args, format);
int result = vsnprintf_s(buffer, size, _TRUNCATE, format, args);
va_end(args);
return result;
}
-# define FMT_SNPRINTF fmt_snprintf
+# define FMT_SNPRINTF fmt_snprintf
#endif // _MSC_VER
-#if defined(_WIN32) && defined(__MINGW32__) && !defined(__NO_ISOCEXT)
-# define FMT_SWPRINTF snwprintf
-#else
-# define FMT_SWPRINTF swprintf
-#endif // defined(_WIN32) && defined(__MINGW32__) && !defined(__NO_ISOCEXT)
-
-typedef void (*FormatFunc)(internal::buffer &, int, string_view);
+using format_func = void (*)(internal::buffer<char>&, int, string_view);
// Portable thread-safe version of strerror.
// Sets buffer to point to a string describing the error code.
@@ -96,18 +90,18 @@
// ERANGE - buffer is not large enough to store the error message
// other - failure
// Buffer should be at least of size 1.
-int safe_strerror(
- int error_code, char *&buffer, std::size_t buffer_size) FMT_NOEXCEPT {
- FMT_ASSERT(buffer != FMT_NULL && buffer_size != 0, "invalid buffer");
+FMT_FUNC int safe_strerror(int error_code, char*& buffer,
+ std::size_t buffer_size) FMT_NOEXCEPT {
+ FMT_ASSERT(buffer != nullptr && buffer_size != 0, "invalid buffer");
class dispatcher {
private:
int error_code_;
- char *&buffer_;
+ char*& buffer_;
std::size_t buffer_size_;
// A noop assignment operator to avoid bogus warnings.
- void operator=(const dispatcher &) {}
+ void operator=(const dispatcher&) {}
// Handle the result of XSI-compliant version of strerror_r.
int handle(int result) {
@@ -116,7 +110,7 @@
}
// Handle the result of GNU-specific version of strerror_r.
- int handle(char *message) {
+ int handle(char* message) {
// If the buffer is full then the message is probably truncated.
if (message == buffer_ && strlen(buffer_) == buffer_size_ - 1)
return ERANGE;
@@ -132,8 +126,8 @@
// Fallback to strerror_s when strerror_r is not available.
int fallback(int result) {
// If the buffer is full then the message is probably truncated.
- return result == 0 && strlen(buffer_) == buffer_size_ - 1 ?
- ERANGE : result;
+ return result == 0 && strlen(buffer_) == buffer_size_ - 1 ? ERANGE
+ : result;
}
#if !FMT_MSC_VER
@@ -146,18 +140,16 @@
#endif
public:
- dispatcher(int err_code, char *&buf, std::size_t buf_size)
- : error_code_(err_code), buffer_(buf), buffer_size_(buf_size) {}
+ dispatcher(int err_code, char*& buf, std::size_t buf_size)
+ : error_code_(err_code), buffer_(buf), buffer_size_(buf_size) {}
- int run() {
- return handle(strerror_r(error_code_, buffer_, buffer_size_));
- }
+ int run() { return handle(strerror_r(error_code_, buffer_, buffer_size_)); }
};
return dispatcher(error_code, buffer, buffer_size).run();
}
-void format_error_code(internal::buffer &out, int error_code,
- string_view message) FMT_NOEXCEPT {
+FMT_FUNC void format_error_code(internal::buffer<char>& out, int error_code,
+ string_view message) FMT_NOEXCEPT {
// Report error code making sure that the output fits into
// inline_buffer_size to avoid dynamic memory allocation and potential
// bad_alloc.
@@ -166,14 +158,13 @@
static const char ERROR_STR[] = "error ";
// Subtract 2 to account for terminating null characters in SEP and ERROR_STR.
std::size_t error_code_size = sizeof(SEP) + sizeof(ERROR_STR) - 2;
- typedef internal::int_traits<int>::main_type main_type;
- main_type abs_value = static_cast<main_type>(error_code);
+ auto abs_value = static_cast<uint32_or_64_t<int>>(error_code);
if (internal::is_negative(error_code)) {
abs_value = 0 - abs_value;
++error_code_size;
}
error_code_size += internal::to_unsigned(internal::count_digits(abs_value));
- writer w(out);
+ internal::writer w(out);
if (message.size() <= inline_buffer_size - error_code_size) {
w.write(message);
w.write(SEP);
@@ -183,206 +174,214 @@
assert(out.size() <= inline_buffer_size);
}
-void report_error(FormatFunc func, int error_code,
- string_view message) FMT_NOEXCEPT {
+// A wrapper around fwrite that throws on error.
+FMT_FUNC void fwrite_fully(const void* ptr, size_t size, size_t count,
+ FILE* stream) {
+ size_t written = std::fwrite(ptr, size, count, stream);
+ if (written < count) {
+ FMT_THROW(system_error(errno, "cannot write to file"));
+ }
+}
+
+FMT_FUNC void report_error(format_func func, int error_code,
+ string_view message) FMT_NOEXCEPT {
memory_buffer full_message;
func(full_message, error_code, message);
- // Use Writer::data instead of Writer::c_str to avoid potential memory
- // allocation.
- std::fwrite(full_message.data(), full_message.size(), 1, stderr);
+ // Don't use fwrite_fully because the latter may throw.
+ (void)std::fwrite(full_message.data(), full_message.size(), 1, stderr);
std::fputc('\n', stderr);
}
-} // namespace
-
-FMT_FUNC size_t internal::count_code_points(basic_string_view<char8_t> s) {
- const char8_t *data = s.data();
- size_t num_code_points = 0;
- for (size_t i = 0, size = s.size(); i != size; ++i) {
- if ((data[i] & 0xc0) != 0x80)
- ++num_code_points;
- }
- return num_code_points;
-}
+} // namespace internal
#if !defined(FMT_STATIC_THOUSANDS_SEPARATOR)
namespace internal {
template <typename Locale>
-locale_ref::locale_ref(const Locale &loc) : locale_(&loc) {
+locale_ref::locale_ref(const Locale& loc) : locale_(&loc) {
static_assert(std::is_same<Locale, std::locale>::value, "");
}
-template <typename Locale>
-Locale locale_ref::get() const {
+template <typename Locale> Locale locale_ref::get() const {
static_assert(std::is_same<Locale, std::locale>::value, "");
return locale_ ? *static_cast<const std::locale*>(locale_) : std::locale();
}
-template <typename Char>
-FMT_FUNC Char thousands_sep_impl(locale_ref loc) {
- return std::use_facet<std::numpunct<Char> >(
- loc.get<std::locale>()).thousands_sep();
+template <typename Char> FMT_FUNC Char thousands_sep_impl(locale_ref loc) {
+ return std::use_facet<std::numpunct<Char>>(loc.get<std::locale>())
+ .thousands_sep();
}
+template <typename Char> FMT_FUNC Char decimal_point_impl(locale_ref loc) {
+ return std::use_facet<std::numpunct<Char>>(loc.get<std::locale>())
+ .decimal_point();
}
+} // namespace internal
#else
template <typename Char>
FMT_FUNC Char internal::thousands_sep_impl(locale_ref) {
return FMT_STATIC_THOUSANDS_SEPARATOR;
}
+template <typename Char>
+FMT_FUNC Char internal::decimal_point_impl(locale_ref) {
+ return '.';
+}
#endif
-FMT_FUNC void system_error::init(
- int err_code, string_view format_str, format_args args) {
+FMT_API FMT_FUNC format_error::~format_error() FMT_NOEXCEPT {}
+FMT_API FMT_FUNC system_error::~system_error() FMT_NOEXCEPT {}
+
+FMT_FUNC void system_error::init(int err_code, string_view format_str,
+ format_args args) {
error_code_ = err_code;
memory_buffer buffer;
format_system_error(buffer, err_code, vformat(format_str, args));
- std::runtime_error &base = *this;
+ std::runtime_error& base = *this;
base = std::runtime_error(to_string(buffer));
}
namespace internal {
-template <typename T>
-int char_traits<char>::format_float(
- char *buf, std::size_t size, const char *format, int precision, T value) {
- return precision < 0 ?
- FMT_SNPRINTF(buf, size, format, value) :
- FMT_SNPRINTF(buf, size, format, precision, value);
+
+template <> FMT_FUNC int count_digits<4>(internal::fallback_uintptr n) {
+ // Assume little endian; pointer formatting is implementation-defined anyway.
+ int i = static_cast<int>(sizeof(void*)) - 1;
+ while (i > 0 && n.value[i] == 0) --i;
+ auto char_digits = std::numeric_limits<unsigned char>::digits / 4;
+ return i >= 0 ? i * char_digits + count_digits<4, unsigned>(n.value[i]) : 1;
}
template <typename T>
-int char_traits<wchar_t>::format_float(
- wchar_t *buf, std::size_t size, const wchar_t *format, int precision,
- T value) {
- return precision < 0 ?
- FMT_SWPRINTF(buf, size, format, value) :
- FMT_SWPRINTF(buf, size, format, precision, value);
+int format_float(char* buf, std::size_t size, const char* format, int precision,
+ T value) {
+#ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
+ if (precision > 100000)
+ throw std::runtime_error(
+ "fuzz mode - avoid large allocation inside snprintf");
+#endif
+ // Suppress the warning about nonliteral format string.
+ auto snprintf_ptr = FMT_SNPRINTF;
+ return precision < 0 ? snprintf_ptr(buf, size, format, value)
+ : snprintf_ptr(buf, size, format, precision, value);
}
template <typename T>
-const char basic_data<T>::DIGITS[] =
+const char basic_data<T>::digits[] =
"0001020304050607080910111213141516171819"
"2021222324252627282930313233343536373839"
"4041424344454647484950515253545556575859"
"6061626364656667686970717273747576777879"
"8081828384858687888990919293949596979899";
-#define FMT_POWERS_OF_10(factor) \
- factor * 10, \
- factor * 100, \
- factor * 1000, \
- factor * 10000, \
- factor * 100000, \
- factor * 1000000, \
- factor * 10000000, \
- factor * 100000000, \
- factor * 1000000000
+template <typename T>
+const char basic_data<T>::hex_digits[] = "0123456789abcdef";
+
+#define FMT_POWERS_OF_10(factor) \
+ factor * 10, factor * 100, factor * 1000, factor * 10000, factor * 100000, \
+ factor * 1000000, factor * 10000000, factor * 100000000, \
+ factor * 1000000000
template <typename T>
-const uint32_t basic_data<T>::POWERS_OF_10_32[] = {
- 1, FMT_POWERS_OF_10(1)
-};
+const uint64_t basic_data<T>::powers_of_10_64[] = {
+ 1, FMT_POWERS_OF_10(1), FMT_POWERS_OF_10(1000000000ull),
+ 10000000000000000000ull};
template <typename T>
-const uint32_t basic_data<T>::ZERO_OR_POWERS_OF_10_32[] = {
- 0, FMT_POWERS_OF_10(1)
-};
+const uint32_t basic_data<T>::zero_or_powers_of_10_32[] = {0,
+ FMT_POWERS_OF_10(1)};
template <typename T>
-const uint64_t basic_data<T>::ZERO_OR_POWERS_OF_10_64[] = {
- 0,
- FMT_POWERS_OF_10(1),
- FMT_POWERS_OF_10(1000000000ull),
- 10000000000000000000ull
-};
+const uint64_t basic_data<T>::zero_or_powers_of_10_64[] = {
+ 0, FMT_POWERS_OF_10(1), FMT_POWERS_OF_10(1000000000ull),
+ 10000000000000000000ull};
// Normalized 64-bit significands of pow(10, k), for k = -348, -340, ..., 340.
// These are generated by support/compute-powers.py.
template <typename T>
-const uint64_t basic_data<T>::POW10_SIGNIFICANDS[] = {
- 0xfa8fd5a0081c0288, 0xbaaee17fa23ebf76, 0x8b16fb203055ac76,
- 0xcf42894a5dce35ea, 0x9a6bb0aa55653b2d, 0xe61acf033d1a45df,
- 0xab70fe17c79ac6ca, 0xff77b1fcbebcdc4f, 0xbe5691ef416bd60c,
- 0x8dd01fad907ffc3c, 0xd3515c2831559a83, 0x9d71ac8fada6c9b5,
- 0xea9c227723ee8bcb, 0xaecc49914078536d, 0x823c12795db6ce57,
- 0xc21094364dfb5637, 0x9096ea6f3848984f, 0xd77485cb25823ac7,
- 0xa086cfcd97bf97f4, 0xef340a98172aace5, 0xb23867fb2a35b28e,
- 0x84c8d4dfd2c63f3b, 0xc5dd44271ad3cdba, 0x936b9fcebb25c996,
- 0xdbac6c247d62a584, 0xa3ab66580d5fdaf6, 0xf3e2f893dec3f126,
- 0xb5b5ada8aaff80b8, 0x87625f056c7c4a8b, 0xc9bcff6034c13053,
- 0x964e858c91ba2655, 0xdff9772470297ebd, 0xa6dfbd9fb8e5b88f,
- 0xf8a95fcf88747d94, 0xb94470938fa89bcf, 0x8a08f0f8bf0f156b,
- 0xcdb02555653131b6, 0x993fe2c6d07b7fac, 0xe45c10c42a2b3b06,
- 0xaa242499697392d3, 0xfd87b5f28300ca0e, 0xbce5086492111aeb,
- 0x8cbccc096f5088cc, 0xd1b71758e219652c, 0x9c40000000000000,
- 0xe8d4a51000000000, 0xad78ebc5ac620000, 0x813f3978f8940984,
- 0xc097ce7bc90715b3, 0x8f7e32ce7bea5c70, 0xd5d238a4abe98068,
- 0x9f4f2726179a2245, 0xed63a231d4c4fb27, 0xb0de65388cc8ada8,
- 0x83c7088e1aab65db, 0xc45d1df942711d9a, 0x924d692ca61be758,
- 0xda01ee641a708dea, 0xa26da3999aef774a, 0xf209787bb47d6b85,
- 0xb454e4a179dd1877, 0x865b86925b9bc5c2, 0xc83553c5c8965d3d,
- 0x952ab45cfa97a0b3, 0xde469fbd99a05fe3, 0xa59bc234db398c25,
- 0xf6c69a72a3989f5c, 0xb7dcbf5354e9bece, 0x88fcf317f22241e2,
- 0xcc20ce9bd35c78a5, 0x98165af37b2153df, 0xe2a0b5dc971f303a,
- 0xa8d9d1535ce3b396, 0xfb9b7cd9a4a7443c, 0xbb764c4ca7a44410,
- 0x8bab8eefb6409c1a, 0xd01fef10a657842c, 0x9b10a4e5e9913129,
- 0xe7109bfba19c0c9d, 0xac2820d9623bf429, 0x80444b5e7aa7cf85,
- 0xbf21e44003acdd2d, 0x8e679c2f5e44ff8f, 0xd433179d9c8cb841,
- 0x9e19db92b4e31ba9, 0xeb96bf6ebadf77d9, 0xaf87023b9bf0ee6b,
+const uint64_t basic_data<T>::pow10_significands[] = {
+ 0xfa8fd5a0081c0288, 0xbaaee17fa23ebf76, 0x8b16fb203055ac76,
+ 0xcf42894a5dce35ea, 0x9a6bb0aa55653b2d, 0xe61acf033d1a45df,
+ 0xab70fe17c79ac6ca, 0xff77b1fcbebcdc4f, 0xbe5691ef416bd60c,
+ 0x8dd01fad907ffc3c, 0xd3515c2831559a83, 0x9d71ac8fada6c9b5,
+ 0xea9c227723ee8bcb, 0xaecc49914078536d, 0x823c12795db6ce57,
+ 0xc21094364dfb5637, 0x9096ea6f3848984f, 0xd77485cb25823ac7,
+ 0xa086cfcd97bf97f4, 0xef340a98172aace5, 0xb23867fb2a35b28e,
+ 0x84c8d4dfd2c63f3b, 0xc5dd44271ad3cdba, 0x936b9fcebb25c996,
+ 0xdbac6c247d62a584, 0xa3ab66580d5fdaf6, 0xf3e2f893dec3f126,
+ 0xb5b5ada8aaff80b8, 0x87625f056c7c4a8b, 0xc9bcff6034c13053,
+ 0x964e858c91ba2655, 0xdff9772470297ebd, 0xa6dfbd9fb8e5b88f,
+ 0xf8a95fcf88747d94, 0xb94470938fa89bcf, 0x8a08f0f8bf0f156b,
+ 0xcdb02555653131b6, 0x993fe2c6d07b7fac, 0xe45c10c42a2b3b06,
+ 0xaa242499697392d3, 0xfd87b5f28300ca0e, 0xbce5086492111aeb,
+ 0x8cbccc096f5088cc, 0xd1b71758e219652c, 0x9c40000000000000,
+ 0xe8d4a51000000000, 0xad78ebc5ac620000, 0x813f3978f8940984,
+ 0xc097ce7bc90715b3, 0x8f7e32ce7bea5c70, 0xd5d238a4abe98068,
+ 0x9f4f2726179a2245, 0xed63a231d4c4fb27, 0xb0de65388cc8ada8,
+ 0x83c7088e1aab65db, 0xc45d1df942711d9a, 0x924d692ca61be758,
+ 0xda01ee641a708dea, 0xa26da3999aef774a, 0xf209787bb47d6b85,
+ 0xb454e4a179dd1877, 0x865b86925b9bc5c2, 0xc83553c5c8965d3d,
+ 0x952ab45cfa97a0b3, 0xde469fbd99a05fe3, 0xa59bc234db398c25,
+ 0xf6c69a72a3989f5c, 0xb7dcbf5354e9bece, 0x88fcf317f22241e2,
+ 0xcc20ce9bd35c78a5, 0x98165af37b2153df, 0xe2a0b5dc971f303a,
+ 0xa8d9d1535ce3b396, 0xfb9b7cd9a4a7443c, 0xbb764c4ca7a44410,
+ 0x8bab8eefb6409c1a, 0xd01fef10a657842c, 0x9b10a4e5e9913129,
+ 0xe7109bfba19c0c9d, 0xac2820d9623bf429, 0x80444b5e7aa7cf85,
+ 0xbf21e44003acdd2d, 0x8e679c2f5e44ff8f, 0xd433179d9c8cb841,
+ 0x9e19db92b4e31ba9, 0xeb96bf6ebadf77d9, 0xaf87023b9bf0ee6b,
};
// Binary exponents of pow(10, k), for k = -348, -340, ..., 340, corresponding
// to significands above.
template <typename T>
-const int16_t basic_data<T>::POW10_EXPONENTS[] = {
- -1220, -1193, -1166, -1140, -1113, -1087, -1060, -1034, -1007, -980, -954,
- -927, -901, -874, -847, -821, -794, -768, -741, -715, -688, -661,
- -635, -608, -582, -555, -529, -502, -475, -449, -422, -396, -369,
- -343, -316, -289, -263, -236, -210, -183, -157, -130, -103, -77,
- -50, -24, 3, 30, 56, 83, 109, 136, 162, 189, 216,
- 242, 269, 295, 322, 348, 375, 402, 428, 455, 481, 508,
- 534, 561, 588, 614, 641, 667, 694, 720, 747, 774, 800,
- 827, 853, 880, 907, 933, 960, 986, 1013, 1039, 1066
-};
+const int16_t basic_data<T>::pow10_exponents[] = {
+ -1220, -1193, -1166, -1140, -1113, -1087, -1060, -1034, -1007, -980, -954,
+ -927, -901, -874, -847, -821, -794, -768, -741, -715, -688, -661,
+ -635, -608, -582, -555, -529, -502, -475, -449, -422, -396, -369,
+ -343, -316, -289, -263, -236, -210, -183, -157, -130, -103, -77,
+ -50, -24, 3, 30, 56, 83, 109, 136, 162, 189, 216,
+ 242, 269, 295, 322, 348, 375, 402, 428, 455, 481, 508,
+ 534, 561, 588, 614, 641, 667, 694, 720, 747, 774, 800,
+ 827, 853, 880, 907, 933, 960, 986, 1013, 1039, 1066};
-template <typename T> const char basic_data<T>::FOREGROUND_COLOR[] = "\x1b[38;2;";
-template <typename T> const char basic_data<T>::BACKGROUND_COLOR[] = "\x1b[48;2;";
-template <typename T> const char basic_data<T>::RESET_COLOR[] = "\x1b[0m";
-template <typename T> const wchar_t basic_data<T>::WRESET_COLOR[] = L"\x1b[0m";
+template <typename T>
+const char basic_data<T>::foreground_color[] = "\x1b[38;2;";
+template <typename T>
+const char basic_data<T>::background_color[] = "\x1b[48;2;";
+template <typename T> const char basic_data<T>::reset_color[] = "\x1b[0m";
+template <typename T> const wchar_t basic_data<T>::wreset_color[] = L"\x1b[0m";
+
+template <typename T> struct bits {
+ static FMT_CONSTEXPR_DECL const int value =
+ static_cast<int>(sizeof(T) * std::numeric_limits<unsigned char>::digits);
+};
// A handmade floating-point number f * pow(2, e).
class fp {
private:
- typedef uint64_t significand_type;
+ using significand_type = uint64_t;
// All sizes are in bits.
- static FMT_CONSTEXPR_DECL const int char_size =
- std::numeric_limits<unsigned char>::digits;
// Subtract 1 to account for an implicit most significant bit in the
// normalized form.
static FMT_CONSTEXPR_DECL const int double_significand_size =
- std::numeric_limits<double>::digits - 1;
+ std::numeric_limits<double>::digits - 1;
static FMT_CONSTEXPR_DECL const uint64_t implicit_bit =
- 1ull << double_significand_size;
+ 1ull << double_significand_size;
public:
significand_type f;
int e;
static FMT_CONSTEXPR_DECL const int significand_size =
- sizeof(significand_type) * char_size;
+ bits<significand_type>::value;
- fp(): f(0), e(0) {}
- fp(uint64_t f_val, int e_val): f(f_val), e(e_val) {}
+ fp() : f(0), e(0) {}
+ fp(uint64_t f_val, int e_val) : f(f_val), e(e_val) {}
// Constructs fp from an IEEE754 double. It is a template to prevent compile
// errors on platforms where double is not IEEE754.
- template <typename Double>
- explicit fp(Double d) {
+ template <typename Double> explicit fp(Double d) {
// Assume double is in the format [sign][exponent][significand].
- typedef std::numeric_limits<Double> limits;
- const int double_size = static_cast<int>(sizeof(Double) * char_size);
+ using limits = std::numeric_limits<Double>;
const int exponent_size =
- double_size - double_significand_size - 1; // -1 for sign
+ bits<Double>::value - double_significand_size - 1; // -1 for sign
const uint64_t significand_mask = implicit_bit - 1;
const uint64_t exponent_mask = (~0ull >> 1) & ~significand_mask;
const int exponent_bias = (1 << exponent_size) - limits::max_exponent - 1;
@@ -397,8 +396,7 @@
}
// Normalizes the value converted from double and multiplied by (1 << SHIFT).
- template <int SHIFT = 0>
- void normalize() {
+ template <int SHIFT = 0> void normalize() {
// Handle subnormals.
auto shifted_implicit_bit = implicit_bit << SHIFT;
while ((f & shifted_implicit_bit) == 0) {
@@ -415,9 +413,9 @@
// a boundary is a value half way between the number and its predecessor
// (lower) or successor (upper). The upper boundary is normalized and lower
// has the same exponent but may be not normalized.
- void compute_boundaries(fp &lower, fp &upper) const {
- lower = f == implicit_bit ?
- fp((f << 2) - 1, e - 2) : fp((f << 1) - 1, e - 1);
+ void compute_boundaries(fp& lower, fp& upper) const {
+ lower =
+ f == implicit_bit ? fp((f << 2) - 1, e - 2) : fp((f << 1) - 1, e - 1);
upper = fp((f << 1) + 1, e - 1);
upper.normalize<1>(); // 1 is to account for the exponent shift above.
lower.f <<= lower.e - upper.e;
@@ -432,14 +430,16 @@
}
// Computes an fp number r with r.f = x.f * y.f / pow(2, 64) rounded to nearest
-// with half-up tie breaking, r.e = x.e + y.e + 64. Result may not be normalized.
-FMT_API fp operator*(fp x, fp y);
-
-// Returns cached power (of 10) c_k = c_k.f * pow(2, c_k.e) such that its
-// (binary) exponent satisfies min_exponent <= c_k.e <= min_exponent + 3.
-FMT_API fp get_cached_power(int min_exponent, int &pow10_exponent);
-
+// with half-up tie breaking, r.e = x.e + y.e + 64. Result may not be
+// normalized.
FMT_FUNC fp operator*(fp x, fp y) {
+ int exp = x.e + y.e + 64;
+#if FMT_USE_INT128
+ auto product = static_cast<__uint128_t>(x.f) * y.f;
+ auto f = static_cast<uint64_t>(product >> 64);
+ if ((static_cast<uint64_t>(product) & (1ULL << 63)) != 0) ++f;
+ return fp(f, exp);
+#else
// Multiply 32-bit parts of significands.
uint64_t mask = (1ULL << 32) - 1;
uint64_t a = x.f >> 32, b = x.f & mask;
@@ -447,351 +447,376 @@
uint64_t ac = a * c, bc = b * c, ad = a * d, bd = b * d;
// Compute mid 64-bit of result and round.
uint64_t mid = (bd >> 32) + (ad & mask) + (bc & mask) + (1U << 31);
- return fp(ac + (ad >> 32) + (bc >> 32) + (mid >> 32), x.e + y.e + 64);
+ return fp(ac + (ad >> 32) + (bc >> 32) + (mid >> 32), exp);
+#endif
}
-FMT_FUNC fp get_cached_power(int min_exponent, int &pow10_exponent) {
+// Returns cached power (of 10) c_k = c_k.f * pow(2, c_k.e) such that its
+// (binary) exponent satisfies min_exponent <= c_k.e <= min_exponent + 28.
+FMT_FUNC fp get_cached_power(int min_exponent, int& pow10_exponent) {
const double one_over_log2_10 = 0.30102999566398114; // 1 / log2(10)
- int index = static_cast<int>(std::ceil(
- (min_exponent + fp::significand_size - 1) * one_over_log2_10));
+ int index = static_cast<int>(
+ std::ceil((min_exponent + fp::significand_size - 1) * one_over_log2_10));
// Decimal exponent of the first (smallest) cached power of 10.
const int first_dec_exp = -348;
// Difference between 2 consecutive decimal exponents in cached powers of 10.
const int dec_exp_step = 8;
index = (index - first_dec_exp - 1) / dec_exp_step + 1;
pow10_exponent = first_dec_exp + index * dec_exp_step;
- return fp(data::POW10_SIGNIFICANDS[index], data::POW10_EXPONENTS[index]);
+ 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;
+enum round_direction { unknown, up, down };
+
+// Given the divisor (normally a power of 10), the remainder = v % divisor for
+// some number v and the error, returns whether v should be rounded up, down, or
+// whether the rounding direction can't be determined due to error.
+// error should be less than divisor / 2.
+inline round_direction get_round_direction(uint64_t divisor, uint64_t remainder,
+ uint64_t error) {
+ FMT_ASSERT(remainder < divisor, ""); // divisor - remainder won't overflow.
+ FMT_ASSERT(error < divisor, ""); // divisor - error won't overflow.
+ FMT_ASSERT(error < divisor - error, ""); // error * 2 won't overflow.
+ // Round down if (remainder + error) * 2 <= divisor.
+ if (remainder <= divisor - remainder && error * 2 <= divisor - remainder * 2)
+ return down;
+ // Round up if (remainder - error) * 2 >= divisor.
+ if (remainder >= error &&
+ remainder - error >= divisor - (remainder - error)) {
+ return up;
}
- if (size > max_digits) {
- --size;
- ++exp10;
- if (buf[size] >= '5')
- return false;
- }
- return true;
+ return unknown;
}
-// Generates output using Grisu2 digit-gen algorithm.
-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) {
+namespace digits {
+enum result {
+ more, // Generate more digits.
+ done, // Done generating digits.
+ error // Digit generation cancelled due to an error.
+};
+}
+
+// Generates output using the Grisu digit-gen algorithm.
+// error: the size of the region (lower, upper) outside of which numbers
+// definitely do not round to value (Delta in Grisu3).
+template <typename Handler>
+digits::result grisu_gen_digits(fp value, uint64_t error, int& exp,
+ Handler& handler) {
+ fp one(1ull << -value.e, value.e);
+ // The integral part of scaled value (p1 in Grisu) = value / one. It cannot be
+ // zero because it contains a product of two 64-bit numbers with MSB set (due
+ // to normalization) - 1, shifted right by at most 60 bits.
+ uint32_t integral = static_cast<uint32_t>(value.f >> -one.e);
+ FMT_ASSERT(integral != 0, "");
+ FMT_ASSERT(integral == value.f >> -one.e, "");
+ // The fractional part of scaled value (p2 in Grisu) c = value % one.
+ uint64_t fractional = value.f & (one.f - 1);
+ exp = count_digits(integral); // kappa in Grisu.
+ // Divide by 10 to prevent overflow.
+ auto result = handler.on_start(data::powers_of_10_64[exp - 1] << -one.e,
+ value.f / 10, error * 10, exp);
+ if (result != digits::more) return result;
+ // Generate digits for the integral part. This can produce up to 10 digits.
+ do {
uint32_t digit = 0;
// This optimization by miloyip reduces the number of integer divisions by
// one per iteration.
switch (exp) {
- case 10: digit = hi / 1000000000; hi %= 1000000000; break;
- case 9: digit = hi / 100000000; hi %= 100000000; break;
- case 8: digit = hi / 10000000; hi %= 10000000; break;
- case 7: digit = hi / 1000000; hi %= 1000000; break;
- case 6: digit = hi / 100000; hi %= 100000; break;
- case 5: digit = hi / 10000; hi %= 10000; break;
- case 4: digit = hi / 1000; hi %= 1000; break;
- case 3: digit = hi / 100; hi %= 100; break;
- case 2: digit = hi / 10; hi %= 10; break;
- case 1: digit = hi; hi = 0; break;
+ case 10:
+ digit = integral / 1000000000;
+ integral %= 1000000000;
+ break;
+ case 9:
+ digit = integral / 100000000;
+ integral %= 100000000;
+ break;
+ case 8:
+ digit = integral / 10000000;
+ integral %= 10000000;
+ break;
+ case 7:
+ digit = integral / 1000000;
+ integral %= 1000000;
+ break;
+ case 6:
+ digit = integral / 100000;
+ integral %= 100000;
+ break;
+ case 5:
+ digit = integral / 10000;
+ integral %= 10000;
+ break;
+ case 4:
+ digit = integral / 1000;
+ integral %= 1000;
+ break;
+ case 3:
+ digit = integral / 100;
+ integral %= 100;
+ break;
+ case 2:
+ digit = integral / 10;
+ integral %= 10;
+ break;
+ case 1:
+ digit = integral;
+ integral = 0;
+ break;
default:
FMT_ASSERT(false, "invalid number of digits");
}
- if (digit != 0 || size != 0)
- buf[size++] = static_cast<char>('0' + digit);
--exp;
- uint64_t remainder = (static_cast<uint64_t>(hi) << -one.e) + lo;
- if (remainder <= delta || size > max_digits) {
- return grisu2_round(
- buf, size, max_digits, delta, remainder,
- static_cast<uint64_t>(data::POWERS_OF_10_32[exp]) << -one.e,
- diff.f, exp);
- }
- }
- // Generate digits for the least significant part (lo).
+ uint64_t remainder =
+ (static_cast<uint64_t>(integral) << -one.e) + fractional;
+ result = handler.on_digit(static_cast<char>('0' + digit),
+ data::powers_of_10_64[exp] << -one.e, remainder,
+ error, exp, true);
+ if (result != digits::more) return result;
+ } while (exp > 0);
+ // Generate digits for the fractional part.
for (;;) {
- lo *= 10;
- delta *= 10;
- char digit = static_cast<char>(lo >> -one.e);
- if (digit != 0 || size != 0)
- buf[size++] = static_cast<char>('0' + digit);
- lo &= one.f - 1;
+ fractional *= 10;
+ error *= 10;
+ char digit =
+ static_cast<char>('0' + static_cast<char>(fractional >> -one.e));
+ fractional &= one.f - 1;
--exp;
- 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);
- }
+ result = handler.on_digit(digit, one.f, fractional, error, exp, false);
+ if (result != digits::more) return result;
}
}
-#if FMT_CLANG_VERSION
-# define FMT_FALLTHROUGH [[clang::fallthrough]];
-#elif FMT_GCC_VERSION >= 700
-# define FMT_FALLTHROUGH [[gnu::fallthrough]];
-#else
-# define FMT_FALLTHROUGH
-#endif
-
-struct gen_digits_params {
- int num_digits;
+// The fixed precision digit handler.
+struct fixed_handler {
+ char* buf;
+ int size;
+ int precision;
+ int exp10;
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));
+ digits::result on_start(uint64_t divisor, uint64_t remainder, uint64_t error,
+ int& exp) {
+ // Non-fixed formats require at least one digit and no precision adjustment.
+ if (!fixed) return digits::more;
+ // Adjust fixed precision by exponent because it is relative to decimal
+ // point.
+ precision += exp + exp10;
+ // Check if precision is satisfied just by leading zeros, e.g.
+ // format("{:.2f}", 0.001) gives "0.00" without generating any digits.
+ if (precision > 0) return digits::more;
+ if (precision < 0) return digits::done;
+ auto dir = get_round_direction(divisor, remainder, error);
+ if (dir == unknown) return digits::error;
+ buf[size++] = dir == up ? '1' : '0';
+ return digits::done;
}
- template <typename F>
- 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 <typename Handler>
-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 {
- h.append('+');
- }
- if (exp >= 100) {
- h.append(static_cast<char>('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]);
- }
-}
-
-struct fill {
- size_t n;
- void operator()(char *buf) const {
- buf[0] = '0';
- buf[1] = '.';
- std::uninitialized_fill_n(buf + 2, n, '0');
- }
-};
-
-// The number is given as v = f * pow(10, exp), where f has size digits.
-template <typename Handler>
-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;
- }
- // 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');
+ digits::result on_digit(char digit, uint64_t divisor, uint64_t remainder,
+ uint64_t error, int, bool integral) {
+ FMT_ASSERT(remainder < divisor, "");
+ buf[size++] = digit;
+ if (size < precision) return digits::more;
+ if (!integral) {
+ // Check if error * 2 < divisor with overflow prevention.
+ // The check is not needed for the integral part because error = 1
+ // and divisor > (1 << 32) there.
+ if (error >= divisor || error >= divisor - error) return digits::error;
+ } else {
+ FMT_ASSERT(error == 1 && divisor > 2, "");
}
- } 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');
+ auto dir = get_round_direction(divisor, remainder, error);
+ if (dir != up) return dir == down ? digits::done : digits::error;
+ ++buf[size - 1];
+ for (int i = size - 1; i > 0 && buf[i] > '9'; --i) {
+ buf[i] = '0';
+ ++buf[i - 1];
}
- } else {
- // 1234e-6 -> 0.001234
- handler.insert(0, 2 - full_exp, fill{to_unsigned(-full_exp)});
+ if (buf[0] > '9') {
+ buf[0] = '1';
+ buf[size++] = '0';
+ }
+ return digits::done;
}
-}
-
-struct char_counter {
- ptrdiff_t size;
-
- template <typename F>
- 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;
-}
+// The shortest representation digit handler.
+template <int GRISU_VERSION> struct grisu_shortest_handler {
+ char* buf;
+ int size;
+ // Distance between scaled value and upper bound (wp_W in Grisu3).
+ uint64_t diff;
-template <typename Double>
-FMT_FUNC typename std::enable_if<sizeof(Double) == sizeof(uint64_t), bool>::type
- grisu2_format(Double value, buffer &buf, core_format_specs specs) {
+ digits::result on_start(uint64_t, uint64_t, uint64_t, int&) {
+ return digits::more;
+ }
+
+ // Decrement the generated number approaching value from above.
+ void round(uint64_t d, uint64_t divisor, uint64_t& remainder,
+ uint64_t error) {
+ while (
+ remainder < d && error - remainder >= divisor &&
+ (remainder + divisor < d || d - remainder >= remainder + divisor - d)) {
+ --buf[size - 1];
+ remainder += divisor;
+ }
+ }
+
+ // Implements Grisu's round_weed.
+ digits::result on_digit(char digit, uint64_t divisor, uint64_t remainder,
+ uint64_t error, int exp, bool integral) {
+ buf[size++] = digit;
+ if (remainder >= error) return digits::more;
+ if (GRISU_VERSION != 3) {
+ uint64_t d = integral ? diff : diff * data::powers_of_10_64[-exp];
+ round(d, divisor, remainder, error);
+ return digits::done;
+ }
+ uint64_t unit = integral ? 1 : data::powers_of_10_64[-exp];
+ uint64_t up = (diff - 1) * unit; // wp_Wup
+ round(up, divisor, remainder, error);
+ uint64_t down = (diff + 1) * unit; // wp_Wdown
+ if (remainder < down && error - remainder >= divisor &&
+ (remainder + divisor < down ||
+ down - remainder > remainder + divisor - down)) {
+ return digits::error;
+ }
+ return 2 * unit <= remainder && remainder <= error - 4 * unit
+ ? digits::done
+ : digits::error;
+ }
+};
+
+template <typename Double,
+ enable_if_t<(sizeof(Double) == sizeof(uint64_t)), int>>
+FMT_API bool grisu_format(Double value, buffer<char>& buf, int precision,
+ unsigned options, int& exp) {
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));
+ bool fixed = (options & grisu_options::fixed) != 0;
+ if (value <= 0) { // <= instead of == to silence a warning.
+ if (precision <= 0 || !fixed) {
+ exp = 0;
+ buf.push_back('0');
+ } else {
+ exp = -precision;
+ buf.resize(precision);
+ std::uninitialized_fill_n(buf.data(), precision, '0');
+ }
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<uint32_t>(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;
+ int cached_exp10 = 0; // K in Grisu.
+ if (precision != -1) {
+ if (precision > 17) return false;
+ fp_value.normalize();
+ auto cached_pow = get_cached_power(
+ min_exp - (fp_value.e + fp::significand_size), cached_exp10);
+ fp_value = fp_value * cached_pow;
+ fixed_handler handler{buf.data(), 0, precision, -cached_exp10, fixed};
+ if (grisu_gen_digits(fp_value, 1, exp, handler) == digits::error)
+ return false;
+ buf.resize(to_unsigned(handler.size));
+ } else {
+ fp lower, upper; // w^- and w^+ in the Grisu paper.
+ fp_value.compute_boundaries(lower, upper);
+ // Find a cached power of 10 such that multiplying upper by it will bring
+ // the exponent in the range [min_exp, -32].
+ auto cached_pow = get_cached_power( // \tilde{c}_{-k} in Grisu.
+ min_exp - (upper.e + fp::significand_size), cached_exp10);
+ fp_value.normalize();
+ fp_value = fp_value * cached_pow;
+ lower = lower * cached_pow; // \tilde{M}^- in Grisu.
+ upper = upper * cached_pow; // \tilde{M}^+ in Grisu.
+ assert(min_exp <= upper.e && upper.e <= -32);
+ auto result = digits::result();
+ int size = 0;
+ if ((options & grisu_options::grisu3) != 0) {
+ --lower.f; // \tilde{M}^- - 1 ulp -> M^-_{\downarrow}.
+ ++upper.f; // \tilde{M}^+ + 1 ulp -> M^+_{\uparrow}.
+ // Numbers outside of (lower, upper) definitely do not round to value.
+ grisu_shortest_handler<3> handler{buf.data(), 0, (upper - fp_value).f};
+ result = grisu_gen_digits(upper, upper.f - lower.f, exp, handler);
+ size = handler.size;
+ } else {
+ ++lower.f; // \tilde{M}^- + 1 ulp -> M^-_{\uparrow}.
+ --upper.f; // \tilde{M}^+ - 1 ulp -> M^+_{\downarrow}.
+ grisu_shortest_handler<2> handler{buf.data(), 0, (upper - fp_value).f};
+ result = grisu_gen_digits(upper, upper.f - lower.f, exp, handler);
+ size = handler.size;
+ }
+ if (result == digits::error) return false;
+ buf.resize(to_unsigned(size));
}
- grisu2_prettify(params, size, cached_exp + exp, prettify_handler(buf, size));
+ exp -= cached_exp10;
return true;
}
template <typename Double>
-void sprintf_format(Double value, internal::buffer &buf,
- core_format_specs spec) {
+char* sprintf_format(Double value, internal::buffer<char>& buf,
+ sprintf_specs specs) {
// 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;
+ 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) {
+ if (specs.alt || !specs.type) *format_ptr++ = '#';
+ if (specs.precision >= 0) {
*format_ptr++ = '.';
*format_ptr++ = '*';
}
- if (std::is_same<Double, long double>::value)
- *format_ptr++ = 'L';
- *format_ptr++ = spec.type;
+ if (std::is_same<Double, long double>::value) *format_ptr++ = 'L';
+
+ char type = specs.type;
+
+ if (type == '%')
+ type = 'f';
+ else if (type == 0 || type == 'n')
+ type = 'g';
+#if FMT_MSC_VER
+ if (type == 'F') {
+ // MSVC's printf doesn't support 'F'.
+ type = 'f';
+ }
+#endif
+ *format_ptr++ = type;
*format_ptr = '\0';
// Format using snprintf.
- char *start = FMT_NULL;
+ char* start = nullptr;
+ char* decimal_point_pos = nullptr;
for (;;) {
std::size_t buffer_size = buf.capacity();
start = &buf[0];
- int result = internal::char_traits<char>::format_float(
- start, buffer_size, format, spec.precision, value);
+ int result =
+ format_float(start, buffer_size, format, specs.precision, value);
if (result >= 0) {
unsigned n = internal::to_unsigned(result);
if (n < buf.capacity()) {
+ // Find the decimal point.
+ auto p = buf.data(), end = p + n;
+ if (*p == '+' || *p == '-') ++p;
+ if (specs.type != 'a' && specs.type != 'A') {
+ while (p < end && *p >= '0' && *p <= '9') ++p;
+ if (p < end && *p != 'e' && *p != 'E') {
+ decimal_point_pos = p;
+ if (!specs.type) {
+ // Keep only one trailing zero after the decimal point.
+ ++p;
+ if (*p == '0') ++p;
+ while (p != end && *p >= '1' && *p <= '9') ++p;
+ char* where = p;
+ while (p != end && *p == '0') ++p;
+ if (p == end || *p < '0' || *p > '9') {
+ if (p != end) std::memmove(where, p, to_unsigned(end - p));
+ n -= static_cast<unsigned>(p - where);
+ }
+ }
+ }
+ }
buf.resize(n);
break; // The buffer is large enough - continue with formatting.
}
@@ -802,6 +827,7 @@
buf.reserve(buf.capacity() + 1);
}
}
+ return decimal_point_pos;
}
} // namespace internal
@@ -819,28 +845,25 @@
return;
}
- int length = MultiByteToWideChar(
- CP_UTF8, MB_ERR_INVALID_CHARS, s.data(), s_size, FMT_NULL, 0);
- if (length == 0)
- FMT_THROW(windows_error(GetLastError(), ERROR_MSG));
+ int length = MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, s.data(),
+ s_size, nullptr, 0);
+ if (length == 0) FMT_THROW(windows_error(GetLastError(), ERROR_MSG));
buffer_.resize(length + 1);
- length = MultiByteToWideChar(
- CP_UTF8, MB_ERR_INVALID_CHARS, s.data(), s_size, &buffer_[0], length);
- if (length == 0)
- FMT_THROW(windows_error(GetLastError(), ERROR_MSG));
+ length = MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, s.data(), s_size,
+ &buffer_[0], length);
+ if (length == 0) FMT_THROW(windows_error(GetLastError(), ERROR_MSG));
buffer_[length] = 0;
}
FMT_FUNC internal::utf16_to_utf8::utf16_to_utf8(wstring_view s) {
if (int error_code = convert(s)) {
FMT_THROW(windows_error(error_code,
- "cannot convert string from UTF-16 to UTF-8"));
+ "cannot convert string from UTF-16 to UTF-8"));
}
}
FMT_FUNC int internal::utf16_to_utf8::convert(wstring_view s) {
- if (s.size() > INT_MAX)
- return ERROR_INVALID_PARAMETER;
+ if (s.size() > INT_MAX) return ERROR_INVALID_PARAMETER;
int s_size = static_cast<int>(s.size());
if (s_size == 0) {
// WideCharToMultiByte does not support zero length, handle separately.
@@ -849,43 +872,42 @@
return 0;
}
- int length = WideCharToMultiByte(
- CP_UTF8, 0, s.data(), s_size, FMT_NULL, 0, FMT_NULL, FMT_NULL);
- if (length == 0)
- return GetLastError();
+ int length = WideCharToMultiByte(CP_UTF8, 0, s.data(), s_size, nullptr, 0,
+ nullptr, nullptr);
+ if (length == 0) return GetLastError();
buffer_.resize(length + 1);
- length = WideCharToMultiByte(
- CP_UTF8, 0, s.data(), s_size, &buffer_[0], length, FMT_NULL, FMT_NULL);
- if (length == 0)
- return GetLastError();
+ length = WideCharToMultiByte(CP_UTF8, 0, s.data(), s_size, &buffer_[0],
+ length, nullptr, nullptr);
+ if (length == 0) return GetLastError();
buffer_[length] = 0;
return 0;
}
-FMT_FUNC void windows_error::init(
- int err_code, string_view format_str, format_args args) {
+FMT_FUNC void windows_error::init(int err_code, string_view format_str,
+ format_args args) {
error_code_ = err_code;
memory_buffer buffer;
internal::format_windows_error(buffer, err_code, vformat(format_str, args));
- std::runtime_error &base = *this;
+ std::runtime_error& base = *this;
base = std::runtime_error(to_string(buffer));
}
-FMT_FUNC void internal::format_windows_error(
- internal::buffer &out, int error_code, string_view message) FMT_NOEXCEPT {
+FMT_FUNC void internal::format_windows_error(internal::buffer<char>& out,
+ int error_code,
+ string_view message) FMT_NOEXCEPT {
FMT_TRY {
wmemory_buffer buf;
buf.resize(inline_buffer_size);
for (;;) {
- wchar_t *system_message = &buf[0];
+ wchar_t* system_message = &buf[0];
int result = FormatMessageW(
- FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
- FMT_NULL, error_code, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
- system_message, static_cast<uint32_t>(buf.size()), FMT_NULL);
+ FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, nullptr,
+ error_code, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), system_message,
+ static_cast<uint32_t>(buf.size()), nullptr);
if (result != 0) {
utf16_to_utf8 utf8_message;
if (utf8_message.convert(system_message) == ERROR_SUCCESS) {
- writer w(out);
+ internal::writer w(out);
w.write(message);
w.write(": ");
w.write(utf8_message);
@@ -897,22 +919,24 @@
break; // Can't get error message, report error code instead.
buf.resize(buf.size() * 2);
}
- } FMT_CATCH(...) {}
+ }
+ FMT_CATCH(...) {}
format_error_code(out, error_code, message);
}
#endif // FMT_USE_WINDOWS_H
-FMT_FUNC void format_system_error(
- internal::buffer &out, int error_code, string_view message) FMT_NOEXCEPT {
+FMT_FUNC void format_system_error(internal::buffer<char>& out, int error_code,
+ string_view message) FMT_NOEXCEPT {
FMT_TRY {
memory_buffer buf;
buf.resize(inline_buffer_size);
for (;;) {
- char *system_message = &buf[0];
- int result = safe_strerror(error_code, system_message, buf.size());
+ char* system_message = &buf[0];
+ int result =
+ internal::safe_strerror(error_code, system_message, buf.size());
if (result == 0) {
- writer w(out);
+ internal::writer w(out);
w.write(message);
w.write(": ");
w.write(system_message);
@@ -922,37 +946,41 @@
break; // Can't get error message, report error code instead.
buf.resize(buf.size() * 2);
}
- } FMT_CATCH(...) {}
+ }
+ FMT_CATCH(...) {}
format_error_code(out, error_code, message);
}
-FMT_FUNC void internal::error_handler::on_error(const char *message) {
+FMT_FUNC void internal::error_handler::on_error(const char* message) {
FMT_THROW(format_error(message));
}
-FMT_FUNC void report_system_error(
- int error_code, fmt::string_view message) FMT_NOEXCEPT {
+FMT_FUNC void report_system_error(int error_code,
+ fmt::string_view message) FMT_NOEXCEPT {
report_error(format_system_error, error_code, message);
}
#if FMT_USE_WINDOWS_H
-FMT_FUNC void report_windows_error(
- int error_code, fmt::string_view message) FMT_NOEXCEPT {
+FMT_FUNC void report_windows_error(int error_code,
+ fmt::string_view message) FMT_NOEXCEPT {
report_error(internal::format_windows_error, error_code, message);
}
#endif
-FMT_FUNC void vprint(std::FILE *f, string_view format_str, format_args args) {
+FMT_FUNC void vprint(std::FILE* f, string_view format_str, format_args args) {
memory_buffer buffer;
internal::vformat_to(buffer, format_str,
- basic_format_args<buffer_context<char>::type>(args));
- std::fwrite(buffer.data(), 1, buffer.size(), f);
+ basic_format_args<buffer_context<char>>(args));
+ internal::fwrite_fully(buffer.data(), 1, buffer.size(), f);
}
-FMT_FUNC void vprint(std::FILE *f, wstring_view format_str, wformat_args args) {
+FMT_FUNC void vprint(std::FILE* f, wstring_view format_str, wformat_args args) {
wmemory_buffer buffer;
internal::vformat_to(buffer, format_str, args);
- std::fwrite(buffer.data(), sizeof(wchar_t), buffer.size(), f);
+ buffer.push_back(L'\0');
+ if (std::fputws(buffer.data(), f) == -1) {
+ FMT_THROW(system_error(errno, "cannot write to file"));
+ }
}
FMT_FUNC void vprint(string_view format_str, format_args args) {
@@ -966,7 +994,7 @@
FMT_END_NAMESPACE
#ifdef _MSC_VER
-# pragma warning(pop)
+# pragma warning(pop)
#endif
#endif // FMT_FORMAT_INL_H_
diff --git a/include/fmt/format.h b/include/fmt/format.h
index 1bb24a5..efec5d6 100644
--- a/include/fmt/format.h
+++ b/include/fmt/format.h
@@ -2,27 +2,32 @@
Formatting library for C++
Copyright (c) 2012 - present, Victor Zverovich
- All rights reserved.
- Redistribution and use in source and binary forms, with or without
- modification, are permitted provided that the following conditions are met:
+ Permission is hereby granted, free of charge, to any person obtaining
+ a copy of this software and associated documentation files (the
+ "Software"), to deal in the Software without restriction, including
+ without limitation the rights to use, copy, modify, merge, publish,
+ distribute, sublicense, and/or sell copies of the Software, and to
+ permit persons to whom the Software is furnished to do so, subject to
+ the following conditions:
- 1. Redistributions of source code must retain the above copyright notice, this
- list of conditions and the following disclaimer.
- 2. Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following disclaimer in the documentation
- and/or other materials provided with the distribution.
+ The above copyright notice and this permission notice shall be
+ included in all copies or substantial portions of the Software.
- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
- ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
- ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+
+ --- Optional exception to the license ---
+
+ As an exception, if, as a result of your compiling your source code, portions
+ of this Software are embedded into a machine-executable object form of such
+ source code, you may redistribute such embedded portions in such object form
+ without including the above copyright and permission notices.
*/
#ifndef FMT_FORMAT_H_
@@ -31,165 +36,122 @@
#include <algorithm>
#include <cassert>
#include <cmath>
+#include <cstdint>
#include <cstring>
+#include <iterator>
#include <limits>
#include <memory>
#include <stdexcept>
-#include <stdint.h>
-
-#ifdef __clang__
-# define FMT_CLANG_VERSION (__clang_major__ * 100 + __clang_minor__)
-#else
-# define FMT_CLANG_VERSION 0
-#endif
-
-#ifdef __INTEL_COMPILER
-# define FMT_ICC_VERSION __INTEL_COMPILER
-#elif defined(__ICL)
-# define FMT_ICC_VERSION __ICL
-#else
-# define FMT_ICC_VERSION 0
-#endif
-
-#ifdef __NVCC__
-# define FMT_CUDA_VERSION (__CUDACC_VER_MAJOR__ * 100 + __CUDACC_VER_MINOR__)
-#else
-# define FMT_CUDA_VERSION 0
-#endif
#include "core.h"
-#if FMT_GCC_VERSION >= 406 || FMT_CLANG_VERSION
-# pragma GCC diagnostic push
-
-// Disable the warning about declaration shadowing because it affects too
-// many valid cases.
-# pragma GCC diagnostic ignored "-Wshadow"
-
-// 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
-# pragma GCC diagnostic ignored "-Wgnu-string-literal-operator-template"
-# endif
-
-#ifdef _SECURE_SCL
-# define FMT_SECURE_SCL _SECURE_SCL
+#ifdef __clang__
+# define FMT_CLANG_VERSION (__clang_major__ * 100 + __clang_minor__)
#else
-# define FMT_SECURE_SCL 0
+# define FMT_CLANG_VERSION 0
#endif
-#if FMT_SECURE_SCL
-# include <iterator>
+#ifdef __INTEL_COMPILER
+# define FMT_ICC_VERSION __INTEL_COMPILER
+#elif defined(__ICL)
+# define FMT_ICC_VERSION __ICL
+#else
+# define FMT_ICC_VERSION 0
+#endif
+
+#ifdef __NVCC__
+# define FMT_CUDA_VERSION (__CUDACC_VER_MAJOR__ * 100 + __CUDACC_VER_MINOR__)
+#else
+# define FMT_CUDA_VERSION 0
#endif
#ifdef __has_builtin
-# define FMT_HAS_BUILTIN(x) __has_builtin(x)
+# define FMT_HAS_BUILTIN(x) __has_builtin(x)
#else
-# define FMT_HAS_BUILTIN(x) 0
-#endif
-
-#ifdef __GNUC_LIBSTD__
-# define FMT_GNUC_LIBSTD_VERSION (__GNUC_LIBSTD__ * 100 + __GNUC_LIBSTD_MINOR__)
+# define FMT_HAS_BUILTIN(x) 0
#endif
#ifndef FMT_THROW
-# if FMT_EXCEPTIONS
-# if FMT_MSC_VER
+# if FMT_EXCEPTIONS
+# if FMT_MSC_VER
FMT_BEGIN_NAMESPACE
namespace internal {
-template <typename Exception>
-inline void do_throw(const Exception &x) {
+template <typename Exception> inline void do_throw(const Exception& x) {
// Silence unreachable code warnings in MSVC because these are nearly
// impossible to fix in a generic code.
volatile bool b = true;
- if (b)
- throw x;
+ if (b) throw x;
}
-}
+} // namespace internal
FMT_END_NAMESPACE
-# define FMT_THROW(x) fmt::internal::do_throw(x)
+# define FMT_THROW(x) fmt::internal::do_throw(x)
+# else
+# define FMT_THROW(x) throw x
+# endif
# else
-# define FMT_THROW(x) throw x
+# define FMT_THROW(x) \
+ do { \
+ static_cast<void>(sizeof(x)); \
+ assert(false); \
+ } while (false)
# endif
-# else
-# define FMT_THROW(x) do { static_cast<void>(sizeof(x)); assert(false); } while(false);
-# endif
#endif
#ifndef FMT_USE_USER_DEFINED_LITERALS
-// For Intel's compiler and NVIDIA's compiler both it and the system gcc/msc
-// must support UDLs.
-# if (FMT_HAS_FEATURE(cxx_user_literals) || \
- FMT_GCC_VERSION >= 407 || FMT_MSC_VER >= 1900) && \
- (!(FMT_ICC_VERSION || FMT_CUDA_VERSION) || \
- FMT_ICC_VERSION >= 1500 || FMT_CUDA_VERSION >= 700)
-# define FMT_USE_USER_DEFINED_LITERALS 1
-# else
-# define FMT_USE_USER_DEFINED_LITERALS 0
-# endif
+// For Intel and NVIDIA compilers both they and the system gcc/msc support UDLs.
+# if (FMT_HAS_FEATURE(cxx_user_literals) || FMT_GCC_VERSION >= 407 || \
+ FMT_MSC_VER >= 1900) && \
+ (!(FMT_ICC_VERSION || FMT_CUDA_VERSION) || FMT_ICC_VERSION >= 1500 || \
+ FMT_CUDA_VERSION >= 700)
+# define FMT_USE_USER_DEFINED_LITERALS 1
+# else
+# define FMT_USE_USER_DEFINED_LITERALS 0
+# endif
#endif
-// EDG C++ Front End based compilers (icc, nvcc) do not currently support UDL
-// templates.
-#if FMT_USE_USER_DEFINED_LITERALS && \
- FMT_ICC_VERSION == 0 && \
- FMT_CUDA_VERSION == 0 && \
- ((FMT_GCC_VERSION >= 600 && __cplusplus >= 201402L) || \
- (defined(FMT_CLANG_VERSION) && FMT_CLANG_VERSION >= 304))
-# define FMT_UDL_TEMPLATE 1
+#ifndef FMT_USE_UDL_TEMPLATE
+// EDG front end based compilers (icc, nvcc) do not support UDL templates yet
+// and GCC 9 warns about them.
+# if FMT_USE_USER_DEFINED_LITERALS && FMT_ICC_VERSION == 0 && \
+ FMT_CUDA_VERSION == 0 && \
+ ((FMT_GCC_VERSION >= 600 && FMT_GCC_VERSION <= 900 && \
+ __cplusplus >= 201402L) || \
+ FMT_CLANG_VERSION >= 304)
+# define FMT_USE_UDL_TEMPLATE 1
+# else
+# define FMT_USE_UDL_TEMPLATE 0
+# endif
+#endif
+
+#ifdef FMT_USE_INT128
+// Do nothing.
+#elif defined(__SIZEOF_INT128__)
+# define FMT_USE_INT128 1
#else
-# define FMT_UDL_TEMPLATE 0
-#endif
-
-#ifndef FMT_USE_EXTERN_TEMPLATES
-# ifndef FMT_HEADER_ONLY
-# define FMT_USE_EXTERN_TEMPLATES \
- ((FMT_CLANG_VERSION >= 209 && __cplusplus >= 201103L) || \
- (FMT_GCC_VERSION >= 303 && FMT_HAS_GXX_CXX11))
-# else
-# define FMT_USE_EXTERN_TEMPLATES 0
-# endif
-#endif
-
-#if FMT_HAS_GXX_CXX11 || FMT_HAS_FEATURE(cxx_trailing_return) || \
- FMT_MSC_VER >= 1600
-# define FMT_USE_TRAILING_RETURN 1
-#else
-# define FMT_USE_TRAILING_RETURN 0
-#endif
-
-#ifndef FMT_USE_GRISU
-# define FMT_USE_GRISU 0
-//# define FMT_USE_GRISU std::numeric_limits<double>::is_iec559
+# define FMT_USE_INT128 0
#endif
// __builtin_clz is broken in clang with Microsoft CodeGen:
// https://github.com/fmtlib/fmt/issues/519
-#ifndef _MSC_VER
-# if FMT_GCC_VERSION >= 400 || FMT_HAS_BUILTIN(__builtin_clz)
+#if (FMT_GCC_VERSION || FMT_HAS_BUILTIN(__builtin_clz)) && !FMT_MSC_VER
# define FMT_BUILTIN_CLZ(n) __builtin_clz(n)
-# endif
-
-# if FMT_GCC_VERSION >= 400 || FMT_HAS_BUILTIN(__builtin_clzll)
+#endif
+#if (FMT_GCC_VERSION || FMT_HAS_BUILTIN(__builtin_clzll)) && !FMT_MSC_VER
# define FMT_BUILTIN_CLZLL(n) __builtin_clzll(n)
-# endif
#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.
#if FMT_MSC_VER && !defined(FMT_BUILTIN_CLZLL) && !defined(_MANAGED)
-# include <intrin.h> // _BitScanReverse, _BitScanReverse64
+# include <intrin.h> // _BitScanReverse, _BitScanReverse64
FMT_BEGIN_NAMESPACE
namespace internal {
// Avoid Clang with Microsoft CodeGen's -Wunknown-pragmas warning.
-# ifndef __clang__
-# pragma intrinsic(_BitScanReverse)
-# endif
+# ifndef __clang__
+# pragma intrinsic(_BitScanReverse)
+# endif
inline uint32_t clz(uint32_t x) {
unsigned long r = 0;
_BitScanReverse(&r, x);
@@ -198,43 +160,52 @@
// Static analysis complains about using uninitialized data
// "r", but the only way that can happen is if "x" is 0,
// which the callers guarantee to not happen.
-# pragma warning(suppress: 6102)
+# pragma warning(suppress : 6102)
return 31 - r;
}
-# define FMT_BUILTIN_CLZ(n) fmt::internal::clz(n)
+# define FMT_BUILTIN_CLZ(n) fmt::internal::clz(n)
-# if defined(_WIN64) && !defined(__clang__)
-# pragma intrinsic(_BitScanReverse64)
-# endif
+# if defined(_WIN64) && !defined(__clang__)
+# pragma intrinsic(_BitScanReverse64)
+# endif
inline uint32_t clzll(uint64_t x) {
unsigned long r = 0;
-# ifdef _WIN64
+# ifdef _WIN64
_BitScanReverse64(&r, x);
-# else
+# else
// Scan the high 32 bits.
- if (_BitScanReverse(&r, static_cast<uint32_t>(x >> 32)))
- return 63 - (r + 32);
+ if (_BitScanReverse(&r, static_cast<uint32_t>(x >> 32))) return 63 - (r + 32);
// Scan the low 32 bits.
_BitScanReverse(&r, static_cast<uint32_t>(x));
-# endif
+# endif
assert(x != 0);
// Static analysis complains about using uninitialized data
// "r", but the only way that can happen is if "x" is 0,
// which the callers guarantee to not happen.
-# pragma warning(suppress: 6102)
+# pragma warning(suppress : 6102)
return 63 - r;
}
-# define FMT_BUILTIN_CLZLL(n) fmt::internal::clzll(n)
-}
+# define FMT_BUILTIN_CLZLL(n) fmt::internal::clzll(n)
+} // namespace internal
FMT_END_NAMESPACE
#endif
FMT_BEGIN_NAMESPACE
namespace internal {
+// A fallback implementation of uintptr_t for systems that lack it.
+struct fallback_uintptr {
+ unsigned char value[sizeof(void*)];
+};
+#ifdef UINTPTR_MAX
+using uintptr_t = ::uintptr_t;
+#else
+using uintptr_t = fallback_uintptr;
+#endif
+
// An equivalent of `*reinterpret_cast<Dest*>(&source)` that doesn't produce
// undefined behavior (e.g. due to type aliasing).
// Example: uint64_t d = bit_cast<uint64_t>(2.718);
@@ -246,184 +217,283 @@
return dest;
}
-// An implementation of begin and end for pre-C++11 compilers such as gcc 4.
-template <typename C>
-FMT_CONSTEXPR auto begin(const C &c) -> decltype(c.begin()) {
- return c.begin();
-}
-template <typename T, std::size_t N>
-FMT_CONSTEXPR T *begin(T (&array)[N]) FMT_NOEXCEPT { return array; }
-template <typename C>
-FMT_CONSTEXPR auto end(const C &c) -> decltype(c.end()) { return c.end(); }
-template <typename T, std::size_t N>
-FMT_CONSTEXPR T *end(T (&array)[N]) FMT_NOEXCEPT { return array + N; }
-
-// For std::result_of in gcc 4.4.
-template <typename Result>
-struct function {
- template <typename T>
- struct result { typedef Result type; };
-};
-
-struct dummy_int {
- int data[2];
- operator int() const { return 0; }
-};
-typedef std::numeric_limits<internal::dummy_int> fputil;
-
-// 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(); }
-
-template <typename Allocator>
-typename Allocator::value_type *allocate(Allocator& alloc, std::size_t n) {
-#if __cplusplus >= 201103L || FMT_MSC_VER >= 1700
- return std::allocator_traits<Allocator>::allocate(alloc, n);
-#else
- return alloc.allocate(n);
-#endif
-}
-
-// A helper function to suppress bogus "conditional expression is constant"
-// warnings.
+// An approximation of iterator_t for pre-C++20 systems.
template <typename T>
-inline T const_check(T value) { return value; }
-} // namespace internal
-FMT_END_NAMESPACE
+using iterator_t = decltype(std::begin(std::declval<T&>()));
-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.
-template <>
-class numeric_limits<fmt::internal::dummy_int> :
- public std::numeric_limits<int> {
+// Detect the iterator category of *any* given type in a SFINAE-friendly way.
+// Unfortunately, older implementations of std::iterator_traits are not safe
+// for use in a SFINAE-context.
+template <typename It, typename Enable = void>
+struct iterator_category : std::false_type {};
+
+template <typename T> struct iterator_category<T*> {
+ using type = std::random_access_iterator_tag;
+};
+
+template <typename It>
+struct iterator_category<It, void_t<typename It::iterator_category>> {
+ using type = typename It::iterator_category;
+};
+
+// Detect if *any* given type models the OutputIterator concept.
+template <typename It> class is_output_iterator {
+ // Check for mutability because all iterator categories derived from
+ // std::input_iterator_tag *may* also meet the requirements of an
+ // OutputIterator, thereby falling into the category of 'mutable iterators'
+ // [iterator.requirements.general] clause 4. The compiler reveals this
+ // property only at the point of *actually dereferencing* the iterator!
+ template <typename U>
+ static decltype(*(std::declval<U>())) test(std::input_iterator_tag);
+ template <typename U> static char& test(std::output_iterator_tag);
+ template <typename U> static const char& test(...);
+
+ using type = decltype(test<It>(typename iterator_category<It>::type{}));
+
public:
- // Portable version of isinf.
- template <typename T>
- static bool isinfinity(T x) {
- using namespace fmt::internal;
- // The resolution "priority" is:
- // isinf macro > std::isinf > ::isinf > fmt::internal::isinf
- if (const_check(sizeof(isinf(x)) != sizeof(fmt::internal::dummy_int)))
- return isinf(x) != 0;
- return !_finite(static_cast<double>(x));
+ static const bool value = !std::is_const<remove_reference_t<type>>::value;
+};
+
+// A workaround for std::string not having mutable data() until C++17.
+template <typename Char> inline Char* get_data(std::basic_string<Char>& s) {
+ return &s[0];
+}
+template <typename Container>
+inline typename Container::value_type* get_data(Container& c) {
+ return c.data();
+}
+
+#ifdef _SECURE_SCL
+// Make a checked iterator to avoid MSVC warnings.
+template <typename T> using checked_ptr = stdext::checked_array_iterator<T*>;
+template <typename T> checked_ptr<T> make_checked(T* p, std::size_t size) {
+ return {p, size};
+}
+#else
+template <typename T> using checked_ptr = T*;
+template <typename T> inline T* make_checked(T* p, std::size_t) { return p; }
+#endif
+
+template <typename Container, FMT_ENABLE_IF(is_contiguous<Container>::value)>
+inline checked_ptr<typename Container::value_type> reserve(
+ std::back_insert_iterator<Container>& it, std::size_t n) {
+ Container& c = get_container(it);
+ std::size_t size = c.size();
+ c.resize(size + n);
+ return make_checked(get_data(c) + size, n);
+}
+
+template <typename Iterator>
+inline Iterator& reserve(Iterator& it, std::size_t) {
+ return it;
+}
+
+// An output iterator that counts the number of objects written to it and
+// discards them.
+template <typename T> class counting_iterator {
+ private:
+ std::size_t count_;
+ mutable T blackhole_;
+
+ public:
+ using iterator_category = std::output_iterator_tag;
+ using value_type = T;
+ using difference_type = std::ptrdiff_t;
+ using pointer = T*;
+ using reference = T&;
+ using _Unchecked_type = counting_iterator; // Mark iterator as checked.
+
+ counting_iterator() : count_(0) {}
+
+ std::size_t count() const { return count_; }
+
+ counting_iterator& operator++() {
+ ++count_;
+ return *this;
}
- // Portable version of isnan.
- template <typename T>
- static bool isnotanumber(T x) {
- using namespace fmt::internal;
- if (const_check(sizeof(isnan(x)) != sizeof(fmt::internal::dummy_int)))
- return isnan(x) != 0;
- return _isnan(static_cast<double>(x)) != 0;
+ counting_iterator operator++(int) {
+ auto it = *this;
+ ++*this;
+ return it;
+ }
+
+ T& operator*() const { return blackhole_; }
+};
+
+template <typename OutputIt> class truncating_iterator_base {
+ protected:
+ OutputIt out_;
+ std::size_t limit_;
+ std::size_t count_;
+
+ truncating_iterator_base(OutputIt out, std::size_t limit)
+ : out_(out), limit_(limit), count_(0) {}
+
+ public:
+ using iterator_category = std::output_iterator_tag;
+ using difference_type = void;
+ using pointer = void;
+ using reference = void;
+ using _Unchecked_type =
+ truncating_iterator_base; // Mark iterator as checked.
+
+ OutputIt base() const { return out_; }
+ std::size_t count() const { return count_; }
+};
+
+// An output iterator that truncates the output and counts the number of objects
+// written to it.
+template <typename OutputIt,
+ typename Enable = typename std::is_void<
+ typename std::iterator_traits<OutputIt>::value_type>::type>
+class truncating_iterator;
+
+template <typename OutputIt>
+class truncating_iterator<OutputIt, std::false_type>
+ : public truncating_iterator_base<OutputIt> {
+ using traits = std::iterator_traits<OutputIt>;
+
+ mutable typename traits::value_type blackhole_;
+
+ public:
+ using value_type = typename traits::value_type;
+
+ truncating_iterator(OutputIt out, std::size_t limit)
+ : truncating_iterator_base<OutputIt>(out, limit) {}
+
+ truncating_iterator& operator++() {
+ if (this->count_++ < this->limit_) ++this->out_;
+ return *this;
+ }
+
+ truncating_iterator operator++(int) {
+ auto it = *this;
+ ++*this;
+ return it;
+ }
+
+ value_type& operator*() const {
+ return this->count_ < this->limit_ ? *this->out_ : blackhole_;
}
};
-} // namespace std
-FMT_BEGIN_NAMESPACE
-template <typename Range>
-class basic_writer;
+template <typename OutputIt>
+class truncating_iterator<OutputIt, std::true_type>
+ : public truncating_iterator_base<OutputIt> {
+ public:
+ using value_type = typename OutputIt::container_type::value_type;
+ truncating_iterator(OutputIt out, std::size_t limit)
+ : truncating_iterator_base<OutputIt>(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; }
+};
+
+// A range with the specified output iterator and value type.
template <typename OutputIt, typename T = typename OutputIt::value_type>
class output_range {
private:
OutputIt it_;
- // Unused yet.
- typedef void sentinel;
- sentinel end() const;
-
public:
- typedef OutputIt iterator;
- typedef T value_type;
+ using value_type = T;
+ using iterator = OutputIt;
+ struct sentinel {};
- explicit output_range(OutputIt it): it_(it) {}
+ explicit output_range(OutputIt it) : it_(it) {}
OutputIt begin() const { return it_; }
+ sentinel end() const { return {}; } // Sentinel is not used yet.
};
-// A range where begin() returns back_insert_iterator.
-template <typename Container>
-class back_insert_range:
- public output_range<std::back_insert_iterator<Container>> {
- typedef output_range<std::back_insert_iterator<Container>> base;
- public:
- typedef typename Container::value_type value_type;
-
- back_insert_range(Container &c): base(std::back_inserter(c)) {}
- back_insert_range(typename base::iterator it): base(it) {}
-};
-
-typedef basic_writer<back_insert_range<internal::buffer>> writer;
-typedef basic_writer<back_insert_range<internal::wbuffer>> wwriter;
-
-/** A formatting error such as invalid format string. */
-class format_error : public std::runtime_error {
- public:
- explicit format_error(const char *message)
- : std::runtime_error(message) {}
-
- explicit format_error(const std::string &message)
- : std::runtime_error(message) {}
-};
-
-namespace internal {
-
-#if FMT_SECURE_SCL
+// A range with an iterator appending to a buffer.
template <typename T>
-struct checked { typedef stdext::checked_array_iterator<T*> type; };
+class buffer_range
+ : public output_range<std::back_insert_iterator<buffer<T>>, T> {
+ public:
+ using iterator = std::back_insert_iterator<buffer<T>>;
+ using output_range<iterator, T>::output_range;
+ buffer_range(buffer<T>& buf)
+ : output_range<iterator, T>(std::back_inserter(buf)) {}
+};
-// Make a checked iterator to avoid warnings on MSVC.
-template <typename T>
-inline stdext::checked_array_iterator<T*> make_checked(T *p, std::size_t size) {
- return {p, size};
+template <typename Char>
+inline size_t count_code_points(basic_string_view<Char> s) {
+ return s.size();
}
-#else
-template <typename T>
-struct checked { typedef T *type; };
-template <typename T>
-inline T *make_checked(T *p, std::size_t) { return p; }
+
+// Counts the number of code points in a UTF-8 string.
+inline size_t count_code_points(basic_string_view<char8_t> s) {
+ const char8_t* data = s.data();
+ size_t num_code_points = 0;
+ for (size_t i = 0, size = s.size(); i != size; ++i) {
+ if ((data[i] & 0xc0) != 0x80) ++num_code_points;
+ }
+ return num_code_points;
+}
+
+inline char8_t to_char8_t(char c) { return static_cast<char8_t>(c); }
+
+template <typename InputIt, typename OutChar>
+using needs_conversion = bool_constant<
+ std::is_same<typename std::iterator_traits<InputIt>::value_type,
+ char>::value &&
+ std::is_same<OutChar, char8_t>::value>;
+
+template <typename OutChar, typename InputIt, typename OutputIt,
+ FMT_ENABLE_IF(!needs_conversion<InputIt, OutChar>::value)>
+OutputIt copy_str(InputIt begin, InputIt end, OutputIt it) {
+ return std::copy(begin, end, it);
+}
+
+template <typename OutChar, typename InputIt, typename OutputIt,
+ FMT_ENABLE_IF(needs_conversion<InputIt, OutChar>::value)>
+OutputIt copy_str(InputIt begin, InputIt end, OutputIt it) {
+ return std::transform(begin, end, it, to_char8_t);
+}
+
+#ifndef FMT_USE_GRISU
+# define FMT_USE_GRISU 0
#endif
+template <typename T> constexpr bool use_grisu() {
+ return FMT_USE_GRISU && std::numeric_limits<double>::is_iec559 &&
+ sizeof(T) <= sizeof(double);
+}
+
template <typename T>
template <typename U>
-void basic_buffer<T>::append(const U *begin, const U *end) {
- std::size_t new_size = size_ + internal::to_unsigned(end - begin);
+void buffer<T>::append(const U* begin, const U* end) {
+ std::size_t new_size = size_ + to_unsigned(end - begin);
reserve(new_size);
- std::uninitialized_copy(begin, end,
- internal::make_checked(ptr_, capacity_) + size_);
+ std::uninitialized_copy(begin, end, make_checked(ptr_, capacity_) + size_);
size_ = new_size;
}
} // 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.
-enum char8_t: unsigned char {};
-#endif
-
// A UTF-8 string view.
class u8string_view : public basic_string_view<char8_t> {
public:
- typedef char8_t char_type;
-
- u8string_view(const char *s):
- basic_string_view<char8_t>(reinterpret_cast<const char8_t*>(s)) {}
- u8string_view(const char *s, size_t count) FMT_NOEXCEPT:
- basic_string_view<char8_t>(reinterpret_cast<const char8_t*>(s), count) {}
+ u8string_view(const char* s)
+ : basic_string_view<char8_t>(reinterpret_cast<const char8_t*>(s)) {}
+ u8string_view(const char* s, size_t count) FMT_NOEXCEPT
+ : basic_string_view<char8_t>(reinterpret_cast<const char8_t*>(s), count) {
+ }
};
#if FMT_USE_USER_DEFINED_LITERALS
inline namespace literals {
-inline u8string_view operator"" _u(const char *s, std::size_t n) {
+inline u8string_view operator"" _u(const char* s, std::size_t n) {
return {s, n};
}
-}
+} // namespace literals
#endif
// The number of characters to store in the basic_memory_buffer object itself
@@ -435,7 +505,7 @@
A dynamically growing memory buffer for trivially copyable/constructible types
with the first ``SIZE`` elements stored in the object itself.
- You can use one of the following typedefs for common character types:
+ You can use one of the following type aliases for common character types:
+----------------+------------------------------+
| Type | Definition |
@@ -460,8 +530,8 @@
\endrst
*/
template <typename T, std::size_t SIZE = inline_buffer_size,
- typename Allocator = std::allocator<T> >
-class basic_memory_buffer: private Allocator, public internal::basic_buffer<T> {
+ typename Allocator = std::allocator<T>>
+class basic_memory_buffer : private Allocator, public internal::buffer<T> {
private:
T store_[SIZE];
@@ -475,10 +545,10 @@
void grow(std::size_t size) FMT_OVERRIDE;
public:
- typedef T value_type;
- typedef const T &const_reference;
+ using value_type = T;
+ using const_reference = const T&;
- explicit basic_memory_buffer(const Allocator &alloc = Allocator())
+ explicit basic_memory_buffer(const Allocator& alloc = Allocator())
: Allocator(alloc) {
this->set(store_, SIZE);
}
@@ -486,7 +556,7 @@
private:
// Move data from other to this buffer.
- void move(basic_memory_buffer &other) {
+ void move(basic_memory_buffer& other) {
Allocator &this_alloc = *this, &other_alloc = other;
this_alloc = std::move(other_alloc);
T* data = other.data();
@@ -511,16 +581,14 @@
of the other object to it.
\endrst
*/
- basic_memory_buffer(basic_memory_buffer &&other) {
- move(other);
- }
+ basic_memory_buffer(basic_memory_buffer&& other) { move(other); }
/**
\rst
Moves the content of the other ``basic_memory_buffer`` object to this one.
\endrst
*/
- basic_memory_buffer &operator=(basic_memory_buffer &&other) {
+ basic_memory_buffer& operator=(basic_memory_buffer&& other) {
assert(this != &other);
deallocate();
move(other);
@@ -533,12 +601,14 @@
template <typename T, std::size_t SIZE, typename Allocator>
void basic_memory_buffer<T, SIZE, Allocator>::grow(std::size_t size) {
+#ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
+ if (size > 1000) throw std::runtime_error("fuzz mode - won't grow that much");
+#endif
std::size_t old_capacity = this->capacity();
std::size_t new_capacity = old_capacity + old_capacity / 2;
- if (size > new_capacity)
- new_capacity = size;
- T *old_data = this->data();
- T *new_data = internal::allocate<Allocator>(*this, new_capacity);
+ if (size > new_capacity) new_capacity = size;
+ T* old_data = this->data();
+ T* new_data = std::allocator_traits<Allocator>::allocate(*this, new_capacity);
// The following code doesn't throw, so the raw pointer above doesn't leak.
std::uninitialized_copy(old_data, old_data + this->size(),
internal::make_checked(new_data, new_capacity));
@@ -546,222 +616,59 @@
// deallocate must not throw according to the standard, but even if it does,
// the buffer already uses the new storage and will deallocate it in
// destructor.
- if (old_data != store_)
- Allocator::deallocate(old_data, old_capacity);
+ if (old_data != store_) Allocator::deallocate(old_data, old_capacity);
}
-typedef basic_memory_buffer<char> memory_buffer;
-typedef basic_memory_buffer<wchar_t> wmemory_buffer;
+using memory_buffer = basic_memory_buffer<char>;
+using wmemory_buffer = basic_memory_buffer<wchar_t>;
+
+/** A formatting error such as invalid format string. */
+class FMT_API format_error : public std::runtime_error {
+ public:
+ explicit format_error(const char* message) : std::runtime_error(message) {}
+ explicit format_error(const std::string& message)
+ : std::runtime_error(message) {}
+ ~format_error() FMT_NOEXCEPT;
+};
namespace internal {
-template <typename Char>
-struct char_traits;
-
-template <>
-struct char_traits<char> {
- // Formats a floating-point number.
- template <typename T>
- FMT_API static int format_float(char *buffer, std::size_t size,
- const char *format, int precision, T value);
-};
-
-template <>
-struct char_traits<wchar_t> {
- template <typename T>
- FMT_API static int format_float(wchar_t *buffer, std::size_t size,
- const wchar_t *format, int precision, T value);
-};
-
-#if FMT_USE_EXTERN_TEMPLATES
-extern template int char_traits<char>::format_float<double>(
- char *buffer, std::size_t size, const char* format, int precision,
- double value);
-extern template int char_traits<char>::format_float<long double>(
- char *buffer, std::size_t size, const char* format, int precision,
- long double value);
-
-extern template int char_traits<wchar_t>::format_float<double>(
- wchar_t *buffer, std::size_t size, const wchar_t* format, int precision,
- double value);
-extern template int char_traits<wchar_t>::format_float<long double>(
- wchar_t *buffer, std::size_t size, const wchar_t* format, int precision,
- long double value);
-#endif
-
-template <typename Container>
-inline typename std::enable_if<
- is_contiguous<Container>::value,
- typename checked<typename Container::value_type>::type>::type
- reserve(std::back_insert_iterator<Container> &it, std::size_t n) {
- Container &c = internal::get_container(it);
- std::size_t size = c.size();
- c.resize(size + n);
- return make_checked(&c[size], n);
-}
-
-template <typename Iterator>
-inline Iterator &reserve(Iterator &it, std::size_t) { return it; }
-
-template <typename Char>
-class null_terminating_iterator;
-
-template <typename Char>
-FMT_CONSTEXPR_DECL const Char *pointer_from(null_terminating_iterator<Char> it);
-
-// An output iterator that counts the number of objects written to it and
-// discards them.
-template <typename T>
-class counting_iterator {
- private:
- std::size_t count_;
- mutable T blackhole_;
-
- public:
- typedef std::output_iterator_tag iterator_category;
- typedef T value_type;
- typedef std::ptrdiff_t difference_type;
- typedef T* pointer;
- typedef T& reference;
- typedef counting_iterator _Unchecked_type; // Mark iterator as checked.
-
- counting_iterator(): count_(0) {}
-
- std::size_t count() const { return count_; }
-
- counting_iterator& operator++() {
- ++count_;
- return *this;
- }
-
- counting_iterator operator++(int) {
- auto it = *this;
- ++*this;
- return it;
- }
-
- T &operator*() const { return blackhole_; }
-};
-
-template <typename OutputIt>
-class truncating_iterator_base {
- protected:
- OutputIt out_;
- std::size_t limit_;
- std::size_t count_;
-
- truncating_iterator_base(OutputIt out, std::size_t limit)
- : out_(out), limit_(limit), count_(0) {}
-
- public:
- typedef std::output_iterator_tag iterator_category;
- 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 <typename OutputIt, typename Enable = typename std::is_void<
- typename std::iterator_traits<OutputIt>::value_type>::type>
-class truncating_iterator;
-
-template <typename OutputIt>
-class truncating_iterator<OutputIt, std::false_type>:
- public truncating_iterator_base<OutputIt> {
- typedef std::iterator_traits<OutputIt> 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<OutputIt>(out, limit) {}
-
- truncating_iterator& operator++() {
- if (this->count_++ < this->limit_)
- ++this->out_;
- return *this;
- }
-
- truncating_iterator operator++(int) {
- auto it = *this;
- ++*this;
- return it;
- }
-
- value_type& operator*() const {
- return this->count_ < this->limit_ ? *this->out_ : blackhole_;
- }
-};
-
-template <typename OutputIt>
-class truncating_iterator<OutputIt, std::true_type>:
- public truncating_iterator_base<OutputIt> {
- public:
- typedef typename OutputIt::container_type::value_type value_type;
-
- truncating_iterator(OutputIt out, std::size_t limit)
- : truncating_iterator_base<OutputIt>(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.
-// Same as (value < 0) but doesn't produce warnings if T is an unsigned type.
-template <typename T>
-FMT_CONSTEXPR typename std::enable_if<
- std::numeric_limits<T>::is_signed, bool>::type is_negative(T value) {
+// Same as `value < 0` but doesn't produce warnings if T is an unsigned type.
+template <typename T, FMT_ENABLE_IF(std::numeric_limits<T>::is_signed)>
+FMT_CONSTEXPR bool is_negative(T value) {
return value < 0;
}
-template <typename T>
-FMT_CONSTEXPR typename std::enable_if<
- !std::numeric_limits<T>::is_signed, bool>::type is_negative(T) {
+template <typename T, FMT_ENABLE_IF(!std::numeric_limits<T>::is_signed)>
+FMT_CONSTEXPR bool is_negative(T) {
return false;
}
+// Smallest of uint32_t and uint64_t that is large enough to represent all
+// values of T.
template <typename T>
-struct int_traits {
- // Smallest of uint32_t and uint64_t that is large enough to represent
- // all values of T.
- typedef typename std::conditional<
- std::numeric_limits<T>::digits <= 32, uint32_t, uint64_t>::type main_type;
+using uint32_or_64_t =
+ conditional_t<std::numeric_limits<T>::digits <= 32, uint32_t, uint64_t>;
+
+// Static data is placed in this class template for the header-only config.
+template <typename T = void> struct FMT_EXTERN_TEMPLATE_API basic_data {
+ static const uint64_t powers_of_10_64[];
+ static const uint32_t zero_or_powers_of_10_32[];
+ static const uint64_t zero_or_powers_of_10_64[];
+ static const uint64_t pow10_significands[];
+ static const int16_t pow10_exponents[];
+ static const char digits[];
+ static const char hex_digits[];
+ static const char foreground_color[];
+ static const char background_color[];
+ static const char reset_color[5];
+ static const wchar_t wreset_color[5];
};
-// Static data is placed in this class template to allow header-only
-// configuration.
-template <typename T = void>
-struct FMT_API basic_data {
- static const uint32_t POWERS_OF_10_32[];
- static const uint32_t ZERO_OR_POWERS_OF_10_32[];
- static const uint64_t ZERO_OR_POWERS_OF_10_64[];
- 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[];
-};
+FMT_EXTERN template struct basic_data<void>;
-#if FMT_USE_EXTERN_TEMPLATES
-extern template struct basic_data<void>;
-#endif
-
-typedef basic_data<> data;
+// This is a struct rather than an alias to avoid shadowing warnings in gcc.
+struct data : basic_data<> {};
#ifdef FMT_BUILTIN_CLZLL
// Returns the number of decimal digits in n. Leading zeros are not counted
@@ -770,7 +677,7 @@
// 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 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.
@@ -790,46 +697,28 @@
}
#endif
-template <typename Char>
-inline size_t count_code_points(basic_string_view<Char> s) { return s.size(); }
-
-// Counts the number of code points in a UTF-8 string.
-FMT_API size_t count_code_points(basic_string_view<char8_t> s);
-
-inline char8_t to_char8_t(char c) { return static_cast<char8_t>(c); }
-
-template <typename InputIt, typename OutChar>
-struct needs_conversion: std::integral_constant<bool,
- std::is_same<
- typename std::iterator_traits<InputIt>::value_type, char>::value &&
- std::is_same<OutChar, char8_t>::value> {};
-
-template <typename OutChar, typename InputIt, typename OutputIt>
-typename std::enable_if<
- !needs_conversion<InputIt, OutChar>::value, OutputIt>::type
- copy_str(InputIt begin, InputIt end, OutputIt it) {
- return std::copy(begin, end, it);
+// Counts the number of digits in n. BITS = log2(radix).
+template <unsigned BITS, typename UInt> inline int count_digits(UInt n) {
+ int num_digits = 0;
+ do {
+ ++num_digits;
+ } while ((n >>= BITS) != 0);
+ return num_digits;
}
-template <typename OutChar, typename InputIt, typename OutputIt>
-typename std::enable_if<
- needs_conversion<InputIt, OutChar>::value, OutputIt>::type
- copy_str(InputIt begin, InputIt end, OutputIt it) {
- return std::transform(begin, end, it, to_char8_t);
-}
+template <> int count_digits<4>(internal::fallback_uintptr n);
#if FMT_HAS_CPP_ATTRIBUTE(always_inline)
-# define FMT_ALWAYS_INLINE __attribute__((always_inline))
+# define FMT_ALWAYS_INLINE __attribute__((always_inline))
#else
-# define FMT_ALWAYS_INLINE
+# define FMT_ALWAYS_INLINE
#endif
template <typename Handler>
-inline char *lg(uint32_t n, Handler h) FMT_ALWAYS_INLINE;
+inline char* lg(uint32_t n, Handler h) FMT_ALWAYS_INLINE;
// Computes g = floor(log10(n)) and calls h.on<g>(n);
-template <typename Handler>
-inline char *lg(uint32_t n, Handler h) {
+template <typename Handler> inline char* lg(uint32_t n, Handler h) {
return n < 100 ? n < 10 ? h.template on<0>(n) : h.template on<1>(n)
: n < 1000000
? n < 10000 ? n < 1000 ? h.template on<2>(n)
@@ -846,16 +735,16 @@
// Usage: lg(n, decimal_formatter(buffer));
class decimal_formatter {
private:
- char *buffer_;
+ char* buffer_;
void write_pair(unsigned N, uint32_t index) {
- std::memcpy(buffer_ + N, data::DIGITS + index * 2, 2);
+ std::memcpy(buffer_ + N, data::digits + index * 2, 2);
}
public:
- explicit decimal_formatter(char *buf) : buffer_(buf) {}
+ explicit decimal_formatter(char* buf) : buffer_(buf) {}
- template <unsigned N> char *on(uint32_t u) {
+ template <unsigned N> char* on(uint32_t u) {
if (N == 0) {
*buffer_ = static_cast<char>(u) + '0';
} else if (N == 1) {
@@ -865,8 +754,8 @@
// https://github.com/jeaiii/itoa
unsigned n = N - 1;
unsigned a = n / 5 * n * 53 / 16;
- uint64_t t = ((1ULL << (32 + a)) /
- data::ZERO_OR_POWERS_OF_10_32[n] + 1 - n / 9);
+ uint64_t t =
+ ((1ULL << (32 + a)) / data::zero_or_powers_of_10_32[n] + 1 - n / 9);
t = ((t * u) >> a) + n / 5 * 4;
write_pair(0, t >> 32);
for (unsigned i = 2; i < N; i += 2) {
@@ -874,140 +763,92 @@
write_pair(i, t >> 32);
}
if (N % 2 == 0) {
- buffer_[N] = static_cast<char>(
- (10ULL * static_cast<uint32_t>(t)) >> 32) + '0';
+ buffer_[N] =
+ static_cast<char>((10ULL * static_cast<uint32_t>(t)) >> 32) + '0';
}
}
return buffer_ += N + 1;
}
};
-// An lg handler that formats a decimal number with a terminating null.
-class decimal_formatter_null : public decimal_formatter {
- public:
- explicit decimal_formatter_null(char *buf) : decimal_formatter(buf) {}
-
- template <unsigned N> char *on(uint32_t u) {
- char *buf = decimal_formatter::on<N>(u);
- *buf = '\0';
- return buf;
- }
-};
-
#ifdef FMT_BUILTIN_CLZ
// Optional version of count_digits for better performance on 32-bit platforms.
inline int count_digits(uint32_t n) {
int t = (32 - FMT_BUILTIN_CLZ(n | 1)) * 1233 >> 12;
- return t - (n < data::ZERO_OR_POWERS_OF_10_32[t]) + 1;
+ return t - (n < data::zero_or_powers_of_10_32[t]) + 1;
}
#endif
-// A functor that doesn't add a thousands separator.
-struct no_thousands_sep {
- typedef char char_type;
-
- template <typename Char>
- void operator()(Char *) {}
-
- enum { size = 0 };
-};
-
-// A functor that adds a thousands separator.
-template <typename Char>
-class add_thousands_sep {
- private:
- basic_string_view<Char> sep_;
-
- // Index of a decimal digit with the least significant digit having index 0.
- unsigned digit_index_;
-
- public:
- typedef Char char_type;
-
- explicit add_thousands_sep(basic_string_view<Char> sep)
- : sep_(sep), digit_index_(0) {}
-
- void operator()(Char *&buffer) {
- if (++digit_index_ % 3 != 0)
- return;
- buffer -= sep_.size();
- std::uninitialized_copy(sep_.data(), sep_.data() + sep_.size(),
- internal::make_checked(buffer, sep_.size()));
- }
-
- enum { size = 1 };
-};
-
-template <typename Char>
-FMT_API Char thousands_sep_impl(locale_ref loc);
-
-template <typename Char>
-inline Char thousands_sep(locale_ref loc) {
+template <typename Char> FMT_API Char thousands_sep_impl(locale_ref loc);
+template <typename Char> inline Char thousands_sep(locale_ref loc) {
return Char(thousands_sep_impl<char>(loc));
}
-
-template <>
-inline wchar_t thousands_sep(locale_ref loc) {
+template <> inline wchar_t thousands_sep(locale_ref loc) {
return thousands_sep_impl<wchar_t>(loc);
}
+template <typename Char> FMT_API Char decimal_point_impl(locale_ref loc);
+template <typename Char> inline Char decimal_point(locale_ref loc) {
+ return Char(decimal_point_impl<char>(loc));
+}
+template <> inline wchar_t decimal_point(locale_ref loc) {
+ return decimal_point_impl<wchar_t>(loc);
+}
+
// 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 <typename UInt, typename Char, typename ThousandsSep>
-inline Char *format_decimal(Char *buffer, UInt value, int num_digits,
- ThousandsSep thousands_sep) {
+// add_thousands_sep is called after writing each char to add a thousands
+// separator if necessary.
+template <typename UInt, typename Char, typename F>
+inline Char* format_decimal(Char* buffer, UInt value, int num_digits,
+ F add_thousands_sep) {
FMT_ASSERT(num_digits >= 0, "invalid digit count");
buffer += num_digits;
- Char *end = buffer;
+ Char* end = buffer;
while (value >= 100) {
// Integer division is slow so do it for a group of two digits instead
// of for every digit. The idea comes from the talk by Alexandrescu
// "Three Optimization Tips for C++". See speed-test for a comparison.
unsigned index = static_cast<unsigned>((value % 100) * 2);
value /= 100;
- *--buffer = static_cast<Char>(data::DIGITS[index + 1]);
- thousands_sep(buffer);
- *--buffer = static_cast<Char>(data::DIGITS[index]);
- thousands_sep(buffer);
+ *--buffer = static_cast<Char>(data::digits[index + 1]);
+ add_thousands_sep(buffer);
+ *--buffer = static_cast<Char>(data::digits[index]);
+ add_thousands_sep(buffer);
}
if (value < 10) {
*--buffer = static_cast<Char>('0' + value);
return end;
}
unsigned index = static_cast<unsigned>(value * 2);
- *--buffer = static_cast<Char>(data::DIGITS[index + 1]);
- thousands_sep(buffer);
- *--buffer = static_cast<Char>(data::DIGITS[index]);
+ *--buffer = static_cast<Char>(data::digits[index + 1]);
+ add_thousands_sep(buffer);
+ *--buffer = static_cast<Char>(data::digits[index]);
return end;
}
-template <typename OutChar, typename UInt, typename Iterator,
- typename ThousandsSep>
-inline Iterator format_decimal(
- Iterator out, UInt value, int num_digits, ThousandsSep sep) {
+template <typename Char, typename UInt, typename Iterator, typename F>
+inline Iterator format_decimal(Iterator out, UInt value, int num_digits,
+ F add_thousands_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).
enum { max_size = std::numeric_limits<UInt>::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<OutChar>(buffer, end, out);
+ Char buffer[max_size + max_size / 3];
+ auto end = format_decimal(buffer, value, num_digits, add_thousands_sep);
+ return internal::copy_str<Char>(buffer, end, out);
}
-template <typename OutChar, typename It, typename UInt>
+template <typename Char, typename It, typename UInt>
inline It format_decimal(It out, UInt value, int num_digits) {
- return format_decimal<OutChar>(out, value, num_digits, no_thousands_sep());
+ return format_decimal<Char>(out, value, num_digits, [](Char*) {});
}
template <unsigned BASE_BITS, typename Char, typename UInt>
-inline Char *format_uint(Char *buffer, UInt value, int num_digits,
+inline Char* format_uint(Char* buffer, UInt value, int num_digits,
bool upper = false) {
buffer += num_digits;
- Char *end = buffer;
+ Char* end = buffer;
do {
- const char *digits = upper ? "0123456789ABCDEF" : "0123456789abcdef";
+ const char* digits = upper ? "0123456789ABCDEF" : data::hex_digits;
unsigned digit = (value & ((1 << BASE_BITS) - 1));
*--buffer = static_cast<Char>(BASE_BITS < 4 ? static_cast<char>('0' + digit)
: digits[digit]);
@@ -1015,20 +856,40 @@
return end;
}
+template <unsigned BASE_BITS, typename Char>
+Char* format_uint(Char* buffer, internal::fallback_uintptr n, int num_digits,
+ bool = false) {
+ auto char_digits = std::numeric_limits<unsigned char>::digits / 4;
+ int start = (num_digits + char_digits - 1) / char_digits - 1;
+ if (int start_digits = num_digits % char_digits) {
+ unsigned value = n.value[start--];
+ buffer = format_uint<BASE_BITS>(buffer, value, start_digits);
+ }
+ for (; start >= 0; --start) {
+ unsigned value = n.value[start];
+ buffer += char_digits;
+ auto p = buffer;
+ for (int i = 0; i < char_digits; ++i) {
+ unsigned digit = (value & ((1 << BASE_BITS) - 1));
+ *--p = static_cast<Char>(data::hex_digits[digit]);
+ value >>= BASE_BITS;
+ }
+ }
+ return buffer;
+}
+
template <unsigned BASE_BITS, typename Char, typename It, typename UInt>
-inline It format_uint(It out, UInt value, int num_digits,
- bool upper = false) {
- // Buffer should be large enough to hold all digits (digits / BASE_BITS + 1)
- // and null.
- char buffer[std::numeric_limits<UInt>::digits / BASE_BITS + 2];
+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).
+ char buffer[std::numeric_limits<UInt>::digits / BASE_BITS + 1];
format_uint<BASE_BITS>(buffer, value, num_digits, upper);
return internal::copy_str<Char>(buffer, buffer + num_digits, out);
}
#ifndef _WIN32
-# define FMT_USE_WINDOWS_H 0
+# define FMT_USE_WINDOWS_H 0
#elif !defined(FMT_USE_WINDOWS_H)
-# define FMT_USE_WINDOWS_H 1
+# define FMT_USE_WINDOWS_H 1
#endif
// Define FMT_USE_WINDOWS_H to 0 to disable use of windows.h.
@@ -1044,7 +905,7 @@
FMT_API explicit utf8_to_utf16(string_view s);
operator wstring_view() const { return wstring_view(&buffer_[0], size()); }
size_t size() const { return buffer_.size() - 1; }
- const wchar_t *c_str() const { return &buffer_[0]; }
+ const wchar_t* c_str() const { return &buffer_[0]; }
std::wstring str() const { return std::wstring(&buffer_[0], size()); }
};
@@ -1059,7 +920,7 @@
FMT_API explicit utf16_to_utf8(wstring_view s);
operator string_view() const { return string_view(&buffer_[0], size()); }
size_t size() const { return buffer_.size() - 1; }
- const char *c_str() const { return &buffer_[0]; }
+ const char* c_str() const { return &buffer_[0]; }
std::string str() const { return std::string(&buffer_[0], size()); }
// Performs conversion returning a system error code instead of
@@ -1068,84 +929,198 @@
FMT_API int convert(wstring_view s);
};
-FMT_API void format_windows_error(fmt::internal::buffer &out, int error_code,
+FMT_API void format_windows_error(fmt::internal::buffer<char>& out,
+ int error_code,
fmt::string_view message) FMT_NOEXCEPT;
#endif
-template <typename T = void>
-struct null {};
+template <typename T = void> struct null {};
+
+// Workaround an array initialization issue in gcc 4.8.
+template <typename Char> struct fill_t {
+ private:
+ Char data_[6];
+
+ public:
+ FMT_CONSTEXPR Char& operator[](size_t index) { return data_[index]; }
+ FMT_CONSTEXPR const Char& operator[](size_t index) const {
+ return data_[index];
+ }
+
+ static FMT_CONSTEXPR fill_t<Char> make() {
+ auto fill = fill_t<Char>();
+ fill[0] = Char(' ');
+ return fill;
+ }
+};
} // namespace internal
-enum alignment {
- ALIGN_DEFAULT, ALIGN_LEFT, ALIGN_RIGHT, ALIGN_CENTER, ALIGN_NUMERIC
-};
-
-// Flags.
-enum { SIGN_FLAG = 1, PLUS_FLAG = 2, MINUS_FLAG = 4, HASH_FLAG = 8 };
-
-// An alignment specifier.
-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() : 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_; }
-};
-
-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 <typename Char>
-struct basic_format_specs : align_spec, core_format_specs {
- FMT_CONSTEXPR basic_format_specs() {}
-};
-
-typedef basic_format_specs<char> format_specs;
-
-template <typename Char, typename ErrorHandler>
-FMT_CONSTEXPR unsigned basic_parse_context<Char, ErrorHandler>::next_arg_id() {
- if (next_arg_id_ >= 0)
- return internal::to_unsigned(next_arg_id_++);
- on_error("cannot switch from manual to automatic argument indexing");
- return 0;
+// We cannot use enum classes as bit fields because of a gcc bug
+// https://gcc.gnu.org/bugzilla/show_bug.cgi?id=61414.
+namespace align {
+enum type { none, left, right, center, numeric };
}
+using align_t = align::type;
+
+namespace sign {
+enum type { none, minus, plus, space };
+}
+using sign_t = sign::type;
+
+// Format specifiers for built-in and string types.
+template <typename Char> struct basic_format_specs {
+ int width;
+ int precision;
+ char type;
+ align_t align : 4;
+ sign_t sign : 3;
+ bool alt : 1; // Alternate form ('#').
+ internal::fill_t<Char> fill;
+
+ constexpr basic_format_specs()
+ : width(0),
+ precision(-1),
+ type(0),
+ align(align::none),
+ sign(sign::none),
+ alt(false),
+ fill(internal::fill_t<Char>::make()) {}
+};
+
+using format_specs = basic_format_specs<char>;
namespace internal {
-// Formats value using Grisu2 algorithm:
+// Writes the exponent exp in the form "[+-]d{2,3}" to buffer.
+template <typename Char, typename It> It write_exponent(int exp, It it) {
+ FMT_ASSERT(-1000 < exp && exp < 1000, "exponent out of range");
+ if (exp < 0) {
+ *it++ = static_cast<Char>('-');
+ exp = -exp;
+ } else {
+ *it++ = static_cast<Char>('+');
+ }
+ if (exp >= 100) {
+ *it++ = static_cast<Char>(static_cast<char>('0' + exp / 100));
+ exp %= 100;
+ }
+ const char* d = data::digits + exp * 2;
+ *it++ = static_cast<Char>(d[0]);
+ *it++ = static_cast<Char>(d[1]);
+ return it;
+}
+
+struct gen_digits_params {
+ int num_digits;
+ bool fixed;
+ bool upper;
+ bool trailing_zeros;
+};
+
+// The number is given as v = digits * pow(10, exp).
+template <typename Char, typename It>
+It grisu_prettify(const char* digits, int size, int exp, It it,
+ gen_digits_params params, Char decimal_point) {
+ // pow(10, full_exp - 1) <= v <= pow(10, full_exp).
+ int full_exp = size + exp;
+ if (!params.fixed) {
+ // Insert a decimal point after the first digit and add an exponent.
+ *it++ = static_cast<Char>(*digits);
+ if (size > 1) *it++ = decimal_point;
+ exp += size - 1;
+ it = copy_str<Char>(digits + 1, digits + size, it);
+ if (size < params.num_digits)
+ it = std::fill_n(it, params.num_digits - size, static_cast<Char>('0'));
+ *it++ = static_cast<Char>(params.upper ? 'E' : 'e');
+ return write_exponent<Char>(exp, it);
+ }
+ if (size <= full_exp) {
+ // 1234e7 -> 12340000000[.0+]
+ it = copy_str<Char>(digits, digits + size, it);
+ it = std::fill_n(it, full_exp - size, static_cast<Char>('0'));
+ int num_zeros = (std::max)(params.num_digits - full_exp, 1);
+ if (params.trailing_zeros) {
+ *it++ = decimal_point;
+#ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
+ if (num_zeros > 1000)
+ throw std::runtime_error("fuzz mode - avoiding excessive cpu use");
+#endif
+ it = std::fill_n(it, num_zeros, static_cast<Char>('0'));
+ }
+ } else if (full_exp > 0) {
+ // 1234e-2 -> 12.34[0+]
+ it = copy_str<Char>(digits, digits + full_exp, it);
+ if (!params.trailing_zeros) {
+ // Remove trailing zeros.
+ while (size > full_exp && digits[size - 1] == '0') --size;
+ if (size != full_exp) *it++ = decimal_point;
+ return copy_str<Char>(digits + full_exp, digits + size, it);
+ }
+ *it++ = decimal_point;
+ it = copy_str<Char>(digits + full_exp, digits + size, it);
+ if (params.num_digits > size) {
+ // Add trailing zeros.
+ int num_zeros = params.num_digits - size;
+ it = std::fill_n(it, num_zeros, static_cast<Char>('0'));
+ }
+ } else {
+ // 1234e-6 -> 0.001234
+ *it++ = static_cast<Char>('0');
+ int num_zeros = -full_exp;
+ if (params.num_digits >= 0 && params.num_digits < num_zeros)
+ num_zeros = params.num_digits;
+ if (!params.trailing_zeros)
+ while (size > 0 && digits[size - 1] == '0') --size;
+ if (num_zeros != 0 || size != 0) {
+ *it++ = decimal_point;
+ it = std::fill_n(it, num_zeros, static_cast<Char>('0'));
+ it = copy_str<Char>(digits, digits + size, it);
+ }
+ }
+ return it;
+}
+
+namespace grisu_options {
+enum { fixed = 1, grisu3 = 2 };
+}
+
+// Formats value using the Grisu algorithm:
// https://www.cs.tufts.edu/~nr/cs257/archive/florian-loitsch/printf.pdf
-template <typename Double>
-FMT_API typename std::enable_if<sizeof(Double) == sizeof(uint64_t), bool>::type
- grisu2_format(Double value, buffer &buf, core_format_specs);
-template <typename Double>
-inline typename std::enable_if<sizeof(Double) != sizeof(uint64_t), bool>::type
- grisu2_format(Double, buffer &, core_format_specs) { return false; }
+template <typename Double, FMT_ENABLE_IF(sizeof(Double) == sizeof(uint64_t))>
+FMT_API bool grisu_format(Double, buffer<char>&, int, unsigned, int&);
+template <typename Double, FMT_ENABLE_IF(sizeof(Double) != sizeof(uint64_t))>
+inline bool grisu_format(Double, buffer<char>&, int, unsigned, int&) {
+ return false;
+}
+
+struct sprintf_specs {
+ int precision;
+ char type;
+ bool alt : 1;
+
+ template <typename Char>
+ constexpr sprintf_specs(basic_format_specs<Char> specs)
+ : precision(specs.precision), type(specs.type), alt(specs.alt) {}
+
+ constexpr bool has_precision() const { return precision >= 0; }
+};
template <typename Double>
-void sprintf_format(Double, internal::buffer &, core_format_specs);
+char* sprintf_format(Double, internal::buffer<char>&, sprintf_specs);
template <typename Handler>
-FMT_CONSTEXPR void handle_int_type_spec(char spec, Handler &&handler) {
+FMT_CONSTEXPR void handle_int_type_spec(char spec, Handler&& handler) {
switch (spec) {
- case 0: case 'd':
+ case 0:
+ case 'd':
handler.on_dec();
break;
- case 'x': case 'X':
+ case 'x':
+ case 'X':
handler.on_hex();
break;
- case 'b': case 'B':
+ case 'b':
+ case 'B':
handler.on_bin();
break;
case 'o':
@@ -1160,20 +1135,31 @@
}
template <typename Handler>
-FMT_CONSTEXPR void handle_float_type_spec(char spec, Handler &&handler) {
+FMT_CONSTEXPR void handle_float_type_spec(char spec, Handler&& handler) {
switch (spec) {
- case 0: case 'g': case 'G':
+ case 0:
+ case 'g':
+ case 'G':
handler.on_general();
break;
- case 'e': case 'E':
+ case 'e':
+ case 'E':
handler.on_exp();
break;
- case 'f': case 'F':
+ case 'f':
+ case 'F':
handler.on_fixed();
break;
- case 'a': case 'A':
+ case '%':
+ handler.on_percent();
+ break;
+ case 'a':
+ case 'A':
handler.on_hex();
break;
+ case 'n':
+ handler.on_num();
+ break;
default:
handler.on_error();
break;
@@ -1181,17 +1167,17 @@
}
template <typename Char, typename Handler>
-FMT_CONSTEXPR void handle_char_specs(
- const basic_format_specs<Char> *specs, Handler &&handler) {
+FMT_CONSTEXPR void handle_char_specs(const basic_format_specs<Char>* specs,
+ Handler&& handler) {
if (!specs) return handler.on_char();
if (specs->type && specs->type != 'c') return handler.on_int();
- if (specs->align() == ALIGN_NUMERIC || specs->flags != 0)
+ if (specs->align == align::numeric || specs->sign != sign::none || specs->alt)
handler.on_error("invalid format specifier for char");
handler.on_char();
}
template <typename Char, typename Handler>
-FMT_CONSTEXPR void handle_cstring_type_spec(Char spec, Handler &&handler) {
+FMT_CONSTEXPR void handle_cstring_type_spec(Char spec, Handler&& handler) {
if (spec == 0 || spec == 's')
handler.on_string();
else if (spec == 'p')
@@ -1201,19 +1187,16 @@
}
template <typename Char, typename ErrorHandler>
-FMT_CONSTEXPR void check_string_type_spec(Char spec, ErrorHandler &&eh) {
- if (spec != 0 && spec != 's')
- eh.on_error("invalid type specifier");
+FMT_CONSTEXPR void check_string_type_spec(Char spec, ErrorHandler&& eh) {
+ if (spec != 0 && spec != 's') eh.on_error("invalid type specifier");
}
template <typename Char, typename ErrorHandler>
-FMT_CONSTEXPR void check_pointer_type_spec(Char spec, ErrorHandler &&eh) {
- if (spec != 0 && spec != 'p')
- eh.on_error("invalid type specifier");
+FMT_CONSTEXPR void check_pointer_type_spec(Char spec, ErrorHandler&& eh) {
+ if (spec != 0 && spec != 'p') eh.on_error("invalid type specifier");
}
-template <typename ErrorHandler>
-class int_type_checker : private ErrorHandler {
+template <typename ErrorHandler> class int_type_checker : private ErrorHandler {
public:
FMT_CONSTEXPR explicit int_type_checker(ErrorHandler eh) : ErrorHandler(eh) {}
@@ -1232,12 +1215,14 @@
class float_type_checker : private ErrorHandler {
public:
FMT_CONSTEXPR explicit float_type_checker(ErrorHandler eh)
- : ErrorHandler(eh) {}
+ : ErrorHandler(eh) {}
FMT_CONSTEXPR void on_general() {}
FMT_CONSTEXPR void on_exp() {}
FMT_CONSTEXPR void on_fixed() {}
+ FMT_CONSTEXPR void on_percent() {}
FMT_CONSTEXPR void on_hex() {}
+ FMT_CONSTEXPR void on_num() {}
FMT_CONSTEXPR void on_error() {
ErrorHandler::on_error("invalid type specifier");
@@ -1251,7 +1236,7 @@
public:
FMT_CONSTEXPR char_specs_checker(char type, ErrorHandler eh)
- : ErrorHandler(eh), type_(type) {}
+ : ErrorHandler(eh), type_(type) {}
FMT_CONSTEXPR void on_int() {
handle_int_type_spec(type_, int_type_checker<ErrorHandler>(*this));
@@ -1263,55 +1248,471 @@
class cstring_type_checker : public ErrorHandler {
public:
FMT_CONSTEXPR explicit cstring_type_checker(ErrorHandler eh)
- : ErrorHandler(eh) {}
+ : ErrorHandler(eh) {}
FMT_CONSTEXPR void on_string() {}
FMT_CONSTEXPR void on_pointer() {}
};
template <typename Context>
-void arg_map<Context>::init(const basic_format_args<Context> &args) {
- if (map_)
- return;
- map_ = new entry[args.max_size()];
+void arg_map<Context>::init(const basic_format_args<Context>& args) {
+ if (map_) return;
+ map_ = new entry[internal::to_unsigned(args.max_size())];
if (args.is_packed()) {
- for (unsigned i = 0;/*nothing*/; ++i) {
+ for (int i = 0;; ++i) {
internal::type arg_type = args.type(i);
- switch (arg_type) {
- case internal::none_type:
- return;
- case internal::named_arg_type:
- push_back(args.values_[i]);
- break;
- default:
- break; // Do nothing.
- }
+ if (arg_type == internal::none_type) return;
+ if (arg_type == internal::named_arg_type) push_back(args.values_[i]);
}
}
- for (unsigned i = 0; ; ++i) {
- switch (args.args_[i].type_) {
- case internal::none_type:
- return;
- case internal::named_arg_type:
- push_back(args.args_[i].value_);
- break;
- default:
- break; // Do nothing.
- }
+ for (int i = 0, n = args.max_size(); i < n; ++i) {
+ auto type = args.args_[i].type_;
+ if (type == internal::named_arg_type) push_back(args.args_[i].value_);
}
}
-template <typename Range>
-class arg_formatter_base {
+// This template provides operations for formatting and writing data into a
+// character range.
+template <typename Range> class basic_writer {
public:
- typedef typename Range::value_type char_type;
- typedef decltype(internal::declval<Range>().begin()) iterator;
- typedef basic_format_specs<char_type> format_specs;
+ using char_type = typename Range::value_type;
+ using iterator = typename Range::iterator;
+ using format_specs = basic_format_specs<char_type>;
private:
- typedef basic_writer<Range> writer_type;
+ iterator out_; // Output iterator.
+ internal::locale_ref locale_;
+
+ // Attempts to reserve space for n extra characters in the output range.
+ // Returns a pointer to the reserved range or a reference to out_.
+ auto reserve(std::size_t n) -> decltype(internal::reserve(out_, n)) {
+ return internal::reserve(out_, n);
+ }
+
+ template <typename F> struct padded_int_writer {
+ size_t size_;
+ string_view prefix;
+ char_type fill;
+ std::size_t padding;
+ F f;
+
+ size_t size() const { return size_; }
+ size_t width() const { return size_; }
+
+ template <typename It> void operator()(It&& it) const {
+ if (prefix.size() != 0)
+ it = internal::copy_str<char_type>(prefix.begin(), prefix.end(), it);
+ it = std::fill_n(it, padding, fill);
+ f(it);
+ }
+ };
+
+ // Writes an integer in the format
+ // <left-padding><prefix><numeric-padding><digits><right-padding>
+ // where <digits> are written by f(it).
+ template <typename F>
+ void write_int(int num_digits, string_view prefix, format_specs specs, F f) {
+ std::size_t size = prefix.size() + internal::to_unsigned(num_digits);
+ char_type fill = specs.fill[0];
+ std::size_t padding = 0;
+ if (specs.align == align::numeric) {
+ auto unsiged_width = internal::to_unsigned(specs.width);
+ if (unsiged_width > size) {
+ padding = unsiged_width - size;
+ size = unsiged_width;
+ }
+ } else if (specs.precision > num_digits) {
+ size = prefix.size() + internal::to_unsigned(specs.precision);
+ padding = internal::to_unsigned(specs.precision - num_digits);
+ fill = static_cast<char_type>('0');
+ }
+ if (specs.align == align::none) specs.align = align::right;
+ write_padded(specs, padded_int_writer<F>{size, prefix, fill, padding, f});
+ }
+
+ // Writes a decimal integer.
+ template <typename Int> void write_decimal(Int value) {
+ auto abs_value = static_cast<uint32_or_64_t<Int>>(value);
+ bool is_negative = internal::is_negative(value);
+ if (is_negative) abs_value = 0 - abs_value;
+ int num_digits = internal::count_digits(abs_value);
+ auto&& it =
+ reserve((is_negative ? 1 : 0) + static_cast<size_t>(num_digits));
+ if (is_negative) *it++ = static_cast<char_type>('-');
+ it = internal::format_decimal<char_type>(it, abs_value, num_digits);
+ }
+
+ // The handle_int_type_spec handler that writes an integer.
+ template <typename Int, typename Specs> struct int_writer {
+ using unsigned_type = uint32_or_64_t<Int>;
+
+ basic_writer<Range>& writer;
+ const Specs& specs;
+ unsigned_type abs_value;
+ char prefix[4];
+ unsigned prefix_size;
+
+ string_view get_prefix() const { return string_view(prefix, prefix_size); }
+
+ int_writer(basic_writer<Range>& w, Int value, const Specs& s)
+ : writer(w),
+ specs(s),
+ abs_value(static_cast<unsigned_type>(value)),
+ prefix_size(0) {
+ if (internal::is_negative(value)) {
+ prefix[0] = '-';
+ ++prefix_size;
+ abs_value = 0 - abs_value;
+ } else if (specs.sign != sign::none && specs.sign != sign::minus) {
+ prefix[0] = specs.sign == sign::plus ? '+' : ' ';
+ ++prefix_size;
+ }
+ }
+
+ struct dec_writer {
+ unsigned_type abs_value;
+ int num_digits;
+
+ template <typename It> void operator()(It&& it) const {
+ it = internal::format_decimal<char_type>(it, abs_value, num_digits);
+ }
+ };
+
+ void on_dec() {
+ int num_digits = internal::count_digits(abs_value);
+ writer.write_int(num_digits, get_prefix(), specs,
+ dec_writer{abs_value, num_digits});
+ }
+
+ struct hex_writer {
+ int_writer& self;
+ int num_digits;
+
+ template <typename It> void operator()(It&& it) const {
+ it = internal::format_uint<4, char_type>(it, self.abs_value, num_digits,
+ self.specs.type != 'x');
+ }
+ };
+
+ void on_hex() {
+ if (specs.alt) {
+ prefix[prefix_size++] = '0';
+ prefix[prefix_size++] = specs.type;
+ }
+ int num_digits = internal::count_digits<4>(abs_value);
+ writer.write_int(num_digits, get_prefix(), specs,
+ hex_writer{*this, num_digits});
+ }
+
+ template <int BITS> struct bin_writer {
+ unsigned_type abs_value;
+ int num_digits;
+
+ template <typename It> void operator()(It&& it) const {
+ it = internal::format_uint<BITS, char_type>(it, abs_value, num_digits);
+ }
+ };
+
+ void on_bin() {
+ if (specs.alt) {
+ prefix[prefix_size++] = '0';
+ prefix[prefix_size++] = static_cast<char>(specs.type);
+ }
+ int num_digits = internal::count_digits<1>(abs_value);
+ writer.write_int(num_digits, get_prefix(), specs,
+ bin_writer<1>{abs_value, num_digits});
+ }
+
+ void on_oct() {
+ int num_digits = internal::count_digits<3>(abs_value);
+ if (specs.alt && specs.precision <= num_digits) {
+ // Octal prefix '0' is counted as a digit, so only add it if precision
+ // is not greater than the number of digits.
+ prefix[prefix_size++] = '0';
+ }
+ writer.write_int(num_digits, get_prefix(), specs,
+ bin_writer<3>{abs_value, num_digits});
+ }
+
+ enum { sep_size = 1 };
+
+ struct num_writer {
+ unsigned_type abs_value;
+ int size;
+ char_type sep;
+
+ template <typename It> void operator()(It&& it) const {
+ basic_string_view<char_type> s(&sep, sep_size);
+ // Index of a decimal digit with the least significant digit having
+ // index 0.
+ unsigned digit_index = 0;
+ it = internal::format_decimal<char_type>(
+ it, abs_value, size, [s, &digit_index](char_type*& buffer) {
+ if (++digit_index % 3 != 0) return;
+ buffer -= s.size();
+ std::uninitialized_copy(s.data(), s.data() + s.size(),
+ internal::make_checked(buffer, s.size()));
+ });
+ }
+ };
+
+ void on_num() {
+ char_type sep = internal::thousands_sep<char_type>(writer.locale_);
+ if (!sep) return on_dec();
+ int num_digits = internal::count_digits(abs_value);
+ int size = num_digits + sep_size * ((num_digits - 1) / 3);
+ writer.write_int(size, get_prefix(), specs,
+ num_writer{abs_value, size, sep});
+ }
+
+ FMT_NORETURN void on_error() {
+ FMT_THROW(format_error("invalid type specifier"));
+ }
+ };
+
+ enum { inf_size = 3 }; // This is an enum to workaround a bug in MSVC.
+
+ struct inf_or_nan_writer {
+ char sign;
+ bool as_percentage;
+ const char* str;
+
+ size_t size() const {
+ return static_cast<std::size_t>(inf_size + (sign ? 1 : 0) +
+ (as_percentage ? 1 : 0));
+ }
+ size_t width() const { return size(); }
+
+ template <typename It> void operator()(It&& it) const {
+ if (sign) *it++ = static_cast<char_type>(sign);
+ it = internal::copy_str<char_type>(
+ str, str + static_cast<std::size_t>(inf_size), it);
+ if (as_percentage) *it++ = static_cast<char_type>('%');
+ }
+ };
+
+ struct double_writer {
+ char sign;
+ internal::buffer<char>& buffer;
+ char* decimal_point_pos;
+ char_type decimal_point;
+
+ size_t size() const { return buffer.size() + (sign ? 1 : 0); }
+ size_t width() const { return size(); }
+
+ template <typename It> void operator()(It&& it) {
+ if (sign) *it++ = static_cast<char_type>(sign);
+ auto begin = buffer.begin();
+ if (decimal_point_pos) {
+ it = internal::copy_str<char_type>(begin, decimal_point_pos, it);
+ *it++ = decimal_point;
+ begin = decimal_point_pos + 1;
+ }
+ it = internal::copy_str<char_type>(begin, buffer.end(), it);
+ }
+ };
+
+ class grisu_writer {
+ private:
+ internal::buffer<char>& digits_;
+ size_t size_;
+ char sign_;
+ int exp_;
+ internal::gen_digits_params params_;
+ char_type decimal_point_;
+
+ public:
+ grisu_writer(char sign, internal::buffer<char>& digits, int exp,
+ const internal::gen_digits_params& params,
+ char_type decimal_point)
+ : digits_(digits),
+ sign_(sign),
+ exp_(exp),
+ params_(params),
+ decimal_point_(decimal_point) {
+ int num_digits = static_cast<int>(digits.size());
+ int full_exp = num_digits + exp - 1;
+ int precision = params.num_digits > 0 ? params.num_digits : 11;
+ params_.fixed |= full_exp >= -4 && full_exp < precision;
+ auto it = internal::grisu_prettify<char>(
+ digits.data(), num_digits, exp, internal::counting_iterator<char>(),
+ params_, '.');
+ size_ = it.count();
+ }
+
+ size_t size() const { return size_ + (sign_ ? 1 : 0); }
+ size_t width() const { return size(); }
+
+ template <typename It> void operator()(It&& it) {
+ if (sign_) *it++ = static_cast<char_type>(sign_);
+ int num_digits = static_cast<int>(digits_.size());
+ it = internal::grisu_prettify<char_type>(digits_.data(), num_digits, exp_,
+ it, params_, decimal_point_);
+ }
+ };
+
+ template <typename Char> struct str_writer {
+ const Char* s;
+ size_t size_;
+
+ size_t size() const { return size_; }
+ size_t width() const {
+ return internal::count_code_points(basic_string_view<Char>(s, size_));
+ }
+
+ template <typename It> void operator()(It&& it) const {
+ it = internal::copy_str<char_type>(s, s + size_, it);
+ }
+ };
+
+ template <typename UIntPtr> struct pointer_writer {
+ UIntPtr value;
+ int num_digits;
+
+ size_t size() const { return to_unsigned(num_digits) + 2; }
+ size_t width() const { return size(); }
+
+ template <typename It> void operator()(It&& it) const {
+ *it++ = static_cast<char_type>('0');
+ *it++ = static_cast<char_type>('x');
+ it = internal::format_uint<4, char_type>(it, value, num_digits);
+ }
+ };
+
+ public:
+ /** Constructs a ``basic_writer`` object. */
+ explicit basic_writer(Range out,
+ internal::locale_ref loc = internal::locale_ref())
+ : out_(out.begin()), locale_(loc) {}
+
+ iterator out() const { return out_; }
+
+ // Writes a value in the format
+ // <left-padding><value><right-padding>
+ // where <value> is written by f(it).
+ template <typename F> void write_padded(const format_specs& specs, F&& f) {
+ // User-perceived width (in code points).
+ unsigned width = to_unsigned(specs.width);
+ size_t size = f.size(); // The number of code units.
+ size_t num_code_points = width != 0 ? f.width() : size;
+ if (width <= num_code_points) return f(reserve(size));
+ auto&& it = reserve(width + (size - num_code_points));
+ char_type fill = specs.fill[0];
+ std::size_t padding = width - num_code_points;
+ if (specs.align == align::right) {
+ it = std::fill_n(it, padding, fill);
+ f(it);
+ } else if (specs.align == align::center) {
+ std::size_t left_padding = padding / 2;
+ it = std::fill_n(it, left_padding, fill);
+ f(it);
+ it = std::fill_n(it, padding - left_padding, fill);
+ } else {
+ f(it);
+ it = std::fill_n(it, padding, fill);
+ }
+ }
+
+ void write(int value) { write_decimal(value); }
+ void write(long value) { write_decimal(value); }
+ void write(long long value) { write_decimal(value); }
+
+ void write(unsigned value) { write_decimal(value); }
+ void write(unsigned long value) { write_decimal(value); }
+ void write(unsigned long long value) { write_decimal(value); }
+
+ // Writes a formatted integer.
+ template <typename T, typename Spec>
+ void write_int(T value, const Spec& spec) {
+ internal::handle_int_type_spec(spec.type,
+ int_writer<T, Spec>(*this, value, spec));
+ }
+
+ void write(double value, const format_specs& specs = format_specs()) {
+ write_double(value, specs);
+ }
+
+ /**
+ \rst
+ Formats *value* using the general format for floating-point numbers
+ (``'g'``) and writes it to the buffer.
+ \endrst
+ */
+ void write(long double value, const format_specs& specs = format_specs()) {
+ write_double(value, specs);
+ }
+
+ // Formats a floating-point number (double or long double).
+ template <typename T, bool USE_GRISU = fmt::internal::use_grisu<T>()>
+ void write_double(T value, const format_specs& specs);
+
+ /** Writes a character to the buffer. */
+ void write(char value) {
+ auto&& it = reserve(1);
+ *it++ = value;
+ }
+
+ template <typename Char, FMT_ENABLE_IF(std::is_same<Char, char_type>::value)>
+ void write(Char value) {
+ auto&& it = reserve(1);
+ *it++ = value;
+ }
+
+ /**
+ \rst
+ Writes *value* to the buffer.
+ \endrst
+ */
+ void write(string_view value) {
+ auto&& it = reserve(value.size());
+ it = internal::copy_str<char_type>(value.begin(), value.end(), it);
+ }
+ void write(wstring_view value) {
+ static_assert(std::is_same<char_type, wchar_t>::value, "");
+ auto&& it = reserve(value.size());
+ it = std::copy(value.begin(), value.end(), it);
+ }
+
+ // Writes a formatted string.
+ template <typename Char>
+ void write(const Char* s, std::size_t size, const format_specs& specs) {
+ write_padded(specs, str_writer<Char>{s, size});
+ }
+
+ template <typename Char>
+ void write(basic_string_view<Char> s,
+ const format_specs& specs = format_specs()) {
+ const Char* data = s.data();
+ std::size_t size = s.size();
+ if (specs.precision >= 0 && internal::to_unsigned(specs.precision) < size)
+ size = internal::to_unsigned(specs.precision);
+ write(data, size, specs);
+ }
+
+ template <typename UIntPtr>
+ void write_pointer(UIntPtr value, const format_specs* specs) {
+ int num_digits = internal::count_digits<4>(value);
+ auto pw = pointer_writer<UIntPtr>{value, num_digits};
+ if (!specs) return pw(reserve(to_unsigned(num_digits) + 2));
+ format_specs specs_copy = *specs;
+ if (specs_copy.align == align::none) specs_copy.align = align::right;
+ write_padded(specs_copy, pw);
+ }
+};
+
+using writer = basic_writer<buffer_range<char>>;
+
+template <typename Range, typename ErrorHandler = internal::error_handler>
+class arg_formatter_base {
+ public:
+ using char_type = typename Range::value_type;
+ using iterator = typename Range::iterator;
+ using format_specs = basic_format_specs<char_type>;
+
+ private:
+ using writer_type = basic_writer<Range>;
writer_type writer_;
- format_specs *specs_;
+ format_specs* specs_;
struct char_writer {
char_type value;
@@ -1319,8 +1720,7 @@
size_t size() const { return 1; }
size_t width() const { return 1; }
- template <typename It>
- void operator()(It &&it) const { *it++ = value; }
+ template <typename It> void operator()(It&& it) const { *it++ = value; }
};
void write_char(char_type value) {
@@ -1330,16 +1730,14 @@
writer_.write(value);
}
- void write_pointer(const void *p) {
- format_specs specs = specs_ ? *specs_ : format_specs();
- specs.flags = HASH_FLAG;
- specs.type = 'x';
- writer_.write_int(reinterpret_cast<uintptr_t>(p), specs);
+ void write_pointer(const void* p) {
+ writer_.write_pointer(internal::bit_cast<internal::uintptr_t>(p), specs_);
}
protected:
- writer_type &writer() { return writer_; }
- format_specs *spec() { return specs_; }
+ writer_type& writer() { return writer_; }
+ FMT_DEPRECATED format_specs* spec() { return specs_; }
+ format_specs* specs() { return specs_; }
iterator out() { return writer_.out(); }
void write(bool value) {
@@ -1347,55 +1745,58 @@
specs_ ? writer_.write(sv, *specs_) : writer_.write(sv);
}
- void write(const char_type *value) {
- if (!value)
+ void write(const char_type* value) {
+ if (!value) {
FMT_THROW(format_error("string pointer is null"));
- auto length = std::char_traits<char_type>::length(value);
- basic_string_view<char_type> sv(value, length);
- specs_ ? writer_.write(sv, *specs_) : writer_.write(sv);
+ } else {
+ auto length = std::char_traits<char_type>::length(value);
+ basic_string_view<char_type> sv(value, length);
+ specs_ ? writer_.write(sv, *specs_) : writer_.write(sv);
+ }
}
public:
- arg_formatter_base(Range r, format_specs *s, locale_ref loc)
- : writer_(r, loc), 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");
return out();
}
- template <typename T>
- typename std::enable_if<
- std::is_integral<T>::value || std::is_same<T, char_type>::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<T, bool>::value) {
- if (specs_ && specs_->type)
- return (*this)(value ? 1 : 0);
- write(value != 0);
- } else if (std::is_same<T, char_type>::value) {
- internal::handle_char_specs(
- specs_, char_spec_handler(*this, static_cast<char_type>(value)));
- } else {
- specs_ ? writer_.write_int(value, *specs_) : writer_.write(value);
- }
+ template <typename T, FMT_ENABLE_IF(std::is_integral<T>::value)>
+ iterator operator()(T value) {
+ if (specs_)
+ writer_.write_int(value, *specs_);
+ else
+ writer_.write(value);
return out();
}
- template <typename T>
- typename std::enable_if<std::is_floating_point<T>::value, iterator>::type
- operator()(T value) {
+ iterator operator()(char_type value) {
+ internal::handle_char_specs(
+ specs_, char_spec_handler(*this, static_cast<char_type>(value)));
+ return out();
+ }
+
+ iterator operator()(bool value) {
+ if (specs_ && specs_->type) return (*this)(value ? 1 : 0);
+ write(value != 0);
+ return out();
+ }
+
+ template <typename T, FMT_ENABLE_IF(std::is_floating_point<T>::value)>
+ iterator operator()(T value) {
writer_.write_double(value, specs_ ? *specs_ : format_specs());
return out();
}
- struct char_spec_handler : internal::error_handler {
- arg_formatter_base &formatter;
+ struct char_spec_handler : ErrorHandler {
+ arg_formatter_base& formatter;
char_type value;
char_spec_handler(arg_formatter_base& f, char_type val)
- : formatter(f), value(val) {}
+ : formatter(f), value(val) {}
void on_int() {
if (formatter.specs_)
@@ -1407,27 +1808,26 @@
};
struct cstring_spec_handler : internal::error_handler {
- arg_formatter_base &formatter;
- const char_type *value;
+ arg_formatter_base& formatter;
+ const char_type* value;
- cstring_spec_handler(arg_formatter_base &f, const char_type *val)
- : formatter(f), value(val) {}
+ cstring_spec_handler(arg_formatter_base& f, const char_type* val)
+ : formatter(f), value(val) {}
void on_string() { formatter.write(value); }
void on_pointer() { formatter.write_pointer(value); }
};
- iterator operator()(const char_type *value) {
+ iterator operator()(const char_type* value) {
if (!specs_) return write(value), out();
- internal::handle_cstring_type_spec(
- specs_->type, cstring_spec_handler(*this, value));
+ internal::handle_cstring_type_spec(specs_->type,
+ cstring_spec_handler(*this, value));
return out();
}
iterator operator()(basic_string_view<char_type> value) {
if (specs_) {
- internal::check_string_type_spec(
- specs_->type, internal::error_handler());
+ internal::check_string_type_spec(specs_->type, internal::error_handler());
writer_.write(value, *specs_);
} else {
writer_.write(value);
@@ -1435,7 +1835,7 @@
return out();
}
- iterator operator()(const void *value) {
+ iterator operator()(const void* value) {
if (specs_)
check_pointer_type_spec(specs_->type, internal::error_handler());
write_pointer(value);
@@ -1443,16 +1843,15 @@
}
};
-template <typename Char>
-FMT_CONSTEXPR bool is_name_start(Char c) {
+template <typename Char> FMT_CONSTEXPR bool is_name_start(Char c) {
return ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z') || '_' == c;
}
// Parses the range [begin, end) as an unsigned integer. This function assumes
// that the range is non-empty and the first character is a digit.
template <typename Char, typename ErrorHandler>
-FMT_CONSTEXPR unsigned parse_nonnegative_int(
- const Char *&begin, const Char *end, ErrorHandler &&eh) {
+FMT_CONSTEXPR int parse_nonnegative_int(const Char*& begin, const Char* end,
+ ErrorHandler&& eh) {
assert(begin != end && '0' <= *begin && *begin <= '9');
if (*begin == '0') {
++begin;
@@ -1460,7 +1859,7 @@
}
unsigned value = 0;
// Convert to unsigned to prevent a warning.
- unsigned max_int = (std::numeric_limits<int>::max)();
+ constexpr unsigned max_int = (std::numeric_limits<int>::max)();
unsigned big = max_int / 10;
do {
// Check for overflow.
@@ -1471,109 +1870,100 @@
value = value * 10 + unsigned(*begin - '0');
++begin;
} while (begin != end && '0' <= *begin && *begin <= '9');
- if (value > max_int)
- eh.on_error("number is too big");
- return value;
+ if (value > max_int) eh.on_error("number is too big");
+ return static_cast<int>(value);
}
-template <typename Char, typename Context>
-class custom_formatter: public function<bool> {
+template <typename Context> class custom_formatter {
private:
- Context &ctx_;
+ using char_type = typename Context::char_type;
+
+ basic_parse_context<char_type>& parse_ctx_;
+ Context& ctx_;
public:
- explicit custom_formatter(Context &ctx): ctx_(ctx) {}
+ explicit custom_formatter(basic_parse_context<char_type>& parse_ctx,
+ Context& ctx)
+ : parse_ctx_(parse_ctx), ctx_(ctx) {}
bool operator()(typename basic_format_arg<Context>::handle h) const {
- h.format(ctx_);
+ h.format(parse_ctx_, ctx_);
return true;
}
- template <typename T>
- bool operator()(T) const { return false; }
+ template <typename T> bool operator()(T) const { return false; }
};
template <typename T>
-struct is_integer {
- enum {
- value = std::is_integral<T>::value && !std::is_same<T, bool>::value &&
- !std::is_same<T, char>::value && !std::is_same<T, wchar_t>::value
- };
-};
+using is_integer =
+ bool_constant<std::is_integral<T>::value && !std::is_same<T, bool>::value &&
+ !std::is_same<T, char>::value &&
+ !std::is_same<T, wchar_t>::value>;
-template <typename ErrorHandler>
-class width_checker: public function<unsigned long long> {
+template <typename ErrorHandler> class width_checker {
public:
- explicit FMT_CONSTEXPR width_checker(ErrorHandler &eh) : handler_(eh) {}
+ explicit FMT_CONSTEXPR width_checker(ErrorHandler& eh) : handler_(eh) {}
- template <typename T>
- FMT_CONSTEXPR
- typename std::enable_if<
- is_integer<T>::value, unsigned long long>::type operator()(T value) {
- if (is_negative(value))
- handler_.on_error("negative width");
+ template <typename T, FMT_ENABLE_IF(is_integer<T>::value)>
+ FMT_CONSTEXPR unsigned long long operator()(T value) {
+ if (is_negative(value)) handler_.on_error("negative width");
return static_cast<unsigned long long>(value);
}
- template <typename T>
- FMT_CONSTEXPR typename std::enable_if<
- !is_integer<T>::value, unsigned long long>::type operator()(T) {
+ template <typename T, FMT_ENABLE_IF(!is_integer<T>::value)>
+ FMT_CONSTEXPR unsigned long long operator()(T) {
handler_.on_error("width is not integer");
return 0;
}
private:
- ErrorHandler &handler_;
+ ErrorHandler& handler_;
};
-template <typename ErrorHandler>
-class precision_checker: public function<unsigned long long> {
+template <typename ErrorHandler> class precision_checker {
public:
- explicit FMT_CONSTEXPR precision_checker(ErrorHandler &eh) : handler_(eh) {}
+ explicit FMT_CONSTEXPR precision_checker(ErrorHandler& eh) : handler_(eh) {}
- template <typename T>
- FMT_CONSTEXPR typename std::enable_if<
- is_integer<T>::value, unsigned long long>::type operator()(T value) {
- if (is_negative(value))
- handler_.on_error("negative precision");
+ template <typename T, FMT_ENABLE_IF(is_integer<T>::value)>
+ FMT_CONSTEXPR unsigned long long operator()(T value) {
+ if (is_negative(value)) handler_.on_error("negative precision");
return static_cast<unsigned long long>(value);
}
- template <typename T>
- FMT_CONSTEXPR typename std::enable_if<
- !is_integer<T>::value, unsigned long long>::type operator()(T) {
+ template <typename T, FMT_ENABLE_IF(!is_integer<T>::value)>
+ FMT_CONSTEXPR unsigned long long operator()(T) {
handler_.on_error("precision is not integer");
return 0;
}
private:
- ErrorHandler &handler_;
+ ErrorHandler& handler_;
};
// A format specifier handler that sets fields in basic_format_specs.
-template <typename Char>
-class specs_setter {
+template <typename Char> class specs_setter {
public:
- explicit FMT_CONSTEXPR specs_setter(basic_format_specs<Char> &specs):
- specs_(specs) {}
+ explicit FMT_CONSTEXPR specs_setter(basic_format_specs<Char>& specs)
+ : specs_(specs) {}
- FMT_CONSTEXPR specs_setter(const specs_setter &other): specs_(other.specs_) {}
+ FMT_CONSTEXPR 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_align(align_t align) { specs_.align = align; }
+ FMT_CONSTEXPR void on_fill(Char fill) { specs_.fill[0] = fill; }
+ FMT_CONSTEXPR void on_plus() { specs_.sign = sign::plus; }
+ FMT_CONSTEXPR void on_minus() { specs_.sign = sign::minus; }
+ FMT_CONSTEXPR void on_space() { specs_.sign = sign::space; }
+ FMT_CONSTEXPR void on_hash() { specs_.alt = true; }
FMT_CONSTEXPR void on_zero() {
- specs_.align_ = ALIGN_NUMERIC;
- specs_.fill_ = '0';
+ specs_.align = align::numeric;
+ specs_.fill[0] = Char('0');
}
- FMT_CONSTEXPR void on_width(unsigned width) { specs_.width_ = width; }
- FMT_CONSTEXPR void on_precision(unsigned precision) {
- specs_.precision = static_cast<int>(precision);
+ FMT_CONSTEXPR void on_width(int width) { specs_.width = width; }
+ FMT_CONSTEXPR void on_precision(int precision) {
+ specs_.precision = precision;
}
FMT_CONSTEXPR void end_precision() {}
@@ -1582,77 +1972,86 @@
}
protected:
- basic_format_specs<Char> &specs_;
+ basic_format_specs<Char>& specs_;
};
-// A format specifier handler that checks if specifiers are consistent with the
-// argument type.
-template <typename Handler>
-class specs_checker : public Handler {
+template <typename ErrorHandler> class numeric_specs_checker {
public:
- FMT_CONSTEXPR specs_checker(const Handler& handler, internal::type arg_type)
- : Handler(handler), arg_type_(arg_type) {}
+ FMT_CONSTEXPR numeric_specs_checker(ErrorHandler& eh, internal::type arg_type)
+ : error_handler_(eh), arg_type_(arg_type) {}
- FMT_CONSTEXPR specs_checker(const specs_checker &other)
- : Handler(other), arg_type_(other.arg_type_) {}
-
- FMT_CONSTEXPR void on_align(alignment align) {
- if (align == ALIGN_NUMERIC)
- require_numeric_argument();
- Handler::on_align(align);
- }
-
- FMT_CONSTEXPR void on_plus() {
- check_sign();
- Handler::on_plus();
- }
-
- FMT_CONSTEXPR void on_minus() {
- check_sign();
- Handler::on_minus();
- }
-
- FMT_CONSTEXPR void on_space() {
- check_sign();
- Handler::on_space();
- }
-
- FMT_CONSTEXPR void on_hash() {
- require_numeric_argument();
- Handler::on_hash();
- }
-
- FMT_CONSTEXPR void on_zero() {
- require_numeric_argument();
- Handler::on_zero();
- }
-
- FMT_CONSTEXPR void end_precision() {
- if (is_integral(arg_type_) || arg_type_ == pointer_type)
- this->on_error("precision not allowed for this argument type");
- }
-
- private:
FMT_CONSTEXPR void require_numeric_argument() {
if (!is_arithmetic(arg_type_))
- this->on_error("format specifier requires numeric argument");
+ error_handler_.on_error("format specifier requires numeric argument");
}
FMT_CONSTEXPR void check_sign() {
require_numeric_argument();
if (is_integral(arg_type_) && arg_type_ != int_type &&
arg_type_ != long_long_type && arg_type_ != internal::char_type) {
- this->on_error("format specifier requires signed argument");
+ error_handler_.on_error("format specifier requires signed argument");
}
}
+ FMT_CONSTEXPR void check_precision() {
+ if (is_integral(arg_type_) || arg_type_ == internal::pointer_type)
+ error_handler_.on_error("precision not allowed for this argument type");
+ }
+
+ private:
+ ErrorHandler& error_handler_;
internal::type arg_type_;
};
-template <template <typename> class Handler, typename T,
- typename Context, typename ErrorHandler>
-FMT_CONSTEXPR void set_dynamic_spec(
- T &value, basic_format_arg<Context> arg, ErrorHandler eh) {
+// A format specifier handler that checks if specifiers are consistent with the
+// argument type.
+template <typename Handler> class specs_checker : public Handler {
+ public:
+ FMT_CONSTEXPR specs_checker(const Handler& handler, internal::type arg_type)
+ : Handler(handler), checker_(*this, arg_type) {}
+
+ FMT_CONSTEXPR specs_checker(const specs_checker& other)
+ : Handler(other), checker_(*this, other.arg_type_) {}
+
+ FMT_CONSTEXPR void on_align(align_t align) {
+ if (align == align::numeric) checker_.require_numeric_argument();
+ Handler::on_align(align);
+ }
+
+ FMT_CONSTEXPR void on_plus() {
+ checker_.check_sign();
+ Handler::on_plus();
+ }
+
+ FMT_CONSTEXPR void on_minus() {
+ checker_.check_sign();
+ Handler::on_minus();
+ }
+
+ FMT_CONSTEXPR void on_space() {
+ checker_.check_sign();
+ Handler::on_space();
+ }
+
+ FMT_CONSTEXPR void on_hash() {
+ checker_.require_numeric_argument();
+ Handler::on_hash();
+ }
+
+ FMT_CONSTEXPR void on_zero() {
+ checker_.require_numeric_argument();
+ Handler::on_zero();
+ }
+
+ FMT_CONSTEXPR void end_precision() { checker_.check_precision(); }
+
+ private:
+ numeric_specs_checker<Handler> checker_;
+};
+
+template <template <typename> class Handler, typename T, typename FormatArg,
+ typename ErrorHandler>
+FMT_CONSTEXPR void set_dynamic_spec(T& value, FormatArg arg, ErrorHandler eh) {
unsigned long long big_value =
visit_format_arg(Handler<ErrorHandler>(eh), arg);
if (big_value > to_unsigned((std::numeric_limits<int>::max)()))
@@ -1662,73 +2061,107 @@
struct auto_id {};
-// The standard format specifier handler with checking.
template <typename Context>
-class specs_handler: public specs_setter<typename Context::char_type> {
+FMT_CONSTEXPR typename Context::format_arg get_arg(Context& ctx, int id) {
+ auto arg = ctx.arg(id);
+ if (!arg) ctx.on_error("argument index out of range");
+ return arg;
+}
+
+// The standard format specifier handler with checking.
+template <typename ParseContext, typename Context>
+class specs_handler : public specs_setter<typename Context::char_type> {
public:
- typedef typename Context::char_type char_type;
+ using char_type = typename Context::char_type;
- FMT_CONSTEXPR specs_handler(
- basic_format_specs<char_type> &specs, Context &ctx)
- : specs_setter<char_type>(specs), context_(ctx) {}
+ FMT_CONSTEXPR specs_handler(basic_format_specs<char_type>& specs,
+ ParseContext& parse_ctx, Context& ctx)
+ : specs_setter<char_type>(specs),
+ parse_context_(parse_ctx),
+ context_(ctx) {}
- template <typename Id>
- FMT_CONSTEXPR void on_dynamic_width(Id arg_id) {
- set_dynamic_spec<width_checker>(
- this->specs_.width_, get_arg(arg_id), context_.error_handler());
+ template <typename Id> FMT_CONSTEXPR void on_dynamic_width(Id arg_id) {
+ set_dynamic_spec<width_checker>(this->specs_.width, get_arg(arg_id),
+ context_.error_handler());
}
- template <typename Id>
- FMT_CONSTEXPR void on_dynamic_precision(Id arg_id) {
- set_dynamic_spec<precision_checker>(
- this->specs_.precision, get_arg(arg_id), context_.error_handler());
+ template <typename Id> FMT_CONSTEXPR void on_dynamic_precision(Id arg_id) {
+ set_dynamic_spec<precision_checker>(this->specs_.precision, get_arg(arg_id),
+ context_.error_handler());
}
- void on_error(const char *message) {
- context_.on_error(message);
- }
+ void on_error(const char* message) { context_.on_error(message); }
private:
- FMT_CONSTEXPR basic_format_arg<Context> get_arg(auto_id) {
- return context_.next_arg();
+ // This is only needed for compatibility with gcc 4.4.
+ using format_arg = typename Context::format_arg;
+
+ FMT_CONSTEXPR format_arg get_arg(auto_id) {
+ return internal::get_arg(context_, parse_context_.next_arg_id());
}
- template <typename Id>
- FMT_CONSTEXPR basic_format_arg<Context> get_arg(Id arg_id) {
- context_.parse_context().check_arg_id(arg_id);
- return context_.get_arg(arg_id);
+ FMT_CONSTEXPR format_arg get_arg(int arg_id) {
+ parse_context_.check_arg_id(arg_id);
+ return internal::get_arg(context_, arg_id);
}
- Context &context_;
+ FMT_CONSTEXPR format_arg get_arg(basic_string_view<char_type> arg_id) {
+ parse_context_.check_arg_id(arg_id);
+ return context_.arg(arg_id);
+ }
+
+ ParseContext& parse_context_;
+ Context& context_;
};
-// An argument reference.
-template <typename Char>
-struct arg_ref {
- enum Kind { NONE, INDEX, NAME };
-
- FMT_CONSTEXPR arg_ref() : kind(NONE), index(0) {}
- FMT_CONSTEXPR explicit arg_ref(unsigned index) : kind(INDEX), index(index) {}
- explicit arg_ref(basic_string_view<Char> nm) : kind(NAME) {
- name = {nm.data(), nm.size()};
+struct string_view_metadata {
+ FMT_CONSTEXPR string_view_metadata() : offset_(0u), size_(0u) {}
+ template <typename Char>
+ FMT_CONSTEXPR string_view_metadata(basic_string_view<Char> primary_string,
+ basic_string_view<Char> view)
+ : offset_(to_unsigned(view.data() - primary_string.data())),
+ size_(view.size()) {}
+ FMT_CONSTEXPR string_view_metadata(std::size_t offset, std::size_t size)
+ : offset_(offset), size_(size) {}
+ template <typename Char>
+ FMT_CONSTEXPR basic_string_view<Char> to_view(const Char* str) const {
+ return {str + offset_, size_};
}
- FMT_CONSTEXPR arg_ref &operator=(unsigned idx) {
- kind = INDEX;
- index = idx;
+ std::size_t offset_;
+ std::size_t size_;
+};
+
+enum class arg_id_kind { none, index, name };
+
+// An argument reference.
+template <typename Char> struct arg_ref {
+ FMT_CONSTEXPR arg_ref() : kind(arg_id_kind::none), val() {}
+ FMT_CONSTEXPR explicit arg_ref(int index)
+ : kind(arg_id_kind::index), val(index) {}
+ FMT_CONSTEXPR explicit arg_ref(string_view_metadata name)
+ : kind(arg_id_kind::name), val(name) {}
+
+ FMT_CONSTEXPR arg_ref& operator=(int idx) {
+ kind = arg_id_kind::index;
+ val.index = idx;
return *this;
}
- Kind kind;
- union {
- unsigned index;
- string_value<Char> name; // This is not string_view because of gcc 4.4.
- };
+ arg_id_kind kind;
+ union value {
+ FMT_CONSTEXPR value() : index(0u) {}
+ FMT_CONSTEXPR value(int id) : index(id) {}
+ FMT_CONSTEXPR value(string_view_metadata n) : name(n) {}
+
+ int index;
+ string_view_metadata name;
+ } val;
};
// Format specifiers with width and precision resolved at formatting rather
// than parsing time to allow re-using the same parsed specifiers with
-// differents sets of arguments (precompilation of format strings).
+// different sets of arguments (precompilation of format strings).
template <typename Char>
struct dynamic_format_specs : basic_format_specs<Char> {
arg_ref<Char> width_ref;
@@ -1738,38 +2171,36 @@
// Format spec handler that saves references to arguments representing dynamic
// width and precision to be resolved at formatting time.
template <typename ParseContext>
-class dynamic_specs_handler :
- public specs_setter<typename ParseContext::char_type> {
+class dynamic_specs_handler
+ : public specs_setter<typename ParseContext::char_type> {
public:
- typedef typename ParseContext::char_type char_type;
+ using char_type = typename ParseContext::char_type;
- FMT_CONSTEXPR dynamic_specs_handler(
- dynamic_format_specs<char_type> &specs, ParseContext &ctx)
- : specs_setter<char_type>(specs), specs_(specs), context_(ctx) {}
+ FMT_CONSTEXPR dynamic_specs_handler(dynamic_format_specs<char_type>& specs,
+ ParseContext& ctx)
+ : specs_setter<char_type>(specs), specs_(specs), context_(ctx) {}
- FMT_CONSTEXPR dynamic_specs_handler(const dynamic_specs_handler &other)
- : specs_setter<char_type>(other),
- specs_(other.specs_), context_(other.context_) {}
+ FMT_CONSTEXPR dynamic_specs_handler(const dynamic_specs_handler& other)
+ : specs_setter<char_type>(other),
+ specs_(other.specs_),
+ context_(other.context_) {}
- template <typename Id>
- FMT_CONSTEXPR void on_dynamic_width(Id arg_id) {
+ template <typename Id> FMT_CONSTEXPR void on_dynamic_width(Id arg_id) {
specs_.width_ref = make_arg_ref(arg_id);
}
- template <typename Id>
- FMT_CONSTEXPR void on_dynamic_precision(Id arg_id) {
+ template <typename Id> FMT_CONSTEXPR void on_dynamic_precision(Id arg_id) {
specs_.precision_ref = make_arg_ref(arg_id);
}
- FMT_CONSTEXPR void on_error(const char *message) {
+ FMT_CONSTEXPR void on_error(const char* message) {
context_.on_error(message);
}
private:
- typedef arg_ref<char_type> arg_ref_type;
+ using arg_ref_type = arg_ref<char_type>;
- template <typename Id>
- FMT_CONSTEXPR arg_ref_type make_arg_ref(Id arg_id) {
+ FMT_CONSTEXPR arg_ref_type make_arg_ref(int arg_id) {
context_.check_arg_id(arg_id);
return arg_ref_type(arg_id);
}
@@ -1778,19 +2209,26 @@
return arg_ref_type(context_.next_arg_id());
}
- dynamic_format_specs<char_type> &specs_;
- ParseContext &context_;
+ FMT_CONSTEXPR arg_ref_type make_arg_ref(basic_string_view<char_type> arg_id) {
+ context_.check_arg_id(arg_id);
+ basic_string_view<char_type> format_str(
+ context_.begin(), to_unsigned(context_.end() - context_.begin()));
+ const auto id_metadata = string_view_metadata(format_str, arg_id);
+ return arg_ref_type(id_metadata);
+ }
+
+ dynamic_format_specs<char_type>& specs_;
+ ParseContext& context_;
};
template <typename Char, typename IDHandler>
-FMT_CONSTEXPR const Char *parse_arg_id(
- const Char *begin, const Char *end, IDHandler &&handler) {
+FMT_CONSTEXPR const Char* parse_arg_id(const Char* begin, const Char* end,
+ IDHandler&& handler) {
assert(begin != end);
Char c = *begin;
- if (c == '}' || c == ':')
- return handler(), begin;
+ if (c == '}' || c == ':') return handler(), begin;
if (c >= '0' && c <= '9') {
- unsigned index = parse_nonnegative_int(begin, end, handler);
+ int index = parse_nonnegative_int(begin, end, handler);
if (begin == end || (*begin != '}' && *begin != ':'))
return handler.on_error("invalid format string"), begin;
handler(index);
@@ -1807,72 +2245,71 @@
}
// Adapts SpecHandler to IDHandler API for dynamic width.
-template <typename SpecHandler, typename Char>
-struct width_adapter {
- explicit FMT_CONSTEXPR width_adapter(SpecHandler &h) : handler(h) {}
+template <typename SpecHandler, typename Char> struct width_adapter {
+ explicit FMT_CONSTEXPR width_adapter(SpecHandler& h) : handler(h) {}
FMT_CONSTEXPR void operator()() { handler.on_dynamic_width(auto_id()); }
- FMT_CONSTEXPR void operator()(unsigned id) { handler.on_dynamic_width(id); }
+ FMT_CONSTEXPR void operator()(int id) { handler.on_dynamic_width(id); }
FMT_CONSTEXPR void operator()(basic_string_view<Char> id) {
handler.on_dynamic_width(id);
}
- FMT_CONSTEXPR void on_error(const char *message) {
+ FMT_CONSTEXPR void on_error(const char* message) {
handler.on_error(message);
}
- SpecHandler &handler;
+ SpecHandler& handler;
};
// Adapts SpecHandler to IDHandler API for dynamic precision.
-template <typename SpecHandler, typename Char>
-struct precision_adapter {
- explicit FMT_CONSTEXPR precision_adapter(SpecHandler &h) : handler(h) {}
+template <typename SpecHandler, typename Char> struct precision_adapter {
+ explicit FMT_CONSTEXPR precision_adapter(SpecHandler& h) : handler(h) {}
FMT_CONSTEXPR void operator()() { handler.on_dynamic_precision(auto_id()); }
- FMT_CONSTEXPR void operator()(unsigned id) {
- handler.on_dynamic_precision(id);
- }
+ FMT_CONSTEXPR void operator()(int id) { handler.on_dynamic_precision(id); }
FMT_CONSTEXPR void operator()(basic_string_view<Char> id) {
handler.on_dynamic_precision(id);
}
- FMT_CONSTEXPR void on_error(const char *message) { handler.on_error(message); }
+ FMT_CONSTEXPR void on_error(const char* message) {
+ handler.on_error(message);
+ }
- SpecHandler &handler;
+ SpecHandler& handler;
};
// Parses fill and alignment.
template <typename Char, typename Handler>
-FMT_CONSTEXPR const Char *parse_align(
- const Char *begin, const Char *end, Handler &&handler) {
+FMT_CONSTEXPR const Char* parse_align(const Char* begin, const Char* end,
+ Handler&& handler) {
FMT_ASSERT(begin != end, "");
- alignment align = ALIGN_DEFAULT;
+ auto align = align::none;
int i = 0;
if (begin + 1 != end) ++i;
do {
switch (static_cast<char>(begin[i])) {
case '<':
- align = ALIGN_LEFT;
+ align = align::left;
break;
case '>':
- align = ALIGN_RIGHT;
+ align = align::right;
break;
case '=':
- align = ALIGN_NUMERIC;
+ align = align::numeric;
break;
case '^':
- align = ALIGN_CENTER;
+ align = align::center;
break;
}
- if (align != ALIGN_DEFAULT) {
+ if (align != align::none) {
if (i > 0) {
auto c = *begin;
if (c == '{')
return handler.on_error("invalid fill character '{'"), begin;
begin += 2;
handler.on_fill(c);
- } else ++begin;
+ } else
+ ++begin;
handler.on_align(align);
break;
}
@@ -1881,8 +2318,8 @@
}
template <typename Char, typename Handler>
-FMT_CONSTEXPR const Char *parse_width(
- const Char *begin, const Char *end, Handler &&handler) {
+FMT_CONSTEXPR const Char* parse_width(const Char* begin, const Char* end,
+ Handler&& handler) {
FMT_ASSERT(begin != end, "");
if ('0' <= *begin && *begin <= '9') {
handler.on_width(parse_nonnegative_int(begin, end, handler));
@@ -1897,13 +2334,34 @@
return begin;
}
+template <typename Char, typename Handler>
+FMT_CONSTEXPR const Char* parse_precision(const Char* begin, const Char* end,
+ Handler&& handler) {
+ ++begin;
+ auto c = begin != end ? *begin : Char();
+ if ('0' <= c && c <= '9') {
+ handler.on_precision(parse_nonnegative_int(begin, end, handler));
+ } else if (c == '{') {
+ ++begin;
+ if (begin != end) {
+ begin =
+ parse_arg_id(begin, end, precision_adapter<Handler, Char>(handler));
+ }
+ if (begin == end || *begin++ != '}')
+ return handler.on_error("invalid format string"), begin;
+ } else {
+ return handler.on_error("missing precision specifier"), begin;
+ }
+ handler.end_precision();
+ return begin;
+}
+
// Parses standard format specifiers and sends notifications about parsed
// components to handler.
template <typename Char, typename SpecHandler>
-FMT_CONSTEXPR const Char *parse_format_specs(
- const Char *begin, const Char *end, SpecHandler &&handler) {
- if (begin == end || *begin == '}')
- return begin;
+FMT_CONSTEXPR const Char* parse_format_specs(const Char* begin, const Char* end,
+ SpecHandler&& handler) {
+ if (begin == end || *begin == '}') return begin;
begin = parse_align(begin, end, handler);
if (begin == end) return begin;
@@ -1941,68 +2399,51 @@
// Parse precision.
if (*begin == '.') {
- ++begin;
- auto c = begin != end ? *begin : 0;
- if ('0' <= c && c <= '9') {
- handler.on_precision(parse_nonnegative_int(begin, end, handler));
- } else if (c == '{') {
- ++begin;
- if (begin != end) {
- begin = parse_arg_id(
- begin, end, precision_adapter<SpecHandler, Char>(handler));
- }
- if (begin == end || *begin++ != '}')
- return handler.on_error("invalid format string"), begin;
- } else {
- return handler.on_error("missing precision specifier"), begin;
- }
- handler.end_precision();
+ begin = parse_precision(begin, end, handler);
}
// Parse type.
- if (begin != end && *begin != '}')
- handler.on_type(*begin++);
+ if (begin != end && *begin != '}') handler.on_type(*begin++);
return begin;
}
// Return the result via the out param to workaround gcc bug 77539.
template <bool IS_CONSTEXPR, typename T, typename Ptr = const T*>
-FMT_CONSTEXPR bool find(Ptr first, Ptr last, T value, Ptr &out) {
+FMT_CONSTEXPR bool find(Ptr first, Ptr last, T value, Ptr& out) {
for (out = first; out != last; ++out) {
- if (*out == value)
- return true;
+ if (*out == value) return true;
}
return false;
}
template <>
-inline bool find<false, char>(
- const char *first, const char *last, char value, const char *&out) {
- out = static_cast<const char*>(std::memchr(first, value, internal::to_unsigned(last - first)));
- return out != FMT_NULL;
+inline bool find<false, char>(const char* first, const char* last, char value,
+ const char*& out) {
+ out = static_cast<const char*>(
+ std::memchr(first, value, internal::to_unsigned(last - first)));
+ return out != nullptr;
}
-template <typename Handler, typename Char>
-struct id_adapter {
+template <typename Handler, typename Char> struct id_adapter {
FMT_CONSTEXPR void operator()() { handler.on_arg_id(); }
- FMT_CONSTEXPR void operator()(unsigned id) { handler.on_arg_id(id); }
+ FMT_CONSTEXPR void operator()(int id) { handler.on_arg_id(id); }
FMT_CONSTEXPR void operator()(basic_string_view<Char> id) {
handler.on_arg_id(id);
}
- FMT_CONSTEXPR void on_error(const char *message) {
+ FMT_CONSTEXPR void on_error(const char* message) {
handler.on_error(message);
}
- Handler &handler;
+ Handler& handler;
};
template <bool IS_CONSTEXPR, typename Char, typename Handler>
-FMT_CONSTEXPR void parse_format_string(
- basic_string_view<Char> format_str, Handler &&handler) {
+FMT_CONSTEXPR void parse_format_string(basic_string_view<Char> format_str,
+ Handler&& handler) {
struct writer {
- FMT_CONSTEXPR void operator()(const Char *begin, const Char *end) {
+ FMT_CONSTEXPR void operator()(const Char* begin, const Char* end) {
if (begin == end) return;
for (;;) {
- const Char *p = FMT_NULL;
+ const Char* p = nullptr;
if (!find<IS_CONSTEXPR>(begin, end, '}', p))
return handler_.on_text(begin, end);
++p;
@@ -2012,20 +2453,19 @@
begin = p + 1;
}
}
- Handler &handler_;
+ Handler& handler_;
} write{handler};
auto begin = format_str.data();
auto end = begin + format_str.size();
while (begin != end) {
// Doing two passes with memchr (one for '{' and another for '}') is up to
// 2.5x faster than the naive one-pass implementation on big format strings.
- const Char *p = begin;
+ const Char* p = begin;
if (*begin != '{' && !find<IS_CONSTEXPR>(begin, end, '{', p))
return write(begin, end);
write(begin, p);
++p;
- if (p == end)
- return handler.on_error("invalid format string");
+ if (p == end) return handler.on_error("invalid format string");
if (static_cast<char>(*p) == '}') {
handler.on_arg_id();
handler.on_replacement_field(p);
@@ -2049,10 +2489,18 @@
}
template <typename T, typename ParseContext>
-FMT_CONSTEXPR const typename ParseContext::char_type *
- parse_format_specs(ParseContext &ctx) {
- // GCC 7.2 requires initializer.
- formatter<T, typename ParseContext::char_type> f{};
+FMT_CONSTEXPR const typename ParseContext::char_type* parse_format_specs(
+ ParseContext& ctx) {
+ using char_type = typename ParseContext::char_type;
+ using context = buffer_context<char_type>;
+ using mapped_type =
+ conditional_t<internal::mapped_type_constant<T, context>::value !=
+ internal::custom_type,
+ decltype(arg_mapper<context>().map(std::declval<T>())), T>;
+ conditional_t<has_formatter<mapped_type, context>::value,
+ formatter<mapped_type, char_type>,
+ internal::fallback_formatter<T, char_type>>
+ f;
return f.parse(ctx);
}
@@ -2061,132 +2509,132 @@
public:
explicit FMT_CONSTEXPR format_string_checker(
basic_string_view<Char> format_str, ErrorHandler eh)
- : arg_id_((std::numeric_limits<unsigned>::max)()), context_(format_str, eh),
- parse_funcs_{&parse_format_specs<Args, parse_context_type>...} {}
+ : arg_id_((std::numeric_limits<unsigned>::max)()),
+ context_(format_str, eh),
+ parse_funcs_{&parse_format_specs<Args, parse_context_type>...} {}
- FMT_CONSTEXPR void on_text(const Char *, const Char *) {}
+ FMT_CONSTEXPR void on_text(const Char*, const Char*) {}
FMT_CONSTEXPR void on_arg_id() {
arg_id_ = context_.next_arg_id();
check_arg_id();
}
- FMT_CONSTEXPR void on_arg_id(unsigned id) {
+ FMT_CONSTEXPR void on_arg_id(int id) {
arg_id_ = id;
context_.check_arg_id(id);
check_arg_id();
}
- FMT_CONSTEXPR void on_arg_id(basic_string_view<Char>) {}
-
- FMT_CONSTEXPR void on_replacement_field(const Char *) {}
-
- FMT_CONSTEXPR const Char *on_format_specs(const Char *begin, const Char *) {
- context_.advance_to(begin);
- return arg_id_ < NUM_ARGS ?
- parse_funcs_[arg_id_](context_) : begin;
+ FMT_CONSTEXPR void on_arg_id(basic_string_view<Char>) {
+ on_error("compile-time checks don't support named arguments");
}
- FMT_CONSTEXPR void on_error(const char *message) {
+ FMT_CONSTEXPR void on_replacement_field(const Char*) {}
+
+ FMT_CONSTEXPR const Char* on_format_specs(const Char* begin, const Char*) {
+ advance_to(context_, begin);
+ return arg_id_ < num_args ? parse_funcs_[arg_id_](context_) : begin;
+ }
+
+ FMT_CONSTEXPR void on_error(const char* message) {
context_.on_error(message);
}
private:
- typedef basic_parse_context<Char, ErrorHandler> parse_context_type;
- enum { NUM_ARGS = sizeof...(Args) };
+ using parse_context_type = basic_parse_context<Char, ErrorHandler>;
+ enum { num_args = sizeof...(Args) };
FMT_CONSTEXPR void check_arg_id() {
- if (arg_id_ >= NUM_ARGS)
- context_.on_error("argument index out of range");
+ if (arg_id_ >= num_args) context_.on_error("argument index out of range");
}
// Format specifier parsing function.
- typedef const Char *(*parse_func)(parse_context_type &);
+ using parse_func = const Char* (*)(parse_context_type&);
unsigned arg_id_;
parse_context_type context_;
- parse_func parse_funcs_[NUM_ARGS > 0 ? NUM_ARGS : 1];
+ parse_func parse_funcs_[num_args > 0 ? num_args : 1];
};
template <typename Char, typename ErrorHandler, typename... Args>
-FMT_CONSTEXPR bool do_check_format_string(
- basic_string_view<Char> s, ErrorHandler eh = ErrorHandler()) {
+FMT_CONSTEXPR bool do_check_format_string(basic_string_view<Char> s,
+ ErrorHandler eh = ErrorHandler()) {
format_string_checker<Char, ErrorHandler, Args...> checker(s, eh);
parse_format_string<true>(s, checker);
return true;
}
-template <typename... Args, typename S>
-typename std::enable_if<is_compile_string<S>::value>::type
- check_format_string(S format_str) {
- typedef typename S::char_type char_t;
- FMT_CONSTEXPR_DECL bool invalid_format = internal::do_check_format_string<
- char_t, internal::error_handler, Args...>(to_string_view(format_str));
+template <typename... Args, typename S,
+ enable_if_t<(is_compile_string<S>::value), int>>
+void check_format_string(S format_str) {
+ FMT_CONSTEXPR_DECL bool invalid_format =
+ internal::do_check_format_string<typename S::char_type,
+ internal::error_handler, Args...>(
+ to_string_view(format_str));
(void)invalid_format;
}
-// Specifies whether to format T using the standard formatter.
-// It is not possible to use get_type in formatter specialization directly
-// because of a bug in MSVC.
-template <typename Context, typename T>
-struct format_type :
- std::integral_constant<bool, get_type<Context, T>::value != custom_type> {};
-
template <template <typename> class Handler, typename Spec, typename Context>
-void handle_dynamic_spec(
- Spec &value, arg_ref<typename Context::char_type> ref, Context &ctx) {
- typedef typename Context::char_type char_type;
+void handle_dynamic_spec(Spec& value, arg_ref<typename Context::char_type> ref,
+ Context& ctx,
+ const typename Context::char_type* format_str) {
switch (ref.kind) {
- case arg_ref<char_type>::NONE:
+ case arg_id_kind::none:
break;
- case arg_ref<char_type>::INDEX:
- internal::set_dynamic_spec<Handler>(
- value, ctx.get_arg(ref.index), ctx.error_handler());
+ case arg_id_kind::index:
+ internal::set_dynamic_spec<Handler>(value, ctx.arg(ref.val.index),
+ ctx.error_handler());
break;
- case arg_ref<char_type>::NAME:
- internal::set_dynamic_spec<Handler>(
- value, ctx.get_arg({ref.name.value, ref.name.size}),
- ctx.error_handler());
+ case arg_id_kind::name: {
+ const auto arg_id = ref.val.name.to_view(format_str);
+ internal::set_dynamic_spec<Handler>(value, ctx.arg(arg_id),
+ ctx.error_handler());
break;
}
+ }
}
} // namespace internal
+template <typename Range>
+using basic_writer FMT_DEPRECATED = internal::basic_writer<Range>;
+using writer FMT_DEPRECATED = internal::writer;
+using wwriter FMT_DEPRECATED =
+ internal::basic_writer<internal::buffer_range<wchar_t>>;
+
/** The default argument formatter. */
template <typename Range>
-class arg_formatter:
- public internal::function<
- typename internal::arg_formatter_base<Range>::iterator>,
- public internal::arg_formatter_base<Range> {
+class arg_formatter : public internal::arg_formatter_base<Range> {
private:
- typedef typename Range::value_type char_type;
- typedef internal::arg_formatter_base<Range> base;
- typedef basic_format_context<typename base::iterator, char_type> context_type;
+ using char_type = typename Range::value_type;
+ using base = internal::arg_formatter_base<Range>;
+ using context_type = basic_format_context<typename base::iterator, char_type>;
- context_type &ctx_;
+ context_type& ctx_;
+ basic_parse_context<char_type>* parse_ctx_;
public:
- typedef Range range;
- typedef typename base::iterator iterator;
- typedef typename base::format_specs format_specs;
+ using range = Range;
+ using iterator = typename base::iterator;
+ using format_specs = typename base::format_specs;
/**
\rst
Constructs an argument formatter object.
*ctx* is a reference to the formatting context,
- *spec* contains format specifier information for standard argument types.
+ *specs* contains format specifier information for standard argument types.
\endrst
*/
- explicit arg_formatter(context_type &ctx, format_specs *spec = FMT_NULL)
- : base(Range(ctx.out()), spec, ctx.locale()), ctx_(ctx) {}
-
- // Deprecated.
- arg_formatter(context_type &ctx, format_specs &spec)
- : base(Range(ctx.out()), &spec), ctx_(ctx) {}
+ explicit arg_formatter(context_type& ctx,
+ basic_parse_context<char_type>* parse_ctx = nullptr,
+ format_specs* specs = nullptr)
+ : base(Range(ctx.out()), specs, ctx.locale()),
+ ctx_(ctx),
+ parse_ctx_(parse_ctx) {}
using base::operator();
/** Formats an argument of a user-defined type. */
iterator operator()(typename basic_format_arg<context_type>::handle handle) {
- handle.format(ctx_);
+ handle.format(*parse_ctx_, ctx_);
return this->out();
}
};
@@ -2195,14 +2643,14 @@
An error returned by an operating system or a language runtime,
for example a file opening error.
*/
-class system_error : public std::runtime_error {
+class FMT_API system_error : public std::runtime_error {
private:
- FMT_API void init(int err_code, string_view format_str, format_args args);
+ void init(int err_code, string_view format_str, format_args args);
protected:
int error_code_;
- system_error() : std::runtime_error("") {}
+ system_error() : std::runtime_error(""), error_code_(0) {}
public:
/**
@@ -2224,10 +2672,11 @@
\endrst
*/
template <typename... Args>
- system_error(int error_code, string_view message, const Args &... args)
- : std::runtime_error("") {
+ system_error(int error_code, string_view message, const Args&... args)
+ : std::runtime_error("") {
init(error_code, message, make_format_args(args...));
}
+ ~system_error() FMT_NOEXCEPT;
int error_code() const { return error_code_; }
};
@@ -2248,511 +2697,126 @@
may look like "Unknown error -1" and is platform-dependent.
\endrst
*/
-FMT_API void format_system_error(internal::buffer &out, int error_code,
+FMT_API void format_system_error(internal::buffer<char>& out, int error_code,
fmt::string_view message) FMT_NOEXCEPT;
-/**
- This template provides operations for formatting and writing data into a
- character range.
- */
-template <typename Range>
-class basic_writer {
- public:
- typedef typename Range::value_type char_type;
- typedef decltype(internal::declval<Range>().begin()) iterator;
- typedef basic_format_specs<char_type> format_specs;
-
- private:
- iterator out_; // Output iterator.
- internal::locale_ref locale_;
-
- // Attempts to reserve space for n extra characters in the output range.
- // Returns a pointer to the reserved range or a reference to out_.
- auto reserve(std::size_t n) -> decltype(internal::reserve(out_, n)) {
- return internal::reserve(out_, n);
- }
-
- // Writes a value in the format
- // <left-padding><value><right-padding>
- // where <value> is written by f(it).
- template <typename F>
- void write_padded(const align_spec &spec, F &&f) {
- unsigned width = spec.width(); // User-perceived width (in code points).
- size_t size = f.size(); // The number of code units.
- size_t num_code_points = width != 0 ? f.width() : size;
- if (width <= num_code_points)
- return f(reserve(size));
- auto &&it = reserve(width + (size - num_code_points));
- char_type fill = static_cast<char_type>(spec.fill());
- std::size_t padding = width - num_code_points;
- if (spec.align() == ALIGN_RIGHT) {
- it = std::fill_n(it, padding, fill);
- f(it);
- } else if (spec.align() == ALIGN_CENTER) {
- std::size_t left_padding = padding / 2;
- it = std::fill_n(it, left_padding, fill);
- f(it);
- it = std::fill_n(it, padding - left_padding, fill);
- } else {
- f(it);
- it = std::fill_n(it, padding, fill);
- }
- }
-
- template <typename F>
- struct padded_int_writer {
- size_t size_;
- string_view prefix;
- char_type fill;
- std::size_t padding;
- F f;
-
- size_t size() const { return size_; }
- size_t width() const { return size_; }
-
- template <typename It>
- void operator()(It &&it) const {
- if (prefix.size() != 0)
- it = internal::copy_str<char_type>(prefix.begin(), prefix.end(), it);
- it = std::fill_n(it, padding, fill);
- f(it);
- }
- };
-
- // Writes an integer in the format
- // <left-padding><prefix><numeric-padding><digits><right-padding>
- // where <digits> are written by f(it).
- template <typename Spec, typename F>
- void write_int(int num_digits, string_view prefix,
- const Spec &spec, F f) {
- std::size_t size = prefix.size() + internal::to_unsigned(num_digits);
- char_type fill = static_cast<char_type>(spec.fill());
- std::size_t padding = 0;
- if (spec.align() == ALIGN_NUMERIC) {
- if (spec.width() > size) {
- padding = spec.width() - size;
- size = spec.width();
- }
- } else if (spec.precision > num_digits) {
- size = prefix.size() + internal::to_unsigned(spec.precision);
- padding = internal::to_unsigned(spec.precision - num_digits);
- fill = static_cast<char_type>('0');
- }
- align_spec as = spec;
- if (spec.align() == ALIGN_DEFAULT)
- as.align_ = ALIGN_RIGHT;
- write_padded(as, padded_int_writer<F>{size, prefix, fill, padding, f});
- }
-
- // Writes a decimal integer.
- template <typename Int>
- void write_decimal(Int value) {
- typedef typename internal::int_traits<Int>::main_type main_type;
- main_type abs_value = static_cast<main_type>(value);
- bool is_negative = internal::is_negative(value);
- if (is_negative)
- abs_value = 0 - abs_value;
- int num_digits = internal::count_digits(abs_value);
- auto &&it = reserve((is_negative ? 1 : 0) + static_cast<size_t>(num_digits));
- if (is_negative)
- *it++ = static_cast<char_type>('-');
- it = internal::format_decimal<char_type>(it, abs_value, num_digits);
- }
-
- // The handle_int_type_spec handler that writes an integer.
- template <typename Int, typename Spec>
- struct int_writer {
- typedef typename internal::int_traits<Int>::main_type unsigned_type;
-
- basic_writer<Range> &writer;
- const Spec &spec;
- unsigned_type abs_value;
- char prefix[4];
- unsigned prefix_size;
-
- string_view get_prefix() const { return string_view(prefix, prefix_size); }
-
- // Counts the number of digits in abs_value. BITS = log2(radix).
- template <unsigned BITS>
- int count_digits() const {
- unsigned_type n = abs_value;
- int num_digits = 0;
- do {
- ++num_digits;
- } while ((n >>= BITS) != 0);
- return num_digits;
- }
-
- int_writer(basic_writer<Range> &w, Int value, const Spec &s)
- : writer(w), spec(s), abs_value(static_cast<unsigned_type>(value)),
- prefix_size(0) {
- if (internal::is_negative(value)) {
- prefix[0] = '-';
- ++prefix_size;
- abs_value = 0 - abs_value;
- } else if (spec.has(SIGN_FLAG)) {
- prefix[0] = spec.has(PLUS_FLAG) ? '+' : ' ';
- ++prefix_size;
- }
- }
-
- struct dec_writer {
- unsigned_type abs_value;
- int num_digits;
-
- template <typename It>
- void operator()(It &&it) const {
- it = internal::format_decimal<char_type>(it, abs_value, num_digits);
- }
- };
-
- void on_dec() {
- int num_digits = internal::count_digits(abs_value);
- writer.write_int(num_digits, get_prefix(), spec,
- dec_writer{abs_value, num_digits});
- }
-
- struct hex_writer {
- int_writer &self;
- int num_digits;
-
- template <typename It>
- void operator()(It &&it) const {
- it = internal::format_uint<4, char_type>(
- it, self.abs_value, num_digits, self.spec.type != 'x');
- }
- };
-
- void on_hex() {
- if (spec.has(HASH_FLAG)) {
- prefix[prefix_size++] = '0';
- prefix[prefix_size++] = static_cast<char>(spec.type);
- }
- int num_digits = count_digits<4>();
- writer.write_int(num_digits, get_prefix(), spec,
- hex_writer{*this, num_digits});
- }
-
- template <int BITS>
- struct bin_writer {
- unsigned_type abs_value;
- int num_digits;
-
- template <typename It>
- void operator()(It &&it) const {
- it = internal::format_uint<BITS, char_type>(it, abs_value, num_digits);
- }
- };
-
- void on_bin() {
- if (spec.has(HASH_FLAG)) {
- prefix[prefix_size++] = '0';
- prefix[prefix_size++] = static_cast<char>(spec.type);
- }
- int num_digits = count_digits<1>();
- writer.write_int(num_digits, get_prefix(), spec,
- bin_writer<1>{abs_value, num_digits});
- }
-
- void on_oct() {
- int num_digits = count_digits<3>();
- if (spec.has(HASH_FLAG) &&
- spec.precision <= num_digits) {
- // Octal prefix '0' is counted as a digit, so only add it if precision
- // is not greater than the number of digits.
- prefix[prefix_size++] = '0';
- }
- writer.write_int(num_digits, get_prefix(), spec,
- bin_writer<3>{abs_value, num_digits});
- }
-
- enum { SEP_SIZE = 1 };
-
- struct num_writer {
- unsigned_type abs_value;
- int size;
- char_type sep;
-
- template <typename It>
- void operator()(It &&it) const {
- basic_string_view<char_type> s(&sep, SEP_SIZE);
- it = internal::format_decimal<char_type>(
- it, abs_value, size, internal::add_thousands_sep<char_type>(s));
- }
- };
-
- void on_num() {
- int num_digits = internal::count_digits(abs_value);
- char_type sep = internal::thousands_sep<char_type>(writer.locale_);
- int size = num_digits + SEP_SIZE * ((num_digits - 1) / 3);
- writer.write_int(size, get_prefix(), spec,
- num_writer{abs_value, size, sep});
- }
-
- void on_error() {
- FMT_THROW(format_error("invalid type specifier"));
- }
- };
-
- // Writes a formatted integer.
- template <typename T, typename Spec>
- void write_int(T value, const Spec &spec) {
- internal::handle_int_type_spec(spec.type,
- int_writer<T, Spec>(*this, value, spec));
- }
-
- enum {INF_SIZE = 3}; // This is an enum to workaround a bug in MSVC.
-
- struct inf_or_nan_writer {
- char sign;
- const char *str;
-
- size_t size() const {
- return static_cast<std::size_t>(INF_SIZE + (sign ? 1 : 0));
- }
- size_t width() const { return size(); }
-
- template <typename It>
- void operator()(It &&it) const {
- if (sign)
- *it++ = static_cast<char_type>(sign);
- it = internal::copy_str<char_type>(
- str, str + static_cast<std::size_t>(INF_SIZE), it);
- }
- };
-
- struct double_writer {
- size_t n;
- char sign;
- internal::buffer &buffer;
-
- size_t size() const { return buffer.size() + (sign ? 1 : 0); }
- size_t width() const { return size(); }
-
- template <typename It>
- void operator()(It &&it) {
- if (sign) {
- *it++ = static_cast<char_type>(sign);
- --n;
- }
- it = internal::copy_str<char_type>(buffer.begin(), buffer.end(), it);
- }
- };
-
- // Formats a floating-point number (double or long double).
- template <typename T>
- void write_double(T value, const format_specs &spec);
-
- template <typename Char>
- struct str_writer {
- const Char *s;
- size_t size_;
-
- size_t size() const { return size_; }
- size_t width() const {
- return internal::count_code_points(basic_string_view<Char>(s, size_));
- }
-
- template <typename It>
- void operator()(It &&it) const {
- it = internal::copy_str<char_type>(s, s + size_, it);
- }
- };
-
- template <typename Char>
- friend class internal::arg_formatter_base;
-
- public:
- /** Constructs a ``basic_writer`` object. */
- explicit basic_writer(
- Range out, internal::locale_ref loc = internal::locale_ref())
- : out_(out.begin()), locale_(loc) {}
-
- iterator out() const { return out_; }
-
- void write(int value) { write_decimal(value); }
- void write(long value) { write_decimal(value); }
- void write(long long value) { write_decimal(value); }
-
- void write(unsigned value) { write_decimal(value); }
- void write(unsigned long value) { write_decimal(value); }
- void write(unsigned long long value) { write_decimal(value); }
-
- /**
- \rst
- Formats *value* and writes it to the buffer.
- \endrst
- */
- template <typename T, typename FormatSpec, typename... FormatSpecs>
- typename std::enable_if<std::is_integral<T>::value, void>::type
- write(T value, FormatSpec spec, FormatSpecs... specs) {
- format_specs s(spec, specs...);
- s.align_ = ALIGN_RIGHT;
- write_int(value, s);
- }
-
- void write(double value) {
- write_double(value, format_specs());
- }
-
- /**
- \rst
- Formats *value* using the general format for floating-point numbers
- (``'g'``) and writes it to the buffer.
- \endrst
- */
- void write(long double value) {
- write_double(value, format_specs());
- }
-
- /** Writes a character to the buffer. */
- void write(char value) {
- *reserve(1) = value;
- }
- void write(wchar_t value) {
- static_assert(std::is_same<char_type, wchar_t>::value, "");
- *reserve(1) = value;
- }
-
- /**
- \rst
- Writes *value* to the buffer.
- \endrst
- */
- void write(string_view value) {
- auto &&it = reserve(value.size());
- it = internal::copy_str<char_type>(value.begin(), value.end(), it);
- }
- void write(wstring_view value) {
- static_assert(std::is_same<char_type, wchar_t>::value, "");
- auto &&it = reserve(value.size());
- it = std::copy(value.begin(), value.end(), it);
- }
-
- // Writes a formatted string.
- template <typename Char>
- void write(const Char *s, std::size_t size, const align_spec &spec) {
- write_padded(spec, str_writer<Char>{s, size});
- }
-
- template <typename Char>
- void write(basic_string_view<Char> s,
- const format_specs &spec = format_specs()) {
- const Char *data = s.data();
- std::size_t size = s.size();
- if (spec.precision >= 0 && internal::to_unsigned(spec.precision) < size)
- size = internal::to_unsigned(spec.precision);
- write(data, size, spec);
- }
-
- template <typename T>
- typename std::enable_if<std::is_same<T, void>::value>::type
- write(const T *p) {
- format_specs specs;
- specs.flags = HASH_FLAG;
- specs.type = 'x';
- write_int(reinterpret_cast<uintptr_t>(p), specs);
- }
-};
-
struct float_spec_handler {
char type;
bool upper;
+ bool fixed;
+ bool as_percentage;
+ bool use_locale;
- explicit float_spec_handler(char t) : type(t), upper(false) {}
+ explicit float_spec_handler(char t)
+ : type(t),
+ upper(false),
+ fixed(false),
+ as_percentage(false),
+ use_locale(false) {}
void on_general() {
- if (type == 'G')
- upper = true;
- else
- type = 'g';
+ if (type == 'G') upper = true;
}
void on_exp() {
- if (type == 'E')
- upper = true;
+ if (type == 'E') upper = true;
}
void on_fixed() {
- if (type == 'F') {
- upper = true;
-#if FMT_MSC_VER
- // MSVC's printf doesn't support 'F'.
- type = 'f';
-#endif
- }
+ fixed = true;
+ if (type == 'F') upper = true;
+ }
+
+ void on_percent() {
+ fixed = true;
+ as_percentage = true;
}
void on_hex() {
- if (type == 'A')
- upper = true;
+ if (type == 'A') upper = true;
}
- void on_error() {
+ void on_num() { use_locale = true; }
+
+ FMT_NORETURN void on_error() {
FMT_THROW(format_error("invalid type specifier"));
}
};
template <typename Range>
-template <typename T>
-void basic_writer<Range>::write_double(T value, const format_specs &spec) {
+template <typename T, bool USE_GRISU>
+void internal::basic_writer<Range>::write_double(T value,
+ const format_specs& specs) {
// Check type.
- float_spec_handler handler(static_cast<char>(spec.type));
+ float_spec_handler handler(static_cast<char>(specs.type));
internal::handle_float_type_spec(handler.type, handler);
char sign = 0;
- // Use signbit instead of value < 0 because the latter is always
- // false for NaN.
+ // Use signbit instead of value < 0 since the latter is always false for NaN.
if (std::signbit(value)) {
sign = '-';
value = -value;
- } else if (spec.has(SIGN_FLAG)) {
- sign = spec.has(PLUS_FLAG) ? '+' : ' ';
+ } else if (specs.sign != sign::none) {
+ if (specs.sign == sign::plus)
+ sign = '+';
+ else if (specs.sign == sign::space)
+ sign = ' ';
}
- struct write_inf_or_nan_t {
- basic_writer &writer;
- format_specs spec;
- char sign;
- void operator()(const char *str) const {
- writer.write_padded(spec, inf_or_nan_writer{sign, str});
- }
- } write_inf_or_nan = {*this, spec, sign};
+ if (!std::isfinite(value)) {
+ // Format infinity and NaN ourselves because sprintf's output is not
+ // consistent across platforms.
+ const char* str = std::isinf(value) ? (handler.upper ? "INF" : "inf")
+ : (handler.upper ? "NAN" : "nan");
+ return write_padded(specs,
+ inf_or_nan_writer{sign, handler.as_percentage, str});
+ }
- // Format NaN and ininity ourselves because sprintf's output is not consistent
- // across platforms.
- if (internal::fputil::isnotanumber(value))
- return write_inf_or_nan(handler.upper ? "NAN" : "nan");
- if (internal::fputil::isinfinity(value))
- return write_inf_or_nan(handler.upper ? "INF" : "inf");
+ if (handler.as_percentage) value *= 100;
memory_buffer buffer;
- bool use_grisu = FMT_USE_GRISU && sizeof(T) <= sizeof(double) &&
- spec.type != 'a' && spec.type != 'A' &&
- internal::grisu2_format(static_cast<double>(value), buffer, spec);
- if (!use_grisu) {
- format_specs normalized_spec(spec);
- normalized_spec.type = handler.type;
- internal::sprintf_format(value, buffer, normalized_spec);
+ int exp = 0;
+ int precision = specs.precision >= 0 || !specs.type ? specs.precision : 6;
+ unsigned options = handler.fixed ? internal::grisu_options::fixed : 0;
+ bool use_grisu = USE_GRISU &&
+ (specs.type != 'a' && specs.type != 'A' &&
+ specs.type != 'e' && specs.type != 'E') &&
+ internal::grisu_format(static_cast<double>(value), buffer,
+ precision, options, exp);
+ char* decimal_point_pos = nullptr;
+ if (!use_grisu)
+ decimal_point_pos = internal::sprintf_format(value, buffer, specs);
+
+ if (handler.as_percentage) {
+ buffer.push_back('%');
+ --exp; // Adjust decimal place position.
}
- size_t n = buffer.size();
- align_spec as = spec;
- if (spec.align() == ALIGN_NUMERIC) {
+ format_specs as = specs;
+ if (specs.align == align::numeric) {
if (sign) {
- auto &&it = reserve(1);
+ auto&& it = reserve(1);
*it++ = static_cast<char_type>(sign);
sign = 0;
- if (as.width_)
- --as.width_;
+ if (as.width) --as.width;
}
- as.align_ = ALIGN_RIGHT;
- } else {
- if (spec.align() == ALIGN_DEFAULT)
- as.align_ = ALIGN_RIGHT;
- if (sign)
- ++n;
+ as.align = align::right;
+ } else if (specs.align == align::none) {
+ as.align = align::right;
}
- write_padded(as, double_writer{n, sign, buffer});
+ char_type decimal_point = handler.use_locale
+ ? internal::decimal_point<char_type>(locale_)
+ : static_cast<char_type>('.');
+ if (use_grisu) {
+ auto params = internal::gen_digits_params();
+ params.fixed = handler.fixed;
+ params.num_digits = precision;
+ params.trailing_zeros =
+ (precision != 0 && (handler.fixed || !specs.type)) || specs.alt;
+ write_padded(as, grisu_writer(sign, buffer, exp, params, decimal_point));
+ } else {
+ write_padded(as,
+ double_writer{sign, buffer, decimal_point_pos, decimal_point});
+ }
}
// Reports a system error without throwing an exception.
@@ -2797,7 +2861,7 @@
\endrst
*/
template <typename... Args>
- windows_error(int error_code, string_view message, const Args &... args) {
+ windows_error(int error_code, string_view message, const Args&... args) {
init(error_code, message, make_format_args(args...));
}
};
@@ -2814,40 +2878,38 @@
private:
// Buffer should be large enough to hold all digits (digits10 + 1),
// a sign and a null character.
- enum {BUFFER_SIZE = std::numeric_limits<unsigned long long>::digits10 + 3};
- mutable char buffer_[BUFFER_SIZE];
- char *str_;
+ enum { buffer_size = std::numeric_limits<unsigned long long>::digits10 + 3 };
+ mutable char buffer_[buffer_size];
+ char* str_;
// Formats value in reverse and returns a pointer to the beginning.
- char *format_decimal(unsigned long long value) {
- char *ptr = buffer_ + (BUFFER_SIZE - 1); // Parens to workaround MSVC bug.
+ char* format_decimal(unsigned long long value) {
+ char* ptr = buffer_ + (buffer_size - 1); // Parens to workaround MSVC bug.
while (value >= 100) {
// Integer division is slow so do it for a group of two digits instead
// of for every digit. The idea comes from the talk by Alexandrescu
// "Three Optimization Tips for C++". See speed-test for a comparison.
unsigned index = static_cast<unsigned>((value % 100) * 2);
value /= 100;
- *--ptr = internal::data::DIGITS[index + 1];
- *--ptr = internal::data::DIGITS[index];
+ *--ptr = internal::data::digits[index + 1];
+ *--ptr = internal::data::digits[index];
}
if (value < 10) {
*--ptr = static_cast<char>('0' + value);
return ptr;
}
unsigned index = static_cast<unsigned>(value * 2);
- *--ptr = internal::data::DIGITS[index + 1];
- *--ptr = internal::data::DIGITS[index];
+ *--ptr = internal::data::digits[index + 1];
+ *--ptr = internal::data::digits[index];
return ptr;
}
void format_signed(long long value) {
unsigned long long abs_value = static_cast<unsigned long long>(value);
bool negative = value < 0;
- if (negative)
- abs_value = 0 - abs_value;
+ if (negative) abs_value = 0 - abs_value;
str_ = format_decimal(abs_value);
- if (negative)
- *--str_ = '-';
+ if (negative) *--str_ = '-';
}
public:
@@ -2860,21 +2922,21 @@
/** Returns the number of characters written to the output buffer. */
std::size_t size() const {
- return internal::to_unsigned(buffer_ - str_ + BUFFER_SIZE - 1);
+ return internal::to_unsigned(buffer_ - str_ + buffer_size - 1);
}
/**
Returns a pointer to the output buffer content. No terminating null
character is appended.
*/
- const char *data() const { return str_; }
+ const char* data() const { return str_; }
/**
Returns a pointer to the output buffer content with terminating null
character appended.
*/
- const char *c_str() const {
- buffer_[BUFFER_SIZE - 1] = '\0';
+ const char* c_str() const {
+ buffer_[buffer_size - 1] = '\0';
return str_;
}
@@ -2886,52 +2948,24 @@
std::string str() const { return std::string(str_, size()); }
};
-// DEPRECATED!
-// Formats a decimal integer value writing into buffer and returns
-// a pointer to the end of the formatted string. This function doesn't
-// write a terminating null character.
-template <typename T>
-inline void format_decimal(char *&buffer, T value) {
- typedef typename internal::int_traits<T>::main_type main_type;
- main_type abs_value = static_cast<main_type>(value);
- if (internal::is_negative(value)) {
- *buffer++ = '-';
- abs_value = 0 - abs_value;
- }
- if (abs_value < 100) {
- if (abs_value < 10) {
- *buffer++ = static_cast<char>('0' + abs_value);
- return;
- }
- unsigned index = static_cast<unsigned>(abs_value * 2);
- *buffer++ = internal::data::DIGITS[index];
- *buffer++ = internal::data::DIGITS[index + 1];
- return;
- }
- int num_digits = internal::count_digits(abs_value);
- internal::format_decimal<char>(
- internal::make_checked(buffer, internal::to_unsigned(num_digits)), abs_value, num_digits);
- buffer += num_digits;
-}
-
-// Formatter of objects of type T.
+// A formatter specialization for the core types corresponding to internal::type
+// constants.
template <typename T, typename Char>
-struct formatter<
- T, Char,
- typename std::enable_if<internal::format_type<
- typename buffer_context<Char>::type, T>::value>::type> {
+struct formatter<T, Char,
+ enable_if_t<internal::type_constant<T, Char>::value !=
+ internal::custom_type>> {
+ FMT_CONSTEXPR formatter() : format_str_(nullptr) {}
// Parses format specifiers stopping either at the end of the range or at the
// terminating '}'.
template <typename ParseContext>
- FMT_CONSTEXPR typename ParseContext::iterator parse(ParseContext &ctx) {
- typedef internal::dynamic_specs_handler<ParseContext> handler_type;
- auto type = internal::get_type<
- typename buffer_context<Char>::type, T>::value;
- internal::specs_checker<handler_type>
- handler(handler_type(specs_, ctx), type);
+ FMT_CONSTEXPR auto parse(ParseContext& ctx) -> decltype(ctx.begin()) {
+ format_str_ = ctx.begin();
+ using handler_type = internal::dynamic_specs_handler<ParseContext>;
+ auto type = internal::type_constant<T, Char>::value;
+ internal::specs_checker<handler_type> handler(handler_type(specs_, ctx),
+ type);
auto it = parse_format_specs(ctx.begin(), ctx.end(), handler);
- auto type_spec = specs_.type;
auto eh = ctx.error_handler();
switch (type) {
case internal::none_type:
@@ -2943,28 +2977,27 @@
case internal::long_long_type:
case internal::ulong_long_type:
case internal::bool_type:
- handle_int_type_spec(
- type_spec, internal::int_type_checker<decltype(eh)>(eh));
+ handle_int_type_spec(specs_.type,
+ internal::int_type_checker<decltype(eh)>(eh));
break;
case internal::char_type:
handle_char_specs(
- &specs_,
- internal::char_specs_checker<decltype(eh)>(type_spec, eh));
+ &specs_, internal::char_specs_checker<decltype(eh)>(specs_.type, eh));
break;
case internal::double_type:
case internal::long_double_type:
- handle_float_type_spec(
- type_spec, internal::float_type_checker<decltype(eh)>(eh));
+ handle_float_type_spec(specs_.type,
+ internal::float_type_checker<decltype(eh)>(eh));
break;
case internal::cstring_type:
internal::handle_cstring_type_spec(
- type_spec, internal::cstring_type_checker<decltype(eh)>(eh));
+ specs_.type, internal::cstring_type_checker<decltype(eh)>(eh));
break;
case internal::string_type:
- internal::check_string_type_spec(type_spec, eh);
+ internal::check_string_type_spec(specs_.type, eh);
break;
case internal::pointer_type:
- internal::check_pointer_type_spec(type_spec, eh);
+ internal::check_pointer_type_spec(specs_.type, eh);
break;
case internal::custom_type:
// Custom format specifiers should be checked in parse functions of
@@ -2975,36 +3008,74 @@
}
template <typename FormatContext>
- auto format(const T &val, FormatContext &ctx) -> decltype(ctx.out()) {
+ auto format(const T& val, FormatContext& ctx) -> decltype(ctx.out()) {
internal::handle_dynamic_spec<internal::width_checker>(
- specs_.width_, specs_.width_ref, ctx);
+ specs_.width, specs_.width_ref, ctx, format_str_);
internal::handle_dynamic_spec<internal::precision_checker>(
- specs_.precision, specs_.precision_ref, ctx);
- typedef output_range<typename FormatContext::iterator,
- typename FormatContext::char_type> range_type;
- return visit_format_arg(arg_formatter<range_type>(ctx, &specs_),
- internal::make_arg<FormatContext>(val));
+ specs_.precision, specs_.precision_ref, ctx, format_str_);
+ using range_type =
+ internal::output_range<typename FormatContext::iterator,
+ typename FormatContext::char_type>;
+ return visit_format_arg(arg_formatter<range_type>(ctx, nullptr, &specs_),
+ internal::make_arg<FormatContext>(val));
}
private:
internal::dynamic_format_specs<Char> specs_;
+ const Char* format_str_;
+};
+
+#define FMT_FORMAT_AS(Type, Base) \
+ template <typename Char> \
+ struct formatter<Type, Char> : formatter<Base, Char> { \
+ template <typename FormatContext> \
+ auto format(const Type& val, FormatContext& ctx) -> decltype(ctx.out()) { \
+ return formatter<Base, Char>::format(val, ctx); \
+ } \
+ }
+
+FMT_FORMAT_AS(signed char, int);
+FMT_FORMAT_AS(unsigned char, unsigned);
+FMT_FORMAT_AS(short, int);
+FMT_FORMAT_AS(unsigned short, unsigned);
+FMT_FORMAT_AS(long, long long);
+FMT_FORMAT_AS(unsigned long, unsigned long long);
+FMT_FORMAT_AS(float, double);
+FMT_FORMAT_AS(Char*, const Char*);
+FMT_FORMAT_AS(std::basic_string<Char>, basic_string_view<Char>);
+FMT_FORMAT_AS(std::nullptr_t, const void*);
+FMT_FORMAT_AS(internal::std_string_view<Char>, basic_string_view<Char>);
+
+template <typename Char>
+struct formatter<void*, Char> : formatter<const void*, Char> {
+ template <typename FormatContext>
+ auto format(void* val, FormatContext& ctx) -> decltype(ctx.out()) {
+ return formatter<const void*, Char>::format(val, ctx);
+ }
+};
+
+template <typename Char, size_t N>
+struct formatter<Char[N], Char> : formatter<basic_string_view<Char>, Char> {
+ template <typename FormatContext>
+ auto format(const Char* val, FormatContext& ctx) -> decltype(ctx.out()) {
+ return formatter<basic_string_view<Char>, Char>::format(val, ctx);
+ }
};
// A formatter for types known only at run time such as variant alternatives.
//
// Usage:
-// typedef std::variant<int, std::string> variant;
+// using variant = std::variant<int, std::string>;
// template <>
// struct formatter<variant>: dynamic_formatter<> {
// void format(buffer &buf, const variant &v, context &ctx) {
// visit([&](const auto &val) { format(buf, val, ctx); }, v);
// }
// };
-template <typename Char = char>
-class dynamic_formatter {
+template <typename Char = char> class dynamic_formatter {
private:
- struct null_handler: internal::error_handler {
- void on_align(alignment) {}
+ struct null_handler : internal::error_handler {
+ void on_align(align_t) {}
void on_plus() {}
void on_minus() {}
void on_space() {}
@@ -3013,108 +3084,122 @@
public:
template <typename ParseContext>
- auto parse(ParseContext &ctx) -> decltype(ctx.begin()) {
+ auto parse(ParseContext& ctx) -> decltype(ctx.begin()) {
+ format_str_ = ctx.begin();
// Checks are deferred to formatting time when the argument type is known.
internal::dynamic_specs_handler<ParseContext> handler(specs_, ctx);
return parse_format_specs(ctx.begin(), ctx.end(), handler);
}
template <typename T, typename FormatContext>
- auto format(const T &val, FormatContext &ctx) -> decltype(ctx.out()) {
+ auto format(const T& val, FormatContext& ctx) -> decltype(ctx.out()) {
handle_specs(ctx);
- internal::specs_checker<null_handler>
- checker(null_handler(), internal::get_type<FormatContext, T>::value);
- checker.on_align(specs_.align());
- if (specs_.flags == 0); // Do nothing.
- else if (specs_.has(SIGN_FLAG))
- specs_.has(PLUS_FLAG) ? checker.on_plus() : checker.on_space();
- else if (specs_.has(MINUS_FLAG))
+ internal::specs_checker<null_handler> checker(
+ null_handler(),
+ internal::mapped_type_constant<T, FormatContext>::value);
+ checker.on_align(specs_.align);
+ switch (specs_.sign) {
+ case sign::none:
+ break;
+ case sign::plus:
+ checker.on_plus();
+ break;
+ case sign::minus:
checker.on_minus();
- else if (specs_.has(HASH_FLAG))
- checker.on_hash();
- if (specs_.precision != -1)
- checker.end_precision();
- typedef output_range<typename FormatContext::iterator,
- typename FormatContext::char_type> range;
- visit_format_arg(arg_formatter<range>(ctx, &specs_),
- internal::make_arg<FormatContext>(val));
+ break;
+ case sign::space:
+ checker.on_space();
+ break;
+ }
+ if (specs_.alt) checker.on_hash();
+ if (specs_.precision >= 0) checker.end_precision();
+ using range = internal::output_range<typename FormatContext::iterator,
+ typename FormatContext::char_type>;
+ visit_format_arg(arg_formatter<range>(ctx, nullptr, &specs_),
+ internal::make_arg<FormatContext>(val));
return ctx.out();
}
private:
- template <typename Context>
- void handle_specs(Context &ctx) {
+ template <typename Context> void handle_specs(Context& ctx) {
internal::handle_dynamic_spec<internal::width_checker>(
- specs_.width_, specs_.width_ref, ctx);
+ specs_.width, specs_.width_ref, ctx, format_str_);
internal::handle_dynamic_spec<internal::precision_checker>(
- specs_.precision, specs_.precision_ref, ctx);
+ specs_.precision, specs_.precision_ref, ctx, format_str_);
}
internal::dynamic_format_specs<Char> specs_;
+ const Char* format_str_;
};
template <typename Range, typename Char>
typename basic_format_context<Range, Char>::format_arg
- basic_format_context<Range, Char>::get_arg(
- basic_string_view<char_type> name) {
- map_.init(this->args());
+basic_format_context<Range, Char>::arg(basic_string_view<char_type> name) {
+ map_.init(args_);
format_arg arg = map_.find(name);
- if (arg.type() == internal::none_type)
- this->on_error("argument not found");
+ if (arg.type() == internal::none_type) this->on_error("argument not found");
return arg;
}
+template <typename Char, typename ErrorHandler>
+FMT_CONSTEXPR void advance_to(basic_parse_context<Char, ErrorHandler>& ctx,
+ const Char* p) {
+ ctx.advance_to(ctx.begin() + (p - &*ctx.begin()));
+}
+
template <typename ArgFormatter, typename Char, typename Context>
struct format_handler : internal::error_handler {
- typedef typename ArgFormatter::range range;
+ using range = typename ArgFormatter::range;
format_handler(range r, basic_string_view<Char> str,
basic_format_args<Context> format_args,
internal::locale_ref loc)
- : context(r.begin(), str, format_args, loc) {}
+ : parse_context(str), context(r.begin(), format_args, loc) {}
- void on_text(const Char *begin, const Char *end) {
+ void on_text(const Char* begin, const Char* end) {
auto size = internal::to_unsigned(end - begin);
auto out = context.out();
- auto &&it = internal::reserve(out, size);
+ auto&& it = internal::reserve(out, size);
it = std::copy_n(begin, size, it);
context.advance_to(out);
}
- void on_arg_id() { arg = context.next_arg(); }
- void on_arg_id(unsigned id) {
- context.parse_context().check_arg_id(id);
- arg = context.get_arg(id);
- }
- void on_arg_id(basic_string_view<Char> id) {
- arg = context.get_arg(id);
- }
+ void get_arg(int id) { arg = internal::get_arg(context, id); }
- void on_replacement_field(const Char *p) {
- context.parse_context().advance_to(p);
- internal::custom_formatter<Char, Context> f(context);
+ void on_arg_id() { get_arg(parse_context.next_arg_id()); }
+ void on_arg_id(int id) {
+ parse_context.check_arg_id(id);
+ get_arg(id);
+ }
+ void on_arg_id(basic_string_view<Char> id) { arg = context.arg(id); }
+
+ void on_replacement_field(const Char* p) {
+ advance_to(parse_context, p);
+ internal::custom_formatter<Context> f(parse_context, context);
if (!visit_format_arg(f, arg))
- context.advance_to(visit_format_arg(ArgFormatter(context), arg));
+ context.advance_to(
+ visit_format_arg(ArgFormatter(context, &parse_context), arg));
}
- const Char *on_format_specs(const Char *begin, const Char *end) {
- auto &parse_ctx = context.parse_context();
- parse_ctx.advance_to(begin);
- internal::custom_formatter<Char, Context> f(context);
- if (visit_format_arg(f, arg))
- return parse_ctx.begin();
+ const Char* on_format_specs(const Char* begin, const Char* end) {
+ advance_to(parse_context, begin);
+ internal::custom_formatter<Context> f(parse_context, context);
+ if (visit_format_arg(f, arg)) return parse_context.begin();
basic_format_specs<Char> specs;
using internal::specs_handler;
- internal::specs_checker<specs_handler<Context>>
- handler(specs_handler<Context>(specs, context), arg.type());
+ using parse_context_t = basic_parse_context<Char>;
+ internal::specs_checker<specs_handler<parse_context_t, Context>> handler(
+ specs_handler<parse_context_t, Context>(specs, parse_context, context),
+ arg.type());
begin = parse_format_specs(begin, end, handler);
- if (begin == end || *begin != '}')
- on_error("missing '}' in format string");
- parse_ctx.advance_to(begin);
- context.advance_to(visit_format_arg(ArgFormatter(context, &specs), arg));
+ if (begin == end || *begin != '}') on_error("missing '}' in format string");
+ advance_to(parse_context, begin);
+ context.advance_to(
+ visit_format_arg(ArgFormatter(context, &parse_context, &specs), arg));
return begin;
}
+ basic_parse_context<Char> parse_context;
Context context;
basic_format_arg<Context> arg;
};
@@ -3122,8 +3207,7 @@
/** Formats arguments and writes the output to the range. */
template <typename ArgFormatter, typename Char, typename Context>
typename Context::iterator vformat_to(
- typename ArgFormatter::range out,
- basic_string_view<Char> format_str,
+ typename ArgFormatter::range out, basic_string_view<Char> format_str,
basic_format_args<Context> args,
internal::locale_ref loc = internal::locale_ref()) {
format_handler<ArgFormatter, Char, Context> h(out, format_str, args, loc);
@@ -3134,26 +3218,29 @@
// Casts ``p`` to ``const void*`` for pointer formatting.
// Example:
// auto s = format("{}", ptr(p));
-template <typename T>
-inline const void *ptr(const T *p) { return p; }
+template <typename T> inline const void* ptr(const T* p) { return p; }
+template <typename T> inline const void* ptr(const std::unique_ptr<T>& p) {
+ return p.get();
+}
+template <typename T> inline const void* ptr(const std::shared_ptr<T>& p) {
+ return p.get();
+}
-template <typename It, typename Char>
-struct arg_join {
+template <typename It, typename Char> struct arg_join : internal::view {
It begin;
It end;
basic_string_view<Char> sep;
- arg_join(It begin, It end, basic_string_view<Char> sep)
- : begin(begin), end(end), sep(sep) {}
+ arg_join(It b, It e, basic_string_view<Char> s) : begin(b), end(e), sep(s) {}
};
template <typename It, typename Char>
-struct formatter<arg_join<It, Char>, Char>:
- formatter<typename std::iterator_traits<It>::value_type, Char> {
+struct formatter<arg_join<It, Char>, Char>
+ : formatter<typename std::iterator_traits<It>::value_type, Char> {
template <typename FormatContext>
- auto format(const arg_join<It, Char> &value, FormatContext &ctx)
+ auto format(const arg_join<It, Char>& value, FormatContext& ctx)
-> decltype(ctx.out()) {
- typedef formatter<typename std::iterator_traits<It>::value_type, Char> base;
+ using base = formatter<typename std::iterator_traits<It>::value_type, Char>;
auto it = value.begin;
auto out = ctx.out();
if (it != value.end) {
@@ -3168,30 +3255,42 @@
}
};
+/**
+ Returns an object that formats the iterator range `[begin, end)` with elements
+ separated by `sep`.
+ */
template <typename It>
arg_join<It, char> join(It begin, It end, string_view sep) {
- return arg_join<It, char>(begin, end, sep);
+ return {begin, end, sep};
}
template <typename It>
arg_join<It, wchar_t> join(It begin, It end, wstring_view sep) {
- return arg_join<It, wchar_t>(begin, end, sep);
+ return {begin, end, sep};
}
-// The following causes ICE in gcc 4.4.
-#if FMT_USE_TRAILING_RETURN && (!FMT_GCC_VERSION || FMT_GCC_VERSION >= 405)
+/**
+ \rst
+ Returns an object that formats `range` with elements separated by `sep`.
+
+ **Example**::
+
+ std::vector<int> v = {1, 2, 3};
+ fmt::print("{}", fmt::join(v, ", "));
+ // Output: "1, 2, 3"
+ \endrst
+ */
template <typename Range>
-auto join(const Range &range, string_view sep)
- -> arg_join<decltype(internal::begin(range)), char> {
- return join(internal::begin(range), internal::end(range), sep);
+arg_join<internal::iterator_t<const Range>, char> join(const Range& range,
+ string_view sep) {
+ return join(std::begin(range), std::end(range), sep);
}
template <typename Range>
-auto join(const Range &range, wstring_view sep)
- -> arg_join<decltype(internal::begin(range)), wchar_t> {
- return join(internal::begin(range), internal::end(range), sep);
+arg_join<internal::iterator_t<const Range>, wchar_t> join(const Range& range,
+ wstring_view sep) {
+ return join(std::begin(range), std::end(range), sep);
}
-#endif
/**
\rst
@@ -3205,121 +3304,62 @@
std::string answer = fmt::to_string(42);
\endrst
*/
-template <typename T>
-std::string to_string(const T &value) {
- std::string str;
- internal::container_buffer<std::string> buf(str);
- writer(buf).write(value);
- return str;
+template <typename T> inline std::string to_string(const T& value) {
+ return format("{}", value);
}
/**
Converts *value* to ``std::wstring`` using the default format for type *T*.
*/
-template <typename T>
-std::wstring to_wstring(const T &value) {
- std::wstring str;
- internal::container_buffer<std::wstring> buf(str);
- wwriter(buf).write(value);
- return str;
+template <typename T> inline std::wstring to_wstring(const T& value) {
+ return format(L"{}", value);
}
template <typename Char, std::size_t SIZE>
-std::basic_string<Char> to_string(const basic_memory_buffer<Char, SIZE> &buf) {
+std::basic_string<Char> to_string(const basic_memory_buffer<Char, SIZE>& buf) {
return std::basic_string<Char>(buf.data(), buf.size());
}
template <typename Char>
-typename buffer_context<Char>::type::iterator internal::vformat_to(
- internal::basic_buffer<Char> &buf, basic_string_view<Char> format_str,
- basic_format_args<typename buffer_context<Char>::type> args) {
- typedef back_insert_range<internal::basic_buffer<Char> > range;
- return vformat_to<arg_formatter<range>>(
- buf, to_string_view(format_str), args);
+typename buffer_context<Char>::iterator internal::vformat_to(
+ internal::buffer<Char>& buf, basic_string_view<Char> format_str,
+ basic_format_args<buffer_context<Char>> args) {
+ using range = buffer_range<Char>;
+ return vformat_to<arg_formatter<range>>(buf, to_string_view(format_str),
+ args);
}
-template <typename S, typename Char = FMT_CHAR(S)>
-inline typename buffer_context<Char>::type::iterator vformat_to(
- internal::basic_buffer<Char> &buf, const S &format_str,
- basic_format_args<typename buffer_context<Char>::type> args) {
+template <typename S, typename Char = char_t<S>,
+ FMT_ENABLE_IF(internal::is_string<S>::value)>
+inline typename buffer_context<Char>::iterator vformat_to(
+ internal::buffer<Char>& buf, const S& format_str,
+ basic_format_args<buffer_context<Char>> args) {
return internal::vformat_to(buf, to_string_view(format_str), args);
}
-template <
- typename S, typename... Args,
- std::size_t SIZE = inline_buffer_size,
- typename Char = typename internal::char_t<S>::type>
-inline typename buffer_context<Char>::type::iterator format_to(
- basic_memory_buffer<Char, SIZE> &buf, const S &format_str,
- const Args &... args) {
+template <typename S, typename... Args, std::size_t SIZE = inline_buffer_size,
+ typename Char = enable_if_t<internal::is_string<S>::value, char_t<S>>>
+inline typename buffer_context<Char>::iterator format_to(
+ basic_memory_buffer<Char, SIZE>& buf, const S& format_str, Args&&... args) {
internal::check_format_string<Args...>(format_str);
- typedef typename buffer_context<Char>::type context;
- format_arg_store<context, Args...> as{args...};
+ using context = buffer_context<Char>;
return internal::vformat_to(buf, to_string_view(format_str),
- basic_format_args<context>(as));
+ {make_format_args<context>(args...)});
}
-namespace internal {
-
-// Detect the iterator category of *any* given type in a SFINAE-friendly way.
-// Unfortunately, older implementations of std::iterator_traits are not safe
-// for use in a SFINAE-context.
-
-// the gist of C++17's void_t magic
-template<typename... Ts>
-struct void_ { typedef void type; };
-
-template <typename T, typename Enable = void>
-struct it_category : std::false_type {};
-
-template <typename T>
-struct it_category<T*> { typedef std::random_access_iterator_tag type; };
-
-template <typename T>
-struct it_category<T, typename void_<typename T::iterator_category>::type> {
- typedef typename T::iterator_category type;
-};
-
-// Detect if *any* given type models the OutputIterator concept.
-template <typename It>
-class is_output_iterator {
- // Check for mutability because all iterator categories derived from
- // std::input_iterator_tag *may* also meet the requirements of an
- // OutputIterator, thereby falling into the category of 'mutable iterators'
- // [iterator.requirements.general] clause 4.
- // The compiler reveals this property only at the point of *actually
- // dereferencing* the iterator!
- template <typename U>
- static decltype(*(internal::declval<U>())) test(std::input_iterator_tag);
- template <typename U>
- static char& test(std::output_iterator_tag);
- template <typename U>
- static const char& test(...);
-
- typedef decltype(test<It>(typename it_category<It>::type{})) type;
- typedef typename std::remove_reference<type>::type result;
- public:
- static const bool value = !std::is_const<result>::value;
-};
-} // internal
+template <typename OutputIt, typename Char = char>
+using format_context_t = basic_format_context<OutputIt, Char>;
template <typename OutputIt, typename Char = char>
-//using format_context_t = basic_format_context<OutputIt, Char>;
-struct format_context_t { typedef basic_format_context<OutputIt, Char> type; };
+using format_args_t = basic_format_args<format_context_t<OutputIt, Char>>;
-template <typename OutputIt, typename Char = char>
-//using format_args_t = basic_format_args<format_context_t<OutputIt, Char>>;
-struct format_args_t {
- typedef basic_format_args<
- typename format_context_t<OutputIt, Char>::type> type;
-};
-
-template <typename String, typename OutputIt, typename... Args>
-inline typename std::enable_if<internal::is_output_iterator<OutputIt>::value,
- OutputIt>::type
- vformat_to(OutputIt out, const String &format_str,
- typename format_args_t<OutputIt, FMT_CHAR(String)>::type args) {
- typedef output_range<OutputIt, FMT_CHAR(String)> range;
+template <typename S, typename OutputIt, typename... Args,
+ FMT_ENABLE_IF(
+ internal::is_output_iterator<OutputIt>::value &&
+ !internal::is_contiguous_back_insert_iterator<OutputIt>::value)>
+inline OutputIt vformat_to(OutputIt out, const S& format_str,
+ format_args_t<OutputIt, char_t<S>> args) {
+ using range = internal::output_range<OutputIt, char_t<S>>;
return vformat_to<arg_formatter<range>>(range(out),
to_string_view(format_str), args);
}
@@ -3335,20 +3375,19 @@
fmt::format_to(std::back_inserter(out), "{}", 42);
\endrst
*/
-template <typename OutputIt, typename S, typename... Args>
-inline FMT_ENABLE_IF_T(
- internal::is_string<S>::value &&
- internal::is_output_iterator<OutputIt>::value, OutputIt)
- format_to(OutputIt out, const S &format_str, const Args &... args) {
+template <typename OutputIt, typename S, typename... Args,
+ FMT_ENABLE_IF(
+ internal::is_output_iterator<OutputIt>::value &&
+ !internal::is_contiguous_back_insert_iterator<OutputIt>::value &&
+ internal::is_string<S>::value)>
+inline OutputIt format_to(OutputIt out, const S& format_str, Args&&... args) {
internal::check_format_string<Args...>(format_str);
- typedef typename format_context_t<OutputIt, FMT_CHAR(S)>::type context;
- format_arg_store<context, Args...> as{args...};
+ using context = format_context_t<OutputIt, char_t<S>>;
return vformat_to(out, to_string_view(format_str),
- basic_format_args<context>(as));
+ {make_format_args<context>(args...)});
}
-template <typename OutputIt>
-struct format_to_n_result {
+template <typename OutputIt> struct format_to_n_result {
/** Iterator past the end of the output range. */
OutputIt out;
/** Total (not truncated) output size. */
@@ -3356,31 +3395,26 @@
};
template <typename OutputIt, typename Char = typename OutputIt::value_type>
-struct format_to_n_context :
- format_context_t<fmt::internal::truncating_iterator<OutputIt>, Char> {};
+using format_to_n_context =
+ format_context_t<fmt::internal::truncating_iterator<OutputIt>, Char>;
template <typename OutputIt, typename Char = typename OutputIt::value_type>
-struct format_to_n_args {
- typedef basic_format_args<
- typename format_to_n_context<OutputIt, Char>::type> type;
-};
-
-template <typename OutputIt, typename Char, typename ...Args>
-inline format_arg_store<
- typename format_to_n_context<OutputIt, Char>::type, Args...>
- make_format_to_n_args(const Args &... args) {
- return format_arg_store<
- typename format_to_n_context<OutputIt, Char>::type, Args...>(args...);
-}
+using format_to_n_args = basic_format_args<format_to_n_context<OutputIt, Char>>;
template <typename OutputIt, typename Char, typename... Args>
-inline typename std::enable_if<
- internal::is_output_iterator<OutputIt>::value,
- format_to_n_result<OutputIt>>::type vformat_to_n(
+inline format_arg_store<format_to_n_context<OutputIt, Char>, Args...>
+make_format_to_n_args(const Args&... args) {
+ return format_arg_store<format_to_n_context<OutputIt, Char>, Args...>(
+ args...);
+}
+
+template <typename OutputIt, typename Char, typename... Args,
+ FMT_ENABLE_IF(internal::is_output_iterator<OutputIt>::value)>
+inline format_to_n_result<OutputIt> vformat_to_n(
OutputIt out, std::size_t n, basic_string_view<Char> format_str,
- typename format_to_n_args<OutputIt, Char>::type args) {
- typedef internal::truncating_iterator<OutputIt> It;
- auto it = vformat_to(It(out, n), format_str, args);
+ format_to_n_args<OutputIt, Char> args) {
+ auto it = vformat_to(internal::truncating_iterator<OutputIt>(out, n),
+ format_str, args);
return {it.base(), it.count()};
}
@@ -3391,25 +3425,22 @@
end of the output range.
\endrst
*/
-template <typename OutputIt, typename S, typename... Args>
-inline FMT_ENABLE_IF_T(
- internal::is_string<S>::value &&
- internal::is_output_iterator<OutputIt>::value,
- format_to_n_result<OutputIt>)
- format_to_n(OutputIt out, std::size_t n, const S &format_str,
- const Args &... args) {
+template <typename OutputIt, typename S, typename... Args,
+ FMT_ENABLE_IF(internal::is_string<S>::value&&
+ internal::is_output_iterator<OutputIt>::value)>
+inline format_to_n_result<OutputIt> format_to_n(OutputIt out, std::size_t n,
+ const S& format_str,
+ const Args&... args) {
internal::check_format_string<Args...>(format_str);
- typedef FMT_CHAR(S) Char;
- format_arg_store<
- typename format_to_n_context<OutputIt, Char>::type, Args...> as(args...);
+ using context = format_to_n_context<OutputIt, char_t<S>>;
return vformat_to_n(out, n, to_string_view(format_str),
- typename format_to_n_args<OutputIt, Char>::type(as));
+ {make_format_args<context>(args...)});
}
template <typename Char>
inline std::basic_string<Char> internal::vformat(
basic_string_view<Char> format_str,
- basic_format_args<typename buffer_context<Char>::type> args) {
+ basic_format_args<buffer_context<Char>> args) {
basic_memory_buffer<Char> buffer;
internal::vformat_to(buffer, format_str, args);
return fmt::to_string(buffer);
@@ -3420,8 +3451,7 @@
``format(format_str, args...)``.
*/
template <typename... Args>
-inline std::size_t formatted_size(string_view format_str,
- const Args &... args) {
+inline std::size_t formatted_size(string_view format_str, const Args&... args) {
auto it = format_to(internal::counting_iterator<char>(), format_str, args...);
return it.count();
}
@@ -3429,53 +3459,52 @@
#if FMT_USE_USER_DEFINED_LITERALS
namespace internal {
-# if FMT_UDL_TEMPLATE
-template <typename Char, Char... CHARS>
-class udl_formatter {
+# if FMT_USE_UDL_TEMPLATE
+template <typename Char, Char... CHARS> class udl_formatter {
public:
template <typename... Args>
- std::basic_string<Char> operator()(const Args &... args) const {
+ std::basic_string<Char> operator()(Args&&... args) const {
FMT_CONSTEXPR_DECL Char s[] = {CHARS..., '\0'};
FMT_CONSTEXPR_DECL bool invalid_format =
do_check_format_string<Char, error_handler, Args...>(
- basic_string_view<Char>(s, sizeof...(CHARS)));
+ basic_string_view<Char>(s, sizeof...(CHARS)));
(void)invalid_format;
- return format(s, args...);
+ return format(s, std::forward<Args>(args)...);
}
};
-# else
-template <typename Char>
-struct udl_formatter {
- const Char *str;
+# else
+template <typename Char> struct udl_formatter {
+ basic_string_view<Char> str;
template <typename... Args>
- auto operator()(Args &&... args) const
- -> decltype(format(str, std::forward<Args>(args)...)) {
+ std::basic_string<Char> operator()(Args&&... args) const {
return format(str, std::forward<Args>(args)...);
}
};
-# endif // FMT_UDL_TEMPLATE
+# endif // FMT_USE_UDL_TEMPLATE
-template <typename Char>
-struct udl_arg {
- const Char *str;
+template <typename Char> struct udl_arg {
+ basic_string_view<Char> str;
- template <typename T>
- named_arg<T, Char> operator=(T &&value) const {
+ template <typename T> named_arg<T, Char> operator=(T&& value) const {
return {str, std::forward<T>(value)};
}
};
-} // namespace internal
+} // namespace internal
inline namespace literals {
-
-# if FMT_UDL_TEMPLATE
+# if FMT_USE_UDL_TEMPLATE
+# pragma GCC diagnostic push
+# if FMT_CLANG_VERSION
+# pragma GCC diagnostic ignored "-Wgnu-string-literal-operator-template"
+# endif
template <typename Char, Char... CHARS>
FMT_CONSTEXPR internal::udl_formatter<Char, CHARS...> operator""_format() {
return {};
}
-# else
+# pragma GCC diagnostic pop
+# else
/**
\rst
User-defined literal equivalent of :func:`fmt::format`.
@@ -3486,11 +3515,15 @@
std::string message = "The answer is {}"_format(42);
\endrst
*/
-inline internal::udl_formatter<char>
-operator"" _format(const char *s, std::size_t) { return {s}; }
-inline internal::udl_formatter<wchar_t>
-operator"" _format(const wchar_t *s, std::size_t) { return {s}; }
-# endif // FMT_UDL_TEMPLATE
+FMT_CONSTEXPR internal::udl_formatter<char> operator"" _format(const char* s,
+ std::size_t n) {
+ return {{s, n}};
+}
+FMT_CONSTEXPR internal::udl_formatter<wchar_t> operator"" _format(
+ const wchar_t* s, std::size_t n) {
+ return {{s, n}};
+}
+# endif // FMT_USE_UDL_TEMPLATE
/**
\rst
@@ -3502,24 +3535,41 @@
fmt::print("Elapsed time: {s:.2f} seconds", "s"_a=1.23);
\endrst
*/
-inline internal::udl_arg<char>
-operator"" _a(const char *s, std::size_t) { return {s}; }
-inline internal::udl_arg<wchar_t>
-operator"" _a(const wchar_t *s, std::size_t) { return {s}; }
-} // inline namespace literals
-#endif // FMT_USE_USER_DEFINED_LITERALS
+FMT_CONSTEXPR internal::udl_arg<char> operator"" _a(const char* s,
+ std::size_t n) {
+ return {{s, n}};
+}
+FMT_CONSTEXPR internal::udl_arg<wchar_t> operator"" _a(const wchar_t* s,
+ std::size_t n) {
+ return {{s, n}};
+}
+} // namespace literals
+#endif // FMT_USE_USER_DEFINED_LITERALS
FMT_END_NAMESPACE
-#define FMT_STRING(s) [] { \
- typedef typename std::remove_cv<std::remove_pointer< \
- typename std::decay<decltype(s)>::type>::type>::type ct; \
- struct str : fmt::compile_string { \
- typedef ct char_type; \
- FMT_CONSTEXPR operator fmt::basic_string_view<ct>() const { \
- return {s, sizeof(s) / sizeof(ct) - 1}; \
- } \
- }; \
- return str{}; \
+/**
+ \rst
+ Constructs a compile-time format string.
+
+ **Example**::
+
+ // A compile-time error because 'd' is an invalid specifier for strings.
+ std::string s = format(FMT_STRING("{:d}"), "foo");
+ \endrst
+ */
+#define FMT_STRING(s) \
+ [] { \
+ struct str : fmt::compile_string { \
+ using char_type = typename std::remove_cv<std::remove_pointer< \
+ typename std::decay<decltype(s)>::type>::type>::type; \
+ FMT_CONSTEXPR operator fmt::basic_string_view<char_type>() const { \
+ return {s, sizeof(s) / sizeof(char_type) - 1}; \
+ } \
+ } result; \
+ /* Suppress Qt Creator warning about unused operator. */ \
+ (void)static_cast<fmt::basic_string_view<typename str::char_type>>( \
+ result); \
+ return result; \
}()
#if defined(FMT_STRING_ALIAS) && FMT_STRING_ALIAS
@@ -3537,19 +3587,14 @@
std::string s = format(fmt("{:d}"), "foo");
\endrst
*/
-# define fmt(s) FMT_STRING(s)
+# define fmt(s) FMT_STRING(s)
#endif
#ifdef FMT_HEADER_ONLY
-# define FMT_FUNC inline
-# include "format-inl.h"
+# define FMT_FUNC inline
+# include "format-inl.h"
#else
-# define FMT_FUNC
-#endif
-
-// Restore warnings.
-#if FMT_GCC_VERSION >= 406 || FMT_CLANG_VERSION
-# pragma GCC diagnostic pop
+# define FMT_FUNC
#endif
#endif // FMT_FORMAT_H_
diff --git a/include/fmt/locale.h b/include/fmt/locale.h
index 8e021bc..7c13656 100644
--- a/include/fmt/locale.h
+++ b/include/fmt/locale.h
@@ -8,65 +8,65 @@
#ifndef FMT_LOCALE_H_
#define FMT_LOCALE_H_
-#include "format.h"
#include <locale>
+#include "format.h"
FMT_BEGIN_NAMESPACE
namespace internal {
template <typename Char>
-typename buffer_context<Char>::type::iterator vformat_to(
- const std::locale &loc, basic_buffer<Char> &buf,
+typename buffer_context<Char>::iterator vformat_to(
+ const std::locale& loc, buffer<Char>& buf,
basic_string_view<Char> format_str,
- basic_format_args<typename buffer_context<Char>::type> args) {
- typedef back_insert_range<basic_buffer<Char> > range;
- return vformat_to<arg_formatter<range>>(
- buf, to_string_view(format_str), args, internal::locale_ref(loc));
+ basic_format_args<buffer_context<Char>> args) {
+ using range = buffer_range<Char>;
+ return vformat_to<arg_formatter<range>>(buf, to_string_view(format_str), args,
+ internal::locale_ref(loc));
}
template <typename Char>
-std::basic_string<Char> vformat(
- const std::locale &loc, basic_string_view<Char> format_str,
- basic_format_args<typename buffer_context<Char>::type> args) {
+std::basic_string<Char> vformat(const std::locale& loc,
+ basic_string_view<Char> format_str,
+ basic_format_args<buffer_context<Char>> args) {
basic_memory_buffer<Char> buffer;
internal::vformat_to(loc, buffer, format_str, args);
return fmt::to_string(buffer);
}
-}
+} // namespace internal
-template <typename S, typename Char = FMT_CHAR(S)>
+template <typename S, typename Char = char_t<S>>
inline std::basic_string<Char> vformat(
- const std::locale &loc, const S &format_str,
- basic_format_args<typename buffer_context<Char>::type> args) {
+ const std::locale& loc, const S& format_str,
+ basic_format_args<buffer_context<Char>> args) {
return internal::vformat(loc, to_string_view(format_str), args);
}
-template <typename S, typename... Args>
-inline std::basic_string<FMT_CHAR(S)> format(
- const std::locale &loc, const S &format_str, const Args &... args) {
+template <typename S, typename... Args, typename Char = char_t<S>>
+inline std::basic_string<Char> format(const std::locale& loc,
+ const S& format_str, Args&&... args) {
return internal::vformat(
- loc, to_string_view(format_str),
- *internal::checked_args<S, Args...>(format_str, args...));
+ loc, to_string_view(format_str),
+ {internal::make_args_checked<Args...>(format_str, args...)});
}
-template <typename String, typename OutputIt, typename... Args>
-inline typename std::enable_if<internal::is_output_iterator<OutputIt>::value,
- OutputIt>::type
- vformat_to(OutputIt out, const std::locale &loc, const String &format_str,
- typename format_args_t<OutputIt, FMT_CHAR(String)>::type args) {
- typedef output_range<OutputIt, FMT_CHAR(String)> range;
+template <typename S, typename OutputIt, typename... Args,
+ typename Char = enable_if_t<
+ internal::is_output_iterator<OutputIt>::value, char_t<S>>>
+inline OutputIt vformat_to(OutputIt out, const std::locale& loc,
+ const S& format_str,
+ format_args_t<OutputIt, Char> args) {
+ using range = internal::output_range<OutputIt, Char>;
return vformat_to<arg_formatter<range>>(
- range(out), to_string_view(format_str), args, internal::locale_ref(loc));
+ range(out), to_string_view(format_str), args, internal::locale_ref(loc));
}
-template <typename OutputIt, typename S, typename... Args>
-inline typename std::enable_if<
- internal::is_string<S>::value &&
- internal::is_output_iterator<OutputIt>::value, OutputIt>::type
- format_to(OutputIt out, const std::locale &loc, const S &format_str,
- const Args &... args) {
+template <typename OutputIt, typename S, typename... Args,
+ FMT_ENABLE_IF(internal::is_output_iterator<OutputIt>::value&&
+ internal::is_string<S>::value)>
+inline OutputIt format_to(OutputIt out, const std::locale& loc,
+ const S& format_str, Args&&... args) {
internal::check_format_string<Args...>(format_str);
- typedef typename format_context_t<OutputIt, FMT_CHAR(S)>::type context;
+ using context = format_context_t<OutputIt, char_t<S>>;
format_arg_store<context, Args...> as{args...};
return vformat_to(out, loc, to_string_view(format_str),
basic_format_args<context>(as));
diff --git a/include/fmt/ostream.h b/include/fmt/ostream.h
index 84b31cc..69bac0e 100644
--- a/include/fmt/ostream.h
+++ b/include/fmt/ostream.h
@@ -8,22 +8,21 @@
#ifndef FMT_OSTREAM_H_
#define FMT_OSTREAM_H_
-#include "format.h"
#include <ostream>
+#include "format.h"
FMT_BEGIN_NAMESPACE
namespace internal {
-template <class Char>
-class formatbuf : public std::basic_streambuf<Char> {
+template <class Char> class formatbuf : public std::basic_streambuf<Char> {
private:
- typedef typename std::basic_streambuf<Char>::int_type int_type;
- typedef typename std::basic_streambuf<Char>::traits_type traits_type;
+ using int_type = typename std::basic_streambuf<Char>::int_type;
+ using traits_type = typename std::basic_streambuf<Char>::traits_type;
- basic_buffer<Char> &buffer_;
+ buffer<Char>& buffer_;
public:
- formatbuf(basic_buffer<Char> &buffer) : buffer_(buffer) {}
+ formatbuf(buffer<Char>& buf) : buffer_(buf) {}
protected:
// The put-area is actually always empty. This makes the implementation
@@ -39,33 +38,32 @@
return ch;
}
- std::streamsize xsputn(const Char *s, std::streamsize count) FMT_OVERRIDE {
+ std::streamsize xsputn(const Char* s, std::streamsize count) FMT_OVERRIDE {
buffer_.append(s, s + count);
return count;
}
};
-template <typename Char>
-struct test_stream : std::basic_ostream<Char> {
+template <typename Char> struct test_stream : std::basic_ostream<Char> {
private:
struct null;
// Hide all operator<< from std::basic_ostream<Char>.
void operator<<(null);
};
-// Checks if T has a user-defined operator<< (e.g. not a member of std::ostream).
-template <typename T, typename Char>
-class is_streamable {
+// Checks if T has a user-defined operator<< (e.g. not a member of
+// std::ostream).
+template <typename T, typename Char> class is_streamable {
private:
template <typename U>
- static decltype(
- internal::declval<test_stream<Char>&>()
- << internal::declval<U>(), std::true_type()) test(int);
+ static decltype((void)(std::declval<test_stream<Char>&>()
+ << std::declval<U>()),
+ std::true_type())
+ test(int);
- template <typename>
- static std::false_type test(...);
+ template <typename> static std::false_type test(...);
- typedef decltype(test<T>(0)) result;
+ using result = decltype(test<T>(0));
public:
static const bool value = result::value;
@@ -73,65 +71,51 @@
// Write the content of buf to os.
template <typename Char>
-void write(std::basic_ostream<Char> &os, basic_buffer<Char> &buf) {
- const Char *data = buf.data();
- typedef std::make_unsigned<std::streamsize>::type UnsignedStreamSize;
- UnsignedStreamSize size = buf.size();
- UnsignedStreamSize max_size =
- internal::to_unsigned((std::numeric_limits<std::streamsize>::max)());
+void write(std::basic_ostream<Char>& os, buffer<Char>& buf) {
+ const Char* buf_data = buf.data();
+ using unsigned_streamsize = std::make_unsigned<std::streamsize>::type;
+ unsigned_streamsize size = buf.size();
+ unsigned_streamsize max_size =
+ to_unsigned((std::numeric_limits<std::streamsize>::max)());
do {
- UnsignedStreamSize n = size <= max_size ? size : max_size;
- os.write(data, static_cast<std::streamsize>(n));
- data += n;
+ unsigned_streamsize n = size <= max_size ? size : max_size;
+ os.write(buf_data, static_cast<std::streamsize>(n));
+ buf_data += n;
size -= n;
} while (size != 0);
}
template <typename Char, typename T>
-void format_value(basic_buffer<Char> &buffer, const T &value) {
- internal::formatbuf<Char> format_buf(buffer);
+void format_value(buffer<Char>& buf, const T& value) {
+ formatbuf<Char> format_buf(buf);
std::basic_ostream<Char> output(&format_buf);
output.exceptions(std::ios_base::failbit | std::ios_base::badbit);
output << value;
- buffer.resize(buffer.size());
+ buf.resize(buf.size());
}
-} // namespace internal
-
-// Disable conversion to int if T has an overloaded operator<< which is a free
-// function (not a member of std::ostream).
-template <typename T, typename Char>
-struct convert_to_int<T, Char, void> {
- static const bool value =
- convert_to_int<T, Char, int>::value &&
- !internal::is_streamable<T, Char>::value;
-};
// Formats an object of type T that has an overloaded ostream operator<<.
template <typename T, typename Char>
-struct formatter<T, Char,
- typename std::enable_if<
- internal::is_streamable<T, Char>::value &&
- !internal::format_type<
- typename buffer_context<Char>::type, T>::value>::type>
+struct fallback_formatter<T, Char, enable_if_t<is_streamable<T, Char>::value>>
: formatter<basic_string_view<Char>, Char> {
-
template <typename Context>
- auto format(const T &value, Context &ctx) -> decltype(ctx.out()) {
+ auto format(const T& value, Context& ctx) -> decltype(ctx.out()) {
basic_memory_buffer<Char> buffer;
- internal::format_value(buffer, value);
+ format_value(buffer, value);
basic_string_view<Char> str(buffer.data(), buffer.size());
return formatter<basic_string_view<Char>, Char>::format(str, ctx);
}
};
+} // namespace internal
template <typename Char>
-inline void vprint(std::basic_ostream<Char> &os,
- basic_string_view<Char> format_str,
- basic_format_args<typename buffer_context<Char>::type> args) {
+void vprint(std::basic_ostream<Char>& os, basic_string_view<Char> format_str,
+ basic_format_args<buffer_context<Char>> args) {
basic_memory_buffer<Char> buffer;
internal::vformat_to(buffer, format_str, args);
internal::write(os, buffer);
}
+
/**
\rst
Prints formatted data to the stream *os*.
@@ -141,12 +125,11 @@
fmt::print(cerr, "Don't {}!", "panic");
\endrst
*/
-template <typename S, typename... Args>
-inline typename std::enable_if<internal::is_string<S>::value>::type
-print(std::basic_ostream<FMT_CHAR(S)> &os, const S &format_str,
- const Args & ... args) {
- internal::checked_args<S, Args...> ca(format_str, args...);
- vprint(os, to_string_view(format_str), *ca);
+template <typename S, typename... Args,
+ typename Char = enable_if_t<internal::is_string<S>::value, char_t<S>>>
+void print(std::basic_ostream<Char>& os, const S& format_str, Args&&... args) {
+ vprint(os, to_string_view(format_str),
+ {internal::make_args_checked<Args...>(format_str, args...)});
}
FMT_END_NAMESPACE
diff --git a/include/fmt/posix.h b/include/fmt/posix.h
index f4e3fad..6b2d7f8 100644
--- a/include/fmt/posix.h
+++ b/include/fmt/posix.h
@@ -10,7 +10,7 @@
#if defined(__MINGW32__) || defined(__CYGWIN__)
// Workaround MinGW bug https://sourceforge.net/p/mingw/bugs/2024/.
-# undef __STRICT_ANSI__
+# undef __STRICT_ANSI__
#endif
#include <errno.h>
@@ -22,42 +22,42 @@
#include <cstddef>
#if defined __APPLE__ || defined(__FreeBSD__)
-# include <xlocale.h> // for LC_NUMERIC_MASK on OS X
+# include <xlocale.h> // for LC_NUMERIC_MASK on OS X
#endif
#include "format.h"
#ifndef FMT_POSIX
-# if defined(_WIN32) && !defined(__MINGW32__)
+# if defined(_WIN32) && !defined(__MINGW32__)
// Fix warnings about deprecated symbols.
-# define FMT_POSIX(call) _##call
-# else
-# define FMT_POSIX(call) call
-# endif
+# define FMT_POSIX(call) _##call
+# else
+# define FMT_POSIX(call) call
+# endif
#endif
// Calls to system functions are wrapped in FMT_SYSTEM for testability.
#ifdef FMT_SYSTEM
-# define FMT_POSIX_CALL(call) FMT_SYSTEM(call)
+# define FMT_POSIX_CALL(call) FMT_SYSTEM(call)
#else
-# define FMT_SYSTEM(call) call
-# ifdef _WIN32
+# define FMT_SYSTEM(call) call
+# ifdef _WIN32
// Fix warnings about deprecated symbols.
-# define FMT_POSIX_CALL(call) ::_##call
-# else
-# define FMT_POSIX_CALL(call) ::call
-# endif
+# define FMT_POSIX_CALL(call) ::_##call
+# else
+# define FMT_POSIX_CALL(call) ::call
+# endif
#endif
// Retries the expression while it evaluates to error_result and errno
// equals to EINTR.
#ifndef _WIN32
-# define FMT_RETRY_VAL(result, expression, error_result) \
- do { \
- result = (expression); \
- } while (result == error_result && errno == EINTR)
+# define FMT_RETRY_VAL(result, expression, error_result) \
+ do { \
+ result = (expression); \
+ } while (result == error_result && errno == EINTR)
#else
-# define FMT_RETRY_VAL(result, expression, error_result) result = (expression)
+# define FMT_RETRY_VAL(result, expression, error_result) result = (expression)
#endif
#define FMT_RETRY(result, expression) FMT_RETRY_VAL(result, expression, -1)
@@ -69,7 +69,7 @@
A reference to a null-terminated string. It can be constructed from a C
string or ``std::string``.
- You can use one of the following typedefs for common character types:
+ You can use one of the following type aliases for common character types:
+---------------+-----------------------------+
| Type | Definition |
@@ -89,28 +89,27 @@
format(std::string("{}"), 42);
\endrst
*/
-template <typename Char>
-class basic_cstring_view {
+template <typename Char> class basic_cstring_view {
private:
- const Char *data_;
+ const Char* data_;
public:
/** Constructs a string reference object from a C string. */
- basic_cstring_view(const Char *s) : data_(s) {}
+ basic_cstring_view(const Char* s) : data_(s) {}
/**
\rst
Constructs a string reference from an ``std::string`` object.
\endrst
*/
- basic_cstring_view(const std::basic_string<Char> &s) : data_(s.c_str()) {}
+ basic_cstring_view(const std::basic_string<Char>& s) : data_(s.c_str()) {}
/** Returns the pointer to a C string. */
- const Char *c_str() const { return data_; }
+ const Char* c_str() const { return data_; }
};
-typedef basic_cstring_view<char> cstring_view;
-typedef basic_cstring_view<wchar_t> wcstring_view;
+using cstring_view = basic_cstring_view<char>;
+using wcstring_view = basic_cstring_view<wchar_t>;
// An error code.
class error_code {
@@ -126,33 +125,32 @@
// A buffered file.
class buffered_file {
private:
- FILE *file_;
+ FILE* file_;
friend class file;
- explicit buffered_file(FILE *f) : file_(f) {}
+ explicit buffered_file(FILE* f) : file_(f) {}
public:
// Constructs a buffered_file object which doesn't represent any file.
- buffered_file() FMT_NOEXCEPT : file_(FMT_NULL) {}
+ buffered_file() FMT_NOEXCEPT : file_(nullptr) {}
// Destroys the object closing the file it represents if any.
FMT_API ~buffered_file() FMT_NOEXCEPT;
private:
- buffered_file(const buffered_file &) = delete;
- void operator=(const buffered_file &) = delete;
-
+ buffered_file(const buffered_file&) = delete;
+ void operator=(const buffered_file&) = delete;
public:
- buffered_file(buffered_file &&other) FMT_NOEXCEPT : file_(other.file_) {
- other.file_ = FMT_NULL;
+ buffered_file(buffered_file&& other) FMT_NOEXCEPT : file_(other.file_) {
+ other.file_ = nullptr;
}
- buffered_file& operator=(buffered_file &&other) {
+ buffered_file& operator=(buffered_file&& other) {
close();
file_ = other.file_;
- other.file_ = FMT_NULL;
+ other.file_ = nullptr;
return *this;
}
@@ -163,18 +161,18 @@
FMT_API void close();
// Returns the pointer to a FILE object representing this file.
- FILE *get() const FMT_NOEXCEPT { return file_; }
+ FILE* get() const FMT_NOEXCEPT { return file_; }
// We place parentheses around fileno to workaround a bug in some versions
// of MinGW that define fileno as a macro.
- FMT_API int (fileno)() const;
+ FMT_API int(fileno)() const;
void vprint(string_view format_str, format_args args) {
fmt::vprint(file_, format_str, args);
}
template <typename... Args>
- inline void print(string_view format_str, const Args & ... args) {
+ inline void print(string_view format_str, const Args&... args) {
vprint(format_str, make_format_args(args...));
}
};
@@ -195,9 +193,9 @@
public:
// Possible values for the oflag argument to the constructor.
enum {
- RDONLY = FMT_POSIX(O_RDONLY), // Open for reading only.
- WRONLY = FMT_POSIX(O_WRONLY), // Open for writing only.
- RDWR = FMT_POSIX(O_RDWR) // Open for reading and writing.
+ RDONLY = FMT_POSIX(O_RDONLY), // Open for reading only.
+ WRONLY = FMT_POSIX(O_WRONLY), // Open for writing only.
+ RDWR = FMT_POSIX(O_RDWR) // Open for reading and writing.
};
// Constructs a file object which doesn't represent any file.
@@ -207,15 +205,13 @@
FMT_API file(cstring_view path, int oflag);
private:
- file(const file &) = delete;
- void operator=(const file &) = delete;
+ file(const file&) = delete;
+ void operator=(const file&) = delete;
public:
- file(file &&other) FMT_NOEXCEPT : fd_(other.fd_) {
- other.fd_ = -1;
- }
+ file(file&& other) FMT_NOEXCEPT : fd_(other.fd_) { other.fd_ = -1; }
- file& operator=(file &&other) {
+ file& operator=(file&& other) {
close();
fd_ = other.fd_;
other.fd_ = -1;
@@ -236,10 +232,10 @@
FMT_API long long size() const;
// Attempts to read count bytes from the file into the specified buffer.
- FMT_API std::size_t read(void *buffer, std::size_t count);
+ FMT_API std::size_t read(void* buffer, std::size_t count);
// Attempts to write count bytes from the specified buffer to the file.
- FMT_API std::size_t write(const void *buffer, std::size_t count);
+ FMT_API std::size_t write(const void* buffer, std::size_t count);
// Duplicates a file descriptor with the dup function and returns
// the duplicate as a file object.
@@ -251,68 +247,59 @@
// Makes fd be the copy of this file descriptor, closing fd first if
// necessary.
- FMT_API void dup2(int fd, error_code &ec) FMT_NOEXCEPT;
+ FMT_API void dup2(int fd, error_code& ec) FMT_NOEXCEPT;
// Creates a pipe setting up read_end and write_end file objects for reading
// and writing respectively.
- FMT_API static void pipe(file &read_end, file &write_end);
+ FMT_API static void pipe(file& read_end, file& write_end);
// Creates a buffered_file object associated with this file and detaches
// this file object from the file.
- FMT_API buffered_file fdopen(const char *mode);
+ FMT_API buffered_file fdopen(const char* mode);
};
// Returns the memory page size.
long getpagesize();
-#if (defined(LC_NUMERIC_MASK) || defined(_MSC_VER)) && \
- !defined(__ANDROID__) && !defined(__CYGWIN__) && !defined(__OpenBSD__) && \
- !defined(__NEWLIB_H__)
-# define FMT_LOCALE
-#endif
-
#ifdef FMT_LOCALE
// A "C" numeric locale.
class Locale {
private:
-# ifdef _MSC_VER
- typedef _locale_t locale_t;
+# ifdef _WIN32
+ using locale_t = _locale_t;
enum { LC_NUMERIC_MASK = LC_NUMERIC };
- static locale_t newlocale(int category_mask, const char *locale, locale_t) {
+ static locale_t newlocale(int category_mask, const char* locale, locale_t) {
return _create_locale(category_mask, locale);
}
- static void freelocale(locale_t locale) {
- _free_locale(locale);
- }
+ static void freelocale(locale_t locale) { _free_locale(locale); }
- static double strtod_l(const char *nptr, char **endptr, _locale_t locale) {
+ static double strtod_l(const char* nptr, char** endptr, _locale_t locale) {
return _strtod_l(nptr, endptr, locale);
}
-# endif
+# endif
locale_t locale_;
- Locale(const Locale &) = delete;
- void operator=(const Locale &) = delete;
+ Locale(const Locale&) = delete;
+ void operator=(const Locale&) = delete;
public:
- typedef locale_t Type;
+ using type = locale_t;
- Locale() : locale_(newlocale(LC_NUMERIC_MASK, "C", FMT_NULL)) {
- if (!locale_)
- FMT_THROW(system_error(errno, "cannot create locale"));
+ Locale() : locale_(newlocale(LC_NUMERIC_MASK, "C", nullptr)) {
+ if (!locale_) FMT_THROW(system_error(errno, "cannot create locale"));
}
~Locale() { freelocale(locale_); }
- Type get() const { return locale_; }
+ type get() const { return locale_; }
// Converts string to floating-point number and advances str past the end
// of the parsed input.
- double strtod(const char *&str) const {
- char *end = FMT_NULL;
+ double strtod(const char*& str) const {
+ char* end = nullptr;
double result = strtod_l(str, &end, locale_);
str = end;
return result;
diff --git a/include/fmt/printf.h b/include/fmt/printf.h
index 6f2715d..c803aa9 100644
--- a/include/fmt/printf.h
+++ b/include/fmt/printf.h
@@ -16,221 +16,90 @@
FMT_BEGIN_NAMESPACE
namespace internal {
-// 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 <typename Char>
-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 <typename Range>
- 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_ : Char();
- }
-
- 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<Char> but the latter
- // doesn't compile by gcc 5.1 due to a compiler bug.
- template <typename CharT>
- friend FMT_CONSTEXPR_DECL const CharT *pointer_from(
- null_terminating_iterator<CharT> it);
-
- private:
- const Char *ptr_;
- const Char *end_;
-};
-
-template <typename T>
-FMT_CONSTEXPR const T *pointer_from(const T *p) { return p; }
-
-template <typename Char>
-FMT_CONSTEXPR const Char *pointer_from(null_terminating_iterator<Char> it) {
- return it.ptr_;
-}
-
-// 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 <typename Iterator, typename ErrorHandler>
-FMT_CONSTEXPR unsigned parse_nonnegative_int(Iterator &it, ErrorHandler &&eh) {
- assert('0' <= *it && *it <= '9');
- if (*it == '0') {
- ++it;
- return 0;
- }
- unsigned value = 0;
- // Convert to unsigned to prevent a warning.
- unsigned max_int = (std::numeric_limits<int>::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;
-}
+// A helper function to suppress bogus "conditional expression is constant"
+// warnings.
+template <typename T> inline T const_check(T value) { return value; }
// Checks if a value fits in int - used to avoid warnings about comparing
// signed and unsigned integers.
-template <bool IsSigned>
-struct int_checker {
- template <typename T>
- static bool fits_in_int(T value) {
+template <bool IsSigned> struct int_checker {
+ template <typename T> static bool fits_in_int(T value) {
unsigned max = std::numeric_limits<int>::max();
return value <= max;
}
static bool fits_in_int(bool) { return true; }
};
-template <>
-struct int_checker<true> {
- template <typename T>
- static bool fits_in_int(T value) {
+template <> struct int_checker<true> {
+ template <typename T> static bool fits_in_int(T value) {
return value >= std::numeric_limits<int>::min() &&
value <= std::numeric_limits<int>::max();
}
static bool fits_in_int(int) { return true; }
};
-class printf_precision_handler: public function<int> {
+class printf_precision_handler {
public:
- template <typename T>
- typename std::enable_if<std::is_integral<T>::value, int>::type
- operator()(T value) {
+ template <typename T, FMT_ENABLE_IF(std::is_integral<T>::value)>
+ int operator()(T value) {
if (!int_checker<std::numeric_limits<T>::is_signed>::fits_in_int(value))
FMT_THROW(format_error("number is too big"));
- return static_cast<int>(value);
+ return (std::max)(static_cast<int>(value), 0);
}
- template <typename T>
- typename std::enable_if<!std::is_integral<T>::value, int>::type operator()(T) {
+ template <typename T, FMT_ENABLE_IF(!std::is_integral<T>::value)>
+ int operator()(T) {
FMT_THROW(format_error("precision is not integer"));
return 0;
}
};
// An argument visitor that returns true iff arg is a zero integer.
-class is_zero_int: public function<bool> {
+class is_zero_int {
public:
- template <typename T>
- typename std::enable_if<std::is_integral<T>::value, bool>::type
- operator()(T value) { return value == 0; }
-
- template <typename T>
- typename std::enable_if<!std::is_integral<T>::value, bool>::type
- operator()(T) { return false; }
-};
-
-template <typename T>
-struct make_unsigned_or_bool : std::make_unsigned<T> {};
-
-template <>
-struct make_unsigned_or_bool<bool> {
- typedef bool type;
-};
-
-template <typename T, typename Context>
-class arg_converter: public function<void> {
- private:
- typedef typename Context::char_type Char;
-
- basic_format_arg<Context> &arg_;
- typename Context::char_type type_;
-
- public:
- arg_converter(basic_format_arg<Context> &arg, Char type)
- : arg_(arg), type_(type) {}
-
- void operator()(bool value) {
- if (type_ != 's')
- operator()<bool>(value);
+ template <typename T, FMT_ENABLE_IF(std::is_integral<T>::value)>
+ bool operator()(T value) {
+ return value == 0;
}
- template <typename U>
- typename std::enable_if<std::is_integral<U>::value>::type
- operator()(U value) {
+ template <typename T, FMT_ENABLE_IF(!std::is_integral<T>::value)>
+ bool operator()(T) {
+ return false;
+ }
+};
+
+template <typename T> struct make_unsigned_or_bool : std::make_unsigned<T> {};
+
+template <> struct make_unsigned_or_bool<bool> { using type = bool; };
+
+template <typename T, typename Context> class arg_converter {
+ private:
+ using char_type = typename Context::char_type;
+
+ basic_format_arg<Context>& arg_;
+ char_type type_;
+
+ public:
+ arg_converter(basic_format_arg<Context>& arg, char_type type)
+ : arg_(arg), type_(type) {}
+
+ void operator()(bool value) {
+ if (type_ != 's') operator()<bool>(value);
+ }
+
+ template <typename U, FMT_ENABLE_IF(std::is_integral<U>::value)>
+ void operator()(U value) {
bool is_signed = type_ == 'd' || type_ == 'i';
- typedef typename std::conditional<
- std::is_same<T, void>::value, U, T>::type TargetType;
- if (const_check(sizeof(TargetType) <= sizeof(int))) {
+ using target_type = conditional_t<std::is_same<T, void>::value, U, T>;
+ if (const_check(sizeof(target_type) <= sizeof(int))) {
// Extra casts are used to silence warnings.
if (is_signed) {
arg_ = internal::make_arg<Context>(
- static_cast<int>(static_cast<TargetType>(value)));
+ static_cast<int>(static_cast<target_type>(value)));
} else {
- typedef typename make_unsigned_or_bool<TargetType>::type Unsigned;
+ using unsigned_type = typename make_unsigned_or_bool<target_type>::type;
arg_ = internal::make_arg<Context>(
- static_cast<unsigned>(static_cast<Unsigned>(value)));
+ static_cast<unsigned>(static_cast<unsigned_type>(value)));
}
} else {
if (is_signed) {
@@ -240,15 +109,13 @@
arg_ = internal::make_arg<Context>(static_cast<long long>(value));
} else {
arg_ = internal::make_arg<Context>(
- static_cast<typename make_unsigned_or_bool<U>::type>(value));
+ static_cast<typename make_unsigned_or_bool<U>::type>(value));
}
}
}
- template <typename U>
- typename std::enable_if<!std::is_integral<U>::value>::type operator()(U) {
- // No coversion needed for non-integral types.
- }
+ template <typename U, FMT_ENABLE_IF(!std::is_integral<U>::value)>
+ void operator()(U) {} // No conversion needed for non-integral types.
};
// Converts an integer argument to T for printf, if T is an integral type.
@@ -256,84 +123,77 @@
// type depending on the type specifier: 'd' and 'i' - signed, other -
// unsigned).
template <typename T, typename Context, typename Char>
-void convert_arg(basic_format_arg<Context> &arg, Char type) {
+void convert_arg(basic_format_arg<Context>& arg, Char type) {
visit_format_arg(arg_converter<T, Context>(arg, type), arg);
}
// Converts an integer argument to char for printf.
-template <typename Context>
-class char_converter: public function<void> {
+template <typename Context> class char_converter {
private:
- basic_format_arg<Context> &arg_;
+ basic_format_arg<Context>& arg_;
public:
- explicit char_converter(basic_format_arg<Context> &arg) : arg_(arg) {}
+ explicit char_converter(basic_format_arg<Context>& arg) : arg_(arg) {}
- template <typename T>
- typename std::enable_if<std::is_integral<T>::value>::type
- operator()(T value) {
- typedef typename Context::char_type Char;
- arg_ = internal::make_arg<Context>(static_cast<Char>(value));
+ template <typename T, FMT_ENABLE_IF(std::is_integral<T>::value)>
+ void operator()(T value) {
+ arg_ = internal::make_arg<Context>(
+ static_cast<typename Context::char_type>(value));
}
- template <typename T>
- typename std::enable_if<!std::is_integral<T>::value>::type operator()(T) {
- // No coversion needed for non-integral types.
- }
+ template <typename T, FMT_ENABLE_IF(!std::is_integral<T>::value)>
+ void operator()(T) {} // No conversion needed for non-integral types.
};
// Checks if an argument is a valid printf width specifier and sets
// left alignment if it is negative.
-template <typename Char>
-class printf_width_handler: public function<unsigned> {
+template <typename Char> class printf_width_handler {
private:
- typedef basic_format_specs<Char> format_specs;
+ using format_specs = basic_format_specs<Char>;
- format_specs &spec_;
+ format_specs& specs_;
public:
- explicit printf_width_handler(format_specs &spec) : spec_(spec) {}
+ explicit printf_width_handler(format_specs& specs) : specs_(specs) {}
- template <typename T>
- typename std::enable_if<std::is_integral<T>::value, unsigned>::type
- operator()(T value) {
- typedef typename internal::int_traits<T>::main_type UnsignedType;
- UnsignedType width = static_cast<UnsignedType>(value);
+ template <typename T, FMT_ENABLE_IF(std::is_integral<T>::value)>
+ unsigned operator()(T value) {
+ auto width = static_cast<uint32_or_64_t<T>>(value);
if (internal::is_negative(value)) {
- spec_.align_ = ALIGN_LEFT;
+ specs_.align = align::left;
width = 0 - width;
}
unsigned int_max = std::numeric_limits<int>::max();
- if (width > int_max)
- FMT_THROW(format_error("number is too big"));
+ if (width > int_max) FMT_THROW(format_error("number is too big"));
return static_cast<unsigned>(width);
}
- template <typename T>
- typename std::enable_if<!std::is_integral<T>::value, unsigned>::type
- operator()(T) {
+ template <typename T, FMT_ENABLE_IF(!std::is_integral<T>::value)>
+ unsigned operator()(T) {
FMT_THROW(format_error("width is not integer"));
return 0;
}
};
template <typename Char, typename Context>
-void printf(basic_buffer<Char> &buf, basic_string_view<Char> format,
+void printf(buffer<Char>& buf, basic_string_view<Char> format,
basic_format_args<Context> args) {
Context(std::back_inserter(buf), format, args).format();
}
+
+template <typename OutputIt, typename Char, typename Context>
+internal::truncating_iterator<OutputIt> printf(
+ internal::truncating_iterator<OutputIt> it, basic_string_view<Char> format,
+ basic_format_args<Context> args) {
+ return Context(it, format, args).format();
+}
} // namespace internal
using internal::printf; // For printing into memory_buffer.
-template <typename Range>
-class printf_arg_formatter;
+template <typename Range> class printf_arg_formatter;
-template <
- typename OutputIt, typename Char,
- typename ArgFormatter =
- printf_arg_formatter<back_insert_range<internal::basic_buffer<Char>>>>
-class basic_printf_context;
+template <typename OutputIt, typename Char> class basic_printf_context;
/**
\rst
@@ -341,61 +201,56 @@
\endrst
*/
template <typename Range>
-class printf_arg_formatter:
- public internal::function<
- typename internal::arg_formatter_base<Range>::iterator>,
- public internal::arg_formatter_base<Range> {
- private:
- typedef typename Range::value_type char_type;
- typedef decltype(internal::declval<Range>().begin()) iterator;
- typedef internal::arg_formatter_base<Range> base;
- typedef basic_printf_context<iterator, char_type> context_type;
+class printf_arg_formatter : public internal::arg_formatter_base<Range> {
+ public:
+ using iterator = typename Range::iterator;
- context_type &context_;
+ private:
+ using char_type = typename Range::value_type;
+ using base = internal::arg_formatter_base<Range>;
+ using context_type = basic_printf_context<iterator, char_type>;
+
+ context_type& context_;
void write_null_pointer(char) {
- this->spec()->type = 0;
+ this->specs()->type = 0;
this->write("(nil)");
}
void write_null_pointer(wchar_t) {
- this->spec()->type = 0;
+ this->specs()->type = 0;
this->write(L"(nil)");
}
public:
- typedef typename base::format_specs format_specs;
+ using format_specs = typename base::format_specs;
/**
\rst
Constructs an argument formatter object.
- *buffer* is a reference to the output buffer and *spec* contains format
+ *buffer* is a reference to the output buffer and *specs* contains format
specifier information for standard argument types.
\endrst
*/
- printf_arg_formatter(internal::basic_buffer<char_type> &buffer,
- format_specs &spec, context_type &ctx)
- : base(back_insert_range<internal::basic_buffer<char_type>>(buffer), &spec,
- ctx.locale()),
- context_(ctx) {}
+ printf_arg_formatter(iterator iter, format_specs& specs, context_type& ctx)
+ : base(Range(iter), &specs, internal::locale_ref()), context_(ctx) {}
- template <typename T>
- typename std::enable_if<std::is_integral<T>::value, iterator>::type
- operator()(T value) {
+ template <typename T, FMT_ENABLE_IF(std::is_integral<T>::value)>
+ iterator operator()(T value) {
// MSVC2013 fails to compile separate overloads for bool and char_type so
// use std::is_same instead.
if (std::is_same<T, bool>::value) {
- format_specs &fmt_spec = *this->spec();
- if (fmt_spec.type != 's')
- return base::operator()(value ? 1 : 0);
- fmt_spec.type = 0;
+ format_specs& fmt_specs = *this->specs();
+ if (fmt_specs.type != 's') return base::operator()(value ? 1 : 0);
+ fmt_specs.type = 0;
this->write(value != 0);
} else if (std::is_same<T, char_type>::value) {
- format_specs &fmt_spec = *this->spec();
- if (fmt_spec.type && fmt_spec.type != 'c')
+ format_specs& fmt_specs = *this->specs();
+ if (fmt_specs.type && fmt_specs.type != 'c')
return (*this)(static_cast<int>(value));
- fmt_spec.flags = 0;
- fmt_spec.align_ = ALIGN_RIGHT;
+ fmt_specs.sign = sign::none;
+ fmt_specs.alt = false;
+ fmt_specs.align = align::right;
return base::operator()(value);
} else {
return base::operator()(value);
@@ -403,17 +258,16 @@
return this->out();
}
- template <typename T>
- typename std::enable_if<std::is_floating_point<T>::value, iterator>::type
- operator()(T value) {
+ template <typename T, FMT_ENABLE_IF(std::is_floating_point<T>::value)>
+ iterator operator()(T value) {
return base::operator()(value);
}
/** Formats a null-terminated C string. */
- iterator operator()(const char *value) {
+ iterator operator()(const char* value) {
if (value)
base::operator()(value);
- else if (this->spec()->type == 'p')
+ else if (this->specs()->type == 'p')
write_null_pointer(char_type());
else
this->write("(null)");
@@ -421,10 +275,10 @@
}
/** Formats a null-terminated wide C string. */
- iterator operator()(const wchar_t *value) {
+ iterator operator()(const wchar_t* value) {
if (value)
base::operator()(value);
- else if (this->spec()->type == 'p')
+ else if (this->specs()->type == 'p')
write_null_pointer(char_type());
else
this->write(L"(null)");
@@ -435,68 +289,60 @@
return base::operator()(value);
}
- iterator operator()(monostate value) {
- return base::operator()(value);
- }
+ iterator operator()(monostate value) { return base::operator()(value); }
/** Formats a pointer. */
- iterator operator()(const void *value) {
- if (value)
- return base::operator()(value);
- this->spec()->type = 0;
+ iterator operator()(const void* value) {
+ if (value) return base::operator()(value);
+ this->specs()->type = 0;
write_null_pointer(char_type());
return this->out();
}
/** Formats an argument of a custom (user-defined) type. */
iterator operator()(typename basic_format_arg<context_type>::handle handle) {
- handle.format(context_);
+ handle.format(context_.parse_context(), context_);
return this->out();
}
};
-template <typename T>
-struct printf_formatter {
+template <typename T> struct printf_formatter {
template <typename ParseContext>
- auto parse(ParseContext &ctx) -> decltype(ctx.begin()) { return ctx.begin(); }
+ auto parse(ParseContext& ctx) -> decltype(ctx.begin()) {
+ return ctx.begin();
+ }
template <typename FormatContext>
- auto format(const T &value, FormatContext &ctx) -> decltype(ctx.out()) {
+ auto format(const T& value, FormatContext& ctx) -> decltype(ctx.out()) {
internal::format_value(internal::get_container(ctx.out()), value);
return ctx.out();
}
};
/** This template formats data and writes the output to a writer. */
-template <typename OutputIt, typename Char, typename ArgFormatter>
-class basic_printf_context :
- // Inherit publicly as a workaround for the icc bug
- // https://software.intel.com/en-us/forums/intel-c-compiler/topic/783476.
- public internal::context_base<
- OutputIt, basic_printf_context<OutputIt, Char, ArgFormatter>, Char> {
+template <typename OutputIt, typename Char> class basic_printf_context {
public:
/** The character type for the output. */
- typedef Char char_type;
-
- template <typename T>
- struct formatter_type { typedef printf_formatter<T> type; };
+ using char_type = Char;
+ using format_arg = basic_format_arg<basic_printf_context>;
+ template <typename T> using formatter_type = printf_formatter<T>;
private:
- typedef internal::context_base<OutputIt, basic_printf_context, Char> base;
- typedef typename base::format_arg format_arg;
- typedef basic_format_specs<char_type> format_specs;
- typedef internal::null_terminating_iterator<char_type> iterator;
+ using format_specs = basic_format_specs<char_type>;
- void parse_flags(format_specs &spec, iterator &it);
+ OutputIt out_;
+ basic_format_args<basic_printf_context> args_;
+ basic_parse_context<Char> parse_ctx_;
+
+ static void parse_flags(format_specs& specs, const Char*& it,
+ const Char* end);
// Returns the argument with specified index or, if arg_index is equal
// to the maximum unsigned value, the next argument.
- format_arg get_arg(
- iterator it,
- unsigned arg_index = (std::numeric_limits<unsigned>::max)());
+ format_arg get_arg(unsigned arg_index = std::numeric_limits<unsigned>::max());
// Parses argument index, flags and width and returns the argument index.
- unsigned parse_header(iterator &it, format_specs &spec);
+ unsigned parse_header(const Char*& it, const Char* end, format_specs& specs);
public:
/**
@@ -508,160 +354,180 @@
*/
basic_printf_context(OutputIt out, basic_string_view<char_type> format_str,
basic_format_args<basic_printf_context> args)
- : base(out, format_str, args) {}
+ : out_(out), args_(args), parse_ctx_(format_str) {}
- using base::parse_context;
- using base::out;
- using base::advance_to;
+ OutputIt out() { return out_; }
+ void advance_to(OutputIt it) { out_ = it; }
+
+ format_arg arg(unsigned id) const { return args_.get(id); }
+
+ basic_parse_context<Char>& parse_context() { return parse_ctx_; }
+
+ FMT_CONSTEXPR void on_error(const char* message) {
+ parse_ctx_.on_error(message);
+ }
/** Formats stored arguments and writes the output to the range. */
- void format();
+ template <typename ArgFormatter =
+ printf_arg_formatter<internal::buffer_range<Char>>>
+ OutputIt format();
};
-template <typename OutputIt, typename Char, typename AF>
-void basic_printf_context<OutputIt, Char, AF>::parse_flags(
- format_specs &spec, iterator &it) {
- for (;;) {
- switch (*it++) {
- case '-':
- spec.align_ = ALIGN_LEFT;
- break;
- case '+':
- spec.flags |= SIGN_FLAG | PLUS_FLAG;
- break;
- case '0':
- spec.fill_ = '0';
- break;
- case ' ':
- spec.flags |= SIGN_FLAG;
- break;
- case '#':
- spec.flags |= HASH_FLAG;
- break;
- default:
- --it;
- return;
+template <typename OutputIt, typename Char>
+void basic_printf_context<OutputIt, Char>::parse_flags(format_specs& specs,
+ const Char*& it,
+ const Char* end) {
+ for (; it != end; ++it) {
+ switch (*it) {
+ case '-':
+ specs.align = align::left;
+ break;
+ case '+':
+ specs.sign = sign::plus;
+ break;
+ case '0':
+ specs.fill[0] = '0';
+ break;
+ case ' ':
+ specs.sign = sign::space;
+ break;
+ case '#':
+ specs.alt = true;
+ break;
+ default:
+ return;
}
}
}
-template <typename OutputIt, typename Char, typename AF>
-typename basic_printf_context<OutputIt, Char, AF>::format_arg
- basic_printf_context<OutputIt, Char, AF>::get_arg(
- iterator it, unsigned arg_index) {
- (void)it;
+template <typename OutputIt, typename Char>
+typename basic_printf_context<OutputIt, Char>::format_arg
+basic_printf_context<OutputIt, Char>::get_arg(unsigned arg_index) {
if (arg_index == std::numeric_limits<unsigned>::max())
- return this->do_get_arg(this->parse_context().next_arg_id());
- return base::get_arg(arg_index - 1);
+ arg_index = parse_ctx_.next_arg_id();
+ else
+ parse_ctx_.check_arg_id(--arg_index);
+ return internal::get_arg(*this, arg_index);
}
-template <typename OutputIt, typename Char, typename AF>
-unsigned basic_printf_context<OutputIt, Char, AF>::parse_header(
- iterator &it, format_specs &spec) {
+template <typename OutputIt, typename Char>
+unsigned basic_printf_context<OutputIt, Char>::parse_header(
+ const Char*& it, const Char* end, format_specs& specs) {
unsigned arg_index = std::numeric_limits<unsigned>::max();
char_type c = *it;
if (c >= '0' && c <= '9') {
// Parse an argument index (if followed by '$') or a width possibly
// preceded with '0' flag(s).
internal::error_handler eh;
- unsigned value = parse_nonnegative_int(it, eh);
- if (*it == '$') { // value is an argument index
+ unsigned value = parse_nonnegative_int(it, end, eh);
+ if (it != end && *it == '$') { // value is an argument index
++it;
arg_index = value;
} else {
- if (c == '0')
- spec.fill_ = '0';
+ if (c == '0') specs.fill[0] = '0';
if (value != 0) {
// Nonzero value means that we parsed width and don't need to
// parse it or flags again, so return now.
- spec.width_ = value;
+ specs.width = value;
return arg_index;
}
}
}
- parse_flags(spec, it);
+ parse_flags(specs, it, end);
// Parse width.
- if (*it >= '0' && *it <= '9') {
- internal::error_handler eh;
- spec.width_ = parse_nonnegative_int(it, eh);
- } else if (*it == '*') {
- ++it;
- spec.width_ = visit_format_arg(
- internal::printf_width_handler<char_type>(spec), get_arg(it));
+ if (it != end) {
+ if (*it >= '0' && *it <= '9') {
+ internal::error_handler eh;
+ specs.width = parse_nonnegative_int(it, end, eh);
+ } else if (*it == '*') {
+ ++it;
+ specs.width = visit_format_arg(
+ internal::printf_width_handler<char_type>(specs), get_arg());
+ }
}
return arg_index;
}
-template <typename OutputIt, typename Char, typename AF>
-void basic_printf_context<OutputIt, Char, AF>::format() {
- auto &buffer = internal::get_container(this->out());
- auto start = iterator(this->parse_context());
+template <typename OutputIt, typename Char>
+template <typename ArgFormatter>
+OutputIt basic_printf_context<OutputIt, Char>::format() {
+ auto out = this->out();
+ const Char* start = parse_ctx_.begin();
+ const Char* end = parse_ctx_.end();
auto it = start;
- using internal::pointer_from;
- while (*it) {
+ while (it != end) {
char_type c = *it++;
if (c != '%') continue;
- if (*it == c) {
- buffer.append(pointer_from(start), pointer_from(it));
+ if (it != end && *it == c) {
+ out = std::copy(start, it, out);
start = ++it;
continue;
}
- buffer.append(pointer_from(start), pointer_from(it) - 1);
+ out = std::copy(start, it - 1, out);
- format_specs spec;
- spec.align_ = ALIGN_RIGHT;
+ format_specs specs;
+ specs.align = align::right;
// Parse argument index, flags and width.
- unsigned arg_index = parse_header(it, spec);
+ unsigned arg_index = parse_header(it, end, specs);
// Parse precision.
- if (*it == '.') {
+ if (it != end && *it == '.') {
++it;
- if ('0' <= *it && *it <= '9') {
+ c = it != end ? *it : 0;
+ if ('0' <= c && c <= '9') {
internal::error_handler eh;
- spec.precision = static_cast<int>(parse_nonnegative_int(it, eh));
- } else if (*it == '*') {
+ specs.precision = static_cast<int>(parse_nonnegative_int(it, end, eh));
+ } else if (c == '*') {
++it;
- spec.precision =
- visit_format_arg(internal::printf_precision_handler(), get_arg(it));
+ specs.precision =
+ visit_format_arg(internal::printf_precision_handler(), get_arg());
} else {
- spec.precision = 0;
+ specs.precision = 0;
}
}
- format_arg arg = get_arg(it, arg_index);
- if (spec.has(HASH_FLAG) && visit_format_arg(internal::is_zero_int(), arg))
- spec.flags = static_cast<uint_least8_t>(spec.flags & (~internal::to_unsigned<int>(HASH_FLAG)));
- if (spec.fill_ == '0') {
+ format_arg arg = get_arg(arg_index);
+ if (specs.alt && visit_format_arg(internal::is_zero_int(), arg))
+ specs.alt = false;
+ if (specs.fill[0] == '0') {
if (arg.is_arithmetic())
- spec.align_ = ALIGN_NUMERIC;
+ specs.align = align::numeric;
else
- spec.fill_ = ' '; // Ignore '0' flag for non-numeric types.
+ specs.fill[0] = ' '; // Ignore '0' flag for non-numeric types.
}
// Parse length and convert the argument to the required type.
+ c = it != end ? *it++ : 0;
+ char_type t = it != end ? *it : 0;
using internal::convert_arg;
- switch (*it++) {
+ switch (c) {
case 'h':
- if (*it == 'h')
- convert_arg<signed char>(arg, *++it);
- else
- convert_arg<short>(arg, *it);
+ if (t == 'h') {
+ ++it;
+ t = it != end ? *it : 0;
+ convert_arg<signed char>(arg, t);
+ } else {
+ convert_arg<short>(arg, t);
+ }
break;
case 'l':
- if (*it == 'l')
- convert_arg<long long>(arg, *++it);
- else
- convert_arg<long>(arg, *it);
+ if (t == 'l') {
+ ++it;
+ t = it != end ? *it : 0;
+ convert_arg<long long>(arg, t);
+ } else {
+ convert_arg<long>(arg, t);
+ }
break;
case 'j':
- convert_arg<intmax_t>(arg, *it);
+ convert_arg<intmax_t>(arg, t);
break;
case 'z':
- convert_arg<std::size_t>(arg, *it);
+ convert_arg<std::size_t>(arg, t);
break;
case 't':
- convert_arg<std::ptrdiff_t>(arg, *it);
+ convert_arg<std::ptrdiff_t>(arg, t);
break;
case 'L':
// printf produces garbage when 'L' is omitted for long double, no
@@ -669,23 +535,22 @@
break;
default:
--it;
- convert_arg<void>(arg, *it);
+ convert_arg<void>(arg, c);
}
// Parse type.
- if (!*it)
- FMT_THROW(format_error("invalid format string"));
- spec.type = static_cast<char>(*it++);
+ if (it == end) FMT_THROW(format_error("invalid format string"));
+ specs.type = static_cast<char>(*it++);
if (arg.is_integral()) {
// Normalize type.
- switch (spec.type) {
- case 'i': case 'u':
- spec.type = 'd';
+ switch (specs.type) {
+ case 'i':
+ case 'u':
+ specs.type = 'd';
break;
case 'c':
- // TODO: handle wchar_t better?
- visit_format_arg(
- internal::char_converter<basic_printf_context>(arg), arg);
+ visit_format_arg(internal::char_converter<basic_printf_context>(arg),
+ arg);
break;
}
}
@@ -693,48 +558,49 @@
start = it;
// Format argument.
- visit_format_arg(AF(buffer, spec, *this), arg);
+ visit_format_arg(ArgFormatter(out, specs, *this), arg);
}
- buffer.append(pointer_from(start), pointer_from(it));
+ return std::copy(start, it, out);
}
-template <typename Buffer>
-struct basic_printf_context_t {
- typedef basic_printf_context<
- std::back_insert_iterator<Buffer>, typename Buffer::value_type> type;
-};
+template <typename Char>
+using basic_printf_context_t =
+ basic_printf_context<std::back_insert_iterator<internal::buffer<Char>>,
+ Char>;
-typedef basic_printf_context_t<internal::buffer>::type printf_context;
-typedef basic_printf_context_t<internal::wbuffer>::type wprintf_context;
+using printf_context = basic_printf_context_t<char>;
+using wprintf_context = basic_printf_context_t<wchar_t>;
-typedef basic_format_args<printf_context> printf_args;
-typedef basic_format_args<wprintf_context> wprintf_args;
+using printf_args = basic_format_args<printf_context>;
+using wprintf_args = basic_format_args<wprintf_context>;
/**
\rst
Constructs an `~fmt::format_arg_store` object that contains references to
- arguments and can be implicitly converted to `~fmt::printf_args`.
+ arguments and can be implicitly converted to `~fmt::printf_args`.
\endrst
*/
-template<typename... Args>
-inline format_arg_store<printf_context, Args...>
- make_printf_args(const Args &... args) { return {args...}; }
+template <typename... Args>
+inline format_arg_store<printf_context, Args...> make_printf_args(
+ const Args&... args) {
+ return {args...};
+}
/**
\rst
Constructs an `~fmt::format_arg_store` object that contains references to
- arguments and can be implicitly converted to `~fmt::wprintf_args`.
+ arguments and can be implicitly converted to `~fmt::wprintf_args`.
\endrst
*/
-template<typename... Args>
-inline format_arg_store<wprintf_context, Args...>
- make_wprintf_args(const Args &... args) { return {args...}; }
+template <typename... Args>
+inline format_arg_store<wprintf_context, Args...> make_wprintf_args(
+ const Args&... args) {
+ return {args...};
+}
-template <typename S, typename Char = FMT_CHAR(S)>
-inline std::basic_string<Char>
-vsprintf(const S &format,
- basic_format_args<typename basic_printf_context_t<
- internal::basic_buffer<Char>>::type> args) {
+template <typename S, typename Char = char_t<S>>
+inline std::basic_string<Char> vsprintf(
+ const S& format, basic_format_args<basic_printf_context_t<Char>> args) {
basic_memory_buffer<Char> buffer;
printf(buffer, to_string_view(format), args);
return to_string(buffer);
@@ -749,27 +615,22 @@
std::string message = fmt::sprintf("The answer is %d", 42);
\endrst
*/
-template <typename S, typename... Args>
-inline FMT_ENABLE_IF_T(
- internal::is_string<S>::value, std::basic_string<FMT_CHAR(S)>)
- sprintf(const S &format, const Args & ... args) {
- internal::check_format_string<Args...>(format);
- typedef internal::basic_buffer<FMT_CHAR(S)> buffer;
- typedef typename basic_printf_context_t<buffer>::type context;
- format_arg_store<context, Args...> as{ args... };
- return vsprintf(to_string_view(format),
- basic_format_args<context>(as));
+template <typename S, typename... Args,
+ typename Char = enable_if_t<internal::is_string<S>::value, char_t<S>>>
+inline std::basic_string<Char> sprintf(const S& format, const Args&... args) {
+ using context = basic_printf_context_t<Char>;
+ return vsprintf(to_string_view(format), {make_format_args<context>(args...)});
}
-template <typename S, typename Char = FMT_CHAR(S)>
-inline int vfprintf(std::FILE *f, const S &format,
- basic_format_args<typename basic_printf_context_t<
- internal::basic_buffer<Char>>::type> args) {
+template <typename S, typename Char = char_t<S>>
+inline int vfprintf(std::FILE* f, const S& format,
+ basic_format_args<basic_printf_context_t<Char>> args) {
basic_memory_buffer<Char> buffer;
printf(buffer, to_string_view(format), args);
std::size_t size = buffer.size();
- return std::fwrite(
- buffer.data(), sizeof(Char), size, f) < size ? -1 : static_cast<int>(size);
+ return std::fwrite(buffer.data(), sizeof(Char), size, f) < size
+ ? -1
+ : static_cast<int>(size);
}
/**
@@ -781,21 +642,17 @@
fmt::fprintf(stderr, "Don't %s!", "panic");
\endrst
*/
-template <typename S, typename... Args>
-inline FMT_ENABLE_IF_T(internal::is_string<S>::value, int)
- fprintf(std::FILE *f, const S &format, const Args & ... args) {
- internal::check_format_string<Args...>(format);
- typedef internal::basic_buffer<FMT_CHAR(S)> buffer;
- typedef typename basic_printf_context_t<buffer>::type context;
- format_arg_store<context, Args...> as{ args... };
+template <typename S, typename... Args,
+ typename Char = enable_if_t<internal::is_string<S>::value, char_t<S>>>
+inline int fprintf(std::FILE* f, const S& format, const Args&... args) {
+ using context = basic_printf_context_t<Char>;
return vfprintf(f, to_string_view(format),
- basic_format_args<context>(as));
+ {make_format_args<context>(args...)});
}
-template <typename S, typename Char = FMT_CHAR(S)>
-inline int vprintf(const S &format,
- basic_format_args<typename basic_printf_context_t<
- internal::basic_buffer<Char>>::type> args) {
+template <typename S, typename Char = char_t<S>>
+inline int vprintf(const S& format,
+ basic_format_args<basic_printf_context_t<Char>> args) {
return vfprintf(stdout, to_string_view(format), args);
}
@@ -808,28 +665,35 @@
fmt::printf("Elapsed time: %.2f seconds", 1.23);
\endrst
*/
-template <typename S, typename... Args>
-inline FMT_ENABLE_IF_T(internal::is_string<S>::value, int)
- printf(const S &format_str, const Args & ... args) {
- internal::check_format_string<Args...>(format_str);
- typedef internal::basic_buffer<FMT_CHAR(S)> buffer;
- typedef typename basic_printf_context_t<buffer>::type context;
- format_arg_store<context, Args...> as{ args... };
+template <typename S, typename... Args,
+ FMT_ENABLE_IF(internal::is_string<S>::value)>
+inline int printf(const S& format_str, const Args&... args) {
+ using context = basic_printf_context_t<char_t<S>>;
return vprintf(to_string_view(format_str),
- basic_format_args<context>(as));
+ {make_format_args<context>(args...)});
}
-template <typename S, typename Char = FMT_CHAR(S)>
-inline int vfprintf(std::basic_ostream<Char> &os,
- const S &format,
- basic_format_args<typename basic_printf_context_t<
- internal::basic_buffer<Char>>::type> args) {
+template <typename S, typename Char = char_t<S>>
+inline int vfprintf(std::basic_ostream<Char>& os, const S& format,
+ basic_format_args<basic_printf_context_t<Char>> args) {
basic_memory_buffer<Char> buffer;
printf(buffer, to_string_view(format), args);
internal::write(os, buffer);
return static_cast<int>(buffer.size());
}
+/** Formats arguments and writes the output to the range. */
+template <typename ArgFormatter, typename Char,
+ typename Context =
+ basic_printf_context<typename ArgFormatter::iterator, Char>>
+typename ArgFormatter::iterator vprintf(internal::buffer<Char>& out,
+ basic_string_view<Char> format_str,
+ basic_format_args<Context> args) {
+ typename ArgFormatter::iterator iter(out);
+ Context(iter, format_str, args).template format<ArgFormatter>();
+ return iter;
+}
+
/**
\rst
Prints formatted data to the stream *os*.
@@ -839,16 +703,12 @@
fmt::fprintf(cerr, "Don't %s!", "panic");
\endrst
*/
-template <typename S, typename... Args>
-inline FMT_ENABLE_IF_T(internal::is_string<S>::value, int)
- fprintf(std::basic_ostream<FMT_CHAR(S)> &os,
- const S &format_str, const Args & ... args) {
- internal::check_format_string<Args...>(format_str);
- typedef internal::basic_buffer<FMT_CHAR(S)> buffer;
- typedef typename basic_printf_context_t<buffer>::type context;
- format_arg_store<context, Args...> as{ args... };
+template <typename S, typename... Args, typename Char = char_t<S>>
+inline int fprintf(std::basic_ostream<Char>& os, const S& format_str,
+ const Args&... args) {
+ using context = basic_printf_context_t<Char>;
return vfprintf(os, to_string_view(format_str),
- basic_format_args<context>(as));
+ {make_format_args<context>(args...)});
}
FMT_END_NAMESPACE
diff --git a/include/fmt/ranges.h b/include/fmt/ranges.h
index 3672d4c..cf0d41a 100644
--- a/include/fmt/ranges.h
+++ b/include/fmt/ranges.h
@@ -1,4 +1,4 @@
-// Formatting library for C++ - the core API
+// Formatting library for C++ - experimental range support
//
// Copyright (c) 2012 - present, Victor Zverovich
// All rights reserved.
@@ -12,20 +12,19 @@
#ifndef FMT_RANGES_H_
#define FMT_RANGES_H_
-#include "format.h"
#include <type_traits>
+#include "format.h"
// output only up to N items from the range.
#ifndef FMT_RANGE_OUTPUT_LENGTH_LIMIT
-# define FMT_RANGE_OUTPUT_LENGTH_LIMIT 256
+# define FMT_RANGE_OUTPUT_LENGTH_LIMIT 256
#endif
FMT_BEGIN_NAMESPACE
-template <typename Char>
-struct formatting_base {
+template <typename Char> struct formatting_base {
template <typename ParseContext>
- FMT_CONSTEXPR auto parse(ParseContext &ctx) -> decltype(ctx.begin()) {
+ FMT_CONSTEXPR auto parse(ParseContext& ctx) -> decltype(ctx.begin()) {
return ctx.begin();
}
};
@@ -33,7 +32,8 @@
template <typename Char, typename Enable = void>
struct formatting_range : formatting_base<Char> {
static FMT_CONSTEXPR_DECL const std::size_t range_length_limit =
- FMT_RANGE_OUTPUT_LENGTH_LIMIT; // output only up to N items from the range.
+ FMT_RANGE_OUTPUT_LENGTH_LIMIT; // output only up to N items from the
+ // range.
Char prefix;
Char delimiter;
Char postfix;
@@ -55,87 +55,78 @@
namespace internal {
template <typename RangeT, typename OutputIterator>
-void copy(const RangeT &range, OutputIterator out) {
+OutputIterator copy(const RangeT& range, OutputIterator out) {
for (auto it = range.begin(), end = range.end(); it != end; ++it)
*out++ = *it;
+ return out;
}
template <typename OutputIterator>
-void copy(const char *str, OutputIterator out) {
- const char *p_curr = str;
- while (*p_curr) {
- *out++ = *p_curr++;
- }
+OutputIterator copy(const char* str, OutputIterator out) {
+ while (*str) *out++ = *str++;
+ return out;
}
template <typename OutputIterator>
-void copy(char ch, OutputIterator out) {
+OutputIterator copy(char ch, OutputIterator out) {
*out++ = ch;
+ return out;
}
/// Return true value if T has std::string interface, like std::string_view.
-template <typename T>
-class is_like_std_string {
+template <typename T> class is_like_std_string {
template <typename U>
- static auto check(U *p) ->
- decltype(p->find('a'), p->length(), p->data(), int());
- template <typename>
- static void check(...);
+ static auto check(U* p)
+ -> decltype((void)p->find('a'), p->length(), (void)p->data(), int());
+ template <typename> static void check(...);
public:
static FMT_CONSTEXPR_DECL const bool value =
- !std::is_void<decltype(check<T>(FMT_NULL))>::value;
+ is_string<T>::value || !std::is_void<decltype(check<T>(nullptr))>::value;
};
template <typename Char>
struct is_like_std_string<fmt::basic_string_view<Char>> : std::true_type {};
-template <typename... Ts>
-struct conditional_helper {};
+template <typename... Ts> struct conditional_helper {};
-template <typename T, typename _ = void>
-struct is_range_ : std::false_type {};
+template <typename T, typename _ = void> struct is_range_ : std::false_type {};
#if !FMT_MSC_VER || FMT_MSC_VER > 1800
template <typename T>
-struct is_range_<T, typename std::conditional<
- false,
- conditional_helper<decltype(internal::declval<T>().begin()),
- decltype(internal::declval<T>().end())>,
- void>::type> : std::true_type {};
+struct is_range_<
+ T, conditional_t<false,
+ conditional_helper<decltype(std::declval<T>().begin()),
+ decltype(std::declval<T>().end())>,
+ void>> : std::true_type {};
#endif
/// tuple_size and tuple_element check.
-template <typename T>
-class is_tuple_like_ {
+template <typename T> class is_tuple_like_ {
template <typename U>
- static auto check(U *p) ->
- decltype(std::tuple_size<U>::value,
- internal::declval<typename std::tuple_element<0, U>::type>(), int());
- template <typename>
- static void check(...);
+ static auto check(U* p)
+ -> decltype(std::tuple_size<U>::value,
+ (void)std::declval<typename std::tuple_element<0, U>::type>(),
+ int());
+ template <typename> static void check(...);
public:
static FMT_CONSTEXPR_DECL const bool value =
- !std::is_void<decltype(check<T>(FMT_NULL))>::value;
+ !std::is_void<decltype(check<T>(nullptr))>::value;
};
// Check for integer_sequence
#if defined(__cpp_lib_integer_sequence) || FMT_MSC_VER >= 1900
template <typename T, T... N>
using integer_sequence = std::integer_sequence<T, N...>;
-template <std::size_t... N>
-using index_sequence = std::index_sequence<N...>;
+template <std::size_t... N> using index_sequence = std::index_sequence<N...>;
template <std::size_t N>
using make_index_sequence = std::make_index_sequence<N>;
#else
-template <typename T, T... N>
-struct integer_sequence {
- typedef T value_type;
+template <typename T, T... N> struct integer_sequence {
+ using value_type = T;
- static FMT_CONSTEXPR std::size_t size() {
- return sizeof...(N);
- }
+ static FMT_CONSTEXPR std::size_t size() { return sizeof...(N); }
};
template <std::size_t... N>
@@ -151,7 +142,7 @@
#endif
template <class Tuple, class F, size_t... Is>
-void for_each(index_sequence<Is...>, Tuple &&tup, F &&f) FMT_NOEXCEPT {
+void for_each(index_sequence<Is...>, Tuple&& tup, F&& f) FMT_NOEXCEPT {
using std::get;
// using free function get<I>(T) now.
const int _[] = {0, ((void)f(get<Is>(tup)), 0)...};
@@ -159,26 +150,25 @@
}
template <class T>
-FMT_CONSTEXPR make_index_sequence<std::tuple_size<T>::value>
-get_indexes(T const &) { return {}; }
+FMT_CONSTEXPR make_index_sequence<std::tuple_size<T>::value> get_indexes(
+ T const&) {
+ return {};
+}
-template <class Tuple, class F>
-void for_each(Tuple &&tup, F &&f) {
+template <class Tuple, class F> void for_each(Tuple&& tup, F&& f) {
const auto indexes = get_indexes(tup);
for_each(indexes, std::forward<Tuple>(tup), std::forward<F>(f));
}
-template<typename Arg>
-FMT_CONSTEXPR const char* format_str_quoted(bool add_space, const Arg&,
- typename std::enable_if<
- !is_like_std_string<typename std::decay<Arg>::type>::value>::type* = nullptr) {
+template <typename Arg, FMT_ENABLE_IF(!is_like_std_string<
+ typename std::decay<Arg>::type>::value)>
+FMT_CONSTEXPR const char* format_str_quoted(bool add_space, const Arg&) {
return add_space ? " {}" : "{}";
}
-template<typename Arg>
-FMT_CONSTEXPR const char* format_str_quoted(bool add_space, const Arg&,
- typename std::enable_if<
- is_like_std_string<typename std::decay<Arg>::type>::value>::type* = nullptr) {
+template <typename Arg, FMT_ENABLE_IF(is_like_std_string<
+ typename std::decay<Arg>::type>::value)>
+FMT_CONSTEXPR const char* format_str_quoted(bool add_space, const Arg&) {
return add_space ? " \"{}\"" : "\"{}\"";
}
@@ -186,61 +176,58 @@
return add_space ? " \"{}\"" : "\"{}\"";
}
FMT_CONSTEXPR const wchar_t* format_str_quoted(bool add_space, const wchar_t*) {
- return add_space ? L" \"{}\"" : L"\"{}\"";
+ return add_space ? L" \"{}\"" : L"\"{}\"";
}
FMT_CONSTEXPR const char* format_str_quoted(bool add_space, const char) {
- return add_space ? " '{}'" : "'{}'";
+ return add_space ? " '{}'" : "'{}'";
}
FMT_CONSTEXPR const wchar_t* format_str_quoted(bool add_space, const wchar_t) {
- return add_space ? L" '{}'" : L"'{}'";
+ return add_space ? L" '{}'" : L"'{}'";
}
} // namespace internal
-template <typename T>
-struct is_tuple_like {
+template <typename T> struct is_tuple_like {
static FMT_CONSTEXPR_DECL const bool value =
- internal::is_tuple_like_<T>::value && !internal::is_range_<T>::value;
+ internal::is_tuple_like_<T>::value && !internal::is_range_<T>::value;
};
template <typename TupleT, typename Char>
-struct formatter<TupleT, Char,
- typename std::enable_if<fmt::is_tuple_like<TupleT>::value>::type> {
-private:
+struct formatter<TupleT, Char, enable_if_t<fmt::is_tuple_like<TupleT>::value>> {
+ private:
// C++11 generic lambda for format()
- template <typename FormatContext>
- struct format_each {
- template <typename T>
- void operator()(const T& v) {
+ template <typename FormatContext> struct format_each {
+ template <typename T> void operator()(const T& v) {
if (i > 0) {
if (formatting.add_prepostfix_space) {
*out++ = ' ';
}
- internal::copy(formatting.delimiter, out);
+ out = internal::copy(formatting.delimiter, out);
}
- format_to(out,
- internal::format_str_quoted(
- (formatting.add_delimiter_spaces && i > 0), v),
- v);
+ out = format_to(out,
+ internal::format_str_quoted(
+ (formatting.add_delimiter_spaces && i > 0), v),
+ v);
++i;
}
formatting_tuple<Char>& formatting;
std::size_t& i;
- typename std::add_lvalue_reference<decltype(std::declval<FormatContext>().out())>::type out;
+ typename std::add_lvalue_reference<decltype(
+ std::declval<FormatContext>().out())>::type out;
};
-public:
+ public:
formatting_tuple<Char> formatting;
template <typename ParseContext>
- FMT_CONSTEXPR auto parse(ParseContext &ctx) -> decltype(ctx.begin()) {
+ FMT_CONSTEXPR auto parse(ParseContext& ctx) -> decltype(ctx.begin()) {
return formatting.parse(ctx);
}
template <typename FormatContext = format_context>
- auto format(const TupleT &values, FormatContext &ctx) -> decltype(ctx.out()) {
+ auto format(const TupleT& values, FormatContext& ctx) -> decltype(ctx.out()) {
auto out = ctx.out();
std::size_t i = 0;
internal::copy(formatting.prefix, out);
@@ -255,54 +242,47 @@
}
};
-template <typename T>
-struct is_range {
+template <typename T, typename Char> struct is_range {
static FMT_CONSTEXPR_DECL const bool value =
- internal::is_range_<T>::value && !internal::is_like_std_string<T>::value;
+ internal::is_range_<T>::value &&
+ !internal::is_like_std_string<T>::value &&
+ !std::is_convertible<T, std::basic_string<Char>>::value;
};
template <typename RangeT, typename Char>
struct formatter<RangeT, Char,
- typename std::enable_if<fmt::is_range<RangeT>::value>::type> {
-
+ enable_if_t<fmt::is_range<RangeT, Char>::value>> {
formatting_range<Char> formatting;
template <typename ParseContext>
- FMT_CONSTEXPR auto parse(ParseContext &ctx) -> decltype(ctx.begin()) {
+ FMT_CONSTEXPR auto parse(ParseContext& ctx) -> decltype(ctx.begin()) {
return formatting.parse(ctx);
}
template <typename FormatContext>
- typename FormatContext::iterator format(
- const RangeT &values, FormatContext &ctx) {
- auto out = ctx.out();
- internal::copy(formatting.prefix, out);
+ typename FormatContext::iterator format(const RangeT& values,
+ FormatContext& ctx) {
+ auto out = internal::copy(formatting.prefix, ctx.out());
std::size_t i = 0;
for (auto it = values.begin(), end = values.end(); it != end; ++it) {
if (i > 0) {
- if (formatting.add_prepostfix_space) {
- *out++ = ' ';
- }
- internal::copy(formatting.delimiter, out);
+ if (formatting.add_prepostfix_space) *out++ = ' ';
+ out = internal::copy(formatting.delimiter, out);
}
- format_to(out,
- internal::format_str_quoted(
- (formatting.add_delimiter_spaces && i > 0), *it),
- *it);
+ out = format_to(out,
+ internal::format_str_quoted(
+ (formatting.add_delimiter_spaces && i > 0), *it),
+ *it);
if (++i > formatting.range_length_limit) {
- format_to(out, " ... <other elements>");
+ out = format_to(out, " ... <other elements>");
break;
}
}
- if (formatting.add_prepostfix_space) {
- *out++ = ' ';
- }
- internal::copy(formatting.postfix, out);
- return ctx.out();
+ if (formatting.add_prepostfix_space) *out++ = ' ';
+ return internal::copy(formatting.postfix, out);
}
};
FMT_END_NAMESPACE
-#endif // FMT_RANGES_H_
-
+#endif // FMT_RANGES_H_
diff --git a/include/fmt/safe-duration-cast.h b/include/fmt/safe-duration-cast.h
new file mode 100644
index 0000000..aa03618
--- /dev/null
+++ b/include/fmt/safe-duration-cast.h
@@ -0,0 +1,293 @@
+/*
+ * For conversion between std::chrono::durations without undefined
+ * behaviour or erroneous results.
+ * This is a stripped down version of duration_cast, for inclusion in fmt.
+ * See https://github.com/pauldreik/safe_duration_cast
+ *
+ * Copyright Paul Dreik 2019
+ *
+ * This file is licensed under the fmt license, see format.h
+ */
+
+#include <chrono>
+#include <cmath>
+#include <limits>
+#include <type_traits>
+
+#include "format.h"
+
+FMT_BEGIN_NAMESPACE
+
+namespace safe_duration_cast {
+
+template <typename To, typename From,
+ FMT_ENABLE_IF(!std::is_same<From, To>::value &&
+ std::numeric_limits<From>::is_signed ==
+ std::numeric_limits<To>::is_signed)>
+FMT_CONSTEXPR To lossless_integral_conversion(const From from, int& ec) {
+ ec = 0;
+ using F = std::numeric_limits<From>;
+ using T = std::numeric_limits<To>;
+ static_assert(F::is_integer, "From must be integral");
+ static_assert(T::is_integer, "To must be integral");
+
+ // A and B are both signed, or both unsigned.
+ if (F::digits <= T::digits) {
+ // From fits in To without any problem.
+ } else {
+ // From does not always fit in To, resort to a dynamic check.
+ if (from < T::min() || from > T::max()) {
+ // outside range.
+ ec = 1;
+ return {};
+ }
+ }
+ return static_cast<To>(from);
+}
+
+/**
+ * converts From to To, without loss. If the dynamic value of from
+ * can't be converted to To without loss, ec is set.
+ */
+template <typename To, typename From,
+ FMT_ENABLE_IF(!std::is_same<From, To>::value &&
+ std::numeric_limits<From>::is_signed !=
+ std::numeric_limits<To>::is_signed)>
+FMT_CONSTEXPR To lossless_integral_conversion(const From from, int& ec) {
+ ec = 0;
+ using F = std::numeric_limits<From>;
+ using T = std::numeric_limits<To>;
+ static_assert(F::is_integer, "From must be integral");
+ static_assert(T::is_integer, "To must be integral");
+
+ if (F::is_signed && !T::is_signed) {
+ // From may be negative, not allowed!
+ if (from < 0) {
+ ec = 1;
+ return {};
+ }
+
+ // From is positive. Can it always fit in To?
+ if (F::digits <= T::digits) {
+ // yes, From always fits in To.
+ } else {
+ // from may not fit in To, we have to do a dynamic check
+ if (from > static_cast<From>(T::max())) {
+ ec = 1;
+ return {};
+ }
+ }
+ }
+
+ if (!F::is_signed && T::is_signed) {
+ // can from be held in To?
+ if (F::digits < T::digits) {
+ // yes, From always fits in To.
+ } else {
+ // from may not fit in To, we have to do a dynamic check
+ if (from > static_cast<From>(T::max())) {
+ // outside range.
+ ec = 1;
+ return {};
+ }
+ }
+ }
+
+ // reaching here means all is ok for lossless conversion.
+ return static_cast<To>(from);
+
+} // function
+
+template <typename To, typename From,
+ FMT_ENABLE_IF(std::is_same<From, To>::value)>
+FMT_CONSTEXPR To lossless_integral_conversion(const From from, int& ec) {
+ ec = 0;
+ return from;
+} // function
+
+// clang-format off
+/**
+ * converts From to To if possible, otherwise ec is set.
+ *
+ * input | output
+ * ---------------------------------|---------------
+ * NaN | NaN
+ * Inf | Inf
+ * normal, fits in output | converted (possibly lossy)
+ * normal, does not fit in output | ec is set
+ * subnormal | best effort
+ * -Inf | -Inf
+ */
+// clang-format on
+template <typename To, typename From,
+ FMT_ENABLE_IF(!std::is_same<From, To>::value)>
+FMT_CONSTEXPR To safe_float_conversion(const From from, int& ec) {
+ ec = 0;
+ using T = std::numeric_limits<To>;
+ static_assert(std::is_floating_point<From>::value, "From must be floating");
+ static_assert(std::is_floating_point<To>::value, "To must be floating");
+
+ // catch the only happy case
+ if (std::isfinite(from)) {
+ if (from >= T::lowest() && from <= T::max()) {
+ return static_cast<To>(from);
+ }
+ // not within range.
+ ec = 1;
+ return {};
+ }
+
+ // nan and inf will be preserved
+ return static_cast<To>(from);
+} // function
+
+template <typename To, typename From,
+ FMT_ENABLE_IF(std::is_same<From, To>::value)>
+FMT_CONSTEXPR To safe_float_conversion(const From from, int& ec) {
+ ec = 0;
+ static_assert(std::is_floating_point<From>::value, "From must be floating");
+ return from;
+}
+
+/**
+ * safe duration cast between integral durations
+ */
+template <typename To, typename FromRep, typename FromPeriod,
+ FMT_ENABLE_IF(std::is_integral<FromRep>::value),
+ FMT_ENABLE_IF(std::is_integral<typename To::rep>::value)>
+To safe_duration_cast(std::chrono::duration<FromRep, FromPeriod> from,
+ int& ec) {
+ using From = std::chrono::duration<FromRep, FromPeriod>;
+ ec = 0;
+ // the basic idea is that we need to convert from count() in the from type
+ // to count() in the To type, by multiplying it with this:
+ using Factor = std::ratio_divide<typename From::period, typename To::period>;
+
+ static_assert(Factor::num > 0, "num must be positive");
+ static_assert(Factor::den > 0, "den must be positive");
+
+ // the conversion is like this: multiply from.count() with Factor::num
+ // /Factor::den and convert it to To::rep, all this without
+ // overflow/underflow. let's start by finding a suitable type that can hold
+ // both To, From and Factor::num
+ using IntermediateRep =
+ typename std::common_type<typename From::rep, typename To::rep,
+ decltype(Factor::num)>::type;
+
+ // safe conversion to IntermediateRep
+ IntermediateRep count =
+ lossless_integral_conversion<IntermediateRep>(from.count(), ec);
+ if (ec) {
+ return {};
+ }
+ // multiply with Factor::num without overflow or underflow
+ if (Factor::num != 1) {
+ constexpr auto max1 =
+ std::numeric_limits<IntermediateRep>::max() / Factor::num;
+ if (count > max1) {
+ ec = 1;
+ return {};
+ }
+ constexpr auto min1 =
+ std::numeric_limits<IntermediateRep>::min() / Factor::num;
+ if (count < min1) {
+ ec = 1;
+ return {};
+ }
+ count *= Factor::num;
+ }
+
+ // this can't go wrong, right? den>0 is checked earlier.
+ if (Factor::den != 1) {
+ count /= Factor::den;
+ }
+ // convert to the to type, safely
+ using ToRep = typename To::rep;
+ const ToRep tocount = lossless_integral_conversion<ToRep>(count, ec);
+ if (ec) {
+ return {};
+ }
+ return To{tocount};
+}
+
+/**
+ * safe duration_cast between floating point durations
+ */
+template <typename To, typename FromRep, typename FromPeriod,
+ FMT_ENABLE_IF(std::is_floating_point<FromRep>::value),
+ FMT_ENABLE_IF(std::is_floating_point<typename To::rep>::value)>
+To safe_duration_cast(std::chrono::duration<FromRep, FromPeriod> from,
+ int& ec) {
+ using From = std::chrono::duration<FromRep, FromPeriod>;
+ ec = 0;
+ if (std::isnan(from.count())) {
+ // nan in, gives nan out. easy.
+ return To{std::numeric_limits<typename To::rep>::quiet_NaN()};
+ }
+ // maybe we should also check if from is denormal, and decide what to do about
+ // it.
+
+ // +-inf should be preserved.
+ if (std::isinf(from.count())) {
+ return To{from.count()};
+ }
+
+ // the basic idea is that we need to convert from count() in the from type
+ // to count() in the To type, by multiplying it with this:
+ using Factor = std::ratio_divide<typename From::period, typename To::period>;
+
+ static_assert(Factor::num > 0, "num must be positive");
+ static_assert(Factor::den > 0, "den must be positive");
+
+ // the conversion is like this: multiply from.count() with Factor::num
+ // /Factor::den and convert it to To::rep, all this without
+ // overflow/underflow. let's start by finding a suitable type that can hold
+ // both To, From and Factor::num
+ using IntermediateRep =
+ typename std::common_type<typename From::rep, typename To::rep,
+ decltype(Factor::num)>::type;
+
+ // force conversion of From::rep -> IntermediateRep to be safe,
+ // even if it will never happen be narrowing in this context.
+ IntermediateRep count =
+ safe_float_conversion<IntermediateRep>(from.count(), ec);
+ if (ec) {
+ return {};
+ }
+
+ // multiply with Factor::num without overflow or underflow
+ if (Factor::num != 1) {
+ constexpr auto max1 = std::numeric_limits<IntermediateRep>::max() /
+ static_cast<IntermediateRep>(Factor::num);
+ if (count > max1) {
+ ec = 1;
+ return {};
+ }
+ constexpr auto min1 = std::numeric_limits<IntermediateRep>::lowest() /
+ static_cast<IntermediateRep>(Factor::num);
+ if (count < min1) {
+ ec = 1;
+ return {};
+ }
+ count *= static_cast<IntermediateRep>(Factor::num);
+ }
+
+ // this can't go wrong, right? den>0 is checked earlier.
+ if (Factor::den != 1) {
+ using common_t = typename std::common_type<IntermediateRep, intmax_t>::type;
+ count /= static_cast<common_t>(Factor::den);
+ }
+
+ // convert to the to type, safely
+ using ToRep = typename To::rep;
+
+ const ToRep tocount = safe_float_conversion<ToRep>(count, ec);
+ if (ec) {
+ return {};
+ }
+ return To{tocount};
+}
+
+} // namespace safe_duration_cast
+
+FMT_END_NAMESPACE
diff --git a/include/fmt/time.h b/include/fmt/time.h
deleted file mode 100644
index fe79891..0000000
--- a/include/fmt/time.h
+++ /dev/null
@@ -1,160 +0,0 @@
-// Formatting library for C++ - time formatting
-//
-// Copyright (c) 2012 - present, Victor Zverovich
-// All rights reserved.
-//
-// For the license information refer to format.h.
-
-#ifndef FMT_TIME_H_
-#define FMT_TIME_H_
-
-#include "format.h"
-#include <ctime>
-#include <locale>
-
-FMT_BEGIN_NAMESPACE
-
-// Prevents expansion of a preceding token as a function-style macro.
-// Usage: f FMT_NOMACRO()
-#define FMT_NOMACRO
-
-namespace internal{
-inline null<> localtime_r FMT_NOMACRO(...) { return null<>(); }
-inline null<> localtime_s(...) { return null<>(); }
-inline null<> gmtime_r(...) { return null<>(); }
-inline null<> gmtime_s(...) { return null<>(); }
-} // namespace internal
-
-// Thread-safe replacement for std::localtime
-inline std::tm localtime(std::time_t time) {
- struct dispatcher {
- std::time_t time_;
- std::tm tm_;
-
- dispatcher(std::time_t t): time_(t) {}
-
- bool run() {
- using namespace fmt::internal;
- return handle(localtime_r(&time_, &tm_));
- }
-
- bool handle(std::tm *tm) { return tm != FMT_NULL; }
-
- bool handle(internal::null<>) {
- using namespace fmt::internal;
- return fallback(localtime_s(&tm_, &time_));
- }
-
- bool fallback(int res) { return res == 0; }
-
-#if !FMT_MSC_VER
- bool fallback(internal::null<>) {
- using namespace fmt::internal;
- std::tm *tm = std::localtime(&time_);
- if (tm) tm_ = *tm;
- return tm != FMT_NULL;
- }
-#endif
- };
- dispatcher lt(time);
- // Too big time values may be unsupported.
- if (!lt.run())
- FMT_THROW(format_error("time_t value out of range"));
- return lt.tm_;
-}
-
-// Thread-safe replacement for std::gmtime
-inline std::tm gmtime(std::time_t time) {
- struct dispatcher {
- std::time_t time_;
- std::tm tm_;
-
- dispatcher(std::time_t t): time_(t) {}
-
- bool run() {
- using namespace fmt::internal;
- return handle(gmtime_r(&time_, &tm_));
- }
-
- bool handle(std::tm *tm) { return tm != FMT_NULL; }
-
- bool handle(internal::null<>) {
- using namespace fmt::internal;
- return fallback(gmtime_s(&tm_, &time_));
- }
-
- bool fallback(int res) { return res == 0; }
-
-#if !FMT_MSC_VER
- bool fallback(internal::null<>) {
- std::tm *tm = std::gmtime(&time_);
- if (tm) tm_ = *tm;
- return tm != FMT_NULL;
- }
-#endif
- };
- dispatcher gt(time);
- // Too big time values may be unsupported.
- if (!gt.run())
- FMT_THROW(format_error("time_t value out of range"));
- return gt.tm_;
-}
-
-namespace internal {
-inline std::size_t strftime(char *str, std::size_t count, const char *format,
- const std::tm *time) {
- return std::strftime(str, count, format, time);
-}
-
-inline std::size_t strftime(wchar_t *str, std::size_t count,
- const wchar_t *format, const std::tm *time) {
- return std::wcsftime(str, count, format, time);
-}
-}
-
-template <typename Char>
-struct formatter<std::tm, Char> {
- template <typename ParseContext>
- auto parse(ParseContext &ctx) -> decltype(ctx.begin()) {
- auto it = ctx.begin();
- if (it != ctx.end() && *it == ':')
- ++it;
- auto end = it;
- while (end != ctx.end() && *end != '}')
- ++end;
- tm_format.reserve(internal::to_unsigned(end - it + 1));
- tm_format.append(it, end);
- tm_format.push_back('\0');
- return end;
- }
-
- template <typename FormatContext>
- auto format(const std::tm &tm, FormatContext &ctx) -> decltype(ctx.out()) {
- basic_memory_buffer<Char> buf;
- std::size_t start = buf.size();
- for (;;) {
- std::size_t size = buf.capacity() - start;
- std::size_t count =
- internal::strftime(&buf[start], size, &tm_format[0], &tm);
- if (count != 0) {
- buf.resize(start + count);
- break;
- }
- if (size >= tm_format.size() * 256) {
- // If the buffer is 256 times larger than the format string, assume
- // that `strftime` gives an empty result. There doesn't seem to be a
- // better way to distinguish the two cases:
- // https://github.com/fmtlib/fmt/issues/367
- break;
- }
- const std::size_t MIN_GROWTH = 10;
- buf.reserve(buf.capacity() + (size > MIN_GROWTH ? size : MIN_GROWTH));
- }
- return std::copy(buf.begin(), buf.end(), ctx.out());
- }
-
- basic_memory_buffer<Char> tm_format;
-};
-FMT_END_NAMESPACE
-
-#endif // FMT_TIME_H_
diff --git a/src/format.cc b/src/format.cc
index dadfc8d..41076f1 100644
--- a/src/format.cc
+++ b/src/format.cc
@@ -8,51 +8,49 @@
#include "fmt/format-inl.h"
FMT_BEGIN_NAMESPACE
-template struct internal::basic_data<void>;
-template FMT_API internal::locale_ref::locale_ref(const std::locale &loc);
+template struct FMT_API internal::basic_data<void>;
+
+// Workaround a bug in MSVC2013 that prevents instantiation of grisu_format.
+bool (*instantiate_grisu_format)(double, internal::buffer<char>&, int, unsigned,
+ int&) = internal::grisu_format;
+
+#ifndef FMT_STATIC_THOUSANDS_SEPARATOR
+template FMT_API internal::locale_ref::locale_ref(const std::locale& loc);
template FMT_API std::locale internal::locale_ref::get<std::locale>() const;
+#endif
// Explicit instantiations for char.
template FMT_API char internal::thousands_sep_impl(locale_ref);
+template FMT_API char internal::decimal_point_impl(locale_ref);
-template FMT_API void internal::basic_buffer<char>::append(const char *, const char *);
+template FMT_API void internal::buffer<char>::append(const char*, const char*);
template FMT_API void internal::arg_map<format_context>::init(
- const basic_format_args<format_context> &args);
-
-template FMT_API int internal::char_traits<char>::format_float(
- char *, std::size_t, const char *, int, double);
-
-template FMT_API int internal::char_traits<char>::format_float(
- char *, std::size_t, const char *, int, long double);
+ const basic_format_args<format_context>& args);
template FMT_API std::string internal::vformat<char>(
string_view, basic_format_args<format_context>);
template FMT_API format_context::iterator internal::vformat_to(
- internal::buffer &, string_view, basic_format_args<format_context>);
+ internal::buffer<char>&, string_view, basic_format_args<format_context>);
-template FMT_API void internal::sprintf_format(
- double, internal::buffer &, core_format_specs);
-template FMT_API void internal::sprintf_format(
- long double, internal::buffer &, core_format_specs);
+template FMT_API char* internal::sprintf_format(double, internal::buffer<char>&,
+ sprintf_specs);
+template FMT_API char* internal::sprintf_format(long double,
+ internal::buffer<char>&,
+ sprintf_specs);
// Explicit instantiations for wchar_t.
template FMT_API wchar_t internal::thousands_sep_impl(locale_ref);
+template FMT_API wchar_t internal::decimal_point_impl(locale_ref);
-template FMT_API void internal::basic_buffer<wchar_t>::append(
- const wchar_t *, const wchar_t *);
+template FMT_API void internal::buffer<wchar_t>::append(const wchar_t*,
+ const wchar_t*);
template FMT_API void internal::arg_map<wformat_context>::init(
- const basic_format_args<wformat_context> &);
-
-template FMT_API int internal::char_traits<wchar_t>::format_float(
- wchar_t *, std::size_t, const wchar_t *, int, double);
-
-template FMT_API int internal::char_traits<wchar_t>::format_float(
- wchar_t *, std::size_t, const wchar_t *, int, long double);
+ const basic_format_args<wformat_context>&);
template FMT_API std::wstring internal::vformat<wchar_t>(
wstring_view, basic_format_args<wformat_context>);
diff --git a/src/posix.cc b/src/posix.cc
index 296da23..69c2781 100644
--- a/src/posix.cc
+++ b/src/posix.cc
@@ -7,43 +7,43 @@
// Disable bogus MSVC warnings.
#if !defined(_CRT_SECURE_NO_WARNINGS) && defined(_MSC_VER)
-# define _CRT_SECURE_NO_WARNINGS
+# define _CRT_SECURE_NO_WARNINGS
#endif
#include "fmt/posix.h"
#include <limits.h>
-#include <sys/types.h>
#include <sys/stat.h>
+#include <sys/types.h>
#ifndef _WIN32
-# include <unistd.h>
+# include <unistd.h>
#else
-# ifndef WIN32_LEAN_AND_MEAN
-# define WIN32_LEAN_AND_MEAN
-# endif
-# include <windows.h>
-# include <io.h>
+# ifndef WIN32_LEAN_AND_MEAN
+# define WIN32_LEAN_AND_MEAN
+# endif
+# include <io.h>
+# include <windows.h>
-# define O_CREAT _O_CREAT
-# define O_TRUNC _O_TRUNC
+# define O_CREAT _O_CREAT
+# define O_TRUNC _O_TRUNC
-# ifndef S_IRUSR
-# define S_IRUSR _S_IREAD
-# endif
+# ifndef S_IRUSR
+# define S_IRUSR _S_IREAD
+# endif
-# ifndef S_IWUSR
-# define S_IWUSR _S_IWRITE
-# endif
+# ifndef S_IWUSR
+# define S_IWUSR _S_IWRITE
+# endif
-# ifdef __MINGW32__
-# define _SH_DENYNO 0x40
-# endif
+# ifdef __MINGW32__
+# define _SH_DENYNO 0x40
+# endif
#endif // _WIN32
#ifdef fileno
-# undef fileno
+# undef fileno
#endif
namespace {
@@ -62,7 +62,7 @@
inline std::size_t convert_rwcount(std::size_t count) { return count; }
#endif
-}
+} // namespace
FMT_BEGIN_NAMESPACE
@@ -72,19 +72,17 @@
}
buffered_file::buffered_file(cstring_view filename, cstring_view mode) {
- FMT_RETRY_VAL(file_,
- FMT_SYSTEM(fopen(filename.c_str(), mode.c_str())), FMT_NULL);
+ FMT_RETRY_VAL(file_, FMT_SYSTEM(fopen(filename.c_str(), mode.c_str())),
+ nullptr);
if (!file_)
FMT_THROW(system_error(errno, "cannot open file {}", filename.c_str()));
}
void buffered_file::close() {
- if (!file_)
- return;
+ if (!file_) return;
int result = FMT_SYSTEM(fclose(file_));
- file_ = FMT_NULL;
- if (result != 0)
- FMT_THROW(system_error(errno, "cannot close file"));
+ file_ = nullptr;
+ if (result != 0) FMT_THROW(system_error(errno, "cannot close file"));
}
// A macro used to prevent expansion of fileno on broken versions of MinGW.
@@ -92,8 +90,7 @@
int buffered_file::fileno() const {
int fd = FMT_POSIX_CALL(fileno FMT_ARGS(file_));
- if (fd == -1)
- FMT_THROW(system_error(errno, "cannot get file descriptor"));
+ if (fd == -1) FMT_THROW(system_error(errno, "cannot get file descriptor"));
return fd;
}
@@ -117,14 +114,12 @@
}
void file::close() {
- if (fd_ == -1)
- return;
+ if (fd_ == -1) return;
// Don't retry close in case of EINTR!
// See http://linux.derkeiler.com/Mailing-Lists/Kernel/2005-09/3000.html
int result = FMT_POSIX_CALL(close(fd_));
fd_ = -1;
- if (result != 0)
- FMT_THROW(system_error(errno, "cannot close file"));
+ if (result != 0) FMT_THROW(system_error(errno, "cannot close file"));
}
long long file::size() const {
@@ -148,24 +143,22 @@
if (FMT_POSIX_CALL(fstat(fd_, &file_stat)) == -1)
FMT_THROW(system_error(errno, "cannot get file attributes"));
static_assert(sizeof(long long) >= sizeof(file_stat.st_size),
- "return type of file::size is not large enough");
+ "return type of file::size is not large enough");
return file_stat.st_size;
#endif
}
-std::size_t file::read(void *buffer, std::size_t count) {
+std::size_t file::read(void* buffer, std::size_t count) {
RWResult result = 0;
FMT_RETRY(result, FMT_POSIX_CALL(read(fd_, buffer, convert_rwcount(count))));
- if (result < 0)
- FMT_THROW(system_error(errno, "cannot read from file"));
+ if (result < 0) FMT_THROW(system_error(errno, "cannot read from file"));
return internal::to_unsigned(result);
}
-std::size_t file::write(const void *buffer, std::size_t count) {
+std::size_t file::write(const void* buffer, std::size_t count) {
RWResult result = 0;
FMT_RETRY(result, FMT_POSIX_CALL(write(fd_, buffer, convert_rwcount(count))));
- if (result < 0)
- FMT_THROW(system_error(errno, "cannot write to file"));
+ if (result < 0) FMT_THROW(system_error(errno, "cannot write to file"));
return internal::to_unsigned(result);
}
@@ -182,19 +175,18 @@
int result = 0;
FMT_RETRY(result, FMT_POSIX_CALL(dup2(fd_, fd)));
if (result == -1) {
- FMT_THROW(system_error(errno,
- "cannot duplicate file descriptor {} to {}", fd_, fd));
+ FMT_THROW(system_error(errno, "cannot duplicate file descriptor {} to {}",
+ fd_, fd));
}
}
-void file::dup2(int fd, error_code &ec) FMT_NOEXCEPT {
+void file::dup2(int fd, error_code& ec) FMT_NOEXCEPT {
int result = 0;
FMT_RETRY(result, FMT_POSIX_CALL(dup2(fd_, fd)));
- if (result == -1)
- ec = error_code(errno);
+ if (result == -1) ec = error_code(errno);
}
-void file::pipe(file &read_end, file &write_end) {
+void file::pipe(file& read_end, file& write_end) {
// Close the descriptors first to make sure that assignments don't throw
// and there are no leaks.
read_end.close();
@@ -209,20 +201,19 @@
// http://pubs.opengroup.org/onlinepubs/009696799/functions/pipe.html
int result = FMT_POSIX_CALL(pipe(fds));
#endif
- if (result != 0)
- FMT_THROW(system_error(errno, "cannot create pipe"));
+ if (result != 0) FMT_THROW(system_error(errno, "cannot create pipe"));
// The following assignments don't throw because read_fd and write_fd
// are closed.
read_end = file(fds[0]);
write_end = file(fds[1]);
}
-buffered_file file::fdopen(const char *mode) {
+buffered_file file::fdopen(const char* mode) {
// Don't retry as fdopen doesn't return EINTR.
- FILE *f = FMT_POSIX_CALL(fdopen(fd_, mode));
+ FILE* f = FMT_POSIX_CALL(fdopen(fd_, mode));
if (!f)
- FMT_THROW(system_error(errno,
- "cannot associate stream with file descriptor"));
+ FMT_THROW(
+ system_error(errno, "cannot associate stream with file descriptor"));
buffered_file bf(f);
fd_ = -1;
return bf;
@@ -235,10 +226,8 @@
return si.dwPageSize;
#else
long size = FMT_POSIX_CALL(sysconf(_SC_PAGESIZE));
- if (size < 0)
- FMT_THROW(system_error(errno, "cannot get memory page size"));
+ if (size < 0) FMT_THROW(system_error(errno, "cannot get memory page size"));
return size;
#endif
}
FMT_END_NAMESPACE
-
diff --git a/support/C++.sublime-syntax b/support/C++.sublime-syntax
new file mode 100644
index 0000000..9dfb5cb
--- /dev/null
+++ b/support/C++.sublime-syntax
@@ -0,0 +1,2061 @@
+%YAML 1.2
+---
+# http://www.sublimetext.com/docs/3/syntax.html
+name: C++ (fmt)
+comment: I don't think anyone uses .hp. .cp tends to be paired with .h. (I could be wrong. :) -- chris
+file_extensions:
+ - cpp
+ - cc
+ - cp
+ - cxx
+ - c++
+ - C
+ - h
+ - hh
+ - hpp
+ - hxx
+ - h++
+ - inl
+ - ipp
+first_line_match: '-\*- C\+\+ -\*-'
+scope: source.c++
+variables:
+ identifier: \b[[:alpha:]_][[:alnum:]_]*\b # upper and lowercase
+ macro_identifier: \b[[:upper:]_][[:upper:][:digit:]_]{2,}\b # only uppercase, at least 3 chars
+ path_lookahead: '(?:::\s*)?(?:{{identifier}}\s*::\s*)*(?:template\s+)?{{identifier}}'
+ operator_method_name: '\boperator\s*(?:[-+*/%^&|~!=<>]|[-+*/%^&|=!<>]=|<<=?|>>=?|&&|\|\||\+\+|--|,|->\*?|\(\)|\[\]|""\s*{{identifier}})'
+ casts: 'const_cast|dynamic_cast|reinterpret_cast|static_cast'
+ operator_keywords: 'and|and_eq|bitand|bitor|compl|not|not_eq|or|or_eq|xor|xor_eq|noexcept'
+ control_keywords: 'break|case|catch|continue|default|do|else|for|goto|if|_Pragma|return|switch|throw|try|while'
+ memory_operators: 'new|delete'
+ basic_types: 'asm|__asm__|auto|bool|_Bool|char|_Complex|double|float|_Imaginary|int|long|short|signed|unsigned|void'
+ before_tag: 'struct|union|enum\s+class|enum\s+struct|enum|class'
+ declspec: '__declspec\(\s*\w+(?:\([^)]+\))?\s*\)'
+ storage_classes: 'static|export|extern|friend|explicit|virtual|register|thread_local'
+ type_qualifier: 'const|constexpr|mutable|typename|volatile'
+ compiler_directive: 'inline|restrict|__restrict__|__restrict'
+ visibility_modifiers: 'private|protected|public'
+ other_keywords: 'typedef|nullptr|{{visibility_modifiers}}|static_assert|sizeof|using|typeid|alignof|alignas|namespace|template'
+ modifiers: '{{storage_classes}}|{{type_qualifier}}|{{compiler_directive}}'
+ non_angle_brackets: '(?=<<|<=)'
+
+ regular: '[^(){}&;*^%=<>-]*'
+ paren_open: (?:\(
+ paren_close: '\))?'
+ generic_open: (?:<
+ generic_close: '>)?'
+ balance_parentheses: '{{regular}}{{paren_open}}{{regular}}{{paren_close}}{{regular}}'
+ generic_lookahead: <{{regular}}{{generic_open}}{{regular}}{{generic_open}}{{regular}}{{generic_close}}\s*{{generic_close}}{{balance_parentheses}}>
+
+ data_structures_forward_decl_lookahead: '(\s+{{macro_identifier}})*\s*(:\s*({{path_lookahead}}|{{visibility_modifiers}}|,|\s|<[^;]*>)+)?;'
+ non_func_keywords: 'if|for|switch|while|decltype|sizeof|__declspec|__attribute__|typeid|alignof|alignas|static_assert'
+
+ format_spec: |-
+ (?x:
+ (?:.? [<>=^])? # fill align
+ [ +-]? # sign
+ \#? # alternate form
+ # technically, octal and hexadecimal integers are also supported as 'width', but rarely used
+ \d* # width
+ ,? # thousands separator
+ (?:\.\d+)? # precision
+ [bcdeEfFgGnosxX%]? # type
+ )
+
+contexts:
+ main:
+ - include: preprocessor-global
+ - include: global
+
+ #############################################################################
+ # Reusable contexts
+ #
+ # The follow contexts are currently constructed to be reused in the
+ # Objetive-C++ syntax. They are specifically constructed to not push into
+ # sub-contexts, which ensures that Objective-C++ code isn't accidentally
+ # lexed as plain C++.
+ #
+ # The "unique-*" contexts are additions that C++ makes over C, and thus can
+ # be directly reused in Objective-C++ along with contexts from Objective-C
+ # and C.
+ #############################################################################
+
+ unique-late-expressions:
+ # This is highlighted after all of the other control keywords
+ # to allow operator overloading to be lexed properly
+ - match: \boperator\b
+ scope: keyword.control.c++
+
+ unique-modifiers:
+ - match: \b({{modifiers}})\b
+ scope: storage.modifier.c++
+
+ unique-variables:
+ - match: \bthis\b
+ scope: variable.language.c++
+ # common C++ instance var naming idiom -- fMemberName
+ - match: '\b(f|m)[[:upper:]]\w*\b'
+ scope: variable.other.readwrite.member.c++
+ # common C++ instance var naming idiom -- m_member_name
+ - match: '\bm_[[:alnum:]_]+\b'
+ scope: variable.other.readwrite.member.c++
+
+ unique-constants:
+ - match: \bnullptr\b
+ scope: constant.language.c++
+
+ unique-keywords:
+ - match: \busing\b
+ scope: keyword.control.c++
+ - match: \bbreak\b
+ scope: keyword.control.flow.break.c++
+ - match: \bcontinue\b
+ scope: keyword.control.flow.continue.c++
+ - match: \bgoto\b
+ scope: keyword.control.flow.goto.c++
+ - match: \breturn\b
+ scope: keyword.control.flow.return.c++
+ - match: \bthrow\b
+ scope: keyword.control.flow.throw.c++
+ - match: \b({{control_keywords}})\b
+ scope: keyword.control.c++
+ - match: '\bdelete\b(\s*\[\])?|\bnew\b(?!])'
+ scope: keyword.control.c++
+ - match: \b({{operator_keywords}})\b
+ scope: keyword.operator.word.c++
+
+ unique-types:
+ - match: \b(char16_t|char32_t|wchar_t|nullptr_t)\b
+ scope: storage.type.c++
+ - match: \bclass\b
+ scope: storage.type.c++
+
+ unique-strings:
+ - match: '((?:L|u8|u|U)?R)("([^\(\)\\ ]{0,16})\()'
+ captures:
+ 1: storage.type.string.c++
+ 2: punctuation.definition.string.begin.c++
+ push:
+ - meta_scope: string.quoted.double.c++
+ - match: '\)\3"'
+ scope: punctuation.definition.string.end.c++
+ pop: true
+ - match: '\{\{|\}\}'
+ scope: constant.character.escape.c++
+ - include: formatting-syntax
+
+ unique-numbers:
+ - match: |-
+ (?x)
+ (?:
+ # floats
+ (?:
+ (?:\b\d(?:[\d']*\d)?\.\d(?:[\d']*\d)?|\B\.\d(?:[\d']*\d)?)(?:[Ee][+-]?\d(?:[\d']*\d)?)?(?:[fFlL]|(?:i[fl]?|h|min|[mun]?s|_\w*))?\b
+ |
+ (?:\b\d(?:[\d']*\d)?\.)(?:\B|(?:[fFlL]|(?:i[fl]?|h|min|[mun]?s|_\w*))\b|(?:[Ee][+-]?\d(?:[\d']*\d)?)(?:[fFlL]|(?:i[fl]?|h|min|[mun]?s|_\w*))?\b)
+ |
+ \b\d(?:[\d']*\d)?(?:[Ee][+-]?\d(?:[\d']*\d)?)(?:[fFlL]|(?:i[fl]?|h|min|[mun]?s|_\w*))?\b
+ )
+ |
+ # ints
+ \b(?:
+ (?:
+ # dec
+ [1-9](?:[\d']*\d)?
+ |
+ # oct
+ 0(?:[0-7']*[0-7])?
+ |
+ # hex
+ 0[Xx][\da-fA-F](?:[\da-fA-F']*[\da-fA-F])?
+ |
+ # bin
+ 0[Bb][01](?:[01']*[01])?
+ )
+ # int suffixes
+ (?:(?:l{1,2}|L{1,2})[uU]?|[uU](?:l{0,2}|L{0,2})|(?:i[fl]?|h|min|[mun]?s|_\w*))?)\b
+ )
+ (?!\.) # Number must not be followed by a decimal point
+ scope: constant.numeric.c++
+
+ identifiers:
+ - match: '{{identifier}}\s*(::)\s*'
+ captures:
+ 1: punctuation.accessor.c++
+ - match: '(?:(::)\s*)?{{identifier}}'
+ captures:
+ 1: punctuation.accessor.c++
+
+ function-specifiers:
+ - match: \b(const|final|noexcept|override)\b
+ scope: storage.modifier.c++
+
+ #############################################################################
+ # The following are C++-specific contexts that should not be reused. This is
+ # because they push into subcontexts and use variables that are C++-specific.
+ #############################################################################
+
+ ## Common context layout
+
+ global:
+ - match: '(?=\btemplate\b)'
+ push:
+ - include: template
+ - match: (?=\S)
+ set: global-modifier
+ - include: namespace
+ - include: keywords-angle-brackets
+ - match: '(?={{path_lookahead}}\s*<)'
+ push: global-modifier
+ # Take care of comments just before a function definition.
+ - match: /\*
+ scope: punctuation.definition.comment.c
+ push:
+ - - match: \s*(?=\w)
+ set: global-modifier
+ - match: ""
+ pop: true
+ - - meta_scope: comment.block.c
+ - match: \*/
+ scope: punctuation.definition.comment.c
+ pop: true
+ - include: early-expressions
+ - match: ^\s*\b(extern)(?=\s+"C(\+\+)?")
+ scope: storage.modifier.c++
+ push:
+ - include: comments
+ - include: strings
+ - match: '\{'
+ scope: punctuation.section.block.begin.c++
+ set:
+ - meta_scope: meta.extern-c.c++
+ - match: '^\s*(#\s*ifdef)\s*__cplusplus\s*'
+ scope: meta.preprocessor.c++
+ captures:
+ 1: keyword.control.import.c++
+ set:
+ - match: '\}'
+ scope: punctuation.section.block.end.c++
+ pop: true
+ - include: preprocessor-global
+ - include: global
+ - match: '\}'
+ scope: punctuation.section.block.end.c++
+ pop: true
+ - include: preprocessor-global
+ - include: global
+ - match: (?=\S)
+ set: global-modifier
+ - match: ^\s*(?=\w)
+ push: global-modifier
+ - include: late-expressions
+
+ statements:
+ - include: preprocessor-statements
+ - include: scope:source.c#label
+ - include: expressions
+
+ expressions:
+ - include: early-expressions
+ - include: late-expressions
+
+ early-expressions:
+ - include: early-expressions-before-generic-type
+ - include: generic-type
+ - include: early-expressions-after-generic-type
+
+ early-expressions-before-generic-type:
+ - include: preprocessor-expressions
+ - include: comments
+ - include: case-default
+ - include: typedef
+ - include: keywords-angle-brackets
+ - include: keywords-parens
+ - include: keywords
+ - include: numbers
+ # Prevent a '<' from getting scoped as the start of another template
+ # parameter list, if in reality a less-than-or-equals sign is meant.
+ - match: <=
+ scope: keyword.operator.comparison.c
+
+ early-expressions-after-generic-type:
+ - include: members-arrow
+ - include: operators
+ - include: members-dot
+ - include: strings
+ - include: parens
+ - include: brackets
+ - include: block
+ - include: variables
+ - include: constants
+ - match: ','
+ scope: punctuation.separator.c++
+ - match: '\)|\}'
+ scope: invalid.illegal.stray-bracket-end.c++
+
+ expressions-minus-generic-type:
+ - include: early-expressions-before-generic-type
+ - include: angle-brackets
+ - include: early-expressions-after-generic-type
+ - include: late-expressions
+
+ expressions-minus-generic-type-function-call:
+ - include: early-expressions-before-generic-type
+ - include: angle-brackets
+ - include: early-expressions-after-generic-type
+ - include: late-expressions-before-function-call
+ - include: identifiers
+ - match: ';'
+ scope: punctuation.terminator.c++
+
+ late-expressions:
+ - include: late-expressions-before-function-call
+ - include: function-call
+ - include: identifiers
+ - match: ';'
+ scope: punctuation.terminator.c++
+
+ late-expressions-before-function-call:
+ - include: unique-late-expressions
+ - include: modifiers-parens
+ - include: modifiers
+ - include: types
+
+ expressions-minus-function-call:
+ - include: early-expressions
+ - include: late-expressions-before-function-call
+ - include: identifiers
+ - match: ';'
+ scope: punctuation.terminator.c++
+
+ comments:
+ - include: scope:source.c#comments
+
+ operators:
+ - include: scope:source.c#operators
+
+ modifiers:
+ - include: unique-modifiers
+ - include: scope:source.c#modifiers
+
+ variables:
+ - include: unique-variables
+ - include: scope:source.c#variables
+
+ constants:
+ - include: unique-constants
+ - include: scope:source.c#constants
+
+ keywords:
+ - include: unique-keywords
+ - include: scope:source.c#keywords
+
+ types:
+ - include: unique-types
+ - include: types-parens
+ - include: scope:source.c#types
+
+ strings:
+ - include: unique-strings
+ - match: '(L|u8|u|U)?(")'
+ captures:
+ 1: storage.type.string.c++
+ 2: punctuation.definition.string.begin.c++
+ push:
+ - meta_scope: string.quoted.double.c++
+ - match: '"'
+ scope: punctuation.definition.string.end.c++
+ pop: true
+ - include: scope:source.c#string_escaped_char
+ - match: |-
+ (?x)%
+ (\d+\$)? # field (argument #)
+ [#0\- +']* # flags
+ [,;:_]? # separator character (AltiVec)
+ ((-?\d+)|\*(-?\d+\$)?)? # minimum field width
+ (\.((-?\d+)|\*(-?\d+\$)?)?)? # precision
+ (hh|h|ll|l|j|t|z|q|L|vh|vl|v|hv|hl)? # length modifier
+ (\[[^\]]+\]|[am]s|[diouxXDOUeEfFgGaACcSspn%]) # conversion type
+ scope: constant.other.placeholder.c++
+ - match: '\{\{|\}\}'
+ scope: constant.character.escape.c++
+ - include: formatting-syntax
+ - include: scope:source.c#strings
+
+ formatting-syntax:
+ # https://docs.python.org/3.6/library/string.html#formatstrings
+ - match: |- # simple form
+ (?x)
+ (\{)
+ (?: [\w.\[\]]+)? # field_name
+ ( ! [ars])? # conversion
+ ( : (?:{{format_spec}}| # format_spec OR
+ [^}%]*%.[^}]*) # any format-like string
+ )?
+ (\})
+ scope: constant.other.placeholder.c++
+ captures:
+ 1: punctuation.definition.placeholder.begin.c++
+ 2: storage.modifier.c++onversion.c++
+ 3: constant.other.format-spec.c++
+ 4: punctuation.definition.placeholder.end.c++
+ - match: \{(?=[^\}"']+\{[^"']*\}) # complex (nested) form
+ scope: punctuation.definition.placeholder.begin.c++
+ push:
+ - meta_scope: constant.other.placeholder.c++
+ - match: \}
+ scope: punctuation.definition.placeholder.end.c++
+ pop: true
+ - match: '[\w.\[\]]+'
+ - match: '![ars]'
+ scope: storage.modifier.conversion.c++
+ - match: ':'
+ push:
+ - meta_scope: meta.format-spec.c++ constant.other.format-spec.c++
+ - match: (?=\})
+ pop: true
+ - include: formatting-syntax
+
+ numbers:
+ - include: unique-numbers
+ - include: scope:source.c#numbers
+
+ ## C++-specific contexts
+
+ case-default:
+ - match: '\b(default|case)\b'
+ scope: keyword.control.c++
+ push:
+ - match: (?=[);,])
+ pop: true
+ - match: ':'
+ scope: punctuation.separator.c++
+ pop: true
+ - include: expressions
+
+ modifiers-parens:
+ - match: '\b(alignas)\b\s*(\()'
+ captures:
+ 1: storage.modifier.c++
+ 2: meta.group.c++ punctuation.section.group.begin.c++
+ push:
+ - meta_content_scope: meta.group.c++
+ - match: '\)'
+ scope: meta.group.c++ punctuation.section.group.end.c++
+ pop: true
+ - include: expressions
+ - match: \b(__attribute__)\s*(\(\()
+ captures:
+ 1: storage.modifier.c++
+ 2: meta.group.c++ punctuation.section.group.begin.c++
+ push :
+ - meta_scope: meta.attribute.c++
+ - meta_content_scope: meta.group.c++
+ - include: parens
+ - include: strings
+ - match: \)\)
+ scope: meta.group.c++ punctuation.section.group.end.c++
+ pop: true
+ - match: \b(__declspec)(\()
+ captures:
+ 1: storage.modifier.c++
+ 2: meta.group.c++ punctuation.section.group.begin.c++
+ push:
+ - meta_content_scope: meta.group.c++
+ - match: '\)'
+ scope: meta.group.c++ punctuation.section.group.end.c++
+ pop: true
+ - match: '\b(align|allocate|code_seg|deprecated|property|uuid)\b\s*(\()'
+ captures:
+ 1: storage.modifier.c++
+ 2: meta.group.c++ punctuation.section.group.begin.c++
+ push:
+ - meta_content_scope: meta.group.c++
+ - match: '\)'
+ scope: meta.group.c++ punctuation.section.group.end.c++
+ pop: true
+ - include: numbers
+ - include: strings
+ - match: \b(get|put)\b
+ scope: variable.parameter.c++
+ - match: ','
+ scope: punctuation.separator.c++
+ - match: '='
+ scope: keyword.operator.assignment.c++
+ - match: '\b(appdomain|deprecated|dllimport|dllexport|jintrinsic|naked|noalias|noinline|noreturn|nothrow|novtable|process|restrict|safebuffers|selectany|thread)\b'
+ scope: constant.other.c++
+
+ types-parens:
+ - match: '\b(decltype)\b\s*(\()'
+ captures:
+ 1: storage.type.c++
+ 2: meta.group.c++ punctuation.section.group.begin.c++
+ push:
+ - meta_content_scope: meta.group.c++
+ - match: '\)'
+ scope: meta.group.c++ punctuation.section.group.end.c++
+ pop: true
+ - include: expressions
+
+ keywords-angle-brackets:
+ - match: \b({{casts}})\b\s*
+ scope: keyword.operator.word.cast.c++
+ push:
+ - match: '>'
+ scope: punctuation.section.generic.end.c++
+ pop: true
+ - match: '<'
+ scope: punctuation.section.generic.begin.c++
+ push:
+ - match: '(?=>)'
+ pop: true
+ - include: expressions-minus-generic-type-function-call
+
+ keywords-parens:
+ - match: '\b(alignof|typeid|static_assert|sizeof)\b\s*(\()'
+ captures:
+ 1: keyword.operator.word.c++
+ 2: meta.group.c++ punctuation.section.group.begin.c++
+ push:
+ - meta_content_scope: meta.group.c++
+ - match: '\)'
+ scope: meta.group.c++ punctuation.section.group.end.c++
+ pop: true
+ - include: expressions
+
+ namespace:
+ - match: '\b(using)\s+(namespace)\s+(?={{path_lookahead}})'
+ captures:
+ 1: keyword.control.c++
+ 2: keyword.control.c++
+ push:
+ - include: identifiers
+ - match: ''
+ pop: true
+ - match: '\b(namespace)\s+(?=({{path_lookahead}})?(?!\s*[;,]))'
+ scope: meta.namespace.c++
+ captures:
+ 1: keyword.control.c++
+ push:
+ - meta_content_scope: meta.namespace.c++ entity.name.namespace.c++
+ - include: identifiers
+ - match: ''
+ set:
+ - meta_scope: meta.namespace.c++
+ - include: comments
+ - match: '='
+ scope: keyword.operator.alias.c++
+ - match: '(?=;)'
+ pop: true
+ - match: '\}'
+ scope: meta.block.c++ punctuation.section.block.end.c++
+ pop: true
+ - match: '\{'
+ scope: punctuation.section.block.begin.c++
+ push:
+ - meta_scope: meta.block.c++
+ - match: '(?=\})'
+ pop: true
+ - include: preprocessor-global
+ - include: global
+ - include: expressions
+
+ template-common:
+ # Exit the template scope if we hit some basic invalid characters. This
+ # helps when a user is in the middle of typing their template types and
+ # prevents re-highlighting the whole file until the next > is found.
+ - match: (?=[{};])
+ pop: true
+ - include: expressions
+
+ template:
+ - match: \btemplate\b
+ scope: storage.type.template.c++
+ push:
+ - meta_scope: meta.template.c++
+ # Explicitly include comments here at the top, in order to NOT match the
+ # \S lookahead in the case of comments.
+ - include: comments
+ - match: <
+ scope: punctuation.section.generic.begin.c++
+ set:
+ - meta_content_scope: meta.template.c++
+ - match: '>'
+ scope: meta.template.c++ punctuation.section.generic.end.c++
+ pop: true
+ - match: \.{3}
+ scope: keyword.operator.variadic.c++
+ - match: \b(typename|{{before_tag}})\b
+ scope: storage.type.c++
+ - include: template # include template here for nested templates
+ - include: template-common
+ - match: (?=\S)
+ set:
+ - meta_content_scope: meta.template.c++
+ - match: \b({{before_tag}})\b
+ scope: storage.type.c++
+ - include: template-common
+
+ generic-type:
+ - match: '(?=(?!template){{path_lookahead}}\s*{{generic_lookahead}}\s*\()'
+ push:
+ - meta_scope: meta.function-call.c++
+ - match: \btemplate\b
+ scope: storage.type.template.c++
+ - match: '(?:(::)\s*)?{{identifier}}\s*(::)\s*'
+ captures:
+ 1: punctuation.accessor.double-colon.c++
+ 2: punctuation.accessor.double-colon.c++
+ - match: (?:(::)\s*)?({{identifier}})\s*(<)
+ captures:
+ 1: punctuation.accessor.double-colon.c++
+ 2: variable.function.c++
+ 3: punctuation.section.generic.begin.c++
+ push:
+ - match: '>'
+ scope: punctuation.section.generic.end.c++
+ pop: true
+ - include: expressions-minus-generic-type-function-call
+ - match: (?:(::)\s*)?({{identifier}})\s*(\()
+ captures:
+ 1: punctuation.accessor.double-colon.c++
+ 2: variable.function.c++
+ 3: punctuation.section.group.begin.c++
+ set:
+ - meta_scope: meta.function-call.c++
+ - meta_content_scope: meta.group.c++
+ - match: '\)'
+ scope: meta.group.c++ punctuation.section.group.end.c++
+ pop: true
+ - include: expressions
+ - include: angle-brackets
+ - match: '\('
+ scope: meta.group.c++ punctuation.section.group.begin.c++
+ set:
+ - meta_scope: meta.function-call.c++
+ - meta_content_scope: meta.group.c++
+ - match: '\)'
+ scope: meta.group.c++ punctuation.section.group.end.c++
+ pop: true
+ - include: expressions
+ - match: '(?=(?!template){{path_lookahead}}\s*{{generic_lookahead}})'
+ push:
+ - include: identifiers
+ - match: '<'
+ scope: punctuation.section.generic.begin.c++
+ set:
+ - match: '>'
+ scope: punctuation.section.generic.end.c++
+ pop: true
+ - include: expressions-minus-generic-type-function-call
+
+ angle-brackets:
+ - match: '<(?!<)'
+ scope: punctuation.section.generic.begin.c++
+ push:
+ - match: '>'
+ scope: punctuation.section.generic.end.c++
+ pop: true
+ - include: expressions-minus-generic-type-function-call
+
+ block:
+ - match: '\{'
+ scope: punctuation.section.block.begin.c++
+ push:
+ - meta_scope: meta.block.c++
+ - match: (?=^\s*#\s*(elif|else|endif)\b)
+ pop: true
+ - match: '\}'
+ scope: punctuation.section.block.end.c++
+ pop: true
+ - include: statements
+
+ function-call:
+ - match: (?={{path_lookahead}}\s*\()
+ push:
+ - meta_scope: meta.function-call.c++
+ - include: scope:source.c#c99
+ - match: '(?:(::)\s*)?{{identifier}}\s*(::)\s*'
+ scope: variable.function.c++
+ captures:
+ 1: punctuation.accessor.c++
+ 2: punctuation.accessor.c++
+ - match: '(?:(::)\s*)?{{identifier}}'
+ scope: variable.function.c++
+ captures:
+ 1: punctuation.accessor.c++
+ - match: '\('
+ scope: meta.group.c++ punctuation.section.group.begin.c++
+ set:
+ - meta_content_scope: meta.function-call.c++ meta.group.c++
+ - match: '\)'
+ scope: meta.function-call.c++ meta.group.c++ punctuation.section.group.end.c++
+ pop: true
+ - include: expressions
+
+ members-inside-function-call:
+ - meta_content_scope: meta.method-call.c++ meta.group.c++
+ - match: \)
+ scope: meta.method-call.c++ meta.group.c++ punctuation.section.group.end.c++
+ pop: true
+ - include: expressions
+
+ members-after-accessor-junction:
+ # After we've seen an accessor (dot or arrow), this context decides what
+ # kind of entity we're accessing.
+ - include: comments
+ - match: \btemplate\b
+ scope: meta.method-call.c++ storage.type.template.c++
+ # Guaranteed to be a template member function call after we match this
+ set:
+ - meta_content_scope: meta.method-call.c++
+ - include: comments
+ - match: '{{identifier}}'
+ scope: variable.function.member.c++
+ set:
+ - meta_content_scope: meta.method-call.c++
+ - match: \(
+ scope: meta.group.c++ punctuation.section.group.begin.c++
+ set: members-inside-function-call
+ - include: comments
+ - include: angle-brackets
+ - match: (?=\S) # safety pop
+ pop: true
+ - match: (?=\S) # safety pop
+ pop: true
+ # Operator overloading
+ - match: '({{operator_method_name}})\s*(\()'
+ captures:
+ 0: meta.method-call.c++
+ 1: variable.function.member.c++
+ 2: meta.group.c++ punctuation.section.group.begin.c++
+ set: members-inside-function-call
+ # Non-templated member function call
+ - match: (~?{{identifier}})\s*(\()
+ captures:
+ 0: meta.method-call.c++
+ 1: variable.function.member.c++
+ 2: meta.group.c++ punctuation.section.group.begin.c++
+ set: members-inside-function-call
+ # Templated member function call
+ - match: (~?{{identifier}})\s*(?={{generic_lookahead}})
+ captures:
+ 1: variable.function.member.c++
+ set:
+ - meta_scope: meta.method-call.c++
+ - match: <
+ scope: punctuation.section.generic.begin.c++
+ set:
+ - meta_content_scope: meta.method-call.c++
+ - match: '>'
+ scope: punctuation.section.generic.end.c++
+ set:
+ - meta_content_scope: meta.method-call.c++
+ - include: comments
+ - match: \(
+ scope: punctuation.section.group.begin.c++
+ set: members-inside-function-call
+ - match: (?=\S) # safety pop
+ pop: true
+ - include: expressions
+ # Explicit base-class access
+ - match: ({{identifier}})\s*(::)
+ captures:
+ 1: variable.other.base-class.c++
+ 2: punctuation.accessor.double-colon.c++
+ set: members-after-accessor-junction # reset
+ # Just a regular member variable
+ - match: '{{identifier}}'
+ scope: variable.other.readwrite.member.c++
+ pop: true
+
+ members-dot:
+ - include: scope:source.c#access-illegal
+ # No lookahead required because members-dot goes after operators in the
+ # early-expressions-after-generic-type context. This means triple dots
+ # (i.e. "..." or "variadic") is attempted first.
+ - match: \.
+ scope: punctuation.accessor.dot.c++
+ push: members-after-accessor-junction
+
+ members-arrow:
+ # This needs to be before operators in the
+ # early-expressions-after-generic-type context because otherwise the "->"
+ # from the C language will match.
+ - match: ->
+ scope: punctuation.accessor.arrow.c++
+ push: members-after-accessor-junction
+
+ typedef:
+ - match: \btypedef\b
+ scope: storage.type.c++
+ push:
+ - match: ({{identifier}})?\s*(?=;)
+ captures:
+ 1: entity.name.type.typedef.c++
+ pop: true
+ - match: \b(struct)\s+({{identifier}})\b
+ captures:
+ 1: storage.type.c++
+ - include: expressions-minus-generic-type
+
+ parens:
+ - match: \(
+ scope: punctuation.section.group.begin.c++
+ push:
+ - meta_scope: meta.group.c++
+ - match: \)
+ scope: punctuation.section.group.end.c++
+ pop: true
+ - include: expressions
+
+ brackets:
+ - match: \[
+ scope: punctuation.section.brackets.begin.c++
+ push:
+ - meta_scope: meta.brackets.c++
+ - match: \]
+ scope: punctuation.section.brackets.end.c++
+ pop: true
+ - include: expressions
+
+ function-trailing-return-type:
+ - match: '{{non_angle_brackets}}'
+ pop: true
+ - include: angle-brackets
+ - include: types
+ - include: modifiers-parens
+ - include: modifiers
+ - include: identifiers
+ - match: \*|&
+ scope: keyword.operator.c++
+ - include: function-trailing-return-type-parens
+ - match: '(?=\S)'
+ pop: true
+
+ function-trailing-return-type-parens:
+ - match: \(
+ scope: punctuation.section.group.begin.c++
+ push:
+ - meta_scope: meta.group.c++
+ - match: \)
+ scope: punctuation.section.group.end.c++
+ pop: true
+ - include: function-trailing-return-type
+
+ ## Detection of function and data structure definitions at the global level
+
+ global-modifier:
+ - include: comments
+ - include: modifiers-parens
+ - include: modifiers
+ # Constructors and destructors don't have a type
+ - match: '(?={{path_lookahead}}\s*::\s*{{identifier}}\s*(\(|$))'
+ set:
+ - meta_content_scope: meta.function.c++ entity.name.function.constructor.c++
+ - include: identifiers
+ - match: '(?=[^\w\s])'
+ set: function-definition-params
+ - match: '(?={{path_lookahead}}\s*::\s*~{{identifier}}\s*(\(|$))'
+ set:
+ - meta_content_scope: meta.function.c++ entity.name.function.destructor.c++
+ - include: identifiers
+ - match: '~{{identifier}}'
+ - match: '(?=[^\w\s])'
+ set: function-definition-params
+ # If we see a path ending in :: before a newline, we don't know if it is
+ # a constructor or destructor, or a long return type, so we are just going
+ # to treat it like a regular function. Most likely it is a constructor,
+ # since it doesn't seem most developers would create such a long typename.
+ - match: '(?={{path_lookahead}}\s*::\s*$)'
+ set:
+ - meta_content_scope: meta.function.c++ entity.name.function.c++
+ - include: identifiers
+ - match: '~{{identifier}}'
+ - match: '(?=[^\w\s])'
+ set: function-definition-params
+ - include: unique-strings
+ - match: '(?=\S)'
+ set: global-type
+
+ global-type:
+ - include: comments
+ - match: \*|&
+ scope: keyword.operator.c++
+ - match: '(?=\b({{control_keywords}}|{{operator_keywords}}|{{casts}}|{{memory_operators}}|{{other_keywords}}|operator)\b)'
+ pop: true
+ - match: '(?=\s)'
+ set: global-maybe-function
+ # If a class/struct/enum followed by a name that is not a macro or declspec
+ # then this is likely a return type of a function. This is uncommon.
+ - match: |-
+ (?x:
+ ({{before_tag}})
+ \s+
+ (?=
+ (?![[:upper:][:digit:]_]+\b|__declspec|{{before_tag}})
+ {{path_lookahead}}
+ (\s+{{identifier}}\s*\(|\s*[*&])
+ )
+ )
+ captures:
+ 1: storage.type.c++
+ set:
+ - include: identifiers
+ - match: ''
+ set: global-maybe-function
+ # The previous match handles return types of struct/enum/etc from a func,
+ # there this one exits the context to allow matching an actual struct/class
+ - match: '(?=\b({{before_tag}})\b)'
+ set: data-structures
+ - match: '(?=\b({{casts}})\b\s*<)'
+ pop: true
+ - match: '{{non_angle_brackets}}'
+ pop: true
+ - include: angle-brackets
+ - include: types
+ # Allow a macro call
+ - match: '({{identifier}})\s*(\()(?=[^\)]+\))'
+ captures:
+ 1: variable.function.c++
+ 2: meta.group.c++ punctuation.section.group.begin.c++
+ push:
+ - meta_scope: meta.function-call.c++
+ - meta_content_scope: meta.group.c++
+ - match: '\)'
+ scope: meta.group.c++ punctuation.section.group.end.c++
+ pop: true
+ - include: expressions
+ - match: '(?={{path_lookahead}}\s*\()'
+ set:
+ - include: function-call
+ - match: ''
+ pop: true
+ - include: variables
+ - include: constants
+ - include: identifiers
+ - match: (?=\W)
+ pop: true
+
+ global-maybe-function:
+ - include: comments
+ # Consume pointer info, macros and any type info that was offset by macros
+ - match: \*|&
+ scope: keyword.operator.c++
+ - match: '(?=\b({{control_keywords}}|{{operator_keywords}}|{{casts}}|{{memory_operators}}|{{other_keywords}})\b)'
+ pop: true
+ - match: '\b({{type_qualifier}})\b'
+ scope: storage.modifier.c++
+ - match: '{{non_angle_brackets}}'
+ pop: true
+ - include: angle-brackets
+ - include: types
+ - include: modifiers-parens
+ - include: modifiers
+ # All uppercase identifier just before a newline is most likely a macro
+ - match: '[[:upper:][:digit:]_]+\s*$'
+ # Operator overloading
+ - match: '(?=({{path_lookahead}}\s*(?:{{generic_lookahead}})?::\s*)?{{operator_method_name}}\s*(\(|$))'
+ set:
+ - meta_content_scope: meta.function.c++ entity.name.function.c++
+ - include: identifiers
+ - match: '(?=\s*(\(|$))'
+ set: function-definition-params
+ # Identifier that is not the function name - likely a macro or type
+ - match: '(?={{path_lookahead}}([ \t]+|[*&])(?!\s*(<|::|\(|$)))'
+ push:
+ - include: identifiers
+ - match: ''
+ pop: true
+ # Real function definition
+ - match: '(?={{path_lookahead}}({{generic_lookahead}}({{path_lookahead}})?)\s*(\(|$))'
+ set: [function-definition-params, global-function-identifier-generic]
+ - match: '(?={{path_lookahead}}\s*(\(|$))'
+ set: [function-definition-params, global-function-identifier]
+ - match: '(?={{path_lookahead}}\s*::\s*$)'
+ set: [function-definition-params, global-function-identifier]
+ - match: '(?=\S)'
+ pop: true
+
+ global-function-identifier-generic:
+ - include: angle-brackets
+ - match: '::'
+ scope: punctuation.accessor.c++
+ - match: '(?={{identifier}}<.*>\s*\()'
+ push:
+ - meta_content_scope: entity.name.function.c++
+ - include: identifiers
+ - match: '(?=<)'
+ pop: true
+ - match: '(?={{identifier}}\s*\()'
+ push:
+ - meta_content_scope: entity.name.function.c++
+ - include: identifiers
+ - match: ''
+ pop: true
+ - match: '(?=\()'
+ pop: true
+
+ global-function-identifier:
+ - meta_content_scope: entity.name.function.c++
+ - include: identifiers
+ - match: '(?=\S)'
+ pop: true
+
+ function-definition-params:
+ - meta_content_scope: meta.function.c++
+ - include: comments
+ - match: '(?=\()'
+ set:
+ - match: \(
+ scope: meta.function.parameters.c++ meta.group.c++ punctuation.section.group.begin.c++
+ set:
+ - meta_content_scope: meta.function.parameters.c++ meta.group.c++
+ - match : \)
+ scope: punctuation.section.group.end.c++
+ set: function-definition-continue
+ - match: '\bvoid\b'
+ scope: storage.type.c++
+ - match: '{{identifier}}(?=\s*(\[|,|\)|=))'
+ scope: variable.parameter.c++
+ - match: '='
+ scope: keyword.operator.assignment.c++
+ push:
+ - match: '(?=,|\))'
+ pop: true
+ - include: expressions-minus-generic-type
+ - include: scope:source.c#preprocessor-line-continuation
+ - include: expressions-minus-generic-type
+ - include: scope:source.c#preprocessor-line-continuation
+ - match: (?=\S)
+ pop: true
+
+ function-definition-continue:
+ - meta_content_scope: meta.function.c++
+ - include: comments
+ - match: '(?=;)'
+ pop: true
+ - match: '->'
+ scope: punctuation.separator.c++
+ set: function-definition-trailing-return
+ - include: function-specifiers
+ - match: '='
+ scope: keyword.operator.assignment.c++
+ - match: '&'
+ scope: keyword.operator.c++
+ - match: \b0\b
+ scope: constant.numeric.c++
+ - match: \b(default|delete)\b
+ scope: storage.modifier.c++
+ - match: '(?=\{)'
+ set: function-definition-body
+ - match: '(?=\S)'
+ pop: true
+
+ function-definition-trailing-return:
+ - include: comments
+ - match: '(?=;)'
+ pop: true
+ - match: '(?=\{)'
+ set: function-definition-body
+ - include: function-specifiers
+ - include: function-trailing-return-type
+
+ function-definition-body:
+ - meta_content_scope: meta.function.c++ meta.block.c++
+ - match: '\{'
+ scope: punctuation.section.block.begin.c++
+ set:
+ - meta_content_scope: meta.function.c++ meta.block.c++
+ - match: '\}'
+ scope: meta.function.c++ meta.block.c++ punctuation.section.block.end.c++
+ pop: true
+ - match: (?=^\s*#\s*(elif|else|endif)\b)
+ pop: true
+ - match: '(?=({{before_tag}})([^(;]+$|.*\{))'
+ push: data-structures
+ - include: statements
+
+ ## Data structures including classes, structs, unions and enums
+
+ data-structures:
+ - match: '\bclass\b'
+ scope: storage.type.c++
+ set: data-structures-class-definition
+ # Detect variable type definitions using struct/enum/union followed by a tag
+ - match: '\b({{before_tag}})(?=\s+{{path_lookahead}}\s+{{path_lookahead}}\s*[=;\[])'
+ scope: storage.type.c++
+ - match: '\bstruct\b'
+ scope: storage.type.c++
+ set: data-structures-struct-definition
+ - match: '\benum(\s+(class|struct))?\b'
+ scope: storage.type.c++
+ set: data-structures-enum-definition
+ - match: '\bunion\b'
+ scope: storage.type.c++
+ set: data-structures-union-definition
+ - match: '(?=\S)'
+ pop: true
+
+ preprocessor-workaround-eat-macro-before-identifier:
+ # Handle macros so they aren't matched as the class name
+ - match: ({{macro_identifier}})(?=\s+~?{{identifier}})
+ captures:
+ 1: meta.assumed-macro.c
+
+ data-structures-class-definition:
+ - meta_scope: meta.class.c++
+ - include: data-structures-definition-common-begin
+ - match: '{{identifier}}(?={{data_structures_forward_decl_lookahead}})'
+ scope: entity.name.class.forward-decl.c++
+ set: data-structures-class-definition-after-identifier
+ - match: '{{identifier}}'
+ scope: entity.name.class.c++
+ set: data-structures-class-definition-after-identifier
+ - match: '(?=[:{])'
+ set: data-structures-class-definition-after-identifier
+ - match: '(?=;)'
+ pop: true
+
+ data-structures-class-definition-after-identifier:
+ - meta_content_scope: meta.class.c++
+ - include: data-structures-definition-common-begin
+ # No matching of identifiers since they should all be macros at this point
+ - include: data-structures-definition-common-end
+ - match: '\{'
+ scope: meta.block.c++ punctuation.section.block.begin.c++
+ set:
+ - meta_content_scope: meta.class.c++ meta.block.c++
+ - match: '\}'
+ scope: meta.class.c++ meta.block.c++ punctuation.section.block.end.c++
+ pop: true
+ - include: data-structures-body
+
+ data-structures-struct-definition:
+ - meta_scope: meta.struct.c++
+ - include: data-structures-definition-common-begin
+ - match: '{{identifier}}(?={{data_structures_forward_decl_lookahead}})'
+ scope: entity.name.struct.forward-decl.c++
+ set: data-structures-struct-definition-after-identifier
+ - match: '{{identifier}}'
+ scope: entity.name.struct.c++
+ set: data-structures-struct-definition-after-identifier
+ - match: '(?=[:{])'
+ set: data-structures-struct-definition-after-identifier
+ - match: '(?=;)'
+ pop: true
+
+ data-structures-struct-definition-after-identifier:
+ - meta_content_scope: meta.struct.c++
+ - include: data-structures-definition-common-begin
+ # No matching of identifiers since they should all be macros at this point
+ - include: data-structures-definition-common-end
+ - match: '\{'
+ scope: meta.block.c++ punctuation.section.block.begin.c++
+ set:
+ - meta_content_scope: meta.struct.c++ meta.block.c++
+ - match: '\}'
+ scope: meta.struct.c++ meta.block.c++ punctuation.section.block.end.c++
+ pop: true
+ - include: data-structures-body
+
+ data-structures-enum-definition:
+ - meta_scope: meta.enum.c++
+ - include: data-structures-definition-common-begin
+ - match: '{{identifier}}(?={{data_structures_forward_decl_lookahead}})'
+ scope: entity.name.enum.forward-decl.c++
+ set: data-structures-enum-definition-after-identifier
+ - match: '{{identifier}}'
+ scope: entity.name.enum.c++
+ set: data-structures-enum-definition-after-identifier
+ - match: '(?=[:{])'
+ set: data-structures-enum-definition-after-identifier
+ - match: '(?=;)'
+ pop: true
+
+ data-structures-enum-definition-after-identifier:
+ - meta_content_scope: meta.enum.c++
+ - include: data-structures-definition-common-begin
+ # No matching of identifiers since they should all be macros at this point
+ - include: data-structures-definition-common-end
+ - match: '\{'
+ scope: meta.block.c++ punctuation.section.block.begin.c++
+ set:
+ - meta_content_scope: meta.enum.c++ meta.block.c++
+ # Enums don't support methods so we have a simplified body
+ - match: '\}'
+ scope: meta.enum.c++ meta.block.c++ punctuation.section.block.end.c++
+ pop: true
+ - include: statements
+
+ data-structures-union-definition:
+ - meta_scope: meta.union.c++
+ - include: data-structures-definition-common-begin
+ - match: '{{identifier}}(?={{data_structures_forward_decl_lookahead}})'
+ scope: entity.name.union.forward-decl.c++
+ set: data-structures-union-definition-after-identifier
+ - match: '{{identifier}}'
+ scope: entity.name.union.c++
+ set: data-structures-union-definition-after-identifier
+ - match: '(?=[{])'
+ set: data-structures-union-definition-after-identifier
+ - match: '(?=;)'
+ pop: true
+
+ data-structures-union-definition-after-identifier:
+ - meta_content_scope: meta.union.c++
+ - include: data-structures-definition-common-begin
+ # No matching of identifiers since they should all be macros at this point
+ # Unions don't support base classes
+ - include: angle-brackets
+ - match: '\{'
+ scope: meta.block.c++ punctuation.section.block.begin.c++
+ set:
+ - meta_content_scope: meta.union.c++ meta.block.c++
+ - match: '\}'
+ scope: meta.union.c++ meta.block.c++ punctuation.section.block.end.c++
+ pop: true
+ - include: data-structures-body
+ - match: '(?=;)'
+ pop: true
+
+ data-structures-definition-common-begin:
+ - include: comments
+ - match: '(?=\b(?:{{before_tag}}|{{control_keywords}})\b)'
+ pop: true
+ - include: preprocessor-other
+ - include: modifiers-parens
+ - include: modifiers
+ - include: preprocessor-workaround-eat-macro-before-identifier
+
+ data-structures-definition-common-end:
+ - include: angle-brackets
+ - match: \bfinal\b
+ scope: storage.modifier.c++
+ - match: ':'
+ scope: punctuation.separator.c++
+ push:
+ - include: comments
+ - include: preprocessor-other
+ - include: modifiers-parens
+ - include: modifiers
+ - match: '\b(virtual|{{visibility_modifiers}})\b'
+ scope: storage.modifier.c++
+ - match: (?={{path_lookahead}})
+ push:
+ - meta_scope: entity.other.inherited-class.c++
+ - include: identifiers
+ - match: ''
+ pop: true
+ - include: angle-brackets
+ - match: ','
+ scope: punctuation.separator.c++
+ - match: (?=\{|;)
+ pop: true
+ - match: '(?=;)'
+ pop: true
+
+ data-structures-body:
+ - include: preprocessor-data-structures
+ - match: '(?=\btemplate\b)'
+ push:
+ - include: template
+ - match: (?=\S)
+ set: data-structures-modifier
+ - include: typedef
+ - match: \b({{visibility_modifiers}})\s*(:)(?!:)
+ captures:
+ 1: storage.modifier.c++
+ 2: punctuation.section.class.c++
+ - match: '^\s*(?=(?:~?\w+|::))'
+ push: data-structures-modifier
+ - include: expressions-minus-generic-type
+
+ data-structures-modifier:
+ - match: '\bfriend\b'
+ scope: storage.modifier.c++
+ push:
+ - match: (?=;)
+ pop: true
+ - match: '\{'
+ scope: punctuation.section.block.begin.c++
+ set:
+ - meta_scope: meta.block.c++
+ - match: '\}'
+ scope: punctuation.section.block.end.c++
+ pop: true
+ - include: statements
+ - match: '\b({{before_tag}})\b'
+ scope: storage.type.c++
+ - include: expressions-minus-function-call
+ - include: comments
+ - include: modifiers-parens
+ - include: modifiers
+ - match: '\bstatic_assert(?=\s*\()'
+ scope: meta.static-assert.c++ keyword.operator.word.c++
+ push:
+ - match: '\('
+ scope: meta.group.c++ punctuation.section.group.begin.c++
+ set:
+ - meta_content_scope: meta.function-call.c++ meta.group.c++
+ - match: '\)'
+ scope: meta.function-call.c++ meta.group.c++ punctuation.section.group.end.c++
+ pop: true
+ - include: expressions
+ # Destructor
+ - match: '(?:{{identifier}}\s*(::)\s*)?~{{identifier}}(?=\s*(\(|$))'
+ scope: meta.method.destructor.c++ entity.name.function.destructor.c++
+ captures:
+ 1: punctuation.accessor.c++
+ set: method-definition-params
+ # It's a macro, not a constructor if there is no type in the first param
+ - match: '({{identifier}})\s*(\()(?=\s*(?!void){{identifier}}\s*[),])'
+ captures:
+ 1: variable.function.c++
+ 2: meta.group.c++ punctuation.section.group.begin.c++
+ push:
+ - meta_scope: meta.function-call.c++
+ - meta_content_scope: meta.group.c++
+ - match: '\)'
+ scope: meta.group.c++ punctuation.section.group.end.c++
+ pop: true
+ - include: expressions
+ # Constructor
+ - include: preprocessor-workaround-eat-macro-before-identifier
+ - match: '((?!{{before_tag}}|template){{identifier}})(?=\s*\()'
+ scope: meta.method.constructor.c++ entity.name.function.constructor.c++
+ set: method-definition-params
+ # Long form constructor
+ - match: '({{identifier}}\s*(::)\s*{{identifier}})(?=\s*\()'
+ captures:
+ 1: meta.method.constructor.c++ entity.name.function.constructor.c++
+ 2: punctuation.accessor.c++
+ push: method-definition-params
+ - match: '(?=\S)'
+ set: data-structures-type
+
+ data-structures-type:
+ - include: comments
+ - match: \*|&
+ scope: keyword.operator.c++
+ # Cast methods
+ - match: '(operator)\s+({{identifier}})(?=\s*(\(|$))'
+ captures:
+ 1: keyword.control.c++
+ 2: meta.method.c++ entity.name.function.c++
+ set: method-definition-params
+ - match: '(?=\b({{control_keywords}}|{{operator_keywords}}|{{casts}}|{{memory_operators}}|{{other_keywords}}|operator)\b)'
+ pop: true
+ - match: '(?=\s)'
+ set: data-structures-maybe-method
+ # If a class/struct/enum followed by a name that is not a macro or declspec
+ # then this is likely a return type of a function. This is uncommon.
+ - match: |-
+ (?x:
+ ({{before_tag}})
+ \s+
+ (?=
+ (?![[:upper:][:digit:]_]+\b|__declspec|{{before_tag}})
+ {{path_lookahead}}
+ (\s+{{identifier}}\s*\(|\s*[*&])
+ )
+ )
+ captures:
+ 1: storage.type.c++
+ set:
+ - include: identifiers
+ - match: ''
+ set: data-structures-maybe-method
+ # The previous match handles return types of struct/enum/etc from a func,
+ # there this one exits the context to allow matching an actual struct/class
+ - match: '(?=\b({{before_tag}})\b)'
+ set: data-structures
+ - match: '(?=\b({{casts}})\b\s*<)'
+ pop: true
+ - match: '{{non_angle_brackets}}'
+ pop: true
+ - include: angle-brackets
+ - include: types
+ - include: variables
+ - include: constants
+ - include: identifiers
+ - match: (?=[&*])
+ set: data-structures-maybe-method
+ - match: (?=\W)
+ pop: true
+
+ data-structures-maybe-method:
+ - include: comments
+ # Consume pointer info, macros and any type info that was offset by macros
+ - match: \*|&
+ scope: keyword.operator.c++
+ - match: '(?=\b({{control_keywords}}|{{operator_keywords}}|{{casts}}|{{memory_operators}}|{{other_keywords}})\b)'
+ pop: true
+ - match: '\b({{type_qualifier}})\b'
+ scope: storage.modifier.c++
+ - match: '{{non_angle_brackets}}'
+ pop: true
+ - include: angle-brackets
+ - include: types
+ - include: modifiers-parens
+ - include: modifiers
+ # Operator overloading
+ - match: '{{operator_method_name}}(?=\s*(\(|$))'
+ scope: meta.method.c++ entity.name.function.c++
+ set: method-definition-params
+ # Identifier that is not the function name - likely a macro or type
+ - match: '(?={{path_lookahead}}([ \t]+|[*&])(?!\s*(<|::|\()))'
+ push:
+ - include: identifiers
+ - match: ''
+ pop: true
+ # Real function definition
+ - match: '(?={{path_lookahead}}({{generic_lookahead}})\s*(\())'
+ set: [method-definition-params, data-structures-function-identifier-generic]
+ - match: '(?={{path_lookahead}}\s*(\())'
+ set: [method-definition-params, data-structures-function-identifier]
+ - match: '(?={{path_lookahead}}\s*::\s*$)'
+ set: [method-definition-params, data-structures-function-identifier]
+ - match: '(?=\S)'
+ pop: true
+
+ data-structures-function-identifier-generic:
+ - include: angle-brackets
+ - match: '(?={{identifier}})'
+ push:
+ - meta_content_scope: entity.name.function.c++
+ - include: identifiers
+ - match: '(?=<)'
+ pop: true
+ - match: '(?=\()'
+ pop: true
+
+ data-structures-function-identifier:
+ - meta_content_scope: entity.name.function.c++
+ - include: identifiers
+ - match: '(?=\S)'
+ pop: true
+
+ method-definition-params:
+ - meta_content_scope: meta.method.c++
+ - include: comments
+ - match: '(?=\()'
+ set:
+ - match: \(
+ scope: meta.method.parameters.c++ meta.group.c++ punctuation.section.group.begin.c++
+ set:
+ - meta_content_scope: meta.method.parameters.c++ meta.group.c++
+ - match : \)
+ scope: punctuation.section.group.end.c++
+ set: method-definition-continue
+ - match: '\bvoid\b'
+ scope: storage.type.c++
+ - match: '{{identifier}}(?=\s*(\[|,|\)|=))'
+ scope: variable.parameter.c++
+ - match: '='
+ scope: keyword.operator.assignment.c++
+ push:
+ - match: '(?=,|\))'
+ pop: true
+ - include: expressions-minus-generic-type
+ - include: expressions-minus-generic-type
+ - match: '(?=\S)'
+ pop: true
+
+ method-definition-continue:
+ - meta_content_scope: meta.method.c++
+ - include: comments
+ - match: '(?=;)'
+ pop: true
+ - match: '->'
+ scope: punctuation.separator.c++
+ set: method-definition-trailing-return
+ - include: function-specifiers
+ - match: '='
+ scope: keyword.operator.assignment.c++
+ - match: '&'
+ scope: keyword.operator.c++
+ - match: \b0\b
+ scope: constant.numeric.c++
+ - match: \b(default|delete)\b
+ scope: storage.modifier.c++
+ - match: '(?=:)'
+ set:
+ - match: ':'
+ scope: punctuation.separator.initializer-list.c++
+ set:
+ - meta_scope: meta.method.constructor.initializer-list.c++
+ - match: '{{identifier}}'
+ scope: variable.other.readwrite.member.c++
+ push:
+ - match: \(
+ scope: meta.group.c++ punctuation.section.group.begin.c++
+ set:
+ - meta_content_scope: meta.group.c++
+ - match: \)
+ scope: meta.group.c++ punctuation.section.group.end.c++
+ pop: true
+ - include: expressions
+ - match: \{
+ scope: meta.group.c++ punctuation.section.group.begin.c++
+ set:
+ - meta_content_scope: meta.group.c++
+ - match: \}
+ scope: meta.group.c++ punctuation.section.group.end.c++
+ pop: true
+ - include: expressions
+ - include: comments
+ - match: (?=\{|;)
+ set: method-definition-continue
+ - include: expressions
+ - match: '(?=\{)'
+ set: method-definition-body
+ - match: '(?=\S)'
+ pop: true
+
+ method-definition-trailing-return:
+ - include: comments
+ - match: '(?=;)'
+ pop: true
+ - match: '(?=\{)'
+ set: method-definition-body
+ - include: function-specifiers
+ - include: function-trailing-return-type
+
+ method-definition-body:
+ - meta_content_scope: meta.method.c++ meta.block.c++
+ - match: '\{'
+ scope: punctuation.section.block.begin.c++
+ set:
+ - meta_content_scope: meta.method.c++ meta.block.c++
+ - match: '\}'
+ scope: meta.method.c++ meta.block.c++ punctuation.section.block.end.c++
+ pop: true
+ - match: (?=^\s*#\s*(elif|else|endif)\b)
+ pop: true
+ - match: '(?=({{before_tag}})([^(;]+$|.*\{))'
+ push: data-structures
+ - include: statements
+
+ ## Preprocessor for data-structures
+
+ preprocessor-data-structures:
+ - include: preprocessor-rule-enabled-data-structures
+ - include: preprocessor-rule-disabled-data-structures
+ - include: preprocessor-practical-workarounds
+
+ preprocessor-rule-disabled-data-structures:
+ - match: ^\s*((#if)\s+(0))\b
+ captures:
+ 1: meta.preprocessor.c++
+ 2: keyword.control.import.c++
+ 3: constant.numeric.preprocessor.c++
+ push:
+ - match: ^\s*(#\s*endif)\b
+ captures:
+ 1: meta.preprocessor.c++ keyword.control.import.c++
+ pop: true
+ - match: ^\s*(#\s*else)\b
+ captures:
+ 1: meta.preprocessor.c++ keyword.control.import.else.c++
+ push:
+ - match: (?=^\s*#\s*endif\b)
+ pop: true
+ - include: negated-block
+ - include: data-structures-body
+ - match: ""
+ push:
+ - meta_scope: comment.block.preprocessor.if-branch.c++
+ - match: (?=^\s*#\s*(else|endif)\b)
+ pop: true
+ - include: scope:source.c#preprocessor-disabled
+
+ preprocessor-rule-enabled-data-structures:
+ - match: ^\s*((#if)\s+(0*1))\b
+ captures:
+ 1: meta.preprocessor.c++
+ 2: keyword.control.import.c++
+ 3: constant.numeric.preprocessor.c++
+ push:
+ - match: ^\s*(#\s*endif)\b
+ captures:
+ 1: meta.preprocessor.c++ keyword.control.import.c++
+ pop: true
+ - match: ^\s*(#\s*else)\b
+ captures:
+ 1: meta.preprocessor.c++ keyword.control.import.else.c++
+ push:
+ - meta_content_scope: comment.block.preprocessor.else-branch.c++
+ - match: (?=^\s*#\s*endif\b)
+ pop: true
+ - include: scope:source.c#preprocessor-disabled
+ - match: ""
+ push:
+ - match: (?=^\s*#\s*(else|endif)\b)
+ pop: true
+ - include: negated-block
+ - include: data-structures-body
+
+ ## Preprocessor for global
+
+ preprocessor-global:
+ - include: preprocessor-rule-enabled-global
+ - include: preprocessor-rule-disabled-global
+ - include: preprocessor-rule-other-global
+
+ preprocessor-statements:
+ - include: preprocessor-rule-enabled-statements
+ - include: preprocessor-rule-disabled-statements
+ - include: preprocessor-rule-other-statements
+
+ preprocessor-expressions:
+ - include: scope:source.c#incomplete-inc
+ - include: preprocessor-macro-define
+ - include: scope:source.c#pragma-mark
+ - include: preprocessor-other
+
+ preprocessor-rule-disabled-global:
+ - match: ^\s*((#if)\s+(0))\b
+ captures:
+ 1: meta.preprocessor.c++
+ 2: keyword.control.import.c++
+ 3: constant.numeric.preprocessor.c++
+ push:
+ - match: ^\s*(#\s*endif)\b
+ captures:
+ 1: meta.preprocessor.c++ keyword.control.import.c++
+ pop: true
+ - match: ^\s*(#\s*else)\b
+ captures:
+ 1: meta.preprocessor.c++ keyword.control.import.else.c++
+ push:
+ - match: (?=^\s*#\s*endif\b)
+ pop: true
+ - include: preprocessor-global
+ - include: negated-block
+ - include: global
+ - match: ""
+ push:
+ - meta_scope: comment.block.preprocessor.if-branch.c++
+ - match: (?=^\s*#\s*(else|endif)\b)
+ pop: true
+ - include: scope:source.c#preprocessor-disabled
+
+ preprocessor-rule-enabled-global:
+ - match: ^\s*((#if)\s+(0*1))\b
+ captures:
+ 1: meta.preprocessor.c++
+ 2: keyword.control.import.c++
+ 3: constant.numeric.preprocessor.c++
+ push:
+ - match: ^\s*(#\s*endif)\b
+ captures:
+ 1: meta.preprocessor.c++ keyword.control.import.c++
+ pop: true
+ - match: ^\s*(#\s*else)\b
+ captures:
+ 1: meta.preprocessor.c++ keyword.control.import.else.c++
+ push:
+ - meta_content_scope: comment.block.preprocessor.else-branch.c++
+ - match: (?=^\s*#\s*endif\b)
+ pop: true
+ - include: scope:source.c#preprocessor-disabled
+ - match: ""
+ push:
+ - match: (?=^\s*#\s*(else|endif)\b)
+ pop: true
+ - include: preprocessor-global
+ - include: negated-block
+ - include: global
+
+ preprocessor-rule-other-global:
+ - match: ^\s*(#\s*(?:if|ifdef|ifndef))\b
+ captures:
+ 1: keyword.control.import.c++
+ push:
+ - meta_scope: meta.preprocessor.c++
+ - include: scope:source.c#preprocessor-line-continuation
+ - include: scope:source.c#preprocessor-comments
+ - match: \bdefined\b
+ scope: keyword.control.c++
+ # Enter a new scope where all elif/else branches have their
+ # contexts popped by a subsequent elif/else/endif. This ensures that
+ # preprocessor branches don't push multiple meta.block scopes on
+ # the stack, thus messing up the "global" context's detection of
+ # functions.
+ - match: $\n
+ set: preprocessor-if-branch-global
+
+ # These gymnastics here ensure that we are properly handling scope even
+ # when the preprocessor is used to create different scope beginnings, such
+ # as a different if/while condition
+ preprocessor-if-branch-global:
+ - match: ^\s*(#\s*endif)\b
+ captures:
+ 1: meta.preprocessor.c++ keyword.control.import.c++
+ pop: true
+ - match: (?=^\s*#\s*(elif|else)\b)
+ push: preprocessor-elif-else-branch-global
+ - match: \{
+ scope: punctuation.section.block.begin.c++
+ set: preprocessor-block-if-branch-global
+ - include: preprocessor-global
+ - include: negated-block
+ - include: global
+
+ preprocessor-block-if-branch-global:
+ - meta_scope: meta.block.c++
+ - match: ^\s*(#\s*endif)\b
+ captures:
+ 1: meta.preprocessor.c++ keyword.control.import.c++
+ set: preprocessor-block-finish-global
+ - match: (?=^\s*#\s*(elif|else)\b)
+ push: preprocessor-elif-else-branch-global
+ - match: \}
+ scope: punctuation.section.block.end.c++
+ set: preprocessor-if-branch-global
+ - include: statements
+
+ preprocessor-block-finish-global:
+ - meta_scope: meta.block.c++
+ - match: ^\s*(#\s*(?:if|ifdef|ifndef))\b
+ captures:
+ 1: meta.preprocessor.c++ keyword.control.import.c++
+ set: preprocessor-block-finish-if-branch-global
+ - match: \}
+ scope: punctuation.section.block.end.c++
+ pop: true
+ - include: statements
+
+ preprocessor-block-finish-if-branch-global:
+ - match: ^\s*(#\s*endif)\b
+ captures:
+ 1: keyword.control.import.c++
+ pop: true
+ - match: \}
+ scope: punctuation.section.block.end.c++
+ set: preprocessor-if-branch-global
+ - include: statements
+
+ preprocessor-elif-else-branch-global:
+ - match: (?=^\s*#\s*(endif)\b)
+ pop: true
+ - include: preprocessor-global
+ - include: negated-block
+ - include: global
+
+ ## Preprocessor for statements
+
+ preprocessor-rule-disabled-statements:
+ - match: ^\s*((#if)\s+(0))\b
+ captures:
+ 1: meta.preprocessor.c++
+ 2: keyword.control.import.c++
+ 3: constant.numeric.preprocessor.c++
+ push:
+ - match: ^\s*(#\s*endif)\b
+ captures:
+ 1: meta.preprocessor.c++ keyword.control.import.c++
+ pop: true
+ - match: ^\s*(#\s*else)\b
+ captures:
+ 1: meta.preprocessor.c++ keyword.control.import.else.c++
+ push:
+ - match: (?=^\s*#\s*endif\b)
+ pop: true
+ - include: negated-block
+ - include: statements
+ - match: ""
+ push:
+ - meta_scope: comment.block.preprocessor.if-branch.c++
+ - match: (?=^\s*#\s*(else|endif)\b)
+ pop: true
+ - include: scope:source.c#preprocessor-disabled
+
+ preprocessor-rule-enabled-statements:
+ - match: ^\s*((#if)\s+(0*1))\b
+ captures:
+ 1: meta.preprocessor.c++
+ 2: keyword.control.import.c++
+ 3: constant.numeric.preprocessor.c++
+ push:
+ - match: ^\s*(#\s*endif)\b
+ captures:
+ 1: meta.preprocessor.c++ keyword.control.import.c++
+ pop: true
+ - match: ^\s*(#\s*else)\b
+ captures:
+ 1: meta.preprocessor.c++ keyword.control.import.else.c++
+ push:
+ - meta_content_scope: comment.block.preprocessor.else-branch.c++
+ - match: (?=^\s*#\s*endif\b)
+ pop: true
+ - include: scope:source.c#preprocessor-disabled
+ - match: ""
+ push:
+ - match: (?=^\s*#\s*(else|endif)\b)
+ pop: true
+ - include: negated-block
+ - include: statements
+
+ preprocessor-rule-other-statements:
+ - match: ^\s*(#\s*(?:if|ifdef|ifndef))\b
+ captures:
+ 1: keyword.control.import.c++
+ push:
+ - meta_scope: meta.preprocessor.c++
+ - include: scope:source.c#preprocessor-line-continuation
+ - include: scope:source.c#preprocessor-comments
+ - match: \bdefined\b
+ scope: keyword.control.c++
+ # Enter a new scope where all elif/else branches have their
+ # contexts popped by a subsequent elif/else/endif. This ensures that
+ # preprocessor branches don't push multiple meta.block scopes on
+ # the stack, thus messing up the "global" context's detection of
+ # functions.
+ - match: $\n
+ set: preprocessor-if-branch-statements
+
+ # These gymnastics here ensure that we are properly handling scope even
+ # when the preprocessor is used to create different scope beginnings, such
+ # as a different if/while condition
+ preprocessor-if-branch-statements:
+ - match: ^\s*(#\s*endif)\b
+ captures:
+ 1: meta.preprocessor.c++ keyword.control.import.c++
+ pop: true
+ - match: (?=^\s*#\s*(elif|else)\b)
+ push: preprocessor-elif-else-branch-statements
+ - match: \{
+ scope: punctuation.section.block.begin.c++
+ set: preprocessor-block-if-branch-statements
+ - match: (?=(?!{{non_func_keywords}}){{path_lookahead}}\s*\()
+ set: preprocessor-if-branch-function-call
+ - include: negated-block
+ - include: statements
+
+ preprocessor-if-branch-function-call:
+ - meta_content_scope: meta.function-call.c++
+ - include: scope:source.c#c99
+ - match: '(?:(::)\s*)?{{identifier}}\s*(::)\s*'
+ scope: variable.function.c++
+ captures:
+ 1: punctuation.accessor.c++
+ 2: punctuation.accessor.c++
+ - match: '(?:(::)\s*)?{{identifier}}'
+ scope: variable.function.c++
+ captures:
+ 1: punctuation.accessor.c++
+ - match: '\('
+ scope: meta.group.c++ punctuation.section.group.begin.c++
+ set: preprocessor-if-branch-function-call-arguments
+
+ preprocessor-if-branch-function-call-arguments:
+ - meta_content_scope: meta.function-call.c++ meta.group.c++
+ - match : \)
+ scope: meta.function-call.c++ meta.group.c++ punctuation.section.group.end.c++
+ set: preprocessor-if-branch-statements
+ - match: ^\s*(#\s*(?:elif|else))\b
+ captures:
+ 1: meta.preprocessor.c++ keyword.control.import.c++
+ set: preprocessor-if-branch-statements
+ - match: ^\s*(#\s*endif)\b
+ captures:
+ 1: meta.preprocessor.c++ keyword.control.import.c++
+ set: preprocessor-if-branch-function-call-arguments-finish
+ - include: expressions
+
+ preprocessor-if-branch-function-call-arguments-finish:
+ - meta_content_scope: meta.function-call.c++ meta.group.c++
+ - match: \)
+ scope: meta.function-call.c++ meta.group.c++ punctuation.section.group.end.c++
+ pop: true
+ - include: expressions
+
+ preprocessor-block-if-branch-statements:
+ - meta_scope: meta.block.c++
+ - match: ^\s*(#\s*endif)\b
+ captures:
+ 1: meta.preprocessor.c++ keyword.control.import.c++
+ set: preprocessor-block-finish-statements
+ - match: (?=^\s*#\s*(elif|else)\b)
+ push: preprocessor-elif-else-branch-statements
+ - match: \}
+ scope: punctuation.section.block.end.c++
+ set: preprocessor-if-branch-statements
+ - include: statements
+
+ preprocessor-block-finish-statements:
+ - meta_scope: meta.block.c++
+ - match: ^\s*(#\s*(?:if|ifdef|ifndef))\b
+ captures:
+ 1: meta.preprocessor.c++ keyword.control.import.c++
+ set: preprocessor-block-finish-if-branch-statements
+ - match: \}
+ scope: punctuation.section.block.end.c++
+ pop: true
+ - include: statements
+
+ preprocessor-block-finish-if-branch-statements:
+ - match: ^\s*(#\s*endif)\b
+ captures:
+ 1: keyword.control.import.c++
+ pop: true
+ - match: \}
+ scope: meta.block.c++ punctuation.section.block.end.c++
+ set: preprocessor-if-branch-statements
+ - include: statements
+
+ preprocessor-elif-else-branch-statements:
+ - match: (?=^\s*#\s*endif\b)
+ pop: true
+ - include: negated-block
+ - include: statements
+
+ ## Preprocessor other
+
+ negated-block:
+ - match: '\}'
+ scope: punctuation.section.block.end.c++
+ push:
+ - match: '\{'
+ scope: punctuation.section.block.begin.c++
+ pop: true
+ - match: (?=^\s*#\s*(elif|else|endif)\b)
+ pop: true
+ - include: statements
+
+ preprocessor-macro-define:
+ - match: ^\s*(\#\s*define)\b
+ captures:
+ 1: meta.preprocessor.macro.c++ keyword.control.import.define.c++
+ push:
+ - meta_content_scope: meta.preprocessor.macro.c++
+ - include: scope:source.c#preprocessor-line-continuation
+ - include: scope:source.c#preprocessor-line-ending
+ - include: scope:source.c#preprocessor-comments
+ - match: '({{identifier}})(?=\()'
+ scope: entity.name.function.preprocessor.c++
+ set:
+ - match: '\('
+ scope: punctuation.section.group.begin.c++
+ set: preprocessor-macro-params
+ - match: '{{identifier}}'
+ scope: entity.name.constant.preprocessor.c++
+ set: preprocessor-macro-definition
+
+ preprocessor-macro-params:
+ - meta_scope: meta.preprocessor.macro.parameters.c++ meta.group.c++
+ - match: '{{identifier}}'
+ scope: variable.parameter.c++
+ - match: \)
+ scope: punctuation.section.group.end.c++
+ set: preprocessor-macro-definition
+ - match: ','
+ scope: punctuation.separator.c++
+ push:
+ - match: '{{identifier}}'
+ scope: variable.parameter.c++
+ pop: true
+ - include: scope:source.c#preprocessor-line-continuation
+ - include: scope:source.c#preprocessor-comments
+ - match: '\.\.\.'
+ scope: keyword.operator.variadic.c++
+ - match: '(?=\))'
+ pop: true
+ - match: (/\*).*(\*/)
+ scope: comment.block.c++
+ captures:
+ 1: punctuation.definition.comment.c++
+ 2: punctuation.definition.comment.c++
+ - match: '\S+'
+ scope: invalid.illegal.unexpected-character.c++
+ - include: scope:source.c#preprocessor-line-continuation
+ - include: scope:source.c#preprocessor-comments
+ - match: '\.\.\.'
+ scope: keyword.operator.variadic.c++
+ - match: (/\*).*(\*/)
+ scope: comment.block.c++
+ captures:
+ 1: punctuation.definition.comment.c++
+ 2: punctuation.definition.comment.c++
+ - match: $\n
+ scope: invalid.illegal.unexpected-end-of-line.c++
+
+ preprocessor-macro-definition:
+ - meta_content_scope: meta.preprocessor.macro.c++
+ - include: scope:source.c#preprocessor-line-continuation
+ - include: scope:source.c#preprocessor-line-ending
+ - include: scope:source.c#preprocessor-comments
+ # Don't define blocks in define statements
+ - match: '\{'
+ scope: punctuation.section.block.begin.c++
+ - match: '\}'
+ scope: punctuation.section.block.end.c++
+ - include: expressions
+
+ preprocessor-practical-workarounds:
+ - include: preprocessor-convention-ignore-uppercase-ident-lines
+ - include: scope:source.c#preprocessor-convention-ignore-uppercase-calls-without-semicolon
+
+ preprocessor-convention-ignore-uppercase-ident-lines:
+ - match: ^(\s*{{macro_identifier}})+\s*$
+ scope: meta.assumed-macro.c++
+ push:
+ # It's possible that we are dealing with a function return type on its own line, and the
+ # name of the function is on the subsequent line.
+ - match: '(?={{path_lookahead}}({{generic_lookahead}}({{path_lookahead}})?)\s*\()'
+ set: [function-definition-params, global-function-identifier-generic]
+ - match: '(?={{path_lookahead}}\s*\()'
+ set: [function-definition-params, global-function-identifier]
+ - match: ^
+ pop: true
+
+ preprocessor-other:
+ - match: ^\s*(#\s*(?:if|ifdef|ifndef|elif|else|line|pragma|undef))\b
+ captures:
+ 1: keyword.control.import.c++
+ push:
+ - meta_scope: meta.preprocessor.c++
+ - include: scope:source.c#preprocessor-line-continuation
+ - include: scope:source.c#preprocessor-line-ending
+ - include: scope:source.c#preprocessor-comments
+ - match: \bdefined\b
+ scope: keyword.control.c++
+ - match: ^\s*(#\s*endif)\b
+ captures:
+ 1: meta.preprocessor.c++ keyword.control.import.c++
+ - match: ^\s*(#\s*(?:error|warning))\b
+ captures:
+ 1: keyword.control.import.error.c++
+ push:
+ - meta_scope: meta.preprocessor.diagnostic.c++
+ - include: scope:source.c#preprocessor-line-continuation
+ - include: scope:source.c#preprocessor-line-ending
+ - include: scope:source.c#preprocessor-comments
+ - include: strings
+ - match: '\S+'
+ scope: string.unquoted.c++
+ - match: ^\s*(#\s*(?:include|include_next|import))\b
+ captures:
+ 1: keyword.control.import.include.c++
+ push:
+ - meta_scope: meta.preprocessor.include.c++
+ - include: scope:source.c#preprocessor-line-continuation
+ - include: scope:source.c#preprocessor-line-ending
+ - include: scope:source.c#preprocessor-comments
+ - match: '"'
+ scope: punctuation.definition.string.begin.c++
+ push:
+ - meta_scope: string.quoted.double.include.c++
+ - match: '"'
+ scope: punctuation.definition.string.end.c++
+ pop: true
+ - match: <
+ scope: punctuation.definition.string.begin.c++
+ push:
+ - meta_scope: string.quoted.other.lt-gt.include.c++
+ - match: '>'
+ scope: punctuation.definition.string.end.c++
+ pop: true
+ - include: preprocessor-practical-workarounds
diff --git a/support/Vagrantfile b/support/Vagrantfile
new file mode 100644
index 0000000..de0fcb9
--- /dev/null
+++ b/support/Vagrantfile
@@ -0,0 +1,19 @@
+# -*- mode: ruby -*-
+# vi: set ft=ruby :
+
+# A vagrant config for testing against gcc-4.8.
+Vagrant.configure("2") do |config|
+ config.vm.box = "ubuntu/trusty64"
+
+ config.vm.provider "virtualbox" do |vb|
+ vb.memory = "4096"
+ end
+
+ config.vm.provision "shell", inline: <<-SHELL
+ apt-get update
+ apt-get install -y g++ make wget git
+ wget -q https://github.com/Kitware/CMake/releases/download/v3.14.4/cmake-3.14.4-Linux-x86_64.tar.gz
+ tar xzf cmake-3.14.4-Linux-x86_64.tar.gz
+ ln -s `pwd`/cmake-3.14.4-Linux-x86_64/bin/cmake /usr/local/bin
+ SHELL
+end
diff --git a/support/appveyor-build.py b/support/appveyor-build.py
index 2cfcb03..6544610 100644
--- a/support/appveyor-build.py
+++ b/support/appveyor-build.py
@@ -23,14 +23,17 @@
# Add MSBuild 14.0 to PATH as described in
# http://help.appveyor.com/discussions/problems/2229-v140-not-found-on-vs2105rc.
os.environ['PATH'] = r'C:\Program Files (x86)\MSBuild\15.0\Bin;' + path
- if image == 'Visual Studio 2013':
- generator = 'Visual Studio 12 2013'
- elif image == 'Visual Studio 2015':
- generator = 'Visual Studio 14 2015'
- elif image == 'Visual Studio 2017':
- generator = 'Visual Studio 15 2017'
- if platform == 'x64':
- generator += ' Win64'
+ if image == 'Visual Studio 2019':
+ generator = 'Visual Studio 16 2019'
+ if platform == 'x64':
+ cmake_command.extend(['-A', 'x64'])
+ else:
+ if image == 'Visual Studio 2015':
+ generator = 'Visual Studio 14 2015'
+ elif image == 'Visual Studio 2017':
+ generator = 'Visual Studio 15 2017'
+ if platform == 'x64':
+ generator += ' Win64'
cmake_command.append('-G' + generator)
build_command = ['cmake', '--build', '.', '--config', config, '--', '/m:4']
test_command = ['ctest', '-C', config]
diff --git a/support/appveyor.yml b/support/appveyor.yml
index af298cf..f53e438 100644
--- a/support/appveyor.yml
+++ b/support/appveyor.yml
@@ -4,20 +4,27 @@
clone_depth: 1
+image:
+ - Visual Studio 2015
+ - Visual Studio 2019
+ - Visual Studio 2017
+
platform:
- Win32
- x64
-image:
- - Visual Studio 2013
- - Visual Studio 2015
- - Visual Studio 2017
-
environment:
CTEST_OUTPUT_ON_FAILURE: 1
MSVC_DEFAULT_OPTIONS: ON
BUILD: msvc
+matrix:
+ exclude:
+ - image: Visual Studio 2015
+ platform: Win32
+ - image: Visual Studio 2019
+ platform: Win32
+
before_build:
- mkdir build
- cd build
diff --git a/support/build.gradle b/support/build.gradle
index 797cf49..11648da 100644
--- a/support/build.gradle
+++ b/support/build.gradle
@@ -9,10 +9,12 @@
//
// https://developer.android.com/studio/releases/gradle-plugin
//
- // Notice that 3.1.3 here is the version of [Android Gradle Plugin]
- // Accroding to URL above you will need Gradle 4.4 or higher
+ // Notice that 3.3.0 here is the version of [Android Gradle Plugin]
+ // Accroding to URL above you will need Gradle 5.0 or higher
//
- classpath 'com.android.tools.build:gradle:3.1.3'
+ // If you are using Android Studio, and it is using Gradle's lower
+ // version, Use the plugin version 3.1.3 ~ 3.2.0 for Gradle 4.4 ~ 4.10
+ classpath 'com.android.tools.build:gradle:3.3.0'
}
}
repositories {
@@ -43,8 +45,8 @@
defaultConfig {
minSdkVersion 21 // Android 5.0+
targetSdkVersion 25 // Follow Compile SDK
- versionCode 20 // Follow release count
- versionName "5.2.1" // Follow Official version
+ versionCode 21 // Follow release count
+ versionName "5.3.0" // Follow Official version
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
externalNativeBuild {
diff --git a/support/cmake/cxx14.cmake b/support/cmake/cxx14.cmake
index 1866cdc..032fcb2 100644
--- a/support/cmake/cxx14.cmake
+++ b/support/cmake/cxx14.cmake
@@ -50,6 +50,7 @@
# Check if variadic templates are working and not affected by GCC bug 39653:
# https://gcc.gnu.org/bugzilla/show_bug.cgi?id=39653
+# Can be removed once gcc 4.4 support is dropped.
check_cxx_source_compiles("
template <class T, class ...Types>
struct S { typedef typename S<Types...>::type type; };
@@ -58,33 +59,6 @@
set (SUPPORTS_VARIADIC_TEMPLATES OFF)
endif ()
-# Check if initializer lists are supported.
-check_cxx_source_compiles("
- #include <initializer_list>
- int main() {}" SUPPORTS_INITIALIZER_LIST)
-if (NOT SUPPORTS_INITIALIZER_LIST)
- set (SUPPORTS_INITIALIZER_LIST OFF)
-endif ()
-
-# Check if enum bases are available
-check_cxx_source_compiles("
- enum C : char {A};
- int main() {}"
- SUPPORTS_ENUM_BASE)
-if (NOT SUPPORTS_ENUM_BASE)
- set (SUPPORTS_ENUM_BASE OFF)
-endif ()
-
-# Check if type traits are available
-check_cxx_source_compiles("
- #include <type_traits>
- class C { void operator=(const C&); };
- int main() { static_assert(!std::is_copy_assignable<C>::value, \"\"); }"
- SUPPORTS_TYPE_TRAITS)
-if (NOT SUPPORTS_TYPE_TRAITS)
- set (SUPPORTS_TYPE_TRAITS OFF)
-endif ()
-
# Check if user-defined literals are available
check_cxx_source_compiles("
void operator\"\" _udl(long double);
@@ -94,4 +68,14 @@
set (SUPPORTS_USER_DEFINED_LITERALS OFF)
endif ()
+# Check if <variant> is available
+set(CMAKE_REQUIRED_FLAGS -std=c++1z)
+check_cxx_source_compiles("
+ #include <variant>
+ int main() {}"
+ FMT_HAS_VARIANT)
+if (NOT FMT_HAS_VARIANT)
+ set (FMT_HAS_VARIANT OFF)
+endif ()
+
set(CMAKE_REQUIRED_FLAGS )
diff --git a/support/cmake/run-cmake.bat b/support/cmake/run-cmake.bat
deleted file mode 100644
index f18bb05..0000000
--- a/support/cmake/run-cmake.bat
+++ /dev/null
@@ -1,11 +0,0 @@
-@echo on
-rem This scripts configures build environment and runs CMake.
-rem Use it instead of running CMake directly when building with
-rem the Microsoft SDK toolchain rather than Visual Studio.
-rem It is used in the same way as cmake, for example:
-rem
-rem run-cmake -G "Visual Studio 10 Win64" .
-
-for /F "delims=" %%i IN ('cmake "-DPRINT_PATH=1" -P %~dp0/FindSetEnv.cmake') DO set setenv=%%i
-if NOT "%setenv%" == "" call "%setenv%"
-cmake %*
diff --git a/support/manage.py b/support/manage.py
index 9bd2e48..e39beff 100755
--- a/support/manage.py
+++ b/support/manage.py
@@ -5,6 +5,9 @@
Usage:
manage.py release [<branch>]
manage.py site
+
+For the release command $FMT_TOKEN should contain a GitHub personal access token
+obtained from https://github.com/settings/tokens.
"""
from __future__ import print_function
@@ -142,6 +145,7 @@
b.data = b.data.replace('std::FILE*', 'std::FILE *')
b.data = b.data.replace('unsigned int', 'unsigned')
b.data = b.data.replace('operator""_', 'operator"" _')
+ b.data = b.data.replace(', size_t', ', std::size_t')
# Fix a broken link in index.rst.
index = os.path.join(target_doc_dir, 'index.rst')
with rewrite(index) as b:
diff --git a/support/rtd/index.rst b/support/rtd/index.rst
index 4a59e9b..7c88322 100644
--- a/support/rtd/index.rst
+++ b/support/rtd/index.rst
@@ -1,2 +1,2 @@
If you are not redirected automatically, follow the
-`link to the fmt documentation <http://fmtlib.net/latest/>`_.
+`link to the fmt documentation <https://fmt.dev/latest/>`_.
diff --git a/support/rtd/theme/layout.html b/support/rtd/theme/layout.html
index ee14086..29ebc55 100644
--- a/support/rtd/theme/layout.html
+++ b/support/rtd/theme/layout.html
@@ -2,15 +2,15 @@
{% block extrahead %}
<meta charset="UTF-8">
-<meta http-equiv="refresh" content="1;url=http://fmtlib.net/latest/">
+<meta http-equiv="refresh" content="1;url=https://fmt.dev/latest/">
<script type="text/javascript">
- window.location.href = "http://fmtlib.net/latest/"
+ window.location.href = "https://fmt.dev/latest/"
</script>
<title>Page Redirection</title>
{% endblock %}
{% block document %}
-If you are not redirected automatically, follow the <a href='http://fmtlib.net/latest/'>link to the fmt documentation</a>.
+If you are not redirected automatically, follow the <a href='https://fmt.dev/latest/'>link to the fmt documentation</a>.
{% endblock %}
{% block footer %}
diff --git a/support/travis-build.py b/support/travis-build.py
index d71a7ae..0cf73c8 100755
--- a/support/travis-build.py
+++ b/support/travis-build.py
@@ -83,19 +83,25 @@
build_dir = os.path.join(fmt_dir, "_build")
test_build_dir = os.path.join(fmt_dir, "_build_test")
-# Configure library.
+# Configure the library.
makedirs_if_not_exist(build_dir)
cmake_flags = [
'-DCMAKE_INSTALL_PREFIX=' + install_dir, '-DCMAKE_BUILD_TYPE=' + build,
'-DCMAKE_CXX_STANDARD=' + standard
]
+
+# Make sure the fuzzers still compile.
+main_cmake_flags = list(cmake_flags)
+if 'ENABLE_FUZZING' in os.environ:
+ main_cmake_flags += ['-DFMT_FUZZ=ON', '-DFMT_FUZZ_LINKMAIN=On']
+
check_call(['cmake', '-DFMT_DOC=OFF', '-DFMT_PEDANTIC=ON', '-DFMT_WERROR=ON', fmt_dir] +
- cmake_flags, cwd=build_dir)
+ main_cmake_flags, cwd=build_dir)
-# Build library.
-check_call(['make', '-j4'], cwd=build_dir)
+# Build the library.
+check_call(['cmake', '--build','.'], cwd=build_dir)
-# Test library.
+# Test the library.
env = os.environ.copy()
env['CTEST_OUTPUT_ON_FAILURE'] = '1'
if call(['make', 'test'], env=env, cwd=build_dir):
@@ -103,7 +109,7 @@
print(f.read())
sys.exit(-1)
-# Install library.
+# Install the library.
check_call(['make', 'install'], cwd=build_dir)
# Test installation.
diff --git a/test/CMakeLists.txt b/test/CMakeLists.txt
index 70e19db..e399096 100644
--- a/test/CMakeLists.txt
+++ b/test/CMakeLists.txt
@@ -17,13 +17,20 @@
target_compile_definitions(gmock PUBLIC GTEST_HAS_PTHREAD=0)
endif ()
-if (NOT SUPPORTS_VARIADIC_TEMPLATES OR NOT SUPPORTS_INITIALIZER_LIST)
+if (NOT SUPPORTS_VARIADIC_TEMPLATES)
target_compile_definitions(gmock PUBLIC GTEST_LANG_CXX11=0)
endif ()
-# Workaround a bug in implementation of variadic templates in MSVC11.
if (MSVC)
+ # Workaround a bug in implementation of variadic templates in MSVC11.
target_compile_definitions(gmock PUBLIC _VARIADIC_MAX=10)
+
+ # Disable MSVC warnings of _CRT_INSECURE_DEPRECATE functions.
+ target_compile_definitions(gmock PRIVATE _CRT_SECURE_NO_WARNINGS)
+ if (CMAKE_CXX_COMPILER_ID MATCHES "Clang")
+ # Disable MSVC warnings of POSIX functions.
+ target_compile_options(gmock PUBLIC -Wno-deprecated-declarations)
+ endif ()
endif ()
# GTest doesn't detect <tuple> with clang.
@@ -33,7 +40,7 @@
# Silence MSVC tr1 deprecation warning in gmock.
target_compile_definitions(gmock
- PUBLIC _SILENCE_TR1_NAMESPACE_DEPRECATION_WARNING=0)
+ PUBLIC _SILENCE_TR1_NAMESPACE_DEPRECATION_WARNING=1)
#------------------------------------------------------------------------------
# Build the actual library tests
@@ -74,9 +81,6 @@
target_link_libraries(${name} test-main)
# Define if certain C++ features can be used.
- target_compile_definitions(${name} PRIVATE
- FMT_USE_TYPE_TRAITS=$<BOOL:${SUPPORTS_TYPE_TRAITS}>
- FMT_USE_ENUM_BASE=$<BOOL:${SUPPORTS_ENUM_BASE}>)
if (FMT_PEDANTIC)
target_compile_options(${name} PRIVATE ${PEDANTIC_COMPILE_FLAGS})
endif ()
@@ -86,7 +90,10 @@
add_fmt_test(assert-test)
add_fmt_test(chrono-test)
+add_fmt_test(color-test)
add_fmt_test(core-test)
+add_fmt_test(grisu-test)
+target_compile_definitions(grisu-test PRIVATE FMT_USE_GRISU=1)
add_fmt_test(gtest-extra-test)
add_fmt_test(format-test mock-allocator.h)
if (NOT (MSVC AND BUILD_SHARED_LIBS))
@@ -94,10 +101,11 @@
endif ()
add_fmt_test(locale-test)
add_fmt_test(ostream-test)
+add_fmt_test(compile-test)
add_fmt_test(printf-test)
-add_fmt_test(time-test)
add_fmt_test(custom-formatter-test)
add_fmt_test(ranges-test)
+add_fmt_test(scan-test)
if (HAVE_OPEN)
add_fmt_executable(posix-mock-test
@@ -110,6 +118,9 @@
if (FMT_PEDANTIC)
target_compile_options(posix-mock-test PRIVATE ${PEDANTIC_COMPILE_FLAGS})
endif ()
+ if (HAVE_STRTOD_L)
+ target_compile_definitions(posix-mock-test PRIVATE FMT_LOCALE)
+ endif ()
add_test(NAME posix-mock-test COMMAND posix-mock-test)
add_fmt_test(posix-test)
endif ()
@@ -126,25 +137,37 @@
target_compile_definitions(header-only-test PRIVATE FMT_HEADER_ONLY=1)
endif ()
-# Test that the library can be compiled with exceptions disabled.
-# -fno-exception is broken in icc: https://github.com/fmtlib/fmt/issues/822.
-if (NOT CMAKE_CXX_COMPILER_ID STREQUAL "Intel")
- check_cxx_compiler_flag(-fno-exceptions HAVE_FNO_EXCEPTIONS_FLAG)
-endif ()
-if (HAVE_FNO_EXCEPTIONS_FLAG)
- add_library(noexception-test ../src/format.cc)
- target_include_directories(
- noexception-test PRIVATE ${PROJECT_SOURCE_DIR}/include)
- target_compile_options(noexception-test PRIVATE -fno-exceptions)
- if (FMT_PEDANTIC)
- target_compile_options(noexception-test PRIVATE ${PEDANTIC_COMPILE_FLAGS})
- endif ()
- target_include_directories(noexception-test SYSTEM PUBLIC gtest gmock)
-endif ()
-
message(STATUS "FMT_PEDANTIC: ${FMT_PEDANTIC}")
if (FMT_PEDANTIC)
+ # MSVC fails to compile GMock when C++17 is enabled.
+ if (FMT_HAS_VARIANT AND NOT MSVC)
+ add_fmt_test(std-format-test)
+ set_property(TARGET std-format-test PROPERTY CXX_STANDARD 17)
+ endif ()
+
+ # Test that the library can be compiled with exceptions disabled.
+ # -fno-exception is broken in icc: https://github.com/fmtlib/fmt/issues/822.
+ if (NOT CMAKE_CXX_COMPILER_ID STREQUAL "Intel")
+ check_cxx_compiler_flag(-fno-exceptions HAVE_FNO_EXCEPTIONS_FLAG)
+ endif ()
+ if (HAVE_FNO_EXCEPTIONS_FLAG)
+ add_library(noexception-test ../src/format.cc)
+ target_include_directories(
+ noexception-test PRIVATE ${PROJECT_SOURCE_DIR}/include)
+ target_compile_options(noexception-test PRIVATE -fno-exceptions)
+ if (FMT_PEDANTIC)
+ target_compile_options(noexception-test PRIVATE ${PEDANTIC_COMPILE_FLAGS})
+ endif ()
+ endif ()
+
+ # Test that the library compiles without locale.
+ add_library(nolocale-test ../src/format.cc)
+ target_include_directories(
+ nolocale-test PRIVATE ${PROJECT_SOURCE_DIR}/include)
+ target_compile_definitions(
+ nolocale-test PRIVATE FMT_STATIC_THOUSANDS_SEPARATOR=1)
+
# Test that the library compiles without windows.h.
if (CMAKE_SYSTEM_NAME STREQUAL "Windows")
add_library(no-windows-h-test ../src/format.cc)
@@ -157,10 +180,10 @@
target_include_directories(no-windows-h-test SYSTEM PUBLIC gtest gmock)
endif ()
- add_test(compile-test ${CMAKE_CTEST_COMMAND}
+ add_test(compile-error-test ${CMAKE_CTEST_COMMAND}
--build-and-test
- "${CMAKE_CURRENT_SOURCE_DIR}/compile-test"
- "${CMAKE_CURRENT_BINARY_DIR}/compile-test"
+ "${CMAKE_CURRENT_SOURCE_DIR}/compile-error-test"
+ "${CMAKE_CURRENT_BINARY_DIR}/compile-error-test"
--build-generator ${CMAKE_GENERATOR}
--build-makeprogram ${CMAKE_MAKE_PROGRAM}
--build-options
diff --git a/test/assert-test.cc b/test/assert-test.cc
index 8af9b09..0679cee 100644
--- a/test/assert-test.cc
+++ b/test/assert-test.cc
@@ -9,14 +9,14 @@
#include "gtest.h"
#if GTEST_HAS_DEATH_TEST
-# define EXPECT_DEBUG_DEATH_IF_SUPPORTED(statement, regex) \
+# define EXPECT_DEBUG_DEATH_IF_SUPPORTED(statement, regex) \
EXPECT_DEBUG_DEATH(statement, regex)
#else
-# define EXPECT_DEBUG_DEATH_IF_SUPPORTED(statement, regex) \
+# define EXPECT_DEBUG_DEATH_IF_SUPPORTED(statement, regex) \
GTEST_UNSUPPORTED_DEATH_TEST_(statement, regex, )
#endif
TEST(AssertTest, Fail) {
- EXPECT_DEBUG_DEATH_IF_SUPPORTED(
- FMT_ASSERT(false, "don't panic!"), "don't panic!");
+ EXPECT_DEBUG_DEATH_IF_SUPPORTED(FMT_ASSERT(false, "don't panic!"),
+ "don't panic!");
}
diff --git a/test/chrono-test.cc b/test/chrono-test.cc
index ec6092b..04b5f2f 100644
--- a/test/chrono-test.cc
+++ b/test/chrono-test.cc
@@ -5,6 +5,10 @@
//
// For the license information refer to format.h.
+#ifdef WIN32
+# define _CRT_SECURE_NO_WARNINGS
+#endif
+
#include "fmt/chrono.h"
#include "gtest-extra.h"
@@ -34,21 +38,71 @@
return time;
}
-std::string format_tm(const std::tm &time, const char *spec,
- const std::locale &loc) {
- auto &facet = std::use_facet<std::time_put<char>>(loc);
+std::string format_tm(const std::tm& time, const char* spec,
+ const std::locale& loc) {
+ auto& facet = std::use_facet<std::time_put<char>>(loc);
std::ostringstream os;
os.imbue(loc);
facet.put(os, os, ' ', &time, spec, spec + std::strlen(spec));
return os.str();
}
-#define EXPECT_TIME(spec, time, duration) { \
- std::locale loc("ja_JP.utf8"); \
- EXPECT_EQ(format_tm(time, spec, loc), \
+TEST(TimeTest, Format) {
+ std::tm tm = std::tm();
+ tm.tm_year = 116;
+ tm.tm_mon = 3;
+ tm.tm_mday = 25;
+ EXPECT_EQ("The date is 2016-04-25.",
+ fmt::format("The date is {:%Y-%m-%d}.", tm));
+}
+
+TEST(TimeTest, GrowBuffer) {
+ std::string s = "{:";
+ for (int i = 0; i < 30; ++i) s += "%c";
+ s += "}\n";
+ std::time_t t = std::time(nullptr);
+ fmt::format(s, *std::localtime(&t));
+}
+
+TEST(TimeTest, FormatToEmptyContainer) {
+ std::string s;
+ auto time = std::tm();
+ time.tm_sec = 42;
+ fmt::format_to(std::back_inserter(s), "{:%S}", time);
+ EXPECT_EQ(s, "42");
+}
+
+TEST(TimeTest, EmptyResult) { EXPECT_EQ("", fmt::format("{}", std::tm())); }
+
+static bool EqualTime(const std::tm& lhs, const std::tm& rhs) {
+ return lhs.tm_sec == rhs.tm_sec && lhs.tm_min == rhs.tm_min &&
+ lhs.tm_hour == rhs.tm_hour && lhs.tm_mday == rhs.tm_mday &&
+ lhs.tm_mon == rhs.tm_mon && lhs.tm_year == rhs.tm_year &&
+ lhs.tm_wday == rhs.tm_wday && lhs.tm_yday == rhs.tm_yday &&
+ lhs.tm_isdst == rhs.tm_isdst;
+}
+
+TEST(TimeTest, LocalTime) {
+ std::time_t t = std::time(nullptr);
+ std::tm tm = *std::localtime(&t);
+ EXPECT_TRUE(EqualTime(tm, fmt::localtime(t)));
+}
+
+TEST(TimeTest, GMTime) {
+ std::time_t t = std::time(nullptr);
+ std::tm tm = *std::gmtime(&t);
+ EXPECT_TRUE(EqualTime(tm, fmt::gmtime(t)));
+}
+
+#define EXPECT_TIME(spec, time, duration) \
+ { \
+ std::locale loc("ja_JP.utf8"); \
+ EXPECT_EQ(format_tm(time, spec, loc), \
fmt::format(loc, "{:" spec "}", duration)); \
}
+#ifndef FMT_STATIC_THOUSANDS_SEPARATOR
+
TEST(ChronoTest, FormatDefault) {
EXPECT_EQ("42s", fmt::format("{}", std::chrono::seconds(42)));
EXPECT_EQ("42as",
@@ -83,12 +137,12 @@
fmt::format("{}", std::chrono::duration<int, std::exa>(42)));
EXPECT_EQ("42m", fmt::format("{}", std::chrono::minutes(42)));
EXPECT_EQ("42h", fmt::format("{}", std::chrono::hours(42)));
- EXPECT_EQ("42[15]s",
- fmt::format("{}",
- std::chrono::duration<int, std::ratio<15, 1>>(42)));
- EXPECT_EQ("42[15/4]s",
- fmt::format("{}",
- std::chrono::duration<int, std::ratio<15, 4>>(42)));
+ EXPECT_EQ(
+ "42[15]s",
+ fmt::format("{}", std::chrono::duration<int, std::ratio<15, 1>>(42)));
+ EXPECT_EQ(
+ "42[15/4]s",
+ fmt::format("{}", std::chrono::duration<int, std::ratio<15, 4>>(42)));
}
TEST(ChronoTest, Align) {
@@ -103,7 +157,8 @@
fmt::format("{:>12%H:%M:%S}", std::chrono::seconds(12345)));
EXPECT_EQ("~~03:25:45~~",
fmt::format("{:~^12%H:%M:%S}", std::chrono::seconds(12345)));
-
+ EXPECT_EQ("03:25:45 ",
+ fmt::format("{:{}%H:%M:%S}", std::chrono::seconds(12345), 12));
}
TEST(ChronoTest, FormatSpecs) {
@@ -131,6 +186,8 @@
fmt::format("{:%H:%M:%S}", std::chrono::seconds(12345)));
EXPECT_EQ("03:25", fmt::format("{:%R}", std::chrono::seconds(12345)));
EXPECT_EQ("03:25:45", fmt::format("{:%T}", std::chrono::seconds(12345)));
+ EXPECT_EQ("12345", fmt::format("{:%Q}", std::chrono::seconds(12345)));
+ EXPECT_EQ("s", fmt::format("{:%q}", std::chrono::seconds(12345)));
}
TEST(ChronoTest, InvalidSpecs) {
@@ -151,8 +208,6 @@
EXPECT_THROW_MSG(fmt::format("{:%B}", sec), fmt::format_error, "no date");
EXPECT_THROW_MSG(fmt::format("{:%z}", sec), fmt::format_error, "no date");
EXPECT_THROW_MSG(fmt::format("{:%Z}", sec), fmt::format_error, "no date");
- EXPECT_THROW_MSG(fmt::format("{:%q}", sec), fmt::format_error,
- "invalid format");
EXPECT_THROW_MSG(fmt::format("{:%Eq}", sec), fmt::format_error,
"invalid format");
EXPECT_THROW_MSG(fmt::format("{:%Oq}", sec), fmt::format_error,
@@ -160,13 +215,14 @@
}
TEST(ChronoTest, Locale) {
- const char *loc_name = "ja_JP.utf8";
+ const char* loc_name = "ja_JP.utf8";
bool has_locale = false;
std::locale loc;
try {
loc = std::locale(loc_name);
has_locale = true;
- } catch (const std::runtime_error &) {}
+ } catch (const std::runtime_error&) {
+ }
if (!has_locale) {
fmt::print("{} locale is missing.\n", loc_name);
return;
@@ -183,3 +239,106 @@
EXPECT_TIME("%r", time, sec);
EXPECT_TIME("%p", time, sec);
}
+
+typedef std::chrono::duration<double, std::milli> dms;
+
+TEST(ChronoTest, FormatDefaultFP) {
+ typedef std::chrono::duration<float> fs;
+ EXPECT_EQ("1.234s", fmt::format("{}", fs(1.234)));
+ typedef std::chrono::duration<float, std::milli> fms;
+ EXPECT_EQ("1.234ms", fmt::format("{}", fms(1.234)));
+ typedef std::chrono::duration<double> ds;
+ EXPECT_EQ("1.234s", fmt::format("{}", ds(1.234)));
+ EXPECT_EQ("1.234ms", fmt::format("{}", dms(1.234)));
+}
+
+TEST(ChronoTest, FormatPrecision) {
+ EXPECT_THROW_MSG(fmt::format("{:.2}", std::chrono::seconds(42)),
+ fmt::format_error,
+ "precision not allowed for this argument type");
+ EXPECT_EQ("1.2ms", fmt::format("{:.1}", dms(1.234)));
+ EXPECT_EQ("1.23ms", fmt::format("{:.{}}", dms(1.234), 2));
+}
+
+TEST(ChronoTest, FormatFullSpecs) {
+ EXPECT_EQ("1.2ms ", fmt::format("{:6.1}", dms(1.234)));
+ EXPECT_EQ(" 1.23ms", fmt::format("{:>8.{}}", dms(1.234), 2));
+ EXPECT_EQ(" 1.2ms ", fmt::format("{:^{}.{}}", dms(1.234), 7, 1));
+ EXPECT_EQ(" 1.23ms ", fmt::format("{0:^{2}.{1}}", dms(1.234), 2, 8));
+ EXPECT_EQ("=1.234ms=", fmt::format("{:=^{}.{}}", dms(1.234), 9, 3));
+ EXPECT_EQ("*1.2340ms*", fmt::format("{:*^10.4}", dms(1.234)));
+}
+
+TEST(ChronoTest, FormatSimpleQq) {
+ typedef std::chrono::duration<float> fs;
+ EXPECT_EQ("1.234 s", fmt::format("{:%Q %q}", fs(1.234)));
+ typedef std::chrono::duration<float, std::milli> fms;
+ EXPECT_EQ("1.234 ms", fmt::format("{:%Q %q}", fms(1.234)));
+ typedef std::chrono::duration<double> ds;
+ EXPECT_EQ("1.234 s", fmt::format("{:%Q %q}", ds(1.234)));
+ EXPECT_EQ("1.234 ms", fmt::format("{:%Q %q}", dms(1.234)));
+}
+
+TEST(ChronoTest, FormatPrecisionQq) {
+ EXPECT_THROW_MSG(fmt::format("{:.2%Q %q}", std::chrono::seconds(42)),
+ fmt::format_error,
+ "precision not allowed for this argument type");
+ EXPECT_EQ("1.2 ms", fmt::format("{:.1%Q %q}", dms(1.234)));
+ EXPECT_EQ("1.23 ms", fmt::format("{:.{}%Q %q}", dms(1.234), 2));
+}
+
+TEST(ChronoTest, FormatFullSpecsQq) {
+ EXPECT_EQ("1.2 ms ", fmt::format("{:7.1%Q %q}", dms(1.234)));
+ EXPECT_EQ(" 1.23 ms", fmt::format("{:>8.{}%Q %q}", dms(1.234), 2));
+ EXPECT_EQ(" 1.2 ms ", fmt::format("{:^{}.{}%Q %q}", dms(1.234), 8, 1));
+ EXPECT_EQ(" 1.23 ms ", fmt::format("{0:^{2}.{1}%Q %q}", dms(1.234), 2, 9));
+ EXPECT_EQ("=1.234 ms=", fmt::format("{:=^{}.{}%Q %q}", dms(1.234), 10, 3));
+ EXPECT_EQ("*1.2340 ms*", fmt::format("{:*^11.4%Q %q}", dms(1.234)));
+}
+
+TEST(ChronoTest, InvalidWidthId) {
+ EXPECT_THROW(fmt::format("{:{o}", std::chrono::seconds(0)),
+ fmt::format_error);
+}
+
+TEST(ChronoTest, InvalidColons) {
+ EXPECT_THROW(fmt::format("{0}=:{0::", std::chrono::seconds(0)),
+ fmt::format_error);
+}
+
+TEST(ChronoTest, NegativeDurations) {
+ EXPECT_EQ("-12345", fmt::format("{:%Q}", std::chrono::seconds(-12345)));
+ EXPECT_EQ("-03:25:45",
+ fmt::format("{:%H:%M:%S}", std::chrono::seconds(-12345)));
+ EXPECT_EQ("-00:01",
+ fmt::format("{:%M:%S}", std::chrono::duration<double>(-1)));
+ EXPECT_EQ("s", fmt::format("{:%q}", std::chrono::seconds(-12345)));
+ EXPECT_EQ("-00.127",
+ fmt::format("{:%S}",
+ std::chrono::duration<signed char, std::milli>{-127}));
+ auto min = std::numeric_limits<int>::min();
+ EXPECT_EQ(fmt::format("{}", min),
+ fmt::format("{:%Q}", std::chrono::duration<int>(min)));
+}
+
+TEST(ChronoTest, SpecialDurations) {
+ EXPECT_EQ(
+ "40.",
+ fmt::format("{:%S}", std::chrono::duration<double>(1e20)).substr(0, 3));
+ auto nan = std::numeric_limits<double>::quiet_NaN();
+ EXPECT_EQ(
+ "nan nan nan nan nan:nan nan",
+ fmt::format("{:%I %H %M %S %R %r}", std::chrono::duration<double>(nan)));
+ fmt::format("{:%S}",
+ std::chrono::duration<float, std::atto>(1.79400457e+31f));
+ EXPECT_EQ(fmt::format("{}", std::chrono::duration<float, std::exa>(1)),
+ "1Es");
+ EXPECT_EQ(fmt::format("{}", std::chrono::duration<float, std::atto>(1)),
+ "1as");
+ EXPECT_EQ(fmt::format("{:%R}", std::chrono::duration<char, std::mega>{2}),
+ "03:33");
+ EXPECT_EQ(fmt::format("{:%T}", std::chrono::duration<char, std::mega>{2}),
+ "03:33:20");
+}
+
+#endif // FMT_STATIC_THOUSANDS_SEPARATOR
diff --git a/test/color-test.cc b/test/color-test.cc
new file mode 100644
index 0000000..62cfca0
--- /dev/null
+++ b/test/color-test.cc
@@ -0,0 +1,81 @@
+// Formatting library for C++ - color tests
+//
+// Copyright (c) 2012 - present, Victor Zverovich
+// All rights reserved.
+//
+// For the license information refer to format.h.
+
+#include "fmt/color.h"
+#include "gtest-extra.h"
+
+TEST(ColorsTest, ColorsPrint) {
+ EXPECT_WRITE(stdout, fmt::print(fg(fmt::rgb(255, 20, 30)), "rgb(255,20,30)"),
+ "\x1b[38;2;255;020;030mrgb(255,20,30)\x1b[0m");
+ EXPECT_WRITE(stdout, fmt::print(fg(fmt::color::blue), "blue"),
+ "\x1b[38;2;000;000;255mblue\x1b[0m");
+ EXPECT_WRITE(
+ stdout,
+ fmt::print(fg(fmt::color::blue) | bg(fmt::color::red), "two color"),
+ "\x1b[38;2;000;000;255m\x1b[48;2;255;000;000mtwo color\x1b[0m");
+ EXPECT_WRITE(stdout, fmt::print(fmt::emphasis::bold, "bold"),
+ "\x1b[1mbold\x1b[0m");
+ EXPECT_WRITE(stdout, fmt::print(fmt::emphasis::italic, "italic"),
+ "\x1b[3mitalic\x1b[0m");
+ EXPECT_WRITE(stdout, fmt::print(fmt::emphasis::underline, "underline"),
+ "\x1b[4munderline\x1b[0m");
+ EXPECT_WRITE(stdout,
+ fmt::print(fmt::emphasis::strikethrough, "strikethrough"),
+ "\x1b[9mstrikethrough\x1b[0m");
+ EXPECT_WRITE(
+ stdout,
+ fmt::print(fg(fmt::color::blue) | fmt::emphasis::bold, "blue/bold"),
+ "\x1b[1m\x1b[38;2;000;000;255mblue/bold\x1b[0m");
+ EXPECT_WRITE(stderr, fmt::print(stderr, fmt::emphasis::bold, "bold error"),
+ "\x1b[1mbold error\x1b[0m");
+ EXPECT_WRITE(stderr, fmt::print(stderr, fg(fmt::color::blue), "blue log"),
+ "\x1b[38;2;000;000;255mblue log\x1b[0m");
+ EXPECT_WRITE(stdout, fmt::print(fmt::text_style(), "hi"), "hi");
+ EXPECT_WRITE(stdout, fmt::print(fg(fmt::terminal_color::red), "tred"),
+ "\x1b[31mtred\x1b[0m");
+ EXPECT_WRITE(stdout, fmt::print(bg(fmt::terminal_color::cyan), "tcyan"),
+ "\x1b[46mtcyan\x1b[0m");
+ EXPECT_WRITE(stdout,
+ fmt::print(fg(fmt::terminal_color::bright_green), "tbgreen"),
+ "\x1b[92mtbgreen\x1b[0m");
+ EXPECT_WRITE(stdout,
+ fmt::print(bg(fmt::terminal_color::bright_magenta), "tbmagenta"),
+ "\x1b[105mtbmagenta\x1b[0m");
+}
+
+TEST(ColorsTest, ColorsFormat) {
+ EXPECT_EQ(fmt::format(fg(fmt::rgb(255, 20, 30)), "rgb(255,20,30)"),
+ "\x1b[38;2;255;020;030mrgb(255,20,30)\x1b[0m");
+ EXPECT_EQ(fmt::format(fg(fmt::color::blue), "blue"),
+ "\x1b[38;2;000;000;255mblue\x1b[0m");
+ EXPECT_EQ(
+ fmt::format(fg(fmt::color::blue) | bg(fmt::color::red), "two color"),
+ "\x1b[38;2;000;000;255m\x1b[48;2;255;000;000mtwo color\x1b[0m");
+ EXPECT_EQ(fmt::format(fmt::emphasis::bold, "bold"), "\x1b[1mbold\x1b[0m");
+ EXPECT_EQ(fmt::format(fmt::emphasis::italic, "italic"),
+ "\x1b[3mitalic\x1b[0m");
+ EXPECT_EQ(fmt::format(fmt::emphasis::underline, "underline"),
+ "\x1b[4munderline\x1b[0m");
+ EXPECT_EQ(fmt::format(fmt::emphasis::strikethrough, "strikethrough"),
+ "\x1b[9mstrikethrough\x1b[0m");
+ EXPECT_EQ(
+ fmt::format(fg(fmt::color::blue) | fmt::emphasis::bold, "blue/bold"),
+ "\x1b[1m\x1b[38;2;000;000;255mblue/bold\x1b[0m");
+ EXPECT_EQ(fmt::format(fmt::emphasis::bold, "bold error"),
+ "\x1b[1mbold error\x1b[0m");
+ EXPECT_EQ(fmt::format(fg(fmt::color::blue), "blue log"),
+ "\x1b[38;2;000;000;255mblue log\x1b[0m");
+ EXPECT_EQ(fmt::format(fmt::text_style(), "hi"), "hi");
+ EXPECT_EQ(fmt::format(fg(fmt::terminal_color::red), "tred"),
+ "\x1b[31mtred\x1b[0m");
+ EXPECT_EQ(fmt::format(bg(fmt::terminal_color::cyan), "tcyan"),
+ "\x1b[46mtcyan\x1b[0m");
+ EXPECT_EQ(fmt::format(fg(fmt::terminal_color::bright_green), "tbgreen"),
+ "\x1b[92mtbgreen\x1b[0m");
+ EXPECT_EQ(fmt::format(bg(fmt::terminal_color::bright_magenta), "tbmagenta"),
+ "\x1b[105mtbmagenta\x1b[0m");
+}
diff --git a/test/compile-test/CMakeLists.txt b/test/compile-error-test/CMakeLists.txt
similarity index 100%
rename from test/compile-test/CMakeLists.txt
rename to test/compile-error-test/CMakeLists.txt
diff --git a/test/compile-test.cc b/test/compile-test.cc
new file mode 100644
index 0000000..32a1da0
--- /dev/null
+++ b/test/compile-test.cc
@@ -0,0 +1,340 @@
+// Formatting library for C++ - formatting library tests
+//
+// Copyright (c) 2012 - present, Victor Zverovich
+// All rights reserved.
+//
+// For the license information refer to format.h.
+
+#include <stdint.h>
+#include <cctype>
+#include <cfloat>
+#include <climits>
+#include <cmath>
+#include <cstring>
+#include <deque>
+#include <list>
+#include <memory>
+#include <string>
+
+// Check if fmt/compile.h compiles with windows.h included before it.
+#ifdef _WIN32
+# include <windows.h>
+#endif
+
+#include "fmt/compile.h"
+#include "gmock.h"
+#include "gtest-extra.h"
+#include "mock-allocator.h"
+#include "util.h"
+
+#undef ERROR
+#undef min
+#undef max
+
+using testing::Return;
+using testing::StrictMock;
+
+FMT_BEGIN_NAMESPACE
+namespace internal {
+bool operator==(const internal::string_view_metadata& lhs,
+ const internal::string_view_metadata& rhs) {
+ return std::tie(lhs.offset_, lhs.size_) == std::tie(rhs.offset_, rhs.size_);
+}
+bool operator!=(const internal::string_view_metadata& lhs,
+ const internal::string_view_metadata& rhs) {
+ return !(lhs == rhs);
+}
+
+bool operator==(const format_part<char>::specification& lhs,
+ const format_part<char>::specification& rhs) {
+ if (lhs.arg_id.which != rhs.arg_id.which) {
+ return false;
+ }
+
+ typedef format_part<char>::argument_id::which_arg_id which_arg_id;
+ switch (lhs.arg_id.which) {
+ case which_arg_id::index: {
+ if (lhs.arg_id.val.index != rhs.arg_id.val.index) {
+ return false;
+ }
+ } break;
+ case which_arg_id::named_index: {
+ if (lhs.arg_id.val.named_index != rhs.arg_id.val.named_index) {
+ return false;
+ }
+ } break;
+ }
+
+ return std::tie(lhs.parsed_specs.width, lhs.parsed_specs.fill[0],
+ lhs.parsed_specs.align, lhs.parsed_specs.precision,
+ lhs.parsed_specs.sign, lhs.parsed_specs.type) ==
+ std::tie(rhs.parsed_specs.width, rhs.parsed_specs.fill[0],
+ rhs.parsed_specs.align, rhs.parsed_specs.precision,
+ rhs.parsed_specs.sign, rhs.parsed_specs.type);
+}
+
+bool operator!=(const format_part<char>::specification& lhs,
+ const format_part<char>::specification& rhs) {
+ return !(lhs == rhs);
+}
+
+bool operator==(const format_part<char>& lhs,
+ const fmt::internal::format_part<char>& rhs) {
+ typedef format_part<char>::kind kind;
+
+ if (lhs.which != rhs.which ||
+ lhs.end_of_argument_id != rhs.end_of_argument_id) {
+ return false;
+ }
+
+ switch (lhs.which) {
+ case kind::argument_id: {
+ return lhs.val.arg_id == rhs.val.arg_id;
+ }
+
+ case kind::named_argument_id: {
+ return lhs.val.named_arg_id == rhs.val.named_arg_id;
+ }
+
+ case kind::text: {
+ return lhs.val.text == rhs.val.text;
+ }
+
+ case kind::specification: {
+ return lhs.val.spec == rhs.val.spec;
+ }
+ }
+
+ return false;
+}
+
+bool operator!=(const fmt::internal::format_part<char>& lhs,
+ const fmt::internal::format_part<char>& rhs) {
+ return !(lhs == rhs);
+}
+}
+FMT_END_NAMESPACE
+
+TEST(CompileTest, FormatPart_ComparisonOperators) {
+ typedef fmt::internal::format_part<char> format_part;
+ typedef fmt::internal::dynamic_format_specs<char> prepared_specs;
+
+ {
+ const auto part = format_part(0u);
+ const auto other = format_part(0u);
+ EXPECT_EQ(part, other);
+ }
+ {
+ const auto lhs = format_part(0u);
+ const auto rhs = format_part(1u);
+ EXPECT_NE(lhs, rhs);
+ }
+ {
+ const auto lhs = format_part(fmt::internal::string_view_metadata(0, 42));
+ const auto rhs = format_part(fmt::internal::string_view_metadata(0, 42));
+ EXPECT_EQ(lhs, rhs);
+ }
+ {
+ const auto lhs = format_part(fmt::internal::string_view_metadata(0, 42));
+ const auto rhs = format_part(fmt::internal::string_view_metadata(0, 4422));
+ EXPECT_NE(lhs, rhs);
+ }
+ {
+ auto lhs = format_part(0u);
+ auto rhs = format_part(fmt::internal::string_view_metadata(0, 42));
+ EXPECT_NE(lhs, rhs);
+ rhs = format_part(fmt::internal::string_view_metadata(0, 0));
+ EXPECT_NE(lhs, rhs);
+ }
+ {
+ auto lhs = format_part(0u);
+ lhs.end_of_argument_id = 42;
+ auto rhs = format_part(0u);
+ rhs.end_of_argument_id = 42;
+ EXPECT_EQ(lhs, rhs);
+ rhs.end_of_argument_id = 13;
+ EXPECT_NE(lhs, rhs);
+ }
+ {
+ const auto specs_argument_id = 0u;
+ const auto specs_named_argument_id =
+ fmt::internal::string_view_metadata(0, 42);
+ auto specs = format_part::specification(0u);
+ auto lhs = format_part(specs);
+ auto rhs = format_part(specs);
+ EXPECT_EQ(lhs, rhs);
+
+ specs.parsed_specs = prepared_specs();
+ lhs = format_part(specs);
+ rhs = format_part(specs);
+ EXPECT_EQ(lhs, rhs);
+
+ specs = format_part::specification(specs_named_argument_id);
+ lhs = format_part(specs);
+ rhs = format_part(specs);
+ EXPECT_EQ(lhs, rhs);
+
+ specs.parsed_specs = prepared_specs();
+ lhs = format_part(specs);
+ rhs = format_part(specs);
+ EXPECT_EQ(lhs, rhs);
+
+ auto lhs_spec = format_part::specification(specs_argument_id);
+ auto rhs_spec = format_part::specification(specs_named_argument_id);
+ lhs = format_part(lhs_spec);
+ rhs = format_part(rhs_spec);
+ EXPECT_NE(lhs, rhs);
+
+ lhs_spec = format_part::specification(specs_argument_id);
+ rhs_spec = format_part::specification(specs_argument_id);
+ lhs_spec.parsed_specs.precision = 1;
+ rhs_spec.parsed_specs.precision = 2;
+ lhs = format_part(lhs_spec);
+ rhs = format_part(rhs_spec);
+ EXPECT_NE(lhs, rhs);
+ }
+ {
+ const auto specs_argument_id = 0u;
+ const auto specs_named_argument_id =
+ fmt::internal::string_view_metadata(0, 42);
+ auto specs = format_part::specification(specs_argument_id);
+ auto lhs = format_part(specs);
+ auto rhs = format_part(0u);
+ auto rhs2 = format_part(fmt::internal::string_view_metadata(0, 42));
+ EXPECT_NE(lhs, rhs);
+ EXPECT_NE(lhs, rhs2);
+
+ specs.parsed_specs = prepared_specs();
+ lhs = format_part{specs};
+ EXPECT_NE(lhs, rhs);
+ EXPECT_NE(lhs, rhs2);
+
+ specs = format_part::specification(specs_named_argument_id);
+ EXPECT_NE(lhs, rhs);
+ EXPECT_NE(lhs, rhs2);
+
+ specs.parsed_specs = prepared_specs();
+ lhs = format_part(specs);
+ EXPECT_NE(lhs, rhs);
+ EXPECT_NE(lhs, rhs2);
+ }
+}
+
+// compiletime_prepared_parts_type_provider is useful only with relaxed
+// constexpr.
+#if FMT_USE_CONSTEXPR
+template <unsigned EXPECTED_PARTS_COUNT, typename Format>
+void check_prepared_parts_type(Format format) {
+ typedef fmt::internal::compiletime_prepared_parts_type_provider<decltype(
+ format)>
+ provider;
+ typedef typename provider::template format_parts_array<EXPECTED_PARTS_COUNT>
+ expected_parts_type;
+ static_assert(
+ std::is_same<typename provider::type, expected_parts_type>::value,
+ "CompileTimePreparedPartsTypeProvider test failed");
+}
+
+TEST(CompileTest, CompileTimePreparedPartsTypeProvider) {
+ check_prepared_parts_type<1u>(FMT_STRING("text"));
+ check_prepared_parts_type<1u>(FMT_STRING("{}"));
+ check_prepared_parts_type<2u>(FMT_STRING("text{}"));
+ check_prepared_parts_type<2u>(FMT_STRING("{}text"));
+ check_prepared_parts_type<3u>(FMT_STRING("text{}text"));
+ check_prepared_parts_type<3u>(FMT_STRING("{:{}.{}} {:{}}"));
+
+ check_prepared_parts_type<3u>(FMT_STRING("{{{}}}")); // '{', 'argument', '}'
+ check_prepared_parts_type<2u>(FMT_STRING("text{{")); // 'text', '{'
+ check_prepared_parts_type<3u>(FMT_STRING("text{{ ")); // 'text', '{', ' '
+ check_prepared_parts_type<2u>(FMT_STRING("}}text")); // '}', text
+ check_prepared_parts_type<2u>(FMT_STRING("text}}text")); // 'text}', 'text'
+ check_prepared_parts_type<4u>(
+ FMT_STRING("text{{}}text")); // 'text', '{', '}', 'text'
+}
+#endif
+
+class custom_parts_container {
+ public:
+ typedef fmt::internal::format_part<char> format_part_type;
+
+ private:
+ typedef std::deque<format_part_type> parts;
+
+ public:
+ void add(format_part_type part) { parts_.push_back(std::move(part)); }
+
+ void substitute_last(format_part_type part) {
+ parts_.back() = std::move(part);
+ }
+
+ format_part_type last() { return parts_.back(); }
+
+ auto begin() -> decltype(std::declval<parts>().begin()) {
+ return parts_.begin();
+ }
+
+ auto begin() const -> decltype(std::declval<const parts>().begin()) {
+ return parts_.begin();
+ }
+
+ auto end() -> decltype(std::declval<parts>().begin()) { return parts_.end(); }
+
+ auto end() const -> decltype(std::declval<const parts>().begin()) {
+ return parts_.end();
+ }
+
+ private:
+ parts parts_;
+};
+
+TEST(CompileTest, PassStringLiteralFormat) {
+ const auto prepared = fmt::compile<int>("test {}");
+ EXPECT_EQ("test 42", fmt::format(prepared, 42));
+ const auto wprepared = fmt::compile<int>(L"test {}");
+ EXPECT_EQ(L"test 42", fmt::format(wprepared, 42));
+}
+
+#if FMT_USE_CONSTEXPR
+TEST(CompileTest, PassCompileString) {
+ const auto prepared = fmt::compile<int>(FMT_STRING("test {}"));
+ EXPECT_EQ("test 42", fmt::format(prepared, 42));
+ const auto wprepared = fmt::compile<int>(FMT_STRING(L"test {}"));
+ EXPECT_EQ(L"test 42", fmt::format(wprepared, 42));
+}
+#endif
+
+TEST(CompileTest, FormatToArrayOfChars) {
+ char buffer[32] = {0};
+ const auto prepared = fmt::compile<int>("4{}");
+ fmt::format_to(fmt::internal::make_checked(buffer, 32), prepared, 2);
+ EXPECT_EQ(std::string("42"), buffer);
+ wchar_t wbuffer[32] = {0};
+ const auto wprepared = fmt::compile<int>(L"4{}");
+ fmt::format_to(fmt::internal::make_checked(wbuffer, 32), wprepared, 2);
+ EXPECT_EQ(std::wstring(L"42"), wbuffer);
+}
+
+TEST(CompileTest, FormatToIterator) {
+ std::string s(2, ' ');
+ const auto prepared = fmt::compile<int>("4{}");
+ fmt::format_to(s.begin(), prepared, 2);
+ EXPECT_EQ("42", s);
+ std::wstring ws(2, L' ');
+ const auto wprepared = fmt::compile<int>(L"4{}");
+ fmt::format_to(ws.begin(), wprepared, 2);
+ EXPECT_EQ(L"42", ws);
+}
+
+TEST(CompileTest, FormatToN) {
+ char buf[5];
+ auto f = fmt::compile<int>("{:10}");
+ auto result = fmt::format_to_n(buf, 5, f, 42);
+ EXPECT_EQ(result.size, 10);
+ EXPECT_EQ(result.out, buf + 5);
+ EXPECT_EQ(fmt::string_view(buf, 5), " ");
+}
+
+TEST(CompileTest, FormattedSize) {
+ auto f = fmt::compile<int>("{:10}");
+ EXPECT_EQ(fmt::formatted_size(f, 42), 10);
+}
diff --git a/test/core-test.cc b/test/core-test.cc
index ef2cdb8..0de26db 100644
--- a/test/core-test.cc
+++ b/test/core-test.cc
@@ -11,9 +11,9 @@
#include <functional>
#include <iterator>
#include <limits>
+#include <memory>
#include <string>
#include <type_traits>
-#include <memory>
#include "test-assert.h"
@@ -21,7 +21,7 @@
// Check if fmt/core.h compiles with windows.h included before it.
#ifdef _WIN32
-# include <windows.h>
+# include <windows.h>
#endif
#include "fmt/core.h"
@@ -30,9 +30,9 @@
#undef max
using fmt::basic_format_arg;
-using fmt::internal::basic_buffer;
-using fmt::internal::value;
using fmt::string_view;
+using fmt::internal::buffer;
+using fmt::internal::value;
using testing::_;
using testing::StrictMock;
@@ -42,24 +42,23 @@
struct test_struct {};
template <typename Context, typename T>
-basic_format_arg<Context> make_arg(const T &value) {
+basic_format_arg<Context> make_arg(const T& value) {
return fmt::internal::make_arg<Context>(value);
}
} // namespace
FMT_BEGIN_NAMESPACE
-template <typename Char>
-struct formatter<test_struct, Char> {
+template <typename Char> struct formatter<test_struct, Char> {
template <typename ParseContext>
- auto parse(ParseContext &ctx) -> decltype(ctx.begin()) {
+ auto parse(ParseContext& ctx) -> decltype(ctx.begin()) {
return ctx.begin();
}
- typedef std::back_insert_iterator<basic_buffer<Char>> iterator;
+ typedef std::back_insert_iterator<buffer<Char>> iterator;
- auto format(test_struct, basic_format_context<iterator, char> &ctx)
+ auto format(test_struct, basic_format_context<iterator, char>& ctx)
-> decltype(ctx.out()) {
- const Char *test = "test";
+ const Char* test = "test";
return std::copy_n(test, std::strlen(test), ctx.out());
}
};
@@ -67,31 +66,29 @@
#if !FMT_GCC_VERSION || FMT_GCC_VERSION >= 470
TEST(BufferTest, Noncopyable) {
- EXPECT_FALSE(std::is_copy_constructible<basic_buffer<char> >::value);
-#if !FMT_MSC_VER
+ EXPECT_FALSE(std::is_copy_constructible<buffer<char>>::value);
+# if !FMT_MSC_VER
// std::is_copy_assignable is broken in MSVC2013.
- EXPECT_FALSE(std::is_copy_assignable<basic_buffer<char> >::value);
-#endif
+ EXPECT_FALSE(std::is_copy_assignable<buffer<char>>::value);
+# endif
}
TEST(BufferTest, Nonmoveable) {
- EXPECT_FALSE(std::is_move_constructible<basic_buffer<char> >::value);
-#if !FMT_MSC_VER
+ EXPECT_FALSE(std::is_move_constructible<buffer<char>>::value);
+# if !FMT_MSC_VER
// std::is_move_assignable is broken in MSVC2013.
- EXPECT_FALSE(std::is_move_assignable<basic_buffer<char> >::value);
-#endif
+ EXPECT_FALSE(std::is_move_assignable<buffer<char>>::value);
+# endif
}
#endif
// A test buffer with a dummy grow method.
-template <typename T>
-struct test_buffer : basic_buffer<T> {
- void grow(std::size_t capacity) { this->set(FMT_NULL, capacity); }
+template <typename T> struct test_buffer : buffer<T> {
+ void grow(std::size_t capacity) { this->set(nullptr, capacity); }
};
-template <typename T>
-struct mock_buffer : basic_buffer<T> {
- MOCK_METHOD1(do_grow, void (std::size_t capacity));
+template <typename T> struct mock_buffer : buffer<T> {
+ MOCK_METHOD1(do_grow, void(std::size_t capacity));
void grow(std::size_t capacity) {
this->set(this->data(), capacity);
@@ -99,14 +96,14 @@
}
mock_buffer() {}
- mock_buffer(T *data) { this->set(data, 0); }
- mock_buffer(T *data, std::size_t capacity) { this->set(data, capacity); }
+ mock_buffer(T* data) { this->set(data, 0); }
+ mock_buffer(T* data, std::size_t capacity) { this->set(data, capacity); }
};
TEST(BufferTest, Ctor) {
{
mock_buffer<int> buffer;
- EXPECT_EQ(FMT_NULL, &buffer[0]);
+ EXPECT_EQ(nullptr, &buffer[0]);
EXPECT_EQ(static_cast<size_t>(0), buffer.size());
EXPECT_EQ(static_cast<size_t>(0), buffer.capacity());
}
@@ -134,9 +131,9 @@
TEST(BufferTest, VirtualDtor) {
typedef StrictMock<dying_buffer> stict_mock_buffer;
- stict_mock_buffer *mock_buffer = new stict_mock_buffer();
+ stict_mock_buffer* mock_buffer = new stict_mock_buffer();
EXPECT_CALL(*mock_buffer, die());
- basic_buffer<int> *buffer = mock_buffer;
+ buffer<int>* buffer = mock_buffer;
delete buffer;
}
@@ -147,7 +144,7 @@
EXPECT_EQ(11, buffer[0]);
buffer[3] = 42;
EXPECT_EQ(42, *(&buffer[0] + 3));
- const basic_buffer<char> &const_buffer = buffer;
+ const fmt::internal::buffer<char>& const_buffer = buffer;
EXPECT_EQ(42, const_buffer[3]);
}
@@ -182,7 +179,7 @@
TEST(BufferTest, Append) {
char data[15];
mock_buffer<char> buffer(data, 10);
- const char *test = "test";
+ const char* test = "test";
buffer.append(test, test + 5);
EXPECT_STREQ(test, &buffer[0]);
EXPECT_EQ(5u, buffer.size());
@@ -197,7 +194,7 @@
TEST(BufferTest, AppendAllocatesEnoughStorage) {
char data[19];
mock_buffer<char> buffer(data, 10);
- const char *test = "abcdefgh";
+ const char* test = "abcdefgh";
buffer.resize(10);
EXPECT_CALL(buffer, do_grow(19));
buffer.append(test, test + 9);
@@ -211,35 +208,31 @@
struct custom_context {
typedef char char_type;
- template <typename T>
- struct formatter_type {
- struct type {
- template <typename ParseContext>
- auto parse(ParseContext &ctx) -> decltype(ctx.begin()) {
- return ctx.begin();
- }
+ template <typename T> struct formatter_type {
+ template <typename ParseContext>
+ auto parse(ParseContext& ctx) -> decltype(ctx.begin()) {
+ return ctx.begin();
+ }
- const char *format(const T &, custom_context& ctx) {
- ctx.called = true;
- return FMT_NULL;
- }
- };
+ const char* format(const T&, custom_context& ctx) {
+ ctx.called = true;
+ return nullptr;
+ }
};
bool called;
+ fmt::format_parse_context ctx;
- fmt::format_parse_context parse_context() {
- return fmt::format_parse_context("");
- }
- void advance_to(const char *) {}
+ fmt::format_parse_context& parse_context() { return ctx; }
+ void advance_to(const char*) {}
};
TEST(ArgTest, MakeValueWithCustomContext) {
test_struct t;
- fmt::internal::value<custom_context> arg =
- fmt::internal::make_value<custom_context>(t);
- custom_context ctx = {false};
- arg.custom.format(&t, ctx);
+ fmt::internal::value<custom_context> arg(
+ fmt::internal::arg_mapper<custom_context>().map(t));
+ custom_context ctx = {false, fmt::format_parse_context("")};
+ arg.custom.format(&t, ctx.parse_context(), ctx);
EXPECT_TRUE(ctx.called);
}
@@ -249,40 +242,35 @@
bool operator==(custom_value<Char> lhs, custom_value<Char> rhs) {
return lhs.value == rhs.value;
}
-}
+} // namespace internal
FMT_END_NAMESPACE
// Use a unique result type to make sure that there are no undesirable
// conversions.
struct test_result {};
-template <typename T>
-struct mock_visitor {
- template <typename U>
- struct result { typedef test_result type; };
+template <typename T> struct mock_visitor {
+ template <typename U> struct result { typedef test_result type; };
mock_visitor() {
ON_CALL(*this, visit(_)).WillByDefault(testing::Return(test_result()));
}
- MOCK_METHOD1_T(visit, test_result (T value));
- MOCK_METHOD0_T(unexpected, void ());
+ MOCK_METHOD1_T(visit, test_result(T value));
+ MOCK_METHOD0_T(unexpected, void());
test_result operator()(T value) { return visit(value); }
- template <typename U>
- test_result operator()(U) {
+ template <typename U> test_result operator()(U) {
unexpected();
return test_result();
}
};
-template <typename T>
-struct visit_type { typedef T Type; };
+template <typename T> struct visit_type { typedef T Type; };
#define VISIT_TYPE(Type_, visit_type_) \
- template <> \
- struct visit_type<Type_> { typedef visit_type_ Type; }
+ template <> struct visit_type<Type_> { typedef visit_type_ Type; }
VISIT_TYPE(signed char, int);
VISIT_TYPE(unsigned char, unsigned);
@@ -299,28 +287,30 @@
VISIT_TYPE(float, double);
-#define CHECK_ARG_(Char, expected, value) { \
- testing::StrictMock<mock_visitor<decltype(expected)>> visitor; \
- EXPECT_CALL(visitor, visit(expected)); \
- typedef std::back_insert_iterator<basic_buffer<Char>> iterator; \
- fmt::visit(visitor, \
- make_arg<fmt::basic_format_context<iterator, Char>>(value)); \
-}
+#define CHECK_ARG_(Char, expected, value) \
+ { \
+ testing::StrictMock<mock_visitor<decltype(expected)>> visitor; \
+ EXPECT_CALL(visitor, visit(expected)); \
+ typedef std::back_insert_iterator<buffer<Char>> iterator; \
+ fmt::visit_format_arg( \
+ visitor, make_arg<fmt::basic_format_context<iterator, Char>>(value)); \
+ }
-#define CHECK_ARG(value, typename_) { \
- typedef decltype(value) value_type; \
- typename_ visit_type<value_type>::Type expected = value; \
- CHECK_ARG_(char, expected, value) \
- CHECK_ARG_(wchar_t, expected, value) \
-}
+#define CHECK_ARG(value, typename_) \
+ { \
+ typedef decltype(value) value_type; \
+ typename_ visit_type<value_type>::Type expected = value; \
+ CHECK_ARG_(char, expected, value) \
+ CHECK_ARG_(wchar_t, expected, value) \
+ }
-template <typename T>
-class NumericArgTest : public testing::Test {};
+template <typename T> class NumericArgTest : public testing::Test {};
-typedef ::testing::Types<
- bool, signed char, unsigned char, signed, unsigned short,
- int, unsigned, long, unsigned long, long long, unsigned long long,
- float, double, long double> Types;
+typedef ::testing::Types<bool, signed char, unsigned char, signed,
+ unsigned short, int, unsigned, long, unsigned long,
+ long long, unsigned long long, float, double,
+ long double>
+ Types;
TYPED_TEST_CASE(NumericArgTest, Types);
template <typename T>
@@ -330,7 +320,7 @@
template <typename T>
typename std::enable_if<std::is_floating_point<T>::value, T>::type
- test_value() {
+test_value() {
return static_cast<T>(4.2);
}
@@ -348,8 +338,8 @@
TEST(ArgTest, StringArg) {
char str_data[] = "test";
- char *str = str_data;
- const char *cstr = str;
+ char* str = str_data;
+ const char* cstr = str;
CHECK_ARG_(char, cstr, str);
string_view sref(str);
@@ -358,8 +348,8 @@
TEST(ArgTest, WStringArg) {
wchar_t str_data[] = L"test";
- wchar_t *str = str_data;
- const wchar_t *cstr = str;
+ wchar_t* str = str_data;
+ const wchar_t* cstr = str;
fmt::wstring_view sref(str);
CHECK_ARG_(wchar_t, cstr, str);
@@ -369,8 +359,8 @@
}
TEST(ArgTest, PointerArg) {
- void *p = FMT_NULL;
- const void *cp = FMT_NULL;
+ void* p = nullptr;
+ const void* cp = nullptr;
CHECK_ARG_(char, cp, p);
CHECK_ARG_(wchar_t, cp, p);
CHECK_ARG(cp, );
@@ -379,14 +369,15 @@
struct check_custom {
test_result operator()(
fmt::basic_format_arg<fmt::format_context>::handle h) const {
- struct test_buffer : fmt::internal::basic_buffer<char> {
+ struct test_buffer : fmt::internal::buffer<char> {
char data[10];
- test_buffer() : fmt::internal::basic_buffer<char>(data, 0, 10) {}
+ test_buffer() : fmt::internal::buffer<char>(data, 0, 10) {}
void grow(std::size_t) {}
} buffer;
- fmt::internal::basic_buffer<char> &base = buffer;
- fmt::format_context ctx(std::back_inserter(base), "", fmt::format_args());
- h.format(ctx);
+ fmt::internal::buffer<char>& base = buffer;
+ fmt::format_parse_context parse_ctx("");
+ fmt::format_context ctx(std::back_inserter(base), fmt::format_args());
+ h.format(parse_ctx, ctx);
EXPECT_EQ("test", std::string(buffer.data, buffer.size()));
return test_result();
}
@@ -395,17 +386,17 @@
TEST(ArgTest, CustomArg) {
test_struct test;
typedef mock_visitor<fmt::basic_format_arg<fmt::format_context>::handle>
- visitor;
+ visitor;
testing::StrictMock<visitor> v;
EXPECT_CALL(v, visit(_)).WillOnce(testing::Invoke(check_custom()));
- fmt::visit(v, make_arg<fmt::format_context>(test));
+ fmt::visit_format_arg(v, make_arg<fmt::format_context>(test));
}
TEST(ArgTest, VisitInvalidArg) {
- testing::StrictMock< mock_visitor<fmt::monostate> > visitor;
+ testing::StrictMock<mock_visitor<fmt::monostate>> visitor;
EXPECT_CALL(visitor, visit(_));
fmt::basic_format_arg<fmt::format_context> arg;
- visit(visitor, arg);
+ fmt::visit_format_arg(visitor, arg);
}
TEST(StringViewTest, Length) {
@@ -416,9 +407,8 @@
}
// Check string_view's comparison operator.
-template <template <typename> class Op>
-void check_op() {
- const char *inputs[] = {"foo", "fop", "fo"};
+template <template <typename> class Op> void check_op() {
+ const char* inputs[] = {"foo", "fop", "fo"};
std::size_t num_inputs = sizeof(inputs) / sizeof(*inputs);
for (std::size_t i = 0; i < num_inputs; ++i) {
for (std::size_t j = 0; j < num_inputs; ++j) {
@@ -442,63 +432,89 @@
check_op<std::greater_equal>();
}
-enum basic_enum {};
+struct enabled_formatter {};
+struct disabled_formatter {};
+struct disabled_formatter_convertible {
+ operator int() const { return 42; }
+};
-TEST(CoreTest, ConvertToInt) {
- EXPECT_FALSE((fmt::convert_to_int<char, char>::value));
- EXPECT_FALSE((fmt::convert_to_int<const char *, char>::value));
- EXPECT_TRUE((fmt::convert_to_int<basic_enum, char>::value));
+FMT_BEGIN_NAMESPACE
+template <> struct formatter<enabled_formatter> {
+ auto parse(format_parse_context& ctx) -> decltype(ctx.begin()) {
+ return ctx.begin();
+ }
+ auto format(enabled_formatter, format_context& ctx) -> decltype(ctx.out()) {
+ return ctx.out();
+ }
+};
+FMT_END_NAMESPACE
+
+TEST(CoreTest, HasFormatter) {
+ using fmt::internal::has_formatter;
+ using context = fmt::format_context;
+ EXPECT_TRUE((has_formatter<enabled_formatter, context>::value));
+ EXPECT_FALSE((has_formatter<disabled_formatter, context>::value));
+ EXPECT_FALSE((has_formatter<disabled_formatter_convertible, context>::value));
}
-enum enum_with_underlying_type : char {};
+struct convertible_to_int {
+ operator int() const { return 42; }
+};
-TEST(CoreTest, IsEnumConvertibleToInt) {
- EXPECT_TRUE((fmt::convert_to_int<enum_with_underlying_type, char>::value));
+FMT_BEGIN_NAMESPACE
+template <> struct formatter<convertible_to_int> {
+ auto parse(format_parse_context& ctx) -> decltype(ctx.begin()) {
+ return ctx.begin();
+ }
+ auto format(convertible_to_int, format_context& ctx) -> decltype(ctx.out()) {
+ return std::copy_n("foo", 3, ctx.out());
+ }
+};
+FMT_END_NAMESPACE
+
+TEST(CoreTest, FormatterOverridesImplicitConversion) {
+ EXPECT_EQ(fmt::format("{}", convertible_to_int()), "foo");
}
namespace my_ns {
-template <typename Char>
-class my_string {
+template <typename Char> class my_string {
public:
- my_string(const Char *s) : s_(s) {}
- const Char * data() const FMT_NOEXCEPT { return s_.data(); }
+ my_string(const Char* s) : s_(s) {}
+ const Char* data() const FMT_NOEXCEPT { return s_.data(); }
std::size_t length() const FMT_NOEXCEPT { return s_.size(); }
operator const Char*() const { return s_.c_str(); }
+
private:
std::basic_string<Char> s_;
};
template <typename Char>
-inline fmt::basic_string_view<Char>
- to_string_view(const my_string<Char> &s) FMT_NOEXCEPT {
- return { s.data(), s.length() };
+inline fmt::basic_string_view<Char> to_string_view(const my_string<Char>& s)
+ FMT_NOEXCEPT {
+ return {s.data(), s.length()};
}
struct non_string {};
-}
+} // namespace my_ns
namespace FakeQt {
class QString {
public:
- QString(const wchar_t *s) : s_(std::make_shared<std::wstring>(s)) {}
- const wchar_t *utf16() const FMT_NOEXCEPT { return s_->data(); }
+ QString(const wchar_t* s) : s_(std::make_shared<std::wstring>(s)) {}
+ const wchar_t* utf16() const FMT_NOEXCEPT { return s_->data(); }
int size() const FMT_NOEXCEPT { return static_cast<int>(s_->size()); }
-#ifdef FMT_STRING_VIEW
- operator FMT_STRING_VIEW<wchar_t>() const FMT_NOEXCEPT { return *s_; }
-#endif
+
private:
std::shared_ptr<std::wstring> s_;
};
-inline fmt::basic_string_view<wchar_t> to_string_view(
- const QString &s) FMT_NOEXCEPT {
- return {s.utf16(),
- static_cast<std::size_t>(s.size())};
+inline fmt::basic_string_view<wchar_t> to_string_view(const QString& s)
+ FMT_NOEXCEPT {
+ return {s.utf16(), static_cast<std::size_t>(s.size())};
}
-}
+} // namespace FakeQt
-template <typename T>
-class IsStringTest : public testing::Test {};
+template <typename T> class IsStringTest : public testing::Test {};
typedef ::testing::Types<char, wchar_t, char16_t, char32_t> StringCharTypes;
TYPED_TEST_CASE(IsStringTest, StringCharTypes);
@@ -506,30 +522,30 @@
namespace {
template <typename Char>
struct derived_from_string_view : fmt::basic_string_view<Char> {};
-}
+} // namespace
TYPED_TEST(IsStringTest, IsString) {
- EXPECT_TRUE((fmt::internal::is_string<TypeParam *>::value));
- EXPECT_TRUE((fmt::internal::is_string<const TypeParam *>::value));
- EXPECT_TRUE((fmt::internal::is_string<TypeParam[2]>::value));
- EXPECT_TRUE((fmt::internal::is_string<const TypeParam[2]>::value));
- EXPECT_TRUE((fmt::internal::is_string<std::basic_string<TypeParam>>::value));
+ EXPECT_TRUE(fmt::internal::is_string<TypeParam*>::value);
+ EXPECT_TRUE(fmt::internal::is_string<const TypeParam*>::value);
+ EXPECT_TRUE(fmt::internal::is_string<TypeParam[2]>::value);
+ EXPECT_TRUE(fmt::internal::is_string<const TypeParam[2]>::value);
+ EXPECT_TRUE(fmt::internal::is_string<std::basic_string<TypeParam>>::value);
EXPECT_TRUE(
- (fmt::internal::is_string<fmt::basic_string_view<TypeParam>>::value));
+ fmt::internal::is_string<fmt::basic_string_view<TypeParam>>::value);
EXPECT_TRUE(
- (fmt::internal::is_string<derived_from_string_view<TypeParam>>::value));
-#ifdef FMT_STRING_VIEW
- EXPECT_TRUE((fmt::internal::is_string<FMT_STRING_VIEW<TypeParam>>::value));
-#endif
- EXPECT_TRUE((fmt::internal::is_string<my_ns::my_string<TypeParam>>::value));
- EXPECT_FALSE((fmt::internal::is_string<my_ns::non_string>::value));
- EXPECT_TRUE((fmt::internal::is_string<FakeQt::QString>::value));
+ fmt::internal::is_string<derived_from_string_view<TypeParam>>::value);
+ using string_view = fmt::internal::std_string_view<TypeParam>;
+ EXPECT_TRUE(std::is_empty<string_view>::value !=
+ fmt::internal::is_string<string_view>::value);
+ EXPECT_TRUE(fmt::internal::is_string<my_ns::my_string<TypeParam>>::value);
+ EXPECT_FALSE(fmt::internal::is_string<my_ns::non_string>::value);
+ EXPECT_TRUE(fmt::internal::is_string<FakeQt::QString>::value);
}
TEST(CoreTest, Format) {
// This should work without including fmt/format.h.
#ifdef FMT_FORMAT_H_
-# error fmt/format.h must not be included in the core test
+# error fmt/format.h must not be included in the core test
#endif
EXPECT_EQ(fmt::format("{}", 42), "42");
}
@@ -537,7 +553,7 @@
TEST(CoreTest, FormatTo) {
// This should work without including fmt/format.h.
#ifdef FMT_FORMAT_H_
-# error fmt/format.h must not be included in the core test
+# error fmt/format.h must not be included in the core test
#endif
std::string s;
fmt::format_to(std::back_inserter(s), "{}", 42);
@@ -551,15 +567,18 @@
EXPECT_EQ(to_string_view(my_string<wchar_t>(L"42")), L"42");
EXPECT_EQ(to_string_view(QString(L"42")), L"42");
fmt::internal::type type =
- fmt::internal::get_type<fmt::format_context, my_string<char>>::value;
+ fmt::internal::mapped_type_constant<my_string<char>,
+ fmt::format_context>::value;
+ EXPECT_EQ(type, fmt::internal::string_type);
+ type = fmt::internal::mapped_type_constant<my_string<wchar_t>,
+ fmt::wformat_context>::value;
EXPECT_EQ(type, fmt::internal::string_type);
type =
- fmt::internal::get_type<fmt::wformat_context, my_string<wchar_t>>::value;
- EXPECT_EQ(type, fmt::internal::string_type);
- type = fmt::internal::get_type<fmt::wformat_context, QString>::value;
+ fmt::internal::mapped_type_constant<QString, fmt::wformat_context>::value;
EXPECT_EQ(type, fmt::internal::string_type);
// Does not compile: only wide format contexts are compatible with QString!
- // type = fmt::internal::get_type<fmt::format_context, QString>::value;
+ // type = fmt::internal::mapped_type_constant<QString,
+ // fmt::format_context>::value;
}
TEST(CoreTest, FormatForeignStrings) {
@@ -572,6 +591,10 @@
EXPECT_EQ(fmt::format(my_string<wchar_t>(L"{}"), QString(L"42")), L"42");
}
+struct implicitly_convertible_to_string {
+ operator std::string() const { return "foo"; }
+};
+
struct implicitly_convertible_to_string_view {
operator fmt::string_view() const { return "foo"; }
};
@@ -581,7 +604,7 @@
}
// std::is_constructible is broken in MSVC until version 2015.
-#if FMT_USE_EXPLICIT && (!FMT_MSC_VER || FMT_MSC_VER >= 1900)
+#if !FMT_MSC_VER || FMT_MSC_VER >= 1900
struct explicitly_convertible_to_string_view {
explicit operator fmt::string_view() const { return "foo"; }
};
@@ -600,11 +623,12 @@
}
struct explicitly_convertible_to_string_like {
- template <
- typename String,
- typename = typename std::enable_if<
- std::is_constructible<String, const char*, std::size_t>::value>::type>
- FMT_EXPLICIT operator String() const { return String("foo", 3u); }
+ template <typename String,
+ typename = typename std::enable_if<std::is_constructible<
+ String, const char*, std::size_t>::value>::type>
+ explicit operator String() const {
+ return String("foo", 3u);
+ }
};
TEST(FormatterTest, FormatExplicitlyConvertibleToStringLike) {
diff --git a/test/custom-formatter-test.cc b/test/custom-formatter-test.cc
index d529771..db1e199 100644
--- a/test/custom-formatter-test.cc
+++ b/test/custom-formatter-test.cc
@@ -5,6 +5,10 @@
//
// For the license information refer to format.h.
+#ifndef _CRT_SECURE_NO_WARNINGS
+#define _CRT_SECURE_NO_WARNINGS
+#endif
+
#include "fmt/format.h"
#include "gtest-extra.h"
@@ -13,22 +17,22 @@
// A custom argument formatter that doesn't print `-` for floating-point values
// rounded to 0.
-class custom_arg_formatter :
- public fmt::arg_formatter<fmt::back_insert_range<fmt::internal::buffer>> {
+class custom_arg_formatter
+ : public fmt::arg_formatter<fmt::internal::buffer_range<char>> {
public:
- typedef fmt::back_insert_range<fmt::internal::buffer> range;
+ using range = fmt::internal::buffer_range<char>;
typedef fmt::arg_formatter<range> base;
- custom_arg_formatter(
- fmt::format_context &ctx, fmt::format_specs *s = FMT_NULL)
- : base(ctx, s) {}
+ custom_arg_formatter(fmt::format_context& ctx,
+ fmt::format_parse_context* parse_ctx,
+ fmt::format_specs* s = nullptr)
+ : base(ctx, parse_ctx, s) {}
using base::operator();
iterator operator()(double value) {
// Comparing a float to 0.0 is safe.
- if (round(value * pow(10, spec()->precision)) == 0.0)
- value = 0;
+ if (round(value * pow(10, specs()->precision)) == 0.0) value = 0;
return base::operator()(value);
}
};
@@ -41,7 +45,7 @@
}
template <typename... Args>
-std::string custom_format(const char *format_str, const Args & ... args) {
+std::string custom_format(const char* format_str, const Args&... args) {
auto va = fmt::make_format_args(args...);
return custom_vformat(format_str, va);
}
diff --git a/test/format b/test/format
new file mode 100644
index 0000000..d9472f9
--- /dev/null
+++ b/test/format
@@ -0,0 +1,861 @@
+// Formatting library for C++ - the standard API implementation
+//
+// Copyright (c) 2012 - present, Victor Zverovich
+// All rights reserved.
+//
+// For the license information refer to format.h.
+
+#ifndef FMT_FORMAT_
+#define FMT_FORMAT_
+
+#include <variant>
+#include "fmt/format.h"
+
+// This implementation verifies the correctness of the standard API proposed in
+// P0645 Text Formatting and is optimized for copy-pasting from the paper, not
+// for efficiency or readability. An efficient implementation should not use
+// std::variant and should store packed argument type tags separately from
+// values in basic_format_args for small number of arguments.
+
+namespace std {
+template<class T>
+constexpr bool Integral = is_integral_v<T>;
+
+template <class O>
+ using iter_difference_t = ptrdiff_t;
+}
+
+// https://fmt.dev/Text%20Formatting.html#format.syn
+namespace std {
+ // [format.error], class format_error
+ class format_error;
+
+ // [format.formatter], formatter
+ template<class charT> class basic_format_parse_context;
+ using format_parse_context = basic_format_parse_context<char>;
+ using wformat_parse_context = basic_format_parse_context<wchar_t>;
+
+ template<class Out, class charT> class basic_format_context;
+ using format_context = basic_format_context<
+ /* unspecified */ std::back_insert_iterator<fmt::internal::buffer<char>>, char>;
+ using wformat_context = basic_format_context<
+ /* unspecified */ std::back_insert_iterator<fmt::internal::buffer<wchar_t>>, wchar_t>;
+
+ template<class T, class charT = char> struct formatter {
+ formatter() = delete;
+ };
+
+ // [format.arguments], arguments
+ template<class Context> class basic_format_arg;
+
+ template<class Visitor, class Context>
+ /* see below */ auto visit_format_arg(Visitor&& vis, basic_format_arg<Context> arg);
+
+ template<class Context, class... Args> struct format_arg_store; // exposition only
+
+ template<class Context> class basic_format_args;
+ using format_args = basic_format_args<format_context>;
+ using wformat_args = basic_format_args<wformat_context>;
+
+ template<class Out, class charT>
+ using format_args_t = basic_format_args<basic_format_context<Out, charT>>;
+
+ template<class Context = format_context, class... Args>
+ format_arg_store<Context, Args...>
+ make_format_args(const Args&... args);
+ template<class... Args>
+ format_arg_store<wformat_context, Args...>
+ make_wformat_args(const Args&... args);
+
+ // [format.functions], formatting functions
+ template<class... Args>
+ string format(string_view fmt, const Args&... args);
+ template<class... Args>
+ wstring format(wstring_view fmt, const Args&... args);
+
+ string vformat(string_view fmt, format_args args);
+ wstring vformat(wstring_view fmt, wformat_args args);
+
+ template<class Out, class... Args>
+ Out format_to(Out out, string_view fmt, const Args&... args);
+ template<class Out, class... Args>
+ Out format_to(Out out, wstring_view fmt, const Args&... args);
+
+ template<class Out>
+ Out vformat_to(Out out, string_view fmt, format_args_t<Out, char> args);
+ template<class Out>
+ Out vformat_to(Out out, wstring_view fmt, format_args_t<Out, wchar_t> args);
+
+ template<class Out>
+ struct format_to_n_result {
+ Out out;
+ iter_difference_t<Out> size;
+ };
+
+ template<class Out, class... Args>
+ format_to_n_result<Out> format_to_n(Out out, iter_difference_t<Out> n,
+ string_view fmt, const Args&... args);
+ template<class Out, class... Args>
+ format_to_n_result<Out> format_to_n(Out out, iter_difference_t<Out> n,
+ wstring_view fmt, const Args&... args);
+
+ template<class... Args>
+ size_t formatted_size(string_view fmt, const Args&... args);
+ template<class... Args>
+ size_t formatted_size(wstring_view fmt, const Args&... args);
+}
+
+// https://fmt.dev/Text%20Formatting.html#format.error
+namespace std {
+ class format_error : public runtime_error {
+ public:
+ explicit format_error(const string& what_arg) : runtime_error(what_arg) {}
+ explicit format_error(const char* what_arg) : runtime_error(what_arg) {}
+ };
+}
+
+namespace std {
+namespace detail {
+struct error_handler {
+ // This function is intentionally not constexpr to give a compile-time error.
+ void on_error(const char* message) {
+ throw std::format_error(message);
+ }
+};
+}
+}
+
+// https://fmt.dev/Text%20Formatting.html#format.parse_context
+namespace std {
+ template<class charT>
+ class basic_format_parse_context {
+ public:
+ using char_type = charT;
+ using const_iterator = typename basic_string_view<charT>::const_iterator;
+ using iterator = const_iterator;
+
+ private:
+ iterator begin_; // exposition only
+ iterator end_; // exposition only
+ enum indexing { unknown, manual, automatic }; // exposition only
+ indexing indexing_; // exposition only
+ size_t next_arg_id_; // exposition only
+ size_t num_args_; // exposition only
+
+ public:
+ explicit constexpr basic_format_parse_context(basic_string_view<charT> fmt,
+ size_t num_args = 0) noexcept;
+ basic_format_parse_context(const basic_format_parse_context&) = delete;
+ basic_format_parse_context& operator=(const basic_format_parse_context&) = delete;
+
+ constexpr const_iterator begin() const noexcept;
+ constexpr const_iterator end() const noexcept;
+ constexpr void advance_to(const_iterator it);
+
+ constexpr size_t next_arg_id();
+ constexpr void check_arg_id(size_t id);
+
+ // Implementation detail:
+ constexpr void check_arg_id(fmt::string_view) {}
+ detail::error_handler error_handler() const { return {}; }
+ void on_error(const char* msg) { error_handler().on_error(msg); }
+ };
+}
+
+namespace std {
+template<class charT>
+/* explicit */ constexpr basic_format_parse_context<charT>::
+ basic_format_parse_context(basic_string_view<charT> fmt,
+ size_t num_args) noexcept
+: begin_(fmt.begin()), end_(fmt.end()), indexing_(unknown), next_arg_id_(0), num_args_(num_args) {}
+
+template<class charT>
+constexpr typename basic_format_parse_context<charT>::const_iterator basic_format_parse_context<charT>::begin() const noexcept { return begin_; }
+
+template<class charT>
+constexpr typename basic_format_parse_context<charT>::const_iterator basic_format_parse_context<charT>::end() const noexcept { return end_; }
+
+template<class charT>
+constexpr void basic_format_parse_context<charT>::advance_to(typename basic_format_parse_context<charT>::iterator it) { begin_ = it; }
+
+template<class charT>
+constexpr size_t basic_format_parse_context<charT>::next_arg_id() {
+ if (indexing_ == manual)
+ throw format_error("manual to automatic indexing");
+ if (indexing_ == unknown)
+ indexing_ = automatic;
+ return next_arg_id_++;
+}
+
+template<class charT>
+constexpr void basic_format_parse_context<charT>::check_arg_id(size_t id) {
+ // clang doesn't support __builtin_is_constant_evaluated yet
+ //if (!(!__builtin_is_constant_evaluated() || id < num_args_))
+ // throw format_error(invalid index is out of range");
+ if (indexing_ == automatic)
+ throw format_error("automatic to manual indexing");
+ if (indexing_ == unknown)
+ indexing_ = manual;
+}
+}
+
+// https://fmt.dev/Text%20Formatting.html#format.context
+namespace std {
+ template<class Out, class charT>
+ class basic_format_context {
+ basic_format_args<basic_format_context> args_; // exposition only
+ Out out_; // exposition only
+
+ public:
+ using iterator = Out;
+ using char_type = charT;
+ template<class T> using formatter_type = formatter<T, charT>;
+
+ basic_format_arg<basic_format_context> arg(size_t id) const;
+
+ iterator out();
+ void advance_to(iterator it);
+
+ // Implementation details:
+ using format_arg = basic_format_arg<basic_format_context>;
+ basic_format_context(Out out, basic_format_args<basic_format_context> args, fmt::internal::locale_ref)
+ : args_(args), out_(out) {}
+ detail::error_handler error_handler() const { return {}; }
+ basic_format_arg<basic_format_context> arg(fmt::basic_string_view<charT>) const {
+ return {}; // unused: named arguments are not supported yet
+ }
+ void on_error(const char* msg) { error_handler().on_error(msg); }
+ };
+}
+
+namespace std {
+template<class O, class charT>
+basic_format_arg<basic_format_context<O, charT>> basic_format_context<O, charT>::arg(size_t id) const { return args_.get(id); }
+
+template<class O, class charT>
+typename basic_format_context<O, charT>::iterator basic_format_context<O, charT>::out() { return out_; }
+
+template<class O, class charT>
+void basic_format_context<O, charT>::advance_to(typename basic_format_context<O, charT>::iterator it) { out_ = it; }
+}
+
+namespace std {
+namespace detail {
+template <typename T>
+constexpr bool is_standard_integer_v =
+ std::is_same_v<T, signed char> ||
+ std::is_same_v<T, short int> ||
+ std::is_same_v<T, int> ||
+ std::is_same_v<T, long int> ||
+ std::is_same_v<T, long long int>;
+
+template <typename T>
+constexpr bool is_standard_unsigned_integer_v =
+ std::is_same_v<T, unsigned char> ||
+ std::is_same_v<T, unsigned short int> ||
+ std::is_same_v<T, unsigned int> ||
+ std::is_same_v<T, unsigned long int> ||
+ std::is_same_v<T, unsigned long long int>;
+
+template <typename T, typename Char> struct formatter;
+}
+}
+
+// https://fmt.dev/Text%20Formatting.html#format.arg
+namespace std {
+ template<class Context>
+ class basic_format_arg {
+ public:
+ class handle;
+
+ private:
+ using char_type = typename Context::char_type; // exposition only
+
+ variant<monostate, bool, char_type,
+ int, unsigned int, long long int, unsigned long long int,
+ double, long double,
+ const char_type*, basic_string_view<char_type>,
+ const void*, handle> value; // exposition only
+
+ template<typename T,
+ typename = enable_if_t<
+ std::is_same_v<T, bool> ||
+ std::is_same_v<T, char_type> ||
+ (std::is_same_v<T, char> && std::is_same_v<char_type, wchar_t>) ||
+ detail::is_standard_integer_v<T> ||
+ detail::is_standard_unsigned_integer_v<T> ||
+ sizeof(typename Context::template formatter_type<T>().format(declval<const T&>(), declval<Context&>())) != 0
+ >> explicit basic_format_arg(const T& v) noexcept; // exposition only
+ explicit basic_format_arg(float n) noexcept; // exposition only
+ explicit basic_format_arg(double n) noexcept; // exposition only
+ explicit basic_format_arg(long double n) noexcept; // exposition only
+ explicit basic_format_arg(const char_type* s); // exposition only
+
+ template<class traits>
+ explicit basic_format_arg(
+ basic_string_view<char_type, traits> s) noexcept; // exposition only
+
+ template<class traits, class Allocator>
+ explicit basic_format_arg(
+ const basic_string<char_type, traits, Allocator>& s) noexcept; // exposition only
+
+ explicit basic_format_arg(nullptr_t) noexcept; // exposition only
+
+ template<class T, typename = enable_if_t<is_void_v<T>>>
+ explicit basic_format_arg(const T* p) noexcept; // exposition only
+
+ // Fails due to a bug in clang
+ //template<class Visitor, class Ctx>
+ // friend auto visit_format_arg(Visitor&& vis,
+ // basic_format_arg<Ctx> arg); // exposition only
+
+ friend auto get_value(basic_format_arg arg) {
+ return arg.value;
+ }
+
+ template <typename T, typename Char> friend struct detail::formatter;
+
+ template<class Ctx, class... Args>
+ friend format_arg_store<Ctx, Args...>
+ make_format_args(const Args&... args); // exposition only
+
+ public:
+ basic_format_arg() noexcept;
+
+ explicit operator bool() const noexcept;
+ };
+}
+
+namespace std {
+template<class Context>
+basic_format_arg<Context>::basic_format_arg() noexcept {}
+
+template<class Context>
+template<class T, typename> /* explicit */ basic_format_arg<Context>::basic_format_arg(const T& v) noexcept {
+ if constexpr (std::is_same_v<T, bool> || std::is_same_v<T, char_type>)
+ value = v;
+ else if constexpr (std::is_same_v<T, char> && std::is_same_v<char_type, wchar_t>)
+ value = static_cast<wchar_t>(v);
+ else if constexpr (detail::is_standard_integer_v<T> && sizeof(T) <= sizeof(int))
+ value = static_cast<int>(v);
+ else if constexpr (detail::is_standard_unsigned_integer_v<T> && sizeof(T) <= sizeof(unsigned))
+ value = static_cast<unsigned>(v);
+ else if constexpr (detail::is_standard_integer_v<T>)
+ value = static_cast<long long int>(v);
+ else if constexpr (detail::is_standard_unsigned_integer_v<T>)
+ value = static_cast<unsigned long long int>(v);
+ else if constexpr (sizeof(typename Context::template formatter_type<T>().format(declval<const T&>(), declval<Context&>())) != 0)
+ value = handle(v);
+}
+
+template<class Context>
+/* explicit */ basic_format_arg<Context>::basic_format_arg(float n) noexcept
+ : value(static_cast<double>(n)) {}
+
+template<class Context>
+/* explicit */ basic_format_arg<Context>::basic_format_arg(double n) noexcept
+ : value(n) {}
+
+template<class Context>
+/* explicit */ basic_format_arg<Context>::basic_format_arg(long double n) noexcept
+ : value(n) {}
+
+template<class Context>
+/* explicit */ basic_format_arg<Context>::basic_format_arg(const typename basic_format_arg<Context>::char_type* s)
+ : value(s) {
+ assert(s != nullptr);
+}
+
+template<class Context>
+template<class traits>
+/* explicit */ basic_format_arg<Context>::basic_format_arg(basic_string_view<char_type, traits> s) noexcept
+ : value(s) {}
+
+template<class Context>
+template<class traits, class Allocator>
+/* explicit */ basic_format_arg<Context>::basic_format_arg(
+ const basic_string<char_type, traits, Allocator>& s) noexcept
+ : value(basic_string_view<char_type>(s.data(), s.size())) {}
+
+
+template<class Context>
+/* explicit */ basic_format_arg<Context>::basic_format_arg(nullptr_t) noexcept
+ : value(static_cast<const void*>(nullptr)) {}
+
+template<class Context>
+template<class T, typename> /* explicit */ basic_format_arg<Context>::basic_format_arg(const T* p) noexcept
+ : value(p) {}
+
+template<class Context>
+/* explicit */ basic_format_arg<Context>::operator bool() const noexcept {
+ return !holds_alternative<monostate>(value);
+}
+}
+
+namespace std {
+ template<class Context>
+ class basic_format_arg<Context>::handle {
+ const void* ptr_; // exposition only
+ void (*format_)(basic_format_parse_context<char_type>&,
+ Context&, const void*); // exposition only
+
+ template<class T> explicit handle(const T& val) noexcept; // exposition only
+
+ friend class basic_format_arg<Context>; // exposition only
+
+ public:
+ void format(basic_format_parse_context<char_type>&, Context& ctx) const;
+ };
+}
+
+namespace std {
+template<class Context>
+template<class T> /* explicit */ basic_format_arg<Context>::handle::handle(const T& val) noexcept
+ : ptr_(&val), format_([](basic_format_parse_context<char_type>& parse_ctx, Context& format_ctx, const void* ptr) {
+ typename Context::template formatter_type<T> f;
+ parse_ctx.advance_to(f.parse(parse_ctx));
+ format_ctx.advance_to(f.format(*static_cast<const T*>(ptr), format_ctx));
+ }) {}
+
+template<class Context>
+void basic_format_arg<Context>::handle::format(basic_format_parse_context<char_type>& parse_ctx, Context& format_ctx) const {
+ format_(parse_ctx, format_ctx, ptr_);
+}
+
+// https://fmt.dev/Text%20Formatting.html#format.visit
+template<class Visitor, class Context>
+ auto visit_format_arg(Visitor&& vis, basic_format_arg<Context> arg) {
+ return visit(vis, get_value(arg));
+ }
+}
+
+// https://fmt.dev/Text%20Formatting.html#format.store
+namespace std {
+ template<class Context, class... Args>
+ struct format_arg_store { // exposition only
+ array<basic_format_arg<Context>, sizeof...(Args)> args;
+ };
+}
+
+// https://fmt.dev/Text%20Formatting.html#format.basic_args
+namespace std {
+ template<class Context>
+ class basic_format_args {
+ size_t size_; // exposition only
+ const basic_format_arg<Context>* data_; // exposition only
+
+ public:
+ basic_format_args() noexcept;
+
+ template<class... Args>
+ basic_format_args(const format_arg_store<Context, Args...>& store) noexcept;
+
+ basic_format_arg<Context> get(size_t i) const noexcept;
+ };
+}
+
+namespace std {
+
+template<class Context>
+basic_format_args<Context>::basic_format_args() noexcept : size_(0) {}
+
+template<class Context>
+template<class... Args>
+ basic_format_args<Context>::basic_format_args(const format_arg_store<Context, Args...>& store) noexcept
+ : size_(sizeof...(Args)), data_(store.args.data()) {}
+
+template<class Context>
+basic_format_arg<Context> basic_format_args<Context>::get(size_t i) const noexcept {
+ return i < size_ ? data_[i] : basic_format_arg<Context>();
+}
+}
+
+namespace std {
+// https://fmt.dev/Text%20Formatting.html#format.make_args
+template<class Context /*= format_context*/, class... Args>
+ format_arg_store<Context, Args...> make_format_args(const Args&... args) {
+ return {basic_format_arg<Context>(args)...};
+ }
+
+// https://fmt.dev/Text%20Formatting.html#format.make_wargs
+template<class... Args>
+ format_arg_store<wformat_context, Args...> make_wformat_args(const Args&... args) {
+ return make_format_args<wformat_context>(args...);
+ }
+}
+
+namespace std {
+namespace detail {
+
+template <typename Range>
+class arg_formatter
+ : public fmt::internal::arg_formatter_base<Range, error_handler> {
+ private:
+ using char_type = typename Range::value_type;
+ using base = fmt::internal::arg_formatter_base<Range, error_handler>;
+ using format_context = std::basic_format_context<typename base::iterator, char_type>;
+ using parse_context = basic_format_parse_context<char_type>;
+
+ parse_context* parse_ctx_;
+ format_context& ctx_;
+
+ public:
+ typedef Range range;
+ typedef typename base::iterator iterator;
+ typedef typename base::format_specs format_specs;
+
+ /**
+ \rst
+ Constructs an argument formatter object.
+ *ctx* is a reference to the formatting context,
+ *spec* contains format specifier information for standard argument types.
+ \endrst
+ */
+ arg_formatter(format_context& ctx, parse_context* parse_ctx = nullptr, fmt::format_specs* spec = nullptr)
+ : base(Range(ctx.out()), spec, {}), parse_ctx_(parse_ctx), ctx_(ctx) {}
+
+ using base::operator();
+
+ /** Formats an argument of a user-defined type. */
+ iterator operator()(typename std::basic_format_arg<format_context>::handle handle) {
+ handle.format(*parse_ctx_, ctx_);
+ return this->out();
+ }
+
+ iterator operator()(monostate) {
+ throw format_error("");
+ }
+};
+
+template <typename Context>
+inline fmt::internal::type get_type(basic_format_arg<Context> arg) {
+ return visit_format_arg([&] (auto val) {
+ using char_type = typename Context::char_type;
+ using T = decltype(val);
+ if (std::is_same_v<T, monostate>)
+ return fmt::internal::none_type;
+ if (std::is_same_v<T, bool>)
+ return fmt::internal::bool_type;
+ if (std::is_same_v<T, char_type>)
+ return fmt::internal::char_type;
+ if (std::is_same_v<T, int>)
+ return fmt::internal::int_type;
+ if (std::is_same_v<T, unsigned int>)
+ return fmt::internal::uint_type;
+ if (std::is_same_v<T, long long int>)
+ return fmt::internal::long_long_type;
+ if (std::is_same_v<T, unsigned long long int>)
+ return fmt::internal::ulong_long_type;
+ if (std::is_same_v<T, double>)
+ return fmt::internal::double_type;
+ if (std::is_same_v<T, long double>)
+ return fmt::internal::long_double_type;
+ if (std::is_same_v<T, const char_type*>)
+ return fmt::internal::cstring_type;
+ if (std::is_same_v<T, basic_string_view<char_type>>)
+ return fmt::internal::string_type;
+ if (std::is_same_v<T, const void*>)
+ return fmt::internal::pointer_type;
+ assert(get_value(arg).index() == 12);
+ return fmt::internal::custom_type;
+ }, arg);
+}
+
+template <typename Context>
+class custom_formatter {
+ private:
+ using parse_context = basic_format_parse_context<typename Context::char_type>;
+ parse_context& parse_ctx_;
+ Context& format_ctx_;
+
+ public:
+ custom_formatter(parse_context& parse_ctx, Context& ctx) : parse_ctx_(parse_ctx), format_ctx_(ctx) {}
+
+ bool operator()(typename basic_format_arg<Context>::handle h) const {
+ h.format(parse_ctx_, format_ctx_);
+ return true;
+ }
+
+ template <typename T> bool operator()(T) const { return false; }
+};
+
+template <typename ArgFormatter, typename Char, typename Context>
+struct format_handler : detail::error_handler {
+ typedef typename ArgFormatter::range range;
+
+ format_handler(range r, basic_string_view<Char> str,
+ basic_format_args<Context> format_args,
+ fmt::internal::locale_ref loc)
+ : parse_ctx(str), context(r.begin(), format_args, loc) {}
+
+ void on_text(const Char* begin, const Char* end) {
+ auto size = fmt::internal::to_unsigned(end - begin);
+ auto out = context.out();
+ auto&& it = fmt::internal::reserve(out, size);
+ it = std::copy_n(begin, size, it);
+ context.advance_to(out);
+ }
+
+ void on_arg_id() {
+ arg = context.arg(parse_ctx.next_arg_id());
+ }
+ void on_arg_id(unsigned id) {
+ parse_ctx.check_arg_id(id);
+ arg = context.arg(id);
+ }
+ void on_arg_id(fmt::basic_string_view<Char>) {}
+
+ void on_replacement_field(const Char* p) {
+ parse_ctx.advance_to(parse_ctx.begin() + (p - &*parse_ctx.begin()));
+ custom_formatter<Context> f(parse_ctx, context);
+ if (!visit_format_arg(f, arg))
+ context.advance_to(visit_format_arg(ArgFormatter(context, &parse_ctx), arg));
+ }
+
+ const Char* on_format_specs(const Char* begin, const Char* end) {
+ parse_ctx.advance_to(parse_ctx.begin() + (begin - &*parse_ctx.begin()));
+ custom_formatter<Context> f(parse_ctx, context);
+ if (visit_format_arg(f, arg)) return &*parse_ctx.begin();
+ fmt::basic_format_specs<Char> specs;
+ using fmt::internal::specs_handler;
+ using parse_context = basic_format_parse_context<Char>;
+ fmt::internal::specs_checker<specs_handler<parse_context, Context>> handler(
+ specs_handler<parse_context, Context>(specs, parse_ctx, context), get_type(arg));
+ begin = parse_format_specs(begin, end, handler);
+ if (begin == end || *begin != '}') on_error("missing '}' in format string");
+ parse_ctx.advance_to(parse_ctx.begin() + (begin - &*parse_ctx.begin()));
+ context.advance_to(visit_format_arg(ArgFormatter(context, &parse_ctx, &specs), arg));
+ return begin;
+ }
+
+ basic_format_parse_context<Char> parse_ctx;
+ Context context;
+ basic_format_arg<Context> arg;
+};
+
+template <typename T, typename Char>
+struct formatter {
+ // Parses format specifiers stopping either at the end of the range or at the
+ // terminating '}'.
+ template <typename ParseContext>
+ FMT_CONSTEXPR typename ParseContext::iterator parse(ParseContext& ctx) {
+ namespace internal = fmt::internal;
+ typedef internal::dynamic_specs_handler<ParseContext> handler_type;
+ auto type = internal::mapped_type_constant<T, fmt::buffer_context<Char>>::value;
+ internal::specs_checker<handler_type> handler(handler_type(specs_, ctx),
+ type);
+ auto it = parse_format_specs(ctx.begin(), ctx.end(), handler);
+ auto type_spec = specs_.type;
+ auto eh = ctx.error_handler();
+ switch (type) {
+ case internal::none_type:
+ case internal::named_arg_type:
+ FMT_ASSERT(false, "invalid argument type");
+ break;
+ case internal::int_type:
+ case internal::uint_type:
+ case internal::long_long_type:
+ case internal::ulong_long_type:
+ case internal::bool_type:
+ handle_int_type_spec(type_spec,
+ internal::int_type_checker<decltype(eh)>(eh));
+ break;
+ case internal::char_type:
+ handle_char_specs(
+ &specs_, internal::char_specs_checker<decltype(eh)>(type_spec, eh));
+ break;
+ case internal::double_type:
+ case internal::long_double_type:
+ handle_float_type_spec(type_spec,
+ internal::float_type_checker<decltype(eh)>(eh));
+ break;
+ case internal::cstring_type:
+ internal::handle_cstring_type_spec(
+ type_spec, internal::cstring_type_checker<decltype(eh)>(eh));
+ break;
+ case internal::string_type:
+ internal::check_string_type_spec(type_spec, eh);
+ break;
+ case internal::pointer_type:
+ internal::check_pointer_type_spec(type_spec, eh);
+ break;
+ case internal::custom_type:
+ // Custom format specifiers should be checked in parse functions of
+ // formatter specializations.
+ break;
+ }
+ return it;
+ }
+
+ template <typename FormatContext>
+ auto format(const T& val, FormatContext& ctx) -> decltype(ctx.out()) {
+ fmt::internal::handle_dynamic_spec<fmt::internal::width_checker>(
+ specs_.width, specs_.width_ref, ctx, nullptr);
+ fmt::internal::handle_dynamic_spec<fmt::internal::precision_checker>(
+ specs_.precision, specs_.precision_ref, ctx, nullptr);
+ using range_type = fmt::internal::output_range<typename FormatContext::iterator,
+ typename FormatContext::char_type>;
+ return visit_format_arg(arg_formatter<range_type>(ctx, nullptr, &specs_),
+ basic_format_arg<FormatContext>(val));
+ }
+
+ private:
+ fmt::internal::dynamic_format_specs<Char> specs_;
+};
+} // namespace detail
+
+// https://fmt.dev/Text%20Formatting.html#format.functions
+template<class... Args>
+ string format(string_view fmt, const Args&... args) {
+ return vformat(fmt, make_format_args(args...));
+ }
+
+template<class... Args>
+ wstring format(wstring_view fmt, const Args&... args) {
+ return vformat(fmt, make_wformat_args(args...));
+ }
+
+string vformat(string_view fmt, format_args args) {
+ fmt::memory_buffer mbuf;
+ fmt::internal::buffer<char>& buf = mbuf;
+ using range = fmt::internal::buffer_range<char>;
+ detail::format_handler<detail::arg_formatter<range>, char, format_context>
+ h(range(std::back_inserter(buf)), fmt, args, {});
+ fmt::internal::parse_format_string<false>(fmt::to_string_view(fmt), h);
+ return to_string(mbuf);
+}
+
+wstring vformat(wstring_view fmt, wformat_args args);
+
+template<class Out, class... Args>
+ Out format_to(Out out, string_view fmt, const Args&... args) {
+ using context = basic_format_context<Out, decltype(fmt)::value_type>;
+ return vformat_to(out, fmt, {make_format_args<context>(args...)});
+ }
+
+template<class Out, class... Args>
+ Out format_to(Out out, wstring_view fmt, const Args&... args) {
+ using context = basic_format_context<Out, decltype(fmt)::value_type>;
+ return vformat_to(out, fmt, {make_format_args<context>(args...)});
+ }
+
+template<class Out>
+ Out vformat_to(Out out, string_view fmt, format_args_t<Out, char> args) {
+ using range = fmt::internal::output_range<Out, char>;
+ detail::format_handler<detail::arg_formatter<range>, char, basic_format_context<Out, char>>
+ h(range(out), fmt, args, {});
+ fmt::internal::parse_format_string<false>(fmt::to_string_view(fmt), h);
+ return h.context.out();
+ }
+
+template<class Out>
+ Out vformat_to(Out out, wstring_view fmt, format_args_t<Out, wchar_t> args);
+
+template<class Out, class... Args>
+ format_to_n_result<Out> format_to_n(Out out, iter_difference_t<Out> n,
+ string_view fmt, const Args&... args);
+template<class Out, class... Args>
+ format_to_n_result<Out> format_to_n(Out out, iter_difference_t<Out> n,
+ wstring_view fmt, const Args&... args);
+
+template<class... Args>
+ size_t formatted_size(string_view fmt, const Args&... args);
+template<class... Args>
+ size_t formatted_size(wstring_view fmt, const Args&... args);
+
+#define charT char
+
+template<> struct formatter<charT, charT> : detail::formatter<charT, charT> {};
+
+template<> struct formatter<char, wchar_t>;
+
+template<> struct formatter<charT*, charT> : detail::formatter<const charT*, charT> {};
+
+template<> struct formatter<const charT*, charT> : detail::formatter<const charT*, charT> {};
+
+template<size_t N> struct formatter<const charT[N], charT>
+ : detail::formatter<std::basic_string_view<charT>, charT> {};
+
+template<class traits, class Allocator>
+ struct formatter<basic_string<charT, traits, Allocator>, charT>
+ : detail::formatter<std::basic_string_view<charT>, charT> {};
+
+template<class traits>
+ struct formatter<basic_string_view<charT, traits>, charT>
+ : detail::formatter<std::basic_string_view<charT>, charT> {};
+
+template <> struct formatter<nullptr_t, charT> : detail::formatter<const void*, charT> {};
+template <> struct formatter<void*, charT> : detail::formatter<const void*, charT> {};
+template <> struct formatter<const void*, charT> : detail::formatter<const void*, charT> {};
+template <> struct formatter<bool, charT> : detail::formatter<bool, charT> {};
+
+template <> struct formatter<signed char, charT> : detail::formatter<int, charT> {};
+template <> struct formatter<short, charT> : detail::formatter<int, charT> {};
+template <> struct formatter<int, charT> : detail::formatter<int, charT> {};
+template <> struct formatter<long, charT>
+ : detail::formatter<std::conditional_t<sizeof(long) == sizeof(int), int, long long>, charT> {};
+template <> struct formatter<long long, charT> : detail::formatter<long long, charT> {};
+template <> struct formatter<unsigned char, charT> : detail::formatter<unsigned int, charT> {};
+template <> struct formatter<unsigned short, charT> : detail::formatter<unsigned int, charT> {};
+template <> struct formatter<unsigned int, charT> : detail::formatter<unsigned int, charT> {};
+template <> struct formatter<unsigned long, charT>
+ : detail::formatter<std::conditional_t<sizeof(long) == sizeof(int), unsigned, unsigned long long>, charT> {};
+template <> struct formatter<unsigned long long, charT> : detail::formatter<unsigned long long, charT> {};
+
+template <> struct formatter<float, charT> : detail::formatter<double, charT> {};
+template <> struct formatter<double, charT> : detail::formatter<double, charT> {};
+template <> struct formatter<long double, charT> : detail::formatter<long double, charT> {};
+
+#undef charT
+
+#define charT wchar_t
+
+template<> struct formatter<charT, charT> : detail::formatter<charT, charT> {};
+
+template<> struct formatter<char, wchar_t> : detail::formatter<charT, charT> {};
+
+template<> struct formatter<charT*, charT> : detail::formatter<const charT*, charT> {};
+
+template<> struct formatter<const charT*, charT> : detail::formatter<const charT*, charT> {};
+
+template<size_t N> struct formatter<const charT[N], charT>
+ : detail::formatter<std::basic_string_view<charT>, charT> {};
+
+template<class traits, class Allocator>
+ struct formatter<std::basic_string<charT, traits, Allocator>, charT>
+ : detail::formatter<std::basic_string_view<charT>, charT> {};
+
+template<class traits>
+ struct formatter<std::basic_string_view<charT, traits>, charT>
+ : detail::formatter<std::basic_string_view<charT>, charT> {};
+
+template <> struct formatter<nullptr_t, charT> : detail::formatter<const void*, charT> {};
+template <> struct formatter<void*, charT> : detail::formatter<const void*, charT> {};
+template <> struct formatter<const void*, charT> : detail::formatter<const void*, charT> {};
+template <> struct formatter<bool, charT> : detail::formatter<bool, charT> {};
+
+template <> struct formatter<signed char, charT> : detail::formatter<int, charT> {};
+template <> struct formatter<short, charT> : detail::formatter<int, charT> {};
+template <> struct formatter<int, charT> : detail::formatter<int, charT> {};
+template <> struct formatter<long, charT>
+ : detail::formatter<std::conditional_t<sizeof(long) == sizeof(int), int, long long>, charT> {};
+template <> struct formatter<long long, charT> : detail::formatter<long long, charT> {};
+template <> struct formatter<unsigned char, charT> : detail::formatter<unsigned int, charT> {};
+template <> struct formatter<unsigned short, charT> : detail::formatter<unsigned int, charT> {};
+template <> struct formatter<unsigned int, charT> : detail::formatter<unsigned int, charT> {};
+template <> struct formatter<unsigned long, charT>
+ : detail::formatter<std::conditional_t<sizeof(long) == sizeof(int), unsigned, unsigned long long>, charT> {};
+template <> struct formatter<unsigned long long, charT> : detail::formatter<unsigned long long, charT> {};
+
+template <> struct formatter<float, charT> : detail::formatter<double, charT> {};
+template <> struct formatter<double, charT> : detail::formatter<double, charT> {};
+template <> struct formatter<long double, charT> : detail::formatter<long double, charT> {};
+
+#undef charT
+
+ template<> struct formatter<const wchar_t, char> {
+ formatter() = delete;
+ };
+}
+
+#endif // FMT_FORMAT_
diff --git a/test/format-impl-test.cc b/test/format-impl-test.cc
index 8d20e77..2017283 100644
--- a/test/format-impl-test.cc
+++ b/test/format-impl-test.cc
@@ -11,7 +11,6 @@
// Include format.cc instead of format.h to test implementation.
#include "../src/format.cc"
-#include "fmt/color.h"
#include "fmt/printf.h"
#include <algorithm>
@@ -21,24 +20,15 @@
#include "gtest-extra.h"
#include "util.h"
-#undef min
#undef max
-#if FMT_HAS_CPP_ATTRIBUTE(noreturn)
-# define FMT_NORETURN [[noreturn]]
-#else
-# define FMT_NORETURN
-#endif
-
using fmt::internal::fp;
-template <bool is_iec559>
-void test_construct_from_double() {
+template <bool is_iec559> void test_construct_from_double() {
fmt::print("warning: double is not IEC559, skipping FP tests\n");
}
-template <>
-void test_construct_from_double<true>() {
+template <> void test_construct_from_double<true>() {
auto v = fp(1.23);
EXPECT_EQ(v.f, 0x13ae147ae147aeu);
EXPECT_EQ(v.e, -52);
@@ -98,23 +88,65 @@
EXPECT_LE(exp, fp.e);
int dec_exp_step = 8;
EXPECT_LE(fp.e, exp + dec_exp_step * log2(10));
- EXPECT_DOUBLE_EQ(pow(10, dec_exp), ldexp(fp.f, fp.e));
+ EXPECT_DOUBLE_EQ(pow(10, dec_exp), ldexp(static_cast<double>(fp.f), fp.e));
}
}
-TEST(FPTest, Grisu2FormatCompilesWithNonIEEEDouble) {
+TEST(FPTest, GetRoundDirection) {
+ using fmt::internal::get_round_direction;
+ EXPECT_EQ(fmt::internal::down, get_round_direction(100, 50, 0));
+ EXPECT_EQ(fmt::internal::up, get_round_direction(100, 51, 0));
+ EXPECT_EQ(fmt::internal::down, get_round_direction(100, 40, 10));
+ EXPECT_EQ(fmt::internal::up, get_round_direction(100, 60, 10));
+ for (int i = 41; i < 60; ++i)
+ EXPECT_EQ(fmt::internal::unknown, get_round_direction(100, i, 10));
+ uint64_t max = std::numeric_limits<uint64_t>::max();
+ EXPECT_THROW(get_round_direction(100, 100, 0), assertion_failure);
+ EXPECT_THROW(get_round_direction(100, 0, 100), assertion_failure);
+ EXPECT_THROW(get_round_direction(100, 0, 50), assertion_failure);
+ // Check that remainder + error doesn't overflow.
+ EXPECT_EQ(fmt::internal::up, get_round_direction(max, max - 1, 2));
+ // Check that 2 * (remainder + error) doesn't overflow.
+ EXPECT_EQ(fmt::internal::unknown,
+ get_round_direction(max, max / 2 + 1, max / 2));
+ // Check that remainder - error doesn't overflow.
+ EXPECT_EQ(fmt::internal::unknown, get_round_direction(100, 40, 41));
+ // Check that 2 * (remainder - error) doesn't overflow.
+ EXPECT_EQ(fmt::internal::up, get_round_direction(max, max - 1, 1));
+}
+
+TEST(FPTest, FixedHandler) {
+ struct handler : fmt::internal::fixed_handler {
+ char buffer[10];
+ handler(int prec = 0) : fmt::internal::fixed_handler() {
+ buf = buffer;
+ precision = prec;
+ }
+ };
+ int exp = 0;
+ handler().on_digit('0', 100, 99, 0, exp, false);
+ EXPECT_THROW(handler().on_digit('0', 100, 100, 0, exp, false),
+ assertion_failure);
+ namespace digits = fmt::internal::digits;
+ EXPECT_EQ(handler(1).on_digit('0', 100, 10, 10, exp, false), digits::done);
+ // Check that divisor - error doesn't overflow.
+ EXPECT_EQ(handler(1).on_digit('0', 100, 10, 101, exp, false), digits::error);
+ // Check that 2 * error doesn't overflow.
+ uint64_t max = std::numeric_limits<uint64_t>::max();
+ EXPECT_EQ(handler(1).on_digit('0', max, 10, max - 1, exp, false),
+ digits::error);
+}
+
+TEST(FPTest, GrisuFormatCompilesWithNonIEEEDouble) {
fmt::memory_buffer buf;
- grisu2_format(4.2f, buf, fmt::core_format_specs());
+ int exp = 0;
+ grisu_format(4.2f, buf, -1, false, exp);
}
-template <typename T>
-struct ValueExtractor: fmt::internal::function<T> {
- T operator()(T value) {
- return value;
- }
+template <typename T> struct value_extractor {
+ T operator()(T value) { return value; }
- template <typename U>
- FMT_NORETURN T operator()(U) {
+ template <typename U> FMT_NORETURN T operator()(U) {
throw std::runtime_error(fmt::format("invalid type {}", typeid(U).name()));
}
};
@@ -122,9 +154,10 @@
TEST(FormatTest, ArgConverter) {
long long value = std::numeric_limits<long long>::max();
auto arg = fmt::internal::make_arg<fmt::format_context>(value);
- visit(fmt::internal::arg_converter<long long, fmt::format_context>(arg, 'd'),
- arg);
- EXPECT_EQ(value, visit(ValueExtractor<long long>(), arg));
+ fmt::visit_format_arg(
+ fmt::internal::arg_converter<long long, fmt::format_context>(arg, 'd'),
+ arg);
+ EXPECT_EQ(value, fmt::visit_format_arg(value_extractor<long long>(), arg));
}
TEST(FormatTest, FormatNegativeNaN) {
@@ -136,11 +169,11 @@
}
TEST(FormatTest, StrError) {
- char *message = FMT_NULL;
+ char* message = nullptr;
char buffer[BUFFER_SIZE];
- EXPECT_ASSERT(fmt::safe_strerror(EDOM, message = FMT_NULL, 0),
+ EXPECT_ASSERT(fmt::internal::safe_strerror(EDOM, message = nullptr, 0),
"invalid buffer");
- EXPECT_ASSERT(fmt::safe_strerror(EDOM, message = buffer, 0),
+ EXPECT_ASSERT(fmt::internal::safe_strerror(EDOM, message = buffer, 0),
"invalid buffer");
buffer[0] = 'x';
#if defined(_GNU_SOURCE) && !defined(__COVERITY__)
@@ -151,17 +184,19 @@
int error_code = EDOM;
#endif
- int result = fmt::safe_strerror(error_code, message = buffer, BUFFER_SIZE);
+ int result =
+ fmt::internal::safe_strerror(error_code, message = buffer, BUFFER_SIZE);
EXPECT_EQ(result, 0);
std::size_t message_size = std::strlen(message);
EXPECT_GE(BUFFER_SIZE - 1u, message_size);
EXPECT_EQ(get_system_error(error_code), message);
// safe_strerror never uses buffer on MinGW.
-#ifndef __MINGW32__
- result = fmt::safe_strerror(error_code, message = buffer, message_size);
+#if !defined(__MINGW32__) && !defined(__sun)
+ result =
+ fmt::internal::safe_strerror(error_code, message = buffer, message_size);
EXPECT_EQ(ERANGE, result);
- result = fmt::safe_strerror(error_code, message = buffer, 1);
+ result = fmt::internal::safe_strerror(error_code, message = buffer, 1);
EXPECT_EQ(buffer, message); // Message should point to buffer.
EXPECT_EQ(ERANGE, result);
EXPECT_STREQ("", message);
@@ -173,14 +208,14 @@
{
fmt::memory_buffer buffer;
format_to(buffer, "garbage");
- fmt::format_error_code(buffer, 42, "test");
+ fmt::internal::format_error_code(buffer, 42, "test");
EXPECT_EQ("test: " + msg, to_string(buffer));
}
{
fmt::memory_buffer buffer;
- std::string prefix(
- fmt::inline_buffer_size - msg.size() - sep.size() + 1, 'x');
- fmt::format_error_code(buffer, 42, prefix);
+ std::string prefix(fmt::inline_buffer_size - msg.size() - sep.size() + 1,
+ 'x');
+ fmt::internal::format_error_code(buffer, 42, prefix);
EXPECT_EQ(msg, to_string(buffer));
}
int codes[] = {42, -1};
@@ -188,16 +223,15 @@
// Test maximum buffer size.
msg = fmt::format("error {}", codes[i]);
fmt::memory_buffer buffer;
- std::string prefix(
- fmt::inline_buffer_size - msg.size() - sep.size(), 'x');
- fmt::format_error_code(buffer, codes[i], prefix);
+ std::string prefix(fmt::inline_buffer_size - msg.size() - sep.size(), 'x');
+ fmt::internal::format_error_code(buffer, codes[i], prefix);
EXPECT_EQ(prefix + sep + msg, to_string(buffer));
std::size_t size = fmt::inline_buffer_size;
EXPECT_EQ(size, buffer.size());
buffer.resize(0);
// Test with a message that doesn't fit into the buffer.
prefix += 'x';
- fmt::format_error_code(buffer, codes[i], prefix);
+ fmt::internal::format_error_code(buffer, codes[i], prefix);
EXPECT_EQ(msg, to_string(buffer));
}
}
@@ -206,41 +240,27 @@
EXPECT_EQ(4, fmt::internal::count_code_points(fmt::u8string_view("ёжик")));
}
-TEST(ColorsTest, Colors) {
- EXPECT_WRITE(stdout, fmt::print(fg(fmt::rgb(255, 20, 30)), "rgb(255,20,30)"),
- "\x1b[38;2;255;020;030mrgb(255,20,30)\x1b[0m");
- EXPECT_WRITE(stdout, fmt::print(fg(fmt::color::blue), "blue"),
- "\x1b[38;2;000;000;255mblue\x1b[0m");
- EXPECT_WRITE(
- stdout,
- fmt::print(fg(fmt::color::blue) | bg(fmt::color::red), "two color"),
- "\x1b[38;2;000;000;255m\x1b[48;2;255;000;000mtwo color\x1b[0m");
- EXPECT_WRITE(stdout, fmt::print(fmt::emphasis::bold, "bold"),
- "\x1b[1mbold\x1b[0m");
- EXPECT_WRITE(stdout, fmt::print(fmt::emphasis::italic, "italic"),
- "\x1b[3mitalic\x1b[0m");
- EXPECT_WRITE(stdout, fmt::print(fmt::emphasis::underline, "underline"),
- "\x1b[4munderline\x1b[0m");
- EXPECT_WRITE(stdout,
- fmt::print(fmt::emphasis::strikethrough, "strikethrough"),
- "\x1b[9mstrikethrough\x1b[0m");
- EXPECT_WRITE(
- stdout,
- fmt::print(fg(fmt::color::blue) | fmt::emphasis::bold, "blue/bold"),
- "\x1b[1m\x1b[38;2;000;000;255mblue/bold\x1b[0m");
- EXPECT_WRITE(stderr, fmt::print(stderr, fmt::emphasis::bold, "bold error"),
- "\x1b[1mbold error\x1b[0m");
- EXPECT_WRITE(stderr, fmt::print(stderr, fg(fmt::color::blue), "blue log"),
- "\x1b[38;2;000;000;255mblue log\x1b[0m");
- EXPECT_WRITE(stdout, fmt::print(fmt::text_style(), "hi"), "hi");
- EXPECT_WRITE(stdout, fmt::print(fg(fmt::terminal_color::red), "tred"),
- "\x1b[31mtred\x1b[0m");
- EXPECT_WRITE(stdout, fmt::print(bg(fmt::terminal_color::cyan), "tcyan"),
- "\x1b[46mtcyan\x1b[0m");
- EXPECT_WRITE(stdout,
- fmt::print(fg(fmt::terminal_color::bright_green), "tbgreen"),
- "\x1b[92mtbgreen\x1b[0m");
- EXPECT_WRITE(stdout,
- fmt::print(bg(fmt::terminal_color::bright_magenta), "tbmagenta"),
- "\x1b[105mtbmagenta\x1b[0m");
+// Tests fmt::internal::count_digits for integer type Int.
+template <typename Int> void test_count_digits() {
+ for (Int i = 0; i < 10; ++i) EXPECT_EQ(1u, fmt::internal::count_digits(i));
+ for (Int i = 1, n = 1, end = std::numeric_limits<Int>::max() / 10; n <= end;
+ ++i) {
+ n *= 10;
+ EXPECT_EQ(i, fmt::internal::count_digits(n - 1));
+ EXPECT_EQ(i + 1, fmt::internal::count_digits(n));
+ }
+}
+
+TEST(UtilTest, CountDigits) {
+ test_count_digits<uint32_t>();
+ test_count_digits<uint64_t>();
+}
+
+TEST(UtilTest, WriteUIntPtr) {
+ fmt::memory_buffer buf;
+ fmt::internal::writer writer(buf);
+ writer.write_pointer(fmt::internal::bit_cast<fmt::internal::fallback_uintptr>(
+ reinterpret_cast<void*>(0xface)),
+ nullptr);
+ EXPECT_EQ("0xface", to_string(buf));
}
diff --git a/test/format-test.cc b/test/format-test.cc
index 2ce513b..dfc265f 100644
--- a/test/format-test.cc
+++ b/test/format-test.cc
@@ -5,6 +5,7 @@
//
// For the license information refer to format.h.
+#include <stdint.h>
#include <cctype>
#include <cfloat>
#include <climits>
@@ -13,13 +14,13 @@
#include <list>
#include <memory>
#include <string>
-#include <stdint.h>
// Check if fmt/format.h compiles with windows.h included before it.
#ifdef _WIN32
-# include <windows.h>
+# include <windows.h>
#endif
+#include "fmt/color.h"
#include "fmt/format.h"
#include "gmock.h"
#include "gtest-extra.h"
@@ -33,11 +34,11 @@
using std::size_t;
using fmt::basic_memory_buffer;
-using fmt::basic_writer;
+using fmt::internal::basic_writer;
using fmt::format;
using fmt::format_error;
-using fmt::string_view;
using fmt::memory_buffer;
+using fmt::string_view;
using fmt::wmemory_buffer;
using testing::Return;
@@ -46,40 +47,34 @@
namespace {
#if !FMT_GCC_VERSION || FMT_GCC_VERSION >= 408
-template <typename Char, typename T>
-bool check_enabled_formatter() {
- static_assert(
- std::is_default_constructible<fmt::formatter<T, Char>>::value, "");
+template <typename Char, typename T> bool check_enabled_formatter() {
+ static_assert(std::is_default_constructible<fmt::formatter<T, Char>>::value,
+ "");
return true;
}
-template <typename Char, typename... T>
-void check_enabled_formatters() {
+template <typename Char, typename... T> void check_enabled_formatters() {
auto dummy = {check_enabled_formatter<Char, T>()...};
(void)dummy;
}
TEST(FormatterTest, TestFormattersEnabled) {
- check_enabled_formatters<char,
- bool, char, signed char, unsigned char, short, unsigned short,
- int, unsigned, long, unsigned long, long long, unsigned long long,
- float, double, long double, void*, const void*,
- char*, const char*, std::string>();
- check_enabled_formatters<wchar_t,
- bool, wchar_t, signed char, unsigned char, short, unsigned short,
- int, unsigned, long, unsigned long, long long, unsigned long long,
- float, double, long double, void*, const void*,
- wchar_t*, const wchar_t*, std::wstring>();
-#if FMT_USE_NULLPTR
- check_enabled_formatters<char, std::nullptr_t>();
- check_enabled_formatters<wchar_t, std::nullptr_t>();
-#endif
+ check_enabled_formatters<char, bool, char, signed char, unsigned char, short,
+ unsigned short, int, unsigned, long, unsigned long,
+ long long, unsigned long long, float, double,
+ long double, void*, const void*, char*, const char*,
+ std::string, std::nullptr_t>();
+ check_enabled_formatters<wchar_t, bool, wchar_t, signed char, unsigned char,
+ short, unsigned short, int, unsigned, long,
+ unsigned long, long long, unsigned long long, float,
+ double, long double, void*, const void*, wchar_t*,
+ const wchar_t*, std::wstring, std::nullptr_t>();
}
#endif
// Format value using the standard library.
template <typename Char, typename T>
-void std_format(const T &value, std::basic_string<Char> &result) {
+void std_format(const T& value, std::basic_string<Char>& result) {
std::basic_ostringstream<Char> os;
os << value;
result = os.str();
@@ -87,12 +82,12 @@
#ifdef __MINGW32__
// Workaround a bug in formatting long double in MinGW.
-void std_format(long double value, std::string &result) {
+void std_format(long double value, std::string& result) {
char buffer[100];
safe_sprintf(buffer, "%Lg", value);
result = buffer;
}
-void std_format(long double value, std::wstring &result) {
+void std_format(long double value, std::wstring& result) {
wchar_t buffer[100];
swprintf(buffer, L"%Lg", value);
result = buffer;
@@ -102,34 +97,32 @@
// Checks if writing value to BasicWriter<Char> produces the same result
// as writing it to std::basic_ostringstream<Char>.
template <typename Char, typename T>
-::testing::AssertionResult check_write(const T &value, const char *type) {
+::testing::AssertionResult check_write(const T& value, const char* type) {
fmt::basic_memory_buffer<Char> buffer;
- typedef fmt::back_insert_range<fmt::internal::basic_buffer<Char>> range;
- fmt::basic_writer<range> writer(buffer);
+ using range = fmt::internal::buffer_range<Char>;
+ basic_writer<range> writer(buffer);
writer.write(value);
std::basic_string<Char> actual = to_string(buffer);
std::basic_string<Char> expected;
std_format(value, expected);
- if (expected == actual)
- return ::testing::AssertionSuccess();
+ if (expected == actual) return ::testing::AssertionSuccess();
return ::testing::AssertionFailure()
- << "Value of: (Writer<" << type << ">() << value).str()\n"
- << " Actual: " << actual << "\n"
- << "Expected: " << expected << "\n";
+ << "Value of: (Writer<" << type << ">() << value).str()\n"
+ << " Actual: " << actual << "\n"
+ << "Expected: " << expected << "\n";
}
struct AnyWriteChecker {
template <typename T>
- ::testing::AssertionResult operator()(const char *, const T &value) const {
+ ::testing::AssertionResult operator()(const char*, const T& value) const {
::testing::AssertionResult result = check_write<char>(value, "char");
return result ? check_write<wchar_t>(value, "wchar_t") : result;
}
};
-template <typename Char>
-struct WriteChecker {
+template <typename Char> struct WriteChecker {
template <typename T>
- ::testing::AssertionResult operator()(const char *, const T &value) const {
+ ::testing::AssertionResult operator()(const char*, const T& value) const {
return check_write<Char>(value, "char");
}
};
@@ -138,30 +131,11 @@
// as writing it to std::ostringstream both for char and wchar_t.
#define CHECK_WRITE(value) EXPECT_PRED_FORMAT1(AnyWriteChecker(), value)
-#define CHECK_WRITE_CHAR(value) \
- EXPECT_PRED_FORMAT1(WriteChecker<char>(), value)
+#define CHECK_WRITE_CHAR(value) EXPECT_PRED_FORMAT1(WriteChecker<char>(), value)
#define CHECK_WRITE_WCHAR(value) \
EXPECT_PRED_FORMAT1(WriteChecker<wchar_t>(), value)
} // namespace
-// Tests fmt::internal::count_digits for integer type Int.
-template <typename Int>
-void test_count_digits() {
- for (Int i = 0; i < 10; ++i)
- EXPECT_EQ(1u, fmt::internal::count_digits(i));
- for (Int i = 1, n = 1,
- end = std::numeric_limits<Int>::max() / 10; n <= end; ++i) {
- n *= 10;
- EXPECT_EQ(i, fmt::internal::count_digits(n - 1));
- EXPECT_EQ(i + 1, fmt::internal::count_digits(n));
- }
-}
-
-TEST(UtilTest, CountDigits) {
- test_count_digits<uint32_t>();
- test_count_digits<uint64_t>();
-}
-
struct uint32_pair {
uint32_t u[2];
};
@@ -196,14 +170,14 @@
fmt::string_view s = "10000000000";
auto begin = s.begin(), end = s.end();
EXPECT_THROW_MSG(
- parse_nonnegative_int(begin, end, fmt::internal::error_handler()),
- fmt::format_error, "number is too big");
+ parse_nonnegative_int(begin, end, fmt::internal::error_handler()),
+ fmt::format_error, "number is too big");
s = "2147483649";
begin = s.begin();
end = s.end();
EXPECT_THROW_MSG(
- parse_nonnegative_int(begin, end, fmt::internal::error_handler()),
- fmt::format_error, "number is too big");
+ parse_nonnegative_int(begin, end, fmt::internal::error_handler()),
+ fmt::format_error, "number is too big");
}
TEST(IteratorTest, CountingIterator) {
@@ -214,7 +188,7 @@
}
TEST(IteratorTest, TruncatingIterator) {
- char *p = FMT_NULL;
+ char* p = nullptr;
fmt::internal::truncating_iterator<char*> it(p, 3);
auto prev = it++;
EXPECT_EQ(prev.base(), p);
@@ -238,13 +212,12 @@
EXPECT_FALSE(fmt::internal::is_output_iterator<std::string>::value);
EXPECT_TRUE(fmt::internal::is_output_iterator<
std::back_insert_iterator<std::string>>::value);
- EXPECT_TRUE(fmt::internal::is_output_iterator<
- std::string::iterator>::value);
- EXPECT_FALSE(fmt::internal::is_output_iterator<
- std::string::const_iterator>::value);
+ EXPECT_TRUE(fmt::internal::is_output_iterator<std::string::iterator>::value);
+ EXPECT_FALSE(
+ fmt::internal::is_output_iterator<std::string::const_iterator>::value);
EXPECT_FALSE(fmt::internal::is_output_iterator<std::list<char>>::value);
- EXPECT_TRUE(fmt::internal::is_output_iterator<
- std::list<char>::iterator>::value);
+ EXPECT_TRUE(
+ fmt::internal::is_output_iterator<std::list<char>::iterator>::value);
EXPECT_FALSE(fmt::internal::is_output_iterator<
std::list<char>::const_iterator>::value);
EXPECT_FALSE(fmt::internal::is_output_iterator<uint32_pair>::value);
@@ -256,11 +229,11 @@
EXPECT_EQ(123u, buffer.capacity());
}
-static void check_forwarding(
- mock_allocator<int> &alloc, allocator_ref<mock_allocator<int>> &ref) {
+static void check_forwarding(mock_allocator<int>& alloc,
+ allocator_ref<mock_allocator<int>>& ref) {
int mem;
// Check if value_type is properly defined.
- allocator_ref< mock_allocator<int> >::value_type *ptr = &mem;
+ allocator_ref<mock_allocator<int>>::value_type* ptr = &mem;
// Check forwarding.
EXPECT_CALL(alloc, allocate(42)).WillOnce(testing::Return(ptr));
ref.allocate(42);
@@ -269,31 +242,31 @@
}
TEST(AllocatorTest, allocator_ref) {
- StrictMock< mock_allocator<int> > alloc;
- typedef allocator_ref< mock_allocator<int> > test_allocator_ref;
+ StrictMock<mock_allocator<int>> alloc;
+ typedef allocator_ref<mock_allocator<int>> test_allocator_ref;
test_allocator_ref ref(&alloc);
// Check if allocator_ref forwards to the underlying allocator.
check_forwarding(alloc, ref);
test_allocator_ref ref2(ref);
check_forwarding(alloc, ref2);
test_allocator_ref ref3;
- EXPECT_EQ(FMT_NULL, ref3.get());
+ EXPECT_EQ(nullptr, ref3.get());
ref3 = ref;
check_forwarding(alloc, ref3);
}
-typedef allocator_ref< std::allocator<char> > TestAllocator;
+typedef allocator_ref<std::allocator<char>> TestAllocator;
-static void check_move_buffer(const char *str,
- basic_memory_buffer<char, 5, TestAllocator> &buffer) {
- std::allocator<char> *alloc = buffer.get_allocator().get();
+static void check_move_buffer(
+ const char* str, basic_memory_buffer<char, 5, TestAllocator>& buffer) {
+ std::allocator<char>* alloc = buffer.get_allocator().get();
basic_memory_buffer<char, 5, TestAllocator> buffer2(std::move(buffer));
// Move shouldn't destroy the inline content of the first buffer.
EXPECT_EQ(str, std::string(&buffer[0], buffer.size()));
EXPECT_EQ(str, std::string(&buffer2[0], buffer2.size()));
EXPECT_EQ(5u, buffer2.capacity());
// Move should transfer allocator.
- EXPECT_EQ(FMT_NULL, buffer.get_allocator().get());
+ EXPECT_EQ(nullptr, buffer.get_allocator().get());
EXPECT_EQ(alloc, buffer2.get_allocator().get());
}
@@ -307,7 +280,7 @@
// dynamic allocation.
buffer.push_back('a');
check_move_buffer("testa", buffer);
- const char *inline_buffer_ptr = &buffer[0];
+ const char* inline_buffer_ptr = &buffer[0];
// Adding one more character causes the content to move from the inline to
// a dynamically allocated buffer.
buffer.push_back('b');
@@ -318,8 +291,8 @@
EXPECT_GT(buffer2.capacity(), 5u);
}
-static void check_move_assign_buffer(
- const char *str, basic_memory_buffer<char, 5> &buffer) {
+static void check_move_assign_buffer(const char* str,
+ basic_memory_buffer<char, 5>& buffer) {
basic_memory_buffer<char, 5> buffer2;
buffer2 = std::move(buffer);
// Move shouldn't destroy the inline content of the first buffer.
@@ -337,7 +310,7 @@
// dynamic allocation.
buffer.push_back('a');
check_move_assign_buffer("testa", buffer);
- const char *inline_buffer_ptr = &buffer[0];
+ const char* inline_buffer_ptr = &buffer[0];
// Adding one more character causes the content to move from the inline to
// a dynamically allocated buffer.
buffer.push_back('b');
@@ -350,7 +323,7 @@
}
TEST(MemoryBufferTest, Grow) {
- typedef allocator_ref< mock_allocator<int> > Allocator;
+ typedef allocator_ref<mock_allocator<int>> Allocator;
typedef basic_memory_buffer<int, 10, Allocator> Base;
mock_allocator<int> alloc;
struct TestMemoryBuffer : Base {
@@ -359,8 +332,7 @@
} buffer((Allocator(&alloc)));
buffer.resize(7);
using fmt::internal::to_unsigned;
- for (int i = 0; i < 7; ++i)
- buffer[to_unsigned(i)] = i * i;
+ for (int i = 0; i < 7; ++i) buffer[to_unsigned(i)] = i * i;
EXPECT_EQ(10u, buffer.capacity());
int mem[20];
mem[7] = 0xdead;
@@ -368,21 +340,21 @@
buffer.grow(20);
EXPECT_EQ(20u, buffer.capacity());
// Check if size elements have been copied
- for (int i = 0; i < 7; ++i)
- EXPECT_EQ(i * i, buffer[to_unsigned(i)]);
+ for (int i = 0; i < 7; ++i) EXPECT_EQ(i * i, buffer[to_unsigned(i)]);
// and no more than that.
EXPECT_EQ(0xdead, buffer[7]);
EXPECT_CALL(alloc, deallocate(mem, 20));
}
TEST(MemoryBufferTest, Allocator) {
- typedef allocator_ref< mock_allocator<char> > TestAllocator;
+ typedef allocator_ref<mock_allocator<char>> TestAllocator;
basic_memory_buffer<char, 10, TestAllocator> buffer;
- EXPECT_EQ(FMT_NULL, buffer.get_allocator().get());
- StrictMock< mock_allocator<char> > alloc;
+ EXPECT_EQ(nullptr, buffer.get_allocator().get());
+ StrictMock<mock_allocator<char>> alloc;
char mem;
{
- basic_memory_buffer<char, 10, TestAllocator> buffer2((TestAllocator(&alloc)));
+ basic_memory_buffer<char, 10, TestAllocator> buffer2(
+ (TestAllocator(&alloc)));
EXPECT_EQ(&alloc, buffer2.get_allocator().get());
std::size_t size = 2 * fmt::inline_buffer_size;
EXPECT_CALL(alloc, allocate(size)).WillOnce(Return(&mem));
@@ -392,8 +364,8 @@
}
TEST(MemoryBufferTest, ExceptionInDeallocate) {
- typedef allocator_ref< mock_allocator<char> > TestAllocator;
- StrictMock< mock_allocator<char> > alloc;
+ typedef allocator_ref<mock_allocator<char>> TestAllocator;
+ StrictMock<mock_allocator<char>> alloc;
basic_memory_buffer<char, 10, TestAllocator> buffer((TestAllocator(&alloc)));
std::size_t size = 2 * fmt::inline_buffer_size;
std::vector<char> mem(size);
@@ -410,8 +382,7 @@
EXPECT_THROW(buffer.reserve(2 * size), std::exception);
EXPECT_EQ(&mem2[0], &buffer[0]);
// Check that the data has been copied.
- for (std::size_t i = 0; i < size; ++i)
- EXPECT_EQ('x', buffer[i]);
+ for (std::size_t i = 0; i < size; ++i) EXPECT_EQ('x', buffer[i]);
}
EXPECT_CALL(alloc, deallocate(&mem2[0], 2 * size));
}
@@ -447,14 +418,14 @@
template <typename Converter, typename Char>
void check_utf_conversion_error(
- const char *message,
- fmt::basic_string_view<Char> str = fmt::basic_string_view<Char>(0, 1)) {
+ const char* message,
+ fmt::basic_string_view<Char> str = fmt::basic_string_view<Char>(0, 1)) {
fmt::memory_buffer out;
fmt::internal::format_windows_error(out, ERROR_INVALID_PARAMETER, message);
fmt::system_error error(0, "");
try {
(Converter)(str);
- } catch (const fmt::system_error &e) {
+ } catch (const fmt::system_error& e) {
error = e;
}
EXPECT_EQ(ERROR_INVALID_PARAMETER, error.error_code());
@@ -467,10 +438,10 @@
}
TEST(UtilTest, UTF8ToUTF16Error) {
- const char *message = "cannot convert string from UTF-8 to UTF-16";
+ const char* message = "cannot convert string from UTF-8 to UTF-16";
check_utf_conversion_error<fmt::internal::utf8_to_utf16, char>(message);
check_utf_conversion_error<fmt::internal::utf8_to_utf16, char>(
- message, fmt::string_view("foo", INT_MAX + 1u));
+ message, fmt::string_view("foo", INT_MAX + 1u));
}
TEST(UtilTest, UTF16ToUTF8Convert) {
@@ -481,15 +452,15 @@
}
#endif // _WIN32
-typedef void (*FormatErrorMessage)(
- fmt::internal::buffer &out, int error_code, string_view message);
+typedef void (*FormatErrorMessage)(fmt::internal::buffer<char>& out,
+ int error_code, string_view message);
template <typename Error>
void check_throw_error(int error_code, FormatErrorMessage format) {
fmt::system_error error(0, "");
try {
throw Error(error_code, "test {}", "error");
- } catch (const fmt::system_error &e) {
+ } catch (const fmt::system_error& e) {
error = e;
}
fmt::memory_buffer message;
@@ -518,7 +489,7 @@
fmt::print("warning: std::allocator allocates {} chars", max_size);
return;
}
- fmt::format_system_error(message, EDOM, fmt::string_view(FMT_NULL, max_size));
+ fmt::format_system_error(message, EDOM, fmt::string_view(nullptr, max_size));
EXPECT_EQ(fmt::format("error {}", EDOM), to_string(message));
}
@@ -541,21 +512,22 @@
TEST(UtilTest, FormatWindowsError) {
LPWSTR message = 0;
- FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER |
- FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, 0,
- ERROR_FILE_EXISTS, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
- reinterpret_cast<LPWSTR>(&message), 0, 0);
+ FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM |
+ FORMAT_MESSAGE_IGNORE_INSERTS,
+ 0, ERROR_FILE_EXISTS,
+ MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
+ reinterpret_cast<LPWSTR>(&message), 0, 0);
fmt::internal::utf16_to_utf8 utf8_message(message);
LocalFree(message);
fmt::memory_buffer actual_message;
- fmt::internal::format_windows_error(
- actual_message, ERROR_FILE_EXISTS, "test");
+ fmt::internal::format_windows_error(actual_message, ERROR_FILE_EXISTS,
+ "test");
EXPECT_EQ(fmt::format("test: {}", utf8_message.str()),
- fmt::to_string(actual_message));
+ fmt::to_string(actual_message));
actual_message.resize(0);
fmt::internal::format_windows_error(
- actual_message, ERROR_FILE_EXISTS,
- fmt::string_view(0, std::numeric_limits<size_t>::max()));
+ actual_message, ERROR_FILE_EXISTS,
+ fmt::string_view(0, std::numeric_limits<size_t>::max()));
EXPECT_EQ(fmt::format("error {}", ERROR_FILE_EXISTS),
fmt::to_string(actual_message));
}
@@ -565,26 +537,28 @@
// this error code is not available on all Windows platforms and
// Windows SDKs, so do not fail the test if the error string cannot
// be retrieved.
- const int provisioning_not_allowed = 0x80284013L /*TBS_E_PROVISIONING_NOT_ALLOWED*/;
+ const int provisioning_not_allowed =
+ 0x80284013L /*TBS_E_PROVISIONING_NOT_ALLOWED*/;
if (FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER |
- FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, 0,
- static_cast<DWORD>(provisioning_not_allowed),
- MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
- reinterpret_cast<LPWSTR>(&message), 0, 0) == 0) {
+ FORMAT_MESSAGE_FROM_SYSTEM |
+ FORMAT_MESSAGE_IGNORE_INSERTS,
+ 0, static_cast<DWORD>(provisioning_not_allowed),
+ MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
+ reinterpret_cast<LPWSTR>(&message), 0, 0) == 0) {
return;
}
fmt::internal::utf16_to_utf8 utf8_message(message);
LocalFree(message);
fmt::memory_buffer actual_message;
- fmt::internal::format_windows_error(
- actual_message, provisioning_not_allowed, "test");
+ fmt::internal::format_windows_error(actual_message, provisioning_not_allowed,
+ "test");
EXPECT_EQ(fmt::format("test: {}", utf8_message.str()),
- fmt::to_string(actual_message));
+ fmt::to_string(actual_message));
}
TEST(UtilTest, WindowsError) {
- check_throw_error<fmt::windows_error>(
- ERROR_FILE_EXISTS, fmt::internal::format_windows_error);
+ check_throw_error<fmt::windows_error>(ERROR_FILE_EXISTS,
+ fmt::internal::format_windows_error);
}
TEST(UtilTest, ReportWindowsError) {
@@ -592,7 +566,7 @@
fmt::internal::format_windows_error(out, ERROR_FILE_EXISTS, "test error");
out.push_back('\n');
EXPECT_WRITE(stderr,
- fmt::report_windows_error(ERROR_FILE_EXISTS, "test error"),
+ fmt::report_windows_error(ERROR_FILE_EXISTS, "test error"),
fmt::to_string(out));
}
@@ -608,7 +582,7 @@
TEST(WriterTest, Data) {
memory_buffer buf;
- fmt::writer w(buf);
+ fmt::internal::writer w(buf);
w.write(42);
EXPECT_EQ("42", to_string(buf));
}
@@ -642,8 +616,15 @@
TEST(WriterTest, WriteDouble) {
CHECK_WRITE(4.2);
CHECK_WRITE(-4.2);
- CHECK_WRITE(std::numeric_limits<double>::min());
- CHECK_WRITE(std::numeric_limits<double>::max());
+ auto min = std::numeric_limits<double>::min();
+ auto max = std::numeric_limits<double>::max();
+ if (fmt::internal::use_grisu<double>()) {
+ EXPECT_EQ("2.2250738585072014e-308", fmt::format("{}", min));
+ EXPECT_EQ("1.7976931348623157e+308", fmt::format("{}", max));
+ } else {
+ CHECK_WRITE(min);
+ CHECK_WRITE(max);
+ }
}
TEST(WriterTest, WriteLongDouble) {
@@ -655,48 +636,45 @@
CHECK_WRITE_WCHAR(-4.2l);
else
fmt::print("warning: long double formatting with std::swprintf is broken");
- CHECK_WRITE(std::numeric_limits<long double>::min());
- CHECK_WRITE(std::numeric_limits<long double>::max());
+ auto min = std::numeric_limits<long double>::min();
+ auto max = std::numeric_limits<long double>::max();
+ if (fmt::internal::use_grisu<long double>()) {
+ EXPECT_EQ("2.2250738585072014e-308", fmt::format("{}", min));
+ EXPECT_EQ("1.7976931348623157e+308", fmt::format("{}", max));
+ } else {
+ CHECK_WRITE(min);
+ CHECK_WRITE(max);
+ }
}
TEST(WriterTest, WriteDoubleAtBufferBoundary) {
memory_buffer buf;
- fmt::writer writer(buf);
- for (int i = 0; i < 100; ++i)
- writer.write(1.23456789);
+ fmt::internal::writer writer(buf);
+ for (int i = 0; i < 100; ++i) writer.write(1.23456789);
}
TEST(WriterTest, WriteDoubleWithFilledBuffer) {
memory_buffer buf;
- fmt::writer writer(buf);
+ fmt::internal::writer writer(buf);
// Fill the buffer.
- for (int i = 0; i < fmt::inline_buffer_size; ++i)
- writer.write(' ');
+ for (int i = 0; i < fmt::inline_buffer_size; ++i) writer.write(' ');
writer.write(1.2);
fmt::string_view sv(buf.data(), buf.size());
sv.remove_prefix(fmt::inline_buffer_size);
EXPECT_EQ("1.2", sv);
}
-TEST(WriterTest, WriteChar) {
- CHECK_WRITE('a');
-}
+TEST(WriterTest, WriteChar) { CHECK_WRITE('a'); }
-TEST(WriterTest, WriteWideChar) {
- CHECK_WRITE_WCHAR(L'a');
-}
+TEST(WriterTest, WriteWideChar) { CHECK_WRITE_WCHAR(L'a'); }
TEST(WriterTest, WriteString) {
CHECK_WRITE_CHAR("abc");
CHECK_WRITE_WCHAR("abc");
- // The following line shouldn't compile:
- //std::declval<fmt::basic_writer<fmt::buffer>>().write(L"abc");
}
TEST(WriterTest, WriteWideString) {
CHECK_WRITE_WCHAR(L"abc");
- // The following line shouldn't compile:
- //std::declval<fmt::basic_writer<fmt::wbuffer>>().write("abc");
}
TEST(FormatToTest, FormatWithoutArgs) {
@@ -722,7 +700,7 @@
TEST(FormatToTest, FormatToNonbackInsertIteratorWithSignAndNumericAlignment) {
char buffer[16] = {};
fmt::format_to(fmt::internal::make_checked(buffer, 16), "{: =+}", 42.0);
- EXPECT_STREQ("+42", buffer);
+ EXPECT_STREQ("+42.0", buffer);
}
TEST(FormatToTest, FormatToMemoryBuffer) {
@@ -755,9 +733,7 @@
EXPECT_THROW_MSG(format("{0{}"), format_error, "invalid format string");
}
-TEST(FormatterTest, NoArgs) {
- EXPECT_EQ("test", format("test"));
-}
+TEST(FormatterTest, NoArgs) { EXPECT_EQ("test", format("test")); }
TEST(FormatterTest, ArgsInDifferentPositions) {
EXPECT_EQ("42", format("{0}", 42));
@@ -781,7 +757,7 @@
EXPECT_THROW_MSG(format(format_str), format_error, "invalid format string");
safe_sprintf(format_str, "{%u}", INT_MAX);
EXPECT_THROW_MSG(format(format_str), format_error,
- "argument index out of range");
+ "argument index out of range");
safe_sprintf(format_str, "{%u", INT_MAX + 1u);
EXPECT_THROW_MSG(format(format_str), format_error, "number is too big");
@@ -789,28 +765,26 @@
EXPECT_THROW_MSG(format(format_str), format_error, "number is too big");
}
-template <int N>
-struct TestFormat {
+template <int N> struct TestFormat {
template <typename... Args>
- static std::string format(fmt::string_view format_str, const Args &... args) {
+ static std::string format(fmt::string_view format_str, const Args&... args) {
return TestFormat<N - 1>::format(format_str, N - 1, args...);
}
};
-template <>
-struct TestFormat<0> {
+template <> struct TestFormat<0> {
template <typename... Args>
- static std::string format(fmt::string_view format_str, const Args &... args) {
+ static std::string format(fmt::string_view format_str, const Args&... args) {
return fmt::format(format_str, args...);
}
};
TEST(FormatterTest, ManyArgs) {
EXPECT_EQ("19", TestFormat<20>::format("{19}"));
- EXPECT_THROW_MSG(TestFormat<20>::format("{20}"),
- format_error, "argument index out of range");
- EXPECT_THROW_MSG(TestFormat<21>::format("{21}"),
- format_error, "argument index out of range");
+ EXPECT_THROW_MSG(TestFormat<20>::format("{20}"), format_error,
+ "argument index out of range");
+ EXPECT_THROW_MSG(TestFormat<21>::format("{21}"), format_error,
+ "argument index out of range");
enum { max_packed_args = fmt::internal::max_packed_args };
std::string format_str = fmt::format("{{{}}}", max_packed_args + 1);
EXPECT_THROW_MSG(TestFormat<max_packed_args>::format(format_str),
@@ -824,30 +798,29 @@
EXPECT_EQ(" -42", format("{0:{width}}", -42, fmt::arg("width", 4)));
EXPECT_EQ("st", format("{0:.{precision}}", "str", fmt::arg("precision", 2)));
EXPECT_EQ("1 2", format("{} {two}", 1, fmt::arg("two", 2)));
- EXPECT_EQ("42", format("{c}",
- fmt::arg("a", 0), fmt::arg("b", 0), fmt::arg("c", 42), fmt::arg("d", 0),
- fmt::arg("e", 0), fmt::arg("f", 0), fmt::arg("g", 0), fmt::arg("h", 0),
- fmt::arg("i", 0), fmt::arg("j", 0), fmt::arg("k", 0), fmt::arg("l", 0),
- fmt::arg("m", 0), fmt::arg("n", 0), fmt::arg("o", 0), fmt::arg("p", 0)));
+ EXPECT_EQ("42", format("{c}", fmt::arg("a", 0), fmt::arg("b", 0),
+ fmt::arg("c", 42), fmt::arg("d", 0), fmt::arg("e", 0),
+ fmt::arg("f", 0), fmt::arg("g", 0), fmt::arg("h", 0),
+ fmt::arg("i", 0), fmt::arg("j", 0), fmt::arg("k", 0),
+ fmt::arg("l", 0), fmt::arg("m", 0), fmt::arg("n", 0),
+ fmt::arg("o", 0), fmt::arg("p", 0)));
}
TEST(FormatterTest, AutoArgIndex) {
EXPECT_EQ("abc", format("{}{}{}", 'a', 'b', 'c'));
- EXPECT_THROW_MSG(format("{0}{}", 'a', 'b'),
- format_error, "cannot switch from manual to automatic argument indexing");
- EXPECT_THROW_MSG(format("{}{0}", 'a', 'b'),
- format_error, "cannot switch from automatic to manual argument indexing");
+ EXPECT_THROW_MSG(format("{0}{}", 'a', 'b'), format_error,
+ "cannot switch from manual to automatic argument indexing");
+ EXPECT_THROW_MSG(format("{}{0}", 'a', 'b'), format_error,
+ "cannot switch from automatic to manual argument indexing");
EXPECT_EQ("1.2", format("{:.{}}", 1.2345, 2));
- EXPECT_THROW_MSG(format("{0}:.{}", 1.2345, 2),
- format_error, "cannot switch from manual to automatic argument indexing");
- EXPECT_THROW_MSG(format("{:.{0}}", 1.2345, 2),
- format_error, "cannot switch from automatic to manual argument indexing");
+ EXPECT_THROW_MSG(format("{0}:.{}", 1.2345, 2), format_error,
+ "cannot switch from manual to automatic argument indexing");
+ EXPECT_THROW_MSG(format("{:.{0}}", 1.2345, 2), format_error,
+ "cannot switch from automatic to manual argument indexing");
EXPECT_THROW_MSG(format("{}"), format_error, "argument index out of range");
}
-TEST(FormatterTest, EmptySpecs) {
- EXPECT_EQ("42", format("{0:}", 42));
-}
+TEST(FormatterTest, EmptySpecs) { EXPECT_EQ("42", format("{0:}", 42)); }
TEST(FormatterTest, LeftAlign) {
EXPECT_EQ("42 ", format("{0:<4}", 42));
@@ -859,8 +832,8 @@
EXPECT_EQ("42 ", format("{0:<5}", 42ul));
EXPECT_EQ("-42 ", format("{0:<5}", -42ll));
EXPECT_EQ("42 ", format("{0:<5}", 42ull));
- EXPECT_EQ("-42 ", format("{0:<5}", -42.0));
- EXPECT_EQ("-42 ", format("{0:<5}", -42.0l));
+ EXPECT_EQ("-42.0 ", format("{0:<7}", -42.0));
+ EXPECT_EQ("-42.0 ", format("{0:<7}", -42.0l));
EXPECT_EQ("c ", format("{0:<5}", 'c'));
EXPECT_EQ("abc ", format("{0:<5}", "abc"));
EXPECT_EQ("0xface ", format("{0:<8}", reinterpret_cast<void*>(0xface)));
@@ -876,8 +849,8 @@
EXPECT_EQ(" 42", format("{0:>5}", 42ul));
EXPECT_EQ(" -42", format("{0:>5}", -42ll));
EXPECT_EQ(" 42", format("{0:>5}", 42ull));
- EXPECT_EQ(" -42", format("{0:>5}", -42.0));
- EXPECT_EQ(" -42", format("{0:>5}", -42.0l));
+ EXPECT_EQ(" -42.0", format("{0:>7}", -42.0));
+ EXPECT_EQ(" -42.0", format("{0:>7}", -42.0l));
EXPECT_EQ(" c", format("{0:>5}", 'c'));
EXPECT_EQ(" abc", format("{0:>5}", "abc"));
EXPECT_EQ(" 0xface", format("{0:>8}", reinterpret_cast<void*>(0xface)));
@@ -896,17 +869,17 @@
EXPECT_EQ(" 42", format("{0:=5}", 42ul));
EXPECT_EQ("- 42", format("{0:=5}", -42ll));
EXPECT_EQ(" 42", format("{0:=5}", 42ull));
- EXPECT_EQ("- 42", format("{0:=5}", -42.0));
- EXPECT_EQ("- 42", format("{0:=5}", -42.0l));
- EXPECT_THROW_MSG(format("{0:=5", 'c'),
- format_error, "missing '}' in format string");
- EXPECT_THROW_MSG(format("{0:=5}", 'c'),
- format_error, "invalid format specifier for char");
- EXPECT_THROW_MSG(format("{0:=5}", "abc"),
- format_error, "format specifier requires numeric argument");
+ EXPECT_EQ("- 42.0", format("{0:=7}", -42.0));
+ EXPECT_EQ("- 42.0", format("{0:=7}", -42.0l));
+ EXPECT_THROW_MSG(format("{0:=5", 'c'), format_error,
+ "missing '}' in format string");
+ EXPECT_THROW_MSG(format("{0:=5}", 'c'), format_error,
+ "invalid format specifier for char");
+ EXPECT_THROW_MSG(format("{0:=5}", "abc"), format_error,
+ "format specifier requires numeric argument");
EXPECT_THROW_MSG(format("{0:=8}", reinterpret_cast<void*>(0xface)),
- format_error, "format specifier requires numeric argument");
- EXPECT_EQ(" 1", fmt::format("{:= }", 1.0));
+ format_error, "format specifier requires numeric argument");
+ EXPECT_EQ(" 1.0", fmt::format("{:= }", 1.0));
}
TEST(FormatterTest, CenterAlign) {
@@ -919,18 +892,18 @@
EXPECT_EQ(" 42 ", format("{0:^5}", 42ul));
EXPECT_EQ(" -42 ", format("{0:^5}", -42ll));
EXPECT_EQ(" 42 ", format("{0:^5}", 42ull));
- EXPECT_EQ(" -42 ", format("{0:^6}", -42.0));
- EXPECT_EQ(" -42 ", format("{0:^5}", -42.0l));
+ EXPECT_EQ(" -42.0 ", format("{0:^7}", -42.0));
+ EXPECT_EQ(" -42.0 ", format("{0:^7}", -42.0l));
EXPECT_EQ(" c ", format("{0:^5}", 'c'));
EXPECT_EQ(" abc ", format("{0:^6}", "abc"));
EXPECT_EQ(" 0xface ", format("{0:^8}", reinterpret_cast<void*>(0xface)));
}
TEST(FormatterTest, Fill) {
- EXPECT_THROW_MSG(format("{0:{<5}", 'c'),
- format_error, "invalid fill character '{'");
- EXPECT_THROW_MSG(format("{0:{<5}}", 'c'),
- format_error, "invalid fill character '{'");
+ EXPECT_THROW_MSG(format("{0:{<5}", 'c'), format_error,
+ "invalid fill character '{'");
+ EXPECT_THROW_MSG(format("{0:{<5}}", 'c'), format_error,
+ "invalid fill character '{'");
EXPECT_EQ("**42", format("{0:*>4}", 42));
EXPECT_EQ("**-42", format("{0:*>5}", -42));
EXPECT_EQ("***42", format("{0:*>5}", 42u));
@@ -938,8 +911,8 @@
EXPECT_EQ("***42", format("{0:*>5}", 42ul));
EXPECT_EQ("**-42", format("{0:*>5}", -42ll));
EXPECT_EQ("***42", format("{0:*>5}", 42ull));
- EXPECT_EQ("**-42", format("{0:*>5}", -42.0));
- EXPECT_EQ("**-42", format("{0:*>5}", -42.0l));
+ EXPECT_EQ("**-42.0", format("{0:*>7}", -42.0));
+ EXPECT_EQ("**-42.0", format("{0:*>7}", -42.0l));
EXPECT_EQ("c****", format("{0:*<5}", 'c'));
EXPECT_EQ("abc**", format("{0:*<5}", "abc"));
EXPECT_EQ("**0xface", format("{0:*>8}", reinterpret_cast<void*>(0xface)));
@@ -951,72 +924,72 @@
EXPECT_EQ("+42", format("{0:+}", 42));
EXPECT_EQ("-42", format("{0:+}", -42));
EXPECT_EQ("+42", format("{0:+}", 42));
- EXPECT_THROW_MSG(format("{0:+}", 42u),
- format_error, "format specifier requires signed argument");
+ EXPECT_THROW_MSG(format("{0:+}", 42u), format_error,
+ "format specifier requires signed argument");
EXPECT_EQ("+42", format("{0:+}", 42l));
- EXPECT_THROW_MSG(format("{0:+}", 42ul),
- format_error, "format specifier requires signed argument");
+ EXPECT_THROW_MSG(format("{0:+}", 42ul), format_error,
+ "format specifier requires signed argument");
EXPECT_EQ("+42", format("{0:+}", 42ll));
- EXPECT_THROW_MSG(format("{0:+}", 42ull),
- format_error, "format specifier requires signed argument");
- EXPECT_EQ("+42", format("{0:+}", 42.0));
- EXPECT_EQ("+42", format("{0:+}", 42.0l));
- EXPECT_THROW_MSG(format("{0:+", 'c'),
- format_error, "missing '}' in format string");
- EXPECT_THROW_MSG(format("{0:+}", 'c'),
- format_error, "invalid format specifier for char");
- EXPECT_THROW_MSG(format("{0:+}", "abc"),
- format_error, "format specifier requires numeric argument");
- EXPECT_THROW_MSG(format("{0:+}", reinterpret_cast<void*>(0x42)),
- format_error, "format specifier requires numeric argument");
+ EXPECT_THROW_MSG(format("{0:+}", 42ull), format_error,
+ "format specifier requires signed argument");
+ EXPECT_EQ("+42.0", format("{0:+}", 42.0));
+ EXPECT_EQ("+42.0", format("{0:+}", 42.0l));
+ EXPECT_THROW_MSG(format("{0:+", 'c'), format_error,
+ "missing '}' in format string");
+ EXPECT_THROW_MSG(format("{0:+}", 'c'), format_error,
+ "invalid format specifier for char");
+ EXPECT_THROW_MSG(format("{0:+}", "abc"), format_error,
+ "format specifier requires numeric argument");
+ EXPECT_THROW_MSG(format("{0:+}", reinterpret_cast<void*>(0x42)), format_error,
+ "format specifier requires numeric argument");
}
TEST(FormatterTest, MinusSign) {
EXPECT_EQ("42", format("{0:-}", 42));
EXPECT_EQ("-42", format("{0:-}", -42));
EXPECT_EQ("42", format("{0:-}", 42));
- EXPECT_THROW_MSG(format("{0:-}", 42u),
- format_error, "format specifier requires signed argument");
+ EXPECT_THROW_MSG(format("{0:-}", 42u), format_error,
+ "format specifier requires signed argument");
EXPECT_EQ("42", format("{0:-}", 42l));
- EXPECT_THROW_MSG(format("{0:-}", 42ul),
- format_error, "format specifier requires signed argument");
+ EXPECT_THROW_MSG(format("{0:-}", 42ul), format_error,
+ "format specifier requires signed argument");
EXPECT_EQ("42", format("{0:-}", 42ll));
- EXPECT_THROW_MSG(format("{0:-}", 42ull),
- format_error, "format specifier requires signed argument");
- EXPECT_EQ("42", format("{0:-}", 42.0));
- EXPECT_EQ("42", format("{0:-}", 42.0l));
- EXPECT_THROW_MSG(format("{0:-", 'c'),
- format_error, "missing '}' in format string");
- EXPECT_THROW_MSG(format("{0:-}", 'c'),
- format_error, "invalid format specifier for char");
- EXPECT_THROW_MSG(format("{0:-}", "abc"),
- format_error, "format specifier requires numeric argument");
- EXPECT_THROW_MSG(format("{0:-}", reinterpret_cast<void*>(0x42)),
- format_error, "format specifier requires numeric argument");
+ EXPECT_THROW_MSG(format("{0:-}", 42ull), format_error,
+ "format specifier requires signed argument");
+ EXPECT_EQ("42.0", format("{0:-}", 42.0));
+ EXPECT_EQ("42.0", format("{0:-}", 42.0l));
+ EXPECT_THROW_MSG(format("{0:-", 'c'), format_error,
+ "missing '}' in format string");
+ EXPECT_THROW_MSG(format("{0:-}", 'c'), format_error,
+ "invalid format specifier for char");
+ EXPECT_THROW_MSG(format("{0:-}", "abc"), format_error,
+ "format specifier requires numeric argument");
+ EXPECT_THROW_MSG(format("{0:-}", reinterpret_cast<void*>(0x42)), format_error,
+ "format specifier requires numeric argument");
}
TEST(FormatterTest, SpaceSign) {
EXPECT_EQ(" 42", format("{0: }", 42));
EXPECT_EQ("-42", format("{0: }", -42));
EXPECT_EQ(" 42", format("{0: }", 42));
- EXPECT_THROW_MSG(format("{0: }", 42u),
- format_error, "format specifier requires signed argument");
+ EXPECT_THROW_MSG(format("{0: }", 42u), format_error,
+ "format specifier requires signed argument");
EXPECT_EQ(" 42", format("{0: }", 42l));
- EXPECT_THROW_MSG(format("{0: }", 42ul),
- format_error, "format specifier requires signed argument");
+ EXPECT_THROW_MSG(format("{0: }", 42ul), format_error,
+ "format specifier requires signed argument");
EXPECT_EQ(" 42", format("{0: }", 42ll));
- EXPECT_THROW_MSG(format("{0: }", 42ull),
- format_error, "format specifier requires signed argument");
- EXPECT_EQ(" 42", format("{0: }", 42.0));
- EXPECT_EQ(" 42", format("{0: }", 42.0l));
- EXPECT_THROW_MSG(format("{0: ", 'c'),
- format_error, "missing '}' in format string");
- EXPECT_THROW_MSG(format("{0: }", 'c'),
- format_error, "invalid format specifier for char");
- EXPECT_THROW_MSG(format("{0: }", "abc"),
- format_error, "format specifier requires numeric argument");
- EXPECT_THROW_MSG(format("{0: }", reinterpret_cast<void*>(0x42)),
- format_error, "format specifier requires numeric argument");
+ EXPECT_THROW_MSG(format("{0: }", 42ull), format_error,
+ "format specifier requires signed argument");
+ EXPECT_EQ(" 42.0", format("{0: }", 42.0));
+ EXPECT_EQ(" 42.0", format("{0: }", 42.0l));
+ EXPECT_THROW_MSG(format("{0: ", 'c'), format_error,
+ "missing '}' in format string");
+ EXPECT_THROW_MSG(format("{0: }", 'c'), format_error,
+ "invalid format specifier for char");
+ EXPECT_THROW_MSG(format("{0: }", "abc"), format_error,
+ "format specifier requires numeric argument");
+ EXPECT_THROW_MSG(format("{0: }", reinterpret_cast<void*>(0x42)), format_error,
+ "format specifier requires numeric argument");
}
TEST(FormatterTest, HashFlag) {
@@ -1052,19 +1025,16 @@
EXPECT_EQ("0x42", format("{0:#x}", 0x42ull));
EXPECT_EQ("042", format("{0:#o}", 042ull));
- if (FMT_USE_GRISU)
- EXPECT_EQ("-42.0", format("{0:#}", -42.0));
- else
- EXPECT_EQ("-42.0000", format("{0:#}", -42.0));
- EXPECT_EQ("-42.0000", format("{0:#}", -42.0l));
- EXPECT_THROW_MSG(format("{0:#", 'c'),
- format_error, "missing '}' in format string");
- EXPECT_THROW_MSG(format("{0:#}", 'c'),
- format_error, "invalid format specifier for char");
- EXPECT_THROW_MSG(format("{0:#}", "abc"),
- format_error, "format specifier requires numeric argument");
- EXPECT_THROW_MSG(format("{0:#}", reinterpret_cast<void*>(0x42)),
- format_error, "format specifier requires numeric argument");
+ EXPECT_EQ("-42.0", format("{0:#}", -42.0));
+ EXPECT_EQ("-42.0", format("{0:#}", -42.0l));
+ EXPECT_THROW_MSG(format("{0:#", 'c'), format_error,
+ "missing '}' in format string");
+ EXPECT_THROW_MSG(format("{0:#}", 'c'), format_error,
+ "invalid format specifier for char");
+ EXPECT_THROW_MSG(format("{0:#}", "abc"), format_error,
+ "format specifier requires numeric argument");
+ EXPECT_THROW_MSG(format("{0:#}", reinterpret_cast<void*>(0x42)), format_error,
+ "format specifier requires numeric argument");
}
TEST(FormatterTest, ZeroFlag) {
@@ -1075,16 +1045,16 @@
EXPECT_EQ("00042", format("{0:05}", 42ul));
EXPECT_EQ("-0042", format("{0:05}", -42ll));
EXPECT_EQ("00042", format("{0:05}", 42ull));
- EXPECT_EQ("-0042", format("{0:05}", -42.0));
- EXPECT_EQ("-0042", format("{0:05}", -42.0l));
- EXPECT_THROW_MSG(format("{0:0", 'c'),
- format_error, "missing '}' in format string");
- EXPECT_THROW_MSG(format("{0:05}", 'c'),
- format_error, "invalid format specifier for char");
- EXPECT_THROW_MSG(format("{0:05}", "abc"),
- format_error, "format specifier requires numeric argument");
+ EXPECT_EQ("-0042.0", format("{0:07}", -42.0));
+ EXPECT_EQ("-0042.0", format("{0:07}", -42.0l));
+ EXPECT_THROW_MSG(format("{0:0", 'c'), format_error,
+ "missing '}' in format string");
+ EXPECT_THROW_MSG(format("{0:05}", 'c'), format_error,
+ "invalid format specifier for char");
+ EXPECT_THROW_MSG(format("{0:05}", "abc"), format_error,
+ "format specifier requires numeric argument");
EXPECT_THROW_MSG(format("{0:05}", reinterpret_cast<void*>(0x42)),
- format_error, "format specifier requires numeric argument");
+ format_error, "format specifier requires numeric argument");
}
TEST(FormatterTest, Width) {
@@ -1113,6 +1083,7 @@
EXPECT_EQ("x ", format("{0:11}", 'x'));
EXPECT_EQ("str ", format("{0:12}", "str"));
}
+template <typename T> inline T const_check(T value) { return value; }
TEST(FormatterTest, RuntimeWidth) {
char format_str[BUFFER_SIZE];
@@ -1127,36 +1098,32 @@
format_str[size + 2] = 0;
EXPECT_THROW_MSG(format(format_str, 0), format_error, "number is too big");
- EXPECT_THROW_MSG(format("{0:{", 0),
- format_error, "invalid format string");
- EXPECT_THROW_MSG(format("{0:{}", 0),
- format_error, "cannot switch from manual to automatic argument indexing");
- EXPECT_THROW_MSG(format("{0:{?}}", 0),
- format_error, "invalid format string");
- EXPECT_THROW_MSG(format("{0:{1}}", 0),
- format_error, "argument index out of range");
+ EXPECT_THROW_MSG(format("{0:{", 0), format_error, "invalid format string");
+ EXPECT_THROW_MSG(format("{0:{}", 0), format_error,
+ "cannot switch from manual to automatic argument indexing");
+ EXPECT_THROW_MSG(format("{0:{?}}", 0), format_error, "invalid format string");
+ EXPECT_THROW_MSG(format("{0:{1}}", 0), format_error,
+ "argument index out of range");
- EXPECT_THROW_MSG(format("{0:{0:}}", 0),
- format_error, "invalid format string");
+ EXPECT_THROW_MSG(format("{0:{0:}}", 0), format_error,
+ "invalid format string");
- EXPECT_THROW_MSG(format("{0:{1}}", 0, -1),
- format_error, "negative width");
- EXPECT_THROW_MSG(format("{0:{1}}", 0, (INT_MAX + 1u)),
- format_error, "number is too big");
- EXPECT_THROW_MSG(format("{0:{1}}", 0, -1l),
- format_error, "negative width");
- if (fmt::internal::const_check(sizeof(long) > sizeof(int))) {
+ EXPECT_THROW_MSG(format("{0:{1}}", 0, -1), format_error, "negative width");
+ EXPECT_THROW_MSG(format("{0:{1}}", 0, (INT_MAX + 1u)), format_error,
+ "number is too big");
+ EXPECT_THROW_MSG(format("{0:{1}}", 0, -1l), format_error, "negative width");
+ if (const_check(sizeof(long) > sizeof(int))) {
long value = INT_MAX;
- EXPECT_THROW_MSG(format("{0:{1}}", 0, (value + 1)),
- format_error, "number is too big");
+ EXPECT_THROW_MSG(format("{0:{1}}", 0, (value + 1)), format_error,
+ "number is too big");
}
- EXPECT_THROW_MSG(format("{0:{1}}", 0, (INT_MAX + 1ul)),
- format_error, "number is too big");
+ EXPECT_THROW_MSG(format("{0:{1}}", 0, (INT_MAX + 1ul)), format_error,
+ "number is too big");
- EXPECT_THROW_MSG(format("{0:{1}}", 0, '0'),
- format_error, "width is not integer");
- EXPECT_THROW_MSG(format("{0:{1}}", 0, 0.0),
- format_error, "width is not integer");
+ EXPECT_THROW_MSG(format("{0:{1}}", 0, '0'), format_error,
+ "width is not integer");
+ EXPECT_THROW_MSG(format("{0:{1}}", 0, 0.0), format_error,
+ "width is not integer");
EXPECT_EQ(" -42", format("{0:{1}}", -42, 4));
EXPECT_EQ(" 42", format("{0:{1}}", 42u, 5));
@@ -1187,46 +1154,50 @@
safe_sprintf(format_str, "{0:.%u}", INT_MAX + 1u);
EXPECT_THROW_MSG(format(format_str, 0), format_error, "number is too big");
- EXPECT_THROW_MSG(format("{0:.", 0),
- format_error, "missing precision specifier");
- EXPECT_THROW_MSG(format("{0:.}", 0),
- format_error, "missing precision specifier");
+ EXPECT_THROW_MSG(format("{0:.", 0), format_error,
+ "missing precision specifier");
+ EXPECT_THROW_MSG(format("{0:.}", 0), format_error,
+ "missing precision specifier");
- EXPECT_THROW_MSG(format("{0:.2", 0),
- format_error, "precision not allowed for this argument type");
- EXPECT_THROW_MSG(format("{0:.2}", 42),
- format_error, "precision not allowed for this argument type");
- EXPECT_THROW_MSG(format("{0:.2f}", 42),
- format_error, "precision not allowed for this argument type");
- EXPECT_THROW_MSG(format("{0:.2}", 42u),
- format_error, "precision not allowed for this argument type");
- EXPECT_THROW_MSG(format("{0:.2f}", 42u),
- format_error, "precision not allowed for this argument type");
- EXPECT_THROW_MSG(format("{0:.2}", 42l),
- format_error, "precision not allowed for this argument type");
- EXPECT_THROW_MSG(format("{0:.2f}", 42l),
- format_error, "precision not allowed for this argument type");
- EXPECT_THROW_MSG(format("{0:.2}", 42ul),
- format_error, "precision not allowed for this argument type");
- EXPECT_THROW_MSG(format("{0:.2f}", 42ul),
- format_error, "precision not allowed for this argument type");
- EXPECT_THROW_MSG(format("{0:.2}", 42ll),
- format_error, "precision not allowed for this argument type");
- EXPECT_THROW_MSG(format("{0:.2f}", 42ll),
- format_error, "precision not allowed for this argument type");
- EXPECT_THROW_MSG(format("{0:.2}", 42ull),
- format_error, "precision not allowed for this argument type");
- EXPECT_THROW_MSG(format("{0:.2f}", 42ull),
- format_error, "precision not allowed for this argument type");
- EXPECT_THROW_MSG(format("{0:3.0}", 'x'),
- format_error, "precision not allowed for this argument type");
+ EXPECT_THROW_MSG(format("{0:.2", 0), format_error,
+ "precision not allowed for this argument type");
+ EXPECT_THROW_MSG(format("{0:.2}", 42), format_error,
+ "precision not allowed for this argument type");
+ EXPECT_THROW_MSG(format("{0:.2f}", 42), format_error,
+ "precision not allowed for this argument type");
+ EXPECT_THROW_MSG(format("{0:.2}", 42u), format_error,
+ "precision not allowed for this argument type");
+ EXPECT_THROW_MSG(format("{0:.2f}", 42u), format_error,
+ "precision not allowed for this argument type");
+ EXPECT_THROW_MSG(format("{0:.2}", 42l), format_error,
+ "precision not allowed for this argument type");
+ EXPECT_THROW_MSG(format("{0:.2f}", 42l), format_error,
+ "precision not allowed for this argument type");
+ EXPECT_THROW_MSG(format("{0:.2}", 42ul), format_error,
+ "precision not allowed for this argument type");
+ EXPECT_THROW_MSG(format("{0:.2f}", 42ul), format_error,
+ "precision not allowed for this argument type");
+ EXPECT_THROW_MSG(format("{0:.2}", 42ll), format_error,
+ "precision not allowed for this argument type");
+ EXPECT_THROW_MSG(format("{0:.2f}", 42ll), format_error,
+ "precision not allowed for this argument type");
+ EXPECT_THROW_MSG(format("{0:.2}", 42ull), format_error,
+ "precision not allowed for this argument type");
+ EXPECT_THROW_MSG(format("{0:.2f}", 42ull), format_error,
+ "precision not allowed for this argument type");
+ EXPECT_THROW_MSG(format("{0:.2%}", 42), format_error,
+ "precision not allowed for this argument type");
+ EXPECT_THROW_MSG(format("{0:3.0}", 'x'), format_error,
+ "precision not allowed for this argument type");
EXPECT_EQ("1.2", format("{0:.2}", 1.2345));
EXPECT_EQ("1.2", format("{0:.2}", 1.2345l));
EXPECT_THROW_MSG(format("{0:.2}", reinterpret_cast<void*>(0xcafe)),
- format_error, "precision not allowed for this argument type");
+ format_error,
+ "precision not allowed for this argument type");
EXPECT_THROW_MSG(format("{0:.2f}", reinterpret_cast<void*>(0xcafe)),
- format_error, "precision not allowed for this argument type");
+ format_error,
+ "precision not allowed for this argument type");
EXPECT_EQ("st", format("{0:.2}", "str"));
}
@@ -1244,87 +1215,88 @@
format_str[size + 2] = 0;
EXPECT_THROW_MSG(format(format_str, 0), format_error, "number is too big");
- EXPECT_THROW_MSG(format("{0:.{", 0),
- format_error, "invalid format string");
- EXPECT_THROW_MSG(format("{0:.{}", 0),
- format_error, "cannot switch from manual to automatic argument indexing");
- EXPECT_THROW_MSG(format("{0:.{?}}", 0),
- format_error, "invalid format string");
- EXPECT_THROW_MSG(format("{0:.{1}", 0, 0),
- format_error, "precision not allowed for this argument type");
- EXPECT_THROW_MSG(format("{0:.{1}}", 0),
- format_error, "argument index out of range");
+ EXPECT_THROW_MSG(format("{0:.{", 0), format_error, "invalid format string");
+ EXPECT_THROW_MSG(format("{0:.{}", 0), format_error,
+ "cannot switch from manual to automatic argument indexing");
+ EXPECT_THROW_MSG(format("{0:.{?}}", 0), format_error,
+ "invalid format string");
+ EXPECT_THROW_MSG(format("{0:.{1}", 0, 0), format_error,
+ "precision not allowed for this argument type");
+ EXPECT_THROW_MSG(format("{0:.{1}}", 0), format_error,
+ "argument index out of range");
- EXPECT_THROW_MSG(format("{0:.{0:}}", 0),
- format_error, "invalid format string");
+ EXPECT_THROW_MSG(format("{0:.{0:}}", 0), format_error,
+ "invalid format string");
- EXPECT_THROW_MSG(format("{0:.{1}}", 0, -1),
- format_error, "negative precision");
- EXPECT_THROW_MSG(format("{0:.{1}}", 0, (INT_MAX + 1u)),
- format_error, "number is too big");
- EXPECT_THROW_MSG(format("{0:.{1}}", 0, -1l),
- format_error, "negative precision");
- if (fmt::internal::const_check(sizeof(long) > sizeof(int))) {
+ EXPECT_THROW_MSG(format("{0:.{1}}", 0, -1), format_error,
+ "negative precision");
+ EXPECT_THROW_MSG(format("{0:.{1}}", 0, (INT_MAX + 1u)), format_error,
+ "number is too big");
+ EXPECT_THROW_MSG(format("{0:.{1}}", 0, -1l), format_error,
+ "negative precision");
+ if (const_check(sizeof(long) > sizeof(int))) {
long value = INT_MAX;
- EXPECT_THROW_MSG(format("{0:.{1}}", 0, (value + 1)),
- format_error, "number is too big");
+ EXPECT_THROW_MSG(format("{0:.{1}}", 0, (value + 1)), format_error,
+ "number is too big");
}
- EXPECT_THROW_MSG(format("{0:.{1}}", 0, (INT_MAX + 1ul)),
- format_error, "number is too big");
+ EXPECT_THROW_MSG(format("{0:.{1}}", 0, (INT_MAX + 1ul)), format_error,
+ "number is too big");
- EXPECT_THROW_MSG(format("{0:.{1}}", 0, '0'),
- format_error, "precision is not integer");
- EXPECT_THROW_MSG(format("{0:.{1}}", 0, 0.0),
- format_error, "precision is not integer");
+ EXPECT_THROW_MSG(format("{0:.{1}}", 0, '0'), format_error,
+ "precision is not integer");
+ EXPECT_THROW_MSG(format("{0:.{1}}", 0, 0.0), format_error,
+ "precision is not integer");
- EXPECT_THROW_MSG(format("{0:.{1}}", 42, 2),
- format_error, "precision not allowed for this argument type");
- EXPECT_THROW_MSG(format("{0:.{1}f}", 42, 2),
- format_error, "precision not allowed for this argument type");
- EXPECT_THROW_MSG(format("{0:.{1}}", 42u, 2),
- format_error, "precision not allowed for this argument type");
- EXPECT_THROW_MSG(format("{0:.{1}f}", 42u, 2),
- format_error, "precision not allowed for this argument type");
- EXPECT_THROW_MSG(format("{0:.{1}}", 42l, 2),
- format_error, "precision not allowed for this argument type");
- EXPECT_THROW_MSG(format("{0:.{1}f}", 42l, 2),
- format_error, "precision not allowed for this argument type");
- EXPECT_THROW_MSG(format("{0:.{1}}", 42ul, 2),
- format_error, "precision not allowed for this argument type");
- EXPECT_THROW_MSG(format("{0:.{1}f}", 42ul, 2),
- format_error, "precision not allowed for this argument type");
- EXPECT_THROW_MSG(format("{0:.{1}}", 42ll, 2),
- format_error, "precision not allowed for this argument type");
- EXPECT_THROW_MSG(format("{0:.{1}f}", 42ll, 2),
- format_error, "precision not allowed for this argument type");
- EXPECT_THROW_MSG(format("{0:.{1}}", 42ull, 2),
- format_error, "precision not allowed for this argument type");
- EXPECT_THROW_MSG(format("{0:.{1}f}", 42ull, 2),
- format_error, "precision not allowed for this argument type");
- EXPECT_THROW_MSG(format("{0:3.{1}}", 'x', 0),
- format_error, "precision not allowed for this argument type");
+ EXPECT_THROW_MSG(format("{0:.{1}}", 42, 2), format_error,
+ "precision not allowed for this argument type");
+ EXPECT_THROW_MSG(format("{0:.{1}f}", 42, 2), format_error,
+ "precision not allowed for this argument type");
+ EXPECT_THROW_MSG(format("{0:.{1}}", 42u, 2), format_error,
+ "precision not allowed for this argument type");
+ EXPECT_THROW_MSG(format("{0:.{1}f}", 42u, 2), format_error,
+ "precision not allowed for this argument type");
+ EXPECT_THROW_MSG(format("{0:.{1}}", 42l, 2), format_error,
+ "precision not allowed for this argument type");
+ EXPECT_THROW_MSG(format("{0:.{1}f}", 42l, 2), format_error,
+ "precision not allowed for this argument type");
+ EXPECT_THROW_MSG(format("{0:.{1}}", 42ul, 2), format_error,
+ "precision not allowed for this argument type");
+ EXPECT_THROW_MSG(format("{0:.{1}f}", 42ul, 2), format_error,
+ "precision not allowed for this argument type");
+ EXPECT_THROW_MSG(format("{0:.{1}}", 42ll, 2), format_error,
+ "precision not allowed for this argument type");
+ EXPECT_THROW_MSG(format("{0:.{1}f}", 42ll, 2), format_error,
+ "precision not allowed for this argument type");
+ EXPECT_THROW_MSG(format("{0:.{1}}", 42ull, 2), format_error,
+ "precision not allowed for this argument type");
+ EXPECT_THROW_MSG(format("{0:.{1}f}", 42ull, 2), format_error,
+ "precision not allowed for this argument type");
+ EXPECT_THROW_MSG(format("{0:3.{1}}", 'x', 0), format_error,
+ "precision not allowed for this argument type");
EXPECT_EQ("1.2", format("{0:.{1}}", 1.2345, 2));
EXPECT_EQ("1.2", format("{1:.{0}}", 2, 1.2345l));
EXPECT_THROW_MSG(format("{0:.{1}}", reinterpret_cast<void*>(0xcafe), 2),
- format_error, "precision not allowed for this argument type");
+ format_error,
+ "precision not allowed for this argument type");
EXPECT_THROW_MSG(format("{0:.{1}f}", reinterpret_cast<void*>(0xcafe), 2),
- format_error, "precision not allowed for this argument type");
+ format_error,
+ "precision not allowed for this argument type");
EXPECT_EQ("st", format("{0:.{1}}", "str", 2));
}
template <typename T>
-void check_unknown_types(const T &value, const char *types, const char *) {
+void check_unknown_types(const T& value, const char* types, const char*) {
char format_str[BUFFER_SIZE];
- const char *special = ".0123456789}";
+ const char* special = ".0123456789}";
for (int i = CHAR_MIN; i <= CHAR_MAX; ++i) {
char c = static_cast<char>(i);
if (std::strchr(types, c) || std::strchr(special, c) || !c) continue;
safe_sprintf(format_str, "{0:10%c}", c);
- const char *message = "invalid type specifier";
+ const char* message = "invalid type specifier";
EXPECT_THROW_MSG(format(format_str, value), format_error, message)
- << format_str << " " << message;
+ << format_str << " " << message;
}
}
@@ -1344,8 +1316,8 @@
}
TEST(FormatterTest, FormatInt) {
- EXPECT_THROW_MSG(format("{0:v", 42),
- format_error, "missing '}' in format string");
+ EXPECT_THROW_MSG(format("{0:v", 42), format_error,
+ "missing '}' in format string");
check_unknown_types(42, "bBdoxXn", "integer");
}
@@ -1448,11 +1420,12 @@
TEST(FormatterTest, FormatFloat) {
EXPECT_EQ("392.500000", format("{0:f}", 392.5f));
+ EXPECT_EQ("12.500000%", format("{0:%}", 0.125f));
}
TEST(FormatterTest, FormatDouble) {
- check_unknown_types(1.2, "eEfFgGaA", "double");
- EXPECT_EQ("0", format("{:}", 0.0));
+ check_unknown_types(1.2, "eEfFgGaAn%", "double");
+ EXPECT_EQ("0.0", format("{:}", 0.0));
EXPECT_EQ("0.000000", format("{:f}", 0.0));
EXPECT_EQ("0", format("{:g}", 0.0));
EXPECT_EQ("392.65", format("{:}", 392.65));
@@ -1460,6 +1433,8 @@
EXPECT_EQ("392.65", format("{:G}", 392.65));
EXPECT_EQ("392.650000", format("{:f}", 392.65));
EXPECT_EQ("392.650000", format("{:F}", 392.65));
+ EXPECT_EQ("12.500000%", format("{:%}", 0.125));
+ EXPECT_EQ("12.34%", format("{:.2%}", 0.1234432));
char buffer[BUFFER_SIZE];
safe_sprintf(buffer, "%e", 392.65);
EXPECT_EQ(buffer, format("{0:e}", 392.65));
@@ -1472,10 +1447,22 @@
EXPECT_EQ(buffer, format("{:A}", -42.0));
}
-TEST(FormatterTest, FormatDoubleBigPrecision) {
- // sprintf with big precision is broken in MSVC2013, so only test on Grisu.
- if (FMT_USE_GRISU)
- EXPECT_EQ(format("0.{:0<1000}", ""), format("{:.1000f}", 0.0));
+TEST(FormatterTest, PrecisionRounding) {
+ EXPECT_EQ("0", format("{:.0f}", 0.0));
+ EXPECT_EQ("0", format("{:.0f}", 0.01));
+ EXPECT_EQ("0", format("{:.0f}", 0.1));
+ EXPECT_EQ("0.000", format("{:.3f}", 0.00049));
+ EXPECT_EQ("0.001", format("{:.3f}", 0.0005));
+ EXPECT_EQ("0.001", format("{:.3f}", 0.00149));
+ EXPECT_EQ("0.002", format("{:.3f}", 0.0015));
+ EXPECT_EQ("1.000", format("{:.3f}", 0.9999));
+ EXPECT_EQ("0.00123", format("{:.3}", 0.00123));
+ EXPECT_EQ("0.1", format("{:.16g}", 0.1));
+ // Trigger rounding error in Grisu by a carefully chosen number.
+ auto n = 3788512123356.985352;
+ char buffer[64];
+ safe_sprintf(buffer, "%f", n);
+ EXPECT_EQ(buffer, format("{:f}", n));
}
TEST(FormatterTest, FormatNaN) {
@@ -1487,6 +1474,7 @@
EXPECT_EQ("nan ", format("{:<7}", nan));
EXPECT_EQ(" nan ", format("{:^7}", nan));
EXPECT_EQ(" nan", format("{:>7}", nan));
+ EXPECT_EQ("nan%", format("{:%}", nan));
}
TEST(FormatterTest, FormatInfinity) {
@@ -1499,20 +1487,25 @@
EXPECT_EQ("inf ", format("{:<7}", inf));
EXPECT_EQ(" inf ", format("{:^7}", inf));
EXPECT_EQ(" inf", format("{:>7}", inf));
+ EXPECT_EQ("inf%", format("{:%}", inf));
}
TEST(FormatterTest, FormatLongDouble) {
- EXPECT_EQ("0", format("{0:}", 0.0l));
+ EXPECT_EQ("0.0", format("{0:}", 0.0l));
EXPECT_EQ("0.000000", format("{0:f}", 0.0l));
EXPECT_EQ("392.65", format("{0:}", 392.65l));
EXPECT_EQ("392.65", format("{0:g}", 392.65l));
EXPECT_EQ("392.65", format("{0:G}", 392.65l));
EXPECT_EQ("392.650000", format("{0:f}", 392.65l));
EXPECT_EQ("392.650000", format("{0:F}", 392.65l));
+ EXPECT_EQ("12.500000%", format("{:%}", 0.125l));
+ EXPECT_EQ("12.34%", format("{:.2%}", 0.1234432l));
char buffer[BUFFER_SIZE];
safe_sprintf(buffer, "%Le", 392.65l);
EXPECT_EQ(buffer, format("{0:e}", 392.65l));
EXPECT_EQ("+0000392.6", format("{0:+010.4g}", 392.64l));
+ safe_sprintf(buffer, "%La", 3.31l);
+ EXPECT_EQ(buffer, format("{:a}", 3.31l));
}
TEST(FormatterTest, FormatChar) {
@@ -1522,13 +1515,18 @@
EXPECT_EQ("z", format("{0:c}", 'z'));
EXPECT_EQ(L"a", format(L"{0}", 'a'));
int n = 'x';
- for (const char *type = types + 1; *type; ++type) {
+ for (const char* type = types + 1; *type; ++type) {
std::string format_str = fmt::format("{{:{}}}", *type);
EXPECT_EQ(fmt::format(format_str, n), fmt::format(format_str, 'x'));
}
EXPECT_EQ(fmt::format("{:02X}", n), fmt::format("{:02X}", 'x'));
}
+TEST(FormatterTest, FormatVolatileChar) {
+ volatile char c = 'x';
+ EXPECT_EQ("x", format("{}", c));
+}
+
TEST(FormatterTest, FormatUnsignedChar) {
EXPECT_EQ("42", format("{}", static_cast<unsigned char>(42)));
EXPECT_EQ("42", format("{}", static_cast<uint8_t>(42)));
@@ -1537,7 +1535,7 @@
TEST(FormatterTest, FormatWChar) {
EXPECT_EQ(L"a", format(L"{0}", L'a'));
// This shouldn't compile:
- //format("{}", L'a');
+ // format("{}", L'a');
}
TEST(FormatterTest, FormatCString) {
@@ -1546,37 +1544,39 @@
EXPECT_EQ("test", format("{0:s}", "test"));
char nonconst[] = "nonconst";
EXPECT_EQ("nonconst", format("{0}", nonconst));
- EXPECT_THROW_MSG(format("{0}", static_cast<const char*>(FMT_NULL)),
- format_error, "string pointer is null");
+ EXPECT_THROW_MSG(format("{0}", static_cast<const char*>(nullptr)),
+ format_error, "string pointer is null");
}
TEST(FormatterTest, FormatSCharString) {
signed char str[] = "test";
EXPECT_EQ("test", format("{0:s}", str));
- const signed char *const_str = str;
+ const signed char* const_str = str;
EXPECT_EQ("test", format("{0:s}", const_str));
}
TEST(FormatterTest, FormatUCharString) {
unsigned char str[] = "test";
EXPECT_EQ("test", format("{0:s}", str));
- const unsigned char *const_str = str;
+ const unsigned char* const_str = str;
EXPECT_EQ("test", format("{0:s}", const_str));
- unsigned char *ptr = str;
+ unsigned char* ptr = str;
EXPECT_EQ("test", format("{0:s}", ptr));
}
TEST(FormatterTest, FormatPointer) {
check_unknown_types(reinterpret_cast<void*>(0x1234), "p", "pointer");
- EXPECT_EQ("0x0", format("{0}", static_cast<void*>(FMT_NULL)));
+ EXPECT_EQ("0x0", format("{0}", static_cast<void*>(nullptr)));
EXPECT_EQ("0x1234", format("{0}", reinterpret_cast<void*>(0x1234)));
EXPECT_EQ("0x1234", format("{0:p}", reinterpret_cast<void*>(0x1234)));
EXPECT_EQ("0x" + std::string(sizeof(void*) * CHAR_BIT / 4, 'f'),
- format("{0}", reinterpret_cast<void*>(~uintptr_t())));
+ format("{0}", reinterpret_cast<void*>(~uintptr_t())));
EXPECT_EQ("0x1234", format("{}", fmt::ptr(reinterpret_cast<int*>(0x1234))));
-#if FMT_USE_NULLPTR
- EXPECT_EQ("0x0", format("{}", FMT_NULL));
-#endif
+ std::unique_ptr<int> up(new int(1));
+ EXPECT_EQ(format("{}", fmt::ptr(up.get())), format("{}", fmt::ptr(up)));
+ std::shared_ptr<int> sp(new int(1));
+ EXPECT_EQ(format("{}", fmt::ptr(sp.get())), format("{}", fmt::ptr(sp)));
+ EXPECT_EQ("0x0", format("{}", nullptr));
}
TEST(FormatterTest, FormatString) {
@@ -1588,24 +1588,33 @@
EXPECT_EQ("", format("{}", string_view()));
}
-#ifdef FMT_USE_STD_STRING_VIEW
+#ifdef FMT_USE_STRING_VIEW
+struct string_viewable {};
+
+FMT_BEGIN_NAMESPACE
+template <> struct formatter<string_viewable> : formatter<std::string_view> {
+ auto format(string_viewable, format_context& ctx) -> decltype(ctx.out()) {
+ return formatter<std::string_view>::format("foo", ctx);
+ }
+};
+FMT_END_NAMESPACE
+
TEST(FormatterTest, FormatStdStringView) {
- EXPECT_EQ("test", format("{0}", std::string_view("test")));
+ EXPECT_EQ("test", format("{}", std::string_view("test")));
+ EXPECT_EQ("foo", format("{}", string_viewable()));
}
#endif
FMT_BEGIN_NAMESPACE
-template <>
-struct formatter<Date> {
+template <> struct formatter<Date> {
template <typename ParseContext>
- FMT_CONSTEXPR auto parse(ParseContext &ctx) -> decltype(ctx.begin()) {
+ FMT_CONSTEXPR auto parse(ParseContext& ctx) -> decltype(ctx.begin()) {
auto it = ctx.begin();
- if (*it == 'd')
- ++it;
+ if (*it == 'd') ++it;
return it;
}
- auto format(const Date &d, format_context &ctx) -> decltype(ctx.out()) {
+ auto format(const Date& d, format_context& ctx) -> decltype(ctx.out()) {
format_to(ctx.out(), "{}-{}-{}", d.year(), d.month(), d.day());
return ctx.out();
}
@@ -1621,10 +1630,9 @@
class Answer {};
FMT_BEGIN_NAMESPACE
-template <>
-struct formatter<Answer> : formatter<int> {
+template <> struct formatter<Answer> : formatter<int> {
template <typename FormatContext>
- auto format(Answer, FormatContext &ctx) -> decltype(ctx.out()) {
+ auto format(Answer, FormatContext& ctx) -> decltype(ctx.out()) {
return formatter<int>::format(42, ctx);
}
};
@@ -1637,8 +1645,8 @@
TEST(FormatterTest, CustomFormatTo) {
char buf[10] = {};
- auto end = &*fmt::format_to(
- fmt::internal::make_checked(buf, 10), "{}", Answer());
+ auto end =
+ &*fmt::format_to(fmt::internal::make_checked(buf, 10), "{}", Answer());
EXPECT_EQ(end, buf + 2);
EXPECT_STREQ(buf, "42");
}
@@ -1652,8 +1660,8 @@
TEST(FormatterTest, FormatStringFromSpeedTest) {
EXPECT_EQ("1.2340000000:0042:+3.13:str:0x3e8:X:%",
- format("{0:0.10f}:{1:04}:{2:+g}:{3}:{4}:{5}:%",
- 1.234, 42, 3.13, "str", reinterpret_cast<void*>(1000), 'X'));
+ format("{0:0.10f}:{1:04}:{2:+g}:{3}:{4}:{5}:%", 1.234, 42, 3.13,
+ "str", reinterpret_cast<void*>(1000), 'X'));
}
TEST(FormatterTest, FormatExamples) {
@@ -1667,24 +1675,25 @@
format_to(out, "The answer is {}.", 42);
EXPECT_EQ("The answer is 42.", to_string(out));
- const char *filename = "nonexistent";
- FILE *ftest = safe_fopen(filename, "r");
+ const char* filename = "nonexistent";
+ FILE* ftest = safe_fopen(filename, "r");
if (ftest) fclose(ftest);
int error_code = errno;
- EXPECT_TRUE(ftest == FMT_NULL);
- EXPECT_SYSTEM_ERROR({
- FILE *f = safe_fopen(filename, "r");
- if (!f)
- throw fmt::system_error(errno, "Cannot open file '{}'", filename);
- fclose(f);
- }, error_code, "Cannot open file 'nonexistent'");
+ EXPECT_TRUE(ftest == nullptr);
+ EXPECT_SYSTEM_ERROR(
+ {
+ FILE* f = safe_fopen(filename, "r");
+ if (!f)
+ throw fmt::system_error(errno, "Cannot open file '{}'", filename);
+ fclose(f);
+ },
+ error_code, "Cannot open file 'nonexistent'");
}
TEST(FormatterTest, Examples) {
EXPECT_EQ("First, thou shalt count to three",
- format("First, thou shalt count to {0}", "three"));
- EXPECT_EQ("Bring me a shrubbery",
- format("Bring me a {}", "shrubbery"));
+ format("First, thou shalt count to {0}", "three"));
+ EXPECT_EQ("Bring me a shrubbery", format("Bring me a {}", "shrubbery"));
EXPECT_EQ("From 1 to 3", format("From {} to {}", 1, 3));
char buffer[BUFFER_SIZE];
@@ -1696,37 +1705,29 @@
EXPECT_EQ("c, b, a", format("{2}, {1}, {0}", 'a', 'b', 'c'));
EXPECT_EQ("abracadabra", format("{0}{1}{0}", "abra", "cad"));
- EXPECT_EQ("left aligned ",
- format("{:<30}", "left aligned"));
+ EXPECT_EQ("left aligned ", format("{:<30}", "left aligned"));
EXPECT_EQ(" right aligned",
- format("{:>30}", "right aligned"));
- EXPECT_EQ(" centered ",
- format("{:^30}", "centered"));
- EXPECT_EQ("***********centered***********",
- format("{:*^30}", "centered"));
+ format("{:>30}", "right aligned"));
+ EXPECT_EQ(" centered ", format("{:^30}", "centered"));
+ EXPECT_EQ("***********centered***********", format("{:*^30}", "centered"));
- EXPECT_EQ("+3.140000; -3.140000",
- format("{:+f}; {:+f}", 3.14, -3.14));
- EXPECT_EQ(" 3.140000; -3.140000",
- format("{: f}; {: f}", 3.14, -3.14));
- EXPECT_EQ("3.140000; -3.140000",
- format("{:-f}; {:-f}", 3.14, -3.14));
+ EXPECT_EQ("+3.140000; -3.140000", format("{:+f}; {:+f}", 3.14, -3.14));
+ EXPECT_EQ(" 3.140000; -3.140000", format("{: f}; {: f}", 3.14, -3.14));
+ EXPECT_EQ("3.140000; -3.140000", format("{:-f}; {:-f}", 3.14, -3.14));
EXPECT_EQ("int: 42; hex: 2a; oct: 52",
- format("int: {0:d}; hex: {0:x}; oct: {0:o}", 42));
+ format("int: {0:d}; hex: {0:x}; oct: {0:o}", 42));
EXPECT_EQ("int: 42; hex: 0x2a; oct: 052",
- format("int: {0:d}; hex: {0:#x}; oct: {0:#o}", 42));
+ format("int: {0:d}; hex: {0:#x}; oct: {0:#o}", 42));
EXPECT_EQ("The answer is 42", format("The answer is {}", 42));
- EXPECT_THROW_MSG(
- format("The answer is {:d}", "forty-two"), format_error,
- "invalid type specifier");
+ EXPECT_THROW_MSG(format("The answer is {:d}", "forty-two"), format_error,
+ "invalid type specifier");
- EXPECT_EQ(L"Cyrillic letter \x42e",
- format(L"Cyrillic letter {}", L'\x42e'));
+ EXPECT_EQ(L"Cyrillic letter \x42e", format(L"Cyrillic letter {}", L'\x42e'));
- EXPECT_WRITE(stdout,
- fmt::print("{}", std::numeric_limits<double>::infinity()), "inf");
+ EXPECT_WRITE(
+ stdout, fmt::print("{}", std::numeric_limits<double>::infinity()), "inf");
}
TEST(FormatIntTest, Data) {
@@ -1749,36 +1750,11 @@
fmt::format_int(std::numeric_limits<int64_t>::max()).str());
}
-template <typename T>
-std::string format_decimal(T value) {
- char buffer[10];
- char *ptr = buffer;
- fmt::format_decimal(ptr, value);
- return std::string(buffer, ptr);
-}
-
-TEST(FormatIntTest, FormatDec) {
- EXPECT_EQ("-42", format_decimal(static_cast<signed char>(-42)));
- EXPECT_EQ("-42", format_decimal(static_cast<short>(-42)));
- std::ostringstream os;
- os << std::numeric_limits<unsigned short>::max();
- EXPECT_EQ(os.str(),
- format_decimal(std::numeric_limits<unsigned short>::max()));
- EXPECT_EQ("1", format_decimal(1));
- EXPECT_EQ("-1", format_decimal(-1));
- EXPECT_EQ("42", format_decimal(42));
- EXPECT_EQ("-42", format_decimal(-42));
- EXPECT_EQ("42", format_decimal(42l));
- EXPECT_EQ("42", format_decimal(42ul));
- EXPECT_EQ("42", format_decimal(42ll));
- EXPECT_EQ("42", format_decimal(42ull));
-}
-
TEST(FormatTest, Print) {
#if FMT_USE_FILE_DESCRIPTORS
EXPECT_WRITE(stdout, fmt::print("Don't {}!", "panic"), "Don't panic!");
- EXPECT_WRITE(stderr,
- fmt::print(stderr, "Don't {}!", "panic"), "Don't panic!");
+ EXPECT_WRITE(stderr, fmt::print(stderr, "Don't {}!", "panic"),
+ "Don't panic!");
#endif
}
@@ -1792,23 +1768,22 @@
std::vector<fmt::basic_format_arg<ctx>> args;
args.emplace_back(fmt::internal::make_arg<ctx>(42));
args.emplace_back(fmt::internal::make_arg<ctx>("abc1"));
- args.emplace_back(fmt::internal::make_arg<ctx>(1.2f));
+ args.emplace_back(fmt::internal::make_arg<ctx>(1.5f));
- std::string result = fmt::vformat("{} and {} and {}",
- fmt::basic_format_args<ctx>(
- args.data(),
- static_cast<unsigned>(args.size())));
+ std::string result = fmt::vformat(
+ "{} and {} and {}", fmt::basic_format_args<ctx>(
+ args.data(), static_cast<unsigned>(args.size())));
- EXPECT_EQ("42 and abc1 and 1.2", result);
+ EXPECT_EQ("42 and abc1 and 1.5", result);
}
TEST(FormatTest, JoinArg) {
using fmt::join;
- int v1[3] = { 1, 2, 3 };
+ int v1[3] = {1, 2, 3};
std::vector<float> v2;
v2.push_back(1.2f);
v2.push_back(3.4f);
- void *v3[2] = { &v1[0], &v1[1] };
+ void* v3[2] = {&v1[0], &v1[1]};
EXPECT_EQ("(1, 2, 3)", format("({})", join(v1, v1 + 3, ", ")));
EXPECT_EQ("(1)", format("({})", join(v1, v1 + 1, ", ")));
@@ -1823,14 +1798,13 @@
EXPECT_EQ(format("{}, {}", v3[0], v3[1]),
format("{}", join(v3, v3 + 2, ", ")));
-#if FMT_USE_TRAILING_RETURN && (!FMT_GCC_VERSION || FMT_GCC_VERSION >= 405)
+#if !FMT_GCC_VERSION || FMT_GCC_VERSION >= 405
EXPECT_EQ("(1, 2, 3)", format("({})", join(v1, ", ")));
EXPECT_EQ("(+01.20, +03.40)", format("({:+06.2f})", join(v2, ", ")));
#endif
}
-template <typename T>
-std::string str(const T &value) {
+template <typename T> std::string str(const T& value) {
return fmt::format("{}", value);
}
@@ -1840,7 +1814,7 @@
EXPECT_EQ("2012-12-9", s);
}
-std::string vformat_message(int id, const char *format, fmt::format_args args) {
+std::string vformat_message(int id, const char* format, fmt::format_args args) {
fmt::memory_buffer buffer;
format_to(buffer, "[{}] ", id);
vformat_to(buffer, format, args);
@@ -1848,28 +1822,44 @@
}
template <typename... Args>
-std::string format_message(int id, const char *format, const Args & ... args) {
+std::string format_message(int id, const char* format, const Args&... args) {
auto va = fmt::make_format_args(args...);
return vformat_message(id, format, va);
}
TEST(FormatTest, FormatMessageExample) {
EXPECT_EQ("[42] something happened",
- format_message(42, "{} happened", "something"));
+ format_message(42, "{} happened", "something"));
}
-template<typename... Args>
-void print_error(const char *file, int line, const char *format,
- const Args & ... args) {
+template <typename... Args>
+void print_error(const char* file, int line, const char* format,
+ const Args&... args) {
fmt::print("{}: {}: ", file, line);
fmt::print(format, args...);
}
TEST(FormatTest, UnpackedArgs) {
EXPECT_EQ("0123456789abcdefg",
- fmt::format("{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}",
- 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 'a', 'b', 'c', 'd', 'e',
- 'f', 'g'));
+ fmt::format("{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}", 0, 1, 2, 3, 4, 5,
+ 6, 7, 8, 9, 'a', 'b', 'c', 'd', 'e', 'f', 'g'));
+}
+
+struct string_like {};
+fmt::string_view to_string_view(string_like) { return "foo"; }
+
+TEST(FormatTest, CompileTimeString) {
+ EXPECT_EQ("42", fmt::format(FMT_STRING("{}"), 42));
+ EXPECT_EQ(L"42", fmt::format(FMT_STRING(L"{}"), 42));
+ EXPECT_EQ("foo", fmt::format(FMT_STRING("{}"), string_like()));
+}
+
+TEST(FormatTest, CustomFormatCompileTimeString) {
+ EXPECT_EQ("42", fmt::format(FMT_STRING("{}"), Answer()));
+ Answer answer;
+ EXPECT_EQ("42", fmt::format(FMT_STRING("{}"), answer));
+ const Answer const_answer;
+ EXPECT_EQ("42", fmt::format(FMT_STRING("{}"), const_answer));
}
#if FMT_USE_USER_DEFINED_LITERALS
@@ -1887,75 +1877,67 @@
}
TEST(LiteralsTest, NamedArg) {
- auto udl_a = format("{first}{second}{first}{third}",
- "first"_a="abra", "second"_a="cad", "third"_a=99);
- EXPECT_EQ(format("{first}{second}{first}{third}",
- fmt::arg("first", "abra"), fmt::arg("second", "cad"),
- fmt::arg("third", 99)),
+ auto udl_a = format("{first}{second}{first}{third}", "first"_a = "abra",
+ "second"_a = "cad", "third"_a = 99);
+ EXPECT_EQ(format("{first}{second}{first}{third}", fmt::arg("first", "abra"),
+ fmt::arg("second", "cad"), fmt::arg("third", 99)),
udl_a);
- auto udl_a_w = format(L"{first}{second}{first}{third}",
- L"first"_a=L"abra", L"second"_a=L"cad", L"third"_a=99);
- EXPECT_EQ(format(L"{first}{second}{first}{third}",
- fmt::arg(L"first", L"abra"), fmt::arg(L"second", L"cad"),
- fmt::arg(L"third", 99)),
- udl_a_w);
+ auto udl_a_w = format(L"{first}{second}{first}{third}", L"first"_a = L"abra",
+ L"second"_a = L"cad", L"third"_a = 99);
+ EXPECT_EQ(
+ format(L"{first}{second}{first}{third}", fmt::arg(L"first", L"abra"),
+ fmt::arg(L"second", L"cad"), fmt::arg(L"third", 99)),
+ udl_a_w);
}
TEST(FormatTest, UdlTemplate) {
EXPECT_EQ("foo", "foo"_format());
EXPECT_EQ(" 42", "{0:10}"_format(42));
- EXPECT_EQ("42", fmt::format(FMT_STRING("{}"), 42));
- EXPECT_EQ(L"42", fmt::format(FMT_STRING(L"{}"), 42));
}
-#endif // FMT_USE_USER_DEFINED_LITERALS
+#endif // FMT_USE_USER_DEFINED_LITERALS
enum TestEnum { A };
-TEST(FormatTest, Enum) {
- EXPECT_EQ("0", fmt::format("{}", A));
-}
+TEST(FormatTest, Enum) { EXPECT_EQ("0", fmt::format("{}", A)); }
-TEST(FormatTest, EnumFormatterUnambiguous) {
- fmt::formatter<TestEnum> f;
- ASSERT_GE(sizeof(f), 0); // use f to avoid compiler warning
+TEST(FormatTest, FormatterNotSpecialized) {
+ EXPECT_FALSE((fmt::internal::has_formatter<fmt::formatter<TestEnum>,
+ fmt::format_context>::value));
}
#if FMT_HAS_FEATURE(cxx_strong_enums)
enum TestFixedEnum : short { B };
-TEST(FormatTest, FixedEnum) {
- EXPECT_EQ("0", fmt::format("{}", B));
-}
+TEST(FormatTest, FixedEnum) { EXPECT_EQ("0", fmt::format("{}", B)); }
#endif
-typedef fmt::back_insert_range<fmt::internal::buffer> buffer_range;
+using buffer_range = fmt::internal::buffer_range<char>;
-class mock_arg_formatter:
- public fmt::internal::function<
- fmt::internal::arg_formatter_base<buffer_range>::iterator>,
- public fmt::internal::arg_formatter_base<buffer_range> {
+class mock_arg_formatter
+ : public fmt::internal::arg_formatter_base<buffer_range> {
private:
- MOCK_METHOD1(call, void (long long value));
+ MOCK_METHOD1(call, void(long long value));
public:
typedef fmt::internal::arg_formatter_base<buffer_range> base;
typedef buffer_range range;
- mock_arg_formatter(fmt::format_context &ctx, fmt::format_specs *s = FMT_NULL)
- : base(fmt::internal::get_container(ctx.out()), s, ctx.locale()) {
+ mock_arg_formatter(fmt::format_context& ctx, fmt::format_parse_context*,
+ fmt::format_specs* s = nullptr)
+ : base(fmt::internal::get_container(ctx.out()), s, ctx.locale()) {
EXPECT_CALL(*this, call(42));
}
template <typename T>
typename std::enable_if<std::is_integral<T>::value, iterator>::type
- operator()(T value) {
+ operator()(T value) {
call(value);
return base::operator()(value);
}
template <typename T>
typename std::enable_if<!std::is_integral<T>::value, iterator>::type
- operator()(T value) {
+ operator()(T value) {
return base::operator()(value);
}
@@ -1970,31 +1952,27 @@
}
template <typename... Args>
-void custom_format(const char *format_str, const Args & ... args) {
+void custom_format(const char* format_str, const Args&... args) {
auto va = fmt::make_format_args(args...);
return custom_vformat(format_str, va);
}
-TEST(FormatTest, CustomArgFormatter) {
- custom_format("{}", 42);
-}
+TEST(FormatTest, CustomArgFormatter) { custom_format("{}", 42); }
TEST(FormatTest, NonNullTerminatedFormatString) {
EXPECT_EQ("42", format(string_view("{}foo", 2), 42));
}
struct variant {
- enum {INT, STRING} type;
+ enum { INT, STRING } type;
explicit variant(int) : type(INT) {}
- explicit variant(const char *) : type(STRING) {}
+ explicit variant(const char*) : type(STRING) {}
};
FMT_BEGIN_NAMESPACE
-template <>
-struct formatter<variant> : dynamic_formatter<> {
+template <> struct formatter<variant> : dynamic_formatter<> {
auto format(variant value, format_context& ctx) -> decltype(ctx.out()) {
- if (value.type == variant::INT)
- return dynamic_formatter<>::format(42, ctx);
+ if (value.type == variant::INT) return dynamic_formatter<>::format(42, ctx);
return dynamic_formatter<>::format("foo", ctx);
}
};
@@ -2006,24 +1984,24 @@
EXPECT_EQ("42", format("{:d}", num));
EXPECT_EQ("foo", format("{:s}", str));
EXPECT_EQ(" 42 foo ", format("{:{}} {:{}}", num, 3, str, 4));
- EXPECT_THROW_MSG(format("{0:{}}", num),
- format_error, "cannot switch from manual to automatic argument indexing");
- EXPECT_THROW_MSG(format("{:{0}}", num),
- format_error, "cannot switch from automatic to manual argument indexing");
- EXPECT_THROW_MSG(format("{:=}", str),
- format_error, "format specifier requires numeric argument");
- EXPECT_THROW_MSG(format("{:+}", str),
- format_error, "format specifier requires numeric argument");
- EXPECT_THROW_MSG(format("{:-}", str),
- format_error, "format specifier requires numeric argument");
- EXPECT_THROW_MSG(format("{: }", str),
- format_error, "format specifier requires numeric argument");
- EXPECT_THROW_MSG(format("{:#}", str),
- format_error, "format specifier requires numeric argument");
- EXPECT_THROW_MSG(format("{:0}", str),
- format_error, "format specifier requires numeric argument");
- EXPECT_THROW_MSG(format("{:.2}", num),
- format_error, "precision not allowed for this argument type");
+ EXPECT_THROW_MSG(format("{0:{}}", num), format_error,
+ "cannot switch from manual to automatic argument indexing");
+ EXPECT_THROW_MSG(format("{:{0}}", num), format_error,
+ "cannot switch from automatic to manual argument indexing");
+ EXPECT_THROW_MSG(format("{:=}", str), format_error,
+ "format specifier requires numeric argument");
+ EXPECT_THROW_MSG(format("{:+}", str), format_error,
+ "format specifier requires numeric argument");
+ EXPECT_THROW_MSG(format("{:-}", str), format_error,
+ "format specifier requires numeric argument");
+ EXPECT_THROW_MSG(format("{: }", str), format_error,
+ "format specifier requires numeric argument");
+ EXPECT_THROW_MSG(format("{:#}", str), format_error,
+ "format specifier requires numeric argument");
+ EXPECT_THROW_MSG(format("{:0}", str), format_error,
+ "format specifier requires numeric argument");
+ EXPECT_THROW_MSG(format("{:.2}", num), format_error,
+ "precision not allowed for this argument type");
}
TEST(FormatTest, ToString) {
@@ -2031,9 +2009,7 @@
EXPECT_EQ("0x1234", fmt::to_string(reinterpret_cast<void*>(0x1234)));
}
-TEST(FormatTest, ToWString) {
- EXPECT_EQ(L"42", fmt::to_wstring(42));
-}
+TEST(FormatTest, ToWString) { EXPECT_EQ(L"42", fmt::to_wstring(42)); }
TEST(FormatTest, OutputIterators) {
std::list<char> out;
@@ -2059,6 +2035,17 @@
EXPECT_EQ(6u, result.size);
EXPECT_EQ(buffer + 3, result.out);
EXPECT_EQ("foox", fmt::string_view(buffer, 4));
+ buffer[0] = 'x';
+ buffer[1] = 'x';
+ buffer[2] = 'x';
+ result = fmt::format_to_n(buffer, 3, "{}", 'A');
+ EXPECT_EQ(1u, result.size);
+ EXPECT_EQ(buffer + 1, result.out);
+ EXPECT_EQ("Axxx", fmt::string_view(buffer, 4));
+ result = fmt::format_to_n(buffer, 3, "{}{} ", 'B', 'C');
+ EXPECT_EQ(3u, result.size);
+ EXPECT_EQ(buffer + 3, result.out);
+ EXPECT_EQ("BC x", fmt::string_view(buffer, 4));
}
TEST(FormatTest, WideFormatToN) {
@@ -2068,6 +2055,17 @@
EXPECT_EQ(5u, result.size);
EXPECT_EQ(buffer + 3, result.out);
EXPECT_EQ(L"123x", fmt::wstring_view(buffer, 4));
+ buffer[0] = L'x';
+ buffer[1] = L'x';
+ buffer[2] = L'x';
+ result = fmt::format_to_n(buffer, 3, L"{}", L'A');
+ EXPECT_EQ(1u, result.size);
+ EXPECT_EQ(buffer + 1, result.out);
+ EXPECT_EQ(L"Axxx", fmt::wstring_view(buffer, 4));
+ result = fmt::format_to_n(buffer, 3, L"{}{} ", L'B', L'C');
+ EXPECT_EQ(3u, result.size);
+ EXPECT_EQ(buffer + 3, result.out);
+ EXPECT_EQ(L"BC x", fmt::wstring_view(buffer, 4));
}
#if FMT_USE_CONSTEXPR
@@ -2089,7 +2087,7 @@
name = n;
}
- FMT_CONSTEXPR void on_error(const char *) { res = ERROR; }
+ FMT_CONSTEXPR void on_error(const char*) { res = ERROR; }
};
template <size_t N>
@@ -2113,7 +2111,7 @@
enum Result { NONE, PLUS, MINUS, SPACE, HASH, ZERO, ERROR };
Result res = NONE;
- fmt::alignment align_ = fmt::ALIGN_DEFAULT;
+ fmt::align_t align = fmt::align::none;
char fill = 0;
unsigned width = 0;
fmt::internal::arg_ref<char> width_ref;
@@ -2124,13 +2122,18 @@
// Workaround for MSVC2017 bug that results in "expression did not evaluate
// to a constant" with compiler-generated copy ctor.
FMT_CONSTEXPR test_format_specs_handler() {}
- FMT_CONSTEXPR test_format_specs_handler(const test_format_specs_handler &other)
- : res(other.res), align_(other.align_), fill(other.fill),
- width(other.width), width_ref(other.width_ref),
- precision(other.precision), precision_ref(other.precision_ref),
- type(other.type) {}
+ FMT_CONSTEXPR test_format_specs_handler(
+ const test_format_specs_handler& other)
+ : res(other.res),
+ align(other.align),
+ fill(other.fill),
+ width(other.width),
+ width_ref(other.width_ref),
+ precision(other.precision),
+ precision_ref(other.precision_ref),
+ type(other.type) {}
- FMT_CONSTEXPR void on_align(fmt::alignment a) { align_ = a; }
+ FMT_CONSTEXPR void on_align(fmt::align_t a) { align = a; }
FMT_CONSTEXPR void on_fill(char f) { fill = f; }
FMT_CONSTEXPR void on_plus() { res = PLUS; }
FMT_CONSTEXPR void on_minus() { res = MINUS; }
@@ -2152,7 +2155,7 @@
FMT_CONSTEXPR void end_precision() {}
FMT_CONSTEXPR void on_type(char t) { type = t; }
- FMT_CONSTEXPR void on_error(const char *) { res = ERROR; }
+ FMT_CONSTEXPR void on_error(const char*) { res = ERROR; }
};
template <size_t N>
@@ -2164,7 +2167,7 @@
TEST(FormatTest, ConstexprParseFormatSpecs) {
typedef test_format_specs_handler handler;
- static_assert(parse_test_specs("<").align_ == fmt::ALIGN_LEFT, "");
+ static_assert(parse_test_specs("<").align == fmt::align::left, "");
static_assert(parse_test_specs("*^").fill == '*', "");
static_assert(parse_test_specs("+").res == handler::PLUS, "");
static_assert(parse_test_specs("-").res == handler::MINUS, "");
@@ -2172,100 +2175,109 @@
static_assert(parse_test_specs("#").res == handler::HASH, "");
static_assert(parse_test_specs("0").res == handler::ZERO, "");
static_assert(parse_test_specs("42").width == 42, "");
- static_assert(parse_test_specs("{42}").width_ref.index == 42, "");
+ static_assert(parse_test_specs("{42}").width_ref.val.index == 42, "");
static_assert(parse_test_specs(".42").precision == 42, "");
- static_assert(parse_test_specs(".{42}").precision_ref.index == 42, "");
+ static_assert(parse_test_specs(".{42}").precision_ref.val.index == 42, "");
static_assert(parse_test_specs("d").type == 'd', "");
static_assert(parse_test_specs("{<").res == handler::ERROR, "");
}
-struct test_context {
+struct test_parse_context {
typedef char char_type;
- FMT_CONSTEXPR fmt::basic_format_arg<test_context> next_arg() {
- return fmt::internal::make_arg<test_context>(11);
- }
+ FMT_CONSTEXPR unsigned next_arg_id() { return 11; }
+ template <typename Id> FMT_CONSTEXPR void check_arg_id(Id) {}
+
+ FMT_CONSTEXPR const char* begin() { return nullptr; }
+ FMT_CONSTEXPR const char* end() { return nullptr; }
+
+ void on_error(const char*) {}
+};
+
+struct test_context {
+ typedef char char_type;
+ typedef fmt::basic_format_arg<test_context> format_arg;
+
+ template <typename T> struct formatter_type {
+ typedef fmt::formatter<T, char_type> type;
+ };
template <typename Id>
- FMT_CONSTEXPR fmt::basic_format_arg<test_context> get_arg(Id) {
- return fmt::internal::make_arg<test_context>(22);
+ FMT_CONSTEXPR fmt::basic_format_arg<test_context> arg(Id id) {
+ return fmt::internal::make_arg<test_context>(id);
}
- template <typename Id>
- FMT_CONSTEXPR void check_arg_id(Id) {}
+ void on_error(const char*) {}
- FMT_CONSTEXPR unsigned next_arg_id() { return 33; }
-
- void on_error(const char *) {}
-
- FMT_CONSTEXPR test_context &parse_context() { return *this; }
FMT_CONSTEXPR test_context error_handler() { return *this; }
};
template <size_t N>
FMT_CONSTEXPR fmt::format_specs parse_specs(const char (&s)[N]) {
fmt::format_specs specs;
+ test_parse_context parse_ctx;
test_context ctx{};
- fmt::internal::specs_handler<test_context> h(specs, ctx);
+ fmt::internal::specs_handler<test_parse_context, test_context> h(
+ specs, parse_ctx, ctx);
parse_format_specs(s, s + N, h);
return specs;
}
TEST(FormatTest, ConstexprSpecsHandler) {
- static_assert(parse_specs("<").align() == fmt::ALIGN_LEFT, "");
- static_assert(parse_specs("*^").fill() == '*', "");
- static_assert(parse_specs("+").has(fmt::PLUS_FLAG), "");
- static_assert(parse_specs("-").has(fmt::MINUS_FLAG), "");
- static_assert(parse_specs(" ").has(fmt::SIGN_FLAG), "");
- static_assert(parse_specs("#").has(fmt::HASH_FLAG), "");
- static_assert(parse_specs("0").align() == fmt::ALIGN_NUMERIC, "");
- static_assert(parse_specs("42").width() == 42, "");
- static_assert(parse_specs("{}").width() == 11, "");
- static_assert(parse_specs("{0}").width() == 22, "");
+ static_assert(parse_specs("<").align == fmt::align::left, "");
+ static_assert(parse_specs("*^").fill[0] == '*', "");
+ static_assert(parse_specs("+").sign == fmt::sign::plus, "");
+ static_assert(parse_specs("-").sign == fmt::sign::minus, "");
+ static_assert(parse_specs(" ").sign == fmt::sign::space, "");
+ static_assert(parse_specs("#").alt, "");
+ static_assert(parse_specs("0").align == fmt::align::numeric, "");
+ static_assert(parse_specs("42").width == 42, "");
+ static_assert(parse_specs("{}").width == 11, "");
+ static_assert(parse_specs("{22}").width == 22, "");
static_assert(parse_specs(".42").precision == 42, "");
static_assert(parse_specs(".{}").precision == 11, "");
- static_assert(parse_specs(".{0}").precision == 22, "");
+ static_assert(parse_specs(".{22}").precision == 22, "");
static_assert(parse_specs("d").type == 'd', "");
}
template <size_t N>
-FMT_CONSTEXPR fmt::internal::dynamic_format_specs<char>
- parse_dynamic_specs(const char (&s)[N]) {
+FMT_CONSTEXPR fmt::internal::dynamic_format_specs<char> parse_dynamic_specs(
+ const char (&s)[N]) {
fmt::internal::dynamic_format_specs<char> specs;
- test_context ctx{};
- fmt::internal::dynamic_specs_handler<test_context> h(specs, ctx);
+ test_parse_context ctx{};
+ fmt::internal::dynamic_specs_handler<test_parse_context> h(specs, ctx);
parse_format_specs(s, s + N, h);
return specs;
}
TEST(FormatTest, ConstexprDynamicSpecsHandler) {
- static_assert(parse_dynamic_specs("<").align() == fmt::ALIGN_LEFT, "");
- static_assert(parse_dynamic_specs("*^").fill() == '*', "");
- static_assert(parse_dynamic_specs("+").has(fmt::PLUS_FLAG), "");
- static_assert(parse_dynamic_specs("-").has(fmt::MINUS_FLAG), "");
- static_assert(parse_dynamic_specs(" ").has(fmt::SIGN_FLAG), "");
- static_assert(parse_dynamic_specs("#").has(fmt::HASH_FLAG), "");
- static_assert(parse_dynamic_specs("0").align() == fmt::ALIGN_NUMERIC, "");
- static_assert(parse_dynamic_specs("42").width() == 42, "");
- static_assert(parse_dynamic_specs("{}").width_ref.index == 33, "");
- static_assert(parse_dynamic_specs("{42}").width_ref.index == 42, "");
+ static_assert(parse_dynamic_specs("<").align == fmt::align::left, "");
+ static_assert(parse_dynamic_specs("*^").fill[0] == '*', "");
+ static_assert(parse_dynamic_specs("+").sign == fmt::sign::plus, "");
+ static_assert(parse_dynamic_specs("-").sign == fmt::sign::minus, "");
+ static_assert(parse_dynamic_specs(" ").sign == fmt::sign::space, "");
+ static_assert(parse_dynamic_specs("#").alt, "");
+ static_assert(parse_dynamic_specs("0").align == fmt::align::numeric, "");
+ static_assert(parse_dynamic_specs("42").width == 42, "");
+ static_assert(parse_dynamic_specs("{}").width_ref.val.index == 11, "");
+ static_assert(parse_dynamic_specs("{42}").width_ref.val.index == 42, "");
static_assert(parse_dynamic_specs(".42").precision == 42, "");
- static_assert(parse_dynamic_specs(".{}").precision_ref.index == 33, "");
- static_assert(parse_dynamic_specs(".{42}").precision_ref.index == 42, "");
+ static_assert(parse_dynamic_specs(".{}").precision_ref.val.index == 11, "");
+ static_assert(parse_dynamic_specs(".{42}").precision_ref.val.index == 42, "");
static_assert(parse_dynamic_specs("d").type == 'd', "");
}
template <size_t N>
FMT_CONSTEXPR test_format_specs_handler check_specs(const char (&s)[N]) {
- fmt::internal::specs_checker<test_format_specs_handler>
- checker(test_format_specs_handler(), fmt::internal::double_type);
+ fmt::internal::specs_checker<test_format_specs_handler> checker(
+ test_format_specs_handler(), fmt::internal::double_type);
parse_format_specs(s, s + N, checker);
return checker;
}
TEST(FormatTest, ConstexprSpecsChecker) {
typedef test_format_specs_handler handler;
- static_assert(check_specs("<").align_ == fmt::ALIGN_LEFT, "");
+ static_assert(check_specs("<").align == fmt::align::left, "");
static_assert(check_specs("*^").fill == '*', "");
static_assert(check_specs("+").res == handler::PLUS, "");
static_assert(check_specs("-").res == handler::MINUS, "");
@@ -2273,34 +2285,32 @@
static_assert(check_specs("#").res == handler::HASH, "");
static_assert(check_specs("0").res == handler::ZERO, "");
static_assert(check_specs("42").width == 42, "");
- static_assert(check_specs("{42}").width_ref.index == 42, "");
+ static_assert(check_specs("{42}").width_ref.val.index == 42, "");
static_assert(check_specs(".42").precision == 42, "");
- static_assert(check_specs(".{42}").precision_ref.index == 42, "");
+ static_assert(check_specs(".{42}").precision_ref.val.index == 42, "");
static_assert(check_specs("d").type == 'd', "");
static_assert(check_specs("{<").res == handler::ERROR, "");
}
struct test_format_string_handler {
- FMT_CONSTEXPR void on_text(const char *, const char *) {}
+ FMT_CONSTEXPR void on_text(const char*, const char*) {}
FMT_CONSTEXPR void on_arg_id() {}
- template <typename T>
- FMT_CONSTEXPR void on_arg_id(T) {}
+ template <typename T> FMT_CONSTEXPR void on_arg_id(T) {}
- FMT_CONSTEXPR void on_replacement_field(const char *) {}
+ FMT_CONSTEXPR void on_replacement_field(const char*) {}
- FMT_CONSTEXPR const char *on_format_specs(const char *begin, const char*) {
+ FMT_CONSTEXPR const char* on_format_specs(const char* begin, const char*) {
return begin;
}
- FMT_CONSTEXPR void on_error(const char *) { error = true; }
+ FMT_CONSTEXPR void on_error(const char*) { error = true; }
bool error = false;
};
-template <size_t N>
-FMT_CONSTEXPR bool parse_string(const char (&s)[N]) {
+template <size_t N> FMT_CONSTEXPR bool parse_string(const char (&s)[N]) {
test_format_string_handler h;
fmt::internal::parse_format_string<true>(fmt::string_view(s, N - 1), h);
return !h.error;
@@ -2316,29 +2326,26 @@
}
struct test_error_handler {
- const char *&error;
+ const char*& error;
- FMT_CONSTEXPR test_error_handler(const char *&err): error(err) {}
+ FMT_CONSTEXPR test_error_handler(const char*& err) : error(err) {}
- FMT_CONSTEXPR test_error_handler(const test_error_handler &other)
- : error(other.error) {}
+ FMT_CONSTEXPR test_error_handler(const test_error_handler& other)
+ : error(other.error) {}
- FMT_CONSTEXPR void on_error(const char *message) {
- if (!error)
- error = message;
+ FMT_CONSTEXPR void on_error(const char* message) {
+ if (!error) error = message;
}
};
-FMT_CONSTEXPR size_t len(const char *s) {
+FMT_CONSTEXPR size_t len(const char* s) {
size_t len = 0;
- while (*s++)
- ++len;
+ while (*s++) ++len;
return len;
}
-FMT_CONSTEXPR bool equal(const char *s1, const char *s2) {
- if (!s1 || !s2)
- return s1 == s2;
+FMT_CONSTEXPR bool equal(const char* s1, const char* s2) {
+ if (!s1 || !s2) return s1 == s2;
while (*s1 && *s1 == *s2) {
++s1;
++s2;
@@ -2347,23 +2354,23 @@
}
template <typename... Args>
-FMT_CONSTEXPR bool test_error(const char *fmt, const char *expected_error) {
- const char *actual_error = FMT_NULL;
+FMT_CONSTEXPR bool test_error(const char* fmt, const char* expected_error) {
+ const char* actual_error = nullptr;
fmt::internal::do_check_format_string<char, test_error_handler, Args...>(
- string_view(fmt, len(fmt)), test_error_handler(actual_error));
+ string_view(fmt, len(fmt)), test_error_handler(actual_error));
return equal(actual_error, expected_error);
}
-#define EXPECT_ERROR_NOARGS(fmt, error) \
- static_assert(test_error(fmt, error), "")
-#define EXPECT_ERROR(fmt, error, ...) \
- static_assert(test_error<__VA_ARGS__>(fmt, error), "")
+# define EXPECT_ERROR_NOARGS(fmt, error) \
+ static_assert(test_error(fmt, error), "")
+# define EXPECT_ERROR(fmt, error, ...) \
+ static_assert(test_error<__VA_ARGS__>(fmt, error), "")
TEST(FormatTest, FormatStringErrors) {
- EXPECT_ERROR_NOARGS("foo", FMT_NULL);
+ EXPECT_ERROR_NOARGS("foo", nullptr);
EXPECT_ERROR_NOARGS("}", "unmatched '}' in format string");
EXPECT_ERROR("{0:s", "unknown format specifier", Date);
-#ifndef _MSC_VER
+# if FMT_MSC_VER >= 1916
// This causes an internal compiler error in MSVC2017.
EXPECT_ERROR("{0:=5", "unknown format specifier", int);
EXPECT_ERROR("{:{<}", "invalid fill character '{'", int);
@@ -2371,17 +2378,17 @@
EXPECT_ERROR("{:.10000000000}", "number is too big", int);
EXPECT_ERROR_NOARGS("{:x}", "argument index out of range");
EXPECT_ERROR("{:=}", "format specifier requires numeric argument",
- const char *);
+ const char*);
EXPECT_ERROR("{:+}", "format specifier requires numeric argument",
- const char *);
+ const char*);
EXPECT_ERROR("{:-}", "format specifier requires numeric argument",
- const char *);
+ const char*);
EXPECT_ERROR("{:#}", "format specifier requires numeric argument",
- const char *);
+ const char*);
EXPECT_ERROR("{: }", "format specifier requires numeric argument",
- const char *);
+ const char*);
EXPECT_ERROR("{:0}", "format specifier requires numeric argument",
- const char *);
+ const char*);
EXPECT_ERROR("{:+}", "format specifier requires signed argument", unsigned);
EXPECT_ERROR("{:-}", "format specifier requires signed argument", unsigned);
EXPECT_ERROR("{: }", "format specifier requires signed argument", unsigned);
@@ -2391,11 +2398,14 @@
EXPECT_ERROR("{:s}", "invalid type specifier", char);
EXPECT_ERROR("{:+}", "invalid format specifier for char", char);
EXPECT_ERROR("{:s}", "invalid type specifier", double);
- EXPECT_ERROR("{:d}", "invalid type specifier", const char *);
+ EXPECT_ERROR("{:d}", "invalid type specifier", const char*);
EXPECT_ERROR("{:d}", "invalid type specifier", std::string);
- EXPECT_ERROR("{:s}", "invalid type specifier", void *);
-#endif
- EXPECT_ERROR("{foo", "missing '}' in format string", int);
+ EXPECT_ERROR("{:s}", "invalid type specifier", void*);
+# else
+ fmt::print("warning: constexpr is broken in this version of MSVC\n");
+# endif
+ EXPECT_ERROR("{foo", "compile-time checks don't support named arguments",
+ int);
EXPECT_ERROR_NOARGS("{10000000000}", "number is too big");
EXPECT_ERROR_NOARGS("{0x}", "invalid format string");
EXPECT_ERROR_NOARGS("{-}", "invalid format string");
@@ -2407,11 +2417,11 @@
EXPECT_ERROR_NOARGS("{}", "argument index out of range");
EXPECT_ERROR("{1}", "argument index out of range", int);
EXPECT_ERROR("{1}{}",
- "cannot switch from manual to automatic argument indexing",
- int, int);
+ "cannot switch from manual to automatic argument indexing", int,
+ int);
EXPECT_ERROR("{}{1}",
- "cannot switch from automatic to manual argument indexing",
- int, int);
+ "cannot switch from automatic to manual argument indexing", int,
+ int);
}
TEST(FormatTest, VFormatTo) {
@@ -2436,12 +2446,28 @@
EXPECT_EQ(L"42", w);
}
+template <typename T> static std::string FmtToString(const T& t) {
+ return fmt::format(FMT_STRING("{}"), t);
+}
+
+TEST(FormatTest, FmtStringInTemplate) {
+ EXPECT_EQ(FmtToString(1), "1");
+ EXPECT_EQ(FmtToString(0), "0");
+}
+
#endif // FMT_USE_CONSTEXPR
+// 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.
+#ifndef __cpp_char8_t
+// Locally provide type char8_t defined in format.h
+using fmt::char8_t;
+#endif
+
TEST(FormatTest, ConstructU8StringViewFromCString) {
fmt::u8string_view s("ab");
EXPECT_EQ(s.size(), 2u);
- const fmt::char8_t *data = s.data();
+ const char8_t* data = s.data();
EXPECT_EQ(data[0], 'a');
EXPECT_EQ(data[1], 'b');
}
@@ -2449,7 +2475,7 @@
TEST(FormatTest, ConstructU8StringViewFromDataAndSize) {
fmt::u8string_view s("foobar", 3);
EXPECT_EQ(s.size(), 3u);
- const fmt::char8_t *data = s.data();
+ const char8_t* data = s.data();
EXPECT_EQ(data[0], 'f');
EXPECT_EQ(data[1], 'o');
EXPECT_EQ(data[2], 'o');
@@ -2460,7 +2486,7 @@
using namespace fmt::literals;
fmt::u8string_view s = "ab"_u;
EXPECT_EQ(s.size(), 2u);
- const fmt::char8_t *data = s.data();
+ const char8_t* data = s.data();
EXPECT_EQ(data[0], 'a');
EXPECT_EQ(data[1], 'b');
EXPECT_EQ(format("{:*^5}"_u, "🤡"_u), "**🤡**"_u);
@@ -2470,3 +2496,41 @@
TEST(FormatTest, FormatU8String) {
EXPECT_EQ(format(fmt::u8string_view("{}"), 42), fmt::u8string_view("42"));
}
+
+TEST(FormatTest, EmphasisNonHeaderOnly) {
+ // ensure this compiles even if FMT_HEADER_ONLY is not defined.
+ EXPECT_EQ(fmt::format(fmt::emphasis::bold, "bold error"),
+ "\x1b[1mbold error\x1b[0m");
+}
+
+TEST(FormatTest, CharTraitsIsNotAmbiguous) {
+ // Test that we don't inject internal names into the std namespace.
+ using namespace std;
+ char_traits<char>::char_type c;
+ (void)c;
+#if __cplusplus >= 201103L
+ std::string s;
+ auto lval = begin(s);
+ (void)lval;
+#endif
+}
+
+struct mychar {
+ int value;
+ mychar() = default;
+
+ template <typename T> mychar(T val) : value(static_cast<int>(val)) {}
+
+ operator int() const { return value; }
+};
+
+FMT_BEGIN_NAMESPACE
+template <> struct is_char<mychar> : std::true_type {};
+FMT_END_NAMESPACE
+
+TEST(FormatTest, FormatCustomChar) {
+ const mychar format[] = {'{', '}', 0};
+ auto result = fmt::format(format, mychar('x'));
+ EXPECT_EQ(result.size(), 1);
+ EXPECT_EQ(result[0], mychar('x'));
+}
diff --git a/test/fuzzing/.gitignore b/test/fuzzing/.gitignore
new file mode 100644
index 0000000..ea41040
--- /dev/null
+++ b/test/fuzzing/.gitignore
@@ -0,0 +1,3 @@
+# ignore artifacts from the build.sh script
+build-*/
+
diff --git a/test/fuzzing/CMakeLists.txt b/test/fuzzing/CMakeLists.txt
new file mode 100644
index 0000000..31344fc
--- /dev/null
+++ b/test/fuzzing/CMakeLists.txt
@@ -0,0 +1,38 @@
+# Copyright (c) 2019, Paul Dreik
+# License: see LICENSE.rst in the fmt root directory
+
+# settings this links in a main. useful for reproducing,
+# kcov, gdb, afl, valgrind.
+# (note that libFuzzer can also reproduce, just pass it the files)
+option(FMT_FUZZ_LINKMAIN "enables the reproduce mode, instead of libFuzzer" On)
+
+# For oss-fuzz - insert $LIB_FUZZING_ENGINE into the link flags, but only for
+# the fuzz targets, otherwise the cmake configuration step fails.
+set(FMT_FUZZ_LDFLAGS "" CACHE STRING "LDFLAGS for the fuzz targets")
+
+# Find all fuzzers.
+set(SOURCES
+ chrono_duration.cpp
+ named_arg.cpp
+ one_arg.cpp
+ sprintf.cpp
+ two_args.cpp
+)
+
+macro(implement_fuzzer sourcefile)
+ get_filename_component(basename ${sourcefile} NAME_WE)
+ set(name fuzzer_${basename})
+ add_executable(${name} ${sourcefile} fuzzer_common.h)
+ if (FMT_FUZZ_LINKMAIN)
+ target_sources(${name} PRIVATE main.cpp)
+ endif ()
+ target_link_libraries(${name} PRIVATE fmt)
+if (FMT_FUZZ_LDFLAGS)
+ target_link_libraries(${name} PRIVATE ${FMT_FUZZ_LDFLAGS})
+endif ()
+ target_compile_features(${name} PRIVATE cxx_generic_lambdas)
+endmacro ()
+
+foreach (X IN ITEMS ${SOURCES})
+ implement_fuzzer(${X})
+endforeach ()
diff --git a/test/fuzzing/README.md b/test/fuzzing/README.md
new file mode 100644
index 0000000..0499d00
--- /dev/null
+++ b/test/fuzzing/README.md
@@ -0,0 +1,43 @@
+# FMT Fuzzer
+
+Fuzzing has revealed [several bugs](https://github.com/fmtlib/fmt/issues?&q=is%3Aissue+fuzz)
+in fmt. It is a part of the continous fuzzing at
+[oss-fuzz](https://github.com/google/oss-fuzz).
+
+The source code is modified to make the fuzzing possible without locking up on
+resource exhaustion:
+```cpp
+#ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
+if(spec.precision>100000) {
+ throw std::runtime_error("fuzz mode - avoiding large precision");
+}
+#endif
+```
+This macro is the defacto standard for making fuzzing practically possible, see
+[the libFuzzer documentation](https://llvm.org/docs/LibFuzzer.html#fuzzer-friendly-build-mode).
+
+## Running the fuzzers locally
+
+There is a [helper script](build.sh) to build the fuzzers, which has only been
+tested on Debian and Ubuntu linux so far. There should be no problems fuzzing on
+Windows (using clang>=8) or on Mac, but the script will probably not work out of
+the box.
+
+Something along
+```sh
+mkdir build
+cd build
+export CXX=clang++
+export CXXFLAGS="-fsanitize=fuzzer-no-link -DFUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION= -g"
+cmake .. -DFMT_SAFE_DURATION_CAST=On -DFMT_FUZZ=On -DFMT_FUZZ_LINKMAIN=Off -DFMT_FUZZ_LDFLAGS="-fsanitize=fuzzer"
+cmake --build .
+```
+should work to build the fuzzers for all platforms which clang supports.
+
+Execute a fuzzer with for instance
+```sh
+cd build
+export UBSAN_OPTIONS=halt_on_error=1
+mkdir out_chrono
+bin/fuzzer_chrono_duration out_chrono
+```
diff --git a/test/fuzzing/build.sh b/test/fuzzing/build.sh
new file mode 100755
index 0000000..141a50d
--- /dev/null
+++ b/test/fuzzing/build.sh
@@ -0,0 +1,110 @@
+#!/bin/sh
+#
+# Creates fuzzer builds of various kinds
+# - reproduce mode (no fuzzing, just enables replaying data through the fuzzers)
+# - oss-fuzz emulated mode (makes sure a simulated invocation by oss-fuzz works)
+# - libFuzzer build (you will need clang)
+# - afl build (you will need afl)
+#
+#
+# Copyright (c) 2019 Paul Dreik
+#
+# License: see LICENSE.rst in the fmt root directory
+
+set -e
+me=$(basename $0)
+root=$(readlink -f "$(dirname "$0")/../..")
+
+
+echo $me: root=$root
+
+here=$(pwd)
+
+CXXFLAGSALL="-DFUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION= -g"
+CMAKEFLAGSALL="$root -GNinja -DCMAKE_BUILD_TYPE=Debug -DFMT_DOC=Off -DFMT_TEST=Off -DFMT_FUZZ=On -DCMAKE_CXX_STANDARD=17"
+
+#builds the fuzzers as one would do if using afl or just making
+#binaries for reproducing.
+builddir=$here/build-fuzzers-reproduce
+mkdir -p $builddir
+cd $builddir
+CXX="ccache g++" CXXFLAGS="$CXXFLAGSALL" cmake \
+$CMAKEFLAGSALL
+cmake --build $builddir
+
+#for performance analysis of the fuzzers
+builddir=$here/build-fuzzers-perfanalysis
+mkdir -p $builddir
+cd $builddir
+CXX="ccache g++" CXXFLAGS="$CXXFLAGSALL -g" cmake \
+$CMAKEFLAGSALL \
+-DFMT_FUZZ_LINKMAIN=On \
+-DCMAKE_BUILD_TYPE=Release
+
+cmake --build $builddir
+
+#builds the fuzzers as oss-fuzz does
+builddir=$here/build-fuzzers-ossfuzz
+mkdir -p $builddir
+cd $builddir
+CXX="clang++" \
+CXXFLAGS="$CXXFLAGSALL -fsanitize=fuzzer-no-link" cmake \
+cmake $CMAKEFLAGSALL \
+-DFMT_FUZZ_LINKMAIN=Off \
+-DFMT_FUZZ_LDFLAGS="-fsanitize=fuzzer"
+
+cmake --build $builddir
+
+
+#builds fuzzers for local fuzzing with libfuzzer with asan+usan
+builddir=$here/build-fuzzers-libfuzzer
+mkdir -p $builddir
+cd $builddir
+CXX="clang++" \
+CXXFLAGS="$CXXFLAGSALL -fsanitize=fuzzer-no-link,address,undefined" cmake \
+cmake $CMAKEFLAGSALL \
+-DFMT_FUZZ_LINKMAIN=Off \
+-DFMT_FUZZ_LDFLAGS="-fsanitize=fuzzer"
+
+cmake --build $builddir
+
+#builds fuzzers for local fuzzing with libfuzzer with asan only
+builddir=$here/build-fuzzers-libfuzzer-addr
+mkdir -p $builddir
+cd $builddir
+CXX="clang++" \
+CXXFLAGS="$CXXFLAGSALL -fsanitize=fuzzer-no-link,undefined" cmake \
+cmake $CMAKEFLAGSALL \
+-DFMT_FUZZ_LINKMAIN=Off \
+-DFMT_FUZZ_LDFLAGS="-fsanitize=fuzzer"
+
+cmake --build $builddir
+
+#builds a fast fuzzer for making coverage fast
+builddir=$here/build-fuzzers-fast
+mkdir -p $builddir
+cd $builddir
+CXX="clang++" \
+CXXFLAGS="$CXXFLAGSALL -fsanitize=fuzzer-no-link -O3" cmake \
+cmake $CMAKEFLAGSALL \
+-DFMT_FUZZ_LINKMAIN=Off \
+-DFMT_FUZZ_LDFLAGS="-fsanitize=fuzzer" \
+ -DCMAKE_BUILD_TYPE=Release
+
+cmake --build $builddir
+
+
+#builds fuzzers for local fuzzing with afl
+builddir=$here/build-fuzzers-afl
+mkdir -p $builddir
+cd $builddir
+CXX="afl-g++" \
+CXXFLAGS="$CXXFLAGSALL -fsanitize=address,undefined" \
+cmake $CMAKEFLAGSALL \
+-DFMT_FUZZ_LINKMAIN=On
+
+cmake --build $builddir
+
+
+echo $me: all good
+
diff --git a/test/fuzzing/chrono_duration.cpp b/test/fuzzing/chrono_duration.cpp
new file mode 100644
index 0000000..d1de9ae
--- /dev/null
+++ b/test/fuzzing/chrono_duration.cpp
@@ -0,0 +1,152 @@
+// Copyright (c) 2019, Paul Dreik
+// License: see LICENSE.rst in the fmt root directory
+
+#include <fmt/chrono.h>
+#include <cstdint>
+#include <limits>
+#include <stdexcept>
+#include <type_traits>
+#include <vector>
+#include "fuzzer_common.h"
+
+template <typename Item, typename Ratio>
+void invoke_inner(fmt::string_view formatstring, const Item item) {
+ const std::chrono::duration<Item, Ratio> value(item);
+ try {
+#if FMT_FUZZ_FORMAT_TO_STRING
+ std::string message = fmt::format(formatstring, value);
+#else
+ fmt::memory_buffer buf;
+ fmt::format_to(buf, formatstring, value);
+#endif
+ } catch (std::exception& /*e*/) {
+ }
+}
+
+// Item is the underlying type for duration (int, long etc)
+template <typename Item>
+void invoke_outer(const uint8_t* Data, std::size_t Size, const int scaling) {
+ // always use a fixed location of the data
+ using fmt_fuzzer::Nfixed;
+
+ constexpr auto N = sizeof(Item);
+ static_assert(N <= Nfixed, "fixed size is too small");
+ if (Size <= Nfixed + 1) {
+ return;
+ }
+
+ const Item item = fmt_fuzzer::assignFromBuf<Item>(Data);
+
+ // fast forward
+ Data += Nfixed;
+ Size -= Nfixed;
+
+ // Data is already allocated separately in libFuzzer so reading past
+ // the end will most likely be detected anyway
+ const auto formatstring = fmt::string_view(fmt_fuzzer::as_chars(Data), Size);
+
+ // doit_impl<Item,std::yocto>(buf.data(),item);
+ // doit_impl<Item,std::zepto>(buf.data(),item);
+ switch (scaling) {
+ case 1:
+ invoke_inner<Item, std::atto>(formatstring, item);
+ break;
+ case 2:
+ invoke_inner<Item, std::femto>(formatstring, item);
+ break;
+ case 3:
+ invoke_inner<Item, std::pico>(formatstring, item);
+ break;
+ case 4:
+ invoke_inner<Item, std::nano>(formatstring, item);
+ break;
+ case 5:
+ invoke_inner<Item, std::micro>(formatstring, item);
+ break;
+ case 6:
+ invoke_inner<Item, std::milli>(formatstring, item);
+ break;
+ case 7:
+ invoke_inner<Item, std::centi>(formatstring, item);
+ break;
+ case 8:
+ invoke_inner<Item, std::deci>(formatstring, item);
+ break;
+ case 9:
+ invoke_inner<Item, std::deca>(formatstring, item);
+ break;
+ case 10:
+ invoke_inner<Item, std::kilo>(formatstring, item);
+ break;
+ case 11:
+ invoke_inner<Item, std::mega>(formatstring, item);
+ break;
+ case 12:
+ invoke_inner<Item, std::giga>(formatstring, item);
+ break;
+ case 13:
+ invoke_inner<Item, std::tera>(formatstring, item);
+ break;
+ case 14:
+ invoke_inner<Item, std::peta>(formatstring, item);
+ break;
+ case 15:
+ invoke_inner<Item, std::exa>(formatstring, item);
+ }
+ // doit_impl<Item,std::zeta>(buf.data(),item);
+ // doit_impl<Item,std::yotta>(buf.data(),item);
+}
+
+extern "C" int LLVMFuzzerTestOneInput(const uint8_t* Data, std::size_t Size) {
+ if (Size <= 4) {
+ return 0;
+ }
+
+ const auto representation = Data[0];
+ const auto scaling = Data[1];
+ Data += 2;
+ Size -= 2;
+
+ switch (representation) {
+ case 1:
+ invoke_outer<char>(Data, Size, scaling);
+ break;
+ case 2:
+ invoke_outer<unsigned char>(Data, Size, scaling);
+ break;
+ case 3:
+ invoke_outer<signed char>(Data, Size, scaling);
+ break;
+ case 4:
+ invoke_outer<short>(Data, Size, scaling);
+ break;
+ case 5:
+ invoke_outer<unsigned short>(Data, Size, scaling);
+ break;
+ case 6:
+ invoke_outer<int>(Data, Size, scaling);
+ break;
+ case 7:
+ invoke_outer<unsigned int>(Data, Size, scaling);
+ break;
+ case 8:
+ invoke_outer<long>(Data, Size, scaling);
+ break;
+ case 9:
+ invoke_outer<unsigned long>(Data, Size, scaling);
+ break;
+ case 10:
+ invoke_outer<float>(Data, Size, scaling);
+ break;
+ case 11:
+ invoke_outer<double>(Data, Size, scaling);
+ break;
+ case 12:
+ invoke_outer<long double>(Data, Size, scaling);
+ break;
+ default:
+ break;
+ }
+
+ return 0;
+}
diff --git a/test/fuzzing/fuzzer_common.h b/test/fuzzing/fuzzer_common.h
new file mode 100644
index 0000000..c3d8561
--- /dev/null
+++ b/test/fuzzing/fuzzer_common.h
@@ -0,0 +1,67 @@
+#ifndef FUZZER_COMMON_H
+#define FUZZER_COMMON_H
+
+// Copyright (c) 2019, Paul Dreik
+// License: see LICENSE.rst in the fmt root directory
+
+#include <cstdint> // std::uint8_t
+#include <cstring> // memcpy
+#include <type_traits> // trivially copyable
+
+// one can format to either a string, or a buf. buf is faster,
+// but one may be interested in formatting to a string instead to
+// verify it works as intended. to avoid a combinatoric explosion,
+// select this at compile time instead of dynamically from the fuzz data
+#define FMT_FUZZ_FORMAT_TO_STRING 0
+
+// if fmt is given a buffer that is separately allocated,
+// chances that address sanitizer detects out of bound reads is
+// much higher. However, it slows down the fuzzing.
+#define FMT_FUZZ_SEPARATE_ALLOCATION 1
+
+// To let the the fuzzer mutation be efficient at cross pollinating
+// between different types, use a fixed size format.
+// The same bit pattern, interpreted as another type,
+// is likely interesting.
+// For this, we must know the size of the largest possible type in use.
+
+// There are some problems on travis, claiming Nfixed is not a constant
+// expression which seems to be an issue with older versions of libstdc++
+#if _GLIBCXX_RELEASE >= 7
+# include <algorithm>
+namespace fmt_fuzzer {
+constexpr auto Nfixed = std::max(sizeof(long double), sizeof(std::intmax_t));
+}
+#else
+namespace fmt_fuzzer {
+constexpr auto Nfixed = 16;
+}
+#endif
+
+namespace fmt_fuzzer {
+// view data as a c char pointer.
+template <typename T> inline const char* as_chars(const T* data) {
+ return static_cast<const char*>(static_cast<const void*>(data));
+}
+
+// view data as a byte pointer
+template <typename T> inline const std::uint8_t* as_bytes(const T* data) {
+ return static_cast<const std::uint8_t*>(static_cast<const void*>(data));
+}
+
+// blits bytes from Data to form an (assumed trivially constructible) object
+// of type Item
+template <class Item> inline Item assignFromBuf(const std::uint8_t* Data) {
+ Item item{};
+ std::memcpy(&item, Data, sizeof(Item));
+ return item;
+}
+
+// reads a boolean value by looking at the first byte from Data
+template <> inline bool assignFromBuf<bool>(const std::uint8_t* Data) {
+ return !!Data[0];
+}
+
+} // namespace fmt_fuzzer
+
+#endif // FUZZER_COMMON_H
diff --git a/test/fuzzing/main.cpp b/test/fuzzing/main.cpp
new file mode 100644
index 0000000..6ac8130
--- /dev/null
+++ b/test/fuzzing/main.cpp
@@ -0,0 +1,21 @@
+#include <cassert>
+#include <fstream>
+#include <sstream>
+#include <vector>
+#include "fuzzer_common.h"
+
+extern "C" int LLVMFuzzerTestOneInput(const uint8_t* Data, std::size_t Size);
+int main(int argc, char* argv[]) {
+ for (int i = 1; i < argc; ++i) {
+ std::ifstream in(argv[i]);
+ assert(in);
+ in.seekg(0, std::ios_base::end);
+ const auto pos = in.tellg();
+ assert(pos >= 0);
+ in.seekg(0, std::ios_base::beg);
+ std::vector<char> buf(static_cast<std::size_t>(pos));
+ in.read(buf.data(), static_cast<long>(buf.size()));
+ assert(in.gcount() == pos);
+ LLVMFuzzerTestOneInput(fmt_fuzzer::as_bytes(buf.data()), buf.size());
+ }
+}
diff --git a/test/fuzzing/named_arg.cpp b/test/fuzzing/named_arg.cpp
new file mode 100644
index 0000000..0f9a451
--- /dev/null
+++ b/test/fuzzing/named_arg.cpp
@@ -0,0 +1,128 @@
+// Copyright (c) 2019, Paul Dreik
+// License: see LICENSE.rst in the fmt root directory
+
+#include <fmt/chrono.h>
+#include <fmt/core.h>
+#include <cstdint>
+#include <stdexcept>
+#include <type_traits>
+#include <vector>
+#include "fuzzer_common.h"
+
+template <typename Item1>
+void invoke_fmt(const uint8_t* Data, std::size_t Size, unsigned int argsize) {
+ constexpr auto N1 = sizeof(Item1);
+ static_assert(N1 <= fmt_fuzzer::Nfixed, "Nfixed too small");
+ if (Size <= fmt_fuzzer::Nfixed) {
+ return;
+ }
+ const Item1 item1 = fmt_fuzzer::assignFromBuf<Item1>(Data);
+
+ Data += fmt_fuzzer::Nfixed;
+ Size -= fmt_fuzzer::Nfixed;
+
+ // how many chars should be used for the argument name?
+ if (argsize <= 0 || argsize >= Size) {
+ return;
+ }
+
+ // allocating buffers separately is slower, but increases chances
+ // of detecting memory errors
+#if FMT_FUZZ_SEPARATE_ALLOCATION
+ std::vector<char> argnamebuffer(argsize);
+ std::memcpy(argnamebuffer.data(), Data, argsize);
+ auto argname = fmt::string_view(argnamebuffer.data(), argsize);
+#else
+ auto argname = fmt::string_view(fmt_fuzzer::as_chars(Data), argsize);
+#endif
+ Data += argsize;
+ Size -= argsize;
+
+#if FMT_FUZZ_SEPARATE_ALLOCATION
+ // allocates as tight as possible, making it easier to catch buffer overruns.
+ std::vector<char> fmtstringbuffer(Size);
+ std::memcpy(fmtstringbuffer.data(), Data, Size);
+ auto fmtstring = fmt::string_view(fmtstringbuffer.data(), Size);
+#else
+ auto fmtstring = fmt::string_view(fmt_fuzzer::as_chars(Data), Size);
+#endif
+
+#if FMT_FUZZ_FORMAT_TO_STRING
+ std::string message = fmt::format(fmtstring, fmt::arg(argname, item1));
+#else
+ fmt::memory_buffer outbuf;
+ fmt::format_to(outbuf, fmtstring, fmt::arg(argname, item1));
+#endif
+}
+
+// for dynamic dispatching to an explicit instantiation
+template <typename Callback> void invoke(int index, Callback callback) {
+ switch (index) {
+ case 0:
+ callback(bool{});
+ break;
+ case 1:
+ callback(char{});
+ break;
+ case 2:
+ using sc = signed char;
+ callback(sc{});
+ break;
+ case 3:
+ using uc = unsigned char;
+ callback(uc{});
+ break;
+ case 4:
+ callback(short{});
+ break;
+ case 5:
+ using us = unsigned short;
+ callback(us{});
+ break;
+ case 6:
+ callback(int{});
+ break;
+ case 7:
+ callback(unsigned{});
+ break;
+ case 8:
+ callback(long{});
+ break;
+ case 9:
+ using ul = unsigned long;
+ callback(ul{});
+ break;
+ case 10:
+ callback(float{});
+ break;
+ case 11:
+ callback(double{});
+ break;
+ case 12:
+ using LD = long double;
+ callback(LD{});
+ break;
+ }
+}
+
+extern "C" int LLVMFuzzerTestOneInput(const uint8_t* Data, std::size_t Size) {
+ if (Size <= 3) {
+ return 0;
+ }
+
+ // switch types depending on the first byte of the input
+ const auto first = Data[0] & 0x0F;
+ const unsigned int second = (Data[0] & 0xF0) >> 4;
+ Data++;
+ Size--;
+
+ auto outerfcn = [=](auto param1) {
+ invoke_fmt<decltype(param1)>(Data, Size, second);
+ };
+
+ try {
+ invoke(first, outerfcn);
+ } catch (std::exception& /*e*/) {
+ }
+ return 0;
+}
diff --git a/test/fuzzing/one_arg.cpp b/test/fuzzing/one_arg.cpp
new file mode 100644
index 0000000..86a159b
--- /dev/null
+++ b/test/fuzzing/one_arg.cpp
@@ -0,0 +1,131 @@
+// Copyright (c) 2019, Paul Dreik
+// License: see LICENSE.rst in the fmt root directory
+
+#include <fmt/core.h>
+#include <cstdint>
+#include <stdexcept>
+#include <type_traits>
+#include <vector>
+
+#include <fmt/chrono.h>
+#include "fuzzer_common.h"
+
+using fmt_fuzzer::Nfixed;
+
+template <typename Item>
+void invoke_fmt(const uint8_t* Data, std::size_t Size) {
+ constexpr auto N = sizeof(Item);
+ static_assert(N <= Nfixed, "Nfixed is too small");
+ if (Size <= Nfixed) {
+ return;
+ }
+ const Item item = fmt_fuzzer::assignFromBuf<Item>(Data);
+ Data += Nfixed;
+ Size -= Nfixed;
+
+#if FMT_FUZZ_SEPARATE_ALLOCATION
+ // allocates as tight as possible, making it easier to catch buffer overruns.
+ std::vector<char> fmtstringbuffer(Size);
+ std::memcpy(fmtstringbuffer.data(), Data, Size);
+ auto fmtstring = fmt::string_view(fmtstringbuffer.data(), Size);
+#else
+ auto fmtstring = fmt::string_view(fmt_fuzzer::as_chars(Data), Size);
+#endif
+
+#if FMT_FUZZ_FORMAT_TO_STRING
+ std::string message = fmt::format(fmtstring, item);
+#else
+ fmt::memory_buffer message;
+ fmt::format_to(message, fmtstring, item);
+#endif
+}
+
+void invoke_fmt_time(const uint8_t* Data, std::size_t Size) {
+ using Item = std::time_t;
+ constexpr auto N = sizeof(Item);
+ static_assert(N <= Nfixed, "Nfixed too small");
+ if (Size <= Nfixed) {
+ return;
+ }
+ const Item item = fmt_fuzzer::assignFromBuf<Item>(Data);
+ Data += Nfixed;
+ Size -= Nfixed;
+#if FMT_FUZZ_SEPARATE_ALLOCATION
+ // allocates as tight as possible, making it easier to catch buffer overruns.
+ std::vector<char> fmtstringbuffer(Size);
+ std::memcpy(fmtstringbuffer.data(), Data, Size);
+ auto fmtstring = fmt::string_view(fmtstringbuffer.data(), Size);
+#else
+ auto fmtstring = fmt::string_view(fmt_fuzzer::as_chars(Data), Size);
+#endif
+ auto* b = std::localtime(&item);
+ if (b) {
+#if FMT_FUZZ_FORMAT_TO_STRING
+ std::string message = fmt::format(fmtstring, *b);
+#else
+ fmt::memory_buffer message;
+ fmt::format_to(message, fmtstring, *b);
+#endif
+ }
+}
+
+extern "C" int LLVMFuzzerTestOneInput(const uint8_t* Data, std::size_t Size) {
+ if (Size <= 3) {
+ return 0;
+ }
+
+ const auto first = Data[0];
+ Data++;
+ Size--;
+
+ try {
+ switch (first) {
+ case 0:
+ invoke_fmt<bool>(Data, Size);
+ break;
+ case 1:
+ invoke_fmt<char>(Data, Size);
+ break;
+ case 2:
+ invoke_fmt<unsigned char>(Data, Size);
+ break;
+ case 3:
+ invoke_fmt<signed char>(Data, Size);
+ break;
+ case 4:
+ invoke_fmt<short>(Data, Size);
+ break;
+ case 5:
+ invoke_fmt<unsigned short>(Data, Size);
+ break;
+ case 6:
+ invoke_fmt<int>(Data, Size);
+ break;
+ case 7:
+ invoke_fmt<unsigned int>(Data, Size);
+ break;
+ case 8:
+ invoke_fmt<long>(Data, Size);
+ break;
+ case 9:
+ invoke_fmt<unsigned long>(Data, Size);
+ break;
+ case 10:
+ invoke_fmt<float>(Data, Size);
+ break;
+ case 11:
+ invoke_fmt<double>(Data, Size);
+ break;
+ case 12:
+ invoke_fmt<long double>(Data, Size);
+ break;
+ case 13:
+ invoke_fmt_time(Data, Size);
+ break;
+ default:
+ break;
+ }
+ } catch (std::exception& /*e*/) {
+ }
+ return 0;
+}
diff --git a/test/fuzzing/sprintf.cpp b/test/fuzzing/sprintf.cpp
new file mode 100644
index 0000000..7dd0222
--- /dev/null
+++ b/test/fuzzing/sprintf.cpp
@@ -0,0 +1,116 @@
+// Copyright (c) 2019, Paul Dreik
+// License: see LICENSE.rst in the fmt root directory
+#include <fmt/format.h>
+#include <fmt/printf.h>
+#include <cstdint>
+#include <stdexcept>
+
+#include "fuzzer_common.h"
+
+using fmt_fuzzer::Nfixed;
+
+template <typename Item1, typename Item2>
+void invoke_fmt(const uint8_t* Data, std::size_t Size) {
+ constexpr auto N1 = sizeof(Item1);
+ constexpr auto N2 = sizeof(Item2);
+ static_assert(N1 <= Nfixed, "size1 exceeded");
+ static_assert(N2 <= Nfixed, "size2 exceeded");
+ if (Size <= Nfixed + Nfixed) {
+ return;
+ }
+ Item1 item1 = fmt_fuzzer::assignFromBuf<Item1>(Data);
+ Data += Nfixed;
+ Size -= Nfixed;
+
+ Item2 item2 = fmt_fuzzer::assignFromBuf<Item2>(Data);
+ Data += Nfixed;
+ Size -= Nfixed;
+
+ auto fmtstring = fmt::string_view(fmt_fuzzer::as_chars(Data), Size);
+
+#if FMT_FUZZ_FORMAT_TO_STRING
+ std::string message = fmt::format(fmtstring, item1, item2);
+#else
+ fmt::memory_buffer message;
+ fmt::format_to(message, fmtstring, item1, item2);
+#endif
+}
+
+// for dynamic dispatching to an explicit instantiation
+template <typename Callback> void invoke(int index, Callback callback) {
+ switch (index) {
+ case 0:
+ callback(bool{});
+ break;
+ case 1:
+ callback(char{});
+ break;
+ case 2:
+ using sc = signed char;
+ callback(sc{});
+ break;
+ case 3:
+ using uc = unsigned char;
+ callback(uc{});
+ break;
+ case 4:
+ callback(short{});
+ break;
+ case 5:
+ using us = unsigned short;
+ callback(us{});
+ break;
+ case 6:
+ callback(int{});
+ break;
+ case 7:
+ callback(unsigned{});
+ break;
+ case 8:
+ callback(long{});
+ break;
+ case 9:
+ using ul = unsigned long;
+ callback(ul{});
+ break;
+ case 10:
+ callback(float{});
+ break;
+ case 11:
+ callback(double{});
+ break;
+ case 12:
+ using LD = long double;
+ callback(LD{});
+ break;
+ case 13:
+ using ptr = void*;
+ callback(ptr{});
+ break;
+ }
+}
+
+extern "C" int LLVMFuzzerTestOneInput(const uint8_t* Data, std::size_t Size) {
+ if (Size <= 3) {
+ return 0;
+ }
+
+ // switch types depending on the first byte of the input
+ const auto first = Data[0] & 0x0F;
+ const auto second = (Data[0] & 0xF0) >> 4;
+ Data++;
+ Size--;
+
+ auto outer = [=](auto param1) {
+ auto inner = [=](auto param2) {
+ invoke_fmt<decltype(param1), decltype(param2)>(Data, Size);
+ };
+ invoke(second, inner);
+ };
+
+ try {
+ invoke(first, outer);
+ } catch (std::exception& /*e*/) {
+ }
+ return 0;
+}
diff --git a/test/fuzzing/two_args.cpp b/test/fuzzing/two_args.cpp
new file mode 100644
index 0000000..72b035c
--- /dev/null
+++ b/test/fuzzing/two_args.cpp
@@ -0,0 +1,112 @@
+// Copyright (c) 2019, Paul Dreik
+// License: see LICENSE.rst in the fmt root directory
+#include <fmt/format.h>
+#include <cstdint>
+#include <stdexcept>
+#include <type_traits>
+
+#include "fuzzer_common.h"
+
+constexpr auto Nfixed = fmt_fuzzer::Nfixed;
+
+template <typename Item1, typename Item2>
+void invoke_fmt(const uint8_t* Data, std::size_t Size) {
+ constexpr auto N1 = sizeof(Item1);
+ constexpr auto N2 = sizeof(Item2);
+ static_assert(N1 <= Nfixed, "size1 exceeded");
+ static_assert(N2 <= Nfixed, "size2 exceeded");
+ if (Size <= Nfixed + Nfixed) {
+ return;
+ }
+ const Item1 item1 = fmt_fuzzer::assignFromBuf<Item1>(Data);
+ Data += Nfixed;
+ Size -= Nfixed;
+
+ const Item2 item2 = fmt_fuzzer::assignFromBuf<Item2>(Data);
+ Data += Nfixed;
+ Size -= Nfixed;
+
+ auto fmtstring = fmt::string_view(fmt_fuzzer::as_chars(Data), Size);
+
+#if FMT_FUZZ_FORMAT_TO_STRING
+ std::string message = fmt::format(fmtstring, item1, item2);
+#else
+ fmt::memory_buffer message;
+ fmt::format_to(message, fmtstring, item1, item2);
+#endif
+}
+
+// for dynamic dispatching to an explicit instantiation
+template <typename Callback> void invoke(int index, Callback callback) {
+ switch (index) {
+ case 0:
+ callback(bool{});
+ break;
+ case 1:
+ callback(char{});
+ break;
+ case 2:
+ using sc = signed char;
+ callback(sc{});
+ break;
+ case 3:
+ using uc = unsigned char;
+ callback(uc{});
+ break;
+ case 4:
+ callback(short{});
+ break;
+ case 5:
+ using us = unsigned short;
+ callback(us{});
+ break;
+ case 6:
+ callback(int{});
+ break;
+ case 7:
+ callback(unsigned{});
+ break;
+ case 8:
+ callback(long{});
+ break;
+ case 9:
+ using ul = unsigned long;
+ callback(ul{});
+ break;
+ case 10:
+ callback(float{});
+ break;
+ case 11:
+ callback(double{});
+ break;
+ case 12:
+ using LD = long double;
+ callback(LD{});
+ break;
+ }
+}
+
+extern "C" int LLVMFuzzerTestOneInput(const uint8_t* Data, std::size_t Size) {
+ if (Size <= 3) {
+ return 0;
+ }
+
+ // switch types depending on the first byte of the input
+ const auto first = Data[0] & 0x0F;
+ const auto second = (Data[0] & 0xF0) >> 4;
+ Data++;
+ Size--;
+
+ auto outer = [=](auto param1) {
+ auto inner = [=](auto param2) {
+ invoke_fmt<decltype(param1), decltype(param2)>(Data, Size);
+ };
+ invoke(second, inner);
+ };
+
+ try {
+ invoke(first, outer);
+ } catch (std::exception& /*e*/) {
+ }
+ return 0;
+}
diff --git a/test/gmock-gtest-all.cc b/test/gmock-gtest-all.cc
index 7dca684..980cc60 100644
--- a/test/gmock-gtest-all.cc
+++ b/test/gmock-gtest-all.cc
@@ -107,8 +107,7 @@
// (e.g. frameworks built on top of Google Test).
#ifndef GTEST_INCLUDE_GTEST_GTEST_SPI_H_
-#define GTEST_INCLUDE_GTEST_GTEST_SPI_H_
-
+# define GTEST_INCLUDE_GTEST_GTEST_SPI_H_
namespace testing {
@@ -149,6 +148,7 @@
// This method is from the TestPartResultReporterInterface
// interface.
virtual void ReportTestPartResult(const TestPartResult& result);
+
private:
void Init();
@@ -170,9 +170,9 @@
public:
// The constructor remembers the arguments.
SingleFailureChecker(const TestPartResultArray* results,
- TestPartResult::Type type,
- const string& substr);
+ TestPartResult::Type type, const string& substr);
~SingleFailureChecker();
+
private:
const TestPartResultArray* const results_;
const TestPartResult::Type type_;
@@ -208,39 +208,43 @@
// helper macro, due to some peculiarity in how the preprocessor
// works. The AcceptsMacroThatExpandsToUnprotectedComma test in
// gtest_unittest.cc will fail to compile if we do that.
-#define EXPECT_FATAL_FAILURE(statement, substr) \
- do { \
- class GTestExpectFatalFailureHelper {\
- public:\
- static void Execute() { statement; }\
- };\
- ::testing::TestPartResultArray gtest_failures;\
- ::testing::internal::SingleFailureChecker gtest_checker(\
- >est_failures, ::testing::TestPartResult::kFatalFailure, (substr));\
- {\
- ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\
- ::testing::ScopedFakeTestPartResultReporter:: \
- INTERCEPT_ONLY_CURRENT_THREAD, >est_failures);\
- GTestExpectFatalFailureHelper::Execute();\
- }\
- } while (::testing::internal::AlwaysFalse())
+# define EXPECT_FATAL_FAILURE(statement, substr) \
+ do { \
+ class GTestExpectFatalFailureHelper { \
+ public: \
+ static void Execute() { statement; } \
+ }; \
+ ::testing::TestPartResultArray gtest_failures; \
+ ::testing::internal::SingleFailureChecker gtest_checker( \
+ >est_failures, ::testing::TestPartResult::kFatalFailure, \
+ (substr)); \
+ { \
+ ::testing::ScopedFakeTestPartResultReporter gtest_reporter( \
+ ::testing::ScopedFakeTestPartResultReporter:: \
+ INTERCEPT_ONLY_CURRENT_THREAD, \
+ >est_failures); \
+ GTestExpectFatalFailureHelper::Execute(); \
+ } \
+ } while (::testing::internal::AlwaysFalse())
-#define EXPECT_FATAL_FAILURE_ON_ALL_THREADS(statement, substr) \
- do { \
- class GTestExpectFatalFailureHelper {\
- public:\
- static void Execute() { statement; }\
- };\
- ::testing::TestPartResultArray gtest_failures;\
- ::testing::internal::SingleFailureChecker gtest_checker(\
- >est_failures, ::testing::TestPartResult::kFatalFailure, (substr));\
- {\
- ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\
- ::testing::ScopedFakeTestPartResultReporter:: \
- INTERCEPT_ALL_THREADS, >est_failures);\
- GTestExpectFatalFailureHelper::Execute();\
- }\
- } while (::testing::internal::AlwaysFalse())
+# define EXPECT_FATAL_FAILURE_ON_ALL_THREADS(statement, substr) \
+ do { \
+ class GTestExpectFatalFailureHelper { \
+ public: \
+ static void Execute() { statement; } \
+ }; \
+ ::testing::TestPartResultArray gtest_failures; \
+ ::testing::internal::SingleFailureChecker gtest_checker( \
+ >est_failures, ::testing::TestPartResult::kFatalFailure, \
+ (substr)); \
+ { \
+ ::testing::ScopedFakeTestPartResultReporter gtest_reporter( \
+ ::testing::ScopedFakeTestPartResultReporter:: \
+ INTERCEPT_ALL_THREADS, \
+ >est_failures); \
+ GTestExpectFatalFailureHelper::Execute(); \
+ } \
+ } while (::testing::internal::AlwaysFalse())
// A macro for testing Google Test assertions or code that's expected to
// generate Google Test non-fatal failures. It asserts that the given
@@ -274,33 +278,39 @@
// instead of
// GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement)
// to avoid an MSVC warning on unreachable code.
-#define EXPECT_NONFATAL_FAILURE(statement, substr) \
- do {\
- ::testing::TestPartResultArray gtest_failures;\
- ::testing::internal::SingleFailureChecker gtest_checker(\
- >est_failures, ::testing::TestPartResult::kNonFatalFailure, \
- (substr));\
- {\
- ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\
- ::testing::ScopedFakeTestPartResultReporter:: \
- INTERCEPT_ONLY_CURRENT_THREAD, >est_failures);\
- if (::testing::internal::AlwaysTrue()) { statement; }\
- }\
- } while (::testing::internal::AlwaysFalse())
+# define EXPECT_NONFATAL_FAILURE(statement, substr) \
+ do { \
+ ::testing::TestPartResultArray gtest_failures; \
+ ::testing::internal::SingleFailureChecker gtest_checker( \
+ >est_failures, ::testing::TestPartResult::kNonFatalFailure, \
+ (substr)); \
+ { \
+ ::testing::ScopedFakeTestPartResultReporter gtest_reporter( \
+ ::testing::ScopedFakeTestPartResultReporter:: \
+ INTERCEPT_ONLY_CURRENT_THREAD, \
+ >est_failures); \
+ if (::testing::internal::AlwaysTrue()) { \
+ statement; \
+ } \
+ } \
+ } while (::testing::internal::AlwaysFalse())
-#define EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(statement, substr) \
- do {\
- ::testing::TestPartResultArray gtest_failures;\
- ::testing::internal::SingleFailureChecker gtest_checker(\
- >est_failures, ::testing::TestPartResult::kNonFatalFailure, \
- (substr));\
- {\
- ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\
- ::testing::ScopedFakeTestPartResultReporter::INTERCEPT_ALL_THREADS, \
- >est_failures);\
- if (::testing::internal::AlwaysTrue()) { statement; }\
- }\
- } while (::testing::internal::AlwaysFalse())
+# define EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(statement, substr) \
+ do { \
+ ::testing::TestPartResultArray gtest_failures; \
+ ::testing::internal::SingleFailureChecker gtest_checker( \
+ >est_failures, ::testing::TestPartResult::kNonFatalFailure, \
+ (substr)); \
+ { \
+ ::testing::ScopedFakeTestPartResultReporter gtest_reporter( \
+ ::testing::ScopedFakeTestPartResultReporter:: \
+ INTERCEPT_ALL_THREADS, \
+ >est_failures); \
+ if (::testing::internal::AlwaysTrue()) { \
+ statement; \
+ } \
+ } \
+ } while (::testing::internal::AlwaysFalse())
#endif // GTEST_INCLUDE_GTEST_GTEST_SPI_H_
@@ -324,76 +334,76 @@
// TODO(kenton@google.com): Use autoconf to detect availability of
// gettimeofday().
-# define GTEST_HAS_GETTIMEOFDAY_ 1
+# define GTEST_HAS_GETTIMEOFDAY_ 1
-# include <fcntl.h> // NOLINT
-# include <limits.h> // NOLINT
-# include <sched.h> // NOLINT
+# include <fcntl.h> // NOLINT
+# include <limits.h> // NOLINT
+# include <sched.h> // NOLINT
// Declares vsnprintf(). This header is not available on Windows.
-# include <strings.h> // NOLINT
-# include <sys/mman.h> // NOLINT
-# include <sys/time.h> // NOLINT
-# include <unistd.h> // NOLINT
-# include <string>
+# include <strings.h> // NOLINT
+# include <sys/mman.h> // NOLINT
+# include <sys/time.h> // NOLINT
+# include <unistd.h> // NOLINT
+# include <string>
#elif GTEST_OS_SYMBIAN
-# define GTEST_HAS_GETTIMEOFDAY_ 1
-# include <sys/time.h> // NOLINT
+# define GTEST_HAS_GETTIMEOFDAY_ 1
+# include <sys/time.h> // NOLINT
#elif GTEST_OS_ZOS
-# define GTEST_HAS_GETTIMEOFDAY_ 1
-# include <sys/time.h> // NOLINT
+# define GTEST_HAS_GETTIMEOFDAY_ 1
+# include <sys/time.h> // NOLINT
// On z/OS we additionally need strings.h for strcasecmp.
-# include <strings.h> // NOLINT
+# include <strings.h> // NOLINT
#elif GTEST_OS_WINDOWS_MOBILE // We are on Windows CE.
-# include <windows.h> // NOLINT
+# include <windows.h> // NOLINT
#elif GTEST_OS_WINDOWS // We are on Windows proper.
-# include <io.h> // NOLINT
-# include <sys/timeb.h> // NOLINT
-# include <sys/types.h> // NOLINT
-# include <sys/stat.h> // NOLINT
+# include <io.h> // NOLINT
+# include <sys/stat.h> // NOLINT
+# include <sys/timeb.h> // NOLINT
+# include <sys/types.h> // NOLINT
-# if GTEST_OS_WINDOWS_MINGW
+# if GTEST_OS_WINDOWS_MINGW
// MinGW has gettimeofday() but not _ftime64().
// TODO(kenton@google.com): Use autoconf to detect availability of
// gettimeofday().
// TODO(kenton@google.com): There are other ways to get the time on
// Windows, like GetTickCount() or GetSystemTimeAsFileTime(). MinGW
// supports these. consider using them instead.
-# define GTEST_HAS_GETTIMEOFDAY_ 1
-# include <sys/time.h> // NOLINT
-# endif // GTEST_OS_WINDOWS_MINGW
+# define GTEST_HAS_GETTIMEOFDAY_ 1
+# include <sys/time.h> // NOLINT
+# endif // GTEST_OS_WINDOWS_MINGW
// cpplint thinks that the header is already included, so we want to
// silence it.
-# include <windows.h> // NOLINT
+# include <windows.h> // NOLINT
#else
// Assume other platforms have gettimeofday().
// TODO(kenton@google.com): Use autoconf to detect availability of
// gettimeofday().
-# define GTEST_HAS_GETTIMEOFDAY_ 1
+# define GTEST_HAS_GETTIMEOFDAY_ 1
// cpplint thinks that the header is already included, so we want to
// silence it.
-# include <sys/time.h> // NOLINT
-# include <unistd.h> // NOLINT
+# include <sys/time.h> // NOLINT
+# include <unistd.h> // NOLINT
#endif // GTEST_OS_LINUX
#if GTEST_HAS_EXCEPTIONS
-# include <stdexcept>
+# include <stdexcept>
#endif
#if GTEST_CAN_STREAM_RESULTS_
-# include <arpa/inet.h> // NOLINT
-# include <netdb.h> // NOLINT
+# include <arpa/inet.h> // NOLINT
+# include <netdb.h> // NOLINT
#endif
// Indicates that this translation unit is part of Google Test's
@@ -439,37 +449,36 @@
// DO NOT #INCLUDE IT IN A USER PROGRAM.
#ifndef GTEST_SRC_GTEST_INTERNAL_INL_H_
-#define GTEST_SRC_GTEST_INTERNAL_INL_H_
+# define GTEST_SRC_GTEST_INTERNAL_INL_H_
// GTEST_IMPLEMENTATION_ is defined to 1 iff the current translation unit is
// part of Google Test's implementation; otherwise it's undefined.
-#if !GTEST_IMPLEMENTATION_
+# if !GTEST_IMPLEMENTATION_
// A user is trying to include this from his code - just say no.
-# error "gtest-internal-inl.h is part of Google Test's internal implementation."
-# error "It must not be included except by Google Test itself."
-#endif // GTEST_IMPLEMENTATION_
+# error \
+ "gtest-internal-inl.h is part of Google Test's internal implementation."
+# error "It must not be included except by Google Test itself."
+# endif // GTEST_IMPLEMENTATION_
-#ifndef _WIN32_WCE
-# include <errno.h>
-#endif // !_WIN32_WCE
-#include <stddef.h>
-#include <stdlib.h> // For strtoll/_strtoul64/malloc/free.
-#include <string.h> // For memmove.
+# ifndef _WIN32_WCE
+# include <errno.h>
+# endif // !_WIN32_WCE
+# include <stddef.h>
+# include <stdlib.h> // For strtoll/_strtoul64/malloc/free.
+# include <string.h> // For memmove.
-#include <algorithm>
-#include <string>
-#include <vector>
+# include <algorithm>
+# include <string>
+# include <vector>
+# if GTEST_CAN_STREAM_RESULTS_
+# include <arpa/inet.h> // NOLINT
+# include <netdb.h> // NOLINT
+# endif
-#if GTEST_CAN_STREAM_RESULTS_
-# include <arpa/inet.h> // NOLINT
-# include <netdb.h> // NOLINT
-#endif
-
-#if GTEST_OS_WINDOWS
-# include <windows.h> // NOLINT
-#endif // GTEST_OS_WINDOWS
-
+# if GTEST_OS_WINDOWS
+# include <windows.h> // NOLINT
+# endif // GTEST_OS_WINDOWS
namespace testing {
@@ -528,21 +537,21 @@
//
// On success, stores the value of the flag in *value, and returns
// true. On failure, returns false without changing *value.
-GTEST_API_ bool ParseInt32Flag(
- const char* str, const char* flag, Int32* value);
+GTEST_API_ bool ParseInt32Flag(const char* str, const char* flag, Int32* value);
// Returns a random seed in range [1, kMaxRandomSeed] based on the
// given --gtest_random_seed flag value.
inline int GetRandomSeedFromFlag(Int32 random_seed_flag) {
- const unsigned int raw_seed = (random_seed_flag == 0) ?
- static_cast<unsigned int>(GetTimeInMillis()) :
- static_cast<unsigned int>(random_seed_flag);
+ const unsigned int raw_seed =
+ (random_seed_flag == 0) ? static_cast<unsigned int>(GetTimeInMillis())
+ : static_cast<unsigned int>(random_seed_flag);
// Normalizes the actual seed to range [1, kMaxRandomSeed] such that
// it's easy to type.
const int normalized_seed =
static_cast<int>((raw_seed - 1U) %
- static_cast<unsigned int>(kMaxRandomSeed)) + 1;
+ static_cast<unsigned int>(kMaxRandomSeed)) +
+ 1;
return normalized_seed;
}
@@ -672,8 +681,8 @@
// returns true iff the test should be run on this shard. The test id is
// some arbitrary but unique non-negative integer assigned to each test
// method. Assumes that 0 <= shard_index < total_shards.
-GTEST_API_ bool ShouldRunTestOnShard(
- int total_shards, int shard_index, int test_id);
+GTEST_API_ bool ShouldRunTestOnShard(int total_shards, int shard_index,
+ int test_id);
// STL container utilities.
@@ -685,8 +694,7 @@
// Solaris has a non-standard signature.
int count = 0;
for (typename Container::const_iterator it = c.begin(); it != c.end(); ++it) {
- if (predicate(*it))
- ++count;
+ if (predicate(*it)) ++count;
}
return count;
}
@@ -736,10 +744,7 @@
// A function for deleting an object. Handy for being used as a
// functor.
-template <typename T>
-static void Delete(T* x) {
- delete x;
-}
+template <typename T> static void Delete(T* x) { delete x; }
// A predicate that checks the key of a TestProperty against a known key.
//
@@ -789,21 +794,21 @@
//
// This recursive algorithm isn't very efficient, but is clear and
// works well enough for matching test names, which are short.
- static bool PatternMatchesString(const char *pattern, const char *str);
+ static bool PatternMatchesString(const char* pattern, const char* str);
// Returns true iff the user-specified filter matches the test case
// name and the test name.
- static bool FilterMatchesTest(const std::string &test_case_name,
- const std::string &test_name);
+ static bool FilterMatchesTest(const std::string& test_case_name,
+ const std::string& test_name);
-#if GTEST_OS_WINDOWS
+# if GTEST_OS_WINDOWS
// Function for supporting the gtest_catch_exception flag.
// Returns EXCEPTION_EXECUTE_HANDLER if Google Test should handle the
// given SEH exception, or EXCEPTION_CONTINUE_SEARCH otherwise.
// This function is useful as an __except condition.
static int GTestShouldProcessSEH(DWORD exception_code);
-#endif // GTEST_OS_WINDOWS
+# endif // GTEST_OS_WINDOWS
// Returns true if "name" matches the ':' separated list of glob-style
// filters in "filter".
@@ -873,7 +878,7 @@
// This is the default global test part result reporter used in UnitTestImpl.
// This class should only be used by UnitTestImpl.
class DefaultGlobalTestPartResultReporter
- : public TestPartResultReporterInterface {
+ : public TestPartResultReporterInterface {
public:
explicit DefaultGlobalTestPartResultReporter(UnitTestImpl* unit_test);
// Implements the TestPartResultReporterInterface. Reports the test part
@@ -1040,8 +1045,7 @@
// this is not a typed or a type-parameterized test.
// set_up_tc: pointer to the function that sets up the test case
// tear_down_tc: pointer to the function that tears down the test case
- TestCase* GetTestCase(const char* test_case_name,
- const char* type_param,
+ TestCase* GetTestCase(const char* test_case_name, const char* type_param,
Test::SetUpTestCaseFunc set_up_tc,
Test::TearDownTestCaseFunc tear_down_tc);
@@ -1068,19 +1072,18 @@
<< "Failed to get the current working directory.";
}
- GetTestCase(test_info->test_case_name(),
- test_info->type_param(),
- set_up_tc,
- tear_down_tc)->AddTestInfo(test_info);
+ GetTestCase(test_info->test_case_name(), test_info->type_param(), set_up_tc,
+ tear_down_tc)
+ ->AddTestInfo(test_info);
}
-#if GTEST_HAS_PARAM_TEST
+# if GTEST_HAS_PARAM_TEST
// Returns ParameterizedTestCaseRegistry object used to keep track of
// value-parameterized tests and instantiate and register them.
internal::ParameterizedTestCaseRegistry& parameterized_test_registry() {
return parameterized_test_registry_;
}
-#endif // GTEST_HAS_PARAM_TEST
+# endif // GTEST_HAS_PARAM_TEST
// Sets the TestCase object for the test that's currently running.
void set_current_test_case(TestCase* a_current_test_case) {
@@ -1114,9 +1117,7 @@
}
// Clears the results of ad-hoc test assertions.
- void ClearAdHocTestResult() {
- ad_hoc_test_result_.Clear();
- }
+ void ClearAdHocTestResult() { ad_hoc_test_result_.Clear(); }
// Adds a TestProperty to the current TestResult object when invoked in a
// context of a test or a test case, or to the global property set. If the
@@ -1124,10 +1125,7 @@
// updated.
void RecordProperty(const TestProperty& test_property);
- enum ReactionToSharding {
- HONOR_SHARDING_PROTOCOL,
- IGNORE_SHARDING_PROTOCOL
- };
+ enum ReactionToSharding { HONOR_SHARDING_PROTOCOL, IGNORE_SHARDING_PROTOCOL };
// Matches the full name of each test against the user-specified
// filter to decide whether the test should run, then records the
@@ -1156,7 +1154,7 @@
return gtest_trace_stack_.get();
}
-#if GTEST_HAS_DEATH_TEST
+# if GTEST_HAS_DEATH_TEST
void InitDeathTestSubprocessControlInfo() {
internal_run_death_test_flag_.reset(ParseInternalRunDeathTestFlag());
}
@@ -1176,17 +1174,17 @@
void SuppressTestEventsIfInSubprocess();
friend class ReplaceDeathTestFactory;
-#endif // GTEST_HAS_DEATH_TEST
+# endif // GTEST_HAS_DEATH_TEST
// Initializes the event listener performing XML output as specified by
// UnitTestOptions. Must not be called before InitGoogleTest.
void ConfigureXmlOutput();
-#if GTEST_CAN_STREAM_RESULTS_
+# if GTEST_CAN_STREAM_RESULTS_
// Initializes the event listener for streaming test results to a socket.
// Must not be called before InitGoogleTest.
void ConfigureStreamingOutput();
-#endif
+# endif
// Performs initialization dependent upon flag values obtained in
// ParseGoogleTestFlagsOnly. Is called from InitGoogleTest after the call to
@@ -1255,14 +1253,14 @@
// shuffled order.
std::vector<int> test_case_indices_;
-#if GTEST_HAS_PARAM_TEST
+# if GTEST_HAS_PARAM_TEST
// ParameterizedTestRegistry object used to register value-parameterized
// tests.
internal::ParameterizedTestCaseRegistry parameterized_test_registry_;
// Indicates whether RegisterParameterizedTests() has been called already.
bool parameterized_tests_registered_;
-#endif // GTEST_HAS_PARAM_TEST
+# endif // GTEST_HAS_PARAM_TEST
// Index of the last death test case registered. Initially -1.
int last_death_test_case_;
@@ -1315,12 +1313,12 @@
// How long the test took to run, in milliseconds.
TimeInMillis elapsed_time_;
-#if GTEST_HAS_DEATH_TEST
+# if GTEST_HAS_DEATH_TEST
// The decomposed components of the gtest_internal_run_death_test flag,
// parsed when RUN_ALL_TESTS is called.
internal::scoped_ptr<InternalRunDeathTestFlag> internal_run_death_test_flag_;
internal::scoped_ptr<internal::DeathTestFactory> death_test_factory_;
-#endif // GTEST_HAS_DEATH_TEST
+# endif // GTEST_HAS_DEATH_TEST
// A per-thread stack of traces created by the SCOPED_TRACE() macro.
internal::ThreadLocal<std::vector<TraceInfo> > gtest_trace_stack_;
@@ -1338,7 +1336,7 @@
return UnitTest::GetInstance()->impl();
}
-#if GTEST_USES_SIMPLE_RE
+# if GTEST_USES_SIMPLE_RE
// Internal helper functions for implementing the simple regular
// expression matcher.
@@ -1352,24 +1350,25 @@
GTEST_API_ bool AtomMatchesChar(bool escaped, char pattern, char ch);
GTEST_API_ bool ValidateRegex(const char* regex);
GTEST_API_ bool MatchRegexAtHead(const char* regex, const char* str);
-GTEST_API_ bool MatchRepetitionAndRegexAtHead(
- bool escaped, char ch, char repeat, const char* regex, const char* str);
+GTEST_API_ bool MatchRepetitionAndRegexAtHead(bool escaped, char ch,
+ char repeat, const char* regex,
+ const char* str);
GTEST_API_ bool MatchRegexAnywhere(const char* regex, const char* str);
-#endif // GTEST_USES_SIMPLE_RE
+# endif // GTEST_USES_SIMPLE_RE
// Parses the command line for Google Test flags, without initializing
// other parts of Google Test.
GTEST_API_ void ParseGoogleTestFlagsOnly(int* argc, char** argv);
GTEST_API_ void ParseGoogleTestFlagsOnly(int* argc, wchar_t** argv);
-#if GTEST_HAS_DEATH_TEST
+# if GTEST_HAS_DEATH_TEST
// Returns the message describing the last system error, regardless of the
// platform.
GTEST_API_ std::string GetLastErrnoDescription();
-# if GTEST_OS_WINDOWS
+# if GTEST_OS_WINDOWS
// Provides leak-safe Windows kernel handle ownership.
class AutoHandle {
public:
@@ -1382,8 +1381,7 @@
void Reset() { Reset(INVALID_HANDLE_VALUE); }
void Reset(HANDLE handle) {
if (handle != handle_) {
- if (handle_ != INVALID_HANDLE_VALUE)
- ::CloseHandle(handle_);
+ if (handle_ != INVALID_HANDLE_VALUE) ::CloseHandle(handle_);
handle_ = handle;
}
}
@@ -1393,7 +1391,7 @@
GTEST_DISALLOW_COPY_AND_ASSIGN_(AutoHandle);
};
-# endif // GTEST_OS_WINDOWS
+# endif // GTEST_OS_WINDOWS
// Attempts to parse a string into a positive integer pointed to by the
// number parameter. Returns true if that is possible.
@@ -1413,18 +1411,18 @@
// BiggestConvertible is the largest integer type that system-provided
// string-to-number conversion routines can return.
-# if GTEST_OS_WINDOWS && !defined(__GNUC__)
+# if GTEST_OS_WINDOWS && !defined(__GNUC__)
// MSVC and C++ Builder define __int64 instead of the standard long long.
typedef unsigned __int64 BiggestConvertible;
const BiggestConvertible parsed = _strtoui64(str.c_str(), &end, 10);
-# else
+# else
typedef unsigned long long BiggestConvertible; // NOLINT
const BiggestConvertible parsed = strtoull(str.c_str(), &end, 10);
-# endif // GTEST_OS_WINDOWS && !defined(__GNUC__)
+# endif // GTEST_OS_WINDOWS && !defined(__GNUC__)
const bool parse_success = *end == '\0' && errno == 0;
@@ -1439,7 +1437,7 @@
}
return false;
}
-#endif // GTEST_HAS_DEATH_TEST
+# endif // GTEST_HAS_DEATH_TEST
// TestResult contains some private methods that should be hidden from
// Google Test user but are required for testing. This class allow our tests
@@ -1465,7 +1463,7 @@
}
};
-#if GTEST_CAN_STREAM_RESULTS_
+# if GTEST_CAN_STREAM_RESULTS_
// Streams test results to the given port on the given host machine.
class StreamingListener : public EmptyTestEventListener {
@@ -1482,9 +1480,7 @@
virtual void CloseConnection() {}
// Sends a string and a newline to the socket.
- void SendLn(const string& message) {
- Send(message + "\n");
- }
+ void SendLn(const string& message) { Send(message + "\n"); }
};
// Concrete class for actually writing strings to a socket.
@@ -1496,8 +1492,7 @@
}
virtual ~SocketWriter() {
- if (sockfd_ != -1)
- CloseConnection();
+ if (sockfd_ != -1) CloseConnection();
}
// Sends a string to the socket.
@@ -1507,9 +1502,8 @@
const int len = static_cast<int>(message.length());
if (write(sockfd_, message.c_str(), len) != len) {
- GTEST_LOG_(WARNING)
- << "stream_result_to: failed to stream to "
- << host_name_ << ":" << port_num_;
+ GTEST_LOG_(WARNING) << "stream_result_to: failed to stream to "
+ << host_name_ << ":" << port_num_;
}
}
@@ -1537,10 +1531,14 @@
static string UrlEncode(const char* str);
StreamingListener(const string& host, const string& port)
- : socket_writer_(new SocketWriter(host, port)) { Start(); }
+ : socket_writer_(new SocketWriter(host, port)) {
+ Start();
+ }
explicit StreamingListener(AbstractSocketWriter* socket_writer)
- : socket_writer_(socket_writer) { Start(); }
+ : socket_writer_(socket_writer) {
+ Start();
+ }
void OnTestProgramStart(const UnitTest& /* unit_test */) {
SendLn("event=TestProgramStart");
@@ -1561,9 +1559,9 @@
}
void OnTestIterationEnd(const UnitTest& unit_test, int /* iteration */) {
- SendLn("event=TestIterationEnd&passed=" +
- FormatBool(unit_test.Passed()) + "&elapsed_time=" +
- StreamableToString(unit_test.elapsed_time()) + "ms");
+ SendLn("event=TestIterationEnd&passed=" + FormatBool(unit_test.Passed()) +
+ "&elapsed_time=" + StreamableToString(unit_test.elapsed_time()) +
+ "ms");
}
void OnTestCaseStart(const TestCase& test_case) {
@@ -1571,9 +1569,9 @@
}
void OnTestCaseEnd(const TestCase& test_case) {
- SendLn("event=TestCaseEnd&passed=" + FormatBool(test_case.Passed())
- + "&elapsed_time=" + StreamableToString(test_case.elapsed_time())
- + "ms");
+ SendLn("event=TestCaseEnd&passed=" + FormatBool(test_case.Passed()) +
+ "&elapsed_time=" + StreamableToString(test_case.elapsed_time()) +
+ "ms");
}
void OnTestStart(const TestInfo& test_info) {
@@ -1582,15 +1580,13 @@
void OnTestEnd(const TestInfo& test_info) {
SendLn("event=TestEnd&passed=" +
- FormatBool((test_info.result())->Passed()) +
- "&elapsed_time=" +
+ FormatBool((test_info.result())->Passed()) + "&elapsed_time=" +
StreamableToString((test_info.result())->elapsed_time()) + "ms");
}
void OnTestPartResult(const TestPartResult& test_part_result) {
const char* file_name = test_part_result.file_name();
- if (file_name == NULL)
- file_name = "";
+ if (file_name == NULL) file_name = "";
SendLn("event=TestPartResult&file=" + UrlEncode(file_name) +
"&line=" + StreamableToString(test_part_result.line_number()) +
"&message=" + UrlEncode(test_part_result.message()));
@@ -1611,7 +1607,7 @@
GTEST_DISALLOW_COPY_AND_ASSIGN_(StreamingListener);
}; // class StreamingListener
-#endif // GTEST_CAN_STREAM_RESULTS_
+# endif // GTEST_CAN_STREAM_RESULTS_
} // namespace internal
} // namespace testing
@@ -1620,7 +1616,7 @@
#undef GTEST_IMPLEMENTATION_
#if GTEST_OS_WINDOWS
-# define vsnprintf _vsnprintf
+# define vsnprintf _vsnprintf
#endif // GTEST_OS_WINDOWS
namespace testing {
@@ -1666,9 +1662,7 @@
} // namespace internal
-static const char* GetDefaultFilter() {
- return kUniversalFilter;
-}
+static const char* GetDefaultFilter() { return kUniversalFilter; }
GTEST_DEFINE_bool_(
also_run_disabled_tests,
@@ -1676,39 +1670,33 @@
"Run disabled tests too, in addition to the tests normally being run.");
GTEST_DEFINE_bool_(
- break_on_failure,
- internal::BoolFromGTestEnv("break_on_failure", false),
+ break_on_failure, internal::BoolFromGTestEnv("break_on_failure", false),
"True iff a failed assertion should be a debugger break-point.");
-GTEST_DEFINE_bool_(
- catch_exceptions,
- internal::BoolFromGTestEnv("catch_exceptions", true),
- "True iff " GTEST_NAME_
- " should catch exceptions and treat them as test failures.");
+GTEST_DEFINE_bool_(catch_exceptions,
+ internal::BoolFromGTestEnv("catch_exceptions", true),
+ "True iff " GTEST_NAME_
+ " should catch exceptions and treat them as test failures.");
GTEST_DEFINE_string_(
- color,
- internal::StringFromGTestEnv("color", "auto"),
+ color, internal::StringFromGTestEnv("color", "auto"),
"Whether to use colors in the output. Valid values: yes, no, "
"and auto. 'auto' means to use colors if the output is "
"being sent to a terminal and the TERM environment variable "
"is set to a terminal type that supports colors.");
GTEST_DEFINE_string_(
- filter,
- internal::StringFromGTestEnv("filter", GetDefaultFilter()),
+ filter, internal::StringFromGTestEnv("filter", GetDefaultFilter()),
"A colon-separated list of glob (not regex) patterns "
"for filtering the tests to run, optionally followed by a "
"'-' and a : separated list of negative patterns (tests to "
"exclude). A test is run if it matches one of the positive "
"patterns and does not match any of the negative patterns.");
-GTEST_DEFINE_bool_(list_tests, false,
- "List all tests without running them.");
+GTEST_DEFINE_bool_(list_tests, false, "List all tests without running them.");
GTEST_DEFINE_string_(
- output,
- internal::StringFromGTestEnv("output", ""),
+ output, internal::StringFromGTestEnv("output", ""),
"A format (currently must be \"xml\"), optionally followed "
"by a colon and an output file name or directory. A directory "
"is indicated by a trailing pathname separator. "
@@ -1718,34 +1706,28 @@
"executable's name and, if necessary, made unique by adding "
"digits.");
-GTEST_DEFINE_bool_(
- print_time,
- internal::BoolFromGTestEnv("print_time", true),
- "True iff " GTEST_NAME_
- " should display elapsed time in text output.");
+GTEST_DEFINE_bool_(print_time, internal::BoolFromGTestEnv("print_time", true),
+ "True iff " GTEST_NAME_
+ " should display elapsed time in text output.");
GTEST_DEFINE_int32_(
- random_seed,
- internal::Int32FromGTestEnv("random_seed", 0),
+ random_seed, internal::Int32FromGTestEnv("random_seed", 0),
"Random number seed to use when shuffling test orders. Must be in range "
"[1, 99999], or 0 to use a seed based on the current time.");
GTEST_DEFINE_int32_(
- repeat,
- internal::Int32FromGTestEnv("repeat", 1),
+ repeat, internal::Int32FromGTestEnv("repeat", 1),
"How many times to repeat each test. Specify a negative number "
"for repeating forever. Useful for shaking out flaky tests.");
-GTEST_DEFINE_bool_(
- show_internal_stack_frames, false,
- "True iff " GTEST_NAME_ " should include internal stack frames when "
- "printing test failure stack traces.");
+GTEST_DEFINE_bool_(show_internal_stack_frames, false,
+ "True iff " GTEST_NAME_
+ " should include internal stack frames when "
+ "printing test failure stack traces.");
-GTEST_DEFINE_bool_(
- shuffle,
- internal::BoolFromGTestEnv("shuffle", false),
- "True iff " GTEST_NAME_
- " should randomize tests' order on every run.");
+GTEST_DEFINE_bool_(shuffle, internal::BoolFromGTestEnv("shuffle", false),
+ "True iff " GTEST_NAME_
+ " should randomize tests' order on every run.");
GTEST_DEFINE_int32_(
stack_trace_depth,
@@ -1754,15 +1736,13 @@
"assertion fails. The valid range is 0 through 100, inclusive.");
GTEST_DEFINE_string_(
- stream_result_to,
- internal::StringFromGTestEnv("stream_result_to", ""),
+ stream_result_to, internal::StringFromGTestEnv("stream_result_to", ""),
"This flag specifies the host name and the port number on which to stream "
"test results. Example: \"localhost:555\". The flag is effective only on "
"Linux.");
GTEST_DEFINE_bool_(
- throw_on_failure,
- internal::BoolFromGTestEnv("throw_on_failure", false),
+ throw_on_failure, internal::BoolFromGTestEnv("throw_on_failure", false),
"When this flag is specified, a failed assertion will throw an exception "
"if exceptions are enabled or exit the program with a non-zero code "
"otherwise.");
@@ -1774,10 +1754,9 @@
// than kMaxRange.
UInt32 Random::Generate(UInt32 range) {
// These constants are the same as are used in glibc's rand(3).
- state_ = (1103515245U*state_ + 12345U) % kMaxRange;
+ state_ = (1103515245U * state_ + 12345U) % kMaxRange;
- GTEST_CHECK_(range > 0)
- << "Cannot generate a number in the range [0, 0).";
+ GTEST_CHECK_(range > 0) << "Cannot generate a number in the range [0, 0).";
GTEST_CHECK_(range <= kMaxRange)
<< "Generation of a number in [0, " << range << ") was requested, "
<< "but this can only generate numbers in [0, " << kMaxRange << ").";
@@ -1828,26 +1807,20 @@
}
// AssertHelper constructor.
-AssertHelper::AssertHelper(TestPartResult::Type type,
- const char* file,
- int line,
- const char* message)
- : data_(new AssertHelperData(type, file, line, message)) {
-}
+AssertHelper::AssertHelper(TestPartResult::Type type, const char* file,
+ int line, const char* message)
+ : data_(new AssertHelperData(type, file, line, message)) {}
-AssertHelper::~AssertHelper() {
- delete data_;
-}
+AssertHelper::~AssertHelper() { delete data_; }
// Message assignment, for assertion streaming support.
void AssertHelper::operator=(const Message& message) const {
- UnitTest::GetInstance()->
- AddTestPartResult(data_->type, data_->file, data_->line,
- AppendUserMessage(data_->message, message),
- UnitTest::GetInstance()->impl()
- ->CurrentOsStackTraceExceptTop(1)
- // Skips the stack frame for this function itself.
- ); // NOLINT
+ UnitTest::GetInstance()->AddTestPartResult(
+ data_->type, data_->file, data_->line,
+ AppendUserMessage(data_->message, message),
+ UnitTest::GetInstance()->impl()->CurrentOsStackTraceExceptTop(1)
+ // Skips the stack frame for this function itself.
+ ); // NOLINT
}
// Mutex for linked pointers.
@@ -1878,24 +1851,24 @@
if (gtest_output_flag == NULL) return std::string("");
const char* const colon = strchr(gtest_output_flag, ':');
- return (colon == NULL) ?
- std::string(gtest_output_flag) :
- std::string(gtest_output_flag, colon - gtest_output_flag);
+ return (colon == NULL)
+ ? std::string(gtest_output_flag)
+ : std::string(gtest_output_flag, colon - gtest_output_flag);
}
// Returns the name of the requested output file, or the default if none
// was explicitly specified.
std::string UnitTestOptions::GetAbsolutePathToOutputFile() {
const char* const gtest_output_flag = GTEST_FLAG(output).c_str();
- if (gtest_output_flag == NULL)
- return "";
+ if (gtest_output_flag == NULL) return "";
const char* const colon = strchr(gtest_output_flag, ':');
if (colon == NULL)
return internal::FilePath::ConcatPaths(
- internal::FilePath(
- UnitTest::GetInstance()->original_working_dir()),
- internal::FilePath(kDefaultOutputFile)).string();
+ internal::FilePath(
+ UnitTest::GetInstance()->original_working_dir()),
+ internal::FilePath(kDefaultOutputFile))
+ .string();
internal::FilePath output_name(colon + 1);
if (!output_name.IsAbsolutePath())
@@ -1907,8 +1880,7 @@
internal::FilePath(UnitTest::GetInstance()->original_working_dir()),
internal::FilePath(colon + 1));
- if (!output_name.IsDirectory())
- return output_name.string();
+ if (!output_name.IsDirectory()) return output_name.string();
internal::FilePath result(internal::FilePath::GenerateUniqueFileName(
output_name, internal::GetCurrentExecutableName(),
@@ -1921,26 +1893,25 @@
//
// This recursive algorithm isn't very efficient, but is clear and
// works well enough for matching test names, which are short.
-bool UnitTestOptions::PatternMatchesString(const char *pattern,
- const char *str) {
+bool UnitTestOptions::PatternMatchesString(const char* pattern,
+ const char* str) {
switch (*pattern) {
- case '\0':
- case ':': // Either ':' or '\0' marks the end of the pattern.
- return *str == '\0';
- case '?': // Matches any single character.
- return *str != '\0' && PatternMatchesString(pattern + 1, str + 1);
- case '*': // Matches any string (possibly empty) of characters.
- return (*str != '\0' && PatternMatchesString(pattern, str + 1)) ||
- PatternMatchesString(pattern + 1, str);
- default: // Non-special character. Matches itself.
- return *pattern == *str &&
- PatternMatchesString(pattern + 1, str + 1);
+ case '\0':
+ case ':': // Either ':' or '\0' marks the end of the pattern.
+ return *str == '\0';
+ case '?': // Matches any single character.
+ return *str != '\0' && PatternMatchesString(pattern + 1, str + 1);
+ case '*': // Matches any string (possibly empty) of characters.
+ return (*str != '\0' && PatternMatchesString(pattern, str + 1)) ||
+ PatternMatchesString(pattern + 1, str);
+ default: // Non-special character. Matches itself.
+ return *pattern == *str && PatternMatchesString(pattern + 1, str + 1);
}
}
-bool UnitTestOptions::MatchesFilter(
- const std::string& name, const char* filter) {
- const char *cur_pattern = filter;
+bool UnitTestOptions::MatchesFilter(const std::string& name,
+ const char* filter) {
+ const char* cur_pattern = filter;
for (;;) {
if (PatternMatchesString(cur_pattern, name.c_str())) {
return true;
@@ -1961,8 +1932,8 @@
// Returns true iff the user-specified filter matches the test case
// name and the test name.
-bool UnitTestOptions::FilterMatchesTest(const std::string &test_case_name,
- const std::string &test_name) {
+bool UnitTestOptions::FilterMatchesTest(const std::string& test_case_name,
+ const std::string& test_name) {
const std::string& full_name = test_case_name + "." + test_name.c_str();
// Split --gtest_filter at '-', if there is one, to separate into
@@ -2024,8 +1995,7 @@
// results. Intercepts only failures from the current thread.
ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter(
TestPartResultArray* result)
- : intercept_mode_(INTERCEPT_ONLY_CURRENT_THREAD),
- result_(result) {
+ : intercept_mode_(INTERCEPT_ONLY_CURRENT_THREAD), result_(result) {
Init();
}
@@ -2034,8 +2004,7 @@
// results.
ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter(
InterceptMode intercept_mode, TestPartResultArray* result)
- : intercept_mode_(intercept_mode),
- result_(result) {
+ : intercept_mode_(intercept_mode), result_(result) {
Init();
}
@@ -2079,9 +2048,7 @@
// from user test code. GetTestTypeId() is guaranteed to always
// return the same value, as it always calls GetTypeId<>() from the
// gtest.cc, which is within the Google Test framework.
-TypeId GetTestTypeId() {
- return GetTypeId<Test>();
-}
+TypeId GetTestTypeId() { return GetTypeId<Test>(); }
// The value of GetTestTypeId() as seen from within the Google Test
// library. This is solely for testing GetTestTypeId().
@@ -2094,11 +2061,10 @@
const char* /* type_expr */,
const char* /* substr_expr */,
const TestPartResultArray& results,
- TestPartResult::Type type,
- const string& substr) {
- const std::string expected(type == TestPartResult::kFatalFailure ?
- "1 fatal failure" :
- "1 non-fatal failure");
+ TestPartResult::Type type, const string& substr) {
+ const std::string expected(type == TestPartResult::kFatalFailure
+ ? "1 fatal failure"
+ : "1 non-fatal failure");
Message msg;
if (results.size() != 1) {
msg << "Expected: " << expected << "\n"
@@ -2117,10 +2083,10 @@
}
if (strstr(r.message(), substr.c_str()) == NULL) {
- return AssertionFailure() << "Expected: " << expected << " containing \""
- << substr << "\"\n"
- << " Actual:\n"
- << r;
+ return AssertionFailure()
+ << "Expected: " << expected << " containing \"" << substr << "\"\n"
+ << " Actual:\n"
+ << r;
}
return AssertionSuccess();
@@ -2129,13 +2095,10 @@
// The constructor of SingleFailureChecker remembers where to look up
// test part results, what type of failure we expect, and what
// substring the failure message should contain.
-SingleFailureChecker:: SingleFailureChecker(
- const TestPartResultArray* results,
- TestPartResult::Type type,
- const string& substr)
- : results_(results),
- type_(type),
- substr_(substr) {}
+SingleFailureChecker::SingleFailureChecker(const TestPartResultArray* results,
+ TestPartResult::Type type,
+ const string& substr)
+ : results_(results), type_(type), substr_(substr) {}
// The destructor of SingleFailureChecker verifies that the given
// TestPartResultArray contains exactly one failure that has the given
@@ -2146,7 +2109,8 @@
}
DefaultGlobalTestPartResultReporter::DefaultGlobalTestPartResultReporter(
- UnitTestImpl* unit_test) : unit_test_(unit_test) {}
+ UnitTestImpl* unit_test)
+ : unit_test_(unit_test) {}
void DefaultGlobalTestPartResultReporter::ReportTestPartResult(
const TestPartResult& result) {
@@ -2155,7 +2119,8 @@
}
DefaultPerThreadTestPartResultReporter::DefaultPerThreadTestPartResultReporter(
- UnitTestImpl* unit_test) : unit_test_(unit_test) {}
+ UnitTestImpl* unit_test)
+ : unit_test_(unit_test) {}
void DefaultPerThreadTestPartResultReporter::ReportTestPartResult(
const TestPartResult& result) {
@@ -2266,7 +2231,7 @@
// Difference between 1970-01-01 and 1601-01-01 in milliseconds.
// http://analogous.blogspot.com/2005/04/epoch.html
const TimeInMillis kJavaEpochToWinFileTimeDelta =
- static_cast<TimeInMillis>(116444736UL) * 100000UL;
+ static_cast<TimeInMillis>(116444736UL) * 100000UL;
const DWORD kTenthMicrosInMilliSecond = 10000;
SYSTEMTIME now_systime;
@@ -2279,28 +2244,28 @@
now_int64.LowPart = now_filetime.dwLowDateTime;
now_int64.HighPart = now_filetime.dwHighDateTime;
now_int64.QuadPart = (now_int64.QuadPart / kTenthMicrosInMilliSecond) -
- kJavaEpochToWinFileTimeDelta;
+ kJavaEpochToWinFileTimeDelta;
return now_int64.QuadPart;
}
return 0;
#elif GTEST_OS_WINDOWS && !GTEST_HAS_GETTIMEOFDAY_
__timeb64 now;
-# ifdef _MSC_VER
+# ifdef _MSC_VER
// MSVC 8 deprecates _ftime64(), so we want to suppress warning 4996
// (deprecated function) there.
// TODO(kenton@google.com): Use GetTickCount()? Or use
// SystemTimeToFileTime()
-# pragma warning(push) // Saves the current warning state.
-# pragma warning(disable:4996) // Temporarily disables warning 4996.
+# pragma warning(push) // Saves the current warning state.
+# pragma warning(disable : 4996) // Temporarily disables warning 4996.
_ftime64(&now);
-# pragma warning(pop) // Restores the warning state.
-# else
+# pragma warning(pop) // Restores the warning state.
+# else
_ftime64(&now);
-# endif // _MSC_VER
+# endif // _MSC_VER
return static_cast<TimeInMillis>(now.time) * 1000 + now.millitm;
#elif GTEST_HAS_GETTIMEOFDAY_
@@ -2308,7 +2273,7 @@
gettimeofday(&now, NULL);
return static_cast<TimeInMillis>(now.tv_sec) * 1000 + now.tv_usec / 1000;
#else
-# error "Don't know how to get the current time on your system."
+# error "Don't know how to get the current time on your system."
#endif
}
@@ -2325,11 +2290,9 @@
if (!ansi) return NULL;
const int length = strlen(ansi);
const int unicode_length =
- MultiByteToWideChar(CP_ACP, 0, ansi, length,
- NULL, 0);
+ MultiByteToWideChar(CP_ACP, 0, ansi, length, NULL, 0);
WCHAR* unicode = new WCHAR[unicode_length + 1];
- MultiByteToWideChar(CP_ACP, 0, ansi, length,
- unicode, unicode_length);
+ MultiByteToWideChar(CP_ACP, 0, ansi, length, unicode, unicode_length);
unicode[unicode_length] = 0;
return unicode;
}
@@ -2338,14 +2301,12 @@
// memory using new. The caller is responsible for deleting the return
// value using delete[]. Returns the ANSI string, or NULL if the
// input is NULL.
-const char* String::Utf16ToAnsi(LPCWSTR utf16_str) {
+const char* String::Utf16ToAnsi(LPCWSTR utf16_str) {
if (!utf16_str) return NULL;
const int ansi_length =
- WideCharToMultiByte(CP_ACP, 0, utf16_str, -1,
- NULL, 0, NULL, NULL);
+ WideCharToMultiByte(CP_ACP, 0, utf16_str, -1, NULL, 0, NULL, NULL);
char* ansi = new char[ansi_length + 1];
- WideCharToMultiByte(CP_ACP, 0, utf16_str, -1,
- ansi, ansi_length, NULL, NULL);
+ WideCharToMultiByte(CP_ACP, 0, utf16_str, -1, ansi, ansi_length, NULL, NULL);
ansi[ansi_length] = 0;
return ansi;
}
@@ -2357,10 +2318,10 @@
// Unlike strcmp(), this function can handle NULL argument(s). A NULL
// C string is considered different to any non-NULL C string,
// including the empty string.
-bool String::CStringEquals(const char * lhs, const char * rhs) {
- if ( lhs == NULL ) return rhs == NULL;
+bool String::CStringEquals(const char* lhs, const char* rhs) {
+ if (lhs == NULL) return rhs == NULL;
- if ( rhs == NULL ) return false;
+ if (rhs == NULL) return false;
return strcmp(lhs, rhs) == 0;
}
@@ -2371,11 +2332,10 @@
// encoding, and streams the result to the given Message object.
static void StreamWideCharsToMessage(const wchar_t* wstr, size_t length,
Message* msg) {
- for (size_t i = 0; i != length; ) { // NOLINT
+ for (size_t i = 0; i != length;) { // NOLINT
if (wstr[i] != L'\0') {
*msg << WideStringToUtf8(wstr + i, static_cast<int>(length - i));
- while (i != length && wstr[i] != L'\0')
- i++;
+ while (i != length && wstr[i] != L'\0') i++;
} else {
*msg << '\0';
i++;
@@ -2400,17 +2360,17 @@
// These two overloads allow streaming a wide C string to a Message
// using the UTF-8 encoding.
-Message& Message::operator <<(const wchar_t* wide_c_str) {
+Message& Message::operator<<(const wchar_t* wide_c_str) {
return *this << internal::String::ShowWideCString(wide_c_str);
}
-Message& Message::operator <<(wchar_t* wide_c_str) {
+Message& Message::operator<<(wchar_t* wide_c_str) {
return *this << internal::String::ShowWideCString(wide_c_str);
}
#if GTEST_HAS_STD_WSTRING
// Converts the given wide string to a narrow string using the UTF-8
// encoding, and streams the result to this Message object.
-Message& Message::operator <<(const ::std::wstring& wstr) {
+Message& Message::operator<<(const ::std::wstring& wstr) {
internal::StreamWideCharsToMessage(wstr.c_str(), wstr.length(), this);
return *this;
}
@@ -2419,7 +2379,7 @@
#if GTEST_HAS_GLOBAL_WSTRING
// Converts the given wide string to a narrow string using the UTF-8
// encoding, and streams the result to this Message object.
-Message& Message::operator <<(const ::wstring& wstr) {
+Message& Message::operator<<(const ::wstring& wstr) {
internal::StreamWideCharsToMessage(wstr.c_str(), wstr.length(), this);
return *this;
}
@@ -2435,28 +2395,22 @@
// Used in EXPECT_TRUE/FALSE(assertion_result).
AssertionResult::AssertionResult(const AssertionResult& other)
: success_(other.success_),
- message_(other.message_.get() != NULL ?
- new ::std::string(*other.message_) :
- static_cast< ::std::string*>(NULL)) {
-}
+ message_(other.message_.get() != NULL
+ ? new ::std::string(*other.message_)
+ : static_cast< ::std::string*>(NULL)) {}
// Returns the assertion's negation. Used with EXPECT/ASSERT_FALSE.
AssertionResult AssertionResult::operator!() const {
AssertionResult negation(!success_);
- if (message_.get() != NULL)
- negation << *message_;
+ if (message_.get() != NULL) negation << *message_;
return negation;
}
// Makes a successful assertion result.
-AssertionResult AssertionSuccess() {
- return AssertionResult(true);
-}
+AssertionResult AssertionSuccess() { return AssertionResult(true); }
// Makes a failed assertion result.
-AssertionResult AssertionFailure() {
- return AssertionResult(false);
-}
+AssertionResult AssertionFailure() { return AssertionResult(false); }
// Makes a failed assertion result with the given failure message.
// Deprecated; use AssertionFailure() << message.
@@ -2484,8 +2438,7 @@
AssertionResult EqFailure(const char* expected_expression,
const char* actual_expression,
const std::string& expected_value,
- const std::string& actual_value,
- bool ignoring_case) {
+ const std::string& actual_value, bool ignoring_case) {
Message msg;
msg << "Value of: " << actual_expression;
if (actual_value != actual_expression) {
@@ -2505,47 +2458,38 @@
// Constructs a failure message for Boolean assertions such as EXPECT_TRUE.
std::string GetBoolAssertionFailureMessage(
- const AssertionResult& assertion_result,
- const char* expression_text,
- const char* actual_predicate_value,
- const char* expected_predicate_value) {
+ const AssertionResult& assertion_result, const char* expression_text,
+ const char* actual_predicate_value, const char* expected_predicate_value) {
const char* actual_message = assertion_result.message();
Message msg;
msg << "Value of: " << expression_text
<< "\n Actual: " << actual_predicate_value;
- if (actual_message[0] != '\0')
- msg << " (" << actual_message << ")";
+ if (actual_message[0] != '\0') msg << " (" << actual_message << ")";
msg << "\nExpected: " << expected_predicate_value;
return msg.GetString();
}
// Helper function for implementing ASSERT_NEAR.
-AssertionResult DoubleNearPredFormat(const char* expr1,
- const char* expr2,
- const char* abs_error_expr,
- double val1,
- double val2,
- double abs_error) {
+AssertionResult DoubleNearPredFormat(const char* expr1, const char* expr2,
+ const char* abs_error_expr, double val1,
+ double val2, double abs_error) {
const double diff = fabs(val1 - val2);
if (diff <= abs_error) return AssertionSuccess();
// TODO(wan): do not print the value of an expression if it's
// already a literal.
return AssertionFailure()
- << "The difference between " << expr1 << " and " << expr2
- << " is " << diff << ", which exceeds " << abs_error_expr << ", where\n"
- << expr1 << " evaluates to " << val1 << ",\n"
- << expr2 << " evaluates to " << val2 << ", and\n"
- << abs_error_expr << " evaluates to " << abs_error << ".";
+ << "The difference between " << expr1 << " and " << expr2 << " is "
+ << diff << ", which exceeds " << abs_error_expr << ", where\n"
+ << expr1 << " evaluates to " << val1 << ",\n"
+ << expr2 << " evaluates to " << val2 << ", and\n"
+ << abs_error_expr << " evaluates to " << abs_error << ".";
}
-
// Helper template for implementing FloatLE() and DoubleLE().
template <typename RawType>
-AssertionResult FloatingPointLE(const char* expr1,
- const char* expr2,
- RawType val1,
- RawType val2) {
+AssertionResult FloatingPointLE(const char* expr1, const char* expr2,
+ RawType val1, RawType val2) {
// Returns success if val1 is less than val2,
if (val1 < val2) {
return AssertionSuccess();
@@ -2570,24 +2514,24 @@
<< val2;
return AssertionFailure()
- << "Expected: (" << expr1 << ") <= (" << expr2 << ")\n"
- << " Actual: " << StringStreamToString(&val1_ss) << " vs "
- << StringStreamToString(&val2_ss);
+ << "Expected: (" << expr1 << ") <= (" << expr2 << ")\n"
+ << " Actual: " << StringStreamToString(&val1_ss) << " vs "
+ << StringStreamToString(&val2_ss);
}
} // namespace internal
// Asserts that val1 is less than, or almost equal to, val2. Fails
// otherwise. In particular, it fails if either val1 or val2 is NaN.
-AssertionResult FloatLE(const char* expr1, const char* expr2,
- float val1, float val2) {
+AssertionResult FloatLE(const char* expr1, const char* expr2, float val1,
+ float val2) {
return internal::FloatingPointLE<float>(expr1, expr2, val1, val2);
}
// Asserts that val1 is less than, or almost equal to, val2. Fails
// otherwise. In particular, it fails if either val1 or val2 is NaN.
-AssertionResult DoubleLE(const char* expr1, const char* expr2,
- double val1, double val2) {
+AssertionResult DoubleLE(const char* expr1, const char* expr2, double val1,
+ double val2) {
return internal::FloatingPointLE<double>(expr1, expr2, val1, val2);
}
@@ -2596,35 +2540,32 @@
// The helper function for {ASSERT|EXPECT}_EQ with int or enum
// arguments.
AssertionResult CmpHelperEQ(const char* expected_expression,
- const char* actual_expression,
- BiggestInt expected,
+ const char* actual_expression, BiggestInt expected,
BiggestInt actual) {
if (expected == actual) {
return AssertionSuccess();
}
- return EqFailure(expected_expression,
- actual_expression,
+ return EqFailure(expected_expression, actual_expression,
FormatForComparisonFailureMessage(expected, actual),
- FormatForComparisonFailureMessage(actual, expected),
- false);
+ FormatForComparisonFailureMessage(actual, expected), false);
}
// A macro for implementing the helper functions needed to implement
// ASSERT_?? and EXPECT_?? with integer or enum arguments. It is here
// just to avoid copy-and-paste of similar code.
-#define GTEST_IMPL_CMP_HELPER_(op_name, op)\
-AssertionResult CmpHelper##op_name(const char* expr1, const char* expr2, \
- BiggestInt val1, BiggestInt val2) {\
- if (val1 op val2) {\
- return AssertionSuccess();\
- } else {\
- return AssertionFailure() \
- << "Expected: (" << expr1 << ") " #op " (" << expr2\
- << "), actual: " << FormatForComparisonFailureMessage(val1, val2)\
- << " vs " << FormatForComparisonFailureMessage(val2, val1);\
- }\
-}
+#define GTEST_IMPL_CMP_HELPER_(op_name, op) \
+ AssertionResult CmpHelper##op_name(const char* expr1, const char* expr2, \
+ BiggestInt val1, BiggestInt val2) { \
+ if (val1 op val2) { \
+ return AssertionSuccess(); \
+ } else { \
+ return AssertionFailure() \
+ << "Expected: (" << expr1 << ") " #op " (" << expr2 \
+ << "), actual: " << FormatForComparisonFailureMessage(val1, val2) \
+ << " vs " << FormatForComparisonFailureMessage(val2, val1); \
+ } \
+ }
// Implements the helper function for {ASSERT|EXPECT}_NE with int or
// enum arguments.
@@ -2634,74 +2575,63 @@
GTEST_IMPL_CMP_HELPER_(LE, <=)
// Implements the helper function for {ASSERT|EXPECT}_LT with int or
// enum arguments.
-GTEST_IMPL_CMP_HELPER_(LT, < )
+GTEST_IMPL_CMP_HELPER_(LT, <)
// Implements the helper function for {ASSERT|EXPECT}_GE with int or
// enum arguments.
GTEST_IMPL_CMP_HELPER_(GE, >=)
// Implements the helper function for {ASSERT|EXPECT}_GT with int or
// enum arguments.
-GTEST_IMPL_CMP_HELPER_(GT, > )
+GTEST_IMPL_CMP_HELPER_(GT, >)
#undef GTEST_IMPL_CMP_HELPER_
// The helper function for {ASSERT|EXPECT}_STREQ.
AssertionResult CmpHelperSTREQ(const char* expected_expression,
const char* actual_expression,
- const char* expected,
- const char* actual) {
+ const char* expected, const char* actual) {
if (String::CStringEquals(expected, actual)) {
return AssertionSuccess();
}
- return EqFailure(expected_expression,
- actual_expression,
- PrintToString(expected),
- PrintToString(actual),
- false);
+ return EqFailure(expected_expression, actual_expression,
+ PrintToString(expected), PrintToString(actual), false);
}
// The helper function for {ASSERT|EXPECT}_STRCASEEQ.
AssertionResult CmpHelperSTRCASEEQ(const char* expected_expression,
const char* actual_expression,
- const char* expected,
- const char* actual) {
+ const char* expected, const char* actual) {
if (String::CaseInsensitiveCStringEquals(expected, actual)) {
return AssertionSuccess();
}
- return EqFailure(expected_expression,
- actual_expression,
- PrintToString(expected),
- PrintToString(actual),
- true);
+ return EqFailure(expected_expression, actual_expression,
+ PrintToString(expected), PrintToString(actual), true);
}
// The helper function for {ASSERT|EXPECT}_STRNE.
AssertionResult CmpHelperSTRNE(const char* s1_expression,
- const char* s2_expression,
- const char* s1,
+ const char* s2_expression, const char* s1,
const char* s2) {
if (!String::CStringEquals(s1, s2)) {
return AssertionSuccess();
} else {
- return AssertionFailure() << "Expected: (" << s1_expression << ") != ("
- << s2_expression << "), actual: \""
- << s1 << "\" vs \"" << s2 << "\"";
+ return AssertionFailure()
+ << "Expected: (" << s1_expression << ") != (" << s2_expression
+ << "), actual: \"" << s1 << "\" vs \"" << s2 << "\"";
}
}
// The helper function for {ASSERT|EXPECT}_STRCASENE.
AssertionResult CmpHelperSTRCASENE(const char* s1_expression,
- const char* s2_expression,
- const char* s1,
+ const char* s2_expression, const char* s1,
const char* s2) {
if (!String::CaseInsensitiveCStringEquals(s1, s2)) {
return AssertionSuccess();
} else {
return AssertionFailure()
- << "Expected: (" << s1_expression << ") != ("
- << s2_expression << ") (ignoring case), actual: \""
- << s1 << "\" vs \"" << s2 << "\"";
+ << "Expected: (" << s1_expression << ") != (" << s2_expression
+ << ") (ignoring case), actual: \"" << s1 << "\" vs \"" << s2 << "\"";
}
}
@@ -2716,23 +2646,20 @@
// only.
bool IsSubstringPred(const char* needle, const char* haystack) {
- if (needle == NULL || haystack == NULL)
- return needle == haystack;
+ if (needle == NULL || haystack == NULL) return needle == haystack;
return strstr(haystack, needle) != NULL;
}
bool IsSubstringPred(const wchar_t* needle, const wchar_t* haystack) {
- if (needle == NULL || haystack == NULL)
- return needle == haystack;
+ if (needle == NULL || haystack == NULL) return needle == haystack;
return wcsstr(haystack, needle) != NULL;
}
// StringType here can be either ::std::string or ::std::wstring.
template <typename StringType>
-bool IsSubstringPred(const StringType& needle,
- const StringType& haystack) {
+bool IsSubstringPred(const StringType& needle, const StringType& haystack) {
return haystack.find(needle) != StringType::npos;
}
@@ -2741,21 +2668,22 @@
// StringType here can be const char*, const wchar_t*, ::std::string,
// or ::std::wstring.
template <typename StringType>
-AssertionResult IsSubstringImpl(
- bool expected_to_be_substring,
- const char* needle_expr, const char* haystack_expr,
- const StringType& needle, const StringType& haystack) {
+AssertionResult IsSubstringImpl(bool expected_to_be_substring,
+ const char* needle_expr,
+ const char* haystack_expr,
+ const StringType& needle,
+ const StringType& haystack) {
if (IsSubstringPred(needle, haystack) == expected_to_be_substring)
return AssertionSuccess();
const bool is_wide_string = sizeof(needle[0]) > 1;
const char* const begin_string_quote = is_wide_string ? "L\"" : "\"";
return AssertionFailure()
- << "Value of: " << needle_expr << "\n"
- << " Actual: " << begin_string_quote << needle << "\"\n"
- << "Expected: " << (expected_to_be_substring ? "" : "not ")
- << "a substring of " << haystack_expr << "\n"
- << "Which is: " << begin_string_quote << haystack << "\"";
+ << "Value of: " << needle_expr << "\n"
+ << " Actual: " << begin_string_quote << needle << "\"\n"
+ << "Expected: " << (expected_to_be_substring ? "" : "not ")
+ << "a substring of " << haystack_expr << "\n"
+ << "Which is: " << begin_string_quote << haystack << "\"";
}
} // namespace
@@ -2764,52 +2692,52 @@
// substring of haystack (NULL is considered a substring of itself
// only), and return an appropriate error message when they fail.
-AssertionResult IsSubstring(
- const char* needle_expr, const char* haystack_expr,
- const char* needle, const char* haystack) {
+AssertionResult IsSubstring(const char* needle_expr, const char* haystack_expr,
+ const char* needle, const char* haystack) {
return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
}
-AssertionResult IsSubstring(
- const char* needle_expr, const char* haystack_expr,
- const wchar_t* needle, const wchar_t* haystack) {
+AssertionResult IsSubstring(const char* needle_expr, const char* haystack_expr,
+ const wchar_t* needle, const wchar_t* haystack) {
return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
}
-AssertionResult IsNotSubstring(
- const char* needle_expr, const char* haystack_expr,
- const char* needle, const char* haystack) {
+AssertionResult IsNotSubstring(const char* needle_expr,
+ const char* haystack_expr, const char* needle,
+ const char* haystack) {
return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
}
-AssertionResult IsNotSubstring(
- const char* needle_expr, const char* haystack_expr,
- const wchar_t* needle, const wchar_t* haystack) {
+AssertionResult IsNotSubstring(const char* needle_expr,
+ const char* haystack_expr, const wchar_t* needle,
+ const wchar_t* haystack) {
return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
}
-AssertionResult IsSubstring(
- const char* needle_expr, const char* haystack_expr,
- const ::std::string& needle, const ::std::string& haystack) {
+AssertionResult IsSubstring(const char* needle_expr, const char* haystack_expr,
+ const ::std::string& needle,
+ const ::std::string& haystack) {
return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
}
-AssertionResult IsNotSubstring(
- const char* needle_expr, const char* haystack_expr,
- const ::std::string& needle, const ::std::string& haystack) {
+AssertionResult IsNotSubstring(const char* needle_expr,
+ const char* haystack_expr,
+ const ::std::string& needle,
+ const ::std::string& haystack) {
return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
}
#if GTEST_HAS_STD_WSTRING
-AssertionResult IsSubstring(
- const char* needle_expr, const char* haystack_expr,
- const ::std::wstring& needle, const ::std::wstring& haystack) {
+AssertionResult IsSubstring(const char* needle_expr, const char* haystack_expr,
+ const ::std::wstring& needle,
+ const ::std::wstring& haystack) {
return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
}
-AssertionResult IsNotSubstring(
- const char* needle_expr, const char* haystack_expr,
- const ::std::wstring& needle, const ::std::wstring& haystack) {
+AssertionResult IsNotSubstring(const char* needle_expr,
+ const char* haystack_expr,
+ const ::std::wstring& needle,
+ const ::std::wstring& haystack) {
return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
}
#endif // GTEST_HAS_STD_WSTRING
@@ -2821,43 +2749,42 @@
namespace {
// Helper function for IsHRESULT{SuccessFailure} predicates
-AssertionResult HRESULTFailureHelper(const char* expr,
- const char* expected,
+AssertionResult HRESULTFailureHelper(const char* expr, const char* expected,
long hr) { // NOLINT
-# if GTEST_OS_WINDOWS_MOBILE
+# if GTEST_OS_WINDOWS_MOBILE
// Windows CE doesn't support FormatMessage.
const char error_text[] = "";
-# else
+# else
// Looks up the human-readable system message for the HRESULT code
// and since we're not passing any params to FormatMessage, we don't
// want inserts expanded.
- const DWORD kFlags = FORMAT_MESSAGE_FROM_SYSTEM |
- FORMAT_MESSAGE_IGNORE_INSERTS;
+ const DWORD kFlags =
+ FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS;
const DWORD kBufSize = 4096;
// Gets the system's human readable message string for this HRESULT.
- char error_text[kBufSize] = { '\0' };
+ char error_text[kBufSize] = {'\0'};
DWORD message_length = ::FormatMessageA(kFlags,
- 0, // no source, we're asking system
+ 0, // no source, we're asking system
hr, // the error
- 0, // no line width restrictions
+ 0, // no line width restrictions
error_text, // output buffer
- kBufSize, // buf size
+ kBufSize, // buf size
NULL); // no arguments for inserts
// Trims tailing white space (FormatMessage leaves a trailing CR-LF)
for (; message_length && IsSpace(error_text[message_length - 1]);
- --message_length) {
+ --message_length) {
error_text[message_length - 1] = '\0';
}
-# endif // GTEST_OS_WINDOWS_MOBILE
+# endif // GTEST_OS_WINDOWS_MOBILE
const std::string error_hex("0x" + String::FormatHexInt(hr));
return ::testing::AssertionFailure()
- << "Expected: " << expr << " " << expected << ".\n"
- << " Actual: " << error_hex << " " << error_text << "\n";
+ << "Expected: " << expr << " " << expected << ".\n"
+ << " Actual: " << error_hex << " " << error_text << "\n";
}
} // namespace
@@ -2891,16 +2818,16 @@
// 17 - 21 bits 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
// The maximum code-point a one-byte UTF-8 sequence can represent.
-const UInt32 kMaxCodePoint1 = (static_cast<UInt32>(1) << 7) - 1;
+const UInt32 kMaxCodePoint1 = (static_cast<UInt32>(1) << 7) - 1;
// The maximum code-point a two-byte UTF-8 sequence can represent.
const UInt32 kMaxCodePoint2 = (static_cast<UInt32>(1) << (5 + 6)) - 1;
// The maximum code-point a three-byte UTF-8 sequence can represent.
-const UInt32 kMaxCodePoint3 = (static_cast<UInt32>(1) << (4 + 2*6)) - 1;
+const UInt32 kMaxCodePoint3 = (static_cast<UInt32>(1) << (4 + 2 * 6)) - 1;
// The maximum code-point a four-byte UTF-8 sequence can represent.
-const UInt32 kMaxCodePoint4 = (static_cast<UInt32>(1) << (3 + 3*6)) - 1;
+const UInt32 kMaxCodePoint4 = (static_cast<UInt32>(1) << (3 + 3 * 6)) - 1;
// Chops off the n lowest bits from a bit pattern. Returns the n
// lowest bits. As a side effect, the original bit pattern will be
@@ -2925,7 +2852,7 @@
char str[5]; // Big enough for the largest valid code point.
if (code_point <= kMaxCodePoint1) {
str[1] = '\0';
- str[0] = static_cast<char>(code_point); // 0xxxxxxx
+ str[0] = static_cast<char>(code_point); // 0xxxxxxx
} else if (code_point <= kMaxCodePoint2) {
str[2] = '\0';
str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
@@ -2953,19 +2880,20 @@
// and thus should be combined into a single Unicode code point
// using CreateCodePointFromUtf16SurrogatePair.
inline bool IsUtf16SurrogatePair(wchar_t first, wchar_t second) {
- return sizeof(wchar_t) == 2 &&
- (first & 0xFC00) == 0xD800 && (second & 0xFC00) == 0xDC00;
+ return sizeof(wchar_t) == 2 && (first & 0xFC00) == 0xD800 &&
+ (second & 0xFC00) == 0xDC00;
}
// Creates a Unicode code point from UTF16 surrogate pair.
inline UInt32 CreateCodePointFromUtf16SurrogatePair(wchar_t first,
wchar_t second) {
const UInt32 mask = (1 << 10) - 1;
- return (sizeof(wchar_t) == 2) ?
- (((first & mask) << 10) | (second & mask)) + 0x10000 :
- // This function should not be called when the condition is
- // false, but we provide a sensible default in case it is.
- static_cast<UInt32>(first);
+ return (sizeof(wchar_t) == 2)
+ ? (((first & mask) << 10) | (second & mask)) + 0x10000
+ :
+ // This function should not be called when the condition is
+ // false, but we provide a sensible default in case it is.
+ static_cast<UInt32>(first);
}
// Converts a wide string to a narrow string in UTF-8 encoding.
@@ -2982,8 +2910,7 @@
// and contains invalid UTF-16 surrogate pairs, values in those pairs
// will be encoded as individual Unicode characters from Basic Normal Plane.
std::string WideStringToUtf8(const wchar_t* str, int num_chars) {
- if (num_chars == -1)
- num_chars = static_cast<int>(wcslen(str));
+ if (num_chars == -1) num_chars = static_cast<int>(wcslen(str));
::std::stringstream stream;
for (int i = 0; i < num_chars; ++i) {
@@ -2992,8 +2919,8 @@
if (str[i] == L'\0') {
break;
} else if (i + 1 < num_chars && IsUtf16SurrogatePair(str[i], str[i + 1])) {
- unicode_code_point = CreateCodePointFromUtf16SurrogatePair(str[i],
- str[i + 1]);
+ unicode_code_point =
+ CreateCodePointFromUtf16SurrogatePair(str[i], str[i + 1]);
i++;
} else {
unicode_code_point = static_cast<UInt32>(str[i]);
@@ -3006,8 +2933,8 @@
// Converts a wide C string to an std::string using the UTF-8 encoding.
// NULL will be converted to "(null)".
-std::string String::ShowWideCString(const wchar_t * wide_c_str) {
- if (wide_c_str == NULL) return "(null)";
+std::string String::ShowWideCString(const wchar_t* wide_c_str) {
+ if (wide_c_str == NULL) return "(null)";
return internal::WideStringToUtf8(wide_c_str, -1);
}
@@ -3018,7 +2945,7 @@
// Unlike wcscmp(), this function can handle NULL argument(s). A NULL
// C string is considered different to any non-NULL C string,
// including the empty string.
-bool String::WideCStringEquals(const wchar_t * lhs, const wchar_t * rhs) {
+bool String::WideCStringEquals(const wchar_t* lhs, const wchar_t* rhs) {
if (lhs == NULL) return rhs == NULL;
if (rhs == NULL) return false;
@@ -3029,32 +2956,26 @@
// Helper function for *_STREQ on wide strings.
AssertionResult CmpHelperSTREQ(const char* expected_expression,
const char* actual_expression,
- const wchar_t* expected,
- const wchar_t* actual) {
+ const wchar_t* expected, const wchar_t* actual) {
if (String::WideCStringEquals(expected, actual)) {
return AssertionSuccess();
}
- return EqFailure(expected_expression,
- actual_expression,
- PrintToString(expected),
- PrintToString(actual),
- false);
+ return EqFailure(expected_expression, actual_expression,
+ PrintToString(expected), PrintToString(actual), false);
}
// Helper function for *_STRNE on wide strings.
AssertionResult CmpHelperSTRNE(const char* s1_expression,
- const char* s2_expression,
- const wchar_t* s1,
+ const char* s2_expression, const wchar_t* s1,
const wchar_t* s2) {
if (!String::WideCStringEquals(s1, s2)) {
return AssertionSuccess();
}
- return AssertionFailure() << "Expected: (" << s1_expression << ") != ("
- << s2_expression << "), actual: "
- << PrintToString(s1)
- << " vs " << PrintToString(s2);
+ return AssertionFailure()
+ << "Expected: (" << s1_expression << ") != (" << s2_expression
+ << "), actual: " << PrintToString(s1) << " vs " << PrintToString(s2);
}
// Compares two C strings, ignoring case. Returns true iff they have
@@ -3063,26 +2984,24 @@
// Unlike strcasecmp(), this function can handle NULL argument(s). A
// NULL C string is considered different to any non-NULL C string,
// including the empty string.
-bool String::CaseInsensitiveCStringEquals(const char * lhs, const char * rhs) {
- if (lhs == NULL)
- return rhs == NULL;
- if (rhs == NULL)
- return false;
+bool String::CaseInsensitiveCStringEquals(const char* lhs, const char* rhs) {
+ if (lhs == NULL) return rhs == NULL;
+ if (rhs == NULL) return false;
return posix::StrCaseCmp(lhs, rhs) == 0;
}
- // Compares two wide C strings, ignoring case. Returns true iff they
- // have the same content.
- //
- // Unlike wcscasecmp(), this function can handle NULL argument(s).
- // A NULL C string is considered different to any non-NULL wide C string,
- // including the empty string.
- // NB: The implementations on different platforms slightly differ.
- // On windows, this method uses _wcsicmp which compares according to LC_CTYPE
- // environment variable. On GNU platform this method uses wcscasecmp
- // which compares according to LC_CTYPE category of the current locale.
- // On MacOS X, it uses towlower, which also uses LC_CTYPE category of the
- // current locale.
+// Compares two wide C strings, ignoring case. Returns true iff they
+// have the same content.
+//
+// Unlike wcscasecmp(), this function can handle NULL argument(s).
+// A NULL C string is considered different to any non-NULL wide C string,
+// including the empty string.
+// NB: The implementations on different platforms slightly differ.
+// On windows, this method uses _wcsicmp which compares according to LC_CTYPE
+// environment variable. On GNU platform this method uses wcscasecmp
+// which compares according to LC_CTYPE category of the current locale.
+// On MacOS X, it uses towlower, which also uses LC_CTYPE category of the
+// current locale.
bool String::CaseInsensitiveWideCStringEquals(const wchar_t* lhs,
const wchar_t* rhs) {
if (lhs == NULL) return rhs == NULL;
@@ -3107,8 +3026,8 @@
// Returns true iff str ends with the given suffix, ignoring case.
// Any string is considered to end with an empty suffix.
-bool String::EndsWithCaseInsensitive(
- const std::string& str, const std::string& suffix) {
+bool String::EndsWithCaseInsensitive(const std::string& str,
+ const std::string& suffix) {
const size_t str_len = str.length();
const size_t suffix_len = suffix.length();
return (str_len >= suffix_len) &&
@@ -3175,21 +3094,16 @@
// class TestResult
// Creates an empty TestResult.
-TestResult::TestResult()
- : death_test_count_(0),
- elapsed_time_(0) {
-}
+TestResult::TestResult() : death_test_count_(0), elapsed_time_(0) {}
// D'tor.
-TestResult::~TestResult() {
-}
+TestResult::~TestResult() {}
// Returns the i-th test part result among all the results. i can
// range from 0 to total_part_count() - 1. If i is not in that range,
// aborts the program.
const TestPartResult& TestResult::GetTestPartResult(int i) const {
- if (i < 0 || i >= total_part_count())
- internal::posix::Abort();
+ if (i < 0 || i >= total_part_count()) internal::posix::Abort();
return test_part_results_.at(i);
}
@@ -3197,15 +3111,12 @@
// test_property_count() - 1. If i is not in that range, aborts the
// program.
const TestProperty& TestResult::GetTestProperty(int i) const {
- if (i < 0 || i >= test_property_count())
- internal::posix::Abort();
+ if (i < 0 || i >= test_property_count()) internal::posix::Abort();
return test_properties_.at(i);
}
// Clears the test part results.
-void TestResult::ClearTestPartResults() {
- test_part_results_.clear();
-}
+void TestResult::ClearTestPartResults() { test_part_results_.clear(); }
// Adds a test part result to the list.
void TestResult::AddTestPartResult(const TestPartResult& test_part_result) {
@@ -3234,36 +3145,17 @@
// The list of reserved attributes used in the <testsuites> element of XML
// output.
static const char* const kReservedTestSuitesAttributes[] = {
- "disabled",
- "errors",
- "failures",
- "name",
- "random_seed",
- "tests",
- "time",
- "timestamp"
-};
+ "disabled", "errors", "failures", "name",
+ "random_seed", "tests", "time", "timestamp"};
// The list of reserved attributes used in the <testsuite> element of XML
// output.
static const char* const kReservedTestSuiteAttributes[] = {
- "disabled",
- "errors",
- "failures",
- "name",
- "tests",
- "time"
-};
+ "disabled", "errors", "failures", "name", "tests", "time"};
// The list of reserved attributes used in the <testcase> element of XML output.
static const char* const kReservedTestCaseAttributes[] = {
- "classname",
- "name",
- "status",
- "time",
- "type_param",
- "value_param"
-};
+ "classname", "name", "status", "time", "type_param", "value_param"};
template <int kSize>
std::vector<std::string> ArrayAsVector(const char* const (&array)[kSize]) {
@@ -3302,7 +3194,7 @@
bool ValidateTestPropertyName(const std::string& property_name,
const std::vector<std::string>& reserved_names) {
if (std::find(reserved_names.begin(), reserved_names.end(), property_name) !=
- reserved_names.end()) {
+ reserved_names.end()) {
ADD_FAILURE() << "Reserved key used in RecordProperty(): " << property_name
<< " (" << FormatWordList(reserved_names)
<< " are reserved by " << GTEST_NAME_ << ")";
@@ -3330,8 +3222,7 @@
// Returns true iff the test failed.
bool TestResult::Failed() const {
for (int i = 0; i < total_part_count(); ++i) {
- if (GetTestPartResult(i).failed())
- return true;
+ if (GetTestPartResult(i).failed()) return true;
}
return false;
}
@@ -3372,26 +3263,20 @@
// Creates a Test object.
// The c'tor saves the values of all Google Test flags.
-Test::Test()
- : gtest_flag_saver_(new internal::GTestFlagSaver) {
-}
+Test::Test() : gtest_flag_saver_(new internal::GTestFlagSaver) {}
// The d'tor restores the values of all Google Test flags.
-Test::~Test() {
- delete gtest_flag_saver_;
-}
+Test::~Test() { delete gtest_flag_saver_; }
// Sets up the test fixture.
//
// A sub-class may override this.
-void Test::SetUp() {
-}
+void Test::SetUp() {}
// Tears down the test fixture.
//
// A sub-class may override this.
-void Test::TearDown() {
-}
+void Test::TearDown() {}
// Allows user supplied key value pairs to be recorded for later output.
void Test::RecordProperty(const std::string& key, const std::string& value) {
@@ -3416,7 +3301,7 @@
NULL, // No info about the source file where the exception occurred.
-1, // We have no info on which line caused the exception.
message,
- ""); // No stack trace, either.
+ ""); // No stack trace, either.
}
} // namespace internal
@@ -3474,8 +3359,8 @@
<< "All tests in the same test case must use the same test fixture\n"
<< "class. However, in test case "
<< this_test_info->test_case_name() << ",\n"
- << "you defined test " << first_test_name
- << " and test " << this_test_name << "\n"
+ << "you defined test " << first_test_name << " and test "
+ << this_test_name << "\n"
<< "using two different test fixture classes. This can happen if\n"
<< "the two classes are from different namespaces or translation\n"
<< "units and have the same name. You should probably rename one\n"
@@ -3496,8 +3381,8 @@
static std::string* FormatSehExceptionMessage(DWORD exception_code,
const char* location) {
Message message;
- message << "SEH exception with code 0x" << std::setbase(16) <<
- exception_code << std::setbase(10) << " thrown in " << location << ".";
+ message << "SEH exception with code 0x" << std::setbase(16) << exception_code
+ << std::setbase(10) << " thrown in " << location << ".";
return new std::string(message.GetString());
}
@@ -3540,8 +3425,8 @@
// exceptions in the same function. Therefore, we provide a separate
// wrapper function for handling SEH exceptions.)
template <class T, typename Result>
-Result HandleSehExceptionsInMethodIfSupported(
- T* object, Result (T::*method)(), const char* location) {
+Result HandleSehExceptionsInMethodIfSupported(T* object, Result (T::*method)(),
+ const char* location) {
#if GTEST_HAS_SEH
__try {
return (object->*method)();
@@ -3550,8 +3435,8 @@
// We create the exception message on the heap because VC++ prohibits
// creation of objects with destructors on stack in functions using __try
// (see error C2712).
- std::string* exception_message = FormatSehExceptionMessage(
- GetExceptionCode(), location);
+ std::string* exception_message =
+ FormatSehExceptionMessage(GetExceptionCode(), location);
internal::ReportFailureInUnknownLocation(TestPartResult::kFatalFailure,
*exception_message);
delete exception_message;
@@ -3567,8 +3452,8 @@
// exceptions, if they are supported; returns the 0-value for type
// Result in case of an SEH exception.
template <class T, typename Result>
-Result HandleExceptionsInMethodIfSupported(
- T* object, Result (T::*method)(), const char* location) {
+Result HandleExceptionsInMethodIfSupported(T* object, Result (T::*method)(),
+ const char* location) {
// NOTE: The user code can affect the way in which Google Test handles
// exceptions by setting GTEST_FLAG(catch_exceptions), but only before
// RUN_ALL_TESTS() starts. It is technically possible to check the flag
@@ -3631,16 +3516,16 @@
// We will run the test only if SetUp() was successful.
if (!HasFatalFailure()) {
impl->os_stack_trace_getter()->UponLeavingGTest();
- internal::HandleExceptionsInMethodIfSupported(
- this, &Test::TestBody, "the test body");
+ internal::HandleExceptionsInMethodIfSupported(this, &Test::TestBody,
+ "the test body");
}
// However, we want to clean up as much as possible. Hence we will
// always call TearDown(), even if SetUp() or the test body has
// failed.
impl->os_stack_trace_getter()->UponLeavingGTest();
- internal::HandleExceptionsInMethodIfSupported(
- this, &Test::TearDown, "TearDown()");
+ internal::HandleExceptionsInMethodIfSupported(this, &Test::TearDown,
+ "TearDown()");
}
// Returns true iff the current test has a fatal failure.
@@ -3650,8 +3535,9 @@
// Returns true iff the current test has a non-fatal failure.
bool Test::HasNonfatalFailure() {
- return internal::GetUnitTestImpl()->current_test_result()->
- HasNonfatalFailure();
+ return internal::GetUnitTestImpl()
+ ->current_test_result()
+ ->HasNonfatalFailure();
}
// class TestInfo
@@ -3659,10 +3545,8 @@
// Constructs a TestInfo object. It assumes ownership of the test factory
// object.
TestInfo::TestInfo(const std::string& a_test_case_name,
- const std::string& a_name,
- const char* a_type_param,
- const char* a_value_param,
- internal::TypeId fixture_class_id,
+ const std::string& a_name, const char* a_type_param,
+ const char* a_value_param, internal::TypeId fixture_class_id,
internal::TestFactoryBase* factory)
: test_case_name_(a_test_case_name),
name_(a_name),
@@ -3697,25 +3581,22 @@
// factory: pointer to the factory that creates a test object.
// The newly created TestInfo instance will assume
// ownership of the factory object.
-TestInfo* MakeAndRegisterTestInfo(
- const char* test_case_name,
- const char* name,
- const char* type_param,
- const char* value_param,
- TypeId fixture_class_id,
- SetUpTestCaseFunc set_up_tc,
- TearDownTestCaseFunc tear_down_tc,
- TestFactoryBase* factory) {
- TestInfo* const test_info =
- new TestInfo(test_case_name, name, type_param, value_param,
- fixture_class_id, factory);
+TestInfo* MakeAndRegisterTestInfo(const char* test_case_name, const char* name,
+ const char* type_param,
+ const char* value_param,
+ TypeId fixture_class_id,
+ SetUpTestCaseFunc set_up_tc,
+ TearDownTestCaseFunc tear_down_tc,
+ TestFactoryBase* factory) {
+ TestInfo* const test_info = new TestInfo(
+ test_case_name, name, type_param, value_param, fixture_class_id, factory);
GetUnitTestImpl()->AddTestInfo(set_up_tc, tear_down_tc, test_info);
return test_info;
}
#if GTEST_HAS_PARAM_TEST
-void ReportInvalidTestCaseType(const char* test_case_name,
- const char* file, int line) {
+void ReportInvalidTestCaseType(const char* test_case_name, const char* file,
+ int line) {
Message errors;
errors
<< "Attempted redefinition of test case " << test_case_name << ".\n"
@@ -3749,11 +3630,10 @@
// Constructor.
//
// TestNameIs has NO default constructor.
- explicit TestNameIs(const char* name)
- : name_(name) {}
+ explicit TestNameIs(const char* name) : name_(name) {}
// Returns true iff the test name of test_info matches name_.
- bool operator()(const TestInfo * test_info) const {
+ bool operator()(const TestInfo* test_info) const {
return test_info && test_info->name() == name_;
}
@@ -3879,8 +3759,7 @@
set_up_tc_(set_up_tc),
tear_down_tc_(tear_down_tc),
should_run_(false),
- elapsed_time_(0) {
-}
+ elapsed_time_(0) {}
// Destructor of TestCase.
TestCase::~TestCase() {
@@ -3904,7 +3783,7 @@
// Adds a test to this test case. Will delete the test upon
// destruction of the TestCase object.
-void TestCase::AddTestInfo(TestInfo * test_info) {
+void TestCase::AddTestInfo(TestInfo* test_info) {
test_info_list_.push_back(test_info);
test_indices_.push_back(static_cast<int>(test_indices_.size()));
}
@@ -3960,11 +3839,10 @@
//
// FormatCountableNoun(1, "formula", "formuli") returns "1 formula".
// FormatCountableNoun(5, "book", "books") returns "5 books".
-static std::string FormatCountableNoun(int count,
- const char * singular_form,
- const char * plural_form) {
+static std::string FormatCountableNoun(int count, const char* singular_form,
+ const char* plural_form) {
return internal::StreamableToString(count) + " " +
- (count == 1 ? singular_form : plural_form);
+ (count == 1 ? singular_form : plural_form);
}
// Formats the count of tests.
@@ -3981,20 +3859,20 @@
// representation. Both kNonFatalFailure and kFatalFailure are translated
// to "Failure", as the user usually doesn't care about the difference
// between the two when viewing the test result.
-static const char * TestPartResultTypeToString(TestPartResult::Type type) {
+static const char* TestPartResultTypeToString(TestPartResult::Type type) {
switch (type) {
- case TestPartResult::kSuccess:
- return "Success";
+ case TestPartResult::kSuccess:
+ return "Success";
- case TestPartResult::kNonFatalFailure:
- case TestPartResult::kFatalFailure:
+ case TestPartResult::kNonFatalFailure:
+ case TestPartResult::kFatalFailure:
#ifdef _MSC_VER
- return "error: ";
+ return "error: ";
#else
- return "Failure\n";
+ return "Failure\n";
#endif
- default:
- return "Unknown result type";
+ default:
+ return "Unknown result type";
}
}
@@ -4003,17 +3881,18 @@
// Prints a TestPartResult to an std::string.
static std::string PrintTestPartResultToString(
const TestPartResult& test_part_result) {
- return (Message()
- << internal::FormatFileLocation(test_part_result.file_name(),
- test_part_result.line_number())
- << " " << TestPartResultTypeToString(test_part_result.type())
- << test_part_result.message()).GetString();
+ return (Message() << internal::FormatFileLocation(
+ test_part_result.file_name(),
+ test_part_result.line_number())
+ << " "
+ << TestPartResultTypeToString(test_part_result.type())
+ << test_part_result.message())
+ .GetString();
}
// Prints a TestPartResult.
static void PrintTestPartResult(const TestPartResult& test_part_result) {
- const std::string& result =
- PrintTestPartResultToString(test_part_result);
+ const std::string& result = PrintTestPartResultToString(test_part_result);
printf("%s\n", result.c_str());
fflush(stdout);
// If the test program runs in Visual Studio or a debugger, the
@@ -4031,22 +3910,21 @@
// class PrettyUnitTestResultPrinter
-enum GTestColor {
- COLOR_DEFAULT,
- COLOR_RED,
- COLOR_GREEN,
- COLOR_YELLOW
-};
+enum GTestColor { COLOR_DEFAULT, COLOR_RED, COLOR_GREEN, COLOR_YELLOW };
#if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
// Returns the character attribute for the given color.
WORD GetColorAttribute(GTestColor color) {
switch (color) {
- case COLOR_RED: return FOREGROUND_RED;
- case COLOR_GREEN: return FOREGROUND_GREEN;
- case COLOR_YELLOW: return FOREGROUND_RED | FOREGROUND_GREEN;
- default: return 0;
+ case COLOR_RED:
+ return FOREGROUND_RED;
+ case COLOR_GREEN:
+ return FOREGROUND_GREEN;
+ case COLOR_YELLOW:
+ return FOREGROUND_RED | FOREGROUND_GREEN;
+ default:
+ return 0;
}
}
@@ -4056,10 +3934,14 @@
// an invalid input.
const char* GetAnsiColorCode(GTestColor color) {
switch (color) {
- case COLOR_RED: return "1";
- case COLOR_GREEN: return "2";
- case COLOR_YELLOW: return "3";
- default: return NULL;
+ case COLOR_RED:
+ return "1";
+ case COLOR_GREEN:
+ return "2";
+ case COLOR_YELLOW:
+ return "3";
+ default:
+ return NULL;
};
}
@@ -4090,9 +3972,9 @@
}
return String::CaseInsensitiveCStringEquals(gtest_color, "yes") ||
- String::CaseInsensitiveCStringEquals(gtest_color, "true") ||
- String::CaseInsensitiveCStringEquals(gtest_color, "t") ||
- String::CStringEquals(gtest_color, "1");
+ String::CaseInsensitiveCStringEquals(gtest_color, "true") ||
+ String::CaseInsensitiveCStringEquals(gtest_color, "t") ||
+ String::CStringEquals(gtest_color, "1");
// We take "yes", "true", "t", and "1" as meaning "yes". If the
// value is neither one of these nor "auto", we treat it as "no" to
// be conservative.
@@ -4161,8 +4043,7 @@
printf(", where ");
if (type_param != NULL) {
printf("%s = %s", kTypeParamLabel, type_param);
- if (value_param != NULL)
- printf(" and ");
+ if (value_param != NULL) printf(" and ");
}
if (value_param != NULL) {
printf("%s = %s", kValueParamLabel, value_param);
@@ -4176,7 +4057,7 @@
class PrettyUnitTestResultPrinter : public TestEventListener {
public:
PrettyUnitTestResultPrinter() {}
- static void PrintTestName(const char * test_case, const char * test) {
+ static void PrintTestName(const char* test_case, const char* test) {
printf("%s.%s", test_case, test);
}
@@ -4199,7 +4080,7 @@
static void PrintFailedTests(const UnitTest& unit_test);
};
- // Fired before each iteration of tests starts.
+// Fired before each iteration of tests starts.
void PrettyUnitTestResultPrinter::OnTestIterationStart(
const UnitTest& unit_test, int iteration) {
if (GTEST_FLAG(repeat) != 1)
@@ -4210,14 +4091,12 @@
// Prints the filter if it's not *. This reminds the user that some
// tests may be skipped.
if (!String::CStringEquals(filter, kUniversalFilter)) {
- ColoredPrintf(COLOR_YELLOW,
- "Note: %s filter = %s\n", GTEST_NAME_, filter);
+ ColoredPrintf(COLOR_YELLOW, "Note: %s filter = %s\n", GTEST_NAME_, filter);
}
if (internal::ShouldShard(kTestTotalShards, kTestShardIndex, false)) {
const Int32 shard_index = Int32FromEnvOrDie(kTestShardIndex, -1);
- ColoredPrintf(COLOR_YELLOW,
- "Note: This is test shard %d of %s.\n",
+ ColoredPrintf(COLOR_YELLOW, "Note: This is test shard %d of %s.\n",
static_cast<int>(shard_index) + 1,
internal::posix::GetEnv(kTestTotalShards));
}
@@ -4228,7 +4107,7 @@
unit_test.random_seed());
}
- ColoredPrintf(COLOR_GREEN, "[==========] ");
+ ColoredPrintf(COLOR_GREEN, "[==========] ");
printf("Running %s from %s.\n",
FormatTestCount(unit_test.test_to_run_count()).c_str(),
FormatTestCaseCount(unit_test.test_case_to_run_count()).c_str());
@@ -4237,7 +4116,7 @@
void PrettyUnitTestResultPrinter::OnEnvironmentsSetUpStart(
const UnitTest& /*unit_test*/) {
- ColoredPrintf(COLOR_GREEN, "[----------] ");
+ ColoredPrintf(COLOR_GREEN, "[----------] ");
printf("Global test environment set-up.\n");
fflush(stdout);
}
@@ -4256,7 +4135,7 @@
}
void PrettyUnitTestResultPrinter::OnTestStart(const TestInfo& test_info) {
- ColoredPrintf(COLOR_GREEN, "[ RUN ] ");
+ ColoredPrintf(COLOR_GREEN, "[ RUN ] ");
PrintTestName(test_info.test_case_name(), test_info.name());
printf("\n");
fflush(stdout);
@@ -4266,8 +4145,7 @@
void PrettyUnitTestResultPrinter::OnTestPartResult(
const TestPartResult& result) {
// If the test part succeeded, we don't need to do anything.
- if (result.type() == TestPartResult::kSuccess)
- return;
+ if (result.type() == TestPartResult::kSuccess) return;
// Print failure message from the assertion (e.g. expected this and got that).
PrintTestPartResult(result);
@@ -4281,12 +4159,12 @@
ColoredPrintf(COLOR_RED, "[ FAILED ] ");
}
PrintTestName(test_info.test_case_name(), test_info.name());
- if (test_info.result()->Failed())
- PrintFullTestCommentIfPresent(test_info);
+ if (test_info.result()->Failed()) PrintFullTestCommentIfPresent(test_info);
if (GTEST_FLAG(print_time)) {
- printf(" (%s ms)\n", internal::StreamableToString(
- test_info.result()->elapsed_time()).c_str());
+ printf(" (%s ms)\n",
+ internal::StreamableToString(test_info.result()->elapsed_time())
+ .c_str());
} else {
printf("\n");
}
@@ -4299,15 +4177,14 @@
const std::string counts =
FormatCountableNoun(test_case.test_to_run_count(), "test", "tests");
ColoredPrintf(COLOR_GREEN, "[----------] ");
- printf("%s from %s (%s ms total)\n\n",
- counts.c_str(), test_case.name(),
+ printf("%s from %s (%s ms total)\n\n", counts.c_str(), test_case.name(),
internal::StreamableToString(test_case.elapsed_time()).c_str());
fflush(stdout);
}
void PrettyUnitTestResultPrinter::OnEnvironmentsTearDownStart(
const UnitTest& /*unit_test*/) {
- ColoredPrintf(COLOR_GREEN, "[----------] ");
+ ColoredPrintf(COLOR_GREEN, "[----------] ");
printf("Global test environment tear-down\n");
fflush(stdout);
}
@@ -4339,7 +4216,7 @@
void PrettyUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test,
int /*iteration*/) {
- ColoredPrintf(COLOR_GREEN, "[==========] ");
+ ColoredPrintf(COLOR_GREEN, "[==========] ");
printf("%s from %s ran.",
FormatTestCount(unit_test.test_to_run_count()).c_str(),
FormatTestCaseCount(unit_test.test_case_to_run_count()).c_str());
@@ -4348,17 +4225,17 @@
internal::StreamableToString(unit_test.elapsed_time()).c_str());
}
printf("\n");
- ColoredPrintf(COLOR_GREEN, "[ PASSED ] ");
+ ColoredPrintf(COLOR_GREEN, "[ PASSED ] ");
printf("%s.\n", FormatTestCount(unit_test.successful_test_count()).c_str());
int num_failures = unit_test.failed_test_count();
if (!unit_test.Passed()) {
const int failed_test_count = unit_test.failed_test_count();
- ColoredPrintf(COLOR_RED, "[ FAILED ] ");
+ ColoredPrintf(COLOR_RED, "[ FAILED ] ");
printf("%s, listed below:\n", FormatTestCount(failed_test_count).c_str());
PrintFailedTests(unit_test);
printf("\n%2d FAILED %s\n", num_failures,
- num_failures == 1 ? "TEST" : "TESTS");
+ num_failures == 1 ? "TEST" : "TESTS");
}
int num_disabled = unit_test.reportable_disabled_test_count();
@@ -4366,9 +4243,7 @@
if (!num_failures) {
printf("\n"); // Add a spacer if no FAILURE banner is displayed.
}
- ColoredPrintf(COLOR_YELLOW,
- " YOU HAVE %d DISABLED %s\n\n",
- num_disabled,
+ ColoredPrintf(COLOR_YELLOW, " YOU HAVE %d DISABLED %s\n\n", num_disabled,
num_disabled == 1 ? "TEST" : "TESTS");
}
// Ensure that Google Test output is printed before, e.g., heapchecker output.
@@ -4384,7 +4259,7 @@
public:
TestEventRepeater() : forwarding_enabled_(true) {}
virtual ~TestEventRepeater();
- void Append(TestEventListener *listener);
+ void Append(TestEventListener* listener);
TestEventListener* Release(TestEventListener* listener);
// Controls whether events will be forwarded to listeners_. Set to false
@@ -4420,12 +4295,12 @@
ForEach(listeners_, Delete<TestEventListener>);
}
-void TestEventRepeater::Append(TestEventListener *listener) {
+void TestEventRepeater::Append(TestEventListener* listener) {
listeners_.push_back(listener);
}
// TODO(vladl@google.com): Factor the search functionality into Vector::Find.
-TestEventListener* TestEventRepeater::Release(TestEventListener *listener) {
+TestEventListener* TestEventRepeater::Release(TestEventListener* listener) {
for (size_t i = 0; i < listeners_.size(); ++i) {
if (listeners_[i] == listener) {
listeners_.erase(listeners_.begin() + i);
@@ -4438,24 +4313,24 @@
// Since most methods are very similar, use macros to reduce boilerplate.
// This defines a member that forwards the call to all listeners.
-#define GTEST_REPEATER_METHOD_(Name, Type) \
-void TestEventRepeater::Name(const Type& parameter) { \
- if (forwarding_enabled_) { \
- for (size_t i = 0; i < listeners_.size(); i++) { \
- listeners_[i]->Name(parameter); \
- } \
- } \
-}
+#define GTEST_REPEATER_METHOD_(Name, Type) \
+ void TestEventRepeater::Name(const Type& parameter) { \
+ if (forwarding_enabled_) { \
+ for (size_t i = 0; i < listeners_.size(); i++) { \
+ listeners_[i]->Name(parameter); \
+ } \
+ } \
+ }
// This defines a member that forwards the call to all listeners in reverse
// order.
-#define GTEST_REVERSE_REPEATER_METHOD_(Name, Type) \
-void TestEventRepeater::Name(const Type& parameter) { \
- if (forwarding_enabled_) { \
- for (int i = static_cast<int>(listeners_.size()) - 1; i >= 0; i--) { \
- listeners_[i]->Name(parameter); \
- } \
- } \
-}
+#define GTEST_REVERSE_REPEATER_METHOD_(Name, Type) \
+ void TestEventRepeater::Name(const Type& parameter) { \
+ if (forwarding_enabled_) { \
+ for (int i = static_cast<int>(listeners_.size()) - 1; i >= 0; i--) { \
+ listeners_[i]->Name(parameter); \
+ } \
+ } \
+ }
GTEST_REPEATER_METHOD_(OnTestProgramStart, UnitTest)
GTEST_REPEATER_METHOD_(OnEnvironmentsSetUpStart, UnitTest)
@@ -4596,9 +4471,7 @@
// 3. To interpret the meaning of errno in a thread-safe way,
// we need the strerror_r() function, which is not available on
// Windows.
- fprintf(stderr,
- "Unable to open file \"%s\"\n",
- output_file_.c_str());
+ fprintf(stderr, "Unable to open file \"%s\"\n", output_file_.c_str());
fflush(stderr);
exit(EXIT_FAILURE);
}
@@ -4620,43 +4493,43 @@
// most invalid characters can be retained using character references.
// TODO(wan): It might be nice to have a minimally invasive, human-readable
// escaping scheme for invalid characters, rather than dropping them.
-std::string XmlUnitTestResultPrinter::EscapeXml(
- const std::string& str, bool is_attribute) {
+std::string XmlUnitTestResultPrinter::EscapeXml(const std::string& str,
+ bool is_attribute) {
Message m;
for (size_t i = 0; i < str.size(); ++i) {
const char ch = str[i];
switch (ch) {
- case '<':
- m << "<";
- break;
- case '>':
- m << ">";
- break;
- case '&':
- m << "&";
- break;
- case '\'':
- if (is_attribute)
- m << "'";
+ case '<':
+ m << "<";
+ break;
+ case '>':
+ m << ">";
+ break;
+ case '&':
+ m << "&";
+ break;
+ case '\'':
+ if (is_attribute)
+ m << "'";
+ else
+ m << '\'';
+ break;
+ case '"':
+ if (is_attribute)
+ m << """;
+ else
+ m << '"';
+ break;
+ default:
+ if (IsValidXmlCharacter(ch)) {
+ if (is_attribute && IsNormalizableWhitespace(ch))
+ m << "&#x" << String::FormatByte(static_cast<unsigned char>(ch))
+ << ";";
else
- m << '\'';
- break;
- case '"':
- if (is_attribute)
- m << """;
- else
- m << '"';
- break;
- default:
- if (IsValidXmlCharacter(ch)) {
- if (is_attribute && IsNormalizableWhitespace(ch))
- m << "&#x" << String::FormatByte(static_cast<unsigned char>(ch))
- << ";";
- else
- m << ch;
- }
- break;
+ m << ch;
+ }
+ break;
}
}
@@ -4671,8 +4544,7 @@
std::string output;
output.reserve(str.size());
for (std::string::const_iterator it = str.begin(); it != str.end(); ++it)
- if (IsValidXmlCharacter(*it))
- output.push_back(*it);
+ if (IsValidXmlCharacter(*it)) output.push_back(*it);
return output;
}
@@ -4696,7 +4568,7 @@
// Formats the given time in milliseconds as seconds.
std::string FormatTimeInMillisAsSeconds(TimeInMillis ms) {
::std::stringstream ss;
- ss << ms/1000.0;
+ ss << ms / 1000.0;
return ss.str();
}
@@ -4706,24 +4578,23 @@
// Using non-reentrant version as localtime_r is not portable.
time_t seconds = static_cast<time_t>(ms / 1000);
#ifdef _MSC_VER
-# pragma warning(push) // Saves the current warning state.
-# pragma warning(disable:4996) // Temporarily disables warning 4996
- // (function or variable may be unsafe).
+# pragma warning(push) // Saves the current warning state.
+# pragma warning(disable : 4996) // Temporarily disables warning 4996
+ // (function or variable may be unsafe).
const struct tm* const time_struct = localtime(&seconds); // NOLINT
-# pragma warning(pop) // Restores the warning state again.
+# pragma warning(pop) // Restores the warning state again.
#else
const struct tm* const time_struct = localtime(&seconds); // NOLINT
#endif
- if (time_struct == NULL)
- return ""; // Invalid ms value
+ if (time_struct == NULL) return ""; // Invalid ms value
// YYYY-MM-DDThh:mm:ss
return StreamableToString(time_struct->tm_year + 1900) + "-" +
- String::FormatIntWidth2(time_struct->tm_mon + 1) + "-" +
- String::FormatIntWidth2(time_struct->tm_mday) + "T" +
- String::FormatIntWidth2(time_struct->tm_hour) + ":" +
- String::FormatIntWidth2(time_struct->tm_min) + ":" +
- String::FormatIntWidth2(time_struct->tm_sec);
+ String::FormatIntWidth2(time_struct->tm_mon + 1) + "-" +
+ String::FormatIntWidth2(time_struct->tm_mday) + "T" +
+ String::FormatIntWidth2(time_struct->tm_hour) + ":" +
+ String::FormatIntWidth2(time_struct->tm_min) + ":" +
+ String::FormatIntWidth2(time_struct->tm_sec);
}
// Streams an XML CDATA section, escaping invalid CDATA sequences as needed.
@@ -4734,8 +4605,8 @@
for (;;) {
const char* const next_segment = strstr(segment, "]]>");
if (next_segment != NULL) {
- stream->write(
- segment, static_cast<std::streamsize>(next_segment - segment));
+ stream->write(segment,
+ static_cast<std::streamsize>(next_segment - segment));
*stream << "]]>]]><![CDATA[";
segment = next_segment + strlen("]]>");
} else {
@@ -4747,15 +4618,13 @@
}
void XmlUnitTestResultPrinter::OutputXmlAttribute(
- std::ostream* stream,
- const std::string& element_name,
- const std::string& name,
- const std::string& value) {
+ std::ostream* stream, const std::string& element_name,
+ const std::string& name, const std::string& value) {
const std::vector<std::string>& allowed_names =
GetReservedAttributesForElement(element_name);
GTEST_CHECK_(std::find(allowed_names.begin(), allowed_names.end(), name) !=
- allowed_names.end())
+ allowed_names.end())
<< "Attribute " << name << " is not allowed for element <" << element_name
<< ">.";
@@ -4799,8 +4668,7 @@
part.file_name(), part.line_number());
const string summary = location + "\n" + part.summary();
*stream << " <failure message=\""
- << EscapeXmlAttribute(summary.c_str())
- << "\" type=\"\">";
+ << EscapeXmlAttribute(summary.c_str()) << "\" type=\"\">";
const string detail = location + "\n" + part.message();
OutputXmlCDataSection(stream, RemoveInvalidXmlCharacters(detail).c_str());
*stream << "</failure>\n";
@@ -4886,7 +4754,7 @@
for (int i = 0; i < result.test_property_count(); ++i) {
const TestProperty& property = result.GetTestProperty(i);
attributes << " " << property.key() << "="
- << "\"" << EscapeXmlAttribute(property.value()) << "\"";
+ << "\"" << EscapeXmlAttribute(property.value()) << "\"";
}
return attributes.GetString();
}
@@ -4905,15 +4773,15 @@
result.reserve(strlen(str) + 1);
for (char ch = *str; ch != '\0'; ch = *++str) {
switch (ch) {
- case '%':
- case '=':
- case '&':
- case '\n':
- result.append("%" + String::FormatByte(static_cast<unsigned char>(ch)));
- break;
- default:
- result.push_back(ch);
- break;
+ case '%':
+ case '=':
+ case '&':
+ case '\n':
+ result.append("%" + String::FormatByte(static_cast<unsigned char>(ch)));
+ break;
+ default:
+ result.push_back(ch);
+ break;
}
}
return result;
@@ -4925,14 +4793,14 @@
addrinfo hints;
memset(&hints, 0, sizeof(hints));
- hints.ai_family = AF_UNSPEC; // To allow both IPv4 and IPv6 addresses.
+ hints.ai_family = AF_UNSPEC; // To allow both IPv4 and IPv6 addresses.
hints.ai_socktype = SOCK_STREAM;
addrinfo* servinfo = NULL;
// Use the getaddrinfo() to get a linked list of IP addresses for
// the given host name.
- const int error_num = getaddrinfo(
- host_name_.c_str(), port_num_.c_str(), &hints, &servinfo);
+ const int error_num =
+ getaddrinfo(host_name_.c_str(), port_num_.c_str(), &hints, &servinfo);
if (error_num != 0) {
GTEST_LOG_(WARNING) << "stream_result_to: getaddrinfo() failed: "
<< gai_strerror(error_num);
@@ -4941,8 +4809,8 @@
// Loop through all the results and connect to the first we can.
for (addrinfo* cur_addr = servinfo; sockfd_ == -1 && cur_addr != NULL;
cur_addr = cur_addr->ai_next) {
- sockfd_ = socket(
- cur_addr->ai_family, cur_addr->ai_socktype, cur_addr->ai_protocol);
+ sockfd_ = socket(cur_addr->ai_family, cur_addr->ai_socktype,
+ cur_addr->ai_protocol);
if (sockfd_ != -1) {
// Connect the client socket to the server socket.
if (connect(sockfd_, cur_addr->ai_addr, cur_addr->ai_addrlen) == -1) {
@@ -4978,12 +4846,10 @@
}
// Pops the info pushed by the c'tor.
-ScopedTrace::~ScopedTrace()
- GTEST_LOCK_EXCLUDED_(&UnitTest::mutex_) {
+ScopedTrace::~ScopedTrace() GTEST_LOCK_EXCLUDED_(&UnitTest::mutex_) {
UnitTest::GetInstance()->PopGTestTrace();
}
-
// class OsStackTraceGetter
// Returns the current OS stack trace as an std::string. Parameters:
@@ -4999,12 +4865,9 @@
return "";
}
-void OsStackTraceGetter::UponLeavingGTest()
- GTEST_LOCK_EXCLUDED_(mutex_) {
-}
+void OsStackTraceGetter::UponLeavingGTest() GTEST_LOCK_EXCLUDED_(mutex_) {}
-const char* const
-OsStackTraceGetter::kElidedFramesMarker =
+const char* const OsStackTraceGetter::kElidedFramesMarker =
"... " GTEST_NAME_ " internal frames ...";
// A helper class that creates the premature-exit file in its
@@ -5043,8 +4906,7 @@
TestEventListeners::TestEventListeners()
: repeater_(new internal::TestEventRepeater()),
default_result_printer_(NULL),
- default_xml_generator_(NULL) {
-}
+ default_xml_generator_(NULL) {}
TestEventListeners::~TestEventListeners() { delete repeater_; }
@@ -5082,8 +4944,7 @@
// list.
delete Release(default_result_printer_);
default_result_printer_ = listener;
- if (listener != NULL)
- Append(listener);
+ if (listener != NULL) Append(listener);
}
}
@@ -5098,8 +4959,7 @@
// list.
delete Release(default_xml_generator_);
default_xml_generator_ = listener;
- if (listener != NULL)
- Append(listener);
+ if (listener != NULL) Append(listener);
}
}
@@ -5196,7 +5056,7 @@
// Gets the time of the test program start, in ms from the start of the
// UNIX epoch.
internal::TimeInMillis UnitTest::start_timestamp() const {
- return impl()->start_timestamp();
+ return impl()->start_timestamp();
}
// Gets the elapsed time, in milliseconds.
@@ -5231,9 +5091,7 @@
// Returns the list of event listeners that can be used to track events
// inside Google Test.
-TestEventListeners& UnitTest::listeners() {
- return *impl()->listeners();
-}
+TestEventListeners& UnitTest::listeners() { return *impl()->listeners(); }
// Registers and returns a global test environment. When a test
// program is run, all global test environments will be set-up in the
@@ -5258,12 +5116,11 @@
// assertion macros (e.g. ASSERT_TRUE, EXPECT_EQ, etc) eventually call
// this to report their results. The user code should use the
// assertion macros instead of calling this directly.
-void UnitTest::AddTestPartResult(
- TestPartResult::Type result_type,
- const char* file_name,
- int line_number,
- const std::string& message,
- const std::string& os_stack_trace) GTEST_LOCK_EXCLUDED_(mutex_) {
+void UnitTest::AddTestPartResult(TestPartResult::Type result_type,
+ const char* file_name, int line_number,
+ const std::string& message,
+ const std::string& os_stack_trace)
+ GTEST_LOCK_EXCLUDED_(mutex_) {
Message msg;
msg << message;
@@ -5271,11 +5128,12 @@
if (impl_->gtest_trace_stack().size() > 0) {
msg << "\n" << GTEST_NAME_ << " trace:";
- for (int i = static_cast<int>(impl_->gtest_trace_stack().size());
- i > 0; --i) {
+ for (int i = static_cast<int>(impl_->gtest_trace_stack().size()); i > 0;
+ --i) {
const internal::TraceInfo& trace = impl_->gtest_trace_stack()[i - 1];
- msg << "\n" << internal::FormatFileLocation(trace.file, trace.line)
- << " " << trace.message;
+ msg << "\n"
+ << internal::FormatFileLocation(trace.file, trace.line) << " "
+ << trace.message;
}
}
@@ -5283,11 +5141,10 @@
msg << internal::kStackTraceMarker << os_stack_trace;
}
- const TestPartResult result =
- TestPartResult(result_type, file_name, line_number,
- msg.GetString().c_str());
- impl_->GetTestPartResultReporterForCurrentThread()->
- ReportTestPartResult(result);
+ const TestPartResult result = TestPartResult(
+ result_type, file_name, line_number, msg.GetString().c_str());
+ impl_->GetTestPartResultReporterForCurrentThread()->ReportTestPartResult(
+ result);
if (result_type != TestPartResult::kSuccess) {
// gtest_break_on_failure takes precedence over
@@ -5361,8 +5218,9 @@
// that understands the premature-exit-file protocol to report the
// test as having failed.
const internal::ScopedPrematureExitFile premature_exit_file(
- in_death_test_child_process ?
- NULL : internal::posix::GetEnv("TEST_PREMATURE_EXIT_FILE"));
+ in_death_test_child_process
+ ? NULL
+ : internal::posix::GetEnv("TEST_PREMATURE_EXIT_FILE"));
// Captures the value of GTEST_FLAG(catch_exceptions). This value will be
// used for the duration of the program.
@@ -5374,20 +5232,20 @@
// process. In either case the user does not want to see pop-up dialogs
// about crashes - they are expected.
if (impl()->catch_exceptions() || in_death_test_child_process) {
-# if !GTEST_OS_WINDOWS_MOBILE
+# if !GTEST_OS_WINDOWS_MOBILE
// SetErrorMode doesn't exist on CE.
SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOALIGNMENTFAULTEXCEPT |
SEM_NOGPFAULTERRORBOX | SEM_NOOPENFILEERRORBOX);
-# endif // !GTEST_OS_WINDOWS_MOBILE
+# endif // !GTEST_OS_WINDOWS_MOBILE
-# if (defined(_MSC_VER) || GTEST_OS_WINDOWS_MINGW) && !GTEST_OS_WINDOWS_MOBILE
+# if (defined(_MSC_VER) || GTEST_OS_WINDOWS_MINGW) && !GTEST_OS_WINDOWS_MOBILE
// Death test children can be terminated with _abort(). On Windows,
// _abort() can show a dialog with a warning message. This forces the
// abort message to go to stderr instead.
_set_error_mode(_OUT_TO_STDERR);
-# endif
+# endif
-# if _MSC_VER >= 1400 && !GTEST_OS_WINDOWS_MOBILE
+# if _MSC_VER >= 1400 && !GTEST_OS_WINDOWS_MOBILE
// In the debug version, Visual Studio pops up a separate dialog
// offering a choice to debug the aborted program. We need to suppress
// this dialog or it will pop up for every EXPECT/ASSERT_DEATH statement
@@ -5403,14 +5261,15 @@
_set_abort_behavior(
0x0, // Clear the following flags:
_WRITE_ABORT_MSG | _CALL_REPORTFAULT); // pop-up window, core dump.
-# endif
+# endif
}
#endif // GTEST_HAS_SEH
return internal::HandleExceptionsInMethodIfSupported(
- impl(),
- &internal::UnitTestImpl::RunAllTests,
- "auxiliary test code (environments or event listeners)") ? 0 : 1;
+ impl(), &internal::UnitTestImpl::RunAllTests,
+ "auxiliary test code (environments or event listeners)")
+ ? 0
+ : 1;
}
// Returns the working directory when the first TEST() or TEST_F() was
@@ -5441,22 +5300,17 @@
#if GTEST_HAS_PARAM_TEST
// Returns ParameterizedTestCaseRegistry object used to keep track of
// value-parameterized tests and instantiate and register them.
-internal::ParameterizedTestCaseRegistry&
- UnitTest::parameterized_test_registry()
- GTEST_LOCK_EXCLUDED_(mutex_) {
+internal::ParameterizedTestCaseRegistry& UnitTest::parameterized_test_registry()
+ GTEST_LOCK_EXCLUDED_(mutex_) {
return impl_->parameterized_test_registry();
}
#endif // GTEST_HAS_PARAM_TEST
// Creates an empty UnitTest.
-UnitTest::UnitTest() {
- impl_ = new internal::UnitTestImpl(this);
-}
+UnitTest::UnitTest() { impl_ = new internal::UnitTestImpl(this); }
// Destructor of UnitTest.
-UnitTest::~UnitTest() {
- delete impl_;
-}
+UnitTest::~UnitTest() { delete impl_; }
// Pushes a trace defined by SCOPED_TRACE() on to the per-thread
// Google Test trace stack.
@@ -5467,8 +5321,7 @@
}
// Pops a trace from the per-thread Google Test trace stack.
-void UnitTest::PopGTestTrace()
- GTEST_LOCK_EXCLUDED_(mutex_) {
+void UnitTest::PopGTestTrace() GTEST_LOCK_EXCLUDED_(mutex_) {
internal::MutexLock lock(&mutex_);
impl_->gtest_trace_stack().pop_back();
}
@@ -5478,12 +5331,12 @@
UnitTestImpl::UnitTestImpl(UnitTest* parent)
: parent_(parent),
#ifdef _MSC_VER
-# pragma warning(push) // Saves the current warning state.
-# pragma warning(disable:4355) // Temporarily disables warning 4355
- // (using this in initializer).
+# pragma warning(push) // Saves the current warning state.
+# pragma warning(disable : 4355) // Temporarily disables warning 4355
+ // (using this in initializer).
default_global_test_part_result_reporter_(this),
default_per_thread_test_part_result_reporter_(this),
-# pragma warning(pop) // Restores the warning state again.
+# pragma warning(pop) // Restores the warning state again.
#else
default_global_test_part_result_reporter_(this),
default_per_thread_test_part_result_reporter_(this),
@@ -5503,7 +5356,7 @@
os_stack_trace_getter_(NULL),
post_flag_parse_init_performed_(false),
random_seed_(0), // Will be overridden by the flag before first use.
- random_(0), // Will be reseeded before first use.
+ random_(0), // Will be reseeded before first use.
start_timestamp_(0),
elapsed_time_(0),
#if GTEST_HAS_DEATH_TEST
@@ -5577,8 +5430,8 @@
if (!target.empty()) {
const size_t pos = target.find(':');
if (pos != std::string::npos) {
- listeners()->Append(new StreamingListener(target.substr(0, pos),
- target.substr(pos+1)));
+ listeners()->Append(
+ new StreamingListener(target.substr(0, pos), target.substr(pos + 1)));
} else {
printf("WARNING: unrecognized streaming target \"%s\" ignored.\n",
target.c_str());
@@ -5630,8 +5483,7 @@
class TestCaseNameIs {
public:
// Constructor.
- explicit TestCaseNameIs(const std::string& name)
- : name_(name) {}
+ explicit TestCaseNameIs(const std::string& name) : name_(name) {}
// Returns true iff the name of test_case matches name_.
bool operator()(const TestCase* test_case) const {
@@ -5659,12 +5511,10 @@
Test::SetUpTestCaseFunc set_up_tc,
Test::TearDownTestCaseFunc tear_down_tc) {
// Can we find a TestCase with the given name?
- const std::vector<TestCase*>::const_iterator test_case =
- std::find_if(test_cases_.begin(), test_cases_.end(),
- TestCaseNameIs(test_case_name));
+ const std::vector<TestCase*>::const_iterator test_case = std::find_if(
+ test_cases_.begin(), test_cases_.end(), TestCaseNameIs(test_case_name));
- if (test_case != test_cases_.end())
- return *test_case;
+ if (test_case != test_cases_.end()) return *test_case;
// No. Let's create one.
TestCase* const new_test_case =
@@ -5713,8 +5563,7 @@
}
// Do not run any test if the --help flag was specified.
- if (g_help_flag)
- return true;
+ if (g_help_flag) return true;
// Repeats the call to the post-flag parsing initialization in case the
// user didn't call InitGoogleTest.
@@ -5738,9 +5587,9 @@
// Compares the full test names with the filter to decide which
// tests to run.
- const bool has_tests_to_run = FilterTests(should_shard
- ? HONOR_SHARDING_PROTOCOL
- : IGNORE_SHARDING_PROTOCOL) > 0;
+ const bool has_tests_to_run =
+ FilterTests(should_shard ? HONOR_SHARDING_PROTOCOL
+ : IGNORE_SHARDING_PROTOCOL) > 0;
// Lists the tests and exits if the --gtest_list_tests flag was specified.
if (GTEST_FLAG(list_tests)) {
@@ -5749,8 +5598,8 @@
return true;
}
- random_seed_ = GTEST_FLAG(shuffle) ?
- GetRandomSeedFromFlag(GTEST_FLAG(random_seed)) : 0;
+ random_seed_ =
+ GTEST_FLAG(shuffle) ? GetRandomSeedFromFlag(GTEST_FLAG(random_seed)) : 0;
// True iff at least one test has failed.
bool failed = false;
@@ -5862,8 +5711,7 @@
// an error and exits. If in_subprocess_for_death_test, sharding is
// disabled because it must only be applied to the original test
// process. Otherwise, we could filter out death tests we intended to execute.
-bool ShouldShard(const char* total_shards_env,
- const char* shard_index_env,
+bool ShouldShard(const char* total_shards_env, const char* shard_index_env,
bool in_subprocess_for_death_test) {
if (in_subprocess_for_death_test) {
return false;
@@ -5875,27 +5723,27 @@
if (total_shards == -1 && shard_index == -1) {
return false;
} else if (total_shards == -1 && shard_index != -1) {
- const Message msg = Message()
- << "Invalid environment variables: you have "
- << kTestShardIndex << " = " << shard_index
- << ", but have left " << kTestTotalShards << " unset.\n";
+ const Message msg = Message() << "Invalid environment variables: you have "
+ << kTestShardIndex << " = " << shard_index
+ << ", but have left " << kTestTotalShards
+ << " unset.\n";
ColoredPrintf(COLOR_RED, msg.GetString().c_str());
fflush(stdout);
exit(EXIT_FAILURE);
} else if (total_shards != -1 && shard_index == -1) {
const Message msg = Message()
- << "Invalid environment variables: you have "
- << kTestTotalShards << " = " << total_shards
- << ", but have left " << kTestShardIndex << " unset.\n";
+ << "Invalid environment variables: you have "
+ << kTestTotalShards << " = " << total_shards
+ << ", but have left " << kTestShardIndex << " unset.\n";
ColoredPrintf(COLOR_RED, msg.GetString().c_str());
fflush(stdout);
exit(EXIT_FAILURE);
} else if (shard_index < 0 || shard_index >= total_shards) {
- const Message msg = Message()
- << "Invalid environment variables: we require 0 <= "
- << kTestShardIndex << " < " << kTestTotalShards
- << ", but you have " << kTestShardIndex << "=" << shard_index
- << ", " << kTestTotalShards << "=" << total_shards << ".\n";
+ const Message msg =
+ Message() << "Invalid environment variables: we require 0 <= "
+ << kTestShardIndex << " < " << kTestTotalShards
+ << ", but you have " << kTestShardIndex << "=" << shard_index
+ << ", " << kTestTotalShards << "=" << total_shards << ".\n";
ColoredPrintf(COLOR_RED, msg.GetString().c_str());
fflush(stdout);
exit(EXIT_FAILURE);
@@ -5937,10 +5785,12 @@
// http://code.google.com/p/googletest/wiki/GoogleTestAdvancedGuide.
// Returns the number of tests that should run.
int UnitTestImpl::FilterTests(ReactionToSharding shard_tests) {
- const Int32 total_shards = shard_tests == HONOR_SHARDING_PROTOCOL ?
- Int32FromEnvOrDie(kTestTotalShards, -1) : -1;
- const Int32 shard_index = shard_tests == HONOR_SHARDING_PROTOCOL ?
- Int32FromEnvOrDie(kTestShardIndex, -1) : -1;
+ const Int32 total_shards = shard_tests == HONOR_SHARDING_PROTOCOL
+ ? Int32FromEnvOrDie(kTestTotalShards, -1)
+ : -1;
+ const Int32 shard_index = shard_tests == HONOR_SHARDING_PROTOCOL
+ ? Int32FromEnvOrDie(kTestShardIndex, -1)
+ : -1;
// num_runnable_tests are the number of tests that will
// run across all shards (i.e., match filter and are not disabled).
@@ -5950,7 +5800,7 @@
int num_selected_tests = 0;
for (size_t i = 0; i < test_cases_.size(); i++) {
TestCase* const test_case = test_cases_[i];
- const std::string &test_case_name = test_case->name();
+ const std::string& test_case_name = test_case->name();
test_case->set_should_run(false);
for (size_t j = 0; j < test_case->test_info_list().size(); j++) {
@@ -5958,26 +5808,24 @@
const std::string test_name(test_info->name());
// A test is disabled if test case name or test name matches
// kDisableTestFilter.
- const bool is_disabled =
- internal::UnitTestOptions::MatchesFilter(test_case_name,
- kDisableTestFilter) ||
- internal::UnitTestOptions::MatchesFilter(test_name,
- kDisableTestFilter);
+ const bool is_disabled = internal::UnitTestOptions::MatchesFilter(
+ test_case_name, kDisableTestFilter) ||
+ internal::UnitTestOptions::MatchesFilter(
+ test_name, kDisableTestFilter);
test_info->is_disabled_ = is_disabled;
- const bool matches_filter =
- internal::UnitTestOptions::FilterMatchesTest(test_case_name,
- test_name);
+ const bool matches_filter = internal::UnitTestOptions::FilterMatchesTest(
+ test_case_name, test_name);
test_info->matches_filter_ = matches_filter;
const bool is_runnable =
(GTEST_FLAG(also_run_disabled_tests) || !is_disabled) &&
matches_filter;
- const bool is_selected = is_runnable &&
+ const bool is_selected =
+ is_runnable &&
(shard_tests == IGNORE_SHARDING_PROTOCOL ||
- ShouldRunTestOnShard(total_shards, shard_index,
- num_runnable_tests));
+ ShouldRunTestOnShard(total_shards, shard_index, num_runnable_tests));
num_runnable_tests += is_runnable;
num_selected_tests += is_selected;
@@ -6021,8 +5869,7 @@
bool printed_test_case_name = false;
for (size_t j = 0; j < test_case->test_info_list().size(); j++) {
- const TestInfo* const test_info =
- test_case->test_info_list()[j];
+ const TestInfo* const test_info = test_case->test_info_list()[j];
if (test_info->matches_filter_) {
if (!printed_test_case_name) {
printed_test_case_name = true;
@@ -6076,8 +5923,8 @@
// Returns the TestResult for the test that's currently running, or
// the TestResult for the ad hoc test if no test is running.
TestResult* UnitTestImpl::current_test_result() {
- return current_test_info_ ?
- &(current_test_info_->result_) : &ad_hoc_test_result_;
+ return current_test_info_ ? &(current_test_info_->result_)
+ : &ad_hoc_test_result_;
}
// Shuffles all test cases, and the tests within each test case,
@@ -6127,7 +5974,7 @@
// suppress unreachable code warnings.
namespace {
class ClassUniqueToAlwaysTrue {};
-}
+} // namespace
bool IsTrue(bool condition) { return condition; }
@@ -6135,8 +5982,7 @@
#if GTEST_HAS_EXCEPTIONS
// This condition is always false so AlwaysTrue() never actually throws,
// but it makes the compiler think that it may throw.
- if (IsTrue(false))
- throw ClassUniqueToAlwaysTrue();
+ if (IsTrue(false)) throw ClassUniqueToAlwaysTrue();
#endif // GTEST_HAS_EXCEPTIONS
return true;
}
@@ -6158,8 +6004,7 @@
// part can be omitted.
//
// Returns the value of the flag, or NULL if the parsing failed.
-const char* ParseFlagValue(const char* str,
- const char* flag,
+const char* ParseFlagValue(const char* str, const char* flag,
bool def_optional) {
// str and flag must not be NULL.
if (str == NULL || flag == NULL) return NULL;
@@ -6221,8 +6066,8 @@
if (value_str == NULL) return false;
// Sets *value to the value of the flag.
- return ParseInt32(Message() << "The value of flag --" << flag,
- value_str, value);
+ return ParseInt32(Message() << "The value of flag --" << flag, value_str,
+ value);
}
// Parses a string for a string flag, in the form of
@@ -6249,8 +6094,7 @@
// GTEST_INTERNAL_PREFIX_ followed by "internal_" are considered Google Test
// internal flags and do not trigger the help message.
static bool HasGoogleTestFlagPrefix(const char* str) {
- return (SkipPrefix("--", &str) ||
- SkipPrefix("-", &str) ||
+ return (SkipPrefix("--", &str) || SkipPrefix("-", &str) ||
SkipPrefix("/", &str)) &&
!SkipPrefix(GTEST_FLAG_PREFIX_ "internal_", &str) &&
(SkipPrefix(GTEST_FLAG_PREFIX_, &str) ||
@@ -6303,68 +6147,92 @@
}
static const char kColorEncodedHelpMessage[] =
-"This program contains tests written using " GTEST_NAME_ ". You can use the\n"
-"following command line flags to control its behavior:\n"
-"\n"
-"Test Selection:\n"
-" @G--" GTEST_FLAG_PREFIX_ "list_tests@D\n"
-" List the names of all tests instead of running them. The name of\n"
-" TEST(Foo, Bar) is \"Foo.Bar\".\n"
-" @G--" GTEST_FLAG_PREFIX_ "filter=@YPOSTIVE_PATTERNS"
+ "This program contains tests written using " GTEST_NAME_
+ ". You can use the\n"
+ "following command line flags to control its behavior:\n"
+ "\n"
+ "Test Selection:\n"
+ " @G--" GTEST_FLAG_PREFIX_
+ "list_tests@D\n"
+ " List the names of all tests instead of running them. The name of\n"
+ " TEST(Foo, Bar) is \"Foo.Bar\".\n"
+ " @G--" GTEST_FLAG_PREFIX_
+ "filter=@YPOSTIVE_PATTERNS"
"[@G-@YNEGATIVE_PATTERNS]@D\n"
-" Run only the tests whose name matches one of the positive patterns but\n"
-" none of the negative patterns. '?' matches any single character; '*'\n"
-" matches any substring; ':' separates two patterns.\n"
-" @G--" GTEST_FLAG_PREFIX_ "also_run_disabled_tests@D\n"
-" Run all disabled tests too.\n"
-"\n"
-"Test Execution:\n"
-" @G--" GTEST_FLAG_PREFIX_ "repeat=@Y[COUNT]@D\n"
-" Run the tests repeatedly; use a negative count to repeat forever.\n"
-" @G--" GTEST_FLAG_PREFIX_ "shuffle@D\n"
-" Randomize tests' orders on every iteration.\n"
-" @G--" GTEST_FLAG_PREFIX_ "random_seed=@Y[NUMBER]@D\n"
-" Random number seed to use for shuffling test orders (between 1 and\n"
-" 99999, or 0 to use a seed based on the current time).\n"
-"\n"
-"Test Output:\n"
-" @G--" GTEST_FLAG_PREFIX_ "color=@Y(@Gyes@Y|@Gno@Y|@Gauto@Y)@D\n"
-" Enable/disable colored output. The default is @Gauto@D.\n"
-" -@G-" GTEST_FLAG_PREFIX_ "print_time=0@D\n"
-" Don't print the elapsed time of each test.\n"
-" @G--" GTEST_FLAG_PREFIX_ "output=xml@Y[@G:@YDIRECTORY_PATH@G"
- GTEST_PATH_SEP_ "@Y|@G:@YFILE_PATH]@D\n"
-" Generate an XML report in the given directory or with the given file\n"
-" name. @YFILE_PATH@D defaults to @Gtest_details.xml@D.\n"
+ " Run only the tests whose name matches one of the positive patterns "
+ "but\n"
+ " none of the negative patterns. '?' matches any single character; "
+ "'*'\n"
+ " matches any substring; ':' separates two patterns.\n"
+ " @G--" GTEST_FLAG_PREFIX_
+ "also_run_disabled_tests@D\n"
+ " Run all disabled tests too.\n"
+ "\n"
+ "Test Execution:\n"
+ " @G--" GTEST_FLAG_PREFIX_
+ "repeat=@Y[COUNT]@D\n"
+ " Run the tests repeatedly; use a negative count to repeat forever.\n"
+ " @G--" GTEST_FLAG_PREFIX_
+ "shuffle@D\n"
+ " Randomize tests' orders on every iteration.\n"
+ " @G--" GTEST_FLAG_PREFIX_
+ "random_seed=@Y[NUMBER]@D\n"
+ " Random number seed to use for shuffling test orders (between 1 and\n"
+ " 99999, or 0 to use a seed based on the current time).\n"
+ "\n"
+ "Test Output:\n"
+ " @G--" GTEST_FLAG_PREFIX_
+ "color=@Y(@Gyes@Y|@Gno@Y|@Gauto@Y)@D\n"
+ " Enable/disable colored output. The default is @Gauto@D.\n"
+ " -@G-" GTEST_FLAG_PREFIX_
+ "print_time=0@D\n"
+ " Don't print the elapsed time of each test.\n"
+ " @G--" GTEST_FLAG_PREFIX_
+ "output=xml@Y[@G:@YDIRECTORY_PATH@G" GTEST_PATH_SEP_
+ "@Y|@G:@YFILE_PATH]@D\n"
+ " Generate an XML report in the given directory or with the given "
+ "file\n"
+ " name. @YFILE_PATH@D defaults to @Gtest_details.xml@D.\n"
#if GTEST_CAN_STREAM_RESULTS_
-" @G--" GTEST_FLAG_PREFIX_ "stream_result_to=@YHOST@G:@YPORT@D\n"
-" Stream test results to the given server.\n"
+ " @G--" GTEST_FLAG_PREFIX_
+ "stream_result_to=@YHOST@G:@YPORT@D\n"
+ " Stream test results to the given server.\n"
#endif // GTEST_CAN_STREAM_RESULTS_
-"\n"
-"Assertion Behavior:\n"
+ "\n"
+ "Assertion Behavior:\n"
#if GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS
-" @G--" GTEST_FLAG_PREFIX_ "death_test_style=@Y(@Gfast@Y|@Gthreadsafe@Y)@D\n"
-" Set the default death test style.\n"
+ " @G--" GTEST_FLAG_PREFIX_
+ "death_test_style=@Y(@Gfast@Y|@Gthreadsafe@Y)@D\n"
+ " Set the default death test style.\n"
#endif // GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS
-" @G--" GTEST_FLAG_PREFIX_ "break_on_failure@D\n"
-" Turn assertion failures into debugger break-points.\n"
-" @G--" GTEST_FLAG_PREFIX_ "throw_on_failure@D\n"
-" Turn assertion failures into C++ exceptions.\n"
-" @G--" GTEST_FLAG_PREFIX_ "catch_exceptions=0@D\n"
-" Do not report exceptions as test failures. Instead, allow them\n"
-" to crash the program or throw a pop-up (on Windows).\n"
-"\n"
-"Except for @G--" GTEST_FLAG_PREFIX_ "list_tests@D, you can alternatively set "
+ " @G--" GTEST_FLAG_PREFIX_
+ "break_on_failure@D\n"
+ " Turn assertion failures into debugger break-points.\n"
+ " @G--" GTEST_FLAG_PREFIX_
+ "throw_on_failure@D\n"
+ " Turn assertion failures into C++ exceptions.\n"
+ " @G--" GTEST_FLAG_PREFIX_
+ "catch_exceptions=0@D\n"
+ " Do not report exceptions as test failures. Instead, allow them\n"
+ " to crash the program or throw a pop-up (on Windows).\n"
+ "\n"
+ "Except for @G--" GTEST_FLAG_PREFIX_
+ "list_tests@D, you can alternatively set "
"the corresponding\n"
-"environment variable of a flag (all letters in upper-case). For example, to\n"
-"disable colored text output, you can either specify @G--" GTEST_FLAG_PREFIX_
+ "environment variable of a flag (all letters in upper-case). For example, "
+ "to\n"
+ "disable colored text output, you can either specify "
+ "@G--" GTEST_FLAG_PREFIX_
"color=no@D or set\n"
-"the @G" GTEST_FLAG_PREFIX_UPPER_ "COLOR@D environment variable to @Gno@D.\n"
-"\n"
-"For more information, please read the " GTEST_NAME_ " documentation at\n"
-"@G" GTEST_PROJECT_URL_ "@D. If you find a bug in " GTEST_NAME_ "\n"
-"(not one in your own code or tests), please report it to\n"
-"@G<" GTEST_DEV_EMAIL_ ">@D.\n";
+ "the @G" GTEST_FLAG_PREFIX_UPPER_
+ "COLOR@D environment variable to @Gno@D.\n"
+ "\n"
+ "For more information, please read the " GTEST_NAME_
+ " documentation at\n"
+ "@G" GTEST_PROJECT_URL_ "@D. If you find a bug in " GTEST_NAME_
+ "\n"
+ "(not one in your own code or tests), please report it to\n"
+ "@G<" GTEST_DEV_EMAIL_ ">@D.\n";
// Parses the command line for Google Test flags, without initializing
// other parts of Google Test. The type parameter CharType can be
@@ -6405,8 +6273,7 @@
ParseStringFlag(arg, kStreamResultToFlag,
>EST_FLAG(stream_result_to)) ||
ParseBoolFlag(arg, kThrowOnFailureFlag,
- >EST_FLAG(throw_on_failure))
- ) {
+ >EST_FLAG(throw_on_failure))) {
// Yes. Shift the remainder of the argv list left by one. Note
// that argv has (*argc + 1) elements, the last one always being
// NULL. The following loop moves the trailing NULL element as
@@ -6530,37 +6397,35 @@
//
// This file implements death tests.
-
#if GTEST_HAS_DEATH_TEST
-# if GTEST_OS_MAC
-# include <crt_externs.h>
-# endif // GTEST_OS_MAC
+# if GTEST_OS_MAC
+# include <crt_externs.h>
+# endif // GTEST_OS_MAC
-# include <errno.h>
-# include <fcntl.h>
-# include <limits.h>
+# include <errno.h>
+# include <fcntl.h>
+# include <limits.h>
-# if GTEST_OS_LINUX
-# include <signal.h>
-# endif // GTEST_OS_LINUX
+# if GTEST_OS_LINUX
+# include <signal.h>
+# endif // GTEST_OS_LINUX
-# include <stdarg.h>
+# include <stdarg.h>
-# if GTEST_OS_WINDOWS
-# include <windows.h>
-# else
-# include <sys/mman.h>
-# include <sys/wait.h>
-# endif // GTEST_OS_WINDOWS
+# if GTEST_OS_WINDOWS
+# include <windows.h>
+# else
+# include <sys/mman.h>
+# include <sys/wait.h>
+# endif // GTEST_OS_WINDOWS
-# if GTEST_OS_QNX
-# include <spawn.h>
-# endif // GTEST_OS_QNX
+# if GTEST_OS_QNX
+# include <spawn.h>
+# endif // GTEST_OS_QNX
#endif // GTEST_HAS_DEATH_TEST
-
// Indicates that this translation unit is part of Google Test's
// implementation. It must come before gtest-internal-inl.h is
// included, or there will be a compiler error. This trick is to
@@ -6622,50 +6487,48 @@
// tests. IMPORTANT: This is an internal utility. Using it may break the
// implementation of death tests. User code MUST NOT use it.
bool InDeathTestChild() {
-# if GTEST_OS_WINDOWS
+# if GTEST_OS_WINDOWS
// On Windows, death tests are thread-safe regardless of the value of the
// death_test_style flag.
return !GTEST_FLAG(internal_run_death_test).empty();
-# else
+# else
if (GTEST_FLAG(death_test_style) == "threadsafe")
return !GTEST_FLAG(internal_run_death_test).empty();
else
return g_in_fast_death_test_child;
-#endif
+# endif
}
} // namespace internal
// ExitedWithCode constructor.
-ExitedWithCode::ExitedWithCode(int exit_code) : exit_code_(exit_code) {
-}
+ExitedWithCode::ExitedWithCode(int exit_code) : exit_code_(exit_code) {}
// ExitedWithCode function-call operator.
bool ExitedWithCode::operator()(int exit_status) const {
-# if GTEST_OS_WINDOWS
+# if GTEST_OS_WINDOWS
return exit_status == exit_code_;
-# else
+# else
return WIFEXITED(exit_status) && WEXITSTATUS(exit_status) == exit_code_;
-# endif // GTEST_OS_WINDOWS
+# endif // GTEST_OS_WINDOWS
}
-# if !GTEST_OS_WINDOWS
+# if !GTEST_OS_WINDOWS
// KilledBySignal constructor.
-KilledBySignal::KilledBySignal(int signum) : signum_(signum) {
-}
+KilledBySignal::KilledBySignal(int signum) : signum_(signum) {}
// KilledBySignal function-call operator.
bool KilledBySignal::operator()(int exit_status) const {
return WIFSIGNALED(exit_status) && WTERMSIG(exit_status) == signum_;
}
-# endif // !GTEST_OS_WINDOWS
+# endif // !GTEST_OS_WINDOWS
namespace internal {
@@ -6676,23 +6539,23 @@
static std::string ExitSummary(int exit_code) {
Message m;
-# if GTEST_OS_WINDOWS
+# if GTEST_OS_WINDOWS
m << "Exited with exit status " << exit_code;
-# else
+# else
if (WIFEXITED(exit_code)) {
m << "Exited with exit status " << WEXITSTATUS(exit_code);
} else if (WIFSIGNALED(exit_code)) {
m << "Terminated by signal " << WTERMSIG(exit_code);
}
-# ifdef WCOREDUMP
+# ifdef WCOREDUMP
if (WCOREDUMP(exit_code)) {
m << " (core dumped)";
}
-# endif
-# endif // GTEST_OS_WINDOWS
+# endif
+# endif // GTEST_OS_WINDOWS
return m.GetString();
}
@@ -6703,7 +6566,7 @@
return !ExitedWithCode(0)(exit_status);
}
-# if !GTEST_OS_WINDOWS
+# if !GTEST_OS_WINDOWS
// Generates a textual failure message when a death test finds more than
// one thread running, or cannot determine the number of threads, prior
// to executing the given statement. It is the responsibility of the
@@ -6718,7 +6581,7 @@
msg << "detected " << thread_count << " threads.";
return msg.GetString();
}
-# endif // !GTEST_OS_WINDOWS
+# endif // !GTEST_OS_WINDOWS
// Flag characters for reporting a death test that did not die.
static const char kDeathTestLived = 'L';
@@ -6763,15 +6626,15 @@
// A replacement for CHECK that calls DeathTestAbort if the assertion
// fails.
-# define GTEST_DEATH_TEST_CHECK_(expression) \
- do { \
- if (!::testing::internal::IsTrue(expression)) { \
- DeathTestAbort( \
- ::std::string("CHECK failed: File ") + __FILE__ + ", line " \
- + ::testing::internal::StreamableToString(__LINE__) + ": " \
- + #expression); \
- } \
- } while (::testing::internal::AlwaysFalse())
+# define GTEST_DEATH_TEST_CHECK_(expression) \
+ do { \
+ if (!::testing::internal::IsTrue(expression)) { \
+ DeathTestAbort(::std::string("CHECK failed: File ") + __FILE__ + \
+ ", line " + \
+ ::testing::internal::StreamableToString(__LINE__) + \
+ ": " + #expression); \
+ } \
+ } while (::testing::internal::AlwaysFalse())
// This macro is similar to GTEST_DEATH_TEST_CHECK_, but it is meant for
// evaluating any system call that fulfills two conditions: it must return
@@ -6780,23 +6643,23 @@
// evaluates the expression as long as it evaluates to -1 and sets
// errno to EINTR. If the expression evaluates to -1 but errno is
// something other than EINTR, DeathTestAbort is called.
-# define GTEST_DEATH_TEST_CHECK_SYSCALL_(expression) \
- do { \
- int gtest_retval; \
- do { \
- gtest_retval = (expression); \
- } while (gtest_retval == -1 && errno == EINTR); \
- if (gtest_retval == -1) { \
- DeathTestAbort( \
- ::std::string("CHECK failed: File ") + __FILE__ + ", line " \
- + ::testing::internal::StreamableToString(__LINE__) + ": " \
- + #expression + " != -1"); \
- } \
- } while (::testing::internal::AlwaysFalse())
+# define GTEST_DEATH_TEST_CHECK_SYSCALL_(expression) \
+ do { \
+ int gtest_retval; \
+ do { \
+ gtest_retval = (expression); \
+ } while (gtest_retval == -1 && errno == EINTR); \
+ if (gtest_retval == -1) { \
+ DeathTestAbort(::std::string("CHECK failed: File ") + __FILE__ + \
+ ", line " + \
+ ::testing::internal::StreamableToString(__LINE__) + \
+ ": " + #expression + " != -1"); \
+ } \
+ } while (::testing::internal::AlwaysFalse())
// Returns the message describing the last system error in errno.
std::string GetLastErrnoDescription() {
- return errno == 0 ? "" : posix::StrError(errno);
+ return errno == 0 ? "" : posix::StrError(errno);
}
// This is called from a death test parent process to read a failure
@@ -6829,17 +6692,18 @@
DeathTest::DeathTest() {
TestInfo* const info = GetUnitTestImpl()->current_test_info();
if (info == NULL) {
- DeathTestAbort("Cannot run a death test outside of a TEST or "
- "TEST_F construct");
+ DeathTestAbort(
+ "Cannot run a death test outside of a TEST or "
+ "TEST_F construct");
}
}
// Creates and returns a death test by dispatching to the current
// death test factory.
-bool DeathTest::Create(const char* statement, const RE* regex,
- const char* file, int line, DeathTest** test) {
- return GetUnitTestImpl()->death_test_factory()->Create(
- statement, regex, file, line, test);
+bool DeathTest::Create(const char* statement, const RE* regex, const char* file,
+ int line, DeathTest** test) {
+ return GetUnitTestImpl()->death_test_factory()->Create(statement, regex, file,
+ line, test);
}
const char* DeathTest::LastMessage() {
@@ -6932,22 +6796,22 @@
set_outcome(DIED);
} else if (bytes_read == 1) {
switch (flag) {
- case kDeathTestReturned:
- set_outcome(RETURNED);
- break;
- case kDeathTestThrew:
- set_outcome(THREW);
- break;
- case kDeathTestLived:
- set_outcome(LIVED);
- break;
- case kDeathTestInternalError:
- FailFromInternalError(read_fd()); // Does not return.
- break;
- default:
- GTEST_LOG_(FATAL) << "Death test child process reported "
- << "unexpected status byte ("
- << static_cast<unsigned int>(flag) << ")";
+ case kDeathTestReturned:
+ set_outcome(RETURNED);
+ break;
+ case kDeathTestThrew:
+ set_outcome(THREW);
+ break;
+ case kDeathTestLived:
+ set_outcome(LIVED);
+ break;
+ case kDeathTestInternalError:
+ FailFromInternalError(read_fd()); // Does not return.
+ break;
+ default:
+ GTEST_LOG_(FATAL) << "Death test child process reported "
+ << "unexpected status byte ("
+ << static_cast<unsigned int>(flag) << ")";
}
} else {
GTEST_LOG_(FATAL) << "Read from death test child process failed: "
@@ -6965,9 +6829,11 @@
// The parent process considers the death test to be a failure if
// it finds any data in our pipe. So, here we write a single flag byte
// to the pipe, then exit.
- const char status_ch =
- reason == TEST_DID_NOT_DIE ? kDeathTestLived :
- reason == TEST_THREW_EXCEPTION ? kDeathTestThrew : kDeathTestReturned;
+ const char status_ch = reason == TEST_DID_NOT_DIE
+ ? kDeathTestLived
+ : reason == TEST_THREW_EXCEPTION
+ ? kDeathTestThrew
+ : kDeathTestReturned;
GTEST_DEATH_TEST_CHECK_SYSCALL_(posix::Write(write_fd(), &status_ch, 1));
// We are leaking the descriptor here because on some platforms (i.e.,
@@ -6986,7 +6852,7 @@
// much easier.
static ::std::string FormatDeathTestOutput(const ::std::string& output) {
::std::string ret;
- for (size_t at = 0; ; ) {
+ for (size_t at = 0;;) {
const size_t line_end = output.find('\n', at);
ret += "[ DEATH ] ";
if (line_end == ::std::string::npos) {
@@ -7022,8 +6888,7 @@
// first failing condition, in the order given above, is the one that is
// reported. Also sets the last death test message string.
bool DeathTestImpl::Passed(bool status_ok) {
- if (!spawned())
- return false;
+ if (!spawned()) return false;
const std::string error_message = GetCapturedStderr();
@@ -7032,45 +6897,50 @@
buffer << "Death test: " << statement() << "\n";
switch (outcome()) {
- case LIVED:
- buffer << " Result: failed to die.\n"
- << " Error msg:\n" << FormatDeathTestOutput(error_message);
- break;
- case THREW:
- buffer << " Result: threw an exception.\n"
- << " Error msg:\n" << FormatDeathTestOutput(error_message);
- break;
- case RETURNED:
- buffer << " Result: illegal return in test statement.\n"
- << " Error msg:\n" << FormatDeathTestOutput(error_message);
- break;
- case DIED:
- if (status_ok) {
- const bool matched = RE::PartialMatch(error_message.c_str(), *regex());
- if (matched) {
- success = true;
- } else {
- buffer << " Result: died but not with expected error.\n"
- << " Expected: " << regex()->pattern() << "\n"
- << "Actual msg:\n" << FormatDeathTestOutput(error_message);
- }
+ case LIVED:
+ buffer << " Result: failed to die.\n"
+ << " Error msg:\n"
+ << FormatDeathTestOutput(error_message);
+ break;
+ case THREW:
+ buffer << " Result: threw an exception.\n"
+ << " Error msg:\n"
+ << FormatDeathTestOutput(error_message);
+ break;
+ case RETURNED:
+ buffer << " Result: illegal return in test statement.\n"
+ << " Error msg:\n"
+ << FormatDeathTestOutput(error_message);
+ break;
+ case DIED:
+ if (status_ok) {
+ const bool matched = RE::PartialMatch(error_message.c_str(), *regex());
+ if (matched) {
+ success = true;
} else {
- buffer << " Result: died but not with expected exit code:\n"
- << " " << ExitSummary(status()) << "\n"
- << "Actual msg:\n" << FormatDeathTestOutput(error_message);
+ buffer << " Result: died but not with expected error.\n"
+ << " Expected: " << regex()->pattern() << "\n"
+ << "Actual msg:\n"
+ << FormatDeathTestOutput(error_message);
}
- break;
- case IN_PROGRESS:
- default:
- GTEST_LOG_(FATAL)
- << "DeathTest::Passed somehow called before conclusion of test";
+ } else {
+ buffer << " Result: died but not with expected exit code:\n"
+ << " " << ExitSummary(status()) << "\n"
+ << "Actual msg:\n"
+ << FormatDeathTestOutput(error_message);
+ }
+ break;
+ case IN_PROGRESS:
+ default:
+ GTEST_LOG_(FATAL)
+ << "DeathTest::Passed somehow called before conclusion of test";
}
DeathTest::set_last_death_test_message(buffer.GetString());
return success;
}
-# if GTEST_OS_WINDOWS
+# if GTEST_OS_WINDOWS
// WindowsDeathTest implements death tests on Windows. Due to the
// specifics of starting new processes on Windows, death tests there are
// always threadsafe, and Google Test considers the
@@ -7101,9 +6971,7 @@
//
class WindowsDeathTest : public DeathTestImpl {
public:
- WindowsDeathTest(const char* a_statement,
- const RE* a_regex,
- const char* file,
+ WindowsDeathTest(const char* a_statement, const RE* a_regex, const char* file,
int line)
: DeathTestImpl(a_statement, a_regex), file_(file), line_(line) {}
@@ -7131,21 +6999,19 @@
// status, or 0 if no child process exists. As a side effect, sets the
// outcome data member.
int WindowsDeathTest::Wait() {
- if (!spawned())
- return 0;
+ if (!spawned()) return 0;
// Wait until the child either signals that it has acquired the write end
// of the pipe or it dies.
- const HANDLE wait_handles[2] = { child_handle_.Get(), event_handle_.Get() };
- switch (::WaitForMultipleObjects(2,
- wait_handles,
+ const HANDLE wait_handles[2] = {child_handle_.Get(), event_handle_.Get()};
+ switch (::WaitForMultipleObjects(2, wait_handles,
FALSE, // Waits for any of the handles.
INFINITE)) {
- case WAIT_OBJECT_0:
- case WAIT_OBJECT_0 + 1:
- break;
- default:
- GTEST_DEATH_TEST_CHECK_(false); // Should not get here.
+ case WAIT_OBJECT_0:
+ case WAIT_OBJECT_0 + 1:
+ break;
+ default:
+ GTEST_DEATH_TEST_CHECK_(false); // Should not get here.
}
// The child has acquired the write end of the pipe or exited.
@@ -7159,9 +7025,8 @@
// returns immediately if the child has already exited, regardless of
// whether previous calls to WaitForMultipleObjects synchronized on this
// handle or not.
- GTEST_DEATH_TEST_CHECK_(
- WAIT_OBJECT_0 == ::WaitForSingleObject(child_handle_.Get(),
- INFINITE));
+ GTEST_DEATH_TEST_CHECK_(WAIT_OBJECT_0 ==
+ ::WaitForSingleObject(child_handle_.Get(), INFINITE));
DWORD status_code;
GTEST_DEATH_TEST_CHECK_(
::GetExitCodeProcess(child_handle_.Get(), &status_code) != FALSE);
@@ -7191,15 +7056,15 @@
// WindowsDeathTest uses an anonymous pipe to communicate results of
// a death test.
- SECURITY_ATTRIBUTES handles_are_inheritable = {
- sizeof(SECURITY_ATTRIBUTES), NULL, TRUE };
+ SECURITY_ATTRIBUTES handles_are_inheritable = {sizeof(SECURITY_ATTRIBUTES),
+ NULL, TRUE};
HANDLE read_handle, write_handle;
- GTEST_DEATH_TEST_CHECK_(
- ::CreatePipe(&read_handle, &write_handle, &handles_are_inheritable,
- 0) // Default buffer size.
- != FALSE);
- set_read_fd(::_open_osfhandle(reinterpret_cast<intptr_t>(read_handle),
- O_RDONLY));
+ GTEST_DEATH_TEST_CHECK_(::CreatePipe(&read_handle, &write_handle,
+ &handles_are_inheritable,
+ 0) // Default buffer size.
+ != FALSE);
+ set_read_fd(
+ ::_open_osfhandle(reinterpret_cast<intptr_t>(read_handle), O_RDONLY));
write_handle_.Reset(write_handle);
event_handle_.Reset(::CreateEvent(
&handles_are_inheritable,
@@ -7207,29 +7072,26 @@
FALSE, // The initial state is non-signalled.
NULL)); // The even is unnamed.
GTEST_DEATH_TEST_CHECK_(event_handle_.Get() != NULL);
- const std::string filter_flag =
- std::string("--") + GTEST_FLAG_PREFIX_ + kFilterFlag + "=" +
- info->test_case_name() + "." + info->name();
+ const std::string filter_flag = std::string("--") + GTEST_FLAG_PREFIX_ +
+ kFilterFlag + "=" + info->test_case_name() +
+ "." + info->name();
const std::string internal_flag =
- std::string("--") + GTEST_FLAG_PREFIX_ + kInternalRunDeathTestFlag +
- "=" + file_ + "|" + StreamableToString(line_) + "|" +
+ std::string("--") + GTEST_FLAG_PREFIX_ + kInternalRunDeathTestFlag + "=" +
+ file_ + "|" + StreamableToString(line_) + "|" +
StreamableToString(death_test_index) + "|" +
StreamableToString(static_cast<unsigned int>(::GetCurrentProcessId())) +
// size_t has the same width as pointers on both 32-bit and 64-bit
// Windows platforms.
// See http://msdn.microsoft.com/en-us/library/tcxf1dw6.aspx.
- "|" + StreamableToString(reinterpret_cast<size_t>(write_handle)) +
- "|" + StreamableToString(reinterpret_cast<size_t>(event_handle_.Get()));
+ "|" + StreamableToString(reinterpret_cast<size_t>(write_handle)) + "|" +
+ StreamableToString(reinterpret_cast<size_t>(event_handle_.Get()));
char executable_path[_MAX_PATH + 1]; // NOLINT
GTEST_DEATH_TEST_CHECK_(
- _MAX_PATH + 1 != ::GetModuleFileNameA(NULL,
- executable_path,
- _MAX_PATH));
+ _MAX_PATH + 1 != ::GetModuleFileNameA(NULL, executable_path, _MAX_PATH));
- std::string command_line =
- std::string(::GetCommandLineA()) + " " + filter_flag + " \"" +
- internal_flag + "\"";
+ std::string command_line = std::string(::GetCommandLineA()) + " " +
+ filter_flag + " \"" + internal_flag + "\"";
DeathTest::set_last_death_test_message("");
@@ -7246,23 +7108,22 @@
startup_info.hStdError = ::GetStdHandle(STD_ERROR_HANDLE);
PROCESS_INFORMATION process_info;
- GTEST_DEATH_TEST_CHECK_(::CreateProcessA(
- executable_path,
- const_cast<char*>(command_line.c_str()),
- NULL, // Retuned process handle is not inheritable.
- NULL, // Retuned thread handle is not inheritable.
- TRUE, // Child inherits all inheritable handles (for write_handle_).
- 0x0, // Default creation flags.
- NULL, // Inherit the parent's environment.
- UnitTest::GetInstance()->original_working_dir(),
- &startup_info,
- &process_info) != FALSE);
+ GTEST_DEATH_TEST_CHECK_(
+ ::CreateProcessA(
+ executable_path, const_cast<char*>(command_line.c_str()),
+ NULL, // Retuned process handle is not inheritable.
+ NULL, // Retuned thread handle is not inheritable.
+ TRUE, // Child inherits all inheritable handles (for write_handle_).
+ 0x0, // Default creation flags.
+ NULL, // Inherit the parent's environment.
+ UnitTest::GetInstance()->original_working_dir(), &startup_info,
+ &process_info) != FALSE);
child_handle_.Reset(process_info.hProcess);
::CloseHandle(process_info.hThread);
set_spawned(true);
return OVERSEE_TEST;
}
-# else // We are not on Windows.
+# else // We are not on Windows.
// ForkingDeathTest provides implementations for most of the abstract
// methods of the DeathTest interface. Only the AssumeRole method is
@@ -7284,15 +7145,13 @@
// Constructs a ForkingDeathTest.
ForkingDeathTest::ForkingDeathTest(const char* a_statement, const RE* a_regex)
- : DeathTestImpl(a_statement, a_regex),
- child_pid_(-1) {}
+ : DeathTestImpl(a_statement, a_regex), child_pid_(-1) {}
// Waits for the child in a death test to exit, returning its exit
// status, or 0 if no child process exists. As a side effect, sets the
// outcome data member.
int ForkingDeathTest::Wait() {
- if (!spawned())
- return 0;
+ if (!spawned()) return 0;
ReadAndInterpretStatusByte();
@@ -7306,8 +7165,8 @@
// in the child process.
class NoExecDeathTest : public ForkingDeathTest {
public:
- NoExecDeathTest(const char* a_statement, const RE* a_regex) :
- ForkingDeathTest(a_statement, a_regex) { }
+ NoExecDeathTest(const char* a_statement, const RE* a_regex)
+ : ForkingDeathTest(a_statement, a_regex) {}
virtual TestRole AssumeRole();
};
@@ -7361,10 +7220,11 @@
// only this specific death test to be run.
class ExecDeathTest : public ForkingDeathTest {
public:
- ExecDeathTest(const char* a_statement, const RE* a_regex,
- const char* file, int line) :
- ForkingDeathTest(a_statement, a_regex), file_(file), line_(line) { }
+ ExecDeathTest(const char* a_statement, const RE* a_regex, const char* file,
+ int line)
+ : ForkingDeathTest(a_statement, a_regex), file_(file), line_(line) {}
virtual TestRole AssumeRole();
+
private:
static ::std::vector<testing::internal::string>
GetArgvsForDeathTestChildProcess() {
@@ -7380,9 +7240,7 @@
// Utility class for accumulating command-line arguments.
class Arguments {
public:
- Arguments() {
- args_.push_back(NULL);
- }
+ Arguments() { args_.push_back(NULL); }
~Arguments() {
for (std::vector<char*>::iterator i = args_.begin(); i != args_.end();
@@ -7397,14 +7255,11 @@
template <typename Str>
void AddArguments(const ::std::vector<Str>& arguments) {
for (typename ::std::vector<Str>::const_iterator i = arguments.begin();
- i != arguments.end();
- ++i) {
+ i != arguments.end(); ++i) {
args_.insert(args_.end() - 1, posix::StrDup(i->c_str()));
}
}
- char* const* Argv() {
- return &args_[0];
- }
+ char* const* Argv() { return &args_[0]; }
private:
std::vector<char*> args_;
@@ -7417,21 +7272,21 @@
int close_fd; // File descriptor to close; the read end of a pipe
};
-# if GTEST_OS_MAC
+# if GTEST_OS_MAC
inline char** GetEnviron() {
// When Google Test is built as a framework on MacOS X, the environ variable
// is unavailable. Apple's documentation (man environ) recommends using
// _NSGetEnviron() instead.
return *_NSGetEnviron();
}
-# else
+# else
// Some POSIX platforms expect you to declare environ. extern "C" makes
// it reside in the global namespace.
extern "C" char** environ;
inline char** GetEnviron() { return environ; }
-# endif // GTEST_OS_MAC
+# endif // GTEST_OS_MAC
-# if !GTEST_OS_QNX
+# if !GTEST_OS_QNX
// The main function for a threadsafe-style death test child process.
// This function is called in a clone()-ed process and thus must avoid
// any potentially unsafe operations like malloc or libc functions.
@@ -7446,8 +7301,8 @@
UnitTest::GetInstance()->original_working_dir();
// We can safely call chdir() as it's a direct system call.
if (chdir(original_dir) != 0) {
- DeathTestAbort(std::string("chdir(\"") + original_dir + "\") failed: " +
- GetLastErrnoDescription());
+ DeathTestAbort(std::string("chdir(\"") + original_dir +
+ "\") failed: " + GetLastErrnoDescription());
return EXIT_FAILURE;
}
@@ -7458,11 +7313,10 @@
// one path separator.
execve(args->argv[0], args->argv, GetEnviron());
DeathTestAbort(std::string("execve(") + args->argv[0] + ", ...) in " +
- original_dir + " failed: " +
- GetLastErrnoDescription());
+ original_dir + " failed: " + GetLastErrnoDescription());
return EXIT_FAILURE;
}
-# endif // !GTEST_OS_QNX
+# endif // !GTEST_OS_QNX
// Two utility routines that together determine the direction the stack
// grows.
@@ -7494,10 +7348,10 @@
// spawn(2) there instead. The function dies with an error message if
// anything goes wrong.
static pid_t ExecDeathTestSpawnChild(char* const* argv, int close_fd) {
- ExecDeathTestArgs args = { argv, close_fd };
+ ExecDeathTestArgs args = {argv, close_fd};
pid_t child_pid = -1;
-# if GTEST_OS_QNX
+# if GTEST_OS_QNX
// Obtains the current directory and sets it to be closed in the child
// process.
const int cwd_fd = open(".", O_RDONLY);
@@ -7510,16 +7364,16 @@
UnitTest::GetInstance()->original_working_dir();
// We can safely call chdir() as it's a direct system call.
if (chdir(original_dir) != 0) {
- DeathTestAbort(std::string("chdir(\"") + original_dir + "\") failed: " +
- GetLastErrnoDescription());
+ DeathTestAbort(std::string("chdir(\"") + original_dir +
+ "\") failed: " + GetLastErrnoDescription());
return EXIT_FAILURE;
}
int fd_flags;
// Set close_fd to be closed after spawn.
GTEST_DEATH_TEST_CHECK_SYSCALL_(fd_flags = fcntl(close_fd, F_GETFD));
- GTEST_DEATH_TEST_CHECK_SYSCALL_(fcntl(close_fd, F_SETFD,
- fd_flags | FD_CLOEXEC));
+ GTEST_DEATH_TEST_CHECK_SYSCALL_(
+ fcntl(close_fd, F_SETFD, fd_flags | FD_CLOEXEC));
struct inheritance inherit = {0};
// spawn is a system call.
child_pid = spawn(args.argv[0], 0, NULL, &inherit, args.argv, GetEnviron());
@@ -7527,8 +7381,8 @@
GTEST_DEATH_TEST_CHECK_(fchdir(cwd_fd) != -1);
GTEST_DEATH_TEST_CHECK_SYSCALL_(close(cwd_fd));
-# else // GTEST_OS_QNX
-# if GTEST_OS_LINUX
+# else // GTEST_OS_QNX
+# if GTEST_OS_LINUX
// When a SIGPROF signal is received while fork() or clone() are executing,
// the process may hang. To avoid this, we ignore SIGPROF here and re-enable
// it after the call to fork()/clone() is complete.
@@ -7537,11 +7391,11 @@
memset(&ignore_sigprof_action, 0, sizeof(ignore_sigprof_action));
sigemptyset(&ignore_sigprof_action.sa_mask);
ignore_sigprof_action.sa_handler = SIG_IGN;
- GTEST_DEATH_TEST_CHECK_SYSCALL_(sigaction(
- SIGPROF, &ignore_sigprof_action, &saved_sigprof_action));
-# endif // GTEST_OS_LINUX
+ GTEST_DEATH_TEST_CHECK_SYSCALL_(
+ sigaction(SIGPROF, &ignore_sigprof_action, &saved_sigprof_action));
+# endif // GTEST_OS_LINUX
-# if GTEST_HAS_CLONE
+# if GTEST_HAS_CLONE
const bool use_fork = GTEST_FLAG(death_test_use_fork);
if (!use_fork) {
@@ -7561,27 +7415,28 @@
const size_t kMaxStackAlignment = 64;
void* const stack_top =
static_cast<char*>(stack) +
- (stack_grows_down ? stack_size - kMaxStackAlignment : 0);
- GTEST_DEATH_TEST_CHECK_(stack_size > kMaxStackAlignment &&
+ (stack_grows_down ? stack_size - kMaxStackAlignment : 0);
+ GTEST_DEATH_TEST_CHECK_(
+ stack_size > kMaxStackAlignment &&
reinterpret_cast<intptr_t>(stack_top) % kMaxStackAlignment == 0);
child_pid = clone(&ExecDeathTestChildMain, stack_top, SIGCHLD, &args);
GTEST_DEATH_TEST_CHECK_(munmap(stack, stack_size) != -1);
}
-# else
+# else
const bool use_fork = true;
-# endif // GTEST_HAS_CLONE
+# endif // GTEST_HAS_CLONE
if (use_fork && (child_pid = fork()) == 0) {
- ExecDeathTestChildMain(&args);
- _exit(0);
+ ExecDeathTestChildMain(&args);
+ _exit(0);
}
-# endif // GTEST_OS_QNX
-# if GTEST_OS_LINUX
+# endif // GTEST_OS_QNX
+# if GTEST_OS_LINUX
GTEST_DEATH_TEST_CHECK_SYSCALL_(
sigaction(SIGPROF, &saved_sigprof_action, NULL));
-# endif // GTEST_OS_LINUX
+# endif // GTEST_OS_LINUX
GTEST_DEATH_TEST_CHECK_(child_pid != -1);
return child_pid;
@@ -7609,14 +7464,14 @@
// it be closed when the child process does an exec:
GTEST_DEATH_TEST_CHECK_(fcntl(pipe_fd[1], F_SETFD, 0) != -1);
- const std::string filter_flag =
- std::string("--") + GTEST_FLAG_PREFIX_ + kFilterFlag + "="
- + info->test_case_name() + "." + info->name();
- const std::string internal_flag =
- std::string("--") + GTEST_FLAG_PREFIX_ + kInternalRunDeathTestFlag + "="
- + file_ + "|" + StreamableToString(line_) + "|"
- + StreamableToString(death_test_index) + "|"
- + StreamableToString(pipe_fd[1]);
+ const std::string filter_flag = std::string("--") + GTEST_FLAG_PREFIX_ +
+ kFilterFlag + "=" + info->test_case_name() +
+ "." + info->name();
+ const std::string internal_flag = std::string("--") + GTEST_FLAG_PREFIX_ +
+ kInternalRunDeathTestFlag + "=" + file_ +
+ "|" + StreamableToString(line_) + "|" +
+ StreamableToString(death_test_index) + "|" +
+ StreamableToString(pipe_fd[1]);
Arguments args;
args.AddArguments(GetArgvsForDeathTestChildProcess());
args.AddArgument(filter_flag.c_str());
@@ -7637,7 +7492,7 @@
return OVERSEE_TEST;
}
-# endif // !GTEST_OS_WINDOWS
+# endif // !GTEST_OS_WINDOWS
// Creates a concrete DeathTest-derived class that depends on the
// --gtest_death_test_style flag, and sets the pointer pointed to
@@ -7650,15 +7505,15 @@
UnitTestImpl* const impl = GetUnitTestImpl();
const InternalRunDeathTestFlag* const flag =
impl->internal_run_death_test_flag();
- const int death_test_index = impl->current_test_info()
- ->increment_death_test_count();
+ const int death_test_index =
+ impl->current_test_info()->increment_death_test_count();
if (flag != NULL) {
if (death_test_index > flag->index()) {
DeathTest::set_last_death_test_message(
- "Death test count (" + StreamableToString(death_test_index)
- + ") somehow exceeded expected maximum ("
- + StreamableToString(flag->index()) + ")");
+ "Death test count (" + StreamableToString(death_test_index) +
+ ") somehow exceeded expected maximum (" +
+ StreamableToString(flag->index()) + ")");
return false;
}
@@ -7669,14 +7524,14 @@
}
}
-# if GTEST_OS_WINDOWS
+# if GTEST_OS_WINDOWS
if (GTEST_FLAG(death_test_style) == "threadsafe" ||
GTEST_FLAG(death_test_style) == "fast") {
*test = new WindowsDeathTest(statement, regex, file, line);
}
-# else
+# else
if (GTEST_FLAG(death_test_style) == "threadsafe") {
*test = new ExecDeathTest(statement, regex, file, line);
@@ -7684,12 +7539,12 @@
*test = new NoExecDeathTest(statement, regex);
}
-# endif // GTEST_OS_WINDOWS
+# endif // GTEST_OS_WINDOWS
else { // NOLINT - this is more readable than unbalanced brackets inside #if.
- DeathTest::set_last_death_test_message(
- "Unknown death test style \"" + GTEST_FLAG(death_test_style)
- + "\" encountered");
+ DeathTest::set_last_death_test_message("Unknown death test style \"" +
+ GTEST_FLAG(death_test_style) +
+ "\" encountered");
return false;
}
@@ -7716,7 +7571,7 @@
dest->swap(parsed);
}
-# if GTEST_OS_WINDOWS
+# if GTEST_OS_WINDOWS
// Recreates the pipe and event handles from the provided parameters,
// signals the event, and returns a file descriptor wrapped around the pipe
// handle. This function is called in the child process only.
@@ -7724,8 +7579,8 @@
size_t write_handle_as_size_t,
size_t event_handle_as_size_t) {
AutoHandle parent_process_handle(::OpenProcess(PROCESS_DUP_HANDLE,
- FALSE, // Non-inheritable.
- parent_process_id));
+ FALSE, // Non-inheritable.
+ parent_process_id));
if (parent_process_handle.Get() == INVALID_HANDLE_VALUE) {
DeathTestAbort("Unable to open parent process " +
StreamableToString(parent_process_id));
@@ -7735,8 +7590,7 @@
// compile-time assertion when available.
GTEST_CHECK_(sizeof(HANDLE) <= sizeof(size_t));
- const HANDLE write_handle =
- reinterpret_cast<HANDLE>(write_handle_as_size_t);
+ const HANDLE write_handle = reinterpret_cast<HANDLE>(write_handle_as_size_t);
HANDLE dup_write_handle;
// The newly initialized handle is accessible only in in the parent
@@ -7758,9 +7612,7 @@
HANDLE dup_event_handle;
if (!::DuplicateHandle(parent_process_handle.Get(), event_handle,
- ::GetCurrentProcess(), &dup_event_handle,
- 0x0,
- FALSE,
+ ::GetCurrentProcess(), &dup_event_handle, 0x0, FALSE,
DUPLICATE_SAME_ACCESS)) {
DeathTestAbort("Unable to duplicate the event handle " +
StreamableToString(event_handle_as_size_t) +
@@ -7782,7 +7634,7 @@
return write_fd;
}
-# endif // GTEST_OS_WINDOWS
+# endif // GTEST_OS_WINDOWS
// Returns a newly created InternalRunDeathTestFlag object with fields
// initialized from the GTEST_FLAG(internal_run_death_test) flag if
@@ -7798,35 +7650,32 @@
SplitString(GTEST_FLAG(internal_run_death_test).c_str(), '|', &fields);
int write_fd = -1;
-# if GTEST_OS_WINDOWS
+# if GTEST_OS_WINDOWS
unsigned int parent_process_id = 0;
size_t write_handle_as_size_t = 0;
size_t event_handle_as_size_t = 0;
- if (fields.size() != 6
- || !ParseNaturalNumber(fields[1], &line)
- || !ParseNaturalNumber(fields[2], &index)
- || !ParseNaturalNumber(fields[3], &parent_process_id)
- || !ParseNaturalNumber(fields[4], &write_handle_as_size_t)
- || !ParseNaturalNumber(fields[5], &event_handle_as_size_t)) {
+ if (fields.size() != 6 || !ParseNaturalNumber(fields[1], &line) ||
+ !ParseNaturalNumber(fields[2], &index) ||
+ !ParseNaturalNumber(fields[3], &parent_process_id) ||
+ !ParseNaturalNumber(fields[4], &write_handle_as_size_t) ||
+ !ParseNaturalNumber(fields[5], &event_handle_as_size_t)) {
DeathTestAbort("Bad --gtest_internal_run_death_test flag: " +
GTEST_FLAG(internal_run_death_test));
}
- write_fd = GetStatusFileDescriptor(parent_process_id,
- write_handle_as_size_t,
+ write_fd = GetStatusFileDescriptor(parent_process_id, write_handle_as_size_t,
event_handle_as_size_t);
-# else
+# else
- if (fields.size() != 4
- || !ParseNaturalNumber(fields[1], &line)
- || !ParseNaturalNumber(fields[2], &index)
- || !ParseNaturalNumber(fields[3], &write_fd)) {
- DeathTestAbort("Bad --gtest_internal_run_death_test flag: "
- + GTEST_FLAG(internal_run_death_test));
+ if (fields.size() != 4 || !ParseNaturalNumber(fields[1], &line) ||
+ !ParseNaturalNumber(fields[2], &index) ||
+ !ParseNaturalNumber(fields[3], &write_fd)) {
+ DeathTestAbort("Bad --gtest_internal_run_death_test flag: " +
+ GTEST_FLAG(internal_run_death_test));
}
-# endif // GTEST_OS_WINDOWS
+# endif // GTEST_OS_WINDOWS
return new InternalRunDeathTestFlag(fields[0], line, index, write_fd);
}
@@ -7867,33 +7716,31 @@
//
// Authors: keith.ray@gmail.com (Keith Ray)
-
#include <stdlib.h>
#if GTEST_OS_WINDOWS_MOBILE
-# include <windows.h>
+# include <windows.h>
#elif GTEST_OS_WINDOWS
-# include <direct.h>
-# include <io.h>
+# include <direct.h>
+# include <io.h>
#elif GTEST_OS_SYMBIAN
// Symbian OpenC has PATH_MAX in sys/syslimits.h
-# include <sys/syslimits.h>
+# include <sys/syslimits.h>
#else
-# include <limits.h>
-# include <climits> // Some Linux distributions define PATH_MAX here.
-#endif // GTEST_OS_WINDOWS_MOBILE
+# include <limits.h>
+# include <climits> // Some Linux distributions define PATH_MAX here.
+#endif // GTEST_OS_WINDOWS_MOBILE
#if GTEST_OS_WINDOWS
-# define GTEST_PATH_MAX_ _MAX_PATH
+# define GTEST_PATH_MAX_ _MAX_PATH
#elif defined(PATH_MAX)
-# define GTEST_PATH_MAX_ PATH_MAX
+# define GTEST_PATH_MAX_ PATH_MAX
#elif defined(_XOPEN_PATH_MAX)
-# define GTEST_PATH_MAX_ _XOPEN_PATH_MAX
+# define GTEST_PATH_MAX_ _XOPEN_PATH_MAX
#else
-# define GTEST_PATH_MAX_ _POSIX_PATH_MAX
+# define GTEST_PATH_MAX_ _POSIX_PATH_MAX
#endif // GTEST_OS_WINDOWS
-
namespace testing {
namespace internal {
@@ -7906,16 +7753,16 @@
const char kAlternatePathSeparator = '/';
const char kPathSeparatorString[] = "\\";
const char kAlternatePathSeparatorString[] = "/";
-# if GTEST_OS_WINDOWS_MOBILE
+# if GTEST_OS_WINDOWS_MOBILE
// Windows CE doesn't have a current directory. You should not use
// the current directory in tests on Windows CE, but this at least
// provides a reasonable fallback.
const char kCurrentDirectoryString[] = "\\";
// Windows CE doesn't define INVALID_FILE_ATTRIBUTES
const DWORD kInvalidFileAttributes = 0xffffffff;
-# else
+# else
const char kCurrentDirectoryString[] = ".\\";
-# endif // GTEST_OS_WINDOWS_MOBILE
+# endif // GTEST_OS_WINDOWS_MOBILE
#else
const char kPathSeparator = '/';
const char kPathSeparatorString[] = "/";
@@ -7938,10 +7785,10 @@
// something reasonable.
return FilePath(kCurrentDirectoryString);
#elif GTEST_OS_WINDOWS
- char cwd[GTEST_PATH_MAX_ + 1] = { '\0' };
+ char cwd[GTEST_PATH_MAX_ + 1] = {'\0'};
return FilePath(_getcwd(cwd, sizeof(cwd)) == NULL ? "" : cwd);
#else
- char cwd[GTEST_PATH_MAX_ + 1] = { '\0' };
+ char cwd[GTEST_PATH_MAX_ + 1] = {'\0'};
return FilePath(getcwd(cwd, sizeof(cwd)) == NULL ? "" : cwd);
#endif // GTEST_OS_WINDOWS_MOBILE
}
@@ -7953,8 +7800,8 @@
FilePath FilePath::RemoveExtension(const char* extension) const {
const std::string dot_extension = std::string(".") + extension;
if (String::EndsWithCaseInsensitive(pathname_, dot_extension)) {
- return FilePath(pathname_.substr(
- 0, pathname_.length() - dot_extension.length()));
+ return FilePath(
+ pathname_.substr(0, pathname_.length() - dot_extension.length()));
}
return *this;
}
@@ -7967,8 +7814,7 @@
#if GTEST_HAS_ALT_PATH_SEP_
const char* const last_alt_sep = strrchr(c_str(), kAlternatePathSeparator);
// Comparing two pointers of which only one is NULL is undefined.
- if (last_alt_sep != NULL &&
- (last_sep == NULL || last_alt_sep > last_sep)) {
+ if (last_alt_sep != NULL && (last_sep == NULL || last_alt_sep > last_sep)) {
return last_alt_sep;
}
#endif
@@ -8010,15 +7856,14 @@
// than zero (e.g., 12), returns "dir/test_12.xml".
// On Windows platform, uses \ as the separator rather than /.
FilePath FilePath::MakeFileName(const FilePath& directory,
- const FilePath& base_name,
- int number,
+ const FilePath& base_name, int number,
const char* extension) {
std::string file;
if (number == 0) {
file = base_name.string() + "." + extension;
} else {
- file = base_name.string() + "_" + StreamableToString(number)
- + "." + extension;
+ file =
+ base_name.string() + "_" + StreamableToString(number) + "." + extension;
}
return ConcatPaths(directory, FilePath(file));
}
@@ -8027,8 +7872,7 @@
// On Windows, uses \ as the separator rather than /.
FilePath FilePath::ConcatPaths(const FilePath& directory,
const FilePath& relative_path) {
- if (directory.IsEmpty())
- return relative_path;
+ if (directory.IsEmpty()) return relative_path;
const FilePath dir(directory.RemoveTrailingPathSeparator());
return FilePath(dir.string() + kPathSeparator + relative_path.string());
}
@@ -8039,7 +7883,7 @@
#if GTEST_OS_WINDOWS_MOBILE
LPCWSTR unicode = String::AnsiToUtf16(pathname_.c_str());
const DWORD attributes = GetFileAttributes(unicode);
- delete [] unicode;
+ delete[] unicode;
return attributes != kInvalidFileAttributes;
#else
posix::StatStruct file_stat;
@@ -8054,8 +7898,8 @@
#if GTEST_OS_WINDOWS
// Don't strip off trailing separator if path is a root directory on
// Windows (like "C:\\").
- const FilePath& path(IsRootDirectory() ? *this :
- RemoveTrailingPathSeparator());
+ const FilePath& path(IsRootDirectory() ? *this
+ : RemoveTrailingPathSeparator());
#else
const FilePath& path(*this);
#endif
@@ -8063,15 +7907,15 @@
#if GTEST_OS_WINDOWS_MOBILE
LPCWSTR unicode = String::AnsiToUtf16(path.c_str());
const DWORD attributes = GetFileAttributes(unicode);
- delete [] unicode;
+ delete[] unicode;
if ((attributes != kInvalidFileAttributes) &&
(attributes & FILE_ATTRIBUTE_DIRECTORY)) {
result = true;
}
#else
posix::StatStruct file_stat;
- result = posix::Stat(path.c_str(), &file_stat) == 0 &&
- posix::IsDir(file_stat);
+ result =
+ posix::Stat(path.c_str(), &file_stat) == 0 && posix::IsDir(file_stat);
#endif // GTEST_OS_WINDOWS_MOBILE
return result;
@@ -8095,10 +7939,9 @@
const char* const name = pathname_.c_str();
#if GTEST_OS_WINDOWS
return pathname_.length() >= 3 &&
- ((name[0] >= 'a' && name[0] <= 'z') ||
- (name[0] >= 'A' && name[0] <= 'Z')) &&
- name[1] == ':' &&
- IsPathSeparator(name[2]);
+ ((name[0] >= 'a' && name[0] <= 'z') ||
+ (name[0] >= 'A' && name[0] <= 'Z')) &&
+ name[1] == ':' && IsPathSeparator(name[2]);
#else
return IsPathSeparator(name[0]);
#endif
@@ -8156,7 +7999,7 @@
FilePath removed_sep(this->RemoveTrailingPathSeparator());
LPCWSTR unicode = String::AnsiToUtf16(removed_sep.c_str());
int result = CreateDirectory(unicode, NULL) ? 0 : -1;
- delete [] unicode;
+ delete[] unicode;
#elif GTEST_OS_WINDOWS
int result = _mkdir(pathname_.c_str());
#else
@@ -8173,9 +8016,8 @@
// name, otherwise return the name string unmodified.
// On Windows platform, uses \ as the separator, other platforms use /.
FilePath FilePath::RemoveTrailingPathSeparator() const {
- return IsDirectory()
- ? FilePath(pathname_.substr(0, pathname_.length() - 1))
- : *this;
+ return IsDirectory() ? FilePath(pathname_.substr(0, pathname_.length() - 1))
+ : *this;
}
// Removes any redundant separators that might be in the pathname.
@@ -8202,8 +8044,7 @@
*dest_ptr = kPathSeparator;
}
#endif
- while (IsPathSeparator(*src))
- src++;
+ while (IsPathSeparator(*src)) src++;
}
dest_ptr++;
}
@@ -8245,33 +8086,31 @@
//
// Author: wan@google.com (Zhanyong Wan)
-
#include <limits.h>
-#include <stdlib.h>
#include <stdio.h>
+#include <stdlib.h>
#include <string.h>
#if GTEST_OS_WINDOWS_MOBILE
-# include <windows.h> // For TerminateProcess()
+# include <windows.h> // For TerminateProcess()
#elif GTEST_OS_WINDOWS
-# include <io.h>
-# include <sys/stat.h>
+# include <io.h>
+# include <sys/stat.h>
#else
-# include <unistd.h>
+# include <unistd.h>
#endif // GTEST_OS_WINDOWS_MOBILE
#if GTEST_OS_MAC
-# include <mach/mach_init.h>
-# include <mach/task.h>
-# include <mach/vm_map.h>
+# include <mach/mach_init.h>
+# include <mach/task.h>
+# include <mach/vm_map.h>
#endif // GTEST_OS_MAC
#if GTEST_OS_QNX
-# include <devctl.h>
-# include <sys/procfs.h>
+# include <devctl.h>
+# include <sys/procfs.h>
#endif // GTEST_OS_QNX
-
// Indicates that this translation unit is part of Google Test's
// implementation. It must come before gtest-internal-inl.h is
// included, or there will be a compiler error. This trick is to
@@ -8304,8 +8143,7 @@
if (status == KERN_SUCCESS) {
// task_threads allocates resources in thread_list and we need to free them
// to avoid leaks.
- vm_deallocate(task,
- reinterpret_cast<vm_address_t>(thread_list),
+ vm_deallocate(task, reinterpret_cast<vm_address_t>(thread_list),
sizeof(thread_t) * thread_count);
return static_cast<size_t>(thread_count);
} else {
@@ -8425,7 +8263,7 @@
bool IsAsciiWhiteSpace(char ch) { return IsInSet(ch, " \f\n\r\t\v"); }
bool IsAsciiWordChar(char ch) {
return ('a' <= ch && ch <= 'z') || ('A' <= ch && ch <= 'Z') ||
- ('0' <= ch && ch <= '9') || ch == '_';
+ ('0' <= ch && ch <= '9') || ch == '_';
}
// Returns true iff "\\c" is a supported escape sequence.
@@ -8438,17 +8276,28 @@
bool AtomMatchesChar(bool escaped, char pattern_char, char ch) {
if (escaped) { // "\\p" where p is pattern_char.
switch (pattern_char) {
- case 'd': return IsAsciiDigit(ch);
- case 'D': return !IsAsciiDigit(ch);
- case 'f': return ch == '\f';
- case 'n': return ch == '\n';
- case 'r': return ch == '\r';
- case 's': return IsAsciiWhiteSpace(ch);
- case 'S': return !IsAsciiWhiteSpace(ch);
- case 't': return ch == '\t';
- case 'v': return ch == '\v';
- case 'w': return IsAsciiWordChar(ch);
- case 'W': return !IsAsciiWordChar(ch);
+ case 'd':
+ return IsAsciiDigit(ch);
+ case 'D':
+ return !IsAsciiDigit(ch);
+ case 'f':
+ return ch == '\f';
+ case 'n':
+ return ch == '\n';
+ case 'r':
+ return ch == '\r';
+ case 's':
+ return IsAsciiWhiteSpace(ch);
+ case 'S':
+ return !IsAsciiWhiteSpace(ch);
+ case 't':
+ return ch == '\t';
+ case 'v':
+ return ch == '\v';
+ case 'w':
+ return IsAsciiWordChar(ch);
+ case 'W':
+ return !IsAsciiWordChar(ch);
}
return IsAsciiPunct(pattern_char) && pattern_char == ch;
}
@@ -8459,7 +8308,8 @@
// Helper function used by ValidateRegex() to format error messages.
std::string FormatRegexSyntaxError(const char* regex, int index) {
return (Message() << "Syntax error at index " << index
- << " in simple regular expression \"" << regex << "\": ").GetString();
+ << " in simple regular expression \"" << regex << "\": ")
+ .GetString();
}
// Generates non-fatal failures and returns false if regex is invalid;
@@ -8504,12 +8354,12 @@
<< "'$' can only appear at the end.";
is_valid = false;
} else if (IsInSet(ch, "()[]{}|")) {
- ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
- << "'" << ch << "' is unsupported.";
+ ADD_FAILURE() << FormatRegexSyntaxError(regex, i) << "'" << ch
+ << "' is unsupported.";
is_valid = false;
} else if (IsRepeat(ch) && !prev_repeatable) {
- ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
- << "'" << ch << "' can only follow a repeatable token.";
+ ADD_FAILURE() << FormatRegexSyntaxError(regex, i) << "'" << ch
+ << "' can only follow a repeatable token.";
is_valid = false;
}
@@ -8527,12 +8377,10 @@
// characters to be indexable by size_t, in which case the test will
// probably time out anyway. We are fine with this limitation as
// std::string has it too.
-bool MatchRepetitionAndRegexAtHead(
- bool escaped, char c, char repeat, const char* regex,
- const char* str) {
+bool MatchRepetitionAndRegexAtHead(bool escaped, char c, char repeat,
+ const char* regex, const char* str) {
const size_t min_count = (repeat == '+') ? 1 : 0;
- const size_t max_count = (repeat == '?') ? 1 :
- static_cast<size_t>(-1) - 1;
+ const size_t max_count = (repeat == '?') ? 1 : static_cast<size_t>(-1) - 1;
// We cannot call numeric_limits::max() as it conflicts with the
// max() macro on Windows.
@@ -8545,8 +8393,7 @@
// greedy match.
return true;
}
- if (str[i] == '\0' || !AtomMatchesChar(escaped, c, str[i]))
- return false;
+ if (str[i] == '\0' || !AtomMatchesChar(escaped, c, str[i])) return false;
}
return false;
}
@@ -8560,25 +8407,23 @@
// "$" only matches the end of a string. Note that regex being
// valid guarantees that there's nothing after "$" in it.
- if (*regex == '$')
- return *str == '\0';
+ if (*regex == '$') return *str == '\0';
// Is the first thing in regex an escape sequence?
const bool escaped = *regex == '\\';
- if (escaped)
- ++regex;
+ if (escaped) ++regex;
if (IsRepeat(regex[1])) {
// MatchRepetitionAndRegexAtHead() calls MatchRegexAtHead(), so
// here's an indirect recursion. It terminates as the regex gets
// shorter in each recursion.
- return MatchRepetitionAndRegexAtHead(
- escaped, regex[0], regex[1], regex + 2, str);
+ return MatchRepetitionAndRegexAtHead(escaped, regex[0], regex[1], regex + 2,
+ str);
} else {
// regex isn't empty, isn't "$", and doesn't start with a
// repetition. We match the first atom of regex with the first
// character of str and recurse.
return (*str != '\0') && AtomMatchesChar(escaped, *regex, *str) &&
- MatchRegexAtHead(regex + 1, str + 1);
+ MatchRegexAtHead(regex + 1, str + 1);
}
}
@@ -8591,16 +8436,13 @@
// exponential with respect to the regex length + the string length,
// but usually it's must faster (often close to linear).
bool MatchRegexAnywhere(const char* regex, const char* str) {
- if (regex == NULL || str == NULL)
- return false;
+ if (regex == NULL || str == NULL) return false;
- if (*regex == '^')
- return MatchRegexAtHead(regex + 1, str);
+ if (*regex == '^') return MatchRegexAtHead(regex + 1, str);
// A successful match can be anywhere in str.
do {
- if (MatchRegexAtHead(regex, str))
- return true;
+ if (MatchRegexAtHead(regex, str)) return true;
} while (*str++ != '\0');
return false;
}
@@ -8681,8 +8523,8 @@
// FormatFileLocation in order to contrast the two functions.
// Note that FormatCompilerIndependentFileLocation() does NOT append colon
// to the file location it produces, unlike FormatFileLocation().
-GTEST_API_ ::std::string FormatCompilerIndependentFileLocation(
- const char* file, int line) {
+GTEST_API_ ::std::string FormatCompilerIndependentFileLocation(const char* file,
+ int line) {
const std::string file_name(file == NULL ? kUnknownFile : file);
if (line < 0)
@@ -8691,15 +8533,17 @@
return file_name + ":" + StreamableToString(line);
}
-
GTestLog::GTestLog(GTestLogSeverity severity, const char* file, int line)
: severity_(severity) {
const char* const marker =
- severity == GTEST_INFO ? "[ INFO ]" :
- severity == GTEST_WARNING ? "[WARNING]" :
- severity == GTEST_ERROR ? "[ ERROR ]" : "[ FATAL ]";
- GetStream() << ::std::endl << marker << " "
- << FormatFileLocation(file, line).c_str() << ": ";
+ severity == GTEST_INFO
+ ? "[ INFO ]"
+ : severity == GTEST_WARNING
+ ? "[WARNING]"
+ : severity == GTEST_ERROR ? "[ ERROR ]" : "[ FATAL ]";
+ GetStream() << ::std::endl
+ << marker << " " << FormatFileLocation(file, line).c_str()
+ << ": ";
}
// Flushes the buffers and, if severity is GTEST_FATAL, aborts the program.
@@ -8713,8 +8557,8 @@
// Disable Microsoft deprecation warnings for POSIX functions called from
// this class (creat, dup, dup2, and close)
#ifdef _MSC_VER
-# pragma warning(push)
-# pragma warning(disable: 4996)
+# pragma warning(push)
+# pragma warning(disable : 4996)
#endif // _MSC_VER
#if GTEST_HAS_STREAM_REDIRECTION
@@ -8724,27 +8568,26 @@
public:
// The ctor redirects the stream to a temporary file.
explicit CapturedStream(int fd) : fd_(fd), uncaptured_fd_(dup(fd)) {
-# if GTEST_OS_WINDOWS
- char temp_dir_path[MAX_PATH + 1] = { '\0' }; // NOLINT
- char temp_file_path[MAX_PATH + 1] = { '\0' }; // NOLINT
+# if GTEST_OS_WINDOWS
+ char temp_dir_path[MAX_PATH + 1] = {'\0'}; // NOLINT
+ char temp_file_path[MAX_PATH + 1] = {'\0'}; // NOLINT
::GetTempPathA(sizeof(temp_dir_path), temp_dir_path);
- const UINT success = ::GetTempFileNameA(temp_dir_path,
- "gtest_redir",
+ const UINT success = ::GetTempFileNameA(temp_dir_path, "gtest_redir",
0, // Generate unique file name.
temp_file_path);
GTEST_CHECK_(success != 0)
<< "Unable to create a temporary file in " << temp_dir_path;
const int captured_fd = creat(temp_file_path, _S_IREAD | _S_IWRITE);
- GTEST_CHECK_(captured_fd != -1) << "Unable to open temporary file "
- << temp_file_path;
+ GTEST_CHECK_(captured_fd != -1)
+ << "Unable to open temporary file " << temp_file_path;
filename_ = temp_file_path;
-# else
+# else
// There's no guarantee that a test has write access to the current
// directory, so we create the temporary file in the /tmp directory
// instead. We use /tmp on most systems, and /sdcard on Android.
// That's because Android doesn't have /tmp.
-# if GTEST_OS_LINUX_ANDROID
+# if GTEST_OS_LINUX_ANDROID
// Note: Android applications are expected to call the framework's
// Context.getExternalStorageDirectory() method through JNI to get
// the location of the world-writable SD Card directory. However,
@@ -8760,20 +8603,18 @@
// other OEM-customized locations. Never rely on these, and always
// use /sdcard.
char name_template[] = "/sdcard/gtest_captured_stream.XXXXXX";
-# else
+# else
char name_template[] = "/tmp/captured_stream.XXXXXX";
-# endif // GTEST_OS_LINUX_ANDROID
+# endif // GTEST_OS_LINUX_ANDROID
const int captured_fd = mkstemp(name_template);
filename_ = name_template;
-# endif // GTEST_OS_WINDOWS
+# endif // GTEST_OS_WINDOWS
fflush(NULL);
dup2(captured_fd, fd_);
close(captured_fd);
}
- ~CapturedStream() {
- remove(filename_.c_str());
- }
+ ~CapturedStream() { remove(filename_.c_str()); }
std::string GetCapturedString() {
if (uncaptured_fd_ != -1) {
@@ -8824,7 +8665,8 @@
// Keeps reading the file until we cannot read further or the
// pre-determined file size is reached.
do {
- bytes_last_read = fread(buffer+bytes_read, 1, file_size-bytes_read, file);
+ bytes_last_read =
+ fread(buffer + bytes_read, 1, file_size - bytes_read, file);
bytes_read += bytes_last_read;
} while (bytes_last_read > 0 && bytes_read < file_size);
@@ -8834,9 +8676,9 @@
return content;
}
-# ifdef _MSC_VER
-# pragma warning(pop)
-# endif // _MSC_VER
+# ifdef _MSC_VER
+# pragma warning(pop)
+# endif // _MSC_VER
static CapturedStream* g_captured_stderr = NULL;
static CapturedStream* g_captured_stdout = NULL;
@@ -8888,11 +8730,10 @@
::std::vector<testing::internal::string> g_argvs;
static const ::std::vector<testing::internal::string>* g_injected_test_argvs =
- NULL; // Owned.
+ NULL; // Owned.
void SetInjectableArgvs(const ::std::vector<testing::internal::string>* argvs) {
- if (g_injected_test_argvs != argvs)
- delete g_injected_test_argvs;
+ if (g_injected_test_argvs != argvs) delete g_injected_test_argvs;
g_injected_test_argvs = argvs;
}
@@ -8955,7 +8796,7 @@
// LONG_MAX or LONG_MIN when the input overflows.)
result != long_value
// The parsed value overflows as an Int32.
- ) {
+ ) {
Message msg;
msg << "WARNING: " << src_text
<< " is expected to be a 32-bit integer, but actually"
@@ -8976,8 +8817,7 @@
bool BoolFromGTestEnv(const char* flag, bool default_value) {
const std::string env_var = FlagToEnvVar(flag);
const char* const string_value = posix::GetEnv(env_var.c_str());
- return string_value == NULL ?
- default_value : strcmp(string_value, "0") != 0;
+ return string_value == NULL ? default_value : strcmp(string_value, "0") != 0;
}
// Reads and returns a 32-bit integer stored in the environment
@@ -8992,8 +8832,8 @@
}
Int32 result = default_value;
- if (!ParseInt32(Message() << "Environment variable " << env_var,
- string_value, &result)) {
+ if (!ParseInt32(Message() << "Environment variable " << env_var, string_value,
+ &result)) {
printf("The default value %s is used.\n",
(Message() << default_value).GetString().c_str());
fflush(stdout);
@@ -9105,7 +8945,7 @@
PrintByteSegmentInObjectTo(obj_bytes, 0, kChunkSize, os);
*os << " ... ";
// Rounds up to 2-byte boundary.
- const size_t resume_pos = (count - kChunkSize + 1)/2*2;
+ const size_t resume_pos = (count - kChunkSize + 1) / 2 * 2;
PrintByteSegmentInObjectTo(obj_bytes, resume_pos, count - resume_pos, os);
}
*os << ">";
@@ -9134,18 +8974,12 @@
// - as is if it's a printable ASCII (e.g. 'a', '2', ' '),
// - as a hexidecimal escape sequence (e.g. '\x7F'), or
// - as a special escape sequence (e.g. '\r', '\n').
-enum CharFormat {
- kAsIs,
- kHexEscape,
- kSpecialEscape
-};
+enum CharFormat { kAsIs, kHexEscape, kSpecialEscape };
// Returns true if c is a printable ASCII character. We test the
// value of c directly instead of calling isprint(), which is buggy on
// Windows Mobile.
-inline bool IsPrintableAscii(wchar_t c) {
- return 0x20 <= c && c <= 0x7E;
-}
+inline bool IsPrintableAscii(wchar_t c) { return 0x20 <= c && c <= 0x7E; }
// Prints a wide or narrow char c as a character literal without the
// quotes, escaping it when necessary; returns how c was formatted.
@@ -9154,44 +8988,44 @@
template <typename UnsignedChar, typename Char>
static CharFormat PrintAsCharLiteralTo(Char c, ostream* os) {
switch (static_cast<wchar_t>(c)) {
- case L'\0':
- *os << "\\0";
- break;
- case L'\'':
- *os << "\\'";
- break;
- case L'\\':
- *os << "\\\\";
- break;
- case L'\a':
- *os << "\\a";
- break;
- case L'\b':
- *os << "\\b";
- break;
- case L'\f':
- *os << "\\f";
- break;
- case L'\n':
- *os << "\\n";
- break;
- case L'\r':
- *os << "\\r";
- break;
- case L'\t':
- *os << "\\t";
- break;
- case L'\v':
- *os << "\\v";
- break;
- default:
- if (IsPrintableAscii(c)) {
- *os << static_cast<char>(c);
- return kAsIs;
- } else {
- *os << "\\x" + String::FormatHexInt(static_cast<UnsignedChar>(c));
- return kHexEscape;
- }
+ case L'\0':
+ *os << "\\0";
+ break;
+ case L'\'':
+ *os << "\\'";
+ break;
+ case L'\\':
+ *os << "\\\\";
+ break;
+ case L'\a':
+ *os << "\\a";
+ break;
+ case L'\b':
+ *os << "\\b";
+ break;
+ case L'\f':
+ *os << "\\f";
+ break;
+ case L'\n':
+ *os << "\\n";
+ break;
+ case L'\r':
+ *os << "\\r";
+ break;
+ case L'\t':
+ *os << "\\t";
+ break;
+ case L'\v':
+ *os << "\\v";
+ break;
+ default:
+ if (IsPrintableAscii(c)) {
+ *os << static_cast<char>(c);
+ return kAsIs;
+ } else {
+ *os << "\\x" + String::FormatHexInt(static_cast<UnsignedChar>(c));
+ return kHexEscape;
+ }
}
return kSpecialEscape;
}
@@ -9200,14 +9034,14 @@
// necessary; returns how c was formatted.
static CharFormat PrintAsStringLiteralTo(wchar_t c, ostream* os) {
switch (c) {
- case L'\'':
- *os << "'";
- return kAsIs;
- case L'"':
- *os << "\\\"";
- return kSpecialEscape;
- default:
- return PrintAsCharLiteralTo<wchar_t>(c, os);
+ case L'\'':
+ *os << "'";
+ return kAsIs;
+ case L'"':
+ *os << "\\\"";
+ return kSpecialEscape;
+ default:
+ return PrintAsCharLiteralTo<wchar_t>(c, os);
}
}
@@ -9232,8 +9066,7 @@
// To aid user debugging, we also print c's code in decimal, unless
// it's 0 (in which case c was printed as '\\0', making the code
// obvious).
- if (c == 0)
- return;
+ if (c == 0) return;
*os << " (" << static_cast<int>(c);
// For more convenience, we print c's code again in hexidecimal,
@@ -9256,17 +9089,15 @@
// Prints a wchar_t as a symbol if it is printable or as its internal
// code otherwise and also as its code. L'\0' is printed as "L'\\0'".
-void PrintTo(wchar_t wc, ostream* os) {
- PrintCharAndCodeTo<wchar_t>(wc, os);
-}
+void PrintTo(wchar_t wc, ostream* os) { PrintCharAndCodeTo<wchar_t>(wc, os); }
// Prints the given array of characters to the ostream. CharType must be either
// char or wchar_t.
// The array starts at begin, the length is len, it may include '\0' characters
// and may not be NUL-terminated.
template <typename CharType>
-static void PrintCharsAsStringTo(
- const CharType* begin, size_t len, ostream* os) {
+static void PrintCharsAsStringTo(const CharType* begin, size_t len,
+ ostream* os) {
const char* const kQuoteBegin = sizeof(CharType) == 1 ? "\"" : "L\"";
*os << kQuoteBegin;
bool is_previous_hex = false;
@@ -9286,8 +9117,8 @@
// Prints a (const) char/wchar_t array of 'len' elements, starting at address
// 'begin'. CharType must be either char or wchar_t.
template <typename CharType>
-static void UniversalPrintCharArray(
- const CharType* begin, size_t len, ostream* os) {
+static void UniversalPrintCharArray(const CharType* begin, size_t len,
+ ostream* os) {
// The code
// const char kFoo[] = "foo";
// generates an array of 4, not 3, elements, with the last one being '\0'.
@@ -9407,7 +9238,6 @@
//
// The Google C++ Testing Framework (Google Test)
-
// Indicates that this translation unit is part of Google Test's
// implementation. It must come before gtest-internal-inl.h is
// included, or there will be a compiler error. This trick is to
@@ -9424,18 +9254,19 @@
// in it.
std::string TestPartResult::ExtractSummary(const char* message) {
const char* const stack_trace = strstr(message, internal::kStackTraceMarker);
- return stack_trace == NULL ? message :
- std::string(message, stack_trace);
+ return stack_trace == NULL ? message : std::string(message, stack_trace);
}
// Prints a TestPartResult object.
std::ostream& operator<<(std::ostream& os, const TestPartResult& result) {
- return os
- << result.file_name() << ":" << result.line_number() << ": "
- << (result.type() == TestPartResult::kSuccess ? "Success" :
- result.type() == TestPartResult::kFatalFailure ? "Fatal failure" :
- "Non-fatal failure") << ":\n"
- << result.message() << std::endl;
+ return os << result.file_name() << ":" << result.line_number() << ": "
+ << (result.type() == TestPartResult::kSuccess
+ ? "Success"
+ : result.type() == TestPartResult::kFatalFailure
+ ? "Fatal failure"
+ : "Non-fatal failure")
+ << ":\n"
+ << result.message() << std::endl;
}
// Appends a TestPartResult to the array.
@@ -9462,8 +9293,8 @@
HasNewFatalFailureHelper::HasNewFatalFailureHelper()
: has_new_fatal_failure_(false),
- original_reporter_(GetUnitTestImpl()->
- GetTestPartResultReporterForCurrentThread()) {
+ original_reporter_(
+ GetUnitTestImpl()->GetTestPartResultReporterForCurrentThread()) {
GetUnitTestImpl()->SetTestPartResultReporterForCurrentThread(this);
}
@@ -9474,8 +9305,7 @@
void HasNewFatalFailureHelper::ReportTestPartResult(
const TestPartResult& result) {
- if (result.fatally_failed())
- has_new_fatal_failure_ = true;
+ if (result.fatally_failed()) has_new_fatal_failure_ = true;
original_reporter_->ReportTestPartResult(result);
}
@@ -9513,7 +9343,6 @@
//
// Author: wan@google.com (Zhanyong Wan)
-
namespace testing {
namespace internal {
@@ -9522,8 +9351,7 @@
// Skips to the first non-space char in str. Returns an empty string if str
// contains only whitespace characters.
static const char* SkipSpaces(const char* str) {
- while (IsSpace(*str))
- str++;
+ while (IsSpace(*str)) str++;
return str;
}
@@ -9551,8 +9379,7 @@
bool found = false;
for (DefinedTestIter it = defined_test_names_.begin();
- it != defined_test_names_.end();
- ++it) {
+ it != defined_test_names_.end(); ++it) {
if (name == *it) {
found = true;
break;
@@ -9568,8 +9395,7 @@
}
for (DefinedTestIter it = defined_test_names_.begin();
- it != defined_test_names_.end();
- ++it) {
+ it != defined_test_names_.end(); ++it) {
if (tests.count(*it) == 0) {
errors << "You forgot to list test " << *it << ".\n";
}
@@ -9667,7 +9493,6 @@
//
// This file implements cardinalities.
-
#include <limits.h>
#include <ostream> // NOLINT
#include <sstream>
@@ -9681,8 +9506,7 @@
class BetweenCardinalityImpl : public CardinalityInterface {
public:
BetweenCardinalityImpl(int min, int max)
- : min_(min >= 0 ? min : 0),
- max_(max >= min_ ? max : min_) {
+ : min_(min >= 0 ? min : 0), max_(max >= min_ ? max : min_) {
std::stringstream ss;
if (min < 0) {
ss << "The invocation lower bound must be >= 0, "
@@ -9694,8 +9518,7 @@
internal::Expect(false, __FILE__, __LINE__, ss.str());
} else if (min > max) {
ss << "The invocation upper bound (" << max
- << ") must be >= the invocation lower bound (" << min
- << ").";
+ << ") must be >= the invocation lower bound (" << min << ").";
internal::Expect(false, __FILE__, __LINE__, ss.str());
}
}
@@ -9822,7 +9645,6 @@
// Mock. They are subject to change without notice, so please DO NOT
// USE THEM IN USER CODE.
-
#include <ctype.h>
#include <ostream> // NOLINT
#include <string>
@@ -9841,12 +9663,11 @@
// We don't care about the current locale as the input is
// guaranteed to be a valid C++ identifier name.
const bool starts_new_word = IsUpper(*p) ||
- (!IsAlpha(prev_char) && IsLower(*p)) ||
- (!IsDigit(prev_char) && IsDigit(*p));
+ (!IsAlpha(prev_char) && IsLower(*p)) ||
+ (!IsDigit(prev_char) && IsDigit(*p));
if (IsAlNum(*p)) {
- if (starts_new_word && result != "")
- result += ' ';
+ if (starts_new_word && result != "") result += ' ';
result += ToLower(*p);
}
}
@@ -9860,12 +9681,9 @@
public:
virtual void ReportFailure(FailureType type, const char* file, int line,
const string& message) {
- AssertHelper(type == kFatal ?
- TestPartResult::kFatalFailure :
- TestPartResult::kNonFatalFailure,
- file,
- line,
- message.c_str()) = Message();
+ AssertHelper(type == kFatal ? TestPartResult::kFatalFailure
+ : TestPartResult::kNonFatalFailure,
+ file, line, message.c_str()) = Message();
if (type == kFatal) {
posix::Abort();
}
@@ -9911,11 +9729,9 @@
// stack_frames_to_skip is treated as 0, since we don't know which
// function calls will be inlined by the compiler and need to be
// conservative.
-GTEST_API_ void Log(LogSeverity severity,
- const string& message,
+GTEST_API_ void Log(LogSeverity severity, const string& message,
int stack_frames_to_skip) {
- if (!LogIsVisible(severity))
- return;
+ if (!LogIsVisible(severity)) return;
// Ensures that logs from different threads don't interleave.
MutexLock l(&g_log_mutex);
@@ -9947,8 +9763,8 @@
std::cout << "\n";
}
std::cout << "Stack trace:\n"
- << ::testing::internal::GetCurrentOsStackTraceExceptTop(
- ::testing::UnitTest::GetInstance(), actual_to_skip);
+ << ::testing::internal::GetCurrentOsStackTraceExceptTop(
+ ::testing::UnitTest::GetInstance(), actual_to_skip);
}
std::cout << ::std::flush;
}
@@ -9991,7 +9807,6 @@
// This file implements Matcher<const string&>, Matcher<string>, and
// utilities for defining matchers.
-
#include <string.h>
#include <sstream>
#include <string>
@@ -10038,9 +9853,7 @@
}
// Constructs a matcher that matches a StringPiece whose value is equal to s.
-Matcher<StringPiece>::Matcher(const internal::string& s) {
- *this = Eq(s);
-}
+Matcher<StringPiece>::Matcher(const internal::string& s) { *this = Eq(s); }
// Constructs a matcher that matches a StringPiece whose value is equal to s.
Matcher<StringPiece>::Matcher(const char* s) {
@@ -10048,9 +9861,7 @@
}
// Constructs a matcher that matches a StringPiece whose value is equal to s.
-Matcher<StringPiece>::Matcher(StringPiece s) {
- *this = Eq(s.ToString());
-}
+Matcher<StringPiece>::Matcher(StringPiece s) { *this = Eq(s.ToString()); }
#endif // GTEST_HAS_STRING_PIECE_
namespace internal {
@@ -10059,18 +9870,18 @@
// the joined string.
GTEST_API_ string JoinAsTuple(const Strings& fields) {
switch (fields.size()) {
- case 0:
- return "";
- case 1:
- return fields[0];
- default:
- string result = "(" + fields[0];
- for (size_t i = 1; i < fields.size(); i++) {
- result += ", ";
- result += fields[i];
- }
- result += ")";
- return result;
+ case 0:
+ return "";
+ case 1:
+ return fields[0];
+ default:
+ string result = "(" + fields[0];
+ for (size_t i = 1; i < fields.size(); i++) {
+ result += ", ";
+ result += fields[i];
+ }
+ result += ")";
+ return result;
}
}
@@ -10083,8 +9894,7 @@
const char* matcher_name,
const Strings& param_values) {
string result = ConvertIdentifierNameToWords(matcher_name);
- if (param_values.size() >= 1)
- result += " " + JoinAsTuple(param_values);
+ if (param_values.size() >= 1) result += " " + JoinAsTuple(param_values);
return negation ? "not (" + result + ")" : result;
}
@@ -10155,8 +9965,7 @@
explicit MaxBipartiteMatchState(const MatchMatrix& graph)
: graph_(&graph),
left_(graph_->LhsSize(), kUnused),
- right_(graph_->RhsSize(), kUnused) {
- }
+ right_(graph_->RhsSize(), kUnused) {}
// Returns the edges of a maximal match, each in the form {left, right}.
ElementMatcherPairs Compute() {
@@ -10213,10 +10022,8 @@
//
bool TryAugment(size_t ilhs, ::std::vector<char>* seen) {
for (size_t irhs = 0; irhs < graph_->RhsSize(); ++irhs) {
- if ((*seen)[irhs])
- continue;
- if (!graph_->HasEdge(ilhs, irhs))
- continue;
+ if ((*seen)[irhs]) continue;
+ if (!graph_->HasEdge(ilhs, irhs)) continue;
// There's an available edge from ilhs to irhs.
(*seen)[irhs] = 1;
// Next a search is performed to determine whether
@@ -10259,8 +10066,7 @@
const size_t MaxBipartiteMatchState::kUnused;
-GTEST_API_ ElementMatcherPairs
-FindMaxBipartiteMatching(const MatchMatrix& g) {
+GTEST_API_ ElementMatcherPairs FindMaxBipartiteMatching(const MatchMatrix& g) {
return MaxBipartiteMatchState(g).Compute();
}
@@ -10269,7 +10075,7 @@
typedef ElementMatcherPairs::const_iterator Iter;
::std::ostream& os = *stream;
os << "{";
- const char *sep = "";
+ const char* sep = "";
for (Iter it = pairs.begin(); it != pairs.end(); ++it) {
os << sep << "\n ("
<< "element #" << it->first << ", "
@@ -10300,7 +10106,7 @@
if (matches.size() > 1) {
if (listener->IsInterested()) {
- const char *sep = "where:\n";
+ const char* sep = "where:\n";
for (size_t mi = 0; mi < matches.size(); ++mi) {
*listener << sep << " - element #" << matches[mi].first
<< " is matched by matcher #" << matches[mi].second;
@@ -10336,7 +10142,7 @@
string MatchMatrix::DebugString() const {
::std::stringstream ss;
- const char *sep = "";
+ const char* sep = "";
for (size_t i = 0; i < LhsSize(); ++i) {
ss << sep;
for (size_t j = 0; j < RhsSize(); ++j) {
@@ -10375,8 +10181,8 @@
return;
}
if (matcher_describers_.size() == 1) {
- *os << "doesn't have " << Elements(1)
- << ", or has " << Elements(1) << " that ";
+ *os << "doesn't have " << Elements(1) << ", or has " << Elements(1)
+ << " that ";
matcher_describers_[0]->DescribeNegationTo(os);
return;
}
@@ -10396,10 +10202,9 @@
// Returns false, writing an explanation to 'listener', if and only
// if the success criteria are not met.
bool UnorderedElementsAreMatcherImplBase::
-VerifyAllElementsAndMatchersAreMatched(
- const ::std::vector<string>& element_printouts,
- const MatchMatrix& matrix,
- MatchResultListener* listener) const {
+ VerifyAllElementsAndMatchersAreMatched(
+ const ::std::vector<string>& element_printouts,
+ const MatchMatrix& matrix, MatchResultListener* listener) const {
bool result = true;
::std::vector<char> element_matched(matrix.LhsSize(), 0);
::std::vector<char> matcher_matched(matrix.RhsSize(), 0);
@@ -10416,8 +10221,7 @@
const char* sep =
"where the following matchers don't match any elements:\n";
for (size_t mi = 0; mi < matcher_matched.size(); ++mi) {
- if (matcher_matched[mi])
- continue;
+ if (matcher_matched[mi]) continue;
result = false;
if (listener->IsInterested()) {
*listener << sep << "matcher #" << mi << ": ";
@@ -10435,8 +10239,7 @@
outer_sep = "\nand ";
}
for (size_t ei = 0; ei < element_matched.size(); ++ei) {
- if (element_matched[ei])
- continue;
+ if (element_matched[ei]) continue;
result = false;
if (listener->IsInterested()) {
*listener << outer_sep << sep << "element #" << ei << ": "
@@ -10487,7 +10290,6 @@
// This file implements the spec builder syntax (ON_CALL and
// EXPECT_CALL).
-
#include <stdlib.h>
#include <iostream> // NOLINT
#include <map>
@@ -10495,7 +10297,7 @@
#include <string>
#if GTEST_OS_CYGWIN || GTEST_OS_LINUX || GTEST_OS_MAC
-# include <unistd.h> // NOLINT
+# include <unistd.h> // NOLINT
#endif
namespace testing {
@@ -10515,8 +10317,7 @@
}
// Constructs an ExpectationBase object.
-ExpectationBase::ExpectationBase(const char* a_file,
- int a_line,
+ExpectationBase::ExpectationBase(const char* a_file, int a_line,
const string& a_source_text)
: file_(a_file),
line_(a_line),
@@ -10609,11 +10410,12 @@
// Describes the state of the expectation (e.g. is it satisfied?
// is it active?).
- *os << " - " << (IsOverSaturated() ? "over-saturated" :
- IsSaturated() ? "saturated" :
- IsSatisfied() ? "satisfied" : "unsatisfied")
- << " and "
- << (is_retired() ? "retired" : "active");
+ *os << " - "
+ << (IsOverSaturated()
+ ? "over-saturated"
+ : IsSaturated() ? "saturated"
+ : IsSatisfied() ? "satisfied" : "unsatisfied")
+ << " and " << (is_retired() ? "retired" : "active");
}
// Checks the action count (i.e. the number of WillOnce() and
@@ -10656,13 +10458,12 @@
::std::stringstream ss;
DescribeLocationTo(&ss);
- ss << "Too " << (too_many ? "many" : "few")
- << " actions specified in " << source_text() << "...\n"
+ ss << "Too " << (too_many ? "many" : "few") << " actions specified in "
+ << source_text() << "...\n"
<< "Expected to be ";
cardinality().DescribeTo(&ss);
- ss << ", but has " << (too_many ? "" : "only ")
- << action_count << " WillOnce()"
- << (action_count == 1 ? "" : "s");
+ ss << ", but has " << (too_many ? "" : "only ") << action_count
+ << " WillOnce()" << (action_count == 1 ? "" : "s");
if (repeated_action_specified_) {
ss << " and a WillRepeatedly()";
}
@@ -10696,14 +10497,14 @@
// manner specified by 'reaction'.
void ReportUninterestingCall(CallReaction reaction, const string& msg) {
switch (reaction) {
- case kAllow:
- Log(kInfo, msg, 3);
- break;
- case kWarn:
- Log(kWarning, msg, 3);
- break;
- default: // FAIL
- Expect(false, NULL, -1, msg);
+ case kAllow:
+ Log(kInfo, msg, 3);
+ break;
+ case kWarn:
+ Log(kWarning, msg, 3);
+ break;
+ default: // FAIL
+ Expect(false, NULL, -1, msg);
}
}
@@ -10796,12 +10597,14 @@
// If the user allows this uninteresting call, we print it
// only when he wants informational messages.
reaction == kAllow ? LogIsVisible(kInfo) :
- // If the user wants this to be a warning, we print it only
- // when he wants to see warnings.
- reaction == kWarn ? LogIsVisible(kWarning) :
- // Otherwise, the user wants this to be an error, and we
- // should always print detailed information in the error.
- true;
+ // If the user wants this to be a warning, we print
+ // it only when he wants to see warnings.
+ reaction == kWarn
+ ? LogIsVisible(kWarning)
+ :
+ // Otherwise, the user wants this to be an error, and we
+ // should always print detailed information in the error.
+ true;
if (!need_to_report_uninteresting_call) {
// Perform the action without printing the call information.
@@ -10817,8 +10620,7 @@
this->UntypedPerformDefaultAction(untyped_args, ss.str());
// Prints the function result.
- if (result != NULL)
- result->PrintAsActionResult(&ss);
+ if (result != NULL) result->PrintAsActionResult(&ss);
ReportUninterestingCall(reaction, ss.str());
return result;
@@ -10833,9 +10635,8 @@
// The UntypedFindMatchingExpectation() function acquires and
// releases g_gmock_mutex.
const ExpectationBase* const untyped_expectation =
- this->UntypedFindMatchingExpectation(
- untyped_args, &untyped_action, &is_excessive,
- &ss, &why);
+ this->UntypedFindMatchingExpectation(untyped_args, &untyped_action,
+ &is_excessive, &ss, &why);
const bool found = untyped_expectation != NULL;
// True iff we need to print the call's arguments and return value.
@@ -10845,10 +10646,9 @@
!found || is_excessive || LogIsVisible(kInfo);
if (!need_to_report_call) {
// Perform the action without printing the call information.
- return
- untyped_action == NULL ?
- this->UntypedPerformDefaultAction(untyped_args, "") :
- this->UntypedPerformAction(untyped_action, untyped_args);
+ return untyped_action == NULL
+ ? this->UntypedPerformDefaultAction(untyped_args, "")
+ : this->UntypedPerformAction(untyped_action, untyped_args);
}
ss << " Function call: " << Name();
@@ -10861,11 +10661,10 @@
}
const UntypedActionResultHolderBase* const result =
- untyped_action == NULL ?
- this->UntypedPerformDefaultAction(untyped_args, ss.str()) :
- this->UntypedPerformAction(untyped_action, untyped_args);
- if (result != NULL)
- result->PrintAsActionResult(&ss);
+ untyped_action == NULL
+ ? this->UntypedPerformDefaultAction(untyped_args, ss.str())
+ : this->UntypedPerformAction(untyped_action, untyped_args);
+ if (result != NULL) result->PrintAsActionResult(&ss);
ss << "\n" << why.str();
if (!found) {
@@ -10873,8 +10672,8 @@
Expect(false, NULL, -1, ss.str());
} else if (is_excessive) {
// We had an upper-bound violation and the failure message is in ss.
- Expect(false, untyped_expectation->file(),
- untyped_expectation->line(), ss.str());
+ Expect(false, untyped_expectation->file(), untyped_expectation->line(),
+ ss.str());
} else {
// We had an expected call and the matching expectation is
// described in ss.
@@ -10887,8 +10686,7 @@
// Returns an Expectation object that references and co-owns exp,
// which must be an expectation on this mock function.
Expectation UntypedFunctionMockerBase::GetHandleOf(ExpectationBase* exp) {
- for (UntypedExpectations::const_iterator it =
- untyped_expectations_.begin();
+ for (UntypedExpectations::const_iterator it = untyped_expectations_.begin();
it != untyped_expectations_.end(); ++it) {
if (it->get() == exp) {
return Expectation(*it);
@@ -10908,8 +10706,7 @@
GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
g_gmock_mutex.AssertHeld();
bool expectations_met = true;
- for (UntypedExpectations::const_iterator it =
- untyped_expectations_.begin();
+ for (UntypedExpectations::const_iterator it = untyped_expectations_.begin();
it != untyped_expectations_.end(); ++it) {
ExpectationBase* const untyped_expectation = it->get();
if (untyped_expectation->IsOverSaturated()) {
@@ -10920,15 +10717,15 @@
} else if (!untyped_expectation->IsSatisfied()) {
expectations_met = false;
::std::stringstream ss;
- ss << "Actual function call count doesn't match "
- << untyped_expectation->source_text() << "...\n";
+ ss << "Actual function call count doesn't match "
+ << untyped_expectation->source_text() << "...\n";
// No need to show the source file location of the expectation
// in the description, as the Expect() call that follows already
// takes care of it.
untyped_expectation->MaybeDescribeExtraMatcherTo(&ss);
untyped_expectation->DescribeCallCountTo(&ss);
- Expect(false, untyped_expectation->file(),
- untyped_expectation->line(), ss.str());
+ Expect(false, untyped_expectation->file(), untyped_expectation->line(),
+ ss.str());
}
}
@@ -10970,7 +10767,7 @@
int first_used_line;
::std::string first_used_test_case;
::std::string first_used_test;
- bool leakable; // true iff it's OK to leak the object.
+ bool leakable; // true iff it's OK to leak the object.
FunctionMockers function_mockers; // All registered methods of the object.
};
@@ -10991,8 +10788,7 @@
// "using ::std::cout;" doesn't work with Symbian's STLport, where cout is
// a macro.
- if (!GMOCK_FLAG(catch_leaked_mocks))
- return;
+ if (!GMOCK_FLAG(catch_leaked_mocks)) return;
int leaked_count = 0;
for (StateMap::const_iterator it = states_.begin(); it != states_.end();
@@ -11009,16 +10805,16 @@
std::cout << " ERROR: this mock object";
if (state.first_used_test != "") {
std::cout << " (used in test " << state.first_used_test_case << "."
- << state.first_used_test << ")";
+ << state.first_used_test << ")";
}
std::cout << " should be deleted but never is. Its address is @"
- << it->first << ".";
+ << it->first << ".";
leaked_count++;
}
if (leaked_count > 0) {
- std::cout << "\nERROR: " << leaked_count
- << " leaked mock " << (leaked_count == 1 ? "object" : "objects")
- << " found at program exit.\n";
+ std::cout << "\nERROR: " << leaked_count << " leaked mock "
+ << (leaked_count == 1 ? "object" : "objects")
+ << " found at program exit.\n";
std::cout.flush();
::std::cerr.flush();
// RUN_ALL_TESTS() has already returned when this destructor is
@@ -11085,11 +10881,11 @@
// Returns the reaction Google Mock will have on uninteresting calls
// made on the given mock object.
internal::CallReaction Mock::GetReactionOnUninterestingCalls(
- const void* mock_obj)
- GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
+ const void* mock_obj) GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
internal::MutexLock l(&internal::g_gmock_mutex);
- return (g_uninteresting_call_reaction.count(mock_obj) == 0) ?
- internal::kDefault : g_uninteresting_call_reaction[mock_obj];
+ return (g_uninteresting_call_reaction.count(mock_obj) == 0)
+ ? internal::kDefault
+ : g_uninteresting_call_reaction[mock_obj];
}
// Tells Google Mock to ignore mock_obj when checking for leaked mock
@@ -11234,8 +11030,8 @@
void Sequence::AddExpectation(const Expectation& expectation) const {
if (*last_expectation_ != expectation) {
if (last_expectation_->expectation_base() != NULL) {
- expectation.expectation_base()->immediate_prerequisites_
- += *last_expectation_;
+ expectation.expectation_base()->immediate_prerequisites_ +=
+ *last_expectation_;
}
*last_expectation_ = expectation;
}
@@ -11292,7 +11088,6 @@
//
// Author: wan@google.com (Zhanyong Wan)
-
namespace testing {
// TODO(wan@google.com): support using environment variables to
@@ -11316,8 +11111,7 @@
// "=value" part can be omitted.
//
// Returns the value of the flag, or NULL if the parsing failed.
-static const char* ParseGoogleMockFlagValue(const char* str,
- const char* flag,
+static const char* ParseGoogleMockFlagValue(const char* str, const char* flag,
bool def_optional) {
// str and flag must not be NULL.
if (str == NULL || flag == NULL) return NULL;
diff --git a/test/grisu-test.cc b/test/grisu-test.cc
new file mode 100644
index 0000000..79a1319
--- /dev/null
+++ b/test/grisu-test.cc
@@ -0,0 +1,57 @@
+// Formatting library for C++ - Grisu tests
+//
+// Copyright (c) 2012 - present, Victor Zverovich
+// All rights reserved.
+//
+// For the license information refer to format.h.
+
+#include "fmt/format.h"
+#include "gtest.h"
+
+static bool reported_skipped;
+
+#undef TEST
+#define TEST(test_fixture, test_name) \
+ void test_fixture##test_name(); \
+ GTEST_TEST(test_fixture, test_name) { \
+ if (FMT_USE_GRISU) { \
+ test_fixture##test_name(); \
+ } else if (!reported_skipped) { \
+ reported_skipped = true; \
+ fmt::print("Skipping Grisu tests.\n"); \
+ } \
+ } \
+ void test_fixture##test_name()
+
+TEST(GrisuTest, NaN) {
+ auto nan = std::numeric_limits<double>::quiet_NaN();
+ EXPECT_EQ("nan", fmt::format("{}", nan));
+ EXPECT_EQ("-nan", fmt::format("{}", -nan));
+}
+
+TEST(GrisuTest, Inf) {
+ auto inf = std::numeric_limits<double>::infinity();
+ EXPECT_EQ("inf", fmt::format("{}", inf));
+ EXPECT_EQ("-inf", fmt::format("{}", -inf));
+}
+
+TEST(GrisuTest, Zero) { EXPECT_EQ("0.0", fmt::format("{}", 0.0)); }
+
+TEST(GrisuTest, Round) {
+ EXPECT_EQ("1.9156918820264798e-56",
+ fmt::format("{}", 1.9156918820264798e-56));
+ EXPECT_EQ("0.0000", fmt::format("{:.4f}", 7.2809479766055470e-15));
+}
+
+TEST(GrisuTest, Prettify) {
+ EXPECT_EQ("0.0001", fmt::format("{}", 1e-4));
+ EXPECT_EQ("1e-05", fmt::format("{}", 1e-5));
+ EXPECT_EQ("9.999e-05", fmt::format("{}", 9.999e-5));
+ EXPECT_EQ("10000000000.0", fmt::format("{}", 1e10));
+ EXPECT_EQ("1e+11", fmt::format("{}", 1e11));
+ EXPECT_EQ("12340000000.0", fmt::format("{}", 1234e7));
+ EXPECT_EQ("12.34", fmt::format("{}", 1234e-2));
+ EXPECT_EQ("0.001234", fmt::format("{}", 1234e-6));
+}
+
+TEST(GrisuTest, ZeroPrecision) { EXPECT_EQ("1", fmt::format("{:.0}", 1.0)); }
diff --git a/test/gtest-extra-test.cc b/test/gtest-extra-test.cc
index 43088db..3f8fd5e 100644
--- a/test/gtest-extra-test.cc
+++ b/test/gtest-extra-test.cc
@@ -7,23 +7,22 @@
#include "gtest-extra.h"
-#include <cstring>
-#include <algorithm>
-#include <stdexcept>
#include <gtest/gtest-spi.h>
+#include <algorithm>
+#include <cstring>
+#include <memory>
+#include <stdexcept>
#if defined(_WIN32) && !defined(__MINGW32__)
-# include <crtdbg.h> // for _CrtSetReportMode
-#endif // _WIN32
+# include <crtdbg.h> // for _CrtSetReportMode
+#endif // _WIN32
#include "util.h"
-using testing::internal::scoped_ptr;
-
namespace {
// This is used to suppress coverity warnings about untrusted values.
-std::string sanitize(const std::string &s) {
+std::string sanitize(const std::string& s) {
std::string result;
for (std::string::const_iterator i = s.begin(), end = s.end(); i != end; ++i)
result.push_back(static_cast<char>(*i & 0xff));
@@ -53,11 +52,9 @@
void do_nothing() {}
-void throw_exception() {
- throw std::runtime_error("test");
-}
+FMT_NORETURN void throw_exception() { throw std::runtime_error("test"); }
-void throw_system_error() {
+FMT_NORETURN void throw_system_error() {
throw fmt::system_error(EDOM, "test");
}
@@ -72,43 +69,50 @@
// Tests that when EXPECT_SYSTEM_ERROR fails, it evaluates its message argument
// exactly once.
TEST_F(SingleEvaluationTest, FailedEXPECT_SYSTEM_ERROR) {
- EXPECT_NONFATAL_FAILURE(
- EXPECT_SYSTEM_ERROR(throw_system_error(), EDOM, p_++), "01234");
+ EXPECT_NONFATAL_FAILURE(EXPECT_SYSTEM_ERROR(throw_system_error(), EDOM, p_++),
+ "01234");
EXPECT_EQ(s_ + 1, p_);
}
// Tests that when EXPECT_WRITE fails, it evaluates its message argument
// exactly once.
TEST_F(SingleEvaluationTest, FailedEXPECT_WRITE) {
- EXPECT_NONFATAL_FAILURE(
- EXPECT_WRITE(stdout, std::printf("test"), p_++), "01234");
+ EXPECT_NONFATAL_FAILURE(EXPECT_WRITE(stdout, std::printf("test"), p_++),
+ "01234");
EXPECT_EQ(s_ + 1, p_);
}
// Tests that assertion arguments are evaluated exactly once.
TEST_F(SingleEvaluationTest, ExceptionTests) {
// successful EXPECT_THROW_MSG
- EXPECT_THROW_MSG({ // NOLINT
- a_++;
- throw_exception();
- }, std::exception, (b_++, "test"));
+ EXPECT_THROW_MSG(
+ { // NOLINT
+ a_++;
+ throw_exception();
+ },
+ std::exception, (b_++, "test"));
EXPECT_EQ(1, a_);
EXPECT_EQ(1, b_);
// failed EXPECT_THROW_MSG, throws different type
- EXPECT_NONFATAL_FAILURE(EXPECT_THROW_MSG({ // NOLINT
- a_++;
- throw_exception();
- }, std::logic_error, (b_++, "test")), "throws a different type");
+ EXPECT_NONFATAL_FAILURE(EXPECT_THROW_MSG(
+ { // NOLINT
+ a_++;
+ throw_exception();
+ },
+ std::logic_error, (b_++, "test")),
+ "throws a different type");
EXPECT_EQ(2, a_);
EXPECT_EQ(2, b_);
// failed EXPECT_THROW_MSG, throws an exception with different message
- EXPECT_NONFATAL_FAILURE(EXPECT_THROW_MSG({ // NOLINT
- a_++;
- throw_exception();
- }, std::exception, (b_++, "other")),
- "throws an exception with a different message");
+ EXPECT_NONFATAL_FAILURE(EXPECT_THROW_MSG(
+ { // NOLINT
+ a_++;
+ throw_exception();
+ },
+ std::exception, (b_++, "other")),
+ "throws an exception with a different message");
EXPECT_EQ(3, a_);
EXPECT_EQ(3, b_);
@@ -121,33 +125,40 @@
TEST_F(SingleEvaluationTest, SystemErrorTests) {
// successful EXPECT_SYSTEM_ERROR
- EXPECT_SYSTEM_ERROR({ // NOLINT
- a_++;
- throw_system_error();
- }, EDOM, (b_++, "test"));
+ EXPECT_SYSTEM_ERROR(
+ { // NOLINT
+ a_++;
+ throw_system_error();
+ },
+ EDOM, (b_++, "test"));
EXPECT_EQ(1, a_);
EXPECT_EQ(1, b_);
// failed EXPECT_SYSTEM_ERROR, throws different type
- EXPECT_NONFATAL_FAILURE(EXPECT_SYSTEM_ERROR({ // NOLINT
- a_++;
- throw_exception();
- }, EDOM, (b_++, "test")), "throws a different type");
+ EXPECT_NONFATAL_FAILURE(EXPECT_SYSTEM_ERROR(
+ { // NOLINT
+ a_++;
+ throw_exception();
+ },
+ EDOM, (b_++, "test")),
+ "throws a different type");
EXPECT_EQ(2, a_);
EXPECT_EQ(2, b_);
// failed EXPECT_SYSTEM_ERROR, throws an exception with different message
- EXPECT_NONFATAL_FAILURE(EXPECT_SYSTEM_ERROR({ // NOLINT
- a_++;
- throw_system_error();
- }, EDOM, (b_++, "other")),
- "throws an exception with a different message");
+ EXPECT_NONFATAL_FAILURE(EXPECT_SYSTEM_ERROR(
+ { // NOLINT
+ a_++;
+ throw_system_error();
+ },
+ EDOM, (b_++, "other")),
+ "throws an exception with a different message");
EXPECT_EQ(3, a_);
EXPECT_EQ(3, b_);
// failed EXPECT_SYSTEM_ERROR, throws nothing
- EXPECT_NONFATAL_FAILURE(
- EXPECT_SYSTEM_ERROR(a_++, EDOM, (b_++, "test")), "throws nothing");
+ EXPECT_NONFATAL_FAILURE(EXPECT_SYSTEM_ERROR(a_++, EDOM, (b_++, "test")),
+ "throws nothing");
EXPECT_EQ(4, a_);
EXPECT_EQ(4, b_);
}
@@ -155,18 +166,23 @@
// Tests that assertion arguments are evaluated exactly once.
TEST_F(SingleEvaluationTest, WriteTests) {
// successful EXPECT_WRITE
- EXPECT_WRITE(stdout, { // NOLINT
- a_++;
- std::printf("test");
- }, (b_++, "test"));
+ EXPECT_WRITE(stdout,
+ { // NOLINT
+ a_++;
+ std::printf("test");
+ },
+ (b_++, "test"));
EXPECT_EQ(1, a_);
EXPECT_EQ(1, b_);
// failed EXPECT_WRITE
- EXPECT_NONFATAL_FAILURE(EXPECT_WRITE(stdout, { // NOLINT
- a_++;
- std::printf("test");
- }, (b_++, "other")), "Actual: test");
+ EXPECT_NONFATAL_FAILURE(EXPECT_WRITE(stdout,
+ { // NOLINT
+ a_++;
+ std::printf("test");
+ },
+ (b_++, "other")),
+ "Actual: test");
EXPECT_EQ(2, a_);
EXPECT_EQ(2, b_);
}
@@ -179,8 +195,8 @@
EXPECT_THROW_MSG(throw runtime_error(""), runtime_error, "");
EXPECT_NONFATAL_FAILURE(EXPECT_THROW_MSG(n++, runtime_error, ""), "");
EXPECT_NONFATAL_FAILURE(EXPECT_THROW_MSG(throw 1, runtime_error, ""), "");
- EXPECT_NONFATAL_FAILURE(EXPECT_THROW_MSG(
- throw runtime_error("a"), runtime_error, "b"), "");
+ EXPECT_NONFATAL_FAILURE(
+ EXPECT_THROW_MSG(throw runtime_error("a"), runtime_error, "b"), "");
}
// Tests that the compiler will not complain about unreachable code in the
@@ -190,8 +206,9 @@
EXPECT_SYSTEM_ERROR(throw fmt::system_error(EDOM, "test"), EDOM, "test");
EXPECT_NONFATAL_FAILURE(EXPECT_SYSTEM_ERROR(n++, EDOM, ""), "");
EXPECT_NONFATAL_FAILURE(EXPECT_SYSTEM_ERROR(throw 1, EDOM, ""), "");
- EXPECT_NONFATAL_FAILURE(EXPECT_SYSTEM_ERROR(
- throw fmt::system_error(EDOM, "aaa"), EDOM, "bbb"), "");
+ EXPECT_NONFATAL_FAILURE(
+ EXPECT_SYSTEM_ERROR(throw fmt::system_error(EDOM, "aaa"), EDOM, "bbb"),
+ "");
}
TEST(AssertionSyntaxTest, ExceptionAssertionBehavesLikeSingleStatement) {
@@ -268,10 +285,9 @@
EXPECT_WRITE(stdout, do_nothing(), "");
EXPECT_WRITE(stdout, std::printf("test"), "test");
EXPECT_WRITE(stderr, std::fprintf(stderr, "test"), "test");
- EXPECT_NONFATAL_FAILURE(
- EXPECT_WRITE(stdout, std::printf("that"), "this"),
- "Expected: this\n"
- " Actual: that");
+ EXPECT_NONFATAL_FAILURE(EXPECT_WRITE(stdout, std::printf("that"), "this"),
+ "Expected: this\n"
+ " Actual: that");
}
TEST(StreamingAssertionsTest, EXPECT_THROW_MSG) {
@@ -279,7 +295,8 @@
<< "unexpected failure";
EXPECT_NONFATAL_FAILURE(
EXPECT_THROW_MSG(throw_exception(), std::exception, "other")
- << "expected failure", "expected failure");
+ << "expected failure",
+ "expected failure");
}
TEST(StreamingAssertionsTest, EXPECT_SYSTEM_ERROR) {
@@ -287,15 +304,15 @@
<< "unexpected failure";
EXPECT_NONFATAL_FAILURE(
EXPECT_SYSTEM_ERROR(throw_system_error(), EDOM, "other")
- << "expected failure", "expected failure");
+ << "expected failure",
+ "expected failure");
}
TEST(StreamingAssertionsTest, EXPECT_WRITE) {
- EXPECT_WRITE(stdout, std::printf("test"), "test")
- << "unexpected failure";
- EXPECT_NONFATAL_FAILURE(
- EXPECT_WRITE(stdout, std::printf("test"), "other")
- << "expected failure", "expected failure");
+ EXPECT_WRITE(stdout, std::printf("test"), "test") << "unexpected failure";
+ EXPECT_NONFATAL_FAILURE(EXPECT_WRITE(stdout, std::printf("test"), "other")
+ << "expected failure",
+ "expected failure");
}
TEST(UtilTest, FormatSystemError) {
@@ -340,10 +357,10 @@
// Put a character in a file buffer.
EXPECT_EQ('x', fputc('x', f.get()));
FMT_POSIX(close(write_fd));
- scoped_ptr<OutputRedirect> redir{FMT_NULL};
- EXPECT_SYSTEM_ERROR_NOASSERT(redir.reset(new OutputRedirect(f.get())),
- EBADF, "cannot flush stream");
- redir.reset(FMT_NULL);
+ std::unique_ptr<OutputRedirect> redir{nullptr};
+ EXPECT_SYSTEM_ERROR_NOASSERT(redir.reset(new OutputRedirect(f.get())), EBADF,
+ "cannot flush stream");
+ redir.reset(nullptr);
write_copy.dup2(write_fd); // "undo" close or dtor will fail
}
@@ -352,9 +369,10 @@
int fd = (f.fileno)();
file copy = file::dup(fd);
FMT_POSIX(close(fd));
- scoped_ptr<OutputRedirect> redir{FMT_NULL};
- EXPECT_SYSTEM_ERROR_NOASSERT(redir.reset(new OutputRedirect(f.get())),
- EBADF, fmt::format("cannot duplicate file descriptor {}", fd));
+ std::unique_ptr<OutputRedirect> redir{nullptr};
+ EXPECT_SYSTEM_ERROR_NOASSERT(
+ redir.reset(new OutputRedirect(f.get())), EBADF,
+ fmt::format("cannot duplicate file descriptor {}", fd));
copy.dup2(fd); // "undo" close or dtor will fail
}
@@ -383,8 +401,8 @@
// Put a character in a file buffer.
EXPECT_EQ('x', fputc('x', f.get()));
FMT_POSIX(close(write_fd));
- EXPECT_SYSTEM_ERROR_NOASSERT(redir.restore_and_read(),
- EBADF, "cannot flush stream");
+ EXPECT_SYSTEM_ERROR_NOASSERT(redir.restore_and_read(), EBADF,
+ "cannot flush stream");
write_copy.dup2(write_fd); // "undo" close or dtor will fail
}
@@ -394,18 +412,20 @@
int write_fd = write_end.descriptor();
file write_copy = write_end.dup(write_fd);
buffered_file f = write_end.fdopen("w");
- scoped_ptr<OutputRedirect> redir(new OutputRedirect(f.get()));
+ std::unique_ptr<OutputRedirect> redir(new OutputRedirect(f.get()));
// Put a character in a file buffer.
EXPECT_EQ('x', fputc('x', f.get()));
- EXPECT_WRITE(stderr, {
- // The close function must be called inside EXPECT_WRITE, otherwise
- // the system may recycle closed file descriptor when redirecting the
- // output in EXPECT_STDERR and the second close will break output
- // redirection.
- FMT_POSIX(close(write_fd));
- SUPPRESS_ASSERT(redir.reset(FMT_NULL));
- }, format_system_error(EBADF, "cannot flush stream"));
- write_copy.dup2(write_fd); // "undo" close or dtor of buffered_file will fail
+ EXPECT_WRITE(stderr,
+ {
+ // The close function must be called inside EXPECT_WRITE,
+ // otherwise the system may recycle closed file descriptor when
+ // redirecting the output in EXPECT_STDERR and the second close
+ // will break output redirection.
+ FMT_POSIX(close(write_fd));
+ SUPPRESS_ASSERT(redir.reset(nullptr));
+ },
+ format_system_error(EBADF, "cannot flush stream"));
+ write_copy.dup2(write_fd); // "undo" close or dtor of buffered_file will fail
}
#endif // FMT_USE_FILE_DESCRIPTORS
diff --git a/test/gtest-extra.cc b/test/gtest-extra.cc
index 2e5ea3e..ae89e71 100644
--- a/test/gtest-extra.cc
+++ b/test/gtest-extra.cc
@@ -12,25 +12,23 @@
using fmt::file;
void OutputRedirect::flush() {
-#if EOF != -1
-# error "FMT_RETRY assumes return value of -1 indicating failure"
-#endif
+# if EOF != -1
+# error "FMT_RETRY assumes return value of -1 indicating failure"
+# endif
int result = 0;
FMT_RETRY(result, fflush(file_));
- if (result != 0)
- throw fmt::system_error(errno, "cannot flush stream");
+ if (result != 0) throw fmt::system_error(errno, "cannot flush stream");
}
void OutputRedirect::restore() {
- if (original_.descriptor() == -1)
- return; // Already restored.
+ if (original_.descriptor() == -1) return; // Already restored.
flush();
// Restore the original file.
original_.dup2(FMT_POSIX(fileno(file_)));
original_.close();
}
-OutputRedirect::OutputRedirect(FILE *f) : file_(f) {
+OutputRedirect::OutputRedirect(FILE* f) : file_(f) {
flush();
int fd = FMT_POSIX(fileno(f));
// Create a file object referring to the original file.
@@ -45,7 +43,7 @@
OutputRedirect::~OutputRedirect() FMT_NOEXCEPT {
try {
restore();
- } catch (const std::exception &e) {
+ } catch (const std::exception& e) {
std::fputs(e.what(), stderr);
}
}
@@ -56,8 +54,7 @@
// Read everything from the pipe.
std::string content;
- if (read_end_.descriptor() == -1)
- return content; // Already read.
+ if (read_end_.descriptor() == -1) return content; // Already read.
enum { BUFFER_SIZE = 4096 };
char buffer[BUFFER_SIZE];
std::size_t count = 0;
@@ -69,7 +66,7 @@
return content;
}
-std::string read(file &f, std::size_t count) {
+std::string read(file& f, std::size_t count) {
std::string buffer(count, '\0');
std::size_t n = 0, offset = 0;
do {
diff --git a/test/gtest-extra.h b/test/gtest-extra.h
index 61e262e..4a69336 100644
--- a/test/gtest-extra.h
+++ b/test/gtest-extra.h
@@ -14,58 +14,56 @@
#include "fmt/core.h"
#ifndef FMT_USE_FILE_DESCRIPTORS
-# define FMT_USE_FILE_DESCRIPTORS 0
+# define FMT_USE_FILE_DESCRIPTORS 0
#endif
#if FMT_USE_FILE_DESCRIPTORS
-# include "fmt/posix.h"
+# include "fmt/posix.h"
#endif
#define FMT_TEST_THROW_(statement, expected_exception, expected_message, fail) \
- GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
- if (::testing::AssertionResult gtest_ar = ::testing::AssertionSuccess()) { \
- std::string gtest_expected_message = expected_message; \
- bool gtest_caught_expected = false; \
- try { \
- GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \
- } \
- catch (expected_exception const& e) { \
- if (gtest_expected_message != e.what()) { \
- gtest_ar \
- << #statement " throws an exception with a different message.\n" \
- << "Expected: " << gtest_expected_message << "\n" \
- << " Actual: " << e.what(); \
- goto GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__); \
- } \
- gtest_caught_expected = true; \
- } \
- catch (...) { \
- gtest_ar << \
- "Expected: " #statement " throws an exception of type " \
- #expected_exception ".\n Actual: it throws a different type."; \
- goto GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__); \
- } \
- if (!gtest_caught_expected) { \
- gtest_ar << \
- "Expected: " #statement " throws an exception of type " \
- #expected_exception ".\n Actual: it throws nothing."; \
- goto GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__); \
- } \
- } else \
- GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__): \
- fail(gtest_ar.failure_message())
+ GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
+ if (::testing::AssertionResult gtest_ar = ::testing::AssertionSuccess()) { \
+ std::string gtest_expected_message = expected_message; \
+ bool gtest_caught_expected = false; \
+ try { \
+ GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \
+ } catch (expected_exception const& e) { \
+ if (gtest_expected_message != e.what()) { \
+ gtest_ar << #statement \
+ " throws an exception with a different message.\n" \
+ << "Expected: " << gtest_expected_message << "\n" \
+ << " Actual: " << e.what(); \
+ goto GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__); \
+ } \
+ gtest_caught_expected = true; \
+ } catch (...) { \
+ gtest_ar << "Expected: " #statement \
+ " throws an exception of type " #expected_exception \
+ ".\n Actual: it throws a different type."; \
+ goto GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__); \
+ } \
+ if (!gtest_caught_expected) { \
+ gtest_ar << "Expected: " #statement \
+ " throws an exception of type " #expected_exception \
+ ".\n Actual: it throws nothing."; \
+ goto GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__); \
+ } \
+ } else \
+ GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__) \
+ : fail(gtest_ar.failure_message())
// Tests that the statement throws the expected exception and the exception's
// what() method returns expected message.
#define EXPECT_THROW_MSG(statement, expected_exception, expected_message) \
- FMT_TEST_THROW_(statement, expected_exception, \
- expected_message, GTEST_NONFATAL_FAILURE_)
+ FMT_TEST_THROW_(statement, expected_exception, expected_message, \
+ GTEST_NONFATAL_FAILURE_)
std::string format_system_error(int error_code, fmt::string_view message);
#define EXPECT_SYSTEM_ERROR(statement, error_code, message) \
- EXPECT_THROW_MSG(statement, fmt::system_error, \
- format_system_error(error_code, message))
+ EXPECT_THROW_MSG(statement, fmt::system_error, \
+ format_system_error(error_code, message))
#if FMT_USE_FILE_DESCRIPTORS
@@ -73,7 +71,7 @@
// The output it can handle is limited by the pipe capacity.
class OutputRedirect {
private:
- FILE *file_;
+ FILE* file_;
fmt::file original_; // Original file passed to redirector.
fmt::file read_end_; // Read end of the pipe where the output is redirected.
@@ -83,7 +81,7 @@
void restore();
public:
- explicit OutputRedirect(FILE *file);
+ explicit OutputRedirect(FILE* file);
~OutputRedirect() FMT_NOEXCEPT;
// Restores the original file, reads output from the pipe into a string
@@ -91,29 +89,28 @@
std::string restore_and_read();
};
-#define FMT_TEST_WRITE_(statement, expected_output, file, fail) \
- GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
- if (::testing::AssertionResult gtest_ar = ::testing::AssertionSuccess()) { \
- std::string gtest_expected_output = expected_output; \
- OutputRedirect gtest_redir(file); \
- GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \
- std::string gtest_output = gtest_redir.restore_and_read(); \
- if (gtest_output != gtest_expected_output) { \
- gtest_ar \
- << #statement " produces different output.\n" \
- << "Expected: " << gtest_expected_output << "\n" \
- << " Actual: " << gtest_output; \
- goto GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__); \
- } \
- } else \
- GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__): \
- fail(gtest_ar.failure_message())
+# define FMT_TEST_WRITE_(statement, expected_output, file, fail) \
+ GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
+ if (::testing::AssertionResult gtest_ar = ::testing::AssertionSuccess()) { \
+ std::string gtest_expected_output = expected_output; \
+ OutputRedirect gtest_redir(file); \
+ GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \
+ std::string gtest_output = gtest_redir.restore_and_read(); \
+ if (gtest_output != gtest_expected_output) { \
+ gtest_ar << #statement " produces different output.\n" \
+ << "Expected: " << gtest_expected_output << "\n" \
+ << " Actual: " << gtest_output; \
+ goto GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__); \
+ } \
+ } else \
+ GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__) \
+ : fail(gtest_ar.failure_message())
// Tests that the statement writes the expected output to file.
-#define EXPECT_WRITE(file, statement, expected_output) \
+# define EXPECT_WRITE(file, statement, expected_output) \
FMT_TEST_WRITE_(statement, expected_output, file, GTEST_NONFATAL_FAILURE_)
-#ifdef _MSC_VER
+# ifdef _MSC_VER
// Suppresses Windows assertions on invalid file descriptors, making
// POSIX functions return proper error codes instead of crashing on Windows.
@@ -122,40 +119,43 @@
_invalid_parameter_handler original_handler_;
int original_report_mode_;
- static void handle_invalid_parameter(const wchar_t *,
- const wchar_t *, const wchar_t *, unsigned , uintptr_t) {}
+ static void handle_invalid_parameter(const wchar_t*, const wchar_t*,
+ const wchar_t*, unsigned, uintptr_t) {}
public:
SuppressAssert()
- : original_handler_(_set_invalid_parameter_handler(handle_invalid_parameter)),
- original_report_mode_(_CrtSetReportMode(_CRT_ASSERT, 0)) {
- }
+ : original_handler_(
+ _set_invalid_parameter_handler(handle_invalid_parameter)),
+ original_report_mode_(_CrtSetReportMode(_CRT_ASSERT, 0)) {}
~SuppressAssert() {
_set_invalid_parameter_handler(original_handler_);
_CrtSetReportMode(_CRT_ASSERT, original_report_mode_);
}
};
-# define SUPPRESS_ASSERT(statement) { SuppressAssert sa; statement; }
-#else
-# define SUPPRESS_ASSERT(statement) statement
-#endif // _MSC_VER
+# define SUPPRESS_ASSERT(statement) \
+ { \
+ SuppressAssert sa; \
+ statement; \
+ }
+# else
+# define SUPPRESS_ASSERT(statement) statement
+# endif // _MSC_VER
-#define EXPECT_SYSTEM_ERROR_NOASSERT(statement, error_code, message) \
- EXPECT_SYSTEM_ERROR(SUPPRESS_ASSERT(statement), error_code, message)
+# define EXPECT_SYSTEM_ERROR_NOASSERT(statement, error_code, message) \
+ EXPECT_SYSTEM_ERROR(SUPPRESS_ASSERT(statement), error_code, message)
// Attempts to read count characters from a file.
-std::string read(fmt::file &f, std::size_t count);
+std::string read(fmt::file& f, std::size_t count);
-#define EXPECT_READ(file, expected_content) \
- EXPECT_EQ(expected_content, read(file, std::strlen(expected_content)))
+# define EXPECT_READ(file, expected_content) \
+ EXPECT_EQ(expected_content, read(file, std::strlen(expected_content)))
#endif // FMT_USE_FILE_DESCRIPTORS
-template <typename Mock>
-struct ScopedMock : testing::StrictMock<Mock> {
+template <typename Mock> struct ScopedMock : testing::StrictMock<Mock> {
ScopedMock() { Mock::instance = this; }
- ~ScopedMock() { Mock::instance = FMT_NULL; }
+ ~ScopedMock() { Mock::instance = nullptr; }
};
#endif // FMT_GTEST_EXTRA_H_
diff --git a/test/locale-test.cc b/test/locale-test.cc
index 83b0f31..37d4687 100644
--- a/test/locale-test.cc
+++ b/test/locale-test.cc
@@ -8,12 +8,25 @@
#include "fmt/locale.h"
#include "gmock.h"
-template <typename Char>
-struct numpunct : std::numpunct<Char> {
+#ifndef FMT_STATIC_THOUSANDS_SEPARATOR
+template <typename Char> struct numpunct : std::numpunct<Char> {
protected:
+ Char do_decimal_point() const FMT_OVERRIDE { return '?'; }
Char do_thousands_sep() const FMT_OVERRIDE { return '~'; }
};
+TEST(LocaleTest, DoubleDecimalPoint) {
+ std::locale loc(std::locale(), new numpunct<char>());
+ EXPECT_EQ("1?23", fmt::format(loc, "{:n}", 1.23));
+ // Test with Grisu disabled.
+ fmt::memory_buffer buf;
+ fmt::internal::writer w(buf, fmt::internal::locale_ref(loc));
+ auto specs = fmt::format_specs();
+ specs.type = 'n';
+ w.write_double<double, false>(1.23, specs);
+ EXPECT_EQ(fmt::to_string(buf), "1?23");
+}
+
TEST(LocaleTest, Format) {
std::locale loc(std::locale(), new numpunct<char>());
EXPECT_EQ("1,234,567", fmt::format(std::locale(), "{:n}", 1234567));
@@ -31,4 +44,9 @@
EXPECT_EQ(L"1~234~567", fmt::format(loc, L"{:n}", 1234567));
fmt::format_arg_store<fmt::wformat_context, int> as{1234567};
EXPECT_EQ(L"1~234~567", fmt::vformat(loc, L"{:n}", fmt::wformat_args(as)));
+ auto sep =
+ std::use_facet<std::numpunct<wchar_t>>(std::locale("C")).thousands_sep();
+ auto result = sep == ',' ? L"1,234,567" : L"1234567";
+ EXPECT_EQ(result, fmt::format(std::locale("C"), L"{:n}", 1234567));
}
+#endif // FMT_STATIC_THOUSANDS_SEPARATOR
diff --git a/test/mock-allocator.h b/test/mock-allocator.h
index 65ee6ab..1dd2dad 100644
--- a/test/mock-allocator.h
+++ b/test/mock-allocator.h
@@ -8,53 +8,51 @@
#ifndef FMT_MOCK_ALLOCATOR_H_
#define FMT_MOCK_ALLOCATOR_H_
-#include "gmock.h"
#include "fmt/format.h"
+#include "gmock.h"
-template <typename T>
-class mock_allocator {
+template <typename T> class mock_allocator {
public:
mock_allocator() {}
- mock_allocator(const mock_allocator &) {}
+ mock_allocator(const mock_allocator&) {}
typedef T value_type;
- MOCK_METHOD1_T(allocate, T* (std::size_t n));
- MOCK_METHOD2_T(deallocate, void (T* p, std::size_t n));
+ MOCK_METHOD1_T(allocate, T*(std::size_t n));
+ MOCK_METHOD2_T(deallocate, void(T* p, std::size_t n));
};
-template <typename Allocator>
-class allocator_ref {
+template <typename Allocator> class allocator_ref {
private:
- Allocator *alloc_;
+ Allocator* alloc_;
- void move(allocator_ref &other) {
+ void move(allocator_ref& other) {
alloc_ = other.alloc_;
- other.alloc_ = FMT_NULL;
+ other.alloc_ = nullptr;
}
public:
typedef typename Allocator::value_type value_type;
- explicit allocator_ref(Allocator *alloc = FMT_NULL) : alloc_(alloc) {}
+ explicit allocator_ref(Allocator* alloc = nullptr) : alloc_(alloc) {}
- allocator_ref(const allocator_ref &other) : alloc_(other.alloc_) {}
- allocator_ref(allocator_ref &&other) { move(other); }
+ allocator_ref(const allocator_ref& other) : alloc_(other.alloc_) {}
+ allocator_ref(allocator_ref&& other) { move(other); }
- allocator_ref& operator=(allocator_ref &&other) {
+ allocator_ref& operator=(allocator_ref&& other) {
assert(this != &other);
move(other);
return *this;
}
- allocator_ref& operator=(const allocator_ref &other) {
+ allocator_ref& operator=(const allocator_ref& other) {
alloc_ = other.alloc_;
return *this;
}
public:
- Allocator *get() const { return alloc_; }
+ Allocator* get() const { return alloc_; }
value_type* allocate(std::size_t n) {
- return fmt::internal::allocate(*alloc_, n);
+ return std::allocator_traits<Allocator>::allocate(*alloc_, n);
}
void deallocate(value_type* p, std::size_t n) { alloc_->deallocate(p, n); }
};
diff --git a/test/ostream-test.cc b/test/ostream-test.cc
index b93fedc..fb88ad4 100644
--- a/test/ostream-test.cc
+++ b/test/ostream-test.cc
@@ -6,6 +6,21 @@
// For the license information refer to format.h.
#define FMT_STRING_ALIAS 1
+#include "fmt/format.h"
+
+struct test {};
+
+// Test that there is no issues with specializations when fmt/ostream.h is
+// included after fmt/format.h.
+namespace fmt {
+template <> struct formatter<test> : formatter<int> {
+ template <typename FormatContext>
+ typename FormatContext::iterator format(const test&, FormatContext& ctx) {
+ return formatter<int>::format(42, ctx);
+ }
+};
+} // namespace fmt
+
#include "fmt/ostream.h"
#include <sstream>
@@ -16,51 +31,56 @@
using fmt::format;
using fmt::format_error;
-static std::ostream &operator<<(std::ostream &os, const Date &d) {
+static std::ostream& operator<<(std::ostream& os, const Date& d) {
os << d.year() << '-' << d.month() << '-' << d.day();
return os;
}
-static std::wostream &operator<<(std::wostream &os, const Date &d) {
+static std::wostream& operator<<(std::wostream& os, const Date& d) {
os << d.year() << L'-' << d.month() << L'-' << d.day();
return os;
}
-enum TestEnum {};
-static std::ostream &operator<<(std::ostream &os, TestEnum) {
- return os << "TestEnum";
+// Make sure that overloaded comma operators do no harm to is_streamable.
+struct type_with_comma_op {};
+template <typename T> void operator,(type_with_comma_op, const T&);
+template <typename T> type_with_comma_op operator<<(T&, const Date&);
+
+enum streamable_enum {};
+static std::ostream& operator<<(std::ostream& os, streamable_enum) {
+ return os << "streamable_enum";
}
-static std::wostream &operator<<(std::wostream &os, TestEnum) {
- return os << L"TestEnum";
+static std::wostream& operator<<(std::wostream& os, streamable_enum) {
+ return os << L"streamable_enum";
}
-enum TestEnum2 {A};
+enum unstreamable_enum {};
TEST(OStreamTest, Enum) {
- EXPECT_FALSE((fmt::convert_to_int<TestEnum, char>::value));
- EXPECT_EQ("TestEnum", fmt::format("{}", TestEnum()));
- EXPECT_EQ("0", fmt::format("{}", A));
- EXPECT_FALSE((fmt::convert_to_int<TestEnum, wchar_t>::value));
- EXPECT_EQ(L"TestEnum", fmt::format(L"{}", TestEnum()));
- EXPECT_EQ(L"0", fmt::format(L"{}", A));
+ EXPECT_EQ("streamable_enum", fmt::format("{}", streamable_enum()));
+ EXPECT_EQ("0", fmt::format("{}", unstreamable_enum()));
+ EXPECT_EQ(L"streamable_enum", fmt::format(L"{}", streamable_enum()));
+ EXPECT_EQ(L"0", fmt::format(L"{}", unstreamable_enum()));
}
-typedef fmt::back_insert_range<fmt::internal::buffer> range;
+using range = fmt::internal::buffer_range<char>;
-struct test_arg_formatter: fmt::arg_formatter<range> {
- test_arg_formatter(fmt::format_context &ctx, fmt::format_specs &s)
- : fmt::arg_formatter<range>(ctx, &s) {}
+struct test_arg_formatter : fmt::arg_formatter<range> {
+ fmt::format_parse_context parse_ctx;
+ test_arg_formatter(fmt::format_context& ctx, fmt::format_specs& s)
+ : fmt::arg_formatter<range>(ctx, &parse_ctx, &s), parse_ctx("") {}
};
TEST(OStreamTest, CustomArg) {
fmt::memory_buffer buffer;
- fmt::internal::buffer &base = buffer;
- fmt::format_context ctx(std::back_inserter(base), "", fmt::format_args());
+ fmt::internal::buffer<char>& base = buffer;
+ fmt::format_context ctx(std::back_inserter(base), fmt::format_args());
fmt::format_specs spec;
test_arg_formatter af(ctx, spec);
- visit(af, fmt::internal::make_arg<fmt::format_context>(TestEnum()));
- EXPECT_EQ("TestEnum", std::string(buffer.data(), buffer.size()));
+ fmt::visit_format_arg(
+ af, fmt::internal::make_arg<fmt::format_context>(streamable_enum()));
+ EXPECT_EQ("streamable_enum", std::string(buffer.data(), buffer.size()));
}
TEST(OStreamTest, Format) {
@@ -75,20 +95,20 @@
TEST(OStreamTest, FormatSpecs) {
EXPECT_EQ("def ", format("{0:<5}", TestString("def")));
EXPECT_EQ(" def", format("{0:>5}", TestString("def")));
- EXPECT_THROW_MSG(format("{0:=5}", TestString("def")),
- format_error, "format specifier requires numeric argument");
+ EXPECT_THROW_MSG(format("{0:=5}", TestString("def")), format_error,
+ "format specifier requires numeric argument");
EXPECT_EQ(" def ", format("{0:^5}", TestString("def")));
EXPECT_EQ("def**", format("{0:*<5}", TestString("def")));
- EXPECT_THROW_MSG(format("{0:+}", TestString()),
- format_error, "format specifier requires numeric argument");
- EXPECT_THROW_MSG(format("{0:-}", TestString()),
- format_error, "format specifier requires numeric argument");
- EXPECT_THROW_MSG(format("{0: }", TestString()),
- format_error, "format specifier requires numeric argument");
- EXPECT_THROW_MSG(format("{0:#}", TestString()),
- format_error, "format specifier requires numeric argument");
- EXPECT_THROW_MSG(format("{0:05}", TestString()),
- format_error, "format specifier requires numeric argument");
+ EXPECT_THROW_MSG(format("{0:+}", TestString()), format_error,
+ "format specifier requires numeric argument");
+ EXPECT_THROW_MSG(format("{0:-}", TestString()), format_error,
+ "format specifier requires numeric argument");
+ EXPECT_THROW_MSG(format("{0: }", TestString()), format_error,
+ "format specifier requires numeric argument");
+ EXPECT_THROW_MSG(format("{0:#}", TestString()), format_error,
+ "format specifier requires numeric argument");
+ EXPECT_THROW_MSG(format("{0:05}", TestString()), format_error,
+ "format specifier requires numeric argument");
EXPECT_EQ("test ", format("{0:13}", TestString("test")));
EXPECT_EQ("test ", format("{0:{1}}", TestString("test"), 13));
EXPECT_EQ("te", format("{0:.2}", TestString("test")));
@@ -96,7 +116,7 @@
}
struct EmptyTest {};
-static std::ostream &operator<<(std::ostream &os, EmptyTest) {
+static std::ostream& operator<<(std::ostream& os, EmptyTest) {
return os << "";
}
@@ -116,7 +136,7 @@
TEST(OStreamTest, WriteToOStream) {
std::ostringstream os;
fmt::memory_buffer buffer;
- const char *foo = "foo";
+ const char* foo = "foo";
buffer.append(foo, foo + std::strlen(foo));
fmt::internal::write(os, buffer);
EXPECT_EQ("foo", os.str());
@@ -125,28 +145,27 @@
TEST(OStreamTest, WriteToOStreamMaxSize) {
std::size_t max_size = std::numeric_limits<std::size_t>::max();
std::streamsize max_streamsize = std::numeric_limits<std::streamsize>::max();
- if (max_size <= fmt::internal::to_unsigned(max_streamsize))
- return;
+ if (max_size <= fmt::internal::to_unsigned(max_streamsize)) return;
- struct test_buffer : fmt::internal::buffer {
+ struct test_buffer : fmt::internal::buffer<char> {
explicit test_buffer(std::size_t size) { resize(size); }
void grow(std::size_t) {}
} buffer(max_size);
struct mock_streambuf : std::streambuf {
- MOCK_METHOD2(xsputn, std::streamsize (const void *s, std::streamsize n));
- std::streamsize xsputn(const char *s, std::streamsize n) {
- const void *v = s;
+ MOCK_METHOD2(xsputn, std::streamsize(const void* s, std::streamsize n));
+ std::streamsize xsputn(const char* s, std::streamsize n) {
+ const void* v = s;
return xsputn(v, n);
}
} streambuf;
struct test_ostream : std::ostream {
- explicit test_ostream(mock_streambuf &buffer) : std::ostream(&buffer) {}
+ explicit test_ostream(mock_streambuf& buffer) : std::ostream(&buffer) {}
} os(streambuf);
testing::InSequence sequence;
- const char *data = FMT_NULL;
+ const char* data = nullptr;
typedef std::make_unsigned<std::streamsize>::type ustreamsize;
ustreamsize size = max_size;
do {
@@ -167,17 +186,39 @@
#if FMT_USE_CONSTEXPR
TEST(OStreamTest, ConstexprString) {
EXPECT_EQ("42", format(fmt("{}"), std::string("42")));
+ EXPECT_EQ("a string", format(fmt("{0}"), TestString("a string")));
}
#endif
namespace fmt_test {
struct ABC {};
-template <typename Output> Output &operator<<(Output &out, ABC) {
+template <typename Output> Output& operator<<(Output& out, ABC) {
out << "ABC";
return out;
}
-} // namespace fmt_test
+} // namespace fmt_test
+
+template <typename T> struct TestTemplate {};
+
+template <typename T>
+std::ostream& operator<<(std::ostream& os, TestTemplate<T>) {
+ return os << 1;
+}
+
+namespace fmt {
+template <typename T> struct formatter<TestTemplate<T>> : formatter<int> {
+ template <typename FormatContext>
+ typename FormatContext::iterator format(TestTemplate<T>, FormatContext& ctx) {
+ return formatter<int>::format(2, ctx);
+ }
+};
+} // namespace fmt
+
+#if !FMT_GCC_VERSION || FMT_GCC_VERSION >= 407
+TEST(OStreamTest, Template) {
+ EXPECT_EQ("2", fmt::format("{}", TestTemplate<int>()));
+}
TEST(FormatTest, FormatToN) {
char buffer[4];
@@ -191,6 +232,7 @@
EXPECT_EQ(buffer + 3, result.out);
EXPECT_EQ("xABx", fmt::string_view(buffer, 4));
}
+#endif
#if FMT_USE_USER_DEFINED_LITERALS
TEST(FormatTest, UDL) {
diff --git a/test/posix-mock-test.cc b/test/posix-mock-test.cc
index 8b0e14e..58e015a 100644
--- a/test/posix-mock-test.cc
+++ b/test/posix-mock-test.cc
@@ -6,8 +6,8 @@
// For the license information refer to format.h.
// Disable bogus MSVC warnings.
-#ifdef _MSC_VER
-# define _CRT_SECURE_NO_WARNINGS
+#ifndef _CRT_SECURE_NO_WARNINGS
+# define _CRT_SECURE_NO_WARNINGS
#endif
#include "posix-mock.h"
@@ -16,11 +16,12 @@
#include <errno.h>
#include <fcntl.h>
#include <climits>
+#include <memory>
#ifdef _WIN32
-# include <io.h>
-# undef max
-# undef ERROR
+# include <io.h>
+# undef max
+# undef ERROR
#endif
#include "gmock.h"
@@ -31,10 +32,9 @@
using fmt::error_code;
using fmt::file;
-using testing::internal::scoped_ptr;
using testing::_;
-using testing::StrEq;
using testing::Return;
+using testing::StrEq;
namespace {
int open_count;
@@ -53,24 +53,24 @@
bool sysconf_error;
enum FStatSimulation { NONE, MAX_SIZE, ERROR } fstat_sim;
-}
+} // namespace
#define EMULATE_EINTR(func, error_result) \
- if (func##_count != 0) { \
- if (func##_count++ != 3) { \
- errno = EINTR; \
- return error_result; \
- } \
+ if (func##_count != 0) { \
+ if (func##_count++ != 3) { \
+ errno = EINTR; \
+ return error_result; \
+ } \
}
#ifndef _MSC_VER
-int test::open(const char *path, int oflag, int mode) {
+int test::open(const char* path, int oflag, int mode) {
EMULATE_EINTR(open, -1);
return ::open(path, oflag, mode);
}
#else
-errno_t test::sopen_s(
- int* pfh, const char *filename, int oflag, int shflag, int pmode) {
+errno_t test::sopen_s(int* pfh, const char* filename, int oflag, int shflag,
+ int pmode) {
EMULATE_EINTR(open, EINTR);
return _sopen_s(pfh, filename, oflag, shflag, pmode);
}
@@ -80,8 +80,7 @@
long test::sysconf(int name) {
long result = ::sysconf(name);
- if (!sysconf_error)
- return result;
+ if (!sysconf_error) return result;
// Simulate an error.
errno = EINVAL;
return -1;
@@ -89,10 +88,9 @@
static off_t max_file_size() { return std::numeric_limits<off_t>::max(); }
-int test::fstat(int fd, struct stat *buf) {
+int test::fstat(int fd, struct stat* buf) {
int result = ::fstat(fd, buf);
- if (fstat_sim == MAX_SIZE)
- buf->st_size = max_file_size();
+ if (fstat_sim == MAX_SIZE) buf->st_size = max_file_size();
return result;
}
@@ -132,18 +130,18 @@
return ::FMT_POSIX(dup2(fildes, fildes2));
}
-FILE *test::fdopen(int fildes, const char *mode) {
- EMULATE_EINTR(fdopen, FMT_NULL);
+FILE* test::fdopen(int fildes, const char* mode) {
+ EMULATE_EINTR(fdopen, nullptr);
return ::FMT_POSIX(fdopen(fildes, mode));
}
-test::ssize_t test::read(int fildes, void *buf, test::size_t nbyte) {
+test::ssize_t test::read(int fildes, void* buf, test::size_t nbyte) {
read_nbyte = nbyte;
EMULATE_EINTR(read, -1);
return ::FMT_POSIX(read(fildes, buf, nbyte));
}
-test::ssize_t test::write(int fildes, const void *buf, test::size_t nbyte) {
+test::ssize_t test::write(int fildes, const void* buf, test::size_t nbyte) {
write_nbyte = nbyte;
EMULATE_EINTR(write, -1);
return ::FMT_POSIX(write(fildes, buf, nbyte));
@@ -155,23 +153,23 @@
return ::pipe(fildes);
}
#else
-int test::pipe(int *pfds, unsigned psize, int textmode) {
+int test::pipe(int* pfds, unsigned psize, int textmode) {
EMULATE_EINTR(pipe, -1);
return _pipe(pfds, psize, textmode);
}
#endif
-FILE *test::fopen(const char *filename, const char *mode) {
- EMULATE_EINTR(fopen, FMT_NULL);
+FILE* test::fopen(const char* filename, const char* mode) {
+ EMULATE_EINTR(fopen, nullptr);
return ::fopen(filename, mode);
}
-int test::fclose(FILE *stream) {
+int test::fclose(FILE* stream) {
EMULATE_EINTR(fclose, EOF);
return ::fclose(stream);
}
-int (test::fileno)(FILE *stream) {
+int(test::fileno)(FILE* stream) {
EMULATE_EINTR(fileno, -1);
#ifdef fileno
return FMT_POSIX(fileno(stream));
@@ -181,18 +179,18 @@
}
#ifndef _WIN32
-# define EXPECT_RETRY(statement, func, message) \
- func##_count = 1; \
- statement; \
- EXPECT_EQ(4, func##_count); \
+# define EXPECT_RETRY(statement, func, message) \
+ func##_count = 1; \
+ statement; \
+ EXPECT_EQ(4, func##_count); \
func##_count = 0;
-# define EXPECT_EQ_POSIX(expected, actual) EXPECT_EQ(expected, actual)
+# define EXPECT_EQ_POSIX(expected, actual) EXPECT_EQ(expected, actual)
#else
-# define EXPECT_RETRY(statement, func, message) \
- func##_count = 1; \
+# define EXPECT_RETRY(statement, func, message) \
+ func##_count = 1; \
EXPECT_SYSTEM_ERROR(statement, EINTR, message); \
func##_count = 0;
-# define EXPECT_EQ_POSIX(expected, actual)
+# define EXPECT_EQ_POSIX(expected, actual)
#endif
static void write_file(fmt::cstring_view filename, fmt::string_view content) {
@@ -208,17 +206,17 @@
#else
EXPECT_EQ(sysconf(_SC_PAGESIZE), fmt::getpagesize());
sysconf_error = true;
- EXPECT_SYSTEM_ERROR(
- fmt::getpagesize(), EINVAL, "cannot get memory page size");
+ EXPECT_SYSTEM_ERROR(fmt::getpagesize(), EINVAL,
+ "cannot get memory page size");
sysconf_error = false;
#endif
}
TEST(FileTest, OpenRetry) {
write_file("test", "there must be something here");
- scoped_ptr<file> f{FMT_NULL};
- EXPECT_RETRY(f.reset(new file("test", file::RDONLY)),
- open, "cannot open file test");
+ std::unique_ptr<file> f{nullptr};
+ EXPECT_RETRY(f.reset(new file("test", file::RDONLY)), open,
+ "cannot open file test");
#ifndef _WIN32
char c = 0;
f->read(&c, 1);
@@ -228,14 +226,16 @@
TEST(FileTest, CloseNoRetryInDtor) {
file read_end, write_end;
file::pipe(read_end, write_end);
- scoped_ptr<file> f(new file(std::move(read_end)));
+ std::unique_ptr<file> f(new file(std::move(read_end)));
int saved_close_count = 0;
- EXPECT_WRITE(stderr, {
- close_count = 1;
- f.reset(FMT_NULL);
- saved_close_count = close_count;
- close_count = 0;
- }, format_system_error(EINTR, "cannot close file") + "\n");
+ EXPECT_WRITE(stderr,
+ {
+ close_count = 1;
+ f.reset(nullptr);
+ saved_close_count = close_count;
+ close_count = 0;
+ },
+ format_system_error(EINTR, "cannot close file") + "\n");
EXPECT_EQ(2, saved_close_count);
}
@@ -256,8 +256,8 @@
EXPECT_EQ(content.size(), static_cast<unsigned long long>(f.size()));
#ifdef _WIN32
fmt::memory_buffer message;
- fmt::internal::format_windows_error(
- message, ERROR_ACCESS_DENIED, "cannot get file size");
+ fmt::internal::format_windows_error(message, ERROR_ACCESS_DENIED,
+ "cannot get file size");
fstat_sim = ERROR;
EXPECT_THROW_MSG(f.size(), fmt::windows_error, fmt::to_string(message));
fstat_sim = NONE;
@@ -284,8 +284,8 @@
write_end.close();
char buffer[SIZE];
std::size_t count = 0;
- EXPECT_RETRY(count = read_end.read(buffer, SIZE),
- read, "cannot read from file");
+ EXPECT_RETRY(count = read_end.read(buffer, SIZE), read,
+ "cannot read from file");
EXPECT_EQ_POSIX(static_cast<std::streamsize>(SIZE), count);
}
@@ -294,8 +294,8 @@
file::pipe(read_end, write_end);
enum { SIZE = 4 };
std::size_t count = 0;
- EXPECT_RETRY(count = write_end.write("test", SIZE),
- write, "cannot write to file");
+ EXPECT_RETRY(count = write_end.write("test", SIZE), write,
+ "cannot write to file");
write_end.close();
#ifndef _WIN32
EXPECT_EQ(static_cast<std::streamsize>(SIZE), count);
@@ -312,8 +312,7 @@
file::pipe(read_end, write_end);
char c;
std::size_t size = UINT_MAX;
- if (sizeof(unsigned) != sizeof(std::size_t))
- ++size;
+ if (sizeof(unsigned) != sizeof(std::size_t)) ++size;
read_count = 1;
read_nbyte = 0;
EXPECT_THROW(read_end.read(&c, size), fmt::system_error);
@@ -326,8 +325,7 @@
file::pipe(read_end, write_end);
char c;
std::size_t size = UINT_MAX;
- if (sizeof(unsigned) != sizeof(std::size_t))
- ++size;
+ if (sizeof(unsigned) != sizeof(std::size_t)) ++size;
write_count = 1;
write_nbyte = 0;
EXPECT_THROW(write_end.write(&c, size), fmt::system_error);
@@ -339,7 +337,8 @@
TEST(FileTest, DupNoRetry) {
int stdout_fd = FMT_POSIX(fileno(stdout));
dup_count = 1;
- EXPECT_SYSTEM_ERROR(file::dup(stdout_fd), EINTR,
+ EXPECT_SYSTEM_ERROR(
+ file::dup(stdout_fd), EINTR,
fmt::format("cannot duplicate file descriptor {}", stdout_fd));
dup_count = 0;
}
@@ -348,8 +347,8 @@
int stdout_fd = FMT_POSIX(fileno(stdout));
file f1 = file::dup(stdout_fd), f2 = file::dup(stdout_fd);
EXPECT_RETRY(f1.dup2(f2.descriptor()), dup2,
- fmt::format("cannot duplicate file descriptor {} to {}",
- f1.descriptor(), f2.descriptor()));
+ fmt::format("cannot duplicate file descriptor {} to {}",
+ f1.descriptor(), f2.descriptor()));
}
TEST(FileTest, Dup2NoExceptRetry) {
@@ -369,8 +368,8 @@
TEST(FileTest, PipeNoRetry) {
file read_end, write_end;
pipe_count = 1;
- EXPECT_SYSTEM_ERROR(
- file::pipe(read_end, write_end), EINTR, "cannot create pipe");
+ EXPECT_SYSTEM_ERROR(file::pipe(read_end, write_end), EINTR,
+ "cannot create pipe");
pipe_count = 0;
}
@@ -378,16 +377,16 @@
file read_end, write_end;
file::pipe(read_end, write_end);
fdopen_count = 1;
- EXPECT_SYSTEM_ERROR(read_end.fdopen("r"),
- EINTR, "cannot associate stream with file descriptor");
+ EXPECT_SYSTEM_ERROR(read_end.fdopen("r"), EINTR,
+ "cannot associate stream with file descriptor");
fdopen_count = 0;
}
TEST(BufferedFileTest, OpenRetry) {
write_file("test", "there must be something here");
- scoped_ptr<buffered_file> f{FMT_NULL};
- EXPECT_RETRY(f.reset(new buffered_file("test", "r")),
- fopen, "cannot open file test");
+ std::unique_ptr<buffered_file> f{nullptr};
+ EXPECT_RETRY(f.reset(new buffered_file("test", "r")), fopen,
+ "cannot open file test");
#ifndef _WIN32
char c = 0;
if (fread(&c, 1, 1, f->get()) < 1)
@@ -398,14 +397,16 @@
TEST(BufferedFileTest, CloseNoRetryInDtor) {
file read_end, write_end;
file::pipe(read_end, write_end);
- scoped_ptr<buffered_file> f(new buffered_file(read_end.fdopen("r")));
+ std::unique_ptr<buffered_file> f(new buffered_file(read_end.fdopen("r")));
int saved_fclose_count = 0;
- EXPECT_WRITE(stderr, {
- fclose_count = 1;
- f.reset(FMT_NULL);
- saved_fclose_count = fclose_count;
- fclose_count = 0;
- }, format_system_error(EINTR, "cannot close file") + "\n");
+ EXPECT_WRITE(stderr,
+ {
+ fclose_count = 1;
+ f.reset(nullptr);
+ saved_fclose_count = fclose_count;
+ fclose_count = 0;
+ },
+ format_system_error(EINTR, "cannot close file") + "\n");
EXPECT_EQ(2, saved_fclose_count);
}
@@ -430,38 +431,42 @@
}
struct TestMock {
- static TestMock *instance;
-} *TestMock::instance;
+ static TestMock* instance;
+} * TestMock::instance;
TEST(ScopedMock, Scope) {
{
ScopedMock<TestMock> mock;
EXPECT_EQ(&mock, TestMock::instance);
- TestMock © = mock;
+ TestMock& copy = mock;
static_cast<void>(copy);
}
- EXPECT_EQ(FMT_NULL, TestMock::instance);
+ EXPECT_EQ(nullptr, TestMock::instance);
}
#ifdef FMT_LOCALE
-typedef fmt::Locale::Type LocaleType;
+typedef fmt::Locale::type LocaleType;
struct LocaleMock {
- static LocaleMock *instance;
- MOCK_METHOD3(newlocale, LocaleType (int category_mask, const char *locale,
- LocaleType base));
- MOCK_METHOD1(freelocale, void (LocaleType locale));
+ static LocaleMock* instance;
+ MOCK_METHOD3(newlocale, LocaleType(int category_mask, const char* locale,
+ LocaleType base));
+ MOCK_METHOD1(freelocale, void(LocaleType locale));
- MOCK_METHOD3(strtod_l, double (const char *nptr, char **endptr,
- LocaleType locale));
-} *LocaleMock::instance;
+ MOCK_METHOD3(strtod_l,
+ double(const char* nptr, char** endptr, LocaleType locale));
+} * LocaleMock::instance;
-#ifdef _MSC_VER
-# pragma warning(push)
-# pragma warning(disable: 4273)
+# ifdef _MSC_VER
+# pragma warning(push)
+# pragma warning(disable : 4273)
+# ifdef __clang__
+# pragma clang diagnostic push
+# pragma clang diagnostic ignored "-Winconsistent-dllimport"
+# endif
-_locale_t _create_locale(int category, const char *locale) {
+_locale_t _create_locale(int category, const char* locale) {
return LocaleMock::instance->newlocale(category, locale, 0);
}
@@ -469,38 +474,44 @@
LocaleMock::instance->freelocale(locale);
}
-double _strtod_l(const char *nptr, char **endptr, _locale_t locale) {
+double _strtod_l(const char* nptr, char** endptr, _locale_t locale) {
return LocaleMock::instance->strtod_l(nptr, endptr, locale);
}
-# pragma warning(pop)
-#endif
+# ifdef __clang__
+# pragma clang diagnostic pop
+# endif
+# pragma warning(pop)
+# endif
-#if defined(__THROW) && FMT_GCC_VERSION > 0 && FMT_GCC_VERSION <= 408
-#define FMT_LOCALE_THROW __THROW
-#else
-#define FMT_LOCALE_THROW
-#endif
+# if defined(__THROW) && FMT_GCC_VERSION > 0 && FMT_GCC_VERSION <= 408
+# define FMT_LOCALE_THROW __THROW
+# else
+# define FMT_LOCALE_THROW
+# endif
-LocaleType newlocale(int category_mask, const char *locale, LocaleType base) FMT_LOCALE_THROW {
+LocaleType newlocale(int category_mask, const char* locale,
+ LocaleType base) FMT_LOCALE_THROW {
return LocaleMock::instance->newlocale(category_mask, locale, base);
}
-#if defined(__APPLE__) || (defined(__FreeBSD__) && __FreeBSD_version < 1200002)
+# if defined(__APPLE__) || \
+ (defined(__FreeBSD__) && __FreeBSD_version < 1200002)
typedef int FreeLocaleResult;
-#else
+# else
typedef void FreeLocaleResult;
-#endif
+# endif
FreeLocaleResult freelocale(LocaleType locale) FMT_LOCALE_THROW {
LocaleMock::instance->freelocale(locale);
return FreeLocaleResult();
}
-double strtod_l(const char *nptr, char **endptr, LocaleType locale) FMT_LOCALE_THROW {
+double strtod_l(const char* nptr, char** endptr,
+ LocaleType locale) FMT_LOCALE_THROW {
return LocaleMock::instance->strtod_l(nptr, endptr, locale);
}
-#undef FMT_LOCALE_THROW
+# undef FMT_LOCALE_THROW
TEST(LocaleTest, LocaleMock) {
ScopedMock<LocaleMock> mock;
@@ -510,12 +521,12 @@
}
TEST(LocaleTest, Locale) {
-#ifndef LC_NUMERIC_MASK
+# ifndef LC_NUMERIC_MASK
enum { LC_NUMERIC_MASK = LC_NUMERIC };
-#endif
+# endif
ScopedMock<LocaleMock> mock;
LocaleType impl = reinterpret_cast<LocaleType>(42);
- EXPECT_CALL(mock, newlocale(LC_NUMERIC_MASK, StrEq("C"), FMT_NULL))
+ EXPECT_CALL(mock, newlocale(LC_NUMERIC_MASK, StrEq("C"), nullptr))
.WillOnce(Return(impl));
EXPECT_CALL(mock, freelocale(impl));
fmt::Locale locale;
@@ -528,7 +539,7 @@
.WillOnce(Return(reinterpret_cast<LocaleType>(42)));
EXPECT_CALL(mock, freelocale(_));
fmt::Locale locale;
- const char *str = "4.2";
+ const char* str = "4.2";
char end = 'x';
EXPECT_CALL(mock, strtod_l(str, _, locale.get()))
.WillOnce(testing::DoAll(testing::SetArgPointee<1>(&end), Return(777)));
diff --git a/test/posix-mock.h b/test/posix-mock.h
index 9a4c68f..028aeee 100644
--- a/test/posix-mock.h
+++ b/test/posix-mock.h
@@ -12,10 +12,10 @@
#include <stdio.h>
#ifdef _WIN32
-# include <windows.h>
+# include <windows.h>
#else
-# include <sys/param.h> // for FreeBSD version
-# include <sys/types.h> // for ssize_t
+# include <sys/param.h> // for FreeBSD version
+# include <sys/types.h> // for ssize_t
#endif
#ifndef _MSC_VER
@@ -28,13 +28,13 @@
// Size type for read and write.
typedef size_t size_t;
typedef ssize_t ssize_t;
-int open(const char *path, int oflag, int mode);
-int fstat(int fd, struct stat *buf);
+int open(const char* path, int oflag, int mode);
+int fstat(int fd, struct stat* buf);
#else
typedef unsigned size_t;
typedef int ssize_t;
-errno_t sopen_s(
- int* pfh, const char *filename, int oflag, int shflag, int pmode);
+errno_t sopen_s(int* pfh, const char* filename, int oflag, int shflag,
+ int pmode);
#endif
#ifndef _WIN32
@@ -48,20 +48,20 @@
int dup(int fildes);
int dup2(int fildes, int fildes2);
-FILE *fdopen(int fildes, const char *mode);
+FILE* fdopen(int fildes, const char* mode);
-ssize_t read(int fildes, void *buf, size_t nbyte);
-ssize_t write(int fildes, const void *buf, size_t nbyte);
+ssize_t read(int fildes, void* buf, size_t nbyte);
+ssize_t write(int fildes, const void* buf, size_t nbyte);
#ifndef _WIN32
int pipe(int fildes[2]);
#else
-int pipe(int *pfds, unsigned psize, int textmode);
+int pipe(int* pfds, unsigned psize, int textmode);
#endif
-FILE *fopen(const char *filename, const char *mode);
-int fclose(FILE *stream);
-int (fileno)(FILE *stream);
+FILE* fopen(const char* filename, const char* mode);
+int fclose(FILE* stream);
+int(fileno)(FILE* stream);
} // namespace test
#define FMT_SYSTEM(call) test::call
diff --git a/test/posix-test.cc b/test/posix-test.cc
index fbd4568..133a922 100644
--- a/test/posix-test.cc
+++ b/test/posix-test.cc
@@ -7,21 +7,20 @@
#include <cstdlib> // std::exit
#include <cstring>
+#include <memory>
#include "fmt/posix.h"
#include "gtest-extra.h"
#include "util.h"
#ifdef fileno
-# undef fileno
+# undef fileno
#endif
using fmt::buffered_file;
using fmt::error_code;
using fmt::file;
-using testing::internal::scoped_ptr;
-
// Checks if the file is open by reading one character from it.
static bool isopen(int fd) {
char buffer;
@@ -45,9 +44,9 @@
}
// Attempts to write a string to a file.
-static void write(file &f, fmt::string_view s) {
+static void write(file& f, fmt::string_view s) {
std::size_t num_chars_left = s.size();
- const char *ptr = s.data();
+ const char* ptr = s.data();
do {
std::size_t count = f.write(ptr, num_chars_left);
ptr += count;
@@ -59,26 +58,26 @@
TEST(BufferedFileTest, DefaultCtor) {
buffered_file f;
- EXPECT_TRUE(f.get() == FMT_NULL);
+ EXPECT_TRUE(f.get() == nullptr);
}
TEST(BufferedFileTest, MoveCtor) {
buffered_file bf = open_buffered_file();
- FILE *fp = bf.get();
- EXPECT_TRUE(fp != FMT_NULL);
+ FILE* fp = bf.get();
+ EXPECT_TRUE(fp != nullptr);
buffered_file bf2(std::move(bf));
EXPECT_EQ(fp, bf2.get());
- EXPECT_TRUE(bf.get() == FMT_NULL);
+ EXPECT_TRUE(bf.get() == nullptr);
}
TEST(BufferedFileTest, MoveAssignment) {
buffered_file bf = open_buffered_file();
- FILE *fp = bf.get();
- EXPECT_TRUE(fp != FMT_NULL);
+ FILE* fp = bf.get();
+ EXPECT_TRUE(fp != nullptr);
buffered_file bf2;
bf2 = std::move(bf);
EXPECT_EQ(fp, bf2.get());
- EXPECT_TRUE(bf.get() == FMT_NULL);
+ EXPECT_TRUE(bf.get() == nullptr);
}
TEST(BufferedFileTest, MoveAssignmentClosesFile) {
@@ -90,13 +89,13 @@
}
TEST(BufferedFileTest, MoveFromTemporaryInCtor) {
- FILE *fp = FMT_NULL;
+ FILE* fp = nullptr;
buffered_file f(open_buffered_file(&fp));
EXPECT_EQ(fp, f.get());
}
TEST(BufferedFileTest, MoveFromTemporaryInAssignment) {
- FILE *fp = FMT_NULL;
+ FILE* fp = nullptr;
buffered_file f;
f = open_buffered_file(&fp);
EXPECT_EQ(fp, f.get());
@@ -119,22 +118,24 @@
}
TEST(BufferedFileTest, CloseErrorInDtor) {
- scoped_ptr<buffered_file> f(new buffered_file(open_buffered_file()));
- EXPECT_WRITE(stderr, {
- // The close function must be called inside EXPECT_WRITE, otherwise
- // the system may recycle closed file descriptor when redirecting the
- // output in EXPECT_STDERR and the second close will break output
- // redirection.
- FMT_POSIX(close(f->fileno()));
- SUPPRESS_ASSERT(f.reset(FMT_NULL));
- }, format_system_error(EBADF, "cannot close file") + "\n");
+ std::unique_ptr<buffered_file> f(new buffered_file(open_buffered_file()));
+ EXPECT_WRITE(stderr,
+ {
+ // The close function must be called inside EXPECT_WRITE,
+ // otherwise the system may recycle closed file descriptor when
+ // redirecting the output in EXPECT_STDERR and the second close
+ // will break output redirection.
+ FMT_POSIX(close(f->fileno()));
+ SUPPRESS_ASSERT(f.reset(nullptr));
+ },
+ format_system_error(EBADF, "cannot close file") + "\n");
}
TEST(BufferedFileTest, Close) {
buffered_file f = open_buffered_file();
int fd = f.fileno();
f.close();
- EXPECT_TRUE(f.get() == FMT_NULL);
+ EXPECT_TRUE(f.get() == nullptr);
EXPECT_TRUE(isclosed(fd));
}
@@ -142,7 +143,7 @@
buffered_file f = open_buffered_file();
FMT_POSIX(close(f.fileno()));
EXPECT_SYSTEM_ERROR_NOASSERT(f.close(), EBADF, "cannot close file");
- EXPECT_TRUE(f.get() == FMT_NULL);
+ EXPECT_TRUE(f.get() == nullptr);
}
TEST(BufferedFileTest, Fileno) {
@@ -150,13 +151,15 @@
#ifndef __COVERITY__
// fileno on a null FILE pointer either crashes or returns an error.
// Disable Coverity because this is intentional.
- EXPECT_DEATH_IF_SUPPORTED({
- try {
- f.fileno();
- } catch (const fmt::system_error&) {
- std::exit(1);
- }
- }, "");
+ EXPECT_DEATH_IF_SUPPORTED(
+ {
+ try {
+ f.fileno();
+ } catch (const fmt::system_error&) {
+ std::exit(1);
+ }
+ },
+ "");
#endif
f = open_buffered_file();
EXPECT_TRUE(f.fileno() != -1);
@@ -170,7 +173,7 @@
}
TEST(FileTest, OpenBufferedFileInCtor) {
- FILE *fp = safe_fopen("test-file", "w");
+ FILE* fp = safe_fopen("test-file", "w");
std::fputs(FILE_CONTENT, fp);
std::fclose(fp);
file f("test-file", file::RDONLY);
@@ -178,8 +181,8 @@
}
TEST(FileTest, OpenBufferedFileError) {
- EXPECT_SYSTEM_ERROR(file("nonexistent", file::RDONLY),
- ENOENT, "cannot open file nonexistent");
+ EXPECT_SYSTEM_ERROR(file("nonexistent", file::RDONLY), ENOENT,
+ "cannot open file nonexistent");
}
TEST(FileTest, MoveCtor) {
@@ -209,7 +212,7 @@
EXPECT_TRUE(isclosed(old_fd));
}
-static file OpenBufferedFile(int &fd) {
+static file OpenBufferedFile(int& fd) {
file f = open_file();
fd = f.descriptor();
return f;
@@ -246,15 +249,17 @@
}
TEST(FileTest, CloseErrorInDtor) {
- scoped_ptr<file> f(new file(open_file()));
- EXPECT_WRITE(stderr, {
- // The close function must be called inside EXPECT_WRITE, otherwise
- // the system may recycle closed file descriptor when redirecting the
- // output in EXPECT_STDERR and the second close will break output
- // redirection.
- FMT_POSIX(close(f->descriptor()));
- SUPPRESS_ASSERT(f.reset(FMT_NULL));
- }, format_system_error(EBADF, "cannot close file") + "\n");
+ std::unique_ptr<file> f(new file(open_file()));
+ EXPECT_WRITE(stderr,
+ {
+ // The close function must be called inside EXPECT_WRITE,
+ // otherwise the system may recycle closed file descriptor when
+ // redirecting the output in EXPECT_STDERR and the second close
+ // will break output redirection.
+ FMT_POSIX(close(f->descriptor()));
+ SUPPRESS_ASSERT(f.reset(nullptr));
+ },
+ format_system_error(EBADF, "cannot close file") + "\n");
}
TEST(FileTest, Close) {
@@ -310,8 +315,8 @@
#ifndef __COVERITY__
TEST(FileTest, DupError) {
int value = -1;
- EXPECT_SYSTEM_ERROR_NOASSERT(file::dup(value),
- EBADF, "cannot duplicate file descriptor -1");
+ EXPECT_SYSTEM_ERROR_NOASSERT(file::dup(value), EBADF,
+ "cannot duplicate file descriptor -1");
}
#endif
@@ -325,8 +330,9 @@
TEST(FileTest, Dup2Error) {
file f = open_file();
- EXPECT_SYSTEM_ERROR_NOASSERT(f.dup2(-1), EBADF,
- fmt::format("cannot duplicate file descriptor {} to -1", f.descriptor()));
+ EXPECT_SYSTEM_ERROR_NOASSERT(
+ f.dup2(-1), EBADF,
+ fmt::format("cannot duplicate file descriptor {} to -1", f.descriptor()));
}
TEST(FileTest, Dup2NoExcept) {
@@ -364,8 +370,8 @@
TEST(FileTest, FdopenError) {
file f;
- EXPECT_SYSTEM_ERROR_NOASSERT(
- f.fdopen("r"), EBADF, "cannot associate stream with file descriptor");
+ EXPECT_SYSTEM_ERROR_NOASSERT(f.fdopen("r"), EBADF,
+ "cannot associate stream with file descriptor");
}
#ifdef FMT_LOCALE
diff --git a/test/printf-test.cc b/test/printf-test.cc
index cc62b91..aa25a59 100644
--- a/test/printf-test.cc
+++ b/test/printf-test.cc
@@ -35,17 +35,17 @@
// A wrapper around fmt::sprintf to workaround bogus warnings about invalid
// format strings in MSVC.
template <typename... Args>
-std::string test_sprintf(fmt::string_view format, const Args &... args) {
+std::string test_sprintf(fmt::string_view format, const Args&... args) {
return fmt::sprintf(format, args...);
}
template <typename... Args>
-std::wstring test_sprintf(fmt::wstring_view format, const Args &... args) {
+std::wstring test_sprintf(fmt::wstring_view format, const Args&... args) {
return fmt::sprintf(format, args...);
}
-#define EXPECT_PRINTF(expected_output, format, arg) \
+#define EXPECT_PRINTF(expected_output, format, arg) \
EXPECT_EQ(expected_output, test_sprintf(format, arg)) \
- << "format: " << format; \
+ << "format: " << format; \
EXPECT_EQ(expected_output, fmt::sprintf(make_positional(format), arg))
TEST(PrintfTest, NoArgs) {
@@ -69,11 +69,10 @@
TEST(PrintfTest, PositionalArgs) {
EXPECT_EQ("42", test_sprintf("%1$d", 42));
EXPECT_EQ("before 42", test_sprintf("before %1$d", 42));
- EXPECT_EQ("42 after", test_sprintf("%1$d after",42));
+ EXPECT_EQ("42 after", test_sprintf("%1$d after", 42));
EXPECT_EQ("before 42 after", test_sprintf("before %1$d after", 42));
EXPECT_EQ("answer = 42", test_sprintf("%1$s = %2$d", "answer", 42));
- EXPECT_EQ("42 is the answer",
- test_sprintf("%2$d is the %1$s", "answer", 42));
+ EXPECT_EQ("42 is the answer", test_sprintf("%2$d is the %1$s", "answer", 42));
EXPECT_EQ("abracadabra", test_sprintf("%1$s%2$s%1$s", "abra", "cad"));
}
@@ -82,46 +81,46 @@
}
TEST(PrintfTest, NumberIsTooBigInArgIndex) {
- EXPECT_THROW_MSG(test_sprintf(format("%{}$", BIG_NUM)),
- format_error, "number is too big");
- EXPECT_THROW_MSG(test_sprintf(format("%{}$d", BIG_NUM)),
- format_error, "number is too big");
+ EXPECT_THROW_MSG(test_sprintf(format("%{}$", BIG_NUM)), format_error,
+ "number is too big");
+ EXPECT_THROW_MSG(test_sprintf(format("%{}$d", BIG_NUM)), format_error,
+ "number is too big");
}
TEST(PrintfTest, SwitchArgIndexing) {
- EXPECT_THROW_MSG(test_sprintf("%1$d%", 1, 2),
- format_error, "cannot switch from manual to automatic argument indexing");
+ EXPECT_THROW_MSG(test_sprintf("%1$d%", 1, 2), format_error,
+ "cannot switch from manual to automatic argument indexing");
EXPECT_THROW_MSG(test_sprintf(format("%1$d%{}d", BIG_NUM), 1, 2),
- format_error, "number is too big");
- EXPECT_THROW_MSG(test_sprintf("%1$d%d", 1, 2),
- format_error, "cannot switch from manual to automatic argument indexing");
+ format_error, "number is too big");
+ EXPECT_THROW_MSG(test_sprintf("%1$d%d", 1, 2), format_error,
+ "cannot switch from manual to automatic argument indexing");
- EXPECT_THROW_MSG(test_sprintf("%d%1$", 1, 2),
- format_error, "cannot switch from automatic to manual argument indexing");
- EXPECT_THROW_MSG(test_sprintf(format("%d%{}$d", BIG_NUM), 1, 2),
- format_error, "number is too big");
- EXPECT_THROW_MSG(test_sprintf("%d%1$d", 1, 2),
- format_error, "cannot switch from automatic to manual argument indexing");
+ EXPECT_THROW_MSG(test_sprintf("%d%1$", 1, 2), format_error,
+ "cannot switch from automatic to manual argument indexing");
+ EXPECT_THROW_MSG(test_sprintf(format("%d%{}$d", BIG_NUM), 1, 2), format_error,
+ "number is too big");
+ EXPECT_THROW_MSG(test_sprintf("%d%1$d", 1, 2), format_error,
+ "cannot switch from automatic to manual argument indexing");
// Indexing errors override width errors.
EXPECT_THROW_MSG(test_sprintf(format("%d%1${}d", BIG_NUM), 1, 2),
- format_error, "number is too big");
+ format_error, "number is too big");
EXPECT_THROW_MSG(test_sprintf(format("%1$d%{}d", BIG_NUM), 1, 2),
- format_error, "number is too big");
+ format_error, "number is too big");
}
TEST(PrintfTest, InvalidArgIndex) {
EXPECT_THROW_MSG(test_sprintf("%0$d", 42), format_error,
- "argument index out of range");
+ "argument index out of range");
EXPECT_THROW_MSG(test_sprintf("%2$d", 42), format_error,
- "argument index out of range");
- EXPECT_THROW_MSG(test_sprintf(format("%{}$d", INT_MAX), 42),
- format_error, "argument index out of range");
+ "argument index out of range");
+ EXPECT_THROW_MSG(test_sprintf(format("%{}$d", INT_MAX), 42), format_error,
+ "argument index out of range");
- EXPECT_THROW_MSG(test_sprintf("%2$", 42),
- format_error, "argument index out of range");
- EXPECT_THROW_MSG(test_sprintf(format("%{}$d", BIG_NUM), 42),
- format_error, "number is too big");
+ EXPECT_THROW_MSG(test_sprintf("%2$", 42), format_error,
+ "argument index out of range");
+ EXPECT_THROW_MSG(test_sprintf(format("%{}$d", BIG_NUM), 42), format_error,
+ "number is too big");
}
TEST(PrintfTest, DefaultAlignRight) {
@@ -175,8 +174,8 @@
EXPECT_PRINTF("0x42", "%#x", 0x42);
EXPECT_PRINTF("0X42", "%#X", 0x42);
- EXPECT_PRINTF(
- fmt::format("0x{:x}", static_cast<unsigned>(-0x42)), "%#x", -0x42);
+ EXPECT_PRINTF(fmt::format("0x{:x}", static_cast<unsigned>(-0x42)), "%#x",
+ -0x42);
EXPECT_PRINTF("0", "%#x", 0);
EXPECT_PRINTF("0x0042", "%#06x", 0x42);
@@ -208,23 +207,23 @@
// Width cannot be specified twice.
EXPECT_THROW_MSG(test_sprintf("%5-5d", 42), format_error,
- "invalid type specifier");
+ "invalid type specifier");
- EXPECT_THROW_MSG(test_sprintf(format("%{}d", BIG_NUM), 42),
- format_error, "number is too big");
- EXPECT_THROW_MSG(test_sprintf(format("%1${}d", BIG_NUM), 42),
- format_error, "number is too big");
+ EXPECT_THROW_MSG(test_sprintf(format("%{}d", BIG_NUM), 42), format_error,
+ "number is too big");
+ EXPECT_THROW_MSG(test_sprintf(format("%1${}d", BIG_NUM), 42), format_error,
+ "number is too big");
}
TEST(PrintfTest, DynamicWidth) {
EXPECT_EQ(" 42", test_sprintf("%*d", 5, 42));
EXPECT_EQ("42 ", test_sprintf("%*d", -5, 42));
EXPECT_THROW_MSG(test_sprintf("%*d", 5.0, 42), format_error,
- "width is not integer");
+ "width is not integer");
EXPECT_THROW_MSG(test_sprintf("%*d"), format_error,
- "argument index out of range");
+ "argument index out of range");
EXPECT_THROW_MSG(test_sprintf("%*d", BIG_NUM, 42), format_error,
- "number is too big");
+ "number is too big");
}
TEST(PrintfTest, IntPrecision) {
@@ -253,8 +252,7 @@
safe_sprintf(buffer, "%.3e", 1234.5678);
EXPECT_PRINTF(buffer, "%.3e", 1234.5678);
EXPECT_PRINTF("1234.568", "%.3f", 1234.5678);
- safe_sprintf(buffer, "%.3g", 1234.5678);
- EXPECT_PRINTF(buffer, "%.3g", 1234.5678);
+ EXPECT_PRINTF("1.23e+03", "%.3g", 1234.5678);
safe_sprintf(buffer, "%.3a", 1234.5678);
EXPECT_PRINTF(buffer, "%.3a", 1234.5678);
}
@@ -267,24 +265,22 @@
EXPECT_EQ("00042", test_sprintf("%.*d", 5, 42));
EXPECT_EQ("42", test_sprintf("%.*d", -5, 42));
EXPECT_THROW_MSG(test_sprintf("%.*d", 5.0, 42), format_error,
- "precision is not integer");
+ "precision is not integer");
EXPECT_THROW_MSG(test_sprintf("%.*d"), format_error,
- "argument index out of range");
+ "argument index out of range");
EXPECT_THROW_MSG(test_sprintf("%.*d", BIG_NUM, 42), format_error,
- "number is too big");
+ "number is too big");
if (sizeof(long long) != sizeof(int)) {
long long prec = static_cast<long long>(INT_MIN) - 1;
EXPECT_THROW_MSG(test_sprintf("%.*d", prec, 42), format_error,
- "number is too big");
- }
+ "number is too big");
+ }
}
-template <typename T>
-struct make_signed { typedef T type; };
+template <typename T> struct make_signed { typedef T type; };
#define SPECIALIZE_MAKE_SIGNED(T, S) \
- template <> \
- struct make_signed<T> { typedef S type; }
+ template <> struct make_signed<T> { typedef S type; }
SPECIALIZE_MAKE_SIGNED(char, signed char);
SPECIALIZE_MAKE_SIGNED(unsigned char, signed char);
@@ -295,7 +291,7 @@
// Test length format specifier ``length_spec``.
template <typename T, typename U>
-void TestLength(const char *length_spec, U value) {
+void TestLength(const char* length_spec, U value) {
long long signed_value = 0;
unsigned long long unsigned_value = 0;
// Apply integer promotion to the argument.
@@ -335,8 +331,7 @@
EXPECT_PRINTF(os.str(), fmt::format("%{}X", length_spec), value);
}
-template <typename T>
-void TestLength(const char *length_spec) {
+template <typename T> void TestLength(const char* length_spec) {
T min = std::numeric_limits<T>::min(), max = std::numeric_limits<T>::max();
TestLength<T>(length_spec, 42);
TestLength<T>(length_spec, -42);
@@ -372,8 +367,8 @@
TestLength<std::size_t>("z");
TestLength<std::ptrdiff_t>("t");
long double max = std::numeric_limits<long double>::max();
- EXPECT_PRINTF(fmt::format("{}", max), "%g", max);
- EXPECT_PRINTF(fmt::format("{}", max), "%Lg", max);
+ EXPECT_PRINTF(fmt::format("{:.6}", max), "%g", max);
+ EXPECT_PRINTF(fmt::format("{:.6}", max), "%Lg", max);
}
TEST(PrintfTest, Bool) {
@@ -411,6 +406,8 @@
EXPECT_PRINTF(buffer, "%E", 392.65);
EXPECT_PRINTF("392.65", "%g", 392.65);
EXPECT_PRINTF("392.65", "%G", 392.65);
+ EXPECT_PRINTF("392", "%g", 392.0);
+ EXPECT_PRINTF("392", "%G", 392.0);
safe_sprintf(buffer, "%a", -392.65);
EXPECT_EQ(buffer, format("{:a}", -392.65));
safe_sprintf(buffer, "%A", -392.65);
@@ -430,42 +427,42 @@
EXPECT_PRINTF("x", "%c", 'x');
int max = std::numeric_limits<int>::max();
EXPECT_PRINTF(fmt::format("{}", static_cast<char>(max)), "%c", max);
- //EXPECT_PRINTF("x", "%lc", L'x');
+ // EXPECT_PRINTF("x", "%lc", L'x');
EXPECT_PRINTF(L"x", L"%c", L'x');
EXPECT_PRINTF(fmt::format(L"{}", static_cast<wchar_t>(max)), L"%c", max);
}
TEST(PrintfTest, String) {
EXPECT_PRINTF("abc", "%s", "abc");
- const char *null_str = FMT_NULL;
+ const char* null_str = nullptr;
EXPECT_PRINTF("(null)", "%s", null_str);
EXPECT_PRINTF(" (null)", "%10s", null_str);
EXPECT_PRINTF(L"abc", L"%s", L"abc");
- const wchar_t *null_wstr = FMT_NULL;
+ const wchar_t* null_wstr = nullptr;
EXPECT_PRINTF(L"(null)", L"%s", null_wstr);
EXPECT_PRINTF(L" (null)", L"%10s", null_wstr);
}
TEST(PrintfTest, Pointer) {
int n;
- void *p = &n;
+ void* p = &n;
EXPECT_PRINTF(fmt::format("{}", p), "%p", p);
- p = FMT_NULL;
+ p = nullptr;
EXPECT_PRINTF("(nil)", "%p", p);
EXPECT_PRINTF(" (nil)", "%10p", p);
- const char *s = "test";
+ const char* s = "test";
EXPECT_PRINTF(fmt::format("{:p}", s), "%p", s);
- const char *null_str = FMT_NULL;
+ const char* null_str = nullptr;
EXPECT_PRINTF("(nil)", "%p", null_str);
p = &n;
EXPECT_PRINTF(fmt::format(L"{}", p), L"%p", p);
- p = FMT_NULL;
+ p = nullptr;
EXPECT_PRINTF(L"(nil)", L"%p", p);
EXPECT_PRINTF(L" (nil)", L"%10p", p);
- const wchar_t *w = L"test";
+ const wchar_t* w = L"test";
EXPECT_PRINTF(fmt::format(L"{:p}", w), L"%p", w);
- const wchar_t *null_wstr = FMT_NULL;
+ const wchar_t* null_wstr = nullptr;
EXPECT_PRINTF(L"(nil)", L"%p", null_wstr);
}
@@ -475,14 +472,12 @@
enum E { A = 42 };
-TEST(PrintfTest, Enum) {
- EXPECT_PRINTF("42", "%d", A);
-}
+TEST(PrintfTest, Enum) { EXPECT_PRINTF("42", "%d", A); }
#if FMT_USE_FILE_DESCRIPTORS
TEST(PrintfTest, Examples) {
- const char *weekday = "Thursday";
- const char *month = "August";
+ const char* weekday = "Thursday";
+ const char* month = "August";
int day = 21;
EXPECT_WRITE(stdout, fmt::printf("%1$s, %3$d %2$s", weekday, month, day),
"Thursday, 21 August");
@@ -496,9 +491,7 @@
}
#endif
-TEST(PrintfTest, WideString) {
- EXPECT_EQ(L"abc", fmt::sprintf(L"%s", L"abc"));
-}
+TEST(PrintfTest, WideString) { EXPECT_EQ(L"abc", fmt::sprintf(L"%s", L"abc")); }
TEST(PrintfTest, PrintfCustom) {
EXPECT_EQ("abc", test_sprintf("%s", TestString("abc")));
@@ -520,7 +513,7 @@
EXPECT_WRITE(stdout, fmt::vfprintf(std::cout, "%d", args), "42");
}
-template<typename... Args>
+template <typename... Args>
void check_format_string_regression(fmt::string_view s, const Args&... args) {
fmt::sprintf(s, args...);
}
@@ -529,41 +522,91 @@
check_format_string_regression("%c%s", 'x', "");
}
+TEST(PrintfTest, FixedLargeExponent) {
+ EXPECT_EQ("1000000000000000000000", fmt::sprintf("%.*f", -13, 1e21));
+}
+
TEST(PrintfTest, VSPrintfMakeArgsExample) {
- fmt::format_arg_store<fmt::printf_context, int, const char *> as{
- 42, "something"};
+ fmt::format_arg_store<fmt::printf_context, int, const char*> as{42,
+ "something"};
fmt::basic_format_args<fmt::printf_context> args(as);
- EXPECT_EQ(
- "[42] something happened", fmt::vsprintf("[%d] %s happened", args));
+ EXPECT_EQ("[42] something happened", fmt::vsprintf("[%d] %s happened", args));
auto as2 = fmt::make_printf_args(42, "something");
fmt::basic_format_args<fmt::printf_context> args2(as2);
- EXPECT_EQ(
- "[42] something happened", fmt::vsprintf("[%d] %s happened", args2));
- //the older gcc versions can't cast the return value
-#if !defined(__GNUC__) || (__GNUC__ > 4)
- EXPECT_EQ(
- "[42] something happened",
- fmt::vsprintf(
- "[%d] %s happened", fmt::make_printf_args(42, "something")));
+ EXPECT_EQ("[42] something happened",
+ fmt::vsprintf("[%d] %s happened", args2));
+ // The older gcc versions can't cast the return value.
+#if !defined(__GNUC__) || (__GNUC__ > 4)
+ EXPECT_EQ("[42] something happened",
+ fmt::vsprintf("[%d] %s happened",
+ {fmt::make_printf_args(42, "something")}));
#endif
}
TEST(PrintfTest, VSPrintfMakeWArgsExample) {
- fmt::format_arg_store<fmt::wprintf_context, int, const wchar_t *> as{
- 42, L"something"};
+ fmt::format_arg_store<fmt::wprintf_context, int, const wchar_t*> as{
+ 42, L"something"};
fmt::basic_format_args<fmt::wprintf_context> args(as);
- EXPECT_EQ(
- L"[42] something happened",
- fmt::vsprintf(L"[%d] %s happened", args));
- auto as2 = fmt::make_wprintf_args(42, L"something");
+ EXPECT_EQ(L"[42] something happened",
+ fmt::vsprintf(L"[%d] %s happened", args));
+ auto as2 = fmt::make_wprintf_args(42, L"something");
fmt::basic_format_args<fmt::wprintf_context> args2(as2);
- EXPECT_EQ(
- L"[42] something happened", fmt::vsprintf(L"[%d] %s happened", args2));
+ EXPECT_EQ(L"[42] something happened",
+ fmt::vsprintf(L"[%d] %s happened", args2));
// the older gcc versions can't cast the return value
#if !defined(__GNUC__) || (__GNUC__ > 4)
- EXPECT_EQ(
- L"[42] something happened",
- fmt::vsprintf(
- L"[%d] %s happened", fmt::make_wprintf_args(42, L"something")));
+ EXPECT_EQ(L"[42] something happened",
+ fmt::vsprintf(L"[%d] %s happened",
+ {fmt::make_wprintf_args(42, L"something")}));
#endif
}
+
+typedef fmt::printf_arg_formatter<fmt::internal::buffer_range<char>>
+ formatter_t;
+typedef fmt::basic_printf_context<formatter_t::iterator, char> context_t;
+
+// A custom printf argument formatter that doesn't print `-` for floating-point
+// values rounded to 0.
+class custom_printf_arg_formatter : public formatter_t {
+ public:
+ using formatter_t::iterator;
+
+ custom_printf_arg_formatter(formatter_t::iterator iter,
+ formatter_t::format_specs& specs, context_t& ctx)
+ : formatter_t(iter, specs, ctx) {}
+
+ using formatter_t::operator();
+
+#if FMT_MSC_VER > 0 && FMT_MSC_VER <= 1804
+ template <typename T, FMT_ENABLE_IF(std::is_floating_point<T>::value)>
+ iterator operator()(T value){
+#else
+ iterator operator()(double value) {
+#endif
+ // Comparing a float to 0.0 is safe.
+ if (round(value * pow(10, specs()->precision)) == 0.0) value = 0;
+ return formatter_t::operator()(value);
+}
+}
+;
+
+typedef fmt::basic_format_args<context_t> format_args_t;
+
+std::string custom_vformat(fmt::string_view format_str, format_args_t args) {
+ fmt::memory_buffer buffer;
+ fmt::vprintf<custom_printf_arg_formatter>(buffer, format_str, args);
+ return std::string(buffer.data(), buffer.size());
+}
+
+template <typename... Args>
+std::string custom_format(const char* format_str, const Args&... args) {
+ auto va = fmt::make_printf_args(args...);
+ return custom_vformat(format_str, {va});
+}
+
+TEST(PrintfTest, CustomFormat) {
+ EXPECT_EQ("0.00", custom_format("%.2f", -.00001));
+ EXPECT_EQ("0.00", custom_format("%.2f", .00001));
+ EXPECT_EQ("1.00", custom_format("%.2f", 1.00001));
+ EXPECT_EQ("-1.00", custom_format("%.2f", -1.00001));
+}
diff --git a/test/ranges-test.cc b/test/ranges-test.cc
index 77b4ced..7d4b6d2 100644
--- a/test/ranges-test.cc
+++ b/test/ranges-test.cc
@@ -13,13 +13,13 @@
#if (__cplusplus > 201402L) || \
(defined(_MSVC_LANG) && _MSVC_LANG > 201402L && _MSC_VER >= 1910)
-#include "fmt/ranges.h"
-#include "gtest.h"
+# include "fmt/ranges.h"
+# include "gtest.h"
-#include <vector>
-#include <array>
-#include <map>
-#include <string>
+# include <array>
+# include <map>
+# include <string>
+# include <vector>
TEST(RangesTest, FormatVector) {
std::vector<int32_t> iv{1, 2, 3, 5, 7, 11};
@@ -39,21 +39,20 @@
}
TEST(RangesTest, FormatPair) {
- std::pair<int64_t, float> pa1{42, 3.14159265358979f};
- EXPECT_EQ("(42, 3.14159)", fmt::format("{}", pa1));
+ std::pair<int64_t, float> pa1{42, 1.5f};
+ EXPECT_EQ("(42, 1.5)", fmt::format("{}", pa1));
}
TEST(RangesTest, FormatTuple) {
- std::tuple<int64_t, float, std::string, char> tu1{42, 3.14159265358979f,
- "this is tuple", 'i'};
- EXPECT_EQ("(42, 3.14159, \"this is tuple\", 'i')", fmt::format("{}", tu1));
+ std::tuple<int64_t, float, std::string, char> tu1{42, 1.5f, "this is tuple",
+ 'i'};
+ EXPECT_EQ("(42, 1.5, \"this is tuple\", 'i')", fmt::format("{}", tu1));
}
struct my_struct {
int32_t i;
std::string str; // can throw
- template <std::size_t N>
- decltype(auto) get() const noexcept {
+ template <std::size_t N> decltype(auto) get() const noexcept {
if constexpr (N == 0)
return i;
else if constexpr (N == 1)
@@ -61,8 +60,7 @@
}
};
-template <std::size_t N>
-decltype(auto) get(const my_struct& s) noexcept {
+template <std::size_t N> decltype(auto) get(const my_struct& s) noexcept {
return s.get<N>();
}
@@ -71,8 +69,7 @@
template <>
struct tuple_size<my_struct> : std::integral_constant<std::size_t, 2> {};
-template <std::size_t N>
-struct tuple_element<N, my_struct> {
+template <std::size_t N> struct tuple_element<N, my_struct> {
using type = decltype(std::declval<my_struct>().get<N>());
};
@@ -83,5 +80,23 @@
EXPECT_EQ("(13, \"my struct\")", fmt::format("{}", mst));
}
+TEST(RangesTest, FormatTo) {
+ char buf[10];
+ auto end = fmt::format_to(buf, "{}", std::vector{1, 2, 3});
+ *end = '\0';
+ EXPECT_STREQ(buf, "{1, 2, 3}");
+}
+
+struct path_like {
+ const path_like* begin() const;
+ const path_like* end() const;
+
+ operator std::string() const;
+};
+
+TEST(RangesTest, PathLike) {
+ EXPECT_FALSE((fmt::is_range<path_like, char>::value));
+}
+
#endif // (__cplusplus > 201402L) || (defined(_MSVC_LANG) && _MSVC_LANG >
// 201402L && _MSC_VER >= 1910)
diff --git a/test/scan-test.cc b/test/scan-test.cc
new file mode 100644
index 0000000..0b49fd9
--- /dev/null
+++ b/test/scan-test.cc
@@ -0,0 +1,114 @@
+// Formatting library for C++ - scanning API test
+//
+// Copyright (c) 2019 - present, Victor Zverovich
+// All rights reserved.
+//
+// For the license information refer to format.h.
+
+#include <time.h>
+#include <climits>
+
+#include "gmock.h"
+#include "gtest-extra.h"
+#include "scan.h"
+
+TEST(ScanTest, ReadText) {
+ fmt::string_view s = "foo";
+ auto end = fmt::scan(s, "foo");
+ EXPECT_EQ(end, s.end());
+ EXPECT_THROW_MSG(fmt::scan("fob", "foo"), fmt::format_error, "invalid input");
+}
+
+TEST(ScanTest, ReadInt) {
+ int n = 0;
+ fmt::scan("42", "{}", n);
+ EXPECT_EQ(n, 42);
+ fmt::scan("-42", "{}", n);
+ EXPECT_EQ(n, -42);
+}
+
+TEST(ScanTest, ReadLongLong) {
+ long long n = 0;
+ fmt::scan("42", "{}", n);
+ EXPECT_EQ(n, 42);
+ fmt::scan("-42", "{}", n);
+ EXPECT_EQ(n, -42);
+}
+
+TEST(ScanTest, ReadUInt) {
+ unsigned n = 0;
+ fmt::scan("42", "{}", n);
+ EXPECT_EQ(n, 42);
+ EXPECT_THROW_MSG(fmt::scan("-42", "{}", n), fmt::format_error,
+ "invalid input");
+}
+
+TEST(ScanTest, ReadULongLong) {
+ unsigned long long n = 0;
+ fmt::scan("42", "{}", n);
+ EXPECT_EQ(n, 42);
+ EXPECT_THROW_MSG(fmt::scan("-42", "{}", n), fmt::format_error,
+ "invalid input");
+}
+
+TEST(ScanTest, ReadString) {
+ std::string s;
+ fmt::scan("foo", "{}", s);
+ EXPECT_EQ(s, "foo");
+}
+
+TEST(ScanTest, ReadStringView) {
+ fmt::string_view s;
+ fmt::scan("foo", "{}", s);
+ EXPECT_EQ(s, "foo");
+}
+
+#ifndef _WIN32
+namespace fmt {
+template <> struct scanner<tm> {
+ std::string format;
+
+ scan_parse_context::iterator parse(scan_parse_context& ctx) {
+ auto it = ctx.begin();
+ if (it != ctx.end() && *it == ':') ++it;
+ auto end = it;
+ while (end != ctx.end() && *end != '}') ++end;
+ format.reserve(internal::to_unsigned(end - it + 1));
+ format.append(it, end);
+ format.push_back('\0');
+ return end;
+ }
+
+ template <class ScanContext>
+ typename ScanContext::iterator scan(tm& t, ScanContext& ctx) {
+ auto result = strptime(ctx.begin(), format.c_str(), &t);
+ if (!result) throw format_error("failed to parse time");
+ return result;
+ }
+};
+} // namespace fmt
+
+TEST(ScanTest, ReadCustom) {
+ const char* input = "Date: 1985-10-25";
+ auto t = tm();
+ fmt::scan(input, "Date: {0:%Y-%m-%d}", t);
+ EXPECT_EQ(t.tm_year, 85);
+ EXPECT_EQ(t.tm_mon, 9);
+ EXPECT_EQ(t.tm_mday, 25);
+}
+#endif
+
+TEST(ScanTest, InvalidFormat) {
+ EXPECT_THROW_MSG(fmt::scan("", "{}"), fmt::format_error,
+ "argument index out of range");
+ EXPECT_THROW_MSG(fmt::scan("", "{"), fmt::format_error,
+ "invalid format string");
+}
+
+TEST(ScanTest, Example) {
+ std::string key;
+ int value;
+ fmt::scan("answer = 42", "{} = {}", key, value);
+ EXPECT_EQ(key, "answer");
+ EXPECT_EQ(value, 42);
+}
diff --git a/test/scan.h b/test/scan.h
new file mode 100644
index 0000000..ace84f7
--- /dev/null
+++ b/test/scan.h
@@ -0,0 +1,235 @@
+// Formatting library for C++ - scanning API proof of concept
+//
+// Copyright (c) 2019 - present, Victor Zverovich
+// All rights reserved.
+//
+// For the license information refer to format.h.
+
+#include <array>
+
+#include "fmt/format.h"
+
+FMT_BEGIN_NAMESPACE
+template <typename T, typename Char = char> struct scanner {
+ // A deleted default constructor indicates a disabled scanner.
+ scanner() = delete;
+};
+
+class scan_parse_context {
+ private:
+ string_view format_;
+
+ public:
+ using iterator = string_view::iterator;
+
+ explicit FMT_CONSTEXPR scan_parse_context(string_view format)
+ : format_(format) {}
+
+ FMT_CONSTEXPR iterator begin() const { return format_.begin(); }
+ FMT_CONSTEXPR iterator end() const { return format_.end(); }
+
+ void advance_to(iterator it) {
+ format_.remove_prefix(internal::to_unsigned(it - begin()));
+ }
+};
+
+struct scan_context {
+ private:
+ string_view input_;
+
+ public:
+ using iterator = const char*;
+
+ explicit scan_context(string_view input) : input_(input) {}
+
+ iterator begin() const { return input_.data(); }
+ iterator end() const { return begin() + input_.size(); }
+
+ void advance_to(iterator it) {
+ input_.remove_prefix(internal::to_unsigned(it - begin()));
+ }
+};
+
+namespace internal {
+enum class scan_type {
+ none_type,
+ int_type,
+ uint_type,
+ long_long_type,
+ ulong_long_type,
+ string_type,
+ string_view_type,
+ custom_type
+};
+
+struct custom_scan_arg {
+ void* value;
+ void (*scan)(void* arg, scan_parse_context& parse_ctx, scan_context& ctx);
+};
+
+class scan_arg {
+ public:
+ scan_type type;
+ union {
+ int* int_value;
+ unsigned* uint_value;
+ long long* long_long_value;
+ unsigned long long* ulong_long_value;
+ std::string* string;
+ fmt::string_view* string_view;
+ custom_scan_arg custom;
+ // TODO: more types
+ };
+
+ scan_arg() : type(scan_type::none_type) {}
+ scan_arg(int& value) : type(scan_type::int_type), int_value(&value) {}
+ scan_arg(unsigned& value) : type(scan_type::uint_type), uint_value(&value) {}
+ scan_arg(long long& value)
+ : type(scan_type::long_long_type), long_long_value(&value) {}
+ scan_arg(unsigned long long& value)
+ : type(scan_type::ulong_long_type), ulong_long_value(&value) {}
+ scan_arg(std::string& value) : type(scan_type::string_type), string(&value) {}
+ scan_arg(fmt::string_view& value)
+ : type(scan_type::string_view_type), string_view(&value) {}
+ template <typename T> scan_arg(T& value) : type(scan_type::custom_type) {
+ custom.value = &value;
+ custom.scan = scan_custom_arg<T>;
+ }
+
+ private:
+ template <typename T>
+ static void scan_custom_arg(void* arg, scan_parse_context& parse_ctx,
+ scan_context& ctx) {
+ scanner<T> s;
+ parse_ctx.advance_to(s.parse(parse_ctx));
+ ctx.advance_to(s.scan(*static_cast<T*>(arg), ctx));
+ }
+};
+} // namespace internal
+
+struct scan_args {
+ int size;
+ const internal::scan_arg* data;
+
+ template <size_t N>
+ scan_args(const std::array<internal::scan_arg, N>& store)
+ : size(N), data(store.data()) {
+ static_assert(N < INT_MAX, "too many arguments");
+ }
+};
+
+namespace internal {
+
+struct scan_handler : error_handler {
+ private:
+ scan_parse_context parse_ctx_;
+ scan_context scan_ctx_;
+ scan_args args_;
+ int next_arg_id_;
+ scan_arg arg_;
+
+ template <typename T = unsigned> T read_uint() {
+ T value = 0;
+ auto it = scan_ctx_.begin(), end = scan_ctx_.end();
+ while (it != end) {
+ char c = *it++;
+ if (c < '0' || c > '9') on_error("invalid input");
+ // TODO: check overflow
+ value = value * 10 + (c - '0');
+ }
+ scan_ctx_.advance_to(it);
+ return value;
+ }
+
+ template <typename T = int> T read_int() {
+ T value = 0;
+ auto it = scan_ctx_.begin(), end = scan_ctx_.end();
+ bool negative = it != end && *it == '-';
+ if (negative) ++it;
+ scan_ctx_.advance_to(it);
+ value = read_uint<typename std::make_unsigned<T>::type>();
+ if (negative) value = -value;
+ return value;
+ }
+
+ public:
+ scan_handler(string_view format, string_view input, scan_args args)
+ : parse_ctx_(format), scan_ctx_(input), args_(args), next_arg_id_(0) {}
+
+ const char* pos() const { return scan_ctx_.begin(); }
+
+ void on_text(const char* begin, const char* end) {
+ auto size = end - begin;
+ auto it = scan_ctx_.begin();
+ if (it + size > scan_ctx_.end() ||
+ !std::equal(begin, end, make_checked(it, size))) {
+ on_error("invalid input");
+ }
+ scan_ctx_.advance_to(it + size);
+ }
+
+ void on_arg_id() { on_arg_id(next_arg_id_++); }
+ void on_arg_id(int id) {
+ if (id >= args_.size) on_error("argument index out of range");
+ arg_ = args_.data[id];
+ }
+ void on_arg_id(string_view) { on_error("invalid format"); }
+
+ void on_replacement_field(const char*) {
+ auto it = scan_ctx_.begin(), end = scan_ctx_.end();
+ switch (arg_.type) {
+ case scan_type::int_type:
+ *arg_.int_value = read_int();
+ break;
+ case scan_type::uint_type:
+ *arg_.uint_value = read_uint();
+ break;
+ case scan_type::long_long_type:
+ *arg_.long_long_value = read_int<long long>();
+ break;
+ case scan_type::ulong_long_type:
+ *arg_.ulong_long_value = read_uint<unsigned long long>();
+ break;
+ case scan_type::string_type:
+ while (it != end && *it != ' ') arg_.string->push_back(*it++);
+ scan_ctx_.advance_to(it);
+ break;
+ case scan_type::string_view_type: {
+ auto s = it;
+ while (it != end && *it != ' ') ++it;
+ *arg_.string_view = fmt::string_view(s, it - s);
+ scan_ctx_.advance_to(it);
+ break;
+ }
+ default:
+ assert(false);
+ }
+ }
+
+ const char* on_format_specs(const char* begin, const char*) {
+ if (arg_.type != scan_type::custom_type) return begin;
+ parse_ctx_.advance_to(begin);
+ arg_.custom.scan(arg_.custom.value, parse_ctx_, scan_ctx_);
+ return parse_ctx_.begin();
+ }
+};
+} // namespace internal
+
+template <typename... Args>
+std::array<internal::scan_arg, sizeof...(Args)> make_scan_args(Args&... args) {
+ return {{args...}};
+}
+
+string_view::iterator vscan(string_view input, string_view format_str,
+ scan_args args) {
+ internal::scan_handler h(format_str, input, args);
+ internal::parse_format_string<false>(format_str, h);
+ return input.begin() + (h.pos() - &*input.begin());
+}
+
+template <typename... Args>
+string_view::iterator scan(string_view input, string_view format_str,
+ Args&... args) {
+ return vscan(input, format_str, make_scan_args(args...));
+}
+FMT_END_NAMESPACE
diff --git a/test/std-format-test.cc b/test/std-format-test.cc
new file mode 100644
index 0000000..2fd60d4
--- /dev/null
+++ b/test/std-format-test.cc
@@ -0,0 +1,160 @@
+#include <format>
+#include "gtest.h"
+
+TEST(StdFormatTest, Escaping) {
+ using namespace std;
+ string s = format("{0}-{{", 8); // s == "8-{"
+ EXPECT_EQ(s, "8-{");
+}
+
+TEST(StdFormatTest, Indexing) {
+ using namespace std;
+ string s0 = format("{} to {}", "a", "b"); // OK: automatic indexing
+ string s1 = format("{1} to {0}", "a", "b"); // OK: manual indexing
+ EXPECT_EQ(s0, "a to b");
+ EXPECT_EQ(s1, "b to a");
+ // Error: mixing automatic and manual indexing
+ EXPECT_THROW(string s2 = format("{0} to {}", "a", "b"), std::format_error);
+ // Error: mixing automatic and manual indexing
+ EXPECT_THROW(string s3 = format("{} to {1}", "a", "b"), std::format_error);
+}
+
+TEST(StdFormatTest, Alignment) {
+ using namespace std;
+ char c = 120;
+ string s0 = format("{:6}", 42); // s0 == " 42"
+ string s1 = format("{:6}", 'x'); // s1 == "x "
+ string s2 = format("{:*<6}", 'x'); // s2 == "x*****"
+ string s3 = format("{:*>6}", 'x'); // s3 == "*****x"
+ string s4 = format("{:*^6}", 'x'); // s4 == "**x***"
+ // Error: '=' with charT and no integer presentation type
+ EXPECT_THROW(string s5 = format("{:=6}", 'x'), std::format_error);
+ string s6 = format("{:6d}", c); // s6 == " 120"
+ string s7 = format("{:=+06d}", c); // s7 == "+00120"
+ string s8 = format("{:0=#6x}", 0xa); // s8 == "0x000a"
+ string s9 = format("{:6}", true); // s9 == "true "
+ EXPECT_EQ(s0, " 42");
+ EXPECT_EQ(s1, "x ");
+ EXPECT_EQ(s2, "x*****");
+ EXPECT_EQ(s3, "*****x");
+ EXPECT_EQ(s4, "**x***");
+ EXPECT_EQ(s6, " 120");
+ EXPECT_EQ(s7, "+00120");
+ EXPECT_EQ(s8, "0x000a");
+ EXPECT_EQ(s9, "true ");
+}
+
+TEST(StdFormatTest, Float) {
+ using namespace std;
+ double inf = numeric_limits<double>::infinity();
+ double nan = numeric_limits<double>::quiet_NaN();
+ string s0 = format("{0:} {0:+} {0:-} {0: }", 1); // s0 == "1 +1 1 1"
+ string s1 = format("{0:} {0:+} {0:-} {0: }", -1); // s1 == "-1 -1 -1 -1"
+ string s2 =
+ format("{0:} {0:+} {0:-} {0: }", inf); // s2 == "inf +inf inf inf"
+ string s3 =
+ format("{0:} {0:+} {0:-} {0: }", nan); // s3 == "nan +nan nan nan"
+ EXPECT_EQ(s0, "1 +1 1 1");
+ EXPECT_EQ(s1, "-1 -1 -1 -1");
+ EXPECT_EQ(s2, "inf +inf inf inf");
+ EXPECT_EQ(s3, "nan +nan nan nan");
+}
+
+TEST(StdFormatTest, Int) {
+ using namespace std;
+ string s0 = format("{}", 42); // s0 == "42"
+ string s1 = format("{0:b} {0:d} {0:o} {0:x}", 42); // s1 == "101010 42 52 2a"
+ string s2 = format("{0:#x} {0:#X}", 42); // s2 == "0x2a 0X2A"
+ string s3 = format("{:n}", 1234); // s3 == "1,234" (depends on the locale)
+ EXPECT_EQ(s0, "42");
+ EXPECT_EQ(s1, "101010 42 52 2a");
+ EXPECT_EQ(s2, "0x2a 0X2A");
+ EXPECT_EQ(s3, "1,234");
+}
+
+#include <format>
+
+enum color { red, green, blue };
+
+const char* color_names[] = {"red", "green", "blue"};
+
+template <> struct std::formatter<color> : std::formatter<const char*> {
+ auto format(color c, format_context& ctx) {
+ return formatter<const char*>::format(color_names[c], ctx);
+ }
+};
+
+struct err {};
+
+TEST(StdFormatTest, Formatter) {
+ std::string s0 = std::format("{}", 42); // OK: library-provided formatter
+ // std::string s1 = std::format("{}", L"foo"); // Ill-formed: disabled
+ // formatter
+ std::string s2 = std::format("{}", red); // OK: user-provided formatter
+ // std::string s3 = std::format("{}", err{}); // Ill-formed: disabled
+ // formatter
+ EXPECT_EQ(s0, "42");
+ EXPECT_EQ(s2, "red");
+}
+
+struct S {
+ int value;
+};
+
+template <> struct std::formatter<S> {
+ size_t width_arg_id = 0;
+
+ // Parses a width argument id in the format { <digit> }.
+ constexpr auto parse(format_parse_context& ctx) {
+ auto iter = ctx.begin();
+ // auto get_char = [&]() { return iter != ctx.end() ? *iter : 0; };
+ auto get_char = [&]() { return iter != ctx.end() ? *iter : '\0'; };
+ if (get_char() != '{') return iter;
+ ++iter;
+ char c = get_char();
+ if (!isdigit(c) || (++iter, get_char()) != '}')
+ throw format_error("invalid format");
+ width_arg_id = c - '0';
+ ctx.check_arg_id(width_arg_id);
+ return ++iter;
+ }
+
+ // Formats S with width given by the argument width_arg_id.
+ auto format(S s, format_context& ctx) {
+ int width = visit_format_arg(
+ [](auto value) -> int {
+ using type = decltype(value);
+ if constexpr (!is_integral_v<type> || is_same_v<type, bool>)
+ throw format_error("width is not integral");
+ // else if (value < 0 || value > numeric_limits<int>::max())
+ else if (fmt::internal::is_negative(value) ||
+ value > numeric_limits<int>::max())
+ throw format_error("invalid width");
+ else
+ return static_cast<int>(value);
+ },
+ ctx.arg(width_arg_id));
+ return format_to(ctx.out(), "{0:{1}}", s.value, width);
+ }
+};
+
+TEST(StdFormatTest, Parsing) {
+ std::string s = std::format("{0:{1}}", S{42}, 10); // s == " 42"
+ EXPECT_EQ(s, " 42");
+}
+
+#if FMT_USE_INT128
+template <> struct std::formatter<__int128_t> : std::formatter<long long> {
+ auto format(__int128_t n, format_context& ctx) {
+ // Format as a long long since we only want to check if it is possible to
+ // specialize formatter for __int128_t.
+ return formatter<long long>::format(static_cast<long long>(n), ctx);
+ }
+};
+
+TEST(StdFormatTest, Int128) {
+ __int128_t n = 42;
+ auto s = std::format("{}", n);
+ EXPECT_EQ(s, "42");
+}
+#endif // FMT_USE_INT128
diff --git a/test/test-assert.h b/test/test-assert.h
index c816155..034a4ce 100644
--- a/test/test-assert.h
+++ b/test/test-assert.h
@@ -13,7 +13,7 @@
class assertion_failure : public std::logic_error {
public:
- explicit assertion_failure(const char *message) : std::logic_error(message) {}
+ explicit assertion_failure(const char* message) : std::logic_error(message) {}
};
#define FMT_ASSERT(condition, message) \
diff --git a/test/test-main.cc b/test/test-main.cc
index bc0be76..d911131 100644
--- a/test/test-main.cc
+++ b/test/test-main.cc
@@ -9,23 +9,23 @@
#include "gtest.h"
#ifdef _WIN32
-# include <windows.h>
+# include <windows.h>
#endif
#ifdef _MSC_VER
-# include <crtdbg.h>
+# include <crtdbg.h>
#else
-# define _CrtSetReportFile(a, b)
-# define _CrtSetReportMode(a, b)
+# define _CrtSetReportFile(a, b)
+# define _CrtSetReportMode(a, b)
#endif
-int main(int argc, char **argv) {
+int main(int argc, char** argv) {
#ifdef _WIN32
// Don't display any error dialogs. This also suppresses message boxes
// on assertion failures in MinGW where _set_error_mode/CrtSetReportMode
// doesn't help.
SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX |
- SEM_NOOPENFILEERRORBOX);
+ SEM_NOOPENFILEERRORBOX);
#endif
// Disable message boxes on assertion failures.
_CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_FILE | _CRTDBG_MODE_DEBUG);
diff --git a/test/time-test.cc b/test/time-test.cc
deleted file mode 100644
index 686d387..0000000
--- a/test/time-test.cc
+++ /dev/null
@@ -1,68 +0,0 @@
-// Formatting library for C++ - time formatting tests
-//
-// Copyright (c) 2012 - present, Victor Zverovich
-// All rights reserved.
-//
-// For the license information refer to format.h.
-
-#ifdef WIN32
-#define _CRT_SECURE_NO_WARNINGS
-#endif
-
-#include "gmock.h"
-#include "fmt/locale.h"
-#include "fmt/time.h"
-
-TEST(TimeTest, Format) {
- std::tm tm = std::tm();
- tm.tm_year = 116;
- tm.tm_mon = 3;
- tm.tm_mday = 25;
- EXPECT_EQ("The date is 2016-04-25.",
- fmt::format("The date is {:%Y-%m-%d}.", tm));
-}
-
-TEST(TimeTest, GrowBuffer) {
- std::string s = "{:";
- for (int i = 0; i < 30; ++i)
- s += "%c";
- s += "}\n";
- std::time_t t = std::time(FMT_NULL);
- fmt::format(s, *std::localtime(&t));
-}
-
-TEST(TimeTest, FormatToEmptyContainer) {
- std::string s;
- auto time = std::tm();
- time.tm_sec = 42;
- fmt::format_to(std::back_inserter(s), "{:%S}", time);
- EXPECT_EQ(s, "42");
-}
-
-TEST(TimeTest, EmptyResult) {
- EXPECT_EQ("", fmt::format("{}", std::tm()));
-}
-
-static bool EqualTime(const std::tm &lhs, const std::tm &rhs) {
- return lhs.tm_sec == rhs.tm_sec &&
- lhs.tm_min == rhs.tm_min &&
- lhs.tm_hour == rhs.tm_hour &&
- lhs.tm_mday == rhs.tm_mday &&
- lhs.tm_mon == rhs.tm_mon &&
- lhs.tm_year == rhs.tm_year &&
- lhs.tm_wday == rhs.tm_wday &&
- lhs.tm_yday == rhs.tm_yday &&
- lhs.tm_isdst == rhs.tm_isdst;
-}
-
-TEST(TimeTest, LocalTime) {
- std::time_t t = std::time(FMT_NULL);
- std::tm tm = *std::localtime(&t);
- EXPECT_TRUE(EqualTime(tm, fmt::localtime(t)));
-}
-
-TEST(TimeTest, GMTime) {
- std::time_t t = std::time(FMT_NULL);
- std::tm tm = *std::gmtime(&t);
- EXPECT_TRUE(EqualTime(tm, fmt::gmtime(t)));
-}
diff --git a/test/util.cc b/test/util.cc
index 12270bc..329f654 100644
--- a/test/util.cc
+++ b/test/util.cc
@@ -8,7 +8,7 @@
#include "util.h"
#include <cstring>
-void increment(char *s) {
+void increment(char* s) {
for (int i = static_cast<int>(std::strlen(s)) - 1; i >= 0; --i) {
if (s[i] != '9') {
++s[i];
@@ -30,15 +30,14 @@
#endif
}
-const char *const FILE_CONTENT = "Don't panic!";
+const char* const FILE_CONTENT = "Don't panic!";
-fmt::buffered_file open_buffered_file(FILE **fp) {
+fmt::buffered_file open_buffered_file(FILE** fp) {
fmt::file read_end, write_end;
fmt::file::pipe(read_end, write_end);
write_end.write(FILE_CONTENT, std::strlen(FILE_CONTENT));
write_end.close();
fmt::buffered_file f = read_end.fdopen("r");
- if (fp)
- *fp = f.get();
+ if (fp) *fp = f.get();
return f;
}
diff --git a/test/util.h b/test/util.h
index 2b068d9..7aa9da2 100644
--- a/test/util.h
+++ b/test/util.h
@@ -11,16 +11,16 @@
#include "fmt/posix.h"
-enum {BUFFER_SIZE = 256};
+enum { BUFFER_SIZE = 256 };
#ifdef _MSC_VER
-# define FMT_VSNPRINTF vsprintf_s
+# define FMT_VSNPRINTF vsprintf_s
#else
-# define FMT_VSNPRINTF vsnprintf
+# define FMT_VSNPRINTF vsnprintf
#endif
template <std::size_t SIZE>
-void safe_sprintf(char (&buffer)[SIZE], const char *format, ...) {
+void safe_sprintf(char (&buffer)[SIZE], const char* format, ...) {
std::va_list args;
va_start(args, format);
FMT_VSNPRINTF(buffer, SIZE, format, args);
@@ -28,19 +28,19 @@
}
// Increment a number in a string.
-void increment(char *s);
+void increment(char* s);
std::string get_system_error(int error_code);
-extern const char *const FILE_CONTENT;
+extern const char* const FILE_CONTENT;
// Opens a buffered file for reading.
-fmt::buffered_file open_buffered_file(FILE **fp = FMT_NULL);
+fmt::buffered_file open_buffered_file(FILE** fp = nullptr);
-inline FILE *safe_fopen(const char *filename, const char *mode) {
+inline FILE* safe_fopen(const char* filename, const char* mode) {
#if defined(_WIN32) && !defined(__MINGW32__)
// Fix MSVC warning about "unsafe" fopen.
- FILE *f = 0;
+ FILE* f = 0;
errno = fopen_s(&f, filename, mode);
return f;
#else
@@ -48,34 +48,33 @@
#endif
}
-template <typename Char>
-class BasicTestString {
+template <typename Char> class BasicTestString {
private:
std::basic_string<Char> value_;
static const Char EMPTY[];
public:
- explicit BasicTestString(const Char *value = EMPTY) : value_(value) {}
+ explicit BasicTestString(const Char* value = EMPTY) : value_(value) {}
- const std::basic_string<Char> &value() const { return value_; }
+ const std::basic_string<Char>& value() const { return value_; }
};
-template <typename Char>
-const Char BasicTestString<Char>::EMPTY[] = {0};
+template <typename Char> const Char BasicTestString<Char>::EMPTY[] = {0};
typedef BasicTestString<char> TestString;
typedef BasicTestString<wchar_t> TestWString;
template <typename Char>
-std::basic_ostream<Char> &operator<<(
- std::basic_ostream<Char> &os, const BasicTestString<Char> &s) {
+std::basic_ostream<Char>& operator<<(std::basic_ostream<Char>& os,
+ const BasicTestString<Char>& s) {
os << s.value();
return os;
}
class Date {
int year_, month_, day_;
+
public:
Date(int year, int month, int day) : year_(year), month_(month), day_(day) {}